reactjrx 1.61.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 (35) hide show
  1. package/dist/index.cjs +667 -342
  2. package/dist/index.d.ts +1 -0
  3. package/dist/index.js +662 -337
  4. package/dist/lib/queries/client/createClient.d.ts +14 -3
  5. package/dist/lib/queries/client/mutations/Mutation.d.ts +23 -11
  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 +2 -2
  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 +21 -23
  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 +10 -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 -103
  34. package/dist/lib/queries/client/mutations/createMutationRunner.d.ts +0 -15
  35. /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,43 +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.observe({ key }),
469
- [key]
470
- );
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]);
471
482
  const result = useObserve(observedMutation.result$) ?? observedMutation.lastValue;
472
483
  const mutate = react.useCallback(
473
484
  (mutationArgs) => {
474
- finalQueryClient.mutationClient.mutate({
485
+ finalQueryClient.mutationRunners.mutate({
475
486
  options: {
476
487
  ...optionsRef.current,
477
488
  mutationKey: optionsRef.current.mutationKey ?? defaultKey.current
478
489
  },
479
490
  args: mutationArgs
491
+ }).catch(noop);
492
+ const mutation = finalQueryClient.getMutationCache().findLatest({
493
+ mutationKey: optionsRef.current.mutationKey ?? defaultKey.current
480
494
  });
495
+ if (mutation) {
496
+ mutationsToCancel.current.push(mutation);
497
+ }
481
498
  },
482
- [finalQueryClient, key]
499
+ [finalQueryClient, serializedKey, defaultKey, optionsRef]
483
500
  );
484
501
  const cancel = react.useCallback(() => {
485
- finalQueryClient.mutationClient.cancel({
486
- key: optionsRef.current.mutationKey ?? defaultKey.current
502
+ mutationsToCancel.current.forEach((mutation) => {
503
+ mutation.cancel();
487
504
  });
488
- }, [finalQueryClient]);
505
+ }, []);
489
506
  react.useEffect(() => {
490
507
  return () => {
491
508
  if (optionsRef.current.cancelOnUnMount) {
492
- finalQueryClient.mutationClient.cancel({
493
- key: optionsRef.current.mutationKey ?? defaultKey.current
494
- });
509
+ cancel();
495
510
  }
496
511
  };
497
- }, []);
512
+ }, [cancel, optionsRef]);
498
513
  return { mutate, cancel, ...result };
499
514
  }
500
515
  const arrayEqual = (a, b) => a.length === b.length && a.every((v, i) => v === b[i]);
@@ -570,7 +585,7 @@ const useQueryParams = ({
570
585
  options,
571
586
  queryFn
572
587
  });
573
- }, [queryKey, options, queryFn]);
588
+ }, [queryKey, options, queryFn, params$]);
574
589
  return params$;
575
590
  };
576
591
  const defaultValue = {
@@ -622,7 +637,7 @@ function useQuery({
622
637
  return newQueryTrigger$.pipe(
623
638
  rxjs.withLatestFrom(key$),
624
639
  rxjs.switchMap(([, key]) => {
625
- const { result$ } = client.query({
640
+ const { result$ } = client.client.query({
626
641
  key,
627
642
  fn$,
628
643
  options$,
@@ -664,7 +679,7 @@ function useQuery({
664
679
  );
665
680
  const refetch = react.useCallback(() => {
666
681
  internalRefresh$.current.next({ type: "refetch", ignoreStale: true });
667
- }, [client]);
682
+ }, [internalRefresh$]);
668
683
  return { ...result, refetch };
669
684
  }
670
685
  function useSubscribeEffect(source, unsafeOptions, deps = []) {
@@ -683,7 +698,7 @@ function useSubscribeEffect(source, unsafeOptions, deps = []) {
683
698
  }),
684
699
  retryOption ? rxjs.retry() : rxjs.identity
685
700
  ),
686
- [makeObservable]
701
+ [makeObservable, retryOption]
687
702
  );
688
703
  useSubscribe(enhancerMakeObservable, deps);
689
704
  }
@@ -1468,116 +1483,46 @@ const dispatchExternalRefetchToAllQueries = ({
1468
1483
  }),
1469
1484
  rxjs.filter((trigger2) => trigger2.type !== "refetch")
1470
1485
  );
1471
- const mergeResults = (stream$) => stream$.pipe(
1472
- rxjs.scan(
1473
- (acc, current) => {
1474
- return {
1475
- ...acc,
1476
- ...current,
1477
- data: current.data ?? acc.data,
1478
- error: current.error ?? acc.error
1479
- };
1480
- },
1481
- {
1482
- data: void 0,
1483
- error: void 0,
1484
- status: "pending"
1485
- }
1486
- ),
1487
- rxjs.distinctUntilChanged(
1488
- ({ data: prevData, ...prev }, { data: currData, ...curr }) => shallowEqual(prev, curr) && shallowEqual(prevData, currData)
1489
- )
1490
- );
1491
1486
  const getDefaultMutationState = () => ({
1492
- context: {},
1487
+ context: void 0,
1493
1488
  data: void 0,
1494
1489
  error: null,
1495
1490
  status: "idle",
1496
1491
  submittedAt: 0,
1497
1492
  variables: void 0
1498
1493
  });
1499
- class Mutation {
1500
- constructor({
1501
- args,
1502
- ...options
1503
- }) {
1504
- __publicField(this, "stateSubject", new rxjs.BehaviorSubject(
1505
- getDefaultMutationState()
1506
- ));
1507
- /**
1508
- * @important
1509
- * proxy for rect-query, not really useful
1510
- */
1511
- __publicField(this, "state", this.stateSubject.getValue());
1512
- __publicField(this, "options");
1513
- __publicField(this, "mutation$");
1514
- this.options = options;
1515
- const mutationFn = options.mutationFn;
1516
- this.state.variables = args;
1517
- this.stateSubject.next(this.state);
1518
- const mutationFnObservable = typeof mutationFn === "function" ? rxjs.defer(() => rxjs.from(mutationFn(args))) : mutationFn;
1519
- const queryRunner$ = mutationFnObservable.pipe(
1520
- retryOnError(options),
1521
- rxjs.take(1),
1522
- rxjs.map((data) => ({ data, isError: false })),
1523
- rxjs.catchError((error) => {
1524
- console.error(error);
1525
- if (options.onError != null) {
1526
- options.onError(error, args);
1527
- }
1528
- return rxjs.of({ data: error, isError: true });
1529
- })
1530
- );
1531
- const loading$ = rxjs.of({
1532
- status: "pending"
1533
- });
1534
- this.mutation$ = rxjs.merge(
1535
- loading$,
1536
- queryRunner$.pipe(
1537
- rxjs.map(({ data, isError }) => {
1538
- if (!isError) {
1539
- if (options.onSuccess != null)
1540
- options.onSuccess(data, args);
1541
- }
1542
- return isError ? {
1543
- status: "error",
1544
- error: data,
1545
- data: void 0
1546
- } : {
1547
- status: "success",
1548
- error: null,
1549
- data
1550
- };
1551
- })
1552
- )
1553
- ).pipe(
1554
- mergeResults,
1555
- rxjs.tap((value) => {
1556
- this.state = { ...this.state, ...value };
1557
- this.stateSubject.next(this.state);
1558
- }),
1559
- options.__queryRunnerHook ?? rxjs.identity,
1560
- rxjs.share()
1561
- );
1562
- }
1563
- }
1494
+ const mergeResults = (stream$) => stream$.pipe(
1495
+ rxjs.scan((acc, current) => {
1496
+ return {
1497
+ ...acc,
1498
+ ...current,
1499
+ data: current.data ?? acc.data,
1500
+ error: current.error ?? acc.error
1501
+ };
1502
+ }, getDefaultMutationState()),
1503
+ rxjs.distinctUntilChanged(
1504
+ ({ data: prevData, ...prev }, { data: currData, ...curr }) => shallowEqual(prev, curr) && shallowEqual(prevData, currData)
1505
+ )
1506
+ );
1564
1507
  const createMutationRunner = ({
1565
1508
  __queryFinalizeHook,
1566
1509
  __queryInitHook,
1567
- __queryTriggerHook
1510
+ __queryTriggerHook,
1511
+ mutationKey,
1512
+ mutationCache
1568
1513
  }) => {
1569
1514
  const trigger$ = new rxjs.Subject();
1570
1515
  const cancel$ = new rxjs.Subject();
1571
1516
  let closed = false;
1572
- const mapOperator$ = new rxjs.BehaviorSubject("merge");
1573
- const mutationsSubject = new rxjs.BehaviorSubject([]);
1517
+ const mapOperator$ = new rxjs.BehaviorSubject(
1518
+ "merge"
1519
+ );
1574
1520
  const destroy = () => {
1575
1521
  if (closed) {
1576
1522
  throw new Error("Trying to close an already closed mutation");
1577
1523
  }
1578
1524
  closed = true;
1579
1525
  mapOperator$.complete();
1580
- mutationsSubject.complete();
1581
1526
  trigger$.complete();
1582
1527
  cancel$.next();
1583
1528
  cancel$.complete();
@@ -1586,39 +1531,26 @@ const createMutationRunner = ({
1586
1531
  rxjs.filter(isDefined),
1587
1532
  rxjs.distinctUntilChanged()
1588
1533
  );
1589
- const mutation$ = stableMapOperator$.pipe(
1534
+ const runner$ = stableMapOperator$.pipe(
1590
1535
  __queryInitHook ?? rxjs.identity,
1591
1536
  rxjs.mergeMap((mapOperator) => {
1592
1537
  const switchOperator = mapOperator === "concat" ? rxjs.concatMap : mapOperator === "switch" ? rxjs.switchMap : rxjs.mergeMap;
1593
- let mutationsForCurrentMapOperatorSubject = [];
1594
- const removeMutation = (mutation) => {
1595
- mutationsForCurrentMapOperatorSubject = mutationsForCurrentMapOperatorSubject.filter(
1596
- (item) => item !== mutation
1597
- );
1598
- mutationsSubject.next(
1599
- mutationsSubject.getValue().filter((item) => item !== mutation)
1600
- );
1601
- };
1602
1538
  return trigger$.pipe(
1603
1539
  rxjs.takeUntil(stableMapOperator$.pipe(rxjs.skip(1))),
1604
- rxjs.map(({ args, options }) => {
1605
- const mutation = new Mutation({
1606
- args,
1607
- ...options,
1608
- mapOperator
1540
+ switchOperator(({ args }) => {
1541
+ const mutation = mutationCache.findLatest({
1542
+ exact: true,
1543
+ mutationKey
1609
1544
  });
1610
- mutationsForCurrentMapOperatorSubject = [
1611
- ...mutationsForCurrentMapOperatorSubject,
1612
- mutation
1613
- ];
1614
- mutationsSubject.next([...mutationsSubject.getValue(), mutation]);
1615
- return mutation;
1616
- }),
1617
- switchOperator((mutation) => {
1618
- if (!mutationsSubject.getValue().includes(mutation))
1545
+ if (!mutation) {
1619
1546
  return rxjs.of({});
1620
- const queryIsOver$ = mutation.mutation$.pipe(
1621
- 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
+ )
1622
1554
  );
1623
1555
  const isThisCurrentFunctionLastOneCalled = trigger$.pipe(
1624
1556
  rxjs.take(1),
@@ -1627,7 +1559,7 @@ const createMutationRunner = ({
1627
1559
  rxjs.takeUntil(queryIsOver$)
1628
1560
  );
1629
1561
  const result$ = rxjs.combineLatest([
1630
- mutation.mutation$,
1562
+ mutation$,
1631
1563
  isThisCurrentFunctionLastOneCalled
1632
1564
  ]).pipe(
1633
1565
  rxjs.map(([result, isLastMutationCalled]) => {
@@ -1636,11 +1568,7 @@ const createMutationRunner = ({
1636
1568
  }
1637
1569
  return result;
1638
1570
  }),
1639
- rxjs.takeUntil(cancel$.pipe()),
1640
- mergeResults,
1641
- rxjs.finalize(() => {
1642
- removeMutation(mutation);
1643
- })
1571
+ mergeResults
1644
1572
  );
1645
1573
  return result$;
1646
1574
  }),
@@ -1648,15 +1576,21 @@ const createMutationRunner = ({
1648
1576
  __queryTriggerHook ?? rxjs.identity
1649
1577
  );
1650
1578
  }),
1651
- __queryFinalizeHook ?? rxjs.identity
1579
+ __queryFinalizeHook ?? rxjs.identity,
1580
+ rxjs.shareReplay(1)
1652
1581
  );
1653
1582
  cancel$.subscribe(() => {
1654
- if (mutationsSubject.getValue().length === 0)
1655
- return;
1656
- 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
+ });
1657
1590
  });
1658
1591
  return {
1659
- mutation$,
1592
+ mutationKey,
1593
+ runner$,
1660
1594
  trigger: ({
1661
1595
  args,
1662
1596
  options
@@ -1666,29 +1600,11 @@ const createMutationRunner = ({
1666
1600
  },
1667
1601
  cancel$,
1668
1602
  destroy,
1669
- mutationsSubject,
1670
1603
  getClosed: () => closed
1671
1604
  };
1672
1605
  };
1673
- const createPredicateForFilters = ({
1674
- mutationKey,
1675
- status,
1676
- predicate
1677
- } = {}) => {
1678
- const defaultPredicate = (mutation) => {
1679
- if (mutationKey !== void 0 && // @todo optimize
1680
- serializeKey(mutation.options.mutationKey) !== serializeKey(mutationKey)) {
1681
- return false;
1682
- }
1683
- if (status && mutation.stateSubject.getValue().status !== status)
1684
- return false;
1685
- return true;
1686
- };
1687
- const finalPredicate = predicate ?? defaultPredicate;
1688
- return finalPredicate;
1689
- };
1690
- class MutationClient {
1691
- constructor() {
1606
+ class MutationRunners {
1607
+ constructor(client) {
1692
1608
  /**
1693
1609
  * Contain all active mutation for a given key.
1694
1610
  * A mutation ca have several triggers running (it is not necessarily one function running)
@@ -1697,105 +1613,23 @@ class MutationClient {
1697
1613
  * - automatically cleaned as soon as the last mutation is done for a given key
1698
1614
  */
1699
1615
  __publicField(this, "mutationRunnersByKey$", new rxjs.BehaviorSubject(/* @__PURE__ */ new Map()));
1700
- /**
1701
- * Mutation result subject. It can be used whether there is a mutation
1702
- * running or not and can be directly observed.
1703
- *
1704
- * @important
1705
- * - automatically cleaned as soon as the last mutation is done for a given key
1706
- */
1707
- __publicField(this, "mutationResults$", new rxjs.BehaviorSubject(/* @__PURE__ */ new Map()));
1708
- __publicField(this, "mutate$", new rxjs.Subject());
1709
- __publicField(this, "cancel$", new rxjs.Subject());
1710
- /**
1711
- * Observable to track how many running mutations per runner
1712
- */
1713
- __publicField(this, "isMutatingSubject", new rxjs.BehaviorSubject([]));
1714
- /**
1715
- * List of all mutations running
1716
- */
1717
- __publicField(this, "mutationsSubject", new rxjs.BehaviorSubject([]));
1718
- this.mutate$.pipe(
1719
- rxjs.tap(({ options, args }) => {
1720
- const { mutationKey } = options;
1721
- const serializedMutationKey = serializeKey(mutationKey);
1722
- let mutationForKey = this.getMutationRunnersByKey(
1723
- serializedMutationKey
1724
- );
1725
- if (!mutationForKey) {
1726
- mutationForKey = {
1727
- ...createMutationRunner(options),
1728
- mutationKey
1729
- };
1730
- this.setMutationRunnersByKey(serializedMutationKey, mutationForKey);
1731
- mutationForKey.mutation$.subscribe((result) => {
1732
- let resultForKeySubject = this.mutationResults$.getValue().get(serializedMutationKey);
1733
- if (!resultForKeySubject) {
1734
- resultForKeySubject = new rxjs.BehaviorSubject(result);
1735
- const resultMap = this.mutationResults$.getValue();
1736
- resultMap.set(serializedMutationKey, resultForKeySubject);
1737
- this.mutationResults$.next(resultMap);
1738
- } else {
1739
- resultForKeySubject == null ? void 0 : resultForKeySubject.next(result);
1740
- }
1741
- });
1742
- mutationForKey.mutationsSubject.pipe(
1743
- rxjs.distinctUntilChanged(shallowEqual),
1744
- rxjs.skip(1),
1745
- rxjs.filter((items) => items.length === 0)
1746
- ).subscribe(() => {
1747
- mutationForKey == null ? void 0 : mutationForKey.destroy();
1748
- const resultMap = this.mutationResults$.getValue();
1749
- resultMap.delete(serializedMutationKey);
1750
- this.mutationResults$.next(resultMap);
1751
- this.deleteMutationRunnersByKey(serializedMutationKey);
1752
- });
1753
- }
1754
- mutationForKey.trigger({ args, options });
1755
- })
1756
- ).subscribe();
1757
- this.cancel$.pipe(
1758
- rxjs.tap(({ key }) => {
1759
- var _a;
1760
- const serializedKey = serializeKey(key);
1761
- (_a = this.mutationRunnersByKey$.getValue().get(serializedKey)) == null ? void 0 : _a.cancel$.next();
1762
- })
1763
- ).subscribe();
1764
- this.mutationRunnersByKey$.pipe(
1765
- rxjs.switchMap((mapItem) => {
1766
- const mutationRunners = Array.from(mapItem.values());
1767
- const mutations$ = rxjs.combineLatest(
1768
- mutationRunners.map(
1769
- (runner) => runner.mutationsSubject.pipe(
1770
- rxjs.map((mutations) => mutations.map((mutation) => mutation))
1771
- )
1772
- )
1773
- );
1774
- return mutations$.pipe(
1775
- rxjs.map(
1776
- (mutationsByKeys) => mutationsByKeys.reduce((acc, value) => [...acc, ...value], [])
1777
- )
1778
- );
1779
- }),
1780
- rxjs.startWith([]),
1781
- rxjs.distinctUntilChanged(shallowEqual)
1782
- ).subscribe(this.mutationsSubject);
1616
+ this.client = client;
1783
1617
  }
1784
1618
  /**
1785
1619
  * @helper
1786
1620
  */
1787
1621
  setMutationRunnersByKey(key, value) {
1788
- const map2 = this.mutationRunnersByKey$.getValue();
1789
- map2.set(key, value);
1790
- this.mutationRunnersByKey$.next(map2);
1622
+ const map = this.mutationRunnersByKey$.getValue();
1623
+ map.set(key, value);
1624
+ this.mutationRunnersByKey$.next(map);
1791
1625
  }
1792
1626
  /**
1793
1627
  * @helper
1794
1628
  */
1795
1629
  deleteMutationRunnersByKey(key) {
1796
- const map2 = this.mutationRunnersByKey$.getValue();
1797
- map2.delete(key);
1798
- this.mutationRunnersByKey$.next(map2);
1630
+ const map = this.mutationRunnersByKey$.getValue();
1631
+ map.delete(key);
1632
+ this.mutationRunnersByKey$.next(map);
1799
1633
  }
1800
1634
  /**
1801
1635
  * @helper
@@ -1803,99 +1637,569 @@ class MutationClient {
1803
1637
  getMutationRunnersByKey(key) {
1804
1638
  return this.mutationRunnersByKey$.getValue().get(key);
1805
1639
  }
1806
- useIsMutating(filters = {}) {
1807
- const predicate = createPredicateForFilters(filters);
1808
- const reduceByNumber = (entries) => entries.reduce((acc, mutation) => {
1809
- return predicate(mutation) && mutation.stateSubject.getValue().status === "pending" ? 1 + acc : acc;
1810
- }, 0);
1811
- const lastValue = reduceByNumber(this.mutationsSubject.getValue());
1812
- const value$ = this.mutationsSubject.pipe(
1813
- rxjs.switchMap((mutations) => {
1814
- const mutationsOnStateUpdate = mutations.map(
1815
- (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
+ }
1816
1736
  );
1817
- return mutationsOnStateUpdate.length === 0 ? rxjs.of([]) : rxjs.combineLatest(mutationsOnStateUpdate);
1818
- }),
1819
- rxjs.map(reduceByNumber),
1820
- rxjs.distinctUntilChanged()
1737
+ }
1821
1738
  );
1822
- return { value$, lastValue };
1823
1739
  }
1824
- 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({
1825
2079
  filters,
1826
2080
  select
1827
2081
  } = {}) {
1828
2082
  const predicate = createPredicateForFilters(filters);
1829
- const finalSelect = select ?? ((mutation) => mutation.stateSubject.getValue());
1830
- const lastValue = this.mutationsSubject.getValue().reduce((acc, mutation) => {
2083
+ const finalSelect = select ?? ((mutation) => mutation.state);
2084
+ const lastValue = this.getAll().reduce((acc, mutation) => {
1831
2085
  const result = [...acc, mutation];
1832
2086
  return result;
1833
2087
  }, []).filter(predicate).map((mutation) => finalSelect(mutation));
1834
- const value$ = this.mutationsSubject.pipe(
1835
- rxjs.switchMap((mutations) => {
1836
- const mutationsOnStateUpdate = mutations.map(
1837
- (mutation) => mutation.stateSubject.pipe(
1838
- rxjs.filter(() => predicate(mutation)),
1839
- rxjs.map(() => finalSelect(mutation))
1840
- )
1841
- );
1842
- 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);
1843
2093
  }),
1844
2094
  rxjs.distinctUntilChanged(shallowEqual)
1845
2095
  );
1846
2096
  return { value$, lastValue };
1847
2097
  }
1848
- observe({ key }) {
1849
- var _a;
1850
- const currentResultValue = (_a = this.mutationResults$.getValue().get(key)) == null ? void 0 : _a.getValue();
1851
- const mapResultToObservedResult = (value) => ({
1852
- ...value,
1853
- isIdle: value.status === "idle",
1854
- isPaused: false,
1855
- isError: value.error !== void 0,
1856
- isPending: false,
1857
- isSuccess: value.status === "success"
2098
+ cancelBy(filters) {
2099
+ this.findAll(filters).forEach((mutation) => {
2100
+ mutation.cancel();
1858
2101
  });
1859
- const lastValue = currentResultValue ? mapResultToObservedResult(currentResultValue) : mapResultToObservedResult({
1860
- data: void 0,
1861
- error: void 0,
1862
- status: "idle"
2102
+ }
2103
+ clear() {
2104
+ this.getAll().forEach((mutation) => {
2105
+ this.remove(mutation);
1863
2106
  });
1864
- const result$ = this.mutationResults$.pipe(
1865
- rxjs.switchMap((resultMap) => {
1866
- const subject = resultMap.get(key);
1867
- return subject ?? rxjs.EMPTY;
1868
- })
1869
- ).pipe(
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),
1870
2158
  rxjs.filter(isDefined),
1871
- rxjs.map((value) => ({
1872
- ...value,
1873
- isIdle: value.status === "idle",
1874
- isPaused: false,
1875
- isError: value.error !== void 0,
1876
- isPending: false,
1877
- isSuccess: value.status === "success"
1878
- }))
2159
+ rxjs.map(this.getDerivedState),
2160
+ rxjs.distinctUntilChanged(shallowEqual)
1879
2161
  );
1880
2162
  return { result$, lastValue };
1881
2163
  }
1882
- mutate(params) {
1883
- this.mutate$.next(params);
2164
+ observe(mutation) {
2165
+ return mutation.state$;
1884
2166
  }
1885
- /**
1886
- * This will cancel any current mutation runnings.
1887
- * No discrimination process
1888
- */
1889
- cancel(params) {
1890
- this.cancel$.next(params);
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
+ });
1891
2201
  }
1892
2202
  destroy() {
1893
- this.cancel$.complete();
1894
- this.mutate$.complete();
1895
- this.mutationResults$.complete();
1896
- this.mutationRunnersByKey$.complete();
1897
- this.isMutatingSubject.complete();
1898
- this.mutationsSubject.complete();
1899
2203
  }
1900
2204
  }
1901
2205
  const createClient = () => {
@@ -1903,7 +2207,6 @@ const createClient = () => {
1903
2207
  const invalidationClient = createInvalidationClient({ queryStore });
1904
2208
  const cacheClient = createCacheClient({ queryStore });
1905
2209
  const refetchClient = createRefetchClient();
1906
- const mutationClient = new MutationClient();
1907
2210
  let hasCalledStart = false;
1908
2211
  const query = ({
1909
2212
  key,
@@ -2014,6 +2317,8 @@ const createClient = () => {
2014
2317
  })
2015
2318
  )
2016
2319
  );
2320
+ const destroy = () => {
2321
+ };
2017
2322
  const start = () => {
2018
2323
  hasCalledStart = true;
2019
2324
  const queryListenerSub = queryListener$.subscribe();
@@ -2025,14 +2330,10 @@ const createClient = () => {
2025
2330
  queryListenerSub.unsubscribe();
2026
2331
  };
2027
2332
  };
2028
- const destroy = () => {
2029
- mutationClient.destroy();
2030
- };
2031
2333
  return {
2032
2334
  start,
2033
2335
  query,
2034
2336
  queryStore,
2035
- mutationClient,
2036
2337
  ...invalidationClient,
2037
2338
  ...cacheClient,
2038
2339
  ...refetchClient,
@@ -2040,11 +2341,35 @@ const createClient = () => {
2040
2341
  };
2041
2342
  };
2042
2343
  class QueryClient {
2043
- constructor() {
2344
+ constructor({ mutationCache } = {
2345
+ mutationCache: new MutationCache()
2346
+ }) {
2044
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);
2045
2354
  this.client = createClient();
2046
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
+ }
2047
2371
  }
2372
+ exports.MutationCache = MutationCache;
2048
2373
  exports.QueryClient = QueryClient;
2049
2374
  exports.QueryClientProvider = QueryClientProvider;
2050
2375
  exports.SIGNAL_RESET = SIGNAL_RESET;