@hyper-fetch/core 9.6.0 → 9.6.2

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 (103) 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/plugin/plugin.lifecycle.spec.ts +457 -0
  35. package/__tests__/features/request/request.async-mapper-removal.spec.ts +138 -0
  36. package/__tests__/features/request/request.immutability.spec.ts +259 -0
  37. package/__tests__/features/request/request.inference.spec.ts +269 -0
  38. package/__tests__/features/request/request.lifecycle.spec.ts +682 -0
  39. package/__tests__/features/request/request.optimistic-settlement.spec.ts +35 -17
  40. package/__tests__/features/request/request.values.spec.ts +408 -0
  41. package/__tests__/features/sdk/sdk.builder.spec.ts +304 -0
  42. package/__tests__/features/utils/emitter.listeners.spec.ts +202 -0
  43. package/__tests__/utils/controlled-adapter.utils.ts +119 -0
  44. package/__tests__/utils/fixtures.utils.ts +193 -0
  45. package/dist/adapter/adapter.bindings.d.ts.map +1 -1
  46. package/dist/adapter/adapter.utils.d.ts.map +1 -1
  47. package/dist/cache/cache.d.ts +12 -1
  48. package/dist/cache/cache.d.ts.map +1 -1
  49. package/dist/cache/cache.events.d.ts +20 -6
  50. package/dist/cache/cache.events.d.ts.map +1 -1
  51. package/dist/cache/cache.utils.d.ts +1 -0
  52. package/dist/cache/cache.utils.d.ts.map +1 -1
  53. package/dist/client/client.d.ts +3 -3
  54. package/dist/client/client.d.ts.map +1 -1
  55. package/dist/client/client.utils.d.ts.map +1 -1
  56. package/dist/dispatcher/dispatcher.d.ts +26 -5
  57. package/dist/dispatcher/dispatcher.d.ts.map +1 -1
  58. package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -1
  59. package/dist/index.mjs +2127 -1741
  60. package/dist/index.mjs.map +1 -1
  61. package/dist/managers/app/app.manager.constants.d.ts.map +1 -1
  62. package/dist/managers/app/app.manager.d.ts +9 -0
  63. package/dist/managers/app/app.manager.d.ts.map +1 -1
  64. package/dist/managers/app/app.manager.utils.d.ts.map +1 -1
  65. package/dist/managers/logger/logger.manager.d.ts.map +1 -1
  66. package/dist/managers/request/request.manager.d.ts.map +1 -1
  67. package/dist/managers/request/request.manager.types.d.ts +2 -0
  68. package/dist/managers/request/request.manager.types.d.ts.map +1 -1
  69. package/dist/mocker/mocker.d.ts +1 -1
  70. package/dist/mocker/mocker.d.ts.map +1 -1
  71. package/dist/plugin/plugin.d.ts +2 -0
  72. package/dist/plugin/plugin.d.ts.map +1 -1
  73. package/dist/request/request.d.ts +1 -1
  74. package/dist/request/request.d.ts.map +1 -1
  75. package/dist/request/request.utils.d.ts.map +1 -1
  76. package/dist/utils/emitter.utils.d.ts.map +1 -1
  77. package/dist/utils/error.utils.d.ts +17 -0
  78. package/dist/utils/error.utils.d.ts.map +1 -0
  79. package/dist/utils/index.d.ts +1 -0
  80. package/dist/utils/index.d.ts.map +1 -1
  81. package/package.json +1 -1
  82. package/src/adapter/adapter.bindings.ts +46 -18
  83. package/src/adapter/adapter.utils.ts +47 -7
  84. package/src/cache/cache.events.ts +24 -8
  85. package/src/cache/cache.ts +109 -21
  86. package/src/cache/cache.utils.ts +33 -10
  87. package/src/client/client.ts +99 -7
  88. package/src/client/client.utils.ts +10 -4
  89. package/src/dispatcher/dispatcher.ts +273 -133
  90. package/src/http-adapter/http-adapter.fetch.ts +15 -3
  91. package/src/managers/app/app.manager.constants.ts +12 -1
  92. package/src/managers/app/app.manager.ts +43 -23
  93. package/src/managers/app/app.manager.utils.ts +8 -4
  94. package/src/managers/logger/logger.manager.ts +21 -8
  95. package/src/managers/request/request.manager.ts +7 -1
  96. package/src/managers/request/request.manager.types.ts +2 -0
  97. package/src/mocker/mocker.ts +14 -11
  98. package/src/plugin/plugin.ts +6 -0
  99. package/src/request/request.ts +31 -22
  100. package/src/request/request.utils.ts +23 -15
  101. package/src/utils/emitter.utils.ts +9 -2
  102. package/src/utils/error.utils.ts +29 -0
  103. package/src/utils/index.ts +1 -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
  };
@@ -163,6 +163,12 @@ export class Plugin<Client extends ClientInstance = ClientInstance, PluginData =
163
163
  return this;
164
164
  };
165
165
 
166
+ /** Called when a cache entry is invalidated */
167
+ onCacheItemInvalidate = (callback: PluginMethods<Client>["onCacheItemInvalidate"]) => {
168
+ this.pluginMethods.onCacheItemInvalidate = callback;
169
+ return this;
170
+ };
171
+
166
172
  /* -------------------------------------------------------------------------------------------------
167
173
  * Adapter lifecycle
168
174
  * -----------------------------------------------------------------------------------------------*/
@@ -237,7 +237,7 @@ export class Request<
237
237
  return this.clone<HasPayload, P extends null ? false : true, HasQuery>({ params });
238
238
  };
239
239
 
240
- /** Set the request body payload. */
240
+ /** Set the request body payload. Passing `null` removes the payload set before. */
241
241
  public setPayload = <P extends Payload>(payload: P) => {
242
242
  return this.clone<P extends null ? false : true, HasParams, HasQuery>({
243
243
  payload,
@@ -342,20 +342,17 @@ export class Request<
342
342
 
343
343
  /** Override the abort key used to cancel this request. */
344
344
  public setAbortKey = (abortKey: string) => {
345
- this.updatedAbortKey = true;
346
- return this.clone({ abortKey });
345
+ return this.clone({ abortKey, updatedAbortKey: true });
347
346
  };
348
347
 
349
348
  /** Override the cache key used to store/retrieve the response. */
350
349
  public setCacheKey = (cacheKey: string) => {
351
- this.updatedCacheKey = true;
352
- return this.clone({ cacheKey });
350
+ return this.clone({ cacheKey, updatedCacheKey: true });
353
351
  };
354
352
 
355
353
  /** Override the query key that identifies this request in the dispatcher queue. */
356
354
  public setQueryKey = (queryKey: string) => {
357
- this.updatedQueryKey = true;
358
- return this.clone({ queryKey });
355
+ return this.clone({ queryKey, updatedQueryKey: true });
359
356
  };
360
357
 
361
358
  /** Enable or disable request deduplication. When enabled, concurrent identical requests share a single response. */
@@ -468,14 +465,24 @@ export class Request<
468
465
  private paramsMapper = (params: ParamsType | null | undefined): Endpoint => {
469
466
  const { endpoint } = this.requestOptions;
470
467
 
471
- let stringEndpoint = String(endpoint);
472
- if (params) {
473
- Object.entries(params).forEach(([key, value]) => {
474
- stringEndpoint = stringEndpoint.replaceAll(new RegExp(`:${key}`, "g"), String(value));
475
- });
468
+ const stringEndpoint = String(endpoint);
469
+ const names = params ? Object.keys(params) : [];
470
+ if (!params || names.length === 0) {
471
+ return stringEndpoint as Endpoint;
476
472
  }
477
473
 
478
- return stringEndpoint as Endpoint;
474
+ // Every `:` segment is replaced once, with the longest matching name. This way `:id` does not eat the beginning
475
+ // of `:idx`, and a value is never parsed again - neither as another param nor as a replacement pattern like `$&`.
476
+ const [start, ...segments] = stringEndpoint.split(":");
477
+ const mapped = segments.map((segment) => {
478
+ const name = names.reduce(
479
+ (longest, current) => (segment.startsWith(current) && current.length > longest.length ? current : longest),
480
+ "",
481
+ );
482
+ return name ? `${params[name]}${segment.slice(name.length)}` : `:${segment}`;
483
+ });
484
+
485
+ return [start, ...mapped].join("") as Endpoint;
479
486
  };
480
487
 
481
488
  /** Serialize the request configuration into a plain JSON object for persistence or transfer. */
@@ -548,12 +555,17 @@ export class Request<
548
555
  ...json,
549
556
  ...configuration,
550
557
  options: configuration?.options || this.options,
551
- abortKey: this.updatedAbortKey ? configuration?.abortKey || this.abortKey : undefined,
552
- cacheKey: this.updatedCacheKey ? configuration?.cacheKey || this.cacheKey : undefined,
553
- queryKey: this.updatedQueryKey ? configuration?.queryKey || this.queryKey : undefined,
558
+ // A key given by hand is kept by all the next clones, an auto-generated one is generated again
559
+ abortKey: configuration?.abortKey || (this.updatedAbortKey ? this.abortKey : undefined),
560
+ cacheKey: configuration?.cacheKey || (this.updatedCacheKey ? this.cacheKey : undefined),
561
+ queryKey: configuration?.queryKey || (this.updatedQueryKey ? this.queryKey : undefined),
562
+ updatedAbortKey: !!configuration?.abortKey || this.updatedAbortKey,
563
+ updatedCacheKey: !!configuration?.cacheKey || this.updatedCacheKey,
564
+ updatedQueryKey: !!configuration?.queryKey || this.updatedQueryKey,
554
565
  endpoint: this.paramsMapper(configuration?.params || this.params),
555
566
  queryParams: configuration?.queryParams || this.queryParams,
556
- payload: configuration?.payload || this.payload,
567
+ // Falsy payloads like `0`, `false` or an empty string are valid values, `null` removes the payload
568
+ payload: configuration?.payload === null ? undefined : (configuration?.payload ?? this.payload),
557
569
  params: (configuration?.params || this.params) as
558
570
  | EmptyTypes
559
571
  | (Endpoint extends string ? ExtractUrlParams<Endpoint> : never),
@@ -700,11 +712,8 @@ export class Request<
700
712
  // Stop listening for aborting
701
713
  requestManager.removeAbortController(scopedAbortKey, requestId);
702
714
 
703
- if (request.unstable_responseMapper) {
704
- return request.unstable_responseMapper(response);
705
- }
706
-
707
- return response;
715
+ // A throwing response mapper gives the error response, the same way as in `send()`
716
+ return mapResponseForSend(request, response);
708
717
  };
709
718
 
710
719
  /**
@@ -4,6 +4,7 @@ import { SAFE_HTTP_METHODS } from "constants/http.constants";
4
4
  import type { Dispatcher } from "dispatcher";
5
5
  import type { RequestResponseEventType } from "managers";
6
6
  import type { ExtractAdapterType, ExtractErrorType } from "types";
7
+ import { runUserCode, throwOutsideLifecycle } from "utils";
7
8
 
8
9
  import type {
9
10
  OptimisticCallbackResult,
@@ -196,6 +197,7 @@ const rollbackOptimistic = (
196
197
  type: "system",
197
198
  extra: { error, reason: args.reason, request: args.request },
198
199
  });
200
+ throwOutsideLifecycle(error);
199
201
  };
200
202
 
201
203
  try {
@@ -216,6 +218,7 @@ const invalidateOptimistic = (optimistic: OptimisticCallbackResult<any>, request
216
218
  type: "system",
217
219
  extra: { error, target, request },
218
220
  });
221
+ throwOutsideLifecycle(error);
219
222
  }
220
223
  });
221
224
  };
@@ -258,6 +261,7 @@ export const sendRequest = async <Request extends RequestInstance>(
258
261
  let isDelivered = false;
259
262
  let isSettled = false;
260
263
  const requestId = dispatcher.add(request);
264
+ const queryKey = scopeKey(request.queryKey, request.scope);
261
265
  const { $hooks } = request;
262
266
 
263
267
  // Failed attempts stay in the dispatcher queue when they are going to be sent again
@@ -265,6 +269,10 @@ export const sendRequest = async <Request extends RequestInstance>(
265
269
  if (response.success || details.isCanceled) {
266
270
  return false;
267
271
  }
272
+ // One that was taken out of the queue while it was running (cleared queue) has just given its last response
273
+ if (!dispatcher.getRequest(queryKey, requestId)) {
274
+ return false;
275
+ }
268
276
  return details.willRetry || (request.offline && details.isOffline);
269
277
  };
270
278
 
@@ -308,31 +316,31 @@ export const sendRequest = async <Request extends RequestInstance>(
308
316
  : undefined;
309
317
 
310
318
  const beforeSentData = { requestId, request, mutationContext };
311
- options?.onBeforeSent?.(beforeSentData);
312
- $hooks.__emit("onBeforeSent", beforeSentData);
319
+ runUserCode(() => options?.onBeforeSent?.(beforeSentData));
320
+ runUserCode(() => $hooks.__emit("onBeforeSent", beforeSentData));
313
321
 
314
322
  const unmountRequestStart = requestManager.events.onRequestStartById<Request>(requestId, (data) => {
315
323
  const enriched = { ...data, mutationContext };
316
- options?.onRequestStart?.(enriched);
317
- $hooks.__emit("onRequestStart", enriched);
324
+ runUserCode(() => options?.onRequestStart?.(enriched));
325
+ runUserCode(() => $hooks.__emit("onRequestStart", enriched));
318
326
  });
319
327
 
320
328
  const unmountResponseStart = requestManager.events.onResponseStartById<Request>(requestId, (data) => {
321
329
  const enriched = { ...data, mutationContext };
322
- options?.onResponseStart?.(enriched);
323
- $hooks.__emit("onResponseStart", enriched);
330
+ runUserCode(() => options?.onResponseStart?.(enriched));
331
+ runUserCode(() => $hooks.__emit("onResponseStart", enriched));
324
332
  });
325
333
 
326
334
  const unmountUpload = requestManager.events.onUploadProgressById<Request>(requestId, (data) => {
327
335
  const enriched = { ...data, mutationContext };
328
- options?.onUploadProgress?.(enriched);
329
- $hooks.__emit("onUploadProgress", enriched);
336
+ runUserCode(() => options?.onUploadProgress?.(enriched));
337
+ runUserCode(() => $hooks.__emit("onUploadProgress", enriched));
330
338
  });
331
339
 
332
340
  const unmountDownload = requestManager.events.onDownloadProgressById<Request>(requestId, (data) => {
333
341
  const enriched = { ...data, mutationContext };
334
- options?.onDownloadProgress?.(enriched);
335
- $hooks.__emit("onDownloadProgress", enriched);
342
+ runUserCode(() => options?.onDownloadProgress?.(enriched));
343
+ runUserCode(() => $hooks.__emit("onDownloadProgress", enriched));
336
344
  });
337
345
 
338
346
  // When resolved
@@ -351,8 +359,8 @@ export const sendRequest = async <Request extends RequestInstance>(
351
359
  }
352
360
  isDelivered = true;
353
361
 
354
- options?.onResponse?.(enrichedValues);
355
- $hooks.__emit("onResponse", enrichedValues);
362
+ runUserCode(() => options?.onResponse?.(enrichedValues));
363
+ runUserCode(() => $hooks.__emit("onResponse", enrichedValues));
356
364
  resolve(data);
357
365
 
358
366
  // Unmount Listeners
@@ -373,7 +381,7 @@ export const sendRequest = async <Request extends RequestInstance>(
373
381
  else {
374
382
  const data = mapping || response;
375
383
  const { success } = data;
376
- handleResponse(success, data as ResponseType<any, any, ExtractAdapterType<Request>>);
384
+ handleResponse(success, data);
377
385
  }
378
386
  });
379
387
 
@@ -389,8 +397,8 @@ export const sendRequest = async <Request extends RequestInstance>(
389
397
  }
390
398
 
391
399
  const enriched = { ...data, mutationContext };
392
- options?.onRemove?.(enriched);
393
- $hooks.__emit("onRemove", enriched);
400
+ runUserCode(() => options?.onRemove?.(enriched));
401
+ runUserCode(() => $hooks.__emit("onRemove", enriched));
394
402
  resolve({
395
403
  data: null,
396
404
  status: null,
@@ -1,5 +1,7 @@
1
1
  import Emitter from "events";
2
2
 
3
+ import { runUserCode } from "./error.utils";
4
+
3
5
  const getListenName = (event: string | symbol) => `listen_${String(event)}`;
4
6
 
5
7
  export class EventEmitter extends Emitter {
@@ -17,8 +19,13 @@ export class EventEmitter extends Emitter {
17
19
  params.push(isTriggeredExternally);
18
20
  }
19
21
 
20
- this.emitCallbacks?.forEach((callback) => callback(...params));
21
- return super.emit(...params);
22
+ this.emitCallbacks?.forEach((callback) => runUserCode(() => callback(...params)));
23
+
24
+ // Every listener gets the event - a throwing one can't keep it from the listeners added after it
25
+ const listeners = this.rawListeners(type);
26
+ listeners.forEach((listener) => runUserCode(() => listener.call(this, ...params.slice(1))));
27
+
28
+ return listeners.length > 0;
22
29
  }
23
30
 
24
31
  onEmit = (callback: (event: string, data: any, isTriggeredExternally?: true) => void) => {
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Callbacks, listeners, plugins and optimistic handlers are the code of the user running inside of the request
3
+ * lifecycle. Their error can't break it, and it can't get lost either - it is thrown from a timer, outside of the
4
+ * lifecycle, so it reaches the error handlers of the environment (`window.onerror`, `uncaughtException`).
5
+ * @internal
6
+ * @param error value thrown by the user code
7
+ */
8
+ export const throwOutsideLifecycle = (error: unknown): void => {
9
+ setTimeout(() => {
10
+ throw error;
11
+ });
12
+ };
13
+
14
+ /**
15
+ * Runs the code of the user in the middle of the request lifecycle. When it throws, the lifecycle goes on
16
+ * and the error is thrown outside of it.
17
+ * @internal
18
+ * @param callback code of the user to run
19
+ * @returns `true` when the callback finished, `false` when it threw
20
+ */
21
+ export const runUserCode = (callback: VoidFunction): boolean => {
22
+ try {
23
+ callback();
24
+ return true;
25
+ } catch (error) {
26
+ throwOutsideLifecycle(error);
27
+ return false;
28
+ }
29
+ };
@@ -1,2 +1,3 @@
1
+ export * from "./error.utils";
1
2
  export * from "./uuid.utils";
2
3
  export * from "./emitter.utils";