reactjrx 1.62.0 → 1.65.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 (36) hide show
  1. package/dist/index.cjs +656 -361
  2. package/dist/index.d.ts +1 -0
  3. package/dist/index.js +651 -356
  4. package/dist/lib/queries/client/createClient.d.ts +14 -3
  5. package/dist/lib/queries/client/mutations/Mutation.d.ts +22 -10
  6. package/dist/lib/queries/client/mutations/cache/MutationCache.d.ts +43 -0
  7. package/dist/lib/queries/client/mutations/cache/mutationCache.test.d.ts +1 -0
  8. package/dist/lib/queries/client/mutations/cache/types.d.ts +61 -0
  9. package/dist/lib/queries/client/mutations/defaultMutationState.d.ts +1 -1
  10. package/dist/lib/queries/client/mutations/filters.d.ts +1 -1
  11. package/dist/lib/queries/client/mutations/observers/MutationObserver.d.ts +25 -0
  12. package/dist/lib/queries/client/mutations/observers/mutationObserver.test.d.ts +1 -0
  13. package/dist/lib/queries/client/mutations/observers/types.d.ts +59 -0
  14. package/dist/lib/queries/client/mutations/operators.d.ts +1 -1
  15. package/dist/lib/queries/client/mutations/runners/MutationRunner.d.ts +19 -0
  16. package/dist/lib/queries/client/mutations/runners/MutationRunners.d.ts +54 -0
  17. package/dist/lib/queries/client/mutations/types.d.ts +13 -66
  18. package/dist/lib/queries/client/tests/utils.d.ts +4 -0
  19. package/dist/lib/queries/client/utils/functionAsObservable.d.ts +2 -0
  20. package/dist/lib/queries/client/utils/wrapInPromise.d.ts +3 -0
  21. package/dist/lib/queries/react/Provider.d.ts +3 -71
  22. package/dist/lib/queries/react/mutations/useIsMutating.d.ts +1 -1
  23. package/dist/lib/queries/react/mutations/useMutation.cancel.test.d.ts +1 -0
  24. package/dist/lib/queries/react/mutations/useMutation.d.ts +8 -7
  25. package/dist/lib/queries/react/mutations/useMutationState.d.ts +2 -1
  26. package/dist/lib/queries/react/{helpers.d.ts → queries/helpers.d.ts} +5 -5
  27. package/dist/lib/queries/react/{types.d.ts → queries/types.d.ts} +1 -1
  28. package/dist/lib/queries/react/queries/useQuery.d.ts +1 -1
  29. package/dist/lib/queries/react/triggers/activityTrigger.d.ts +1 -1
  30. package/dist/lib/queries/react/triggers/networkTrigger.d.ts +1 -1
  31. package/dist/tests/utils.d.ts +4 -1
  32. package/package.json +2 -1
  33. package/dist/lib/queries/client/mutations/MutationClient.d.ts +0 -91
  34. package/dist/lib/queries/client/mutations/MutationResultObserver.d.ts +0 -32
  35. package/dist/lib/queries/client/mutations/createMutationRunner.d.ts +0 -15
  36. /package/dist/lib/queries/{react → client}/keys/nanoid.d.ts +0 -0
package/dist/index.cjs CHANGED
@@ -74,6 +74,7 @@ function useObserve(source$, unsafeOptions, unsafeDeps) {
74
74
  sub.unsubscribe();
75
75
  };
76
76
  },
77
+ // eslint-disable-next-line react-hooks/exhaustive-deps
77
78
  [...deps]
78
79
  );
79
80
  const getSnapshot = react.useCallback(() => {
@@ -100,7 +101,12 @@ function useSubscribe(source, deps = []) {
100
101
  return () => {
101
102
  sub.unsubscribe();
102
103
  };
103
- }, [...deps, sourceAsObservable]);
104
+ }, [
105
+ // eslint-disable-next-line react-hooks/exhaustive-deps
106
+ ...deps,
107
+ sourceAsObservable,
108
+ sourceRef
109
+ ]);
104
110
  }
105
111
  const useConstant = (fn) => {
106
112
  const ref = react.useRef();
@@ -138,7 +144,7 @@ const useSubject = ({
138
144
  completed.current = true;
139
145
  }
140
146
  };
141
- }, []);
147
+ }, [completeOnUnmountRef, onBeforeCompleteRef, subject]);
142
148
  return subject;
143
149
  };
144
150
  const useObserveCallback = (callback, deps) => {
@@ -146,7 +152,7 @@ const useObserveCallback = (callback, deps) => {
146
152
  useSubscribe(() => callback(trigger$.current), [trigger$, ...deps]);
147
153
  const trigger2 = react.useCallback((arg) => {
148
154
  trigger$.current.next(arg);
149
- }, []);
155
+ }, [trigger$]);
150
156
  return [trigger2, trigger$];
151
157
  };
152
158
  function trigger(mapper = rxjs.identity) {
@@ -161,9 +167,10 @@ function trigger(mapper = rxjs.identity) {
161
167
  const useBehaviorSubject = (state) => {
162
168
  const subject = useConstant(() => new rxjs.BehaviorSubject(state));
163
169
  const completed = react.useRef(false);
170
+ const stateRef = react.useRef(state);
164
171
  react.useEffect(() => {
165
172
  if (completed.current) {
166
- subject.current = new rxjs.BehaviorSubject(state);
173
+ subject.current = new rxjs.BehaviorSubject(stateRef.current);
167
174
  completed.current = false;
168
175
  }
169
176
  return () => {
@@ -172,7 +179,7 @@ const useBehaviorSubject = (state) => {
172
179
  completed.current = true;
173
180
  }
174
181
  };
175
- }, []);
182
+ }, [subject]);
176
183
  return subject;
177
184
  };
178
185
  const SIGNAL_RESET = Symbol("SIGNAL_RESET");
@@ -401,27 +408,27 @@ function retryBackoff(config) {
401
408
  const Context = react.createContext({
402
409
  client: null
403
410
  });
404
- const ClientEffect = ({
405
- client
406
- }) => {
411
+ const ClientEffect = ({ client }) => {
407
412
  react.useEffect(() => {
408
- const destroy = client.start();
413
+ const stop = client.mount();
409
414
  return () => {
410
- destroy();
415
+ stop();
411
416
  };
412
417
  }, [client]);
413
418
  return null;
414
419
  };
415
420
  const QueryClientProvider = react.memo(
416
421
  ({ children, client }) => {
417
- const value = react.useMemo(() => ({ client: client.client }), [client]);
422
+ const value = react.useMemo(() => ({ client }), [client]);
418
423
  return /* @__PURE__ */ jsxRuntime.jsxs(Context.Provider, { value, children: [
419
424
  /* @__PURE__ */ jsxRuntime.jsx(ClientEffect, { client: value.client }),
420
425
  children
421
426
  ] });
422
427
  }
423
428
  );
424
- const useQueryClient = ({ unsafe = false } = {}) => {
429
+ const useQueryClient = ({
430
+ unsafe = false
431
+ } = {}) => {
425
432
  const context = react.useContext(Context);
426
433
  if (!unsafe && context.client === null) {
427
434
  throw new Error("You forgot to register the provider");
@@ -458,45 +465,51 @@ const nanoid = (size = 21) => crypto.getRandomValues(new Uint8Array(size)).reduc
458
465
  }
459
466
  return id;
460
467
  }, "");
468
+ function noop() {
469
+ }
461
470
  function useMutation(options, queryClient) {
462
471
  const defaultQueryClient = useQueryClient({ unsafe: !!queryClient });
463
- const finalQueryClient = (queryClient == null ? void 0 : queryClient.client) ?? defaultQueryClient;
472
+ const finalQueryClient = queryClient ?? defaultQueryClient;
464
473
  const optionsRef = useLiveRef(options);
465
474
  const defaultKey = useConstant(() => [nanoid()]);
466
- const key = serializeKey(options.mutationKey ?? defaultKey.current);
467
- const observedMutation = react.useMemo(
468
- () => finalQueryClient.mutationClient.mutationResultObserver.observe({
469
- key
470
- }),
471
- [key]
472
- );
475
+ const serializedKey = serializeKey(options.mutationKey ?? defaultKey.current);
476
+ const mutationsToCancel = react.useRef([]);
477
+ const observedMutation = react.useMemo(() => {
478
+ return finalQueryClient.mutationObserver.observeBy({
479
+ mutationKey: optionsRef.current.mutationKey ?? defaultKey.current
480
+ });
481
+ }, [serializedKey, defaultKey, finalQueryClient, optionsRef]);
473
482
  const result = useObserve(observedMutation.result$) ?? observedMutation.lastValue;
474
483
  const mutate = react.useCallback(
475
484
  (mutationArgs) => {
476
- finalQueryClient.mutationClient.mutate({
485
+ finalQueryClient.mutationRunners.mutate({
477
486
  options: {
478
487
  ...optionsRef.current,
479
488
  mutationKey: optionsRef.current.mutationKey ?? defaultKey.current
480
489
  },
481
490
  args: mutationArgs
491
+ }).catch(noop);
492
+ const mutation = finalQueryClient.getMutationCache().findLatest({
493
+ mutationKey: optionsRef.current.mutationKey ?? defaultKey.current
482
494
  });
495
+ if (mutation) {
496
+ mutationsToCancel.current.push(mutation);
497
+ }
483
498
  },
484
- [finalQueryClient, key]
499
+ [finalQueryClient, serializedKey, defaultKey, optionsRef]
485
500
  );
486
501
  const cancel = react.useCallback(() => {
487
- finalQueryClient.mutationClient.cancel({
488
- key: optionsRef.current.mutationKey ?? defaultKey.current
502
+ mutationsToCancel.current.forEach((mutation) => {
503
+ mutation.cancel();
489
504
  });
490
- }, [finalQueryClient]);
505
+ }, []);
491
506
  react.useEffect(() => {
492
507
  return () => {
493
508
  if (optionsRef.current.cancelOnUnMount) {
494
- finalQueryClient.mutationClient.cancel({
495
- key: optionsRef.current.mutationKey ?? defaultKey.current
496
- });
509
+ cancel();
497
510
  }
498
511
  };
499
- }, []);
512
+ }, [cancel, optionsRef]);
500
513
  return { mutate, cancel, ...result };
501
514
  }
502
515
  const arrayEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
@@ -572,7 +585,7 @@ const useQueryParams = ({
572
585
  options,
573
586
  queryFn
574
587
  });
575
- }, [queryKey, options, queryFn]);
588
+ }, [queryKey, options, queryFn, params$]);
576
589
  return params$;
577
590
  };
578
591
  const defaultValue = {
@@ -624,7 +637,7 @@ function useQuery({
624
637
  return newQueryTrigger$.pipe(
625
638
  rxjs.withLatestFrom(key$),
626
639
  rxjs.switchMap(([, key]) => {
627
- const { result$ } = client.query({
640
+ const { result$ } = client.client.query({
628
641
  key,
629
642
  fn$,
630
643
  options$,
@@ -666,7 +679,7 @@ function useQuery({
666
679
  );
667
680
  const refetch = react.useCallback(() => {
668
681
  internalRefresh$.current.next({ type: "refetch", ignoreStale: true });
669
- }, [client]);
682
+ }, [internalRefresh$]);
670
683
  return { ...result, refetch };
671
684
  }
672
685
  function useSubscribeEffect(source, unsafeOptions, deps = []) {
@@ -685,7 +698,7 @@ function useSubscribeEffect(source, unsafeOptions, deps = []) {
685
698
  }),
686
699
  retryOption ? rxjs.retry() : rxjs.identity
687
700
  ),
688
- [makeObservable]
701
+ [makeObservable, retryOption]
689
702
  );
690
703
  useSubscribe(enhancerMakeObservable, deps);
691
704
  }
@@ -1491,88 +1504,25 @@ const mergeResults = (stream$) => stream$.pipe(
1491
1504
  ({ data: prevData, ...prev }, { data: currData, ...curr }) => shallowEqual(prev, curr) && shallowEqual(prevData, currData)
1492
1505
  )
1493
1506
  );
1494
- class Mutation {
1495
- constructor({
1496
- args,
1497
- ...options
1498
- }) {
1499
- __publicField(this, "stateSubject", new rxjs.ReplaySubject(1));
1500
- /**
1501
- * @important
1502
- * convenience over usage of stateSubject for sync access
1503
- */
1504
- __publicField(this, "state", getDefaultMutationState());
1505
- __publicField(this, "options");
1506
- __publicField(this, "mutation$");
1507
- this.options = options;
1508
- const mutationFn = options.mutationFn;
1509
- this.state.variables = args;
1510
- this.stateSubject.next(this.state);
1511
- const mutationFnObservable = typeof mutationFn === "function" ? rxjs.defer(() => rxjs.from(mutationFn(args))) : mutationFn;
1512
- const queryRunner$ = mutationFnObservable.pipe(
1513
- retryOnError(options),
1514
- rxjs.take(1),
1515
- rxjs.map((data) => ({ data, isError: false })),
1516
- rxjs.catchError((error) => {
1517
- console.error(error);
1518
- if (options.onError != null) {
1519
- options.onError(error, args);
1520
- }
1521
- return rxjs.of({ data: error, isError: true });
1522
- })
1523
- );
1524
- const initState$ = rxjs.of({
1525
- ...this.state,
1526
- status: "pending",
1527
- submittedAt: (/* @__PURE__ */ new Date()).getTime()
1528
- });
1529
- this.mutation$ = rxjs.merge(
1530
- initState$,
1531
- queryRunner$.pipe(
1532
- rxjs.map(({ data, isError }) => {
1533
- if (!isError) {
1534
- if (options.onSuccess != null)
1535
- options.onSuccess(data, args);
1536
- }
1537
- return isError ? {
1538
- status: "error",
1539
- error: data,
1540
- data: void 0
1541
- } : {
1542
- status: "success",
1543
- error: null,
1544
- data
1545
- };
1546
- })
1547
- )
1548
- ).pipe(
1549
- mergeResults,
1550
- rxjs.tap((value) => {
1551
- this.state = { ...this.state, ...value };
1552
- this.stateSubject.next(this.state);
1553
- }),
1554
- options.__queryRunnerHook ?? rxjs.identity,
1555
- rxjs.share()
1556
- );
1557
- }
1558
- }
1559
1507
  const createMutationRunner = ({
1560
1508
  __queryFinalizeHook,
1561
1509
  __queryInitHook,
1562
- __queryTriggerHook
1510
+ __queryTriggerHook,
1511
+ mutationKey,
1512
+ mutationCache
1563
1513
  }) => {
1564
1514
  const trigger$ = new rxjs.Subject();
1565
1515
  const cancel$ = new rxjs.Subject();
1566
1516
  let closed = false;
1567
- const mapOperator$ = new rxjs.BehaviorSubject("merge");
1568
- const mutationsSubject = new rxjs.BehaviorSubject([]);
1517
+ const mapOperator$ = new rxjs.BehaviorSubject(
1518
+ "merge"
1519
+ );
1569
1520
  const destroy = () => {
1570
1521
  if (closed) {
1571
1522
  throw new Error("Trying to close an already closed mutation");
1572
1523
  }
1573
1524
  closed = true;
1574
1525
  mapOperator$.complete();
1575
- mutationsSubject.complete();
1576
1526
  trigger$.complete();
1577
1527
  cancel$.next();
1578
1528
  cancel$.complete();
@@ -1581,39 +1531,26 @@ const createMutationRunner = ({
1581
1531
  rxjs.filter(isDefined),
1582
1532
  rxjs.distinctUntilChanged()
1583
1533
  );
1584
- const mutation$ = stableMapOperator$.pipe(
1534
+ const runner$ = stableMapOperator$.pipe(
1585
1535
  __queryInitHook ?? rxjs.identity,
1586
1536
  rxjs.mergeMap((mapOperator) => {
1587
1537
  const switchOperator = mapOperator === "concat" ? rxjs.concatMap : mapOperator === "switch" ? rxjs.switchMap : rxjs.mergeMap;
1588
- let mutationsForCurrentMapOperatorSubject = [];
1589
- const removeMutation = (mutation) => {
1590
- mutationsForCurrentMapOperatorSubject = mutationsForCurrentMapOperatorSubject.filter(
1591
- (item) => item !== mutation
1592
- );
1593
- mutationsSubject.next(
1594
- mutationsSubject.getValue().filter((item) => item !== mutation)
1595
- );
1596
- };
1597
1538
  return trigger$.pipe(
1598
1539
  rxjs.takeUntil(stableMapOperator$.pipe(rxjs.skip(1))),
1599
- rxjs.map(({ args, options }) => {
1600
- const mutation = new Mutation({
1601
- args,
1602
- ...options,
1603
- mapOperator
1540
+ switchOperator(({ args }) => {
1541
+ const mutation = mutationCache.findLatest({
1542
+ exact: true,
1543
+ mutationKey
1604
1544
  });
1605
- mutationsForCurrentMapOperatorSubject = [
1606
- ...mutationsForCurrentMapOperatorSubject,
1607
- mutation
1608
- ];
1609
- mutationsSubject.next([...mutationsSubject.getValue(), mutation]);
1610
- return mutation;
1611
- }),
1612
- switchOperator((mutation) => {
1613
- if (!mutationsSubject.getValue().includes(mutation))
1545
+ if (!mutation) {
1614
1546
  return rxjs.of({});
1615
- const queryIsOver$ = mutation.mutation$.pipe(
1616
- rxjs.map(({ data, error }) => error || data)
1547
+ }
1548
+ const mutation$ = mutation.execute(args);
1549
+ const queryIsOver$ = rxjs.merge(
1550
+ cancel$,
1551
+ mutation$.pipe(
1552
+ rxjs.filter(({ status }) => status === "success" || status === "error")
1553
+ )
1617
1554
  );
1618
1555
  const isThisCurrentFunctionLastOneCalled = trigger$.pipe(
1619
1556
  rxjs.take(1),
@@ -1622,7 +1559,7 @@ const createMutationRunner = ({
1622
1559
  rxjs.takeUntil(queryIsOver$)
1623
1560
  );
1624
1561
  const result$ = rxjs.combineLatest([
1625
- mutation.mutation$,
1562
+ mutation$,
1626
1563
  isThisCurrentFunctionLastOneCalled
1627
1564
  ]).pipe(
1628
1565
  rxjs.map(([result, isLastMutationCalled]) => {
@@ -1631,11 +1568,7 @@ const createMutationRunner = ({
1631
1568
  }
1632
1569
  return result;
1633
1570
  }),
1634
- rxjs.takeUntil(cancel$.pipe()),
1635
- mergeResults,
1636
- rxjs.finalize(() => {
1637
- removeMutation(mutation);
1638
- })
1571
+ mergeResults
1639
1572
  );
1640
1573
  return result$;
1641
1574
  }),
@@ -1647,12 +1580,17 @@ const createMutationRunner = ({
1647
1580
  rxjs.shareReplay(1)
1648
1581
  );
1649
1582
  cancel$.subscribe(() => {
1650
- if (mutationsSubject.getValue().length === 0)
1651
- return;
1652
- mutationsSubject.next([]);
1583
+ var _a;
1584
+ (_a = mutationCache.findAll({
1585
+ mutationKey,
1586
+ exact: true
1587
+ })) == null ? void 0 : _a.forEach((mutation) => {
1588
+ mutation.cancel();
1589
+ });
1653
1590
  });
1654
1591
  return {
1655
- mutation$,
1592
+ mutationKey,
1593
+ runner$,
1656
1594
  trigger: ({
1657
1595
  args,
1658
1596
  options
@@ -1662,115 +1600,11 @@ const createMutationRunner = ({
1662
1600
  },
1663
1601
  cancel$,
1664
1602
  destroy,
1665
- mutationsSubject,
1666
1603
  getClosed: () => closed
1667
1604
  };
1668
1605
  };
1669
- const createPredicateForFilters = ({
1670
- mutationKey,
1671
- status,
1672
- predicate
1673
- } = {}) => {
1674
- const defaultPredicate = (mutation) => {
1675
- if (mutationKey !== void 0 && // @todo optimize
1676
- serializeKey(mutation.options.mutationKey) !== serializeKey(mutationKey)) {
1677
- return false;
1678
- }
1679
- if (status && mutation.state.status !== status)
1680
- return false;
1681
- return true;
1682
- };
1683
- const finalPredicate = predicate ?? defaultPredicate;
1684
- return finalPredicate;
1685
- };
1686
- class MutationResultObserver {
1687
- constructor(mutationRunnersByKey$) {
1688
- /**
1689
- * Mutation result subject. It can be used whether there is a mutation
1690
- * running or not and can be directly observed.
1691
- *
1692
- * @important
1693
- * - automatically cleaned as soon as the last mutation is done for a given key
1694
- */
1695
- __publicField(this, "mutationResults$", new rxjs.BehaviorSubject(/* @__PURE__ */ new Map()));
1696
- mutationRunnersByKey$.pipe(
1697
- rxjs.switchMap((mapItem) => {
1698
- const runners = Array.from(mapItem.values()).map((runner) => {
1699
- const serializedMutationKey = serializeKey(runner.mutationKey);
1700
- return runner.mutation$.pipe(
1701
- rxjs.tap((result) => {
1702
- this.updateResultForKey({
1703
- serializedMutationKey,
1704
- result
1705
- });
1706
- }),
1707
- rxjs.finalize(() => {
1708
- this.deleteResultForKey({ serializedMutationKey });
1709
- })
1710
- );
1711
- });
1712
- return rxjs.merge(...runners);
1713
- })
1714
- ).subscribe();
1715
- }
1716
- getDefaultResultValue() {
1717
- return {
1718
- ...getDefaultMutationState(),
1719
- isSuccess: false,
1720
- isPending: false,
1721
- isIdle: true,
1722
- isError: false
1723
- };
1724
- }
1725
- deleteResultForKey({
1726
- serializedMutationKey
1727
- }) {
1728
- const resultMap = this.mutationResults$.getValue();
1729
- resultMap.delete(serializedMutationKey);
1730
- this.mutationResults$.next(resultMap);
1731
- }
1732
- updateResultForKey({
1733
- serializedMutationKey,
1734
- result
1735
- }) {
1736
- const resultForKeySubject = this.mutationResults$.getValue().get(serializedMutationKey);
1737
- const valueForResult = {
1738
- ...this.getDefaultResultValue(),
1739
- ...result,
1740
- isSuccess: result.status === "success",
1741
- isPending: result.status === "pending",
1742
- isIdle: result.status === "idle",
1743
- isError: result.status === "error"
1744
- };
1745
- if (!resultForKeySubject) {
1746
- const resultMap = this.mutationResults$.getValue();
1747
- resultMap.set(
1748
- serializedMutationKey,
1749
- new rxjs.BehaviorSubject(valueForResult)
1750
- );
1751
- this.mutationResults$.next(resultMap);
1752
- } else {
1753
- resultForKeySubject == null ? void 0 : resultForKeySubject.next(valueForResult);
1754
- }
1755
- }
1756
- observe({ key }) {
1757
- var _a;
1758
- const currentResultValue = (_a = this.mutationResults$.getValue().get(key)) == null ? void 0 : _a.getValue();
1759
- const lastValue = currentResultValue ?? this.getDefaultResultValue();
1760
- const result$ = this.mutationResults$.pipe(
1761
- rxjs.switchMap((resultMap) => {
1762
- const subject = resultMap.get(key);
1763
- return subject ?? rxjs.EMPTY;
1764
- })
1765
- ).pipe(rxjs.filter(isDefined));
1766
- return { result$, lastValue };
1767
- }
1768
- destroy() {
1769
- this.mutationResults$.complete();
1770
- }
1771
- }
1772
- class MutationClient {
1773
- constructor() {
1606
+ class MutationRunners {
1607
+ constructor(client) {
1774
1608
  /**
1775
1609
  * Contain all active mutation for a given key.
1776
1610
  * A mutation ca have several triggers running (it is not necessarily one function running)
@@ -1779,87 +1613,23 @@ class MutationClient {
1779
1613
  * - automatically cleaned as soon as the last mutation is done for a given key
1780
1614
  */
1781
1615
  __publicField(this, "mutationRunnersByKey$", new rxjs.BehaviorSubject(/* @__PURE__ */ new Map()));
1782
- __publicField(this, "mutate$", new rxjs.Subject());
1783
- __publicField(this, "cancel$", new rxjs.Subject());
1784
- /**
1785
- * Observable to track how many running mutations per runner
1786
- */
1787
- __publicField(this, "isMutatingSubject", new rxjs.BehaviorSubject([]));
1788
- /**
1789
- * List of all mutations running
1790
- */
1791
- __publicField(this, "mutationsSubject", new rxjs.BehaviorSubject([]));
1792
- __publicField(this, "mutationResultObserver", new MutationResultObserver(
1793
- this.mutationRunnersByKey$
1794
- ));
1795
- this.mutate$.pipe(
1796
- rxjs.tap(({ options, args }) => {
1797
- const { mutationKey } = options;
1798
- const serializedMutationKey = serializeKey(mutationKey);
1799
- let mutationForKey = this.getMutationRunnersByKey(
1800
- serializedMutationKey
1801
- );
1802
- if (!mutationForKey) {
1803
- mutationForKey = {
1804
- ...createMutationRunner(options),
1805
- mutationKey
1806
- };
1807
- this.setMutationRunnersByKey(serializedMutationKey, mutationForKey);
1808
- mutationForKey.mutation$.subscribe();
1809
- mutationForKey.mutationsSubject.pipe(
1810
- rxjs.distinctUntilChanged(shallowEqual),
1811
- rxjs.skip(1),
1812
- rxjs.filter((items) => items.length === 0)
1813
- ).subscribe(() => {
1814
- mutationForKey == null ? void 0 : mutationForKey.destroy();
1815
- this.deleteMutationRunnersByKey(serializedMutationKey);
1816
- });
1817
- }
1818
- mutationForKey.trigger({ args, options });
1819
- })
1820
- ).subscribe();
1821
- this.cancel$.pipe(
1822
- rxjs.tap(({ key }) => {
1823
- var _a;
1824
- const serializedKey = serializeKey(key);
1825
- (_a = this.mutationRunnersByKey$.getValue().get(serializedKey)) == null ? void 0 : _a.cancel$.next();
1826
- })
1827
- ).subscribe();
1828
- this.mutationRunnersByKey$.pipe(
1829
- rxjs.switchMap((mapItem) => {
1830
- const mutationRunners = Array.from(mapItem.values());
1831
- const mutations$ = rxjs.combineLatest(
1832
- mutationRunners.map(
1833
- (runner) => runner.mutationsSubject.pipe(
1834
- rxjs.map((mutations) => mutations.map((mutation) => mutation))
1835
- )
1836
- )
1837
- );
1838
- return mutations$.pipe(
1839
- rxjs.map(
1840
- (mutationsByKeys) => mutationsByKeys.reduce((acc, value) => [...acc, ...value], [])
1841
- )
1842
- );
1843
- }),
1844
- rxjs.startWith([]),
1845
- rxjs.distinctUntilChanged(shallowEqual)
1846
- ).subscribe(this.mutationsSubject);
1616
+ this.client = client;
1847
1617
  }
1848
1618
  /**
1849
1619
  * @helper
1850
1620
  */
1851
1621
  setMutationRunnersByKey(key, value) {
1852
- const map2 = this.mutationRunnersByKey$.getValue();
1853
- map2.set(key, value);
1854
- this.mutationRunnersByKey$.next(map2);
1622
+ const map = this.mutationRunnersByKey$.getValue();
1623
+ map.set(key, value);
1624
+ this.mutationRunnersByKey$.next(map);
1855
1625
  }
1856
1626
  /**
1857
1627
  * @helper
1858
1628
  */
1859
1629
  deleteMutationRunnersByKey(key) {
1860
- const map2 = this.mutationRunnersByKey$.getValue();
1861
- map2.delete(key);
1862
- this.mutationRunnersByKey$.next(map2);
1630
+ const map = this.mutationRunnersByKey$.getValue();
1631
+ map.delete(key);
1632
+ this.mutationRunnersByKey$.next(map);
1863
1633
  }
1864
1634
  /**
1865
1635
  * @helper
@@ -1867,65 +1637,569 @@ class MutationClient {
1867
1637
  getMutationRunnersByKey(key) {
1868
1638
  return this.mutationRunnersByKey$.getValue().get(key);
1869
1639
  }
1870
- useIsMutating(filters = {}) {
1871
- const predicate = createPredicateForFilters(filters);
1872
- const reduceByNumber = (entries) => entries.reduce((acc, mutation) => {
1873
- return predicate(mutation) && mutation.state.status === "pending" ? 1 + acc : acc;
1874
- }, 0);
1875
- const lastValue = reduceByNumber(this.mutationsSubject.getValue());
1876
- const value$ = this.mutationsSubject.pipe(
1877
- rxjs.switchMap((mutations) => {
1878
- const mutationsOnStateUpdate = mutations.map(
1879
- (mutation) => mutation.stateSubject.pipe(rxjs.map(() => mutation))
1640
+ async mutate(params) {
1641
+ const { mutationKey } = params.options;
1642
+ const serializedMutationKey = serializeKey(mutationKey);
1643
+ let mutationForKey = this.getMutationRunnersByKey(serializedMutationKey);
1644
+ if (!mutationForKey) {
1645
+ mutationForKey = {
1646
+ ...createMutationRunner({
1647
+ ...params.options,
1648
+ client: this.client,
1649
+ mutationCache: this.client.getMutationCache()
1650
+ }),
1651
+ mutationKey
1652
+ };
1653
+ this.setMutationRunnersByKey(serializedMutationKey, mutationForKey);
1654
+ mutationForKey.runner$.subscribe();
1655
+ this.client.getMutationCache().mutationsBy({
1656
+ exact: true,
1657
+ mutationKey
1658
+ }).pipe(
1659
+ rxjs.distinctUntilChanged(shallowEqual),
1660
+ rxjs.skip(1),
1661
+ rxjs.filter((items) => items.length === 0),
1662
+ rxjs.take(1)
1663
+ ).subscribe(() => {
1664
+ mutationForKey == null ? void 0 : mutationForKey.destroy();
1665
+ this.deleteMutationRunnersByKey(serializedMutationKey);
1666
+ });
1667
+ }
1668
+ const mutation = this.client.getMutationCache().build(this.client, params.options);
1669
+ mutationForKey.trigger(params);
1670
+ return await new Promise((resolve, reject) => {
1671
+ mutation.observeTillFinished().pipe(rxjs.last()).subscribe({
1672
+ error: reject,
1673
+ next: resolve
1674
+ });
1675
+ });
1676
+ }
1677
+ destroy() {
1678
+ this.mutationRunnersByKey$.complete();
1679
+ }
1680
+ }
1681
+ const functionAsObservable = (fn) => {
1682
+ return rxjs.defer(() => {
1683
+ const result = fn();
1684
+ if (result instanceof Promise) {
1685
+ return rxjs.from(result);
1686
+ }
1687
+ if (result instanceof rxjs.Observable) {
1688
+ return result;
1689
+ }
1690
+ return rxjs.of(result);
1691
+ });
1692
+ };
1693
+ class Mutation {
1694
+ constructor({
1695
+ options,
1696
+ mutationCache
1697
+ }) {
1698
+ __publicField(this, "state", getDefaultMutationState());
1699
+ __publicField(this, "state$");
1700
+ __publicField(this, "options");
1701
+ __publicField(this, "mutationCache");
1702
+ __publicField(this, "observerCount", new rxjs.BehaviorSubject(0));
1703
+ __publicField(this, "observerCount$", this.observerCount.asObservable());
1704
+ __publicField(this, "cancelSubject", new rxjs.Subject());
1705
+ __publicField(this, "executeSubject", new rxjs.Subject());
1706
+ this.options = options;
1707
+ this.mutationCache = mutationCache;
1708
+ this.state$ = rxjs.merge(
1709
+ rxjs.of(this.state),
1710
+ this.executeSubject.pipe(
1711
+ rxjs.switchMap((variables) => this.createMutation(variables)),
1712
+ rxjs.tap((value) => {
1713
+ this.state = { ...this.state, ...value };
1714
+ }),
1715
+ rxjs.takeUntil(this.cancelSubject)
1716
+ ),
1717
+ rxjs.NEVER
1718
+ ).pipe(
1719
+ /**
1720
+ * refCount as true somewhat make NEVER complete when there are
1721
+ * no more observers. I thought I should have to complete manually (which is
1722
+ * why we still cancel the observable when we remove it from cache)
1723
+ */
1724
+ rxjs.shareReplay({ bufferSize: 1, refCount: true }),
1725
+ rxjs.takeUntil(this.cancelSubject),
1726
+ (source) => {
1727
+ return new rxjs.Observable(
1728
+ (observer) => {
1729
+ this.observerCount.next(this.observerCount.getValue() + 1);
1730
+ const sub = source.subscribe(observer);
1731
+ return () => {
1732
+ this.observerCount.next(this.observerCount.getValue() - 1);
1733
+ sub.unsubscribe();
1734
+ };
1735
+ }
1880
1736
  );
1881
- return mutationsOnStateUpdate.length === 0 ? rxjs.of([]) : rxjs.combineLatest(mutationsOnStateUpdate);
1882
- }),
1883
- rxjs.map(reduceByNumber),
1884
- rxjs.distinctUntilChanged()
1737
+ }
1885
1738
  );
1886
- return { value$, lastValue };
1887
1739
  }
1888
- mutationState({
1740
+ createMutation(variables) {
1741
+ const mutationFn = this.options.mutationFn;
1742
+ const onCacheMutate$ = functionAsObservable(
1743
+ () => {
1744
+ var _a, _b;
1745
+ return (_b = (_a = this.mutationCache.config).onMutate) == null ? void 0 : _b.call(
1746
+ _a,
1747
+ variables,
1748
+ this
1749
+ );
1750
+ }
1751
+ );
1752
+ const onMutate = rxjs.concat(
1753
+ onCacheMutate$.pipe(
1754
+ rxjs.mergeMap(() => {
1755
+ const onMutate$ = functionAsObservable(
1756
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
1757
+ () => {
1758
+ var _a, _b;
1759
+ return ((_b = (_a = this.options).onMutate) == null ? void 0 : _b.call(_a, variables)) ?? void 0;
1760
+ }
1761
+ );
1762
+ return onMutate$;
1763
+ })
1764
+ )
1765
+ );
1766
+ const queryRunner$ = onMutate.pipe(
1767
+ rxjs.switchMap((context) => {
1768
+ const fn$ = typeof mutationFn === "function" ? (
1769
+ // eslint-disable-next-line @typescript-eslint/promise-function-async
1770
+ functionAsObservable(() => mutationFn(variables))
1771
+ ) : mutationFn;
1772
+ return fn$.pipe(
1773
+ retryOnError(this.options),
1774
+ rxjs.take(1),
1775
+ rxjs.map((data) => ({ data, context, isError: false })),
1776
+ rxjs.catchError((error) => {
1777
+ console.error(error);
1778
+ const onCacheError$ = functionAsObservable(
1779
+ () => {
1780
+ var _a, _b;
1781
+ return (_b = (_a = this.mutationCache.config).onError) == null ? void 0 : _b.call(_a, error, variables, context, this);
1782
+ }
1783
+ );
1784
+ const onError$ = functionAsObservable(
1785
+ () => {
1786
+ var _a, _b;
1787
+ return (_b = (_a = this.options).onError) == null ? void 0 : _b.call(_a, error, variables, context);
1788
+ }
1789
+ );
1790
+ return rxjs.concat(onCacheError$, onError$).pipe(
1791
+ rxjs.toArray(),
1792
+ rxjs.map(() => ({ data: error, context, isError: true }))
1793
+ );
1794
+ })
1795
+ );
1796
+ })
1797
+ );
1798
+ const initState$ = rxjs.of({
1799
+ ...this.state,
1800
+ variables,
1801
+ status: "pending",
1802
+ submittedAt: (/* @__PURE__ */ new Date()).getTime()
1803
+ });
1804
+ const mutation$ = rxjs.merge(
1805
+ initState$,
1806
+ queryRunner$.pipe(
1807
+ rxjs.switchMap(({ data: dataOrError, isError, context }) => {
1808
+ const error = isError ? dataOrError : null;
1809
+ const data = isError ? void 0 : dataOrError;
1810
+ const onCacheSuccess$ = isError ? rxjs.of(null) : functionAsObservable(
1811
+ () => {
1812
+ var _a, _b;
1813
+ return (_b = (_a = this.mutationCache.config).onSuccess) == null ? void 0 : _b.call(
1814
+ _a,
1815
+ data,
1816
+ variables,
1817
+ context,
1818
+ this
1819
+ );
1820
+ }
1821
+ );
1822
+ const onSuccess$ = isError ? rxjs.of(null) : functionAsObservable(
1823
+ () => {
1824
+ var _a, _b;
1825
+ return (_b = (_a = this.options).onSuccess) == null ? void 0 : _b.call(_a, data, variables, context);
1826
+ }
1827
+ );
1828
+ const onCacheSettled$ = functionAsObservable(
1829
+ () => {
1830
+ var _a, _b;
1831
+ return (_b = (_a = this.mutationCache.config).onSettled) == null ? void 0 : _b.call(
1832
+ _a,
1833
+ data,
1834
+ error,
1835
+ variables,
1836
+ context,
1837
+ this
1838
+ );
1839
+ }
1840
+ );
1841
+ const onSettled$ = functionAsObservable(
1842
+ () => {
1843
+ var _a, _b;
1844
+ return (_b = (_a = this.options).onSettled) == null ? void 0 : _b.call(_a, data, error, variables, context);
1845
+ }
1846
+ );
1847
+ const result$ = rxjs.concat(
1848
+ onCacheSuccess$,
1849
+ onSuccess$,
1850
+ onCacheSettled$,
1851
+ onSettled$
1852
+ ).pipe(
1853
+ rxjs.toArray(),
1854
+ rxjs.map(
1855
+ () => isError ? {
1856
+ status: "error",
1857
+ error,
1858
+ data,
1859
+ context,
1860
+ variables
1861
+ } : {
1862
+ status: "success",
1863
+ error,
1864
+ data,
1865
+ context,
1866
+ variables
1867
+ }
1868
+ )
1869
+ );
1870
+ return result$;
1871
+ })
1872
+ )
1873
+ ).pipe(
1874
+ mergeResults,
1875
+ this.options.__queryRunnerHook ?? rxjs.identity,
1876
+ rxjs.takeUntil(this.cancelSubject)
1877
+ );
1878
+ return mutation$;
1879
+ }
1880
+ observeTillFinished() {
1881
+ return this.state$.pipe(
1882
+ rxjs.takeWhile(
1883
+ (result) => result.status !== "error" && result.status !== "success",
1884
+ true
1885
+ )
1886
+ );
1887
+ }
1888
+ /**
1889
+ * @important
1890
+ * The resulting observable will complete as soon as the mutation
1891
+ * is over, unlike the state which can be re-subscribed later.
1892
+ */
1893
+ execute(variables) {
1894
+ this.executeSubject.next(variables);
1895
+ this.executeSubject.complete();
1896
+ return this.observeTillFinished();
1897
+ }
1898
+ cancel() {
1899
+ this.cancelSubject.next();
1900
+ this.cancelSubject.complete();
1901
+ this.executeSubject.complete();
1902
+ }
1903
+ }
1904
+ const createPredicateForFilters = ({
1905
+ mutationKey,
1906
+ status,
1907
+ predicate,
1908
+ exact = true
1909
+ } = {}) => {
1910
+ const finalPredicate = (mutation) => {
1911
+ if (exact && mutationKey !== void 0 && !compareKeys(mutation.options.mutationKey, mutationKey, { exact })) {
1912
+ return false;
1913
+ }
1914
+ if (!exact && mutationKey !== void 0 && !compareKeys(mutationKey, mutation.options.mutationKey, { exact })) {
1915
+ return false;
1916
+ }
1917
+ if (status && mutation.state.status !== status)
1918
+ return false;
1919
+ if (predicate) {
1920
+ return predicate(mutation);
1921
+ }
1922
+ return true;
1923
+ };
1924
+ return finalPredicate;
1925
+ };
1926
+ class MutationCache {
1927
+ constructor(config = {}) {
1928
+ __publicField(this, "mutationsSubject", new rxjs.BehaviorSubject([]));
1929
+ __publicField(this, "mutations$", this.mutationsSubject.pipe(
1930
+ rxjs.map((mutations) => mutations.map(({ mutation }) => mutation)),
1931
+ rxjs.distinctUntilChanged(arrayEqual),
1932
+ rxjs.share()
1933
+ ));
1934
+ __publicField(this, "added$", this.mutations$.pipe(
1935
+ rxjs.pairwise(),
1936
+ rxjs.map(
1937
+ ([previous, current]) => current.filter((mutation) => !previous.includes(mutation))[0]
1938
+ ),
1939
+ rxjs.filter(isDefined),
1940
+ rxjs.share()
1941
+ ));
1942
+ __publicField(this, "removed$", this.mutations$.pipe(
1943
+ rxjs.pairwise(),
1944
+ rxjs.map(
1945
+ ([previous, current]) => previous.filter((mutation) => !current.includes(mutation))
1946
+ ),
1947
+ rxjs.mergeMap((removedItems) => rxjs.from(removedItems)),
1948
+ rxjs.share()
1949
+ ));
1950
+ __publicField(this, "stateChange$", this.added$.pipe(
1951
+ rxjs.mergeMap(
1952
+ (mutation) => mutation.state$.pipe(
1953
+ rxjs.map(() => mutation),
1954
+ rxjs.takeUntil(
1955
+ this.removed$.pipe(
1956
+ rxjs.filter((removedMutation) => removedMutation === mutation)
1957
+ )
1958
+ )
1959
+ )
1960
+ ),
1961
+ rxjs.share()
1962
+ ));
1963
+ this.config = config;
1964
+ }
1965
+ subscribe(listener) {
1966
+ const sub = rxjs.merge(
1967
+ this.added$.pipe(
1968
+ rxjs.tap((mutation) => {
1969
+ listener({
1970
+ type: "added",
1971
+ mutation
1972
+ });
1973
+ })
1974
+ ),
1975
+ this.removed$.pipe(
1976
+ rxjs.tap((mutation) => {
1977
+ listener({
1978
+ type: "removed",
1979
+ mutation
1980
+ });
1981
+ })
1982
+ ),
1983
+ this.stateChange$.pipe(
1984
+ rxjs.tap((mutation) => {
1985
+ listener({
1986
+ type: "updated",
1987
+ action: {
1988
+ ...mutation.state,
1989
+ // @todo
1990
+ type: "success"
1991
+ },
1992
+ mutation
1993
+ });
1994
+ })
1995
+ )
1996
+ ).subscribe();
1997
+ return () => {
1998
+ sub.unsubscribe();
1999
+ };
2000
+ }
2001
+ build(client, options) {
2002
+ const mutation = new Mutation({
2003
+ mutationCache: this,
2004
+ // mutationId: ++this.#mutationId,
2005
+ options: client.defaultMutationOptions(options)
2006
+ // state
2007
+ });
2008
+ const sub = mutation.state$.pipe(
2009
+ /**
2010
+ * Once a mutation is finished and there are no more observers than us
2011
+ * we start the process of cleaning it up based on gc settings
2012
+ */
2013
+ rxjs.filter(({ status }) => status === "success" || status === "error"),
2014
+ rxjs.switchMap(
2015
+ () => mutation.observerCount$.pipe(
2016
+ rxjs.filter((count) => count <= 1),
2017
+ rxjs.take(1)
2018
+ )
2019
+ ),
2020
+ rxjs.switchMap(() => rxjs.timer(mutation.options.gcTime ?? 0)),
2021
+ rxjs.take(1)
2022
+ ).subscribe({
2023
+ complete: () => {
2024
+ this.remove(mutation);
2025
+ }
2026
+ });
2027
+ this.mutationsSubject.next([
2028
+ ...this.mutationsSubject.getValue(),
2029
+ { mutation, sub }
2030
+ ]);
2031
+ return mutation;
2032
+ }
2033
+ getAll() {
2034
+ return this.findAll();
2035
+ }
2036
+ remove(mutation) {
2037
+ this.removeBy({ predicate: (item) => item === mutation });
2038
+ }
2039
+ removeBy(filters) {
2040
+ const defaultedFilters = { exact: true, ...filters };
2041
+ const predicate = createPredicateForFilters(defaultedFilters);
2042
+ const toRemove = this.mutationsSubject.getValue().filter(({ mutation }) => {
2043
+ return predicate(mutation);
2044
+ }).map(({ mutation, sub }) => {
2045
+ mutation.cancel();
2046
+ sub.unsubscribe();
2047
+ return mutation;
2048
+ });
2049
+ this.mutationsSubject.next(
2050
+ this.mutationsSubject.getValue().filter(({ mutation }) => !toRemove.includes(mutation))
2051
+ );
2052
+ }
2053
+ find(filters) {
2054
+ var _a;
2055
+ const defaultedFilters = { exact: true, ...filters };
2056
+ const predicate = createPredicateForFilters(defaultedFilters);
2057
+ return (_a = this.mutationsSubject.getValue().find(({ mutation }) => predicate(mutation))) == null ? void 0 : _a.mutation;
2058
+ }
2059
+ findLatest(filters) {
2060
+ var _a;
2061
+ const defaultedFilters = { exact: true, ...filters };
2062
+ const predicate = createPredicateForFilters(defaultedFilters);
2063
+ return (_a = this.mutationsSubject.getValue().slice().reverse().find(({ mutation }) => predicate(mutation))) == null ? void 0 : _a.mutation;
2064
+ }
2065
+ findAll(filters = {}) {
2066
+ const defaultedFilters = { exact: true, ...filters };
2067
+ const predicate = createPredicateForFilters(defaultedFilters);
2068
+ return this.mutationsSubject.getValue().filter(({ mutation }) => predicate(mutation)).map(({ mutation }) => mutation);
2069
+ }
2070
+ mutationsBy(filters) {
2071
+ const defaultedFilters = { exact: true, ...filters };
2072
+ const predicate = createPredicateForFilters(defaultedFilters);
2073
+ return this.mutations$.pipe(
2074
+ rxjs.map((mutations) => mutations.filter(predicate)),
2075
+ rxjs.distinctUntilChanged(arrayEqual)
2076
+ );
2077
+ }
2078
+ mutationStateBy({
1889
2079
  filters,
1890
2080
  select
1891
2081
  } = {}) {
1892
2082
  const predicate = createPredicateForFilters(filters);
1893
2083
  const finalSelect = select ?? ((mutation) => mutation.state);
1894
- const lastValue = this.mutationsSubject.getValue().reduce((acc, mutation) => {
2084
+ const lastValue = this.getAll().reduce((acc, mutation) => {
1895
2085
  const result = [...acc, mutation];
1896
2086
  return result;
1897
2087
  }, []).filter(predicate).map((mutation) => finalSelect(mutation));
1898
- const value$ = this.mutationsSubject.pipe(
1899
- rxjs.switchMap((mutations) => {
1900
- const mutationsOnStateUpdate = mutations.map(
1901
- (mutation) => mutation.stateSubject.pipe(
1902
- rxjs.filter(() => predicate(mutation)),
1903
- rxjs.map(() => finalSelect(mutation))
1904
- )
1905
- );
1906
- return mutationsOnStateUpdate.length === 0 ? rxjs.of([]) : rxjs.combineLatest(mutationsOnStateUpdate);
2088
+ const value$ = this.stateChange$.pipe(
2089
+ rxjs.startWith(),
2090
+ rxjs.map(() => {
2091
+ const filteredMutations = this.getAll().filter(predicate);
2092
+ return filteredMutations.map(finalSelect);
1907
2093
  }),
1908
2094
  rxjs.distinctUntilChanged(shallowEqual)
1909
2095
  );
1910
2096
  return { value$, lastValue };
1911
2097
  }
1912
- mutate(params) {
1913
- this.mutate$.next(params);
2098
+ cancelBy(filters) {
2099
+ this.findAll(filters).forEach((mutation) => {
2100
+ mutation.cancel();
2101
+ });
1914
2102
  }
1915
- /**
1916
- * This will cancel any current mutation runnings.
1917
- * No discrimination process
1918
- */
1919
- cancel(params) {
1920
- this.cancel$.next(params);
2103
+ clear() {
2104
+ this.getAll().forEach((mutation) => {
2105
+ this.remove(mutation);
2106
+ });
2107
+ }
2108
+ }
2109
+ class MutationObserver {
2110
+ constructor(client, options) {
2111
+ __publicField(this, "getDerivedState", (state) => {
2112
+ return {
2113
+ ...getDefaultMutationState(),
2114
+ ...state,
2115
+ isSuccess: state.status === "success",
2116
+ isPending: state.status === "pending",
2117
+ isIdle: state.status === "idle",
2118
+ isError: state.status === "error"
2119
+ };
2120
+ });
2121
+ this.client = client;
2122
+ this.options = options;
2123
+ }
2124
+ observeBy(filters) {
2125
+ const reduceStateFromMutation = (values) => {
2126
+ var _a;
2127
+ return values.reduce(
2128
+ (acc, { state, options }) => {
2129
+ if (options.mapOperator === "switch")
2130
+ return state;
2131
+ if (acc && state.submittedAt >= acc.submittedAt) {
2132
+ return {
2133
+ ...state,
2134
+ data: state.data ?? acc.data,
2135
+ error: state.error ?? acc.error
2136
+ };
2137
+ }
2138
+ return acc;
2139
+ },
2140
+ ((_a = values[0]) == null ? void 0 : _a.state) ?? getDefaultMutationState()
2141
+ );
2142
+ };
2143
+ const mutations = this.client.getMutationCache().findAll(filters);
2144
+ const lastValue = this.getDerivedState(
2145
+ reduceStateFromMutation(mutations)
2146
+ );
2147
+ const result$ = this.client.getMutationCache().mutationsBy(filters).pipe(
2148
+ rxjs.switchMap(
2149
+ (mutations2) => rxjs.combineLatest(
2150
+ mutations2.map(
2151
+ (mutation) => this.observe(mutation).pipe(
2152
+ rxjs.map((state) => ({ state, options: mutation.options }))
2153
+ )
2154
+ )
2155
+ )
2156
+ ),
2157
+ rxjs.map(reduceStateFromMutation),
2158
+ rxjs.filter(isDefined),
2159
+ rxjs.map(this.getDerivedState),
2160
+ rxjs.distinctUntilChanged(shallowEqual)
2161
+ );
2162
+ return { result$, lastValue };
2163
+ }
2164
+ observe(mutation) {
2165
+ return mutation.state$;
2166
+ }
2167
+ subscribe(subscription) {
2168
+ const sub = this.client.getMutationCache().mutations$.pipe(
2169
+ rxjs.mergeMap((mutations) => {
2170
+ const observed$ = mutations.map(
2171
+ (mutation) => this.observe(mutation).pipe(
2172
+ // we only want next changes
2173
+ rxjs.skip(1)
2174
+ )
2175
+ );
2176
+ return rxjs.merge(...observed$);
2177
+ })
2178
+ ).subscribe(subscription);
2179
+ return () => {
2180
+ sub.unsubscribe();
2181
+ };
2182
+ }
2183
+ async mutate(variables, options) {
2184
+ const mergedOptions = {
2185
+ ...this.options,
2186
+ ...options
2187
+ };
2188
+ return await this.client.mutationRunners.mutate({
2189
+ args: variables,
2190
+ options: {
2191
+ mutationFn: async () => void 0,
2192
+ ...mergedOptions,
2193
+ mutationKey: mergedOptions.mutationKey ?? [nanoid()]
2194
+ }
2195
+ });
2196
+ }
2197
+ reset() {
2198
+ this.client.getMutationCache().getAll().forEach((mutation) => {
2199
+ mutation.cancel();
2200
+ });
1921
2201
  }
1922
2202
  destroy() {
1923
- this.cancel$.complete();
1924
- this.mutate$.complete();
1925
- this.mutationResultObserver.destroy();
1926
- this.mutationRunnersByKey$.complete();
1927
- this.isMutatingSubject.complete();
1928
- this.mutationsSubject.complete();
1929
2203
  }
1930
2204
  }
1931
2205
  const createClient = () => {
@@ -1933,7 +2207,6 @@ const createClient = () => {
1933
2207
  const invalidationClient = createInvalidationClient({ queryStore });
1934
2208
  const cacheClient = createCacheClient({ queryStore });
1935
2209
  const refetchClient = createRefetchClient();
1936
- const mutationClient = new MutationClient();
1937
2210
  let hasCalledStart = false;
1938
2211
  const query = ({
1939
2212
  key,
@@ -2044,6 +2317,8 @@ const createClient = () => {
2044
2317
  })
2045
2318
  )
2046
2319
  );
2320
+ const destroy = () => {
2321
+ };
2047
2322
  const start = () => {
2048
2323
  hasCalledStart = true;
2049
2324
  const queryListenerSub = queryListener$.subscribe();
@@ -2055,14 +2330,10 @@ const createClient = () => {
2055
2330
  queryListenerSub.unsubscribe();
2056
2331
  };
2057
2332
  };
2058
- const destroy = () => {
2059
- mutationClient.destroy();
2060
- };
2061
2333
  return {
2062
2334
  start,
2063
2335
  query,
2064
2336
  queryStore,
2065
- mutationClient,
2066
2337
  ...invalidationClient,
2067
2338
  ...cacheClient,
2068
2339
  ...refetchClient,
@@ -2070,11 +2341,35 @@ const createClient = () => {
2070
2341
  };
2071
2342
  };
2072
2343
  class QueryClient {
2073
- constructor() {
2344
+ constructor({ mutationCache } = {
2345
+ mutationCache: new MutationCache()
2346
+ }) {
2074
2347
  __publicField(this, "client");
2348
+ __publicField(this, "mutationCache");
2349
+ __publicField(this, "mutationRunners");
2350
+ __publicField(this, "mutationObserver");
2351
+ this.mutationCache = mutationCache;
2352
+ this.mutationRunners = new MutationRunners(this);
2353
+ this.mutationObserver = new MutationObserver(this);
2075
2354
  this.client = createClient();
2076
2355
  }
2356
+ mount() {
2357
+ const stop = this.client.start();
2358
+ return () => {
2359
+ this.mutationRunners.destroy();
2360
+ stop();
2361
+ };
2362
+ }
2363
+ getMutationCache() {
2364
+ return this.mutationCache;
2365
+ }
2366
+ defaultMutationOptions(options) {
2367
+ return options;
2368
+ }
2369
+ clear() {
2370
+ }
2077
2371
  }
2372
+ exports.MutationCache = MutationCache;
2078
2373
  exports.QueryClient = QueryClient;
2079
2374
  exports.QueryClientProvider = QueryClientProvider;
2080
2375
  exports.SIGNAL_RESET = SIGNAL_RESET;