@hyper-fetch/core 8.1.1 → 8.2.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 (166) hide show
  1. package/README.md +137 -52
  2. package/__tests__/e2e/e2e.advanced.spec.ts +7 -7
  3. package/__tests__/features/adapter/adapter.base.spec.ts +2 -1
  4. package/__tests__/features/adapter/adapter.bindings.spec.ts +4 -4
  5. package/__tests__/features/adapter/adapter.browser.spec.ts +0 -1
  6. package/__tests__/features/adapter/adapter.server.spec.ts +4 -5
  7. package/__tests__/features/adapter/adapter.utils.spec.ts +6 -7
  8. package/__tests__/features/cache/cache.base.spec.ts +7 -7
  9. package/__tests__/features/cache/cache.events.spec.ts +15 -15
  10. package/__tests__/features/cache/cache.garbage-collector.spec.ts +18 -18
  11. package/__tests__/features/cache/cache.lazy-storage.spec.ts +8 -8
  12. package/__tests__/features/cache/cache.modes.spec.ts +7 -6
  13. package/__tests__/features/cache/cache.scoping.spec.ts +12 -8
  14. package/__tests__/features/cache/cache.typescript.spec.ts +2 -2
  15. package/__tests__/features/cache/cache.utils.spec.ts +14 -14
  16. package/__tests__/features/client/client.auth.spec.ts +0 -1
  17. package/__tests__/features/client/client.base.spec.ts +2 -3
  18. package/__tests__/features/client/client.from-json.spec.ts +0 -1
  19. package/__tests__/features/client/client.hydration.spec.ts +5 -5
  20. package/__tests__/features/client/client.interceptor.spec.ts +3 -3
  21. package/__tests__/features/client/client.methods.spec.ts +5 -5
  22. package/__tests__/features/client/client.middleware.spec.ts +2 -2
  23. package/__tests__/features/client/client.utils.spec.ts +16 -15
  24. package/__tests__/features/dispatcher/dispatcher.base.spec.ts +3 -3
  25. package/__tests__/features/dispatcher/dispatcher.custom-storage.spec.ts +4 -5
  26. package/__tests__/features/dispatcher/dispatcher.events.spec.ts +4 -4
  27. package/__tests__/features/dispatcher/dispatcher.queue.spec.ts +13 -13
  28. package/__tests__/features/dispatcher/dispatcher.requests.spec.ts +10 -10
  29. package/__tests__/features/dispatcher/dispatcher.utils.spec.ts +35 -8
  30. package/__tests__/features/managers/app/app.manager.base.spec.ts +2 -3
  31. package/__tests__/features/managers/logger/logger.base.spec.ts +1 -2
  32. package/__tests__/features/managers/request/request.manager.base.spec.ts +8 -9
  33. package/__tests__/features/managers/request/request.manager.events.spec.ts +1 -2
  34. package/__tests__/features/mocker/mocker.base.spec.ts +6 -6
  35. package/__tests__/features/plugin/plugin.base.spec.ts +1 -2
  36. package/__tests__/features/request/request.cloning.spec.ts +0 -1
  37. package/__tests__/features/request/request.deduplicate-defaults.spec.ts +79 -0
  38. package/__tests__/features/request/request.retry-on-error.spec.ts +1 -2
  39. package/__tests__/features/request/request.sending.spec.ts +73 -24
  40. package/__tests__/features/request/request.setters.spec.ts +4 -3
  41. package/__tests__/features/request/request.typescript.spec.ts +0 -1
  42. package/__tests__/features/request/request.utils.spec.ts +1 -0
  43. package/__tests__/features/sdk/sdk.base.spec.ts +7 -12
  44. package/__tests__/features/sdk/sdk.configuration.spec.ts +5 -7
  45. package/__tests__/features/sdk/sdk.request-fields.spec.ts +80 -0
  46. package/__tests__/features/sdk/sdk.types.spec.ts +283 -0
  47. package/__tests__/shared/callbacks.shared.ts +1 -1
  48. package/__tests__/tsconfig.json +4 -17
  49. package/__tests__/utils/adapter.utils.ts +1 -2
  50. package/__tests__/utils/callbacks.utils.ts +1 -2
  51. package/__tests__/utils/dispatcher.utils.ts +1 -1
  52. package/__tests__/vitest.setup.ts +1 -1
  53. package/dist/adapter/adapter.d.ts +22 -5
  54. package/dist/adapter/adapter.d.ts.map +1 -1
  55. package/dist/adapter/adapter.types.d.ts +9 -1
  56. package/dist/adapter/adapter.types.d.ts.map +1 -1
  57. package/dist/adapter/adapter.utils.d.ts.map +1 -1
  58. package/dist/cache/cache.d.ts +6 -9
  59. package/dist/cache/cache.d.ts.map +1 -1
  60. package/dist/cache/cache.events.d.ts +7 -4
  61. package/dist/cache/cache.events.d.ts.map +1 -1
  62. package/dist/cache/cache.types.d.ts +1 -0
  63. package/dist/cache/cache.types.d.ts.map +1 -1
  64. package/dist/client/client.create.d.ts +1 -1
  65. package/dist/client/client.create.d.ts.map +1 -1
  66. package/dist/client/client.d.ts +8 -4
  67. package/dist/client/client.d.ts.map +1 -1
  68. package/dist/client/client.types.d.ts +1 -1
  69. package/dist/client/client.types.d.ts.map +1 -1
  70. package/dist/client/client.utils.d.ts.map +1 -1
  71. package/dist/constants/http.constants.d.ts +5 -1
  72. package/dist/constants/http.constants.d.ts.map +1 -1
  73. package/dist/constants/time.constants.d.ts.map +1 -1
  74. package/dist/dispatcher/dispatcher.d.ts +4 -4
  75. package/dist/dispatcher/dispatcher.d.ts.map +1 -1
  76. package/dist/dispatcher/dispatcher.events.d.ts +1 -1
  77. package/dist/dispatcher/dispatcher.events.d.ts.map +1 -1
  78. package/dist/dispatcher/dispatcher.utils.d.ts +1 -1
  79. package/dist/dispatcher/dispatcher.utils.d.ts.map +1 -1
  80. package/dist/http-adapter/http-adapter.constants.d.ts.map +1 -1
  81. package/dist/http-adapter/http-adapter.d.ts.map +1 -1
  82. package/dist/http-adapter/http-adapter.fetch.d.ts +2 -2
  83. package/dist/http-adapter/http-adapter.fetch.d.ts.map +1 -1
  84. package/dist/http-adapter/http-adapter.types.d.ts +2 -2
  85. package/dist/http-adapter/http-adapter.types.d.ts.map +1 -1
  86. package/dist/http-adapter/http-adapter.utils.d.ts.map +1 -1
  87. package/dist/index.mjs +2382 -2301
  88. package/dist/index.mjs.map +1 -1
  89. package/dist/managers/app/app.manager.constants.d.ts +1 -1
  90. package/dist/managers/app/app.manager.constants.d.ts.map +1 -1
  91. package/dist/managers/app/app.manager.d.ts +1 -1
  92. package/dist/managers/app/app.manager.d.ts.map +1 -1
  93. package/dist/managers/app/app.manager.events.d.ts +9 -0
  94. package/dist/managers/app/app.manager.events.d.ts.map +1 -1
  95. package/dist/managers/logger/logger.manager.d.ts +1 -1
  96. package/dist/managers/logger/logger.manager.d.ts.map +1 -1
  97. package/dist/managers/request/request.manager.d.ts.map +1 -1
  98. package/dist/managers/request/request.manager.events.d.ts +14 -3
  99. package/dist/managers/request/request.manager.events.d.ts.map +1 -1
  100. package/dist/mocker/mocker.types.d.ts +1 -0
  101. package/dist/mocker/mocker.types.d.ts.map +1 -1
  102. package/dist/plugin/plugin.d.ts +17 -1
  103. package/dist/plugin/plugin.d.ts.map +1 -1
  104. package/dist/plugin/plugin.types.d.ts +5 -4
  105. package/dist/plugin/plugin.types.d.ts.map +1 -1
  106. package/dist/request/request.d.ts +33 -4
  107. package/dist/request/request.d.ts.map +1 -1
  108. package/dist/request/request.hooks.d.ts +2 -2
  109. package/dist/request/request.hooks.d.ts.map +1 -1
  110. package/dist/request/request.types.d.ts +92 -5
  111. package/dist/request/request.types.d.ts.map +1 -1
  112. package/dist/request/request.utils.d.ts.map +1 -1
  113. package/dist/sdk/sdk.d.ts +25 -5
  114. package/dist/sdk/sdk.d.ts.map +1 -1
  115. package/dist/types/http.types.d.ts +1 -1
  116. package/dist/types/http.types.d.ts.map +1 -1
  117. package/dist/types/request.types.d.ts +2 -2
  118. package/dist/types/request.types.d.ts.map +1 -1
  119. package/dist/utils/emitter.utils.d.ts +1 -1
  120. package/dist/utils/emitter.utils.d.ts.map +1 -1
  121. package/package.json +8 -8
  122. package/src/adapter/adapter.bindings.ts +14 -14
  123. package/src/adapter/adapter.ts +28 -10
  124. package/src/adapter/adapter.types.ts +10 -1
  125. package/src/adapter/adapter.utils.ts +5 -5
  126. package/src/cache/cache.events.ts +7 -5
  127. package/src/cache/cache.ts +14 -17
  128. package/src/cache/cache.types.ts +1 -0
  129. package/src/client/client.create.ts +1 -1
  130. package/src/client/client.ts +14 -9
  131. package/src/client/client.types.ts +2 -2
  132. package/src/client/client.utils.ts +3 -2
  133. package/src/constants/http.constants.ts +5 -0
  134. package/src/constants/time.constants.ts +1 -1
  135. package/src/dispatcher/dispatcher.events.ts +1 -2
  136. package/src/dispatcher/dispatcher.ts +13 -13
  137. package/src/dispatcher/dispatcher.utils.ts +10 -4
  138. package/src/http-adapter/http-adapter.constants.ts +1 -0
  139. package/src/http-adapter/http-adapter.fetch.ts +19 -9
  140. package/src/http-adapter/http-adapter.ts +2 -1
  141. package/src/http-adapter/http-adapter.types.ts +3 -2
  142. package/src/http-adapter/http-adapter.utils.ts +15 -11
  143. package/src/managers/app/app.manager.constants.ts +2 -1
  144. package/src/managers/app/app.manager.events.ts +9 -1
  145. package/src/managers/app/app.manager.ts +1 -1
  146. package/src/managers/app/app.manager.utils.ts +2 -2
  147. package/src/managers/logger/logger.manager.ts +1 -2
  148. package/src/managers/request/request.manager.events.ts +14 -12
  149. package/src/managers/request/request.manager.ts +4 -4
  150. package/src/mocker/mocker.ts +2 -2
  151. package/src/mocker/mocker.types.ts +1 -0
  152. package/src/plugin/plugin.ts +17 -1
  153. package/src/plugin/plugin.types.ts +5 -4
  154. package/src/request/request.hooks.ts +6 -5
  155. package/src/request/request.ts +77 -34
  156. package/src/request/request.types.ts +107 -5
  157. package/src/request/request.utils.ts +17 -16
  158. package/src/sdk/sdk.ts +79 -23
  159. package/src/types/http.types.ts +1 -1
  160. package/src/types/request.types.ts +3 -2
  161. package/src/utils/emitter.utils.ts +1 -1
  162. package/src/utils/uuid.utils.ts +1 -1
  163. package/tsconfig.json +30 -2
  164. package/vite.config.ts +14 -20
  165. package/.eslintrc.cjs +0 -12
  166. package/tsconfig.base.json +0 -7
@@ -1,6 +1,4 @@
1
1
  import type { AdapterInstance, ResponseType } from "adapter";
2
- import type { ResponseDetailsType, LoggerMethods } from "managers";
3
- import type { ClientInstance } from "client";
4
2
  import type {
5
3
  CacheOptionsType,
6
4
  CacheAsyncStorageType,
@@ -10,6 +8,8 @@ import type {
10
8
  RequestCacheType,
11
9
  } from "cache";
12
10
  import { getCacheData, getCacheEvents } from "cache";
11
+ import type { ClientInstance } from "client";
12
+ import type { ResponseDetailsType, LoggerMethods } from "managers";
13
13
  import type { RequestInstance } from "request";
14
14
  import { Request, scopeKey } from "request";
15
15
  import type { ExtractAdapterType, ExtractErrorType, ExtractResponseType } from "types";
@@ -27,7 +27,7 @@ export class Cache<Adapter extends AdapterInstance> {
27
27
  public events: ReturnType<typeof getCacheEvents>;
28
28
 
29
29
  public storage: CacheStorageType;
30
- public lazyStorage?: CacheAsyncStorageType;
30
+ public lazyStorage?: CacheAsyncStorageType = undefined;
31
31
  public version: string;
32
32
  public garbageCollectors = new Map<string, ReturnType<typeof setTimeout>>();
33
33
  private logger: LoggerMethods;
@@ -44,6 +44,7 @@ export class Cache<Adapter extends AdapterInstance> {
44
44
  this.lazyStorage = lazyStorage;
45
45
  }
46
46
 
47
+ /** Initialize the cache with a client reference, set up logging, and start garbage collection. */
47
48
  initialize = (client: ClientInstance<{ adapter: Adapter }>) => {
48
49
  this.client = client;
49
50
  this.logger = client.loggerManager.initialize(client, "Cache");
@@ -126,8 +127,6 @@ export class Cache<Adapter extends AdapterInstance> {
126
127
  * Update the cache data with partial response data
127
128
  * @param request
128
129
  * @param partialResponse
129
- * @param isTriggeredExtrenally - informs whether an update was triggered due to internal logic or externally, e.g.
130
- * via plugin.
131
130
  * @returns
132
131
  */
133
132
  update = <Request extends RequestCacheType<RequestInstance>>(
@@ -173,7 +172,7 @@ export class Cache<Adapter extends AdapterInstance> {
173
172
  keys = (): string[] => {
174
173
  const values = this.storage.keys();
175
174
 
176
- return Array.from(values);
175
+ return [...values];
177
176
  };
178
177
 
179
178
  /**
@@ -198,11 +197,11 @@ export class Cache<Adapter extends AdapterInstance> {
198
197
  * It emits invalidation event for each matching cacheKey and sets staleTime to 0 to indicate out of time cache
199
198
  * @param key - cacheKey or Request instance or RegExp for partial matching
200
199
  */
201
- invalidate = (cacheKeys: string | RegExp | RequestInstance | Array<string | RegExp | RequestInstance>) => {
200
+ invalidate = (cacheKeys: string | RegExp | RequestInstance | (string | RegExp | RequestInstance)[]) => {
202
201
  this.logger.debug({ title: "Revalidating cache element", type: "system", extra: { cacheKeys } });
203
202
 
204
203
  const onInvalidate = (key: string | RegExp | RequestInstance) => {
205
- const keys = Array.from(this.storage.keys());
204
+ const keys = [...this.storage.keys()];
206
205
  const handleInvalidation = (invalidateStorageKey: string, notifyCacheKey: string = invalidateStorageKey) => {
207
206
  const value = this.storage.get(invalidateStorageKey);
208
207
  if (value) {
@@ -221,7 +220,7 @@ export class Cache<Adapter extends AdapterInstance> {
221
220
  handleInvalidation(scopeKey(key.cacheKey, key.scope), key.cacheKey);
222
221
  } else if (typeof key === "string") {
223
222
  handleInvalidation(key);
224
- } else if (keys.length) {
223
+ } else if (keys.length > 0) {
225
224
  keys.forEach((entityKey) => {
226
225
  if (key.test(entityKey)) {
227
226
  handleInvalidation(entityKey);
@@ -250,7 +249,7 @@ export class Cache<Adapter extends AdapterInstance> {
250
249
  // No data in lazy storage
251
250
  const hasLazyData = this.lazyStorage && data;
252
251
  if (hasLazyData) {
253
- const now = +new Date();
252
+ const now = Date.now();
254
253
  const isNewestData = syncData ? syncData.responseTimestamp < data.responseTimestamp : true;
255
254
  const isStaleData = data.staleTime <= now - data.responseTimestamp;
256
255
  const isValidLazyData = data.version === this.version;
@@ -273,8 +272,7 @@ export class Cache<Adapter extends AdapterInstance> {
273
272
  };
274
273
 
275
274
  /**
276
- * Used to receive keys from sync storage and lazy storage
277
- * @param cacheKey
275
+ * Used to receive keys from lazy storage only
278
276
  */
279
277
  getLazyKeys = async () => {
280
278
  const keys = (await this.lazyStorage?.keys()) || [];
@@ -283,13 +281,12 @@ export class Cache<Adapter extends AdapterInstance> {
283
281
  };
284
282
 
285
283
  /**
286
- * Used to receive keys from sync storage and lazy storage
287
- * @param cacheKey
284
+ * Used to receive deduplicated keys from both sync storage and lazy storage
288
285
  */
289
286
  getAllKeys = async () => {
290
287
  const keys = await this.lazyStorage?.keys();
291
- const asyncKeys = Array.from(keys || []);
292
- const syncKeys = Array.from(this.storage.keys());
288
+ const asyncKeys = [...keys || []];
289
+ const syncKeys = [...this.storage.keys()];
293
290
 
294
291
  return [...new Set([...asyncKeys, ...syncKeys])];
295
292
  };
@@ -308,7 +305,7 @@ export class Cache<Adapter extends AdapterInstance> {
308
305
 
309
306
  // Garbage collect
310
307
  if (cacheData) {
311
- const timeLeft = cacheData.cacheTime + cacheData.responseTimestamp - +new Date();
308
+ const timeLeft = cacheData.cacheTime + cacheData.responseTimestamp - Date.now();
312
309
  // null
313
310
  if (cacheData.cacheTime === null) {
314
311
  this.logger.debug({ title: "Cache time is null", type: "system", extra: { cacheKey } });
@@ -2,6 +2,7 @@ import type { AdapterInstance, ResponseType } from "adapter";
2
2
  import type { ResponseDetailsType } from "managers";
3
3
  import type { RequestInstance } from "request";
4
4
 
5
+ /** Configuration options for the Cache instance. */
5
6
  export type CacheOptionsType = {
6
7
  /**
7
8
  * Assign your custom sync storage
@@ -1,7 +1,7 @@
1
- import type { TypeWithDefaults } from "types";
2
1
  import type { ClientErrorType, ClientOptionsType } from "client";
3
2
  import { Client } from "client";
4
3
  import type { HttpAdapterType } from "http-adapter";
4
+ import type { TypeWithDefaults } from "types";
5
5
 
6
6
  export type ClientGenericType = {
7
7
  error?: ClientErrorType;
@@ -1,6 +1,5 @@
1
1
  import type { AdapterInstance, ResponseType } from "adapter";
2
- import type { HttpAdapterType } from "http-adapter";
3
- import { parseResponse, HttpAdapter } from "http-adapter";
2
+ import { Cache } from "cache";
4
3
  import type {
5
4
  ClientErrorType,
6
5
  ClientInstance,
@@ -10,14 +9,14 @@ import type {
10
9
  RequestInterceptorType,
11
10
  ResponseInterceptorType,
12
11
  } from "client";
13
- import { Cache } from "cache";
14
12
  import { Dispatcher } from "dispatcher";
13
+ import type { HttpAdapterType } from "http-adapter";
14
+ import { parseResponse, HttpAdapter } from "http-adapter";
15
+ import type { LogLevel } from "managers";
16
+ import { AppManager, LoggerManager, RequestManager } from "managers";
15
17
  import type { PluginInstance, PluginMethodParameters, PluginMethods } from "plugin";
16
18
  import type { RequestInstance, RequestJSON, RequestOptionsType } from "request";
17
19
  import { getRequestKey, getSimpleKey, Request, scopeKey } from "request";
18
- import type { LogLevel } from "managers";
19
- import { AppManager, LoggerManager, RequestManager } from "managers";
20
- import { interceptRequest, interceptResponse, resolveClientMode } from "./client.utils";
21
20
  import type {
22
21
  EmptyTypes,
23
22
  TypeWithDefaults,
@@ -32,6 +31,8 @@ import type {
32
31
  } from "types";
33
32
  import { getUniqueRequestId } from "utils";
34
33
 
34
+ import { interceptRequest, interceptResponse, resolveClientMode } from "./client.utils";
35
+
35
36
  /**
36
37
  * **Client** is a class that allows you to configure the connection with the server and then use it to create
37
38
  * requests. It allows you to set global defaults for the requests configuration, query params configuration.
@@ -232,7 +233,7 @@ export class Client<
232
233
  };
233
234
 
234
235
  /**
235
- * Method for removing listeners on request.
236
+ * Method for removing response interceptors.
236
237
  * */
237
238
  removeOnResponseInterceptors = (
238
239
  callbacks: ResponseInterceptorType<ClientInstance, any, null | GlobalErrorType>[],
@@ -270,7 +271,7 @@ export class Client<
270
271
  };
271
272
 
272
273
  triggerPlugins = <Key extends keyof PluginMethods<Client>>(key: Key, data: PluginMethodParameters<Key, Client>) => {
273
- if (!this.plugins.length) {
274
+ if (this.plugins.length === 0) {
274
275
  return this;
275
276
  }
276
277
 
@@ -285,18 +286,22 @@ export class Client<
285
286
  * Key setters
286
287
  */
287
288
 
289
+ /** Set a custom mapper that generates the abort key used to cancel in-flight requests. */
288
290
  setAbortKeyMapper = (callback: (request: RequestInstance) => string) => {
289
291
  this.unstable_abortKeyMapper = callback;
290
292
  return this;
291
293
  };
294
+ /** Set a custom mapper that generates the cache key used to store and retrieve cached responses. */
292
295
  setCacheKeyMapper = (callback: (request: RequestInstance) => string) => {
293
296
  this.unstable_cacheKeyMapper = callback;
294
297
  return this;
295
298
  };
299
+ /** Set a custom mapper that generates the query key used to identify requests in the dispatcher queue. */
296
300
  setQueryKeyMapper = (callback: (request: RequestInstance) => string) => {
297
301
  this.unstable_queryKeyMapper = callback;
298
302
  return this;
299
303
  };
304
+ /** Set a custom mapper that generates the unique request ID for deduplication and tracking. */
300
305
  setRequestIdMapper = (callback: (request: RequestInstance) => string) => {
301
306
  this.unstable_requestIdMapper = callback;
302
307
  return this;
@@ -404,7 +409,7 @@ export class Client<
404
409
  options?: Partial<HydrationOptions> | ((item: HydrateDataType) => Partial<HydrationOptions>),
405
410
  ) => {
406
411
  hydrationData?.forEach((item) => {
407
- if (!item) return;
412
+ if (!item) {return;}
408
413
 
409
414
  const { cacheKey, scope, response, ...fallbackOptions } = item;
410
415
  const defaults = {
@@ -1,7 +1,7 @@
1
- /* eslint-disable @typescript-eslint/no-shadow */
2
- import type { RequestInstance } from "request";
3
1
  import type { AdapterInstance, ResponseType } from "adapter";
4
2
  import type { Client } from "client";
3
+ /* eslint-disable @typescript-eslint/no-shadow */
4
+ import type { RequestInstance } from "request";
5
5
  import type { ExtendRequest, ExtractClientAdapterType, TypeWithDefaults } from "types";
6
6
 
7
7
  export type ClientErrorType = Record<string, any> | string;
@@ -1,6 +1,7 @@
1
1
  import type { ResponseType } from "adapter";
2
2
  import type { RequestInstance } from "request";
3
3
  import type { ExtendRequest, ExtractClientAdapterType } from "types";
4
+
4
5
  import type {
5
6
  ClientInstance,
6
7
  ClientMode,
@@ -30,7 +31,7 @@ export const interceptRequest = async (interceptors: RequestInterceptorType[], r
30
31
  for (const interceptor of interceptors) {
31
32
  // eslint-disable-next-line no-await-in-loop
32
33
  newRequest = (await interceptor(request)) as RequestInstance;
33
- if (!newRequest) throw new Error("Request modifier must return request");
34
+ if (!newRequest) {throw new Error("Request modifier must return request");}
34
35
  }
35
36
  }
36
37
  return newRequest;
@@ -47,7 +48,7 @@ export const interceptResponse = async <GlobalErrorType, Client extends ClientIn
47
48
  for (const interceptor of interceptors) {
48
49
  // eslint-disable-next-line no-await-in-loop
49
50
  newResponse = await interceptor(response, request);
50
- if (!newResponse) throw new Error("Response modifier must return data");
51
+ if (!newResponse) {throw new Error("Response modifier must return data");}
51
52
  }
52
53
  }
53
54
  return newResponse;
@@ -4,4 +4,9 @@ export enum HttpMethods {
4
4
  PUT = "PUT",
5
5
  PATCH = "PATCH",
6
6
  DELETE = "DELETE",
7
+ /** Safe, idempotent read with a request body (IETF draft-ietf-httpbis-safe-method-w-body). */
8
+ QUERY = "QUERY",
7
9
  }
10
+
11
+ /** Methods that are safe reads: routed to the fetch dispatcher and deduplicated by default. */
12
+ export const SAFE_HTTP_METHODS: string[] = [HttpMethods.GET, HttpMethods.QUERY];
@@ -7,5 +7,5 @@ export enum Time {
7
7
  MONTH_30 = 2.592e9,
8
8
  MONTH_31 = 2.6784e9,
9
9
  YEAR = 3.1536e10,
10
- YEAR_LEAP = 3.16224e10,
10
+ YEAR_LEAP = 3.162_24e10,
11
11
  }
@@ -1,5 +1,3 @@
1
- import type EventEmitter from "events";
2
-
3
1
  import type { QueueDataType } from "dispatcher";
4
2
  import {
5
3
  getDispatcherChangeKey,
@@ -9,6 +7,7 @@ import {
9
7
  getDispatcherDrainedKey,
10
8
  getDispatcherDrainedByKey,
11
9
  } from "dispatcher";
10
+ import type EventEmitter from "events";
12
11
  import type { RequestInstance } from "request";
13
12
 
14
13
  export const getDispatcherEvents = (emitter: EventEmitter) => ({
@@ -1,3 +1,6 @@
1
+ import type { AdapterInstance, RequestResponseType } from "adapter";
2
+ import { getErrorMessage } from "adapter";
3
+ import type { ClientInstance } from "client";
1
4
  import type {
2
5
  QueueDataType,
3
6
  DispatcherOptionsType,
@@ -7,13 +10,10 @@ import type {
7
10
  RunningRequestValueType,
8
11
  } from "dispatcher";
9
12
  import { getRequestType, canRetryRequest, getDispatcherEvents, DispatcherMode } from "dispatcher";
10
- import type { ClientInstance } from "client";
11
- import { EventEmitter } from "utils";
12
13
  import type { ResponseDetailsType, LoggerMethods } from "managers";
13
14
  import type { RequestInstance, RequestJSON } from "request";
14
15
  import { Request, scopeKey } from "request";
15
- import type { AdapterInstance, RequestResponseType } from "adapter";
16
- import { getErrorMessage } from "adapter";
16
+ import { EventEmitter } from "utils";
17
17
 
18
18
  /**
19
19
  * Dispatcher controls and manages the requests that are going to be executed with adapter. It manages them based on the options provided with request.
@@ -109,10 +109,10 @@ export class Dispatcher<Adapter extends AdapterInstance> {
109
109
  };
110
110
 
111
111
  /**
112
- * Return all
112
+ * Return all queue keys currently tracked by the dispatcher storage
113
113
  */
114
114
  getQueuesKeys = () => {
115
- return Array.from(this.storage.keys());
115
+ return [...this.storage.keys()];
116
116
  };
117
117
 
118
118
  /**
@@ -217,7 +217,7 @@ export class Dispatcher<Adapter extends AdapterInstance> {
217
217
  const isStopped = queue && queue.stopped;
218
218
  const isOffline = !this.client.appManager.isOnline;
219
219
  const isConcurrent = !queueItem?.request.queued;
220
- const isInactive = !runningRequests.length;
220
+ const isInactive = runningRequests.length === 0;
221
221
  const isEmpty = !queueItem;
222
222
 
223
223
  // When there are no requests to flush, when its stopped, there is running request
@@ -309,7 +309,7 @@ export class Dispatcher<Adapter extends AdapterInstance> {
309
309
  * Get currently running requests from all queryKeys
310
310
  */
311
311
  getAllRunningRequests = () => {
312
- return Array.from(this.runningRequests.values()).flat();
312
+ return [...this.runningRequests.values()].flat();
313
313
  };
314
314
 
315
315
  /**
@@ -342,7 +342,7 @@ export class Dispatcher<Adapter extends AdapterInstance> {
342
342
  * Get the value based on the currently running requests
343
343
  */
344
344
  hasRunningRequests = (queryKey: string) => {
345
- return !!this.getRunningRequests(queryKey).length;
345
+ return this.getRunningRequests(queryKey).length > 0;
346
346
  };
347
347
 
348
348
  /**
@@ -350,7 +350,7 @@ export class Dispatcher<Adapter extends AdapterInstance> {
350
350
  */
351
351
  hasRunningRequest = (queryKey: string, requestId: string) => {
352
352
  const runningRequests = this.getRunningRequests(queryKey);
353
- return !!runningRequests.find((req) => req.requestId === requestId);
353
+ return !!runningRequests.some((req) => req.requestId === requestId);
354
354
  };
355
355
 
356
356
  /**
@@ -420,7 +420,7 @@ export class Dispatcher<Adapter extends AdapterInstance> {
420
420
  const requestId = this.client.unstable_requestIdMapper(request);
421
421
  return {
422
422
  requestId,
423
- timestamp: +new Date(),
423
+ timestamp: Date.now(),
424
424
  request,
425
425
  retries: 0,
426
426
  stopped: false,
@@ -491,7 +491,7 @@ export class Dispatcher<Adapter extends AdapterInstance> {
491
491
  const queue = this.getQueue(queryKey);
492
492
  const queueItem = queue.requests.find((req) => req.requestId === requestId);
493
493
 
494
- if (!queueItem) return;
494
+ if (!queueItem) {return;}
495
495
 
496
496
  queue.requests = queue.requests.filter((req) => req.requestId !== requestId);
497
497
  this.storage.set(queryKey, queue);
@@ -512,7 +512,7 @@ export class Dispatcher<Adapter extends AdapterInstance> {
512
512
  resolved: queueItem.resolved,
513
513
  });
514
514
 
515
- if (!queue.requests.length) {
515
+ if (queue.requests.length === 0) {
516
516
  this.client.triggerPlugins("onDispatcherQueueDrained", { queue, dispatcher: this });
517
517
  this.events.emitDrained(queue);
518
518
  }
@@ -1,6 +1,6 @@
1
- import type { RequestInstance } from "request";
2
1
  import type { ResolvedQueueItemType } from "dispatcher";
3
2
  import { DispatcherMode } from "dispatcher";
3
+ import type { RequestInstance } from "request";
4
4
 
5
5
  // Events
6
6
 
@@ -41,14 +41,17 @@ export const canRetryRequest = (currentRetries: number, retry: number | undefine
41
41
 
42
42
  const isInDeduplicateRange = (request: RequestInstance, latestRequest: ResolvedQueueItemType) => {
43
43
  if (request.deduplicateTime) {
44
- return +new Date() - latestRequest.timestamp <= request.deduplicateTime;
44
+ return Date.now() - latestRequest.timestamp <= request.deduplicateTime;
45
45
  }
46
46
  return true;
47
47
  };
48
48
 
49
49
  export const getRequestType = (request: RequestInstance, latestRequest: ResolvedQueueItemType | undefined) => {
50
- const { queued, cancelable, deduplicate } = request;
50
+ const { queued, cancelable, deduplicate, used } = request;
51
51
  const canDeduplicate = latestRequest ? isInDeduplicateRange(request, latestRequest) : false;
52
+ // Only join requests that are genuinely still ongoing. A resolved item already emitted its
53
+ // response (a late joiner would wait forever), and a stopped item may never fire at all.
54
+ const isOngoing = latestRequest ? !latestRequest.resolved && !latestRequest.stopped : false;
52
55
 
53
56
  if (queued) {
54
57
  return DispatcherMode.ONE_BY_ONE;
@@ -56,7 +59,10 @@ export const getRequestType = (request: RequestInstance, latestRequest: Resolved
56
59
  if (cancelable) {
57
60
  return DispatcherMode.PREVIOUS_CANCELED;
58
61
  }
59
- if (canDeduplicate && deduplicate) {
62
+ // A request marked with setUsed(true) is an intentional resend, like the auth interceptor
63
+ // retrying after a token refresh. Deduplicating it against the original in-flight request
64
+ // would deadlock: the retry would wait for a response that is blocked on the interceptor.
65
+ if (canDeduplicate && isOngoing && deduplicate && !used) {
60
66
  return DispatcherMode.DEDUPLICATED;
61
67
  }
62
68
  return DispatcherMode.ALL_AT_ONCE;
@@ -1,4 +1,5 @@
1
1
  import { Time } from "constants/time.constants";
2
+
2
3
  import type { HttpAdapterExtraType } from "./http-adapter.types";
3
4
 
4
5
  export const defaultTimeout = Time.SEC * 5;
@@ -1,10 +1,11 @@
1
- import { Adapter } from "../adapter/adapter";
2
- import { HttpMethods } from "constants/http.constants";
3
- import type { HttpMethodsType, HttpStatusType } from "types";
4
1
  import type { QueryParamsType } from "adapter";
2
+ import { HttpMethods, SAFE_HTTP_METHODS } from "constants/http.constants";
3
+ import type { HttpMethodsType, HttpStatusType } from "types";
4
+
5
+ import { Adapter } from "../adapter/adapter";
6
+ import { defaultTimeout, xhrExtra } from "./http-adapter.constants";
5
7
  import type { HttpAdapterExtraType, FetchAdapterOptionsType } from "./http-adapter.types";
6
8
  import { parseErrorResponse, parseResponse, stringifyQueryParams } from "./http-adapter.utils";
7
- import { defaultTimeout, xhrExtra } from "./http-adapter.constants";
8
9
 
9
10
  const defaultExtra = xhrExtra;
10
11
 
@@ -25,6 +26,15 @@ export const getAdapter = () =>
25
26
  systemErrorExtra: defaultExtra,
26
27
  })
27
28
  .setQueryParamsMapper(stringifyQueryParams)
29
+ // Safe reads (GET, QUERY) deduplicate by default: concurrent identical requests collapse
30
+ // into one network call. Explicit `deduplicate` in request options still wins.
31
+ .setRequestDefaults((options) => {
32
+ const method = options.method ?? HttpMethods.GET;
33
+ if (SAFE_HTTP_METHODS.includes(method)) {
34
+ return { deduplicate: true };
35
+ }
36
+ return {};
37
+ })
28
38
  .setFetcher(
29
39
  async ({
30
40
  request,
@@ -93,7 +103,7 @@ export const getAdapter = () =>
93
103
 
94
104
  const response = await fetch(fullUrl, init);
95
105
 
96
- if (timeoutId) clearTimeout(timeoutId);
106
+ if (timeoutId) {clearTimeout(timeoutId);}
97
107
 
98
108
  onResponseStart();
99
109
 
@@ -128,7 +138,7 @@ export const getAdapter = () =>
128
138
  while (true) {
129
139
  // eslint-disable-next-line no-await-in-loop
130
140
  const { done, value } = await reader.read();
131
- if (done) break;
141
+ if (done) {break;}
132
142
  chunks.push(value);
133
143
  receivedLength += value.length;
134
144
  onResponseProgress({ total: contentLength || receivedLength, loaded: receivedLength } as ProgressEvent);
@@ -157,8 +167,8 @@ export const getAdapter = () =>
157
167
  onError({ error, status, extra });
158
168
  }
159
169
  }
160
- } catch (err: any) {
161
- if (timeoutId) clearTimeout(timeoutId);
170
+ } catch (error: any) {
171
+ if (timeoutId) {clearTimeout(timeoutId);}
162
172
  unmountListener();
163
173
 
164
174
  if (controller?.signal?.aborted) {
@@ -168,7 +178,7 @@ export const getAdapter = () =>
168
178
  return;
169
179
  }
170
180
 
171
- onError({ error: err, status: 0, extra: defaultExtra });
181
+ onError({ error, status: 0, extra: defaultExtra });
172
182
  }
173
183
  },
174
184
  );
@@ -1,6 +1,7 @@
1
- import { getAdapter } from "./http-adapter.fetch";
2
1
  import type { HttpAdapterType } from "http-adapter/http-adapter.types";
3
2
 
3
+ import { getAdapter } from "./http-adapter.fetch";
4
+
4
5
  export const HttpAdapter = (): HttpAdapterType => {
5
6
  return getAdapter();
6
7
  };
@@ -1,5 +1,6 @@
1
- import type { HttpMethodsType, HttpStatusType } from "../types";
2
1
  import type { DeclareAdapterType, QueryParamsType, QueryParamType } from "adapter";
2
+
3
+ import type { HttpMethodsType, HttpStatusType } from "../types";
3
4
  import type { stringifyQueryParams } from "./http-adapter.utils";
4
5
  /**
5
6
  * Base Adapter
@@ -83,7 +84,7 @@ export type QueryStringifyOptionsType = {
83
84
  export type BufferEncoding =
84
85
  | "ascii"
85
86
  | "utf8"
86
- | "utf-8"
87
+ | "utf8"
87
88
  | "utf16le"
88
89
  | "ucs2"
89
90
  | "ucs-2"
@@ -1,9 +1,10 @@
1
1
  import type { QueryParamsType, QueryParamType, QueryParamValuesType } from "adapter";
2
2
  import { getErrorMessage } from "adapter";
3
+ import { stringifyDefaultOptions } from "client";
3
4
  import type { RequestInstance } from "request";
4
5
  import type { ExtractErrorType, EmptyTypes } from "types";
6
+
5
7
  import type { BufferEncoding, QueryStringifyOptionsType } from "./http-adapter.types";
6
- import { stringifyDefaultOptions } from "client";
7
8
 
8
9
  // Utils
9
10
 
@@ -28,7 +29,7 @@ export const getResponseHeaders = (headersString: string): Record<string, string
28
29
  export const parseResponse = (response: string | unknown) => {
29
30
  try {
30
31
  return JSON.parse(response as string);
31
- } catch (err) {
32
+ } catch {
32
33
  return response;
33
34
  }
34
35
  };
@@ -36,12 +37,15 @@ export const parseResponse = (response: string | unknown) => {
36
37
  export const handleResponse = (responseChunks: any[], responseType: string, responseEncoding: BufferEncoding) => {
37
38
  const bufferedResponse = Buffer.concat(responseChunks);
38
39
  switch (responseType) {
39
- case "arraybuffer":
40
+ case "arraybuffer": {
40
41
  return bufferedResponse;
41
- case "json":
42
+ }
43
+ case "json": {
42
44
  return parseResponse(bufferedResponse.toString(responseEncoding));
43
- default:
45
+ }
46
+ default: {
44
47
  return bufferedResponse.toString(responseEncoding);
48
+ }
45
49
  }
46
50
  };
47
51
 
@@ -73,7 +77,7 @@ const encodeValue = (
73
77
  { encode, strict }: Pick<QueryStringifyOptionsType, "encode" | "strict">,
74
78
  ): string => {
75
79
  if (encode && strict) {
76
- return encodeURIComponent(value).replace(/[!'()*]/g, (s) => `%${s.charCodeAt(0).toString(16).toUpperCase()}`);
80
+ return encodeURIComponent(value).replaceAll(/[!'()*]/g, (s) => `%${s.codePointAt(0)!.toString(16).toUpperCase()}`);
77
81
  }
78
82
  if (encode) {
79
83
  return encodeURIComponent(value);
@@ -103,7 +107,7 @@ const encodeParams = (key: string, value: QueryParamType, options: QueryStringif
103
107
  return `${encodeValue(key, options)}=${encodeValue(parsedValue(), options)}`;
104
108
  };
105
109
 
106
- const encodeArray = (key: string, array: Array<QueryParamValuesType>, options: QueryStringifyOptionsType): string => {
110
+ const encodeArray = (key: string, array: QueryParamValuesType[], options: QueryStringifyOptionsType): string => {
107
111
  const { arrayFormat, arraySeparator } = options;
108
112
 
109
113
  return array
@@ -121,15 +125,15 @@ const encodeArray = (key: string, array: Array<QueryParamValuesType>, options: Q
121
125
  break;
122
126
  }
123
127
  case "comma": {
124
- const keyValue = (!acc.length && `${encodeValue(key, options)}=`) || "";
128
+ const keyValue = (acc.length === 0 && `${encodeValue(key, options)}=`) || "";
125
129
  return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(",")];
126
130
  }
127
131
  case "separator": {
128
- const keyValue = (!acc.length && `${encodeValue(key, options)}=`) || "";
132
+ const keyValue = (acc.length === 0 && `${encodeValue(key, options)}=`) || "";
129
133
  return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(arraySeparator || "|")];
130
134
  }
131
135
  case "bracket-separator": {
132
- const keyValue = (!acc.length && `${encodeValue(key, options)}[]=`) || "";
136
+ const keyValue = (acc.length === 0 && `${encodeValue(key, options)}[]=`) || "";
133
137
  return [[...acc, `${keyValue}${encodeValue(String(value), options)}`].join(arraySeparator || "|")];
134
138
  }
135
139
  default: {
@@ -147,7 +151,7 @@ export const stringifyQueryParams = (
147
151
  queryParams: QueryParamsType | string | EmptyTypes,
148
152
  options: QueryStringifyOptionsType = stringifyDefaultOptions,
149
153
  ): string => {
150
- if (!queryParams || !Object.keys(queryParams).length) {
154
+ if (!queryParams || Object.keys(queryParams).length === 0) {
151
155
  return "";
152
156
  }
153
157
 
@@ -1,5 +1,6 @@
1
- import type { RequiredKeys } from "types";
2
1
  import type { AppManagerOptionsType } from "managers";
2
+ import type { RequiredKeys } from "types";
3
+
3
4
  import { onWindowEvent, onDocumentEvent } from "./app.manager.utils";
4
5
 
5
6
  export enum AppEvents {
@@ -1,32 +1,40 @@
1
1
  import type EventEmitter from "events";
2
-
3
2
  import { AppEvents } from "managers";
4
3
 
4
+ /** Create event emitters and listeners for application-level focus, blur, online, and offline state changes. */
5
5
  export const getAppManagerEvents = (emitter: EventEmitter) => ({
6
+ /** Emit when the application window gains focus */
6
7
  emitFocus: (): void => {
7
8
  emitter.emit(AppEvents.FOCUS);
8
9
  },
10
+ /** Emit when the application window loses focus */
9
11
  emitBlur: (): void => {
10
12
  emitter.emit(AppEvents.BLUR);
11
13
  },
14
+ /** Emit when the application transitions to online state */
12
15
  emitOnline: (): void => {
13
16
  emitter.emit(AppEvents.ONLINE);
14
17
  },
18
+ /** Emit when the application transitions to offline state */
15
19
  emitOffline: (): void => {
16
20
  emitter.emit(AppEvents.OFFLINE);
17
21
  },
22
+ /** Listen for focus events */
18
23
  onFocus: (callback: () => void): VoidFunction => {
19
24
  emitter.on(AppEvents.FOCUS, callback);
20
25
  return () => emitter.removeListener(AppEvents.FOCUS, callback);
21
26
  },
27
+ /** Listen for blur events */
22
28
  onBlur: (callback: () => void): VoidFunction => {
23
29
  emitter.on(AppEvents.BLUR, callback);
24
30
  return () => emitter.removeListener(AppEvents.BLUR, callback);
25
31
  },
32
+ /** Listen for online state transitions */
26
33
  onOnline: (callback: () => void): VoidFunction => {
27
34
  emitter.on(AppEvents.ONLINE, callback);
28
35
  return () => emitter.removeListener(AppEvents.ONLINE, callback);
29
36
  },
37
+ /** Listen for offline state transitions */
30
38
  onOffline: (callback: () => void): VoidFunction => {
31
39
  emitter.on(AppEvents.OFFLINE, callback);
32
40
  return () => emitter.removeListener(AppEvents.OFFLINE, callback);