@hyper-fetch/core 9.6.1 → 9.7.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 (134) hide show
  1. package/__tests__/features/adapter/adapter.bindings.progress.spec.ts +120 -0
  2. package/__tests__/features/adapter/adapter.bindings.spec.ts +4 -6
  3. package/__tests__/features/adapter/adapter.defaults.spec.ts +87 -0
  4. package/__tests__/features/adapter/adapter.mapping.spec.ts +257 -0
  5. package/__tests__/features/cache/cache.lazy-storage.clear.spec.ts +145 -0
  6. package/__tests__/features/cache/cache.lazy-storage.resilience.spec.ts +667 -0
  7. package/__tests__/features/cache/cache.scoped-events.spec.ts +183 -0
  8. package/__tests__/features/cache/cache.semantics.spec.ts +785 -0
  9. package/__tests__/features/cache/cache.structural-sharing.spec.ts +565 -0
  10. package/__tests__/features/cache/cache.timing.spec.ts +448 -0
  11. package/__tests__/features/client/client.clear.spec.ts +313 -0
  12. package/__tests__/features/client/client.configuration.spec.ts +416 -0
  13. package/__tests__/features/client/client.hydration.round-trip.spec.ts +324 -0
  14. package/__tests__/features/client/client.interceptor.spec.ts +54 -45
  15. package/__tests__/features/client/client.interceptors.pipeline.spec.ts +599 -0
  16. package/__tests__/features/client/client.user-errors.spec.ts +220 -0
  17. package/__tests__/features/dispatcher/dispatcher.cleanup.spec.ts +534 -0
  18. package/__tests__/features/dispatcher/dispatcher.control.spec.ts +381 -0
  19. package/__tests__/features/dispatcher/dispatcher.modes.spec.ts +527 -0
  20. package/__tests__/features/dispatcher/dispatcher.offline.spec.ts +278 -0
  21. package/__tests__/features/dispatcher/dispatcher.queue.spec.ts +35 -12
  22. package/__tests__/features/dispatcher/dispatcher.reentrancy.spec.ts +309 -0
  23. package/__tests__/features/dispatcher/dispatcher.response-order.spec.ts +241 -0
  24. package/__tests__/features/dispatcher/dispatcher.retry-flow.spec.ts +554 -0
  25. package/__tests__/features/dispatcher/dispatcher.retry-removal.spec.ts +196 -0
  26. package/__tests__/features/dispatcher/dispatcher.retry.spec.ts +4 -3
  27. package/__tests__/features/http-adapter/http-adapter.e2e.spec.ts +917 -0
  28. package/__tests__/features/managers/app/app.manager.events.spec.ts +434 -0
  29. package/__tests__/features/managers/logger/logger.levels.spec.ts +199 -0
  30. package/__tests__/features/managers/request/request.manager.abort.spec.ts +449 -0
  31. package/__tests__/features/mocker/mocker.base.spec.ts +22 -3
  32. package/__tests__/features/mocker/mocker.errors.spec.ts +99 -0
  33. package/__tests__/features/mocker/mocker.outcomes.spec.ts +308 -0
  34. package/__tests__/features/optimistic/optimistic.concurrency.spec.ts +278 -0
  35. package/__tests__/features/optimistic/optimistic.helpers.spec.ts +307 -0
  36. package/__tests__/features/optimistic/optimistic.matrix.spec.ts +315 -0
  37. package/__tests__/features/optimistic/optimistic.races.spec.ts +270 -0
  38. package/__tests__/features/optimistic/optimistic.random.spec.ts +191 -0
  39. package/__tests__/features/optimistic/optimistic.rollback.spec.ts +1001 -0
  40. package/__tests__/features/optimistic/optimistic.typescript.spec.ts +196 -0
  41. package/__tests__/features/plugin/plugin.lifecycle.spec.ts +457 -0
  42. package/__tests__/features/request/request.async-mapper-removal.spec.ts +138 -0
  43. package/__tests__/features/request/request.immutability.spec.ts +259 -0
  44. package/__tests__/features/request/request.inference.spec.ts +269 -0
  45. package/__tests__/features/request/request.lifecycle.spec.ts +682 -0
  46. package/__tests__/features/request/request.optimistic-settlement.spec.ts +35 -17
  47. package/__tests__/features/request/request.optimistic.spec.ts +12 -1
  48. package/__tests__/features/request/request.values.spec.ts +408 -0
  49. package/__tests__/features/sdk/sdk.builder.spec.ts +304 -0
  50. package/__tests__/features/utils/emitter.listeners.spec.ts +202 -0
  51. package/__tests__/utils/controlled-adapter.utils.ts +119 -0
  52. package/__tests__/utils/fixtures.utils.ts +193 -0
  53. package/__tests__/utils/optimistic.utils.ts +124 -0
  54. package/dist/adapter/adapter.bindings.d.ts.map +1 -1
  55. package/dist/adapter/adapter.utils.d.ts.map +1 -1
  56. package/dist/cache/cache.d.ts +12 -1
  57. package/dist/cache/cache.d.ts.map +1 -1
  58. package/dist/cache/cache.events.d.ts +20 -6
  59. package/dist/cache/cache.events.d.ts.map +1 -1
  60. package/dist/cache/cache.utils.d.ts +1 -0
  61. package/dist/cache/cache.utils.d.ts.map +1 -1
  62. package/dist/client/client.d.ts +3 -3
  63. package/dist/client/client.d.ts.map +1 -1
  64. package/dist/client/client.utils.d.ts.map +1 -1
  65. package/dist/dispatcher/dispatcher.d.ts +26 -5
  66. package/dist/dispatcher/dispatcher.d.ts.map +1 -1
  67. package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -1
  68. package/dist/index.d.ts +1 -0
  69. package/dist/index.d.ts.map +1 -1
  70. package/dist/index.mjs +2787 -1893
  71. package/dist/index.mjs.map +1 -1
  72. package/dist/managers/app/app.manager.constants.d.ts.map +1 -1
  73. package/dist/managers/app/app.manager.d.ts +9 -0
  74. package/dist/managers/app/app.manager.d.ts.map +1 -1
  75. package/dist/managers/app/app.manager.utils.d.ts.map +1 -1
  76. package/dist/managers/logger/logger.manager.d.ts.map +1 -1
  77. package/dist/managers/request/request.manager.d.ts.map +1 -1
  78. package/dist/managers/request/request.manager.types.d.ts +2 -0
  79. package/dist/managers/request/request.manager.types.d.ts.map +1 -1
  80. package/dist/mocker/mocker.d.ts +1 -1
  81. package/dist/mocker/mocker.d.ts.map +1 -1
  82. package/dist/optimistic/index.d.ts +5 -0
  83. package/dist/optimistic/index.d.ts.map +1 -0
  84. package/dist/optimistic/optimistic.d.ts +67 -0
  85. package/dist/optimistic/optimistic.d.ts.map +1 -0
  86. package/dist/optimistic/optimistic.settlement.d.ts +60 -0
  87. package/dist/optimistic/optimistic.settlement.d.ts.map +1 -0
  88. package/dist/optimistic/optimistic.types.d.ts +109 -0
  89. package/dist/optimistic/optimistic.types.d.ts.map +1 -0
  90. package/dist/optimistic/optimistic.utils.d.ts +29 -0
  91. package/dist/optimistic/optimistic.utils.d.ts.map +1 -0
  92. package/dist/plugin/plugin.d.ts +2 -0
  93. package/dist/plugin/plugin.d.ts.map +1 -1
  94. package/dist/request/request.d.ts +14 -6
  95. package/dist/request/request.d.ts.map +1 -1
  96. package/dist/request/request.types.d.ts +40 -1
  97. package/dist/request/request.types.d.ts.map +1 -1
  98. package/dist/request/request.utils.d.ts.map +1 -1
  99. package/dist/utils/emitter.utils.d.ts.map +1 -1
  100. package/dist/utils/error.utils.d.ts +17 -0
  101. package/dist/utils/error.utils.d.ts.map +1 -0
  102. package/dist/utils/index.d.ts +1 -0
  103. package/dist/utils/index.d.ts.map +1 -1
  104. package/package.json +1 -1
  105. package/src/adapter/adapter.bindings.ts +46 -18
  106. package/src/adapter/adapter.utils.ts +47 -7
  107. package/src/cache/cache.events.ts +24 -8
  108. package/src/cache/cache.ts +110 -21
  109. package/src/cache/cache.utils.ts +33 -10
  110. package/src/client/client.ts +101 -7
  111. package/src/client/client.utils.ts +10 -4
  112. package/src/dispatcher/dispatcher.ts +285 -132
  113. package/src/http-adapter/http-adapter.fetch.ts +15 -3
  114. package/src/index.ts +4 -0
  115. package/src/managers/app/app.manager.constants.ts +12 -1
  116. package/src/managers/app/app.manager.ts +43 -23
  117. package/src/managers/app/app.manager.utils.ts +8 -4
  118. package/src/managers/logger/logger.manager.ts +21 -8
  119. package/src/managers/request/request.manager.ts +7 -1
  120. package/src/managers/request/request.manager.types.ts +2 -0
  121. package/src/mocker/mocker.ts +14 -11
  122. package/src/optimistic/index.ts +4 -0
  123. package/src/optimistic/optimistic.settlement.ts +406 -0
  124. package/src/optimistic/optimistic.ts +162 -0
  125. package/src/optimistic/optimistic.types.ts +175 -0
  126. package/src/optimistic/optimistic.utils.ts +112 -0
  127. package/src/plugin/plugin.ts +6 -0
  128. package/src/request/request.ts +50 -28
  129. package/src/request/request.types.ts +41 -1
  130. package/src/request/request.utils.ts +51 -66
  131. package/src/utils/emitter.utils.ts +9 -2
  132. package/src/utils/error.utils.ts +29 -0
  133. package/src/utils/index.ts +1 -0
  134. package/tsconfig.json +2 -0
@@ -20,6 +20,8 @@ export class AppManager {
20
20
  isFocused: boolean;
21
21
 
22
22
  private unmountCallbacks: VoidFunction[] = [];
23
+ private hasFocusUpdate = false;
24
+ private hasOnlineUpdate = false;
23
25
 
24
26
  constructor(public options?: AppManagerOptionsType) {
25
27
  this.emitter?.setMaxListeners(1000);
@@ -60,39 +62,56 @@ export class AppManager {
60
62
  callbacks.forEach((unmount) => unmount());
61
63
  };
62
64
 
63
- private setInitialFocus = async (initValue: Exclude<AppManagerOptionsType["initiallyFocused"], undefined>) => {
64
- if (typeof initValue !== "function") {
65
- this.isFocused = initValue;
66
- return;
67
- }
65
+ private setInitialFocus = (initValue: Exclude<AppManagerOptionsType["initiallyFocused"], undefined>) => {
66
+ this.isFocused = this.readInitialValue(initValue, (isFocused) => {
67
+ // The environment could report the state in the meantime - it is more recent than the initial value
68
+ if (!this.hasFocusUpdate && isFocused !== this.isFocused) {
69
+ this.setFocused(isFocused);
70
+ }
71
+ });
72
+ };
68
73
 
69
- // Synchronous getters apply right away, so there is no moment with a wrong value
70
- const value = initValue();
71
- if (typeof value === "boolean") {
72
- this.isFocused = value;
73
- } else {
74
- this.isFocused = false;
75
- this.isFocused = await value;
76
- }
74
+ private setInitialOnline = (initValue: Exclude<AppManagerOptionsType["initiallyOnline"], undefined>) => {
75
+ this.isOnline = this.readInitialValue(initValue, (isOnline) => {
76
+ // The environment could report the state in the meantime - it is more recent than the initial value
77
+ if (!this.hasOnlineUpdate && isOnline !== this.isOnline) {
78
+ this.setOnline(isOnline);
79
+ }
80
+ });
77
81
  };
78
82
 
79
- private setInitialOnline = async (initValue: Exclude<AppManagerOptionsType["initiallyOnline"], undefined>) => {
83
+ /**
84
+ * Reads the initial state from a value or a getter. Synchronous getters apply right away, so there is no moment
85
+ * with a wrong value. Asynchronous ones start with `false` and apply once resolved - the change is emitted like
86
+ * any other, so the modules waiting for the focus or the network get notified.
87
+ * A getter which throws or rejects leaves the state unknown, so it falls back to `true` - just like the defaults do.
88
+ */
89
+ private readInitialValue = (
90
+ initValue: boolean | (() => boolean | Promise<boolean>),
91
+ onResolved: (value: boolean) => void,
92
+ ): boolean => {
80
93
  if (typeof initValue !== "function") {
81
- this.isOnline = initValue;
82
- return;
94
+ return initValue;
83
95
  }
84
96
 
85
- // Synchronous getters apply right away, so there is no moment with a wrong value
86
- const value = initValue();
87
- if (typeof value === "boolean") {
88
- this.isOnline = value;
89
- } else {
90
- this.isOnline = false;
91
- this.isOnline = await value;
97
+ try {
98
+ const value = initValue();
99
+ if (typeof value === "boolean") {
100
+ return value;
101
+ }
102
+
103
+ Promise.resolve(value).then(
104
+ (resolved) => onResolved(resolved),
105
+ () => onResolved(true),
106
+ );
107
+ return false;
108
+ } catch {
109
+ return true;
92
110
  }
93
111
  };
94
112
 
95
113
  setFocused = (isFocused: boolean) => {
114
+ this.hasFocusUpdate = true;
96
115
  this.isFocused = isFocused;
97
116
 
98
117
  if (isFocused) {
@@ -103,6 +122,7 @@ export class AppManager {
103
122
  };
104
123
 
105
124
  setOnline = (isOnline: boolean) => {
125
+ this.hasOnlineUpdate = true;
106
126
  this.isOnline = isOnline;
107
127
 
108
128
  if (isOnline) {
@@ -36,8 +36,10 @@ export const onWindowEvent = <K extends keyof WindowEventMap>(
36
36
  ): VoidFunction => {
37
37
  /* istanbul ignore next */
38
38
  if (hasWindow()) {
39
- window.addEventListener(key, listener, options);
40
- return () => window.removeEventListener(key, listener, options);
39
+ // Keep the target - the cleanup has to reach the same object, even when the global one is already gone
40
+ const target = window;
41
+ target.addEventListener(key, listener, options);
42
+ return () => target.removeEventListener(key, listener, options);
41
43
  }
42
44
  /* istanbul ignore next */
43
45
  return () => null;
@@ -50,8 +52,10 @@ export const onDocumentEvent = <K extends keyof DocumentEventMap>(
50
52
  ): VoidFunction => {
51
53
  /* istanbul ignore next */
52
54
  if (hasDocument()) {
53
- window.document.addEventListener(key, listener, options);
54
- return () => window.document.removeEventListener(key, listener, options);
55
+ // Keep the target - the cleanup has to reach the same object, even when the global one is already gone
56
+ const target = window.document;
57
+ target.addEventListener(key, listener, options);
58
+ return () => target.removeEventListener(key, listener, options);
55
59
  }
56
60
  /* istanbul ignore next */
57
61
  return () => null;
@@ -1,6 +1,6 @@
1
1
  import type { ClientInstance } from "client";
2
2
  import EventEmitter from "events";
3
- import type { LogLevel, LoggerOptionsType, LoggerType, LoggerMethods } from "managers";
3
+ import type { LogLevel, LoggerArgs, LoggerOptionsType, LoggerType, LoggerMethods } from "managers";
4
4
  import { logger, logLevelOrder } from "managers";
5
5
 
6
6
  /**
@@ -35,19 +35,32 @@ export class LoggerManager {
35
35
  initialize = (client: Pick<ClientInstance, "debug">, module: string): LoggerMethods => {
36
36
  this.client = client;
37
37
 
38
+ // Modules keep their logger methods for the whole lifetime. When they come from the logger manager of the client,
39
+ // the logs have to follow the manager currently assigned to it - otherwise `client.setLogger()` would affect
40
+ // only the modules initialized later.
41
+ const getClientManager = () => (client as Partial<Pick<ClientInstance, "loggerManager">>).loggerManager;
42
+ const isClientManager = getClientManager() === this;
43
+
44
+ const log: LoggerType = (data) => {
45
+ const clientManager = getClientManager();
46
+ const manager = isClientManager && clientManager instanceof LoggerManager ? clientManager : this;
47
+ manager.log(data, client);
48
+ };
49
+
38
50
  return {
39
- error: (data) => this.log({ ...data, level: "error", module }),
40
- warning: (data) => this.log({ ...data, level: "warning", module }),
41
- info: (data) => this.log({ ...data, level: "info", module }),
42
- debug: (data) => this.log({ ...data, level: "debug", module }),
51
+ error: (data) => log({ ...data, level: "error", module }),
52
+ warning: (data) => log({ ...data, level: "warning", module }),
53
+ info: (data) => log({ ...data, level: "info", module }),
54
+ debug: (data) => log({ ...data, level: "debug", module }),
43
55
  };
44
56
  };
45
57
 
46
- private log: LoggerType = (data) => {
47
- if (!this.client.debug) {
58
+ private log = (data: LoggerArgs, client: Pick<ClientInstance, "debug"> = this.client) => {
59
+ if (!client.debug) {
48
60
  return;
49
61
  }
50
- if (logLevelOrder.indexOf(this.level) <= logLevelOrder.indexOf(data.level)) {
62
+ // Level is the least severe type of the logs to show - logs of this level and the more severe ones are printed
63
+ if (logLevelOrder.indexOf(this.level) < logLevelOrder.indexOf(data.level)) {
51
64
  return;
52
65
  }
53
66
  if (this.modules && !this.modules.includes(data.module)) {
@@ -34,7 +34,13 @@ export class RequestManager {
34
34
  };
35
35
 
36
36
  removeAbortController = (abortKey: string, requestId: string) => {
37
- this.abortControllers.get(abortKey)?.delete(requestId);
37
+ const abortGroup = this.abortControllers.get(abortKey);
38
+ abortGroup?.delete(requestId);
39
+
40
+ // Do not keep an empty group for every abortKey (and every scope) that was ever used
41
+ if (abortGroup?.size === 0) {
42
+ this.abortControllers.delete(abortKey);
43
+ }
38
44
  };
39
45
 
40
46
  // Aborting
@@ -29,6 +29,8 @@ export type RequestResponseEventType<T extends RequestInstance> = {
29
29
  requestId: string;
30
30
  response: ResponseType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>;
31
31
  details: ResponseDetailsType;
32
+ /** Result of the optimistic callback - available in the callbacks of `send()` and in the request `$hooks` */
33
+ mutationContext?: OptimisticCallbackResult<any>;
32
34
  };
33
35
 
34
36
  export type RequestDeduplicatedEventType<T extends RequestInstance> = RequestEventType<T> & {
@@ -16,7 +16,6 @@ export const mocker = async <T extends AdapterInstance>({
16
16
  onBeforeRequest,
17
17
  onRequestStart,
18
18
  onSuccess,
19
- onAbortError,
20
19
  adapter,
21
20
  }: Awaited<ReturnType<typeof getAdapterBindings<T>>>) => {
22
21
  if (!request.unstable_mock) {
@@ -34,7 +33,10 @@ export const mocker = async <T extends AdapterInstance>({
34
33
  } = request.unstable_mock.config;
35
34
  const result = await request.unstable_mock.fn({ request, requestId });
36
35
 
37
- const { data, error, status, success = true, extra = request.client.adapter.defaultExtra } = result;
36
+ const { data, error, status, extra = request.client.adapter.defaultExtra } = result;
37
+ // Without the `success` flag, a mock with nothing but an error is a failed response
38
+ const hasData = data !== undefined && data !== null;
39
+ const { success = !error || hasData } = result;
38
40
 
39
41
  createAbortListener({
40
42
  status: adapter.systemErrorStatus,
@@ -64,9 +66,11 @@ export const mocker = async <T extends AdapterInstance>({
64
66
  const chunkSize = Math.ceil(totalSize / intervals);
65
67
  let currentlyLoaded = 0;
66
68
  const timer = setInterval(function handleProgressInterval() {
69
+ // Aborted or timed out - nothing more is transferred
67
70
  if (thrown) {
68
71
  resolveProgress(true);
69
72
  clearInterval(timer);
73
+ return;
70
74
  }
71
75
 
72
76
  const currentTime = Math.min(totalTime, Date.now() - dataStart);
@@ -83,8 +87,9 @@ export const mocker = async <T extends AdapterInstance>({
83
87
  }, interval);
84
88
  });
85
89
 
90
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
86
91
  if (typeof timeout === "number") {
87
- setTimeout(() => {
92
+ timeoutId = setTimeout(() => {
88
93
  thrown = true;
89
94
  onTimeoutError({
90
95
  status: 0 as ExtractAdapterStatusType<T>,
@@ -102,12 +107,12 @@ export const mocker = async <T extends AdapterInstance>({
102
107
  if (!thrown) {
103
108
  await progress(responseTime, totalDownloaded, onResponseProgress);
104
109
  }
110
+ clearTimeout(timeoutId);
111
+ // An abort or a timeout was already reported when it happened
105
112
  if (thrown) {
106
- onAbortError({
107
- status: adapter.systemErrorStatus,
108
- extra: adapter.systemErrorExtra,
109
- });
110
- } else if (success || (error && data)) {
113
+ return;
114
+ }
115
+ if (success || (error && data)) {
111
116
  onSuccess({
112
117
  data,
113
118
  error,
@@ -121,7 +126,5 @@ export const mocker = async <T extends AdapterInstance>({
121
126
  extra: extra as ExtractAdapterExtraType<T>,
122
127
  });
123
128
  }
124
- if (!thrown) {
125
- onResponseEnd();
126
- }
129
+ onResponseEnd();
127
130
  };
@@ -0,0 +1,4 @@
1
+ export * from "./optimistic";
2
+ export * from "./optimistic.settlement";
3
+ export * from "./optimistic.types";
4
+ export * from "./optimistic.utils";
@@ -0,0 +1,406 @@
1
+ import type { AdapterInstance, ResponseSuccessType, ResponseType } from "adapter";
2
+ import type { CacheValueType } from "cache";
3
+ import type { ClientInstance } from "client";
4
+ import type {
5
+ OptimisticCallbackResult,
6
+ OptimisticCallbackReturnType,
7
+ OptimisticRollbackArgs,
8
+ RequestInstance,
9
+ } from "request";
10
+ import { getRequestKey, scopeKey, stringifyKey } from "request";
11
+ import { throwOutsideLifecycle } from "utils";
12
+
13
+ import { OptimisticOperation } from "./optimistic";
14
+
15
+ /**
16
+ * Settlement of optimistic updates.
17
+ *
18
+ * Every cache key changed by pending mutations has a counter. While it is above zero, fetch responses for the key are
19
+ * not written to the cache, and fetches still running when a mutation on the key settles are marked as stale - they
20
+ * started before the change was confirmed or reverted. Once the last mutation settles and the stale fetches are done,
21
+ * the key is refreshed (invalidated) once, so the server's data replaces the optimistic value.
22
+ */
23
+
24
+ type KeyState = {
25
+ /** Mutations still pending on the key */
26
+ pending: number;
27
+ /** A settled mutation asked for the refresh */
28
+ refresh: boolean;
29
+ /** Request used to invalidate the key */
30
+ request: RequestInstance;
31
+ };
32
+
33
+ type ClientState = {
34
+ keys: Map<string, KeyState>;
35
+ /** Running fetches that started before a mutation on their key settled - request id to storage key */
36
+ staleRequests: Map<string, string>;
37
+ };
38
+
39
+ type AppliedOperation = {
40
+ operation: OptimisticOperation<unknown, RequestInstance>;
41
+ storageKey: string;
42
+ /** Request of the changed entry */
43
+ request: RequestInstance;
44
+ previous: unknown;
45
+ };
46
+
47
+ /** @internal State of one mutation's optimistic updates, from applying them until the mutation settles */
48
+ export type OptimisticPendingType = {
49
+ client: ClientInstance;
50
+ result: OptimisticCallbackResult<unknown>;
51
+ applied: AppliedOperation[];
52
+ /** Every key the operations target, with the request used to refresh it */
53
+ targets: Map<string, RequestInstance>;
54
+ /** Keys changed by the operations - their fetch responses are held back until the mutation settles */
55
+ guarded: Set<string>;
56
+ /** Keys where user code failed - refreshed whatever the outcome */
57
+ failed: Set<string>;
58
+ };
59
+
60
+ /** @internal How the mutation settled */
61
+ export type OptimisticOutcomeType =
62
+ | { type: "success"; response: ResponseType<any, any, AdapterInstance>; request: RequestInstance }
63
+ | ({ type: "rollback" } & OptimisticRollbackArgs<RequestInstance>);
64
+
65
+ const clientStates = new WeakMap<ClientInstance, ClientState>();
66
+
67
+ const getClientState = (client: ClientInstance): ClientState => {
68
+ let state = clientStates.get(client);
69
+ if (!state) {
70
+ state = { keys: new Map(), staleRequests: new Map() };
71
+ clientStates.set(client, state);
72
+ }
73
+ return state;
74
+ };
75
+
76
+ /**
77
+ * Failures of user code (helpers, commits, rollbacks, predicates) are logged and thrown outside of the request
78
+ * lifecycle, like every other user code running in it - the request and the other changes still settle.
79
+ */
80
+ const reportFailure = (client: ClientInstance, title: string, extra: { error: unknown } & Record<string, unknown>) => {
81
+ client.logger.error({ title, type: "system", extra });
82
+ throwOutsideLifecycle(extra.error);
83
+ };
84
+
85
+ const readEntry = (client: ClientInstance, storageKey: string) => {
86
+ return client.cache.get<unknown, unknown>(storageKey);
87
+ };
88
+
89
+ /**
90
+ * Writes the data through the regular cache path, so listeners get one event per change. The entry keeps its
91
+ * timestamps and staleness - an optimistic value doesn't make the entry fresh.
92
+ */
93
+ const writeData = (request: RequestInstance, entry: CacheValueType<unknown, unknown, AdapterInstance>, data: unknown) => {
94
+ const entryRequest = request.clone({ staleTime: entry.staleTime, cacheTime: entry.cacheTime }) as RequestInstance;
95
+ request.client.cache.set(entryRequest, { ...entry, data });
96
+ };
97
+
98
+ /**
99
+ * Cache keys targeted by the operation. `optimistic.all()` matches every entry of the same method and endpoint
100
+ * whatever the query params; a custom cache key matches itself and the keys derived from it (infinite pages).
101
+ */
102
+ const resolveTargets = (client: ClientInstance, operation: OptimisticOperation<unknown, RequestInstance>) => {
103
+ const { target } = operation;
104
+ const targets = new Map<string, RequestInstance>();
105
+
106
+ if (!operation.allVariants) {
107
+ targets.set(scopeKey(target.cacheKey, target.scope), target);
108
+ return targets;
109
+ }
110
+
111
+ const isGeneratedKey = target.cacheKey === getRequestKey(target);
112
+ const prefix = isGeneratedKey
113
+ ? `${stringifyKey(target.method)}_${stringifyKey(target.endpoint)}_`
114
+ : `${target.cacheKey}_`;
115
+
116
+ client.cache.keys().forEach((storageKey) => {
117
+ const entry = client.cache.storage.get<unknown, unknown, AdapterInstance>(storageKey);
118
+ if (!entry || entry.scope !== target.scope) {
119
+ return;
120
+ }
121
+ if (entry.cacheKey === target.cacheKey) {
122
+ targets.set(storageKey, target);
123
+ } else if (entry.cacheKey.startsWith(prefix)) {
124
+ // `setCacheKey` marks the instance it is called on - a clone keeps the user's request untouched
125
+ targets.set(storageKey, target.clone().setCacheKey(entry.cacheKey) as RequestInstance);
126
+ }
127
+ });
128
+
129
+ return targets;
130
+ };
131
+
132
+ /**
133
+ * Runs `.rollback()` / `.commit()` of an operation and writes what it returned. User code can't break the settlement:
134
+ * a throw or a promise is reported and the key gets refreshed.
135
+ */
136
+ const runSettleCallback = (
137
+ pending: OptimisticPendingType,
138
+ { operation, storageKey, request, previous }: AppliedOperation,
139
+ outcome: OptimisticOutcomeType,
140
+ ) => {
141
+ const { client } = pending;
142
+ const entry = readEntry(client, storageKey);
143
+ const isCommit = outcome.type === "success";
144
+ const title = isCommit ? "Optimistic commit failed" : "Optimistic rollback failed";
145
+ const run = (data: unknown) => {
146
+ if (outcome.type === "success") {
147
+ const response = outcome.response as ResponseSuccessType<unknown, AdapterInstance>;
148
+ return operation.onCommit?.({ data, response, request: outcome.request });
149
+ }
150
+ const { type: _type, ...args } = outcome;
151
+ return operation.onRollback?.({ ...args, data, previous });
152
+ };
153
+
154
+ // Entry deleted or cache cleared in the meantime - there is nothing to update
155
+ if (!(isCommit ? operation.onCommit : operation.onRollback) || !entry) {
156
+ return;
157
+ }
158
+
159
+ try {
160
+ const next = run(entry.data);
161
+
162
+ if (next instanceof Promise) {
163
+ next.catch((error: unknown) => reportFailure(client, title, { error, storageKey }));
164
+ throw new TypeError("Optimistic rollback and commit must be synchronous, the returned promise was ignored");
165
+ }
166
+ if (next !== undefined && next !== entry.data) {
167
+ writeData(request, entry, next);
168
+ }
169
+ } catch (error) {
170
+ reportFailure(client, title, { error, storageKey, request: outcome.request });
171
+ pending.failed.add(storageKey);
172
+ }
173
+ };
174
+
175
+ /** Rollback of the hand-written object form - runs once, its failure can't affect the request */
176
+ const runObjectRollback = (pending: OptimisticPendingType, args: OptimisticRollbackArgs<RequestInstance>) => {
177
+ const { client, result } = pending;
178
+ const onFailure = (error: unknown) => {
179
+ reportFailure(client, "Optimistic rollback failed", { error, reason: args.reason, request: args.request });
180
+ };
181
+
182
+ try {
183
+ // Async rollback is not awaited, but its rejection can't stay unhandled
184
+ Promise.resolve(result.rollback?.(args)).catch(onFailure);
185
+ } catch (error) {
186
+ onFailure(error);
187
+ }
188
+ };
189
+
190
+ const runObjectInvalidation = ({ client, result }: OptimisticPendingType, request: RequestInstance) => {
191
+ result.invalidate?.forEach((target) => {
192
+ try {
193
+ client.cache.invalidate(target);
194
+ } catch (error) {
195
+ reportFailure(client, "Optimistic invalidation failed", { error, target, request });
196
+ }
197
+ });
198
+ };
199
+
200
+ /**
201
+ * `rollbackOnError` decides about final errors only - aborted and removed requests are always reverted.
202
+ * A predicate that throws is reported and the change is reverted.
203
+ */
204
+ const shouldRollback = (pending: OptimisticPendingType, outcome: OptimisticRollbackArgs<RequestInstance>) => {
205
+ const { rollbackOnError } = pending.result;
206
+ if (outcome.reason !== "error" || rollbackOnError === undefined || rollbackOnError === true) {
207
+ return true;
208
+ }
209
+ if (rollbackOnError === false) {
210
+ return false;
211
+ }
212
+ try {
213
+ return !!rollbackOnError({ response: outcome.response, request: outcome.request });
214
+ } catch (error) {
215
+ reportFailure(pending.client, "Optimistic rollbackOnError failed", { error, request: outcome.request });
216
+ return true;
217
+ }
218
+ };
219
+
220
+ const getRunningRequestsOnKey = (client: ClientInstance, storageKey: string) => {
221
+ return [...client.fetchDispatcher.getAllRunningRequests(), ...client.submitDispatcher.getAllRunningRequests()].filter(
222
+ ({ request }) => scopeKey(request.cacheKey, request.scope) === storageKey,
223
+ );
224
+ };
225
+
226
+ const hasStaleRequests = (state: ClientState, storageKey: string) => {
227
+ return [...state.staleRequests.values()].includes(storageKey);
228
+ };
229
+
230
+ /** Refreshes the key once nothing pending or stale is left on it */
231
+ const refreshWhenIdle = (client: ClientInstance, state: ClientState, storageKey: string) => {
232
+ const keyState = state.keys.get(storageKey);
233
+ if (!keyState || keyState.pending > 0 || hasStaleRequests(state, storageKey)) {
234
+ return;
235
+ }
236
+ state.keys.delete(storageKey);
237
+ if (keyState.refresh) {
238
+ client.cache.invalidate(keyState.request);
239
+ }
240
+ };
241
+
242
+ const release = (pending: OptimisticPendingType, refresh: boolean) => {
243
+ const { client, targets, failed, guarded } = pending;
244
+ const state = getClientState(client);
245
+
246
+ targets.forEach((request, storageKey) => {
247
+ const keyState = state.keys.get(storageKey);
248
+ const shouldRefresh = refresh || failed.has(storageKey);
249
+
250
+ if (!guarded.has(storageKey)) {
251
+ // Nothing was changed here - refresh together with the mutations still pending on the key, or right away
252
+ if (keyState && shouldRefresh) {
253
+ keyState.refresh = true;
254
+ } else if (shouldRefresh) {
255
+ client.cache.invalidate(request);
256
+ }
257
+ return;
258
+ }
259
+ // State was reset by clearing the client
260
+ if (!keyState) {
261
+ return;
262
+ }
263
+ keyState.pending -= 1;
264
+ keyState.refresh = keyState.refresh || shouldRefresh;
265
+ keyState.request = request;
266
+
267
+ getRunningRequestsOnKey(client, storageKey).forEach(({ requestId }) => {
268
+ state.staleRequests.set(requestId, storageKey);
269
+ });
270
+
271
+ refreshWhenIdle(client, state, storageKey);
272
+ });
273
+ };
274
+
275
+ /**
276
+ * @internal
277
+ * Normalizes what `setOptimistic` or the `optimistic` send option returned into the object form.
278
+ */
279
+ export const getOptimisticResult = (
280
+ value: OptimisticCallbackReturnType<unknown, RequestInstance> | undefined,
281
+ ): OptimisticCallbackResult<unknown> => {
282
+ if (Array.isArray(value)) {
283
+ return { updates: value };
284
+ }
285
+ return value || {};
286
+ };
287
+
288
+ /**
289
+ * @internal
290
+ * Applies the operations of the mutation and registers its target keys as pending. A failing operation is reported,
291
+ * the others still apply.
292
+ */
293
+ export const applyOptimistic = (
294
+ client: ClientInstance,
295
+ result: OptimisticCallbackResult<unknown>,
296
+ ): OptimisticPendingType => {
297
+ const pending: OptimisticPendingType = {
298
+ client,
299
+ result,
300
+ applied: [],
301
+ targets: new Map(),
302
+ guarded: new Set(),
303
+ failed: new Set(),
304
+ };
305
+ const state = getClientState(client);
306
+
307
+ result.updates?.forEach((value) => {
308
+ try {
309
+ if (!(value instanceof OptimisticOperation)) {
310
+ throw new TypeError("Optimistic updates accept operations created with optimistic()");
311
+ }
312
+ const operation = value as OptimisticOperation<unknown, RequestInstance>;
313
+
314
+ resolveTargets(client, operation).forEach((request, storageKey) => {
315
+ pending.targets.set(storageKey, request);
316
+ const entry = readEntry(client, storageKey);
317
+ // No data yet - there is nothing to change and nothing to revert
318
+ if (!entry) {
319
+ return;
320
+ }
321
+ try {
322
+ const next = operation.update(entry.data);
323
+ if (next !== entry.data) {
324
+ writeData(request, entry, next);
325
+ }
326
+ pending.applied.push({ operation, storageKey, request, previous: entry.data });
327
+ pending.guarded.add(storageKey);
328
+ } catch (error) {
329
+ reportFailure(client, "Optimistic update failed", { error, storageKey });
330
+ pending.failed.add(storageKey);
331
+ }
332
+ });
333
+ } catch (error) {
334
+ reportFailure(client, "Optimistic update failed", { error, operation: value });
335
+ }
336
+ });
337
+
338
+ pending.guarded.forEach((storageKey) => {
339
+ const request = pending.targets.get(storageKey) as RequestInstance;
340
+ const keyState = state.keys.get(storageKey) ?? { pending: 0, refresh: false, request };
341
+ keyState.pending += 1;
342
+ state.keys.set(storageKey, keyState);
343
+ });
344
+
345
+ return pending;
346
+ };
347
+
348
+ /**
349
+ * @internal
350
+ * Settles the mutation once. Success runs the commits and invalidations, a final error, abort or queue removal runs the
351
+ * rollbacks in reverse order of application. The targets get refreshed after the last pending mutation on them.
352
+ */
353
+ export const settleOptimistic = (pending: OptimisticPendingType, outcome: OptimisticOutcomeType) => {
354
+ const { result, applied } = pending;
355
+ const canRefresh = result.revalidate !== false;
356
+
357
+ if (outcome.type === "success") {
358
+ applied.forEach((operation) => runSettleCallback(pending, operation, outcome));
359
+ runObjectInvalidation(pending, outcome.request);
360
+ return release(pending, canRefresh);
361
+ }
362
+
363
+ const { type: _type, ...args } = outcome;
364
+ if (!shouldRollback(pending, args)) {
365
+ return release(pending, false);
366
+ }
367
+
368
+ // The latest change is reverted first
369
+ for (let index = applied.length - 1; index >= 0; index -= 1) {
370
+ runSettleCallback(pending, applied[index], outcome);
371
+ }
372
+ runObjectRollback(pending, args);
373
+ return release(pending, canRefresh);
374
+ };
375
+
376
+ /**
377
+ * @internal
378
+ * Stale response guard, called where the dispatcher writes a response to the cache. A response is discarded when a
379
+ * mutation changed its key and is pending, or when the fetch started before the latest such mutation settled - the
380
+ * refresh after the mutation supplies current data. Keys that had no data when the change was applied are not
381
+ * guarded, so a first load is never held back. Manual cache writes don't go through this check.
382
+ */
383
+ export const isStaleOptimisticResponse = (
384
+ client: ClientInstance,
385
+ request: RequestInstance,
386
+ requestId: string,
387
+ ): boolean => {
388
+ const state = clientStates.get(client);
389
+ if (!state) {
390
+ return false;
391
+ }
392
+
393
+ const storageKey = scopeKey(request.cacheKey, request.scope);
394
+ const isMarked = state.staleRequests.delete(requestId);
395
+ const isPending = (state.keys.get(storageKey)?.pending ?? 0) > 0;
396
+ if (isMarked) {
397
+ refreshWhenIdle(client, state, storageKey);
398
+ }
399
+
400
+ return isMarked || isPending;
401
+ };
402
+
403
+ /** @internal Drops the pending state of the client, its mutations will never settle after clearing it */
404
+ export const resetOptimisticState = (client: ClientInstance) => {
405
+ clientStates.delete(client);
406
+ };