@hyper-fetch/core 9.6.2 → 9.8.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 (55) hide show
  1. package/__tests__/features/adapter/adapter.typescript.spec.ts +34 -0
  2. package/__tests__/features/adapter/adapter.utils.spec.ts +10 -0
  3. package/__tests__/features/cache/cache.utils.spec.ts +18 -0
  4. package/__tests__/features/optimistic/optimistic.concurrency.spec.ts +278 -0
  5. package/__tests__/features/optimistic/optimistic.helpers.spec.ts +307 -0
  6. package/__tests__/features/optimistic/optimistic.matrix.spec.ts +315 -0
  7. package/__tests__/features/optimistic/optimistic.races.spec.ts +270 -0
  8. package/__tests__/features/optimistic/optimistic.random.spec.ts +191 -0
  9. package/__tests__/features/optimistic/optimistic.rollback.spec.ts +1001 -0
  10. package/__tests__/features/optimistic/optimistic.typescript.spec.ts +196 -0
  11. package/__tests__/features/request/request.cloning.spec.ts +28 -0
  12. package/__tests__/features/request/request.optimistic.spec.ts +12 -1
  13. package/__tests__/features/request/request.sending.spec.ts +13 -10
  14. package/__tests__/type-stress/custom-adapter/custom-adapter.ts +20 -0
  15. package/__tests__/type-stress/custom-adapter/tsconfig.json +4 -0
  16. package/__tests__/utils/optimistic.utils.ts +124 -0
  17. package/dist/cache/cache.d.ts.map +1 -1
  18. package/dist/client/client.d.ts.map +1 -1
  19. package/dist/dispatcher/dispatcher.d.ts.map +1 -1
  20. package/dist/index.d.ts +1 -0
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.mjs +578 -70
  23. package/dist/index.mjs.map +1 -1
  24. package/dist/optimistic/index.d.ts +5 -0
  25. package/dist/optimistic/index.d.ts.map +1 -0
  26. package/dist/optimistic/optimistic.d.ts +67 -0
  27. package/dist/optimistic/optimistic.d.ts.map +1 -0
  28. package/dist/optimistic/optimistic.settlement.d.ts +60 -0
  29. package/dist/optimistic/optimistic.settlement.d.ts.map +1 -0
  30. package/dist/optimistic/optimistic.types.d.ts +109 -0
  31. package/dist/optimistic/optimistic.types.d.ts.map +1 -0
  32. package/dist/optimistic/optimistic.utils.d.ts +29 -0
  33. package/dist/optimistic/optimistic.utils.d.ts.map +1 -0
  34. package/dist/request/request.d.ts +13 -5
  35. package/dist/request/request.d.ts.map +1 -1
  36. package/dist/request/request.types.d.ts +40 -1
  37. package/dist/request/request.types.d.ts.map +1 -1
  38. package/dist/request/request.utils.d.ts.map +1 -1
  39. package/dist/types/adapter.types.d.ts +12 -1
  40. package/dist/types/adapter.types.d.ts.map +1 -1
  41. package/package.json +2 -2
  42. package/src/cache/cache.ts +2 -1
  43. package/src/client/client.ts +2 -0
  44. package/src/dispatcher/dispatcher.ts +13 -0
  45. package/src/index.ts +1 -0
  46. package/src/optimistic/index.ts +4 -0
  47. package/src/optimistic/optimistic.settlement.ts +406 -0
  48. package/src/optimistic/optimistic.ts +162 -0
  49. package/src/optimistic/optimistic.types.ts +175 -0
  50. package/src/optimistic/optimistic.utils.ts +112 -0
  51. package/src/request/request.ts +19 -6
  52. package/src/request/request.types.ts +41 -1
  53. package/src/request/request.utils.ts +30 -54
  54. package/src/types/adapter.types.ts +42 -25
  55. package/tsconfig.json +2 -0
package/dist/index.mjs CHANGED
@@ -989,6 +989,216 @@ var HttpMethods = /* @__PURE__ */ function(HttpMethods) {
989
989
  /** Methods that are safe reads: routed to the fetch dispatcher and deduplicated by default. */
990
990
  var SAFE_HTTP_METHODS = [HttpMethods.GET, HttpMethods.QUERY];
991
991
  //#endregion
992
+ //#region src/optimistic/optimistic.utils.ts
993
+ var isComparableId = (value) => typeof value === "string" || typeof value === "number";
994
+ /**
995
+ * Tells if the item is selected by the match. Plain values are compared with the `key` field of the item, numbers and
996
+ * strings match each other the same way route params do (`"1"` matches `1`).
997
+ */
998
+ var isOptimisticMatch = (item, match, key = "id") => {
999
+ if (typeof match === "function") return !!match(item);
1000
+ if (item === null || typeof item !== "object") return false;
1001
+ const value = item[key];
1002
+ if (Object.is(value, match)) return true;
1003
+ return isComparableId(value) && isComparableId(match) && String(value) === String(match);
1004
+ };
1005
+ var assertList = (list) => {
1006
+ if (!Array.isArray(list)) throw new TypeError("Optimistic list helpers need an array, use .list(field) for an array inside an object");
1007
+ return list;
1008
+ };
1009
+ var assertEntry = (data) => {
1010
+ if (data === null || typeof data !== "object" || Array.isArray(data)) throw new TypeError("Optimistic increment(field, by) needs an object, use increment(match, field, by) on a list");
1011
+ return data;
1012
+ };
1013
+ var addToField = (item, field, by) => {
1014
+ const value = item[field];
1015
+ return {
1016
+ ...item,
1017
+ [field]: (typeof value === "number" ? value : 0) + by
1018
+ };
1019
+ };
1020
+ /**
1021
+ * Maps the matching items. The list keeps its reference when nothing matched, so unchanged data produces no write.
1022
+ */
1023
+ var mapMatching = (list, { match, key }, map) => {
1024
+ const items = assertList(list);
1025
+ let changed = false;
1026
+ const next = items.map((item) => {
1027
+ if (!isOptimisticMatch(item, match, key)) return item;
1028
+ changed = true;
1029
+ return map(item);
1030
+ });
1031
+ return changed ? next : items;
1032
+ };
1033
+ var patchItems = (list, selector, fields) => {
1034
+ return mapMatching(list, selector, (item) => ({
1035
+ ...item,
1036
+ ...fields
1037
+ }));
1038
+ };
1039
+ var insertItem = (list, item, options) => {
1040
+ const items = assertList(list);
1041
+ const at = options?.at ?? "end";
1042
+ if (at === "start") return [item, ...items];
1043
+ if (at === "end") return [...items, item];
1044
+ const next = [...items];
1045
+ next.splice(at, 0, item);
1046
+ return next;
1047
+ };
1048
+ var removeItems = (list, { match, key }) => {
1049
+ const items = assertList(list);
1050
+ const next = items.filter((item) => !isOptimisticMatch(item, match, key));
1051
+ return next.length === items.length ? items : next;
1052
+ };
1053
+ var incrementItems = (list, selector, { field, by }) => {
1054
+ return mapMatching(list, selector, (item) => addToField(item, field, by));
1055
+ };
1056
+ var incrementField = (data, field, by) => {
1057
+ return addToField(assertEntry(data), field, by);
1058
+ };
1059
+ /**
1060
+ * Runs a list helper on the array held in `field`. A missing list counts as empty, the object keeps its reference when
1061
+ * the list did not change.
1062
+ */
1063
+ var updateListField = (data, field, update) => {
1064
+ const entry = assertEntry(data);
1065
+ const list = entry[field] ?? [];
1066
+ const next = update(assertList(list));
1067
+ return next === list ? entry : {
1068
+ ...entry,
1069
+ [field]: next
1070
+ };
1071
+ };
1072
+ //#endregion
1073
+ //#region src/optimistic/optimistic.ts
1074
+ /**
1075
+ * One change of one target, built with `optimistic(target)`. Core applies it before the mutation is sent, and runs its
1076
+ * `.commit()` on success or its `.rollback()` when the mutation fails, is aborted or removed from the queue.
1077
+ * Operations are immutable - `.rollback()` and `.commit()` return a new operation, so one can be reused.
1078
+ */
1079
+ var OptimisticOperation = class OptimisticOperation {
1080
+ /** @internal */
1081
+ target;
1082
+ /** @internal */
1083
+ allVariants;
1084
+ /** @internal */
1085
+ update;
1086
+ /** @internal */
1087
+ onRollback = void 0;
1088
+ /** @internal */
1089
+ onCommit = void 0;
1090
+ constructor(options) {
1091
+ this.target = options.target;
1092
+ this.allVariants = options.allVariants;
1093
+ this.update = options.update;
1094
+ this.onRollback = options.onRollback;
1095
+ this.onCommit = options.onCommit;
1096
+ }
1097
+ /**
1098
+ * Undo of this change, written by hand and run by core when the mutation fails for good, is aborted or removed from
1099
+ * the queue. Rollbacks of one mutation run in reverse order of the changes. It receives
1100
+ * `{ data, previous, reason, response, request }` and returns the new data; returning nothing leaves the data as it
1101
+ * is. Build the result from `data` and use `previous` only to look old values up. Must be synchronous.
1102
+ * Without it nothing is undone locally and the target is refetched.
1103
+ */
1104
+ rollback(callback) {
1105
+ return new OptimisticOperation({
1106
+ target: this.target,
1107
+ allVariants: this.allVariants,
1108
+ update: this.update,
1109
+ onRollback: callback,
1110
+ onCommit: this.onCommit
1111
+ });
1112
+ }
1113
+ /**
1114
+ * Runs when the mutation succeeds, before the target is refreshed. It receives `{ data, response, request }` and
1115
+ * returns the new data, for example to swap a temporary item for the one from the response. Returning nothing leaves
1116
+ * the data as it is. Must be synchronous.
1117
+ */
1118
+ commit(callback) {
1119
+ return new OptimisticOperation({
1120
+ target: this.target,
1121
+ allVariants: this.allVariants,
1122
+ update: this.update,
1123
+ onRollback: this.onRollback,
1124
+ onCommit: callback
1125
+ });
1126
+ }
1127
+ };
1128
+ var createTarget = (target, allVariants) => {
1129
+ const operation = (update) => {
1130
+ return new OptimisticOperation({
1131
+ target,
1132
+ allVariants,
1133
+ update
1134
+ });
1135
+ };
1136
+ const createListHelpers = (onList) => ({
1137
+ patch: (match, fields, options) => {
1138
+ return operation(onList((list) => patchItems(list, {
1139
+ match,
1140
+ key: options?.key
1141
+ }, fields)));
1142
+ },
1143
+ insert: (item, options) => {
1144
+ return operation(onList((list) => insertItem(list, item, options)));
1145
+ },
1146
+ remove: (match, options) => {
1147
+ return operation(onList((list) => removeItems(list, {
1148
+ match,
1149
+ key: options?.key
1150
+ })));
1151
+ },
1152
+ increment: (match, field, by, options) => {
1153
+ return operation(onList((list) => incrementItems(list, {
1154
+ match,
1155
+ key: options?.key
1156
+ }, {
1157
+ field,
1158
+ by
1159
+ })));
1160
+ }
1161
+ });
1162
+ const listHelpers = createListHelpers((update) => (data) => update(data));
1163
+ return {
1164
+ ...listHelpers,
1165
+ set: (updater) => operation(updater),
1166
+ increment: (...args) => {
1167
+ if (args.length >= 3) {
1168
+ const [match, field, by, options] = args;
1169
+ return listHelpers.increment(match, field, by, options);
1170
+ }
1171
+ const [field, by] = args;
1172
+ return operation((data) => incrementField(data, field, by));
1173
+ },
1174
+ list: (field) => {
1175
+ return createListHelpers((update) => (data) => updateListField(data, field, update));
1176
+ }
1177
+ };
1178
+ };
1179
+ var optimisticFactory = (target) => createTarget(target, false);
1180
+ optimisticFactory.all = (target) => createTarget(target, true);
1181
+ /**
1182
+ * Describes an optimistic change of a cached request. Return the operations from `setOptimistic` or pass them with the
1183
+ * `optimistic` send option, core applies them, runs `.commit()` / `.rollback()` when the mutation settles and refreshes
1184
+ * the targets once the last pending mutation on them is done.
1185
+ *
1186
+ * - `optimistic(getTodos)` - the entry of this request (its params and query params)
1187
+ * - `optimistic.all(getTodos)` - every cached variant of it, whatever the query params (filters, infinite pages)
1188
+ *
1189
+ * Helpers: `set(updater)`, `patch(match, fields)`, `insert(item, { at })`, `remove(match)`,
1190
+ * `increment(field, by)` / `increment(match, field, by)` and `.list("field")` for an array inside an object.
1191
+ *
1192
+ * @example
1193
+ * optimistic(getTodos)
1194
+ * .patch(params.todoId, payload)
1195
+ * .rollback(({ data, previous }) => {
1196
+ * const before = previous.find((todo) => todo.id === params.todoId);
1197
+ * return data.map((todo) => (todo.id === params.todoId && before ? before : todo));
1198
+ * });
1199
+ */
1200
+ var optimistic = optimisticFactory;
1201
+ //#endregion
992
1202
  //#region src/utils/error.utils.ts
993
1203
  /**
994
1204
  * Callbacks, listeners, plugins and optimistic handlers are the code of the user running inside of the request
@@ -1354,6 +1564,305 @@ var EventEmitter = class extends import_events.default {
1354
1564
  removeListener = this.off;
1355
1565
  };
1356
1566
  //#endregion
1567
+ //#region src/optimistic/optimistic.settlement.ts
1568
+ var clientStates = /* @__PURE__ */ new WeakMap();
1569
+ var getClientState = (client) => {
1570
+ let state = clientStates.get(client);
1571
+ if (!state) {
1572
+ state = {
1573
+ keys: /* @__PURE__ */ new Map(),
1574
+ staleRequests: /* @__PURE__ */ new Map()
1575
+ };
1576
+ clientStates.set(client, state);
1577
+ }
1578
+ return state;
1579
+ };
1580
+ /**
1581
+ * Failures of user code (helpers, commits, rollbacks, predicates) are logged and thrown outside of the request
1582
+ * lifecycle, like every other user code running in it - the request and the other changes still settle.
1583
+ */
1584
+ var reportFailure = (client, title, extra) => {
1585
+ client.logger.error({
1586
+ title,
1587
+ type: "system",
1588
+ extra
1589
+ });
1590
+ throwOutsideLifecycle(extra.error);
1591
+ };
1592
+ var readEntry = (client, storageKey) => {
1593
+ return client.cache.get(storageKey);
1594
+ };
1595
+ /**
1596
+ * Writes the data through the regular cache path, so listeners get one event per change. The entry keeps its
1597
+ * timestamps and staleness - an optimistic value doesn't make the entry fresh.
1598
+ */
1599
+ var writeData = (request, entry, data) => {
1600
+ const entryRequest = request.clone({
1601
+ staleTime: entry.staleTime,
1602
+ cacheTime: entry.cacheTime
1603
+ });
1604
+ request.client.cache.set(entryRequest, {
1605
+ ...entry,
1606
+ data
1607
+ });
1608
+ };
1609
+ /**
1610
+ * Cache keys targeted by the operation. `optimistic.all()` matches every entry of the same method and endpoint
1611
+ * whatever the query params; a custom cache key matches itself and the keys derived from it (infinite pages).
1612
+ */
1613
+ var resolveTargets = (client, operation) => {
1614
+ const { target } = operation;
1615
+ const targets = /* @__PURE__ */ new Map();
1616
+ if (!operation.allVariants) {
1617
+ targets.set(scopeKey(target.cacheKey, target.scope), target);
1618
+ return targets;
1619
+ }
1620
+ const prefix = target.cacheKey === getRequestKey(target) ? `${stringifyKey(target.method)}_${stringifyKey(target.endpoint)}_` : `${target.cacheKey}_`;
1621
+ client.cache.keys().forEach((storageKey) => {
1622
+ const entry = client.cache.storage.get(storageKey);
1623
+ if (!entry || entry.scope !== target.scope) return;
1624
+ if (entry.cacheKey === target.cacheKey) targets.set(storageKey, target);
1625
+ else if (entry.cacheKey.startsWith(prefix)) targets.set(storageKey, target.clone().setCacheKey(entry.cacheKey));
1626
+ });
1627
+ return targets;
1628
+ };
1629
+ /**
1630
+ * Runs `.rollback()` / `.commit()` of an operation and writes what it returned. User code can't break the settlement:
1631
+ * a throw or a promise is reported and the key gets refreshed.
1632
+ */
1633
+ var runSettleCallback = (pending, { operation, storageKey, request, previous }, outcome) => {
1634
+ const { client } = pending;
1635
+ const entry = readEntry(client, storageKey);
1636
+ const isCommit = outcome.type === "success";
1637
+ const title = isCommit ? "Optimistic commit failed" : "Optimistic rollback failed";
1638
+ const run = (data) => {
1639
+ if (outcome.type === "success") {
1640
+ const response = outcome.response;
1641
+ return operation.onCommit?.({
1642
+ data,
1643
+ response,
1644
+ request: outcome.request
1645
+ });
1646
+ }
1647
+ const { type: _type, ...args } = outcome;
1648
+ return operation.onRollback?.({
1649
+ ...args,
1650
+ data,
1651
+ previous
1652
+ });
1653
+ };
1654
+ if (!(isCommit ? operation.onCommit : operation.onRollback) || !entry) return;
1655
+ try {
1656
+ const next = run(entry.data);
1657
+ if (next instanceof Promise) {
1658
+ next.catch((error) => reportFailure(client, title, {
1659
+ error,
1660
+ storageKey
1661
+ }));
1662
+ throw new TypeError("Optimistic rollback and commit must be synchronous, the returned promise was ignored");
1663
+ }
1664
+ if (next !== void 0 && next !== entry.data) writeData(request, entry, next);
1665
+ } catch (error) {
1666
+ reportFailure(client, title, {
1667
+ error,
1668
+ storageKey,
1669
+ request: outcome.request
1670
+ });
1671
+ pending.failed.add(storageKey);
1672
+ }
1673
+ };
1674
+ /** Rollback of the hand-written object form - runs once, its failure can't affect the request */
1675
+ var runObjectRollback = (pending, args) => {
1676
+ const { client, result } = pending;
1677
+ const onFailure = (error) => {
1678
+ reportFailure(client, "Optimistic rollback failed", {
1679
+ error,
1680
+ reason: args.reason,
1681
+ request: args.request
1682
+ });
1683
+ };
1684
+ try {
1685
+ Promise.resolve(result.rollback?.(args)).catch(onFailure);
1686
+ } catch (error) {
1687
+ onFailure(error);
1688
+ }
1689
+ };
1690
+ var runObjectInvalidation = ({ client, result }, request) => {
1691
+ result.invalidate?.forEach((target) => {
1692
+ try {
1693
+ client.cache.invalidate(target);
1694
+ } catch (error) {
1695
+ reportFailure(client, "Optimistic invalidation failed", {
1696
+ error,
1697
+ target,
1698
+ request
1699
+ });
1700
+ }
1701
+ });
1702
+ };
1703
+ /**
1704
+ * `rollbackOnError` decides about final errors only - aborted and removed requests are always reverted.
1705
+ * A predicate that throws is reported and the change is reverted.
1706
+ */
1707
+ var shouldRollback = (pending, outcome) => {
1708
+ const { rollbackOnError } = pending.result;
1709
+ if (outcome.reason !== "error" || rollbackOnError === void 0 || rollbackOnError === true) return true;
1710
+ if (rollbackOnError === false) return false;
1711
+ try {
1712
+ return !!rollbackOnError({
1713
+ response: outcome.response,
1714
+ request: outcome.request
1715
+ });
1716
+ } catch (error) {
1717
+ reportFailure(pending.client, "Optimistic rollbackOnError failed", {
1718
+ error,
1719
+ request: outcome.request
1720
+ });
1721
+ return true;
1722
+ }
1723
+ };
1724
+ var getRunningRequestsOnKey = (client, storageKey) => {
1725
+ return [...client.fetchDispatcher.getAllRunningRequests(), ...client.submitDispatcher.getAllRunningRequests()].filter(({ request }) => scopeKey(request.cacheKey, request.scope) === storageKey);
1726
+ };
1727
+ var hasStaleRequests = (state, storageKey) => {
1728
+ return [...state.staleRequests.values()].includes(storageKey);
1729
+ };
1730
+ /** Refreshes the key once nothing pending or stale is left on it */
1731
+ var refreshWhenIdle = (client, state, storageKey) => {
1732
+ const keyState = state.keys.get(storageKey);
1733
+ if (!keyState || keyState.pending > 0 || hasStaleRequests(state, storageKey)) return;
1734
+ state.keys.delete(storageKey);
1735
+ if (keyState.refresh) client.cache.invalidate(keyState.request);
1736
+ };
1737
+ var release = (pending, refresh) => {
1738
+ const { client, targets, failed, guarded } = pending;
1739
+ const state = getClientState(client);
1740
+ targets.forEach((request, storageKey) => {
1741
+ const keyState = state.keys.get(storageKey);
1742
+ const shouldRefresh = refresh || failed.has(storageKey);
1743
+ if (!guarded.has(storageKey)) {
1744
+ if (keyState && shouldRefresh) keyState.refresh = true;
1745
+ else if (shouldRefresh) client.cache.invalidate(request);
1746
+ return;
1747
+ }
1748
+ if (!keyState) return;
1749
+ keyState.pending -= 1;
1750
+ keyState.refresh = keyState.refresh || shouldRefresh;
1751
+ keyState.request = request;
1752
+ getRunningRequestsOnKey(client, storageKey).forEach(({ requestId }) => {
1753
+ state.staleRequests.set(requestId, storageKey);
1754
+ });
1755
+ refreshWhenIdle(client, state, storageKey);
1756
+ });
1757
+ };
1758
+ /**
1759
+ * @internal
1760
+ * Normalizes what `setOptimistic` or the `optimistic` send option returned into the object form.
1761
+ */
1762
+ var getOptimisticResult = (value) => {
1763
+ if (Array.isArray(value)) return { updates: value };
1764
+ return value || {};
1765
+ };
1766
+ /**
1767
+ * @internal
1768
+ * Applies the operations of the mutation and registers its target keys as pending. A failing operation is reported,
1769
+ * the others still apply.
1770
+ */
1771
+ var applyOptimistic = (client, result) => {
1772
+ const pending = {
1773
+ client,
1774
+ result,
1775
+ applied: [],
1776
+ targets: /* @__PURE__ */ new Map(),
1777
+ guarded: /* @__PURE__ */ new Set(),
1778
+ failed: /* @__PURE__ */ new Set()
1779
+ };
1780
+ const state = getClientState(client);
1781
+ result.updates?.forEach((value) => {
1782
+ try {
1783
+ if (!(value instanceof OptimisticOperation)) throw new TypeError("Optimistic updates accept operations created with optimistic()");
1784
+ const operation = value;
1785
+ resolveTargets(client, operation).forEach((request, storageKey) => {
1786
+ pending.targets.set(storageKey, request);
1787
+ const entry = readEntry(client, storageKey);
1788
+ if (!entry) return;
1789
+ try {
1790
+ const next = operation.update(entry.data);
1791
+ if (next !== entry.data) writeData(request, entry, next);
1792
+ pending.applied.push({
1793
+ operation,
1794
+ storageKey,
1795
+ request,
1796
+ previous: entry.data
1797
+ });
1798
+ pending.guarded.add(storageKey);
1799
+ } catch (error) {
1800
+ reportFailure(client, "Optimistic update failed", {
1801
+ error,
1802
+ storageKey
1803
+ });
1804
+ pending.failed.add(storageKey);
1805
+ }
1806
+ });
1807
+ } catch (error) {
1808
+ reportFailure(client, "Optimistic update failed", {
1809
+ error,
1810
+ operation: value
1811
+ });
1812
+ }
1813
+ });
1814
+ pending.guarded.forEach((storageKey) => {
1815
+ const request = pending.targets.get(storageKey);
1816
+ const keyState = state.keys.get(storageKey) ?? {
1817
+ pending: 0,
1818
+ refresh: false,
1819
+ request
1820
+ };
1821
+ keyState.pending += 1;
1822
+ state.keys.set(storageKey, keyState);
1823
+ });
1824
+ return pending;
1825
+ };
1826
+ /**
1827
+ * @internal
1828
+ * Settles the mutation once. Success runs the commits and invalidations, a final error, abort or queue removal runs the
1829
+ * rollbacks in reverse order of application. The targets get refreshed after the last pending mutation on them.
1830
+ */
1831
+ var settleOptimistic = (pending, outcome) => {
1832
+ const { result, applied } = pending;
1833
+ const canRefresh = result.revalidate !== false;
1834
+ if (outcome.type === "success") {
1835
+ applied.forEach((operation) => runSettleCallback(pending, operation, outcome));
1836
+ runObjectInvalidation(pending, outcome.request);
1837
+ return release(pending, canRefresh);
1838
+ }
1839
+ const { type: _type, ...args } = outcome;
1840
+ if (!shouldRollback(pending, args)) return release(pending, false);
1841
+ for (let index = applied.length - 1; index >= 0; index -= 1) runSettleCallback(pending, applied[index], outcome);
1842
+ runObjectRollback(pending, args);
1843
+ return release(pending, canRefresh);
1844
+ };
1845
+ /**
1846
+ * @internal
1847
+ * Stale response guard, called where the dispatcher writes a response to the cache. A response is discarded when a
1848
+ * mutation changed its key and is pending, or when the fetch started before the latest such mutation settled - the
1849
+ * refresh after the mutation supplies current data. Keys that had no data when the change was applied are not
1850
+ * guarded, so a first load is never held back. Manual cache writes don't go through this check.
1851
+ */
1852
+ var isStaleOptimisticResponse = (client, request, requestId) => {
1853
+ const state = clientStates.get(client);
1854
+ if (!state) return false;
1855
+ const storageKey = scopeKey(request.cacheKey, request.scope);
1856
+ const isMarked = state.staleRequests.delete(requestId);
1857
+ const isPending = (state.keys.get(storageKey)?.pending ?? 0) > 0;
1858
+ if (isMarked) refreshWhenIdle(client, state, storageKey);
1859
+ return isMarked || isPending;
1860
+ };
1861
+ /** @internal Drops the pending state of the client, its mutations will never settle after clearing it */
1862
+ var resetOptimisticState = (client) => {
1863
+ clientStates.delete(client);
1864
+ };
1865
+ //#endregion
1357
1866
  //#region src/request/request.utils.ts
1358
1867
  var scopeKey = (key, scope) => {
1359
1868
  return scope ? `${scope}__${key}` : key;
@@ -1461,67 +1970,36 @@ var mapResponseForSend = async (request, response) => {
1461
1970
  if (mapping instanceof Promise) return await mapping;
1462
1971
  return mapping || response;
1463
1972
  };
1464
- /**
1465
- * Rollback is user code running in the middle of the response handling, its failure can't affect the request
1466
- */
1467
- var rollbackOptimistic = (optimistic, args) => {
1468
- const logFailure = (error) => {
1469
- args.request.client.logger.error({
1470
- title: "Optimistic rollback failed",
1471
- type: "system",
1472
- extra: {
1473
- error,
1474
- reason: args.reason,
1475
- request: args.request
1476
- }
1477
- });
1478
- throwOutsideLifecycle(error);
1479
- };
1480
- try {
1481
- Promise.resolve(optimistic.rollback?.(args)).catch(logFailure);
1482
- } catch (error) {
1483
- logFailure(error);
1484
- }
1485
- };
1486
- var invalidateOptimistic = (optimistic, request) => {
1487
- optimistic.invalidate?.forEach((target) => {
1488
- try {
1489
- request.client.cache.invalidate(target);
1490
- } catch (error) {
1491
- request.client.logger.error({
1492
- title: "Optimistic invalidation failed",
1493
- type: "system",
1494
- extra: {
1495
- error,
1496
- target,
1497
- request
1498
- }
1499
- });
1500
- throwOutsideLifecycle(error);
1501
- }
1502
- });
1503
- };
1504
1973
  var sendRequest = async (request, options) => {
1505
1974
  const { client } = request;
1506
1975
  const { requestManager } = client;
1507
1976
  const [dispatcher] = getRequestDispatcher(request, options?.dispatcherType);
1508
1977
  let mutationContext;
1509
- if (request.optimistic) try {
1510
- mutationContext = await request.optimistic({
1511
- request,
1512
- client: request.client,
1513
- payload: request.payload
1514
- });
1515
- } catch (error) {
1516
- return {
1517
- data: null,
1518
- error: /* @__PURE__ */ new Error(`Optimistic callback failed: ${error instanceof Error ? error.message : error}`),
1519
- status: null,
1520
- success: false,
1521
- extra: client.adapter.defaultExtra,
1522
- requestTimestamp: Date.now(),
1523
- responseTimestamp: Date.now()
1524
- };
1978
+ let pendingOptimistic;
1979
+ const optimisticSource = options?.optimistic ?? request.optimistic;
1980
+ if (optimisticSource) {
1981
+ try {
1982
+ const result = Array.isArray(optimisticSource) ? optimisticSource : optimisticSource({
1983
+ request,
1984
+ client: request.client,
1985
+ payload: request.payload,
1986
+ params: request.params,
1987
+ queryParams: request.queryParams,
1988
+ optimistic
1989
+ });
1990
+ mutationContext = getOptimisticResult(result instanceof Promise ? await result : result);
1991
+ } catch (error) {
1992
+ return {
1993
+ data: null,
1994
+ error: /* @__PURE__ */ new Error(`Optimistic callback failed: ${error instanceof Error ? error.message : error}`),
1995
+ status: null,
1996
+ success: false,
1997
+ extra: client.adapter.defaultExtra,
1998
+ requestTimestamp: Date.now(),
1999
+ responseTimestamp: Date.now()
2000
+ };
2001
+ }
2002
+ pendingOptimistic = applyOptimistic(client, mutationContext);
1525
2003
  }
1526
2004
  return new Promise((resolve) => {
1527
2005
  let isResolved = false;
@@ -1540,19 +2018,25 @@ var sendRequest = async (request, options) => {
1540
2018
  if (!mappings.has(values)) mappings.set(values, runResponseMapper(request, values.response));
1541
2019
  return mappings.get(values);
1542
2020
  };
1543
- const unmountSettlement = mutationContext ? requestManager.events.onResponseById(requestId, (values) => {
1544
- const optimistic = mutationContext;
2021
+ const unmountSettlement = pendingOptimistic ? requestManager.events.onResponseById(requestId, (values) => {
2022
+ const pending = pendingOptimistic;
1545
2023
  const willBeResent = getWillBeResent(values);
1546
2024
  const settle = (response) => {
1547
2025
  if (isSettled || !response.success && willBeResent) return;
1548
2026
  isSettled = true;
1549
- if (values.details.isCanceled) rollbackOptimistic(optimistic, {
2027
+ if (values.details.isCanceled) settleOptimistic(pending, {
2028
+ type: "rollback",
1550
2029
  reason: "abort",
1551
2030
  response,
1552
2031
  request
1553
2032
  });
1554
- else if (response.success) invalidateOptimistic(optimistic, request);
1555
- else rollbackOptimistic(optimistic, {
2033
+ else if (response.success) settleOptimistic(pending, {
2034
+ type: "success",
2035
+ response,
2036
+ request
2037
+ });
2038
+ else settleOptimistic(pending, {
2039
+ type: "rollback",
1556
2040
  reason: "error",
1557
2041
  response,
1558
2042
  request
@@ -1633,9 +2117,10 @@ var sendRequest = async (request, options) => {
1633
2117
  if (!isResolved) {
1634
2118
  isResolved = true;
1635
2119
  isDelivered = true;
1636
- if (mutationContext && !isSettled) {
2120
+ if (pendingOptimistic && !isSettled) {
1637
2121
  isSettled = true;
1638
- rollbackOptimistic(mutationContext, {
2122
+ settleOptimistic(pendingOptimistic, {
2123
+ type: "rollback",
1639
2124
  reason: "removed",
1640
2125
  request
1641
2126
  });
@@ -1844,10 +2329,18 @@ var Request = class Request {
1844
2329
  };
1845
2330
  /**
1846
2331
  * Configure optimistic update behavior for this request.
1847
- * The callback runs before the request is sent and receives the request, client, and payload.
1848
- * Return `context` (available in lifecycle callbacks), `rollback` (called automatically once on
1849
- * failure, abort or queue removal), and `invalidate` (requests invalidated on success).
1850
- * Both run for every way of sending the request, not only inside of framework hooks.
2332
+ * The callback runs before the request is sent and receives `{ request, client, payload, params, queryParams,
2333
+ * optimistic }`. A synchronous callback changes the cache within the `send()` call.
2334
+ *
2335
+ * Return an array of changes built with `optimistic()` - core applies them, runs their `.commit()` on success or
2336
+ * `.rollback()` on final failure, abort or queue removal, and refreshes the targets after the last pending mutation
2337
+ * on them. Or return an object with `updates`, `context` (available in lifecycle callbacks as `mutationContext`),
2338
+ * `rollback` (called once on failure, abort or queue removal), `invalidate` (requests invalidated on success),
2339
+ * `rollbackOnError` and `revalidate`.
2340
+ * Everything runs for every way of sending the request, not only inside of framework hooks.
2341
+ *
2342
+ * @example
2343
+ * toggleTodo.setOptimistic(({ params, payload }) => [optimistic(getTodos).patch(params.todoId, payload)]);
1851
2344
  */
1852
2345
  setOptimistic = (callback) => {
1853
2346
  const cloned = this.clone();
@@ -2127,7 +2620,7 @@ var Request = class Request {
2127
2620
  * ```
2128
2621
  */
2129
2622
  send = async (options) => {
2130
- const { dispatcherType: _dispatcherType, cachePolicy = "network-only", ...configuration } = options || {};
2623
+ const { dispatcherType: _dispatcherType, cachePolicy = "network-only", optimistic: _optimistic, ...configuration } = options || {};
2131
2624
  const request = this.clone(configuration);
2132
2625
  const sendRequestOptions = options === void 0 ? void 0 : {
2133
2626
  ...options,
@@ -3308,7 +3801,12 @@ var Dispatcher = class {
3308
3801
  isOffline
3309
3802
  }));
3310
3803
  const storageKey = scopeKey(request.cacheKey, scope);
3311
- if ((this.cachedOrder.get(storageKey) ?? 0) > sentOrder) this.logger.debug({
3804
+ const isOutdated = (this.cachedOrder.get(storageKey) ?? 0) > sentOrder;
3805
+ let isStaleOptimistic = false;
3806
+ notify(() => {
3807
+ isStaleOptimistic = isStaleOptimisticResponse(this.client, request, requestId);
3808
+ });
3809
+ if (isOutdated) this.logger.debug({
3312
3810
  title: "Response of a request sent before the cached one, skipping the cache",
3313
3811
  type: "system",
3314
3812
  extra: {
@@ -3317,6 +3815,15 @@ var Dispatcher = class {
3317
3815
  response
3318
3816
  }
3319
3817
  });
3818
+ else if (isStaleOptimistic) this.logger.debug({
3819
+ title: "Response started before a pending optimistic change settled, skipping the cache",
3820
+ type: "system",
3821
+ extra: {
3822
+ requestId,
3823
+ request,
3824
+ response
3825
+ }
3826
+ });
3320
3827
  else {
3321
3828
  if (response.success) this.cachedOrder.set(storageKey, sentOrder);
3322
3829
  notify(() => cache.set(request, {
@@ -4669,6 +5176,7 @@ var Client = class {
4669
5176
  });
4670
5177
  this.requestManager.abortAll();
4671
5178
  this.requestManager.abortControllers.clear();
5179
+ resetOptimisticState(this);
4672
5180
  this.fetchDispatcher.clear();
4673
5181
  this.submitDispatcher.clear();
4674
5182
  this.cache.clear();
@@ -5166,6 +5674,6 @@ var fetchInfinite = async (request, options) => {
5166
5674
  return result;
5167
5675
  };
5168
5676
  //#endregion
5169
- export { AbortError, Adapter, AppEvents, AppManager, Cache, Client, DeletedError, Dispatcher, DispatcherMode, EventEmitter, HttpAdapter, HttpMethods, LoggerManager, Plugin, Request, RequestManager, RequestProcessingError, SAFE_HTTP_METHODS, Time, TimeoutError, UnexpectedError, appManagerInitialOptions, canRetryRequest, createClient, createConfiguration, createRequestHooks, createSdk, defaultMapper, defaultTimeout, fetchInfinite, getAbortByAbortKey, getAbortByIdKey, getAbortKey, getAdapter, getAdapterBindings, getAdapterHeaders, getAdapterOnError, getAdapterPayload, getAppManagerEvents, getCacheByKey, getCacheData, getCacheEvents, getCacheKey, getCachedPages, getDeleteByKey, getDeleteKey, getDispatcherChangeByKey, getDispatcherChangeKey, getDispatcherDrainedByKey, getDispatcherDrainedKey, getDispatcherEvents, getDispatcherRunningByKey, getDispatcherRunningKey, getDispatcherStatusByKey, getDispatcherStatusKey, getDownloadProgressByIdKey, getDownloadProgressByQueryKey, getDownloadProgressKey, getErrorMessage, getHasNextPage, getHasPreviousPage, getInitialPageParam, getInvalidateByKey, getInvalidateKey, getIsEqualTimestamp, getLoadingByCacheKey, getLoadingByIdKey, getLoadingByQueryKey, getLoadingKey, getNextPageParam, getPageItems, getPageRequest, getPageTotal, getPaginationMode, getPreviousPageParam, getProgressData, getProgressValue, getRemoveByIdKey, getRemoveByQueryKey, getRemoveKey, getRequestDeduplicatedByCacheKey, getRequestDeduplicatedByIdKey, getRequestDeduplicatedByQueryKey, getRequestDeduplicatedKey, getRequestDispatcher, getRequestEta, getRequestKey, getRequestManagerEvents, getRequestStarByQueryKey, getRequestStartByIdKey, getRequestStartKey, getRequestType, getResponseByCacheKey, getResponseByIdKey, getResponseHeaders, getResponseKey, getResponseStartByIdKey, getResponseStartByQueryKey, getResponseStartKey, getSimpleKey, getTime, getUniqueRequestId, getUploadProgressByIdKey, getUploadProgressByQueryKey, getUploadProgressKey, handleResponse, hasDocument, hasWindow, interceptRequest, interceptResponse, isNavigatorOnline, isPlainObject, logLevelOrder, logger, loggerColors, loggerStyles, mapResponseForSend, mocker, onDocumentEvent, onWindowEvent, parseErrorResponse, parseResponse, replaceEqualDeep, resolveClientMode, runResponseMapper, runUserCode, scopeKey, sendRequest, stringifyDefaultOptions, stringifyKey, stringifyQueryParams, stringifyValue, throwOutsideLifecycle, xhrExtra };
5677
+ export { AbortError, Adapter, AppEvents, AppManager, Cache, Client, DeletedError, Dispatcher, DispatcherMode, EventEmitter, HttpAdapter, HttpMethods, LoggerManager, OptimisticOperation, Plugin, Request, RequestManager, RequestProcessingError, SAFE_HTTP_METHODS, Time, TimeoutError, UnexpectedError, appManagerInitialOptions, applyOptimistic, canRetryRequest, createClient, createConfiguration, createRequestHooks, createSdk, defaultMapper, defaultTimeout, fetchInfinite, getAbortByAbortKey, getAbortByIdKey, getAbortKey, getAdapter, getAdapterBindings, getAdapterHeaders, getAdapterOnError, getAdapterPayload, getAppManagerEvents, getCacheByKey, getCacheData, getCacheEvents, getCacheKey, getCachedPages, getDeleteByKey, getDeleteKey, getDispatcherChangeByKey, getDispatcherChangeKey, getDispatcherDrainedByKey, getDispatcherDrainedKey, getDispatcherEvents, getDispatcherRunningByKey, getDispatcherRunningKey, getDispatcherStatusByKey, getDispatcherStatusKey, getDownloadProgressByIdKey, getDownloadProgressByQueryKey, getDownloadProgressKey, getErrorMessage, getHasNextPage, getHasPreviousPage, getInitialPageParam, getInvalidateByKey, getInvalidateKey, getIsEqualTimestamp, getLoadingByCacheKey, getLoadingByIdKey, getLoadingByQueryKey, getLoadingKey, getNextPageParam, getOptimisticResult, getPageItems, getPageRequest, getPageTotal, getPaginationMode, getPreviousPageParam, getProgressData, getProgressValue, getRemoveByIdKey, getRemoveByQueryKey, getRemoveKey, getRequestDeduplicatedByCacheKey, getRequestDeduplicatedByIdKey, getRequestDeduplicatedByQueryKey, getRequestDeduplicatedKey, getRequestDispatcher, getRequestEta, getRequestKey, getRequestManagerEvents, getRequestStarByQueryKey, getRequestStartByIdKey, getRequestStartKey, getRequestType, getResponseByCacheKey, getResponseByIdKey, getResponseHeaders, getResponseKey, getResponseStartByIdKey, getResponseStartByQueryKey, getResponseStartKey, getSimpleKey, getTime, getUniqueRequestId, getUploadProgressByIdKey, getUploadProgressByQueryKey, getUploadProgressKey, handleResponse, hasDocument, hasWindow, incrementField, incrementItems, insertItem, interceptRequest, interceptResponse, isNavigatorOnline, isOptimisticMatch, isPlainObject, isStaleOptimisticResponse, logLevelOrder, logger, loggerColors, loggerStyles, mapResponseForSend, mocker, onDocumentEvent, onWindowEvent, optimistic, parseErrorResponse, parseResponse, patchItems, removeItems, replaceEqualDeep, resetOptimisticState, resolveClientMode, runResponseMapper, runUserCode, scopeKey, sendRequest, settleOptimistic, stringifyDefaultOptions, stringifyKey, stringifyQueryParams, stringifyValue, throwOutsideLifecycle, updateListField, xhrExtra };
5170
5678
 
5171
5679
  //# sourceMappingURL=index.mjs.map