@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,3 +1,24 @@
1
+ import type { ResponseErrorType, ResponseSuccessType, ResponseType } from "adapter";
2
+ import type { ClientInstance } from "client";
3
+ import { Time } from "constants/time.constants";
4
+ import type { MockerConfigType, MockResponseType } from "mocker";
5
+ import type {
6
+ ExtractAdapterType,
7
+ ExtractClientAdapterType,
8
+ ExtractClientGlobalError,
9
+ ExtractEndpointType,
10
+ ExtractParamsType,
11
+ ExtractPayloadType,
12
+ ExtractQueryParamsType,
13
+ EmptyTypes,
14
+ ExtractAdapterMethodType,
15
+ ExtractAdapterOptionsType,
16
+ HydrateDataType,
17
+ SyncOrAsync,
18
+ } from "types";
19
+
20
+ import type { RequestHooks } from "./request.hooks";
21
+ import { createRequestHooks } from "./request.hooks";
1
22
  /* eslint-disable max-lines */
2
23
  import type {
3
24
  RequestSendOptionsType,
@@ -15,27 +36,7 @@ import type {
15
36
  RetryOnErrorCallbackType,
16
37
  OptimisticCallback,
17
38
  } from "./request.types";
18
- import type { RequestHooks } from "./request.hooks";
19
- import { createRequestHooks } from "./request.hooks";
20
39
  import { mapResponseForSend, sendRequest, scopeKey } from "./request.utils";
21
- import type { ClientInstance } from "client";
22
- import type { ResponseErrorType, ResponseSuccessType, ResponseType } from "adapter";
23
- import type {
24
- ExtractAdapterType,
25
- ExtractClientAdapterType,
26
- ExtractClientGlobalError,
27
- ExtractEndpointType,
28
- ExtractParamsType,
29
- ExtractPayloadType,
30
- ExtractQueryParamsType,
31
- EmptyTypes,
32
- ExtractAdapterMethodType,
33
- ExtractAdapterOptionsType,
34
- HydrateDataType,
35
- SyncOrAsync,
36
- } from "types";
37
- import { Time } from "constants/time.constants";
38
- import type { MockerConfigType, MockResponseType } from "mocker";
39
40
 
40
41
  type ClientAdapterOptions<C extends ClientInstance> = ExtractAdapterOptionsType<ExtractClientAdapterType<C>>;
41
42
  type ClientAdapterMethod<C extends ClientInstance> = ExtractAdapterMethodType<ExtractClientAdapterType<C>>;
@@ -76,13 +77,13 @@ export class Request<
76
77
  MutationContext = undefined,
77
78
  > {
78
79
  endpoint: Endpoint;
79
- headers?: HeadersInit;
80
+ headers?: HeadersInit = undefined;
80
81
  auth: boolean;
81
82
  method: ClientAdapterMethod<Client>;
82
83
  params: ExtractUrlParams<Endpoint> | EmptyTypes;
83
84
  payload: PayloadType<Payload>;
84
85
  queryParams: QueryParams | EmptyTypes;
85
- options?: ClientAdapterOptions<Client> | undefined;
86
+ options?: ClientAdapterOptions<Client> | undefined = undefined;
86
87
  cancelable: boolean;
87
88
  retry: number;
88
89
  retryTime: number;
@@ -111,23 +112,37 @@ export class Request<
111
112
 
112
113
  isMockerEnabled = false;
113
114
 
115
+ static readonly OPTIONAL_FIELDS = [
116
+ "unstable_mock",
117
+ "unstable_payloadMapper",
118
+ "unstable_requestMapper",
119
+ "unstable_responseMapper",
120
+ "retryOnError",
121
+ "optimistic",
122
+ ] as const;
123
+
124
+ // The `= undefined` initializers below are load-bearing. Metro (React Native) compiles
125
+ // class properties in loose mode, which drops field declarations that have no initializer,
126
+ // and the SDK proxy relies on an `in` check to tell request properties apart from deeper
127
+ // API path segments (see OPTIONAL_REQUEST_FIELDS in sdk/sdk.ts).
114
128
  unstable_mock?: {
115
129
  fn: (options: {
116
130
  request: RequestInstance;
117
131
  requestId: string;
118
132
  }) => MockResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>;
119
133
  config: MockerConfigType;
120
- };
134
+ } = undefined;
121
135
  /** @internal */
122
- unstable_payloadMapper?: PayloadMapperType<Payload>;
136
+ unstable_payloadMapper?: PayloadMapperType<Payload> = undefined;
123
137
  /** @internal */
124
- unstable_requestMapper?: RequestMapper<any, any>;
138
+ unstable_requestMapper?: RequestMapper<any, any> = undefined;
125
139
  /** @internal */
126
- unstable_responseMapper?: ResponseMapper<this, ResponseSuccessType<any, any> | ResponseErrorType<any, any>>;
140
+ unstable_responseMapper?: ResponseMapper<this, ResponseSuccessType<any, any> | ResponseErrorType<any, any>> =
141
+ undefined;
127
142
  /** @internal */
128
- retryOnError?: RetryOnErrorCallbackType<RequestInstance>;
143
+ retryOnError?: RetryOnErrorCallbackType<RequestInstance> = undefined;
129
144
  /** @internal */
130
- optimistic?: OptimisticCallback<RequestInstance, any>;
145
+ optimistic?: OptimisticCallback<RequestInstance, any> = undefined;
131
146
 
132
147
  unstable_hasParams: HasParams = false as HasParams;
133
148
  unstable_hasPayload: HasPayload = false as HasPayload;
@@ -204,28 +219,34 @@ export class Request<
204
219
  this.updatedQueryKey = initialRequestConfiguration?.updatedQueryKey ?? false;
205
220
  }
206
221
 
222
+ /** Set the request headers. Returns a cloned request with the new headers applied. */
207
223
  public setHeaders = (headers: HeadersInit) => {
208
224
  return this.clone({ headers });
209
225
  };
210
226
 
227
+ /** Set whether authentication interceptors should run for this request. */
211
228
  public setAuth = (auth: boolean) => {
212
229
  return this.clone({ auth });
213
230
  };
214
231
 
232
+ /** Set the URL path parameters (e.g., `:userId`). */
215
233
  public setParams = <P extends ExtractParamsType<this>>(params: P) => {
216
234
  return this.clone<HasPayload, P extends null ? false : true, HasQuery>({ params });
217
235
  };
218
236
 
237
+ /** Set the request body payload. */
219
238
  public setPayload = <P extends Payload>(payload: P) => {
220
239
  return this.clone<P extends null ? false : true, HasParams, HasQuery>({
221
240
  payload,
222
241
  });
223
242
  };
224
243
 
244
+ /** Set the query parameters appended to the URL. */
225
245
  public setQueryParams = (queryParams: QueryParams) => {
226
246
  return this.clone<HasPayload, HasParams, true>({ queryParams });
227
247
  };
228
248
 
249
+ /** Set adapter-specific options (e.g., axios config, fetch init). */
229
250
  public setOptions = (options: ClientAdapterOptions<Client>) => {
230
251
  return this.clone<HasPayload, HasParams, true>({ options });
231
252
  };
@@ -242,14 +263,17 @@ export class Request<
242
263
  return cloned;
243
264
  };
244
265
 
266
+ /** Set whether in-flight requests with the same abort key are cancelled when a new one is dispatched. */
245
267
  public setCancelable = (cancelable: boolean) => {
246
268
  return this.clone({ cancelable });
247
269
  };
248
270
 
271
+ /** Set the number of retry attempts on failure. */
249
272
  public setRetry = (retry: ClientRequestOptions<Endpoint, Client>["retry"]) => {
250
273
  return this.clone({ retry });
251
274
  };
252
275
 
276
+ /** Set the delay in milliseconds between retry attempts. */
253
277
  public setRetryTime = (retryTime: ClientRequestOptions<Endpoint, Client>["retryTime"]) => {
254
278
  return this.clone({ retryTime });
255
279
  };
@@ -293,53 +317,65 @@ export class Request<
293
317
  >;
294
318
  };
295
319
 
320
+ /** Set how long (in ms) the response remains in cache before being garbage collected. */
296
321
  public setCacheTime = (cacheTime: ClientRequestOptions<Endpoint, Client>["cacheTime"]) => {
297
322
  return this.clone({ cacheTime });
298
323
  };
299
324
 
325
+ /** Set whether this request should use the cache. */
300
326
  public setCache = (cache: ClientRequestOptions<Endpoint, Client>["cache"]) => {
301
327
  return this.clone({ cache });
302
328
  };
303
329
 
330
+ /** Set how long (in ms) cached data is considered fresh before triggering a revalidation. */
304
331
  public setStaleTime = (staleTime: ClientRequestOptions<Endpoint, Client>["staleTime"]) => {
305
332
  return this.clone({ staleTime });
306
333
  };
307
334
 
335
+ /** Set whether the request should be queued and executed sequentially rather than immediately. */
308
336
  public setQueued = (queued: boolean) => {
309
337
  return this.clone({ queued });
310
338
  };
311
339
 
340
+ /** Override the abort key used to cancel this request. */
312
341
  public setAbortKey = (abortKey: string) => {
313
342
  this.updatedAbortKey = true;
314
343
  return this.clone({ abortKey });
315
344
  };
316
345
 
346
+ /** Override the cache key used to store/retrieve the response. */
317
347
  public setCacheKey = (cacheKey: string) => {
318
348
  this.updatedCacheKey = true;
319
349
  return this.clone({ cacheKey });
320
350
  };
321
351
 
352
+ /** Override the query key that identifies this request in the dispatcher queue. */
322
353
  public setQueryKey = (queryKey: string) => {
323
354
  this.updatedQueryKey = true;
324
355
  return this.clone({ queryKey });
325
356
  };
326
357
 
358
+ /** Enable or disable request deduplication. When enabled, concurrent identical requests share a single response. */
327
359
  public setDeduplicate = (deduplicate: boolean) => {
328
360
  return this.clone({ deduplicate });
329
361
  };
330
362
 
363
+ /** Set the time window (in ms) during which identical requests are deduplicated. */
331
364
  public setDeduplicateTime = (deduplicateTime: number) => {
332
365
  return this.clone({ deduplicateTime });
333
366
  };
334
367
 
368
+ /** Mark the request as used (prevents automatic refetching in hooks). */
335
369
  public setUsed = (used: boolean) => {
336
370
  return this.clone({ used });
337
371
  };
338
372
 
373
+ /** Set whether the request should be stored in the offline queue when there is no network connection. */
339
374
  public setOffline = (offline: boolean) => {
340
375
  return this.clone({ offline });
341
376
  };
342
377
 
378
+ /** Attach a mock handler to this request. When mocking is enabled, the handler is called instead of the real adapter. */
343
379
  public setMock = (
344
380
  fn: (options: {
345
381
  request: Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
@@ -354,12 +390,14 @@ export class Request<
354
390
  return this;
355
391
  };
356
392
 
393
+ /** Remove any attached mock handler and disable mocking for this request. */
357
394
  public clearMock = () => {
358
395
  this.unstable_mock = undefined;
359
396
  this.isMockerEnabled = false;
360
397
  return this;
361
398
  };
362
399
 
400
+ /** Enable or disable the mocker for this request without removing the mock handler. */
363
401
  public setMockingEnabled = (isMockerEnabled: boolean) => {
364
402
  this.isMockerEnabled = isMockerEnabled;
365
403
  return this;
@@ -373,7 +411,7 @@ export class Request<
373
411
  public setPayloadMapper = <MappedPayload extends any | Promise<any>>(
374
412
  payloadMapper: (data: Payload) => MappedPayload,
375
413
  ) => {
376
- const cloned = this.clone<HasPayload, HasParams, HasQuery>(undefined);
414
+ const cloned = this.clone<HasPayload, HasParams, HasQuery>();
377
415
 
378
416
  cloned.unstable_payloadMapper = payloadMapper as typeof this.unstable_payloadMapper;
379
417
 
@@ -386,7 +424,7 @@ export class Request<
386
424
  * @returns new request
387
425
  */
388
426
  public setRequestMapper = <NewRequest extends RequestInstance>(requestMapper: RequestMapper<this, NewRequest>) => {
389
- const cloned = this.clone<HasPayload, HasParams, HasQuery>(undefined);
427
+ const cloned = this.clone<HasPayload, HasParams, HasQuery>();
390
428
 
391
429
  cloned.unstable_requestMapper = requestMapper;
392
430
 
@@ -425,13 +463,14 @@ export class Request<
425
463
  let stringEndpoint = String(endpoint);
426
464
  if (params) {
427
465
  Object.entries(params).forEach(([key, value]) => {
428
- stringEndpoint = stringEndpoint.replace(new RegExp(`:${key}`, "g"), String(value));
466
+ stringEndpoint = stringEndpoint.replaceAll(new RegExp(`:${key}`, "g"), String(value));
429
467
  });
430
468
  }
431
469
 
432
470
  return stringEndpoint as Endpoint;
433
471
  };
434
472
 
473
+ /** Serialize the request configuration into a plain JSON object for persistence or transfer. */
435
474
  public toJSON(): RequestJSON<this> {
436
475
  return {
437
476
  requestOptions: this.requestOptions as unknown as RequestOptionsType<
@@ -473,6 +512,7 @@ export class Request<
473
512
  };
474
513
  }
475
514
 
515
+ /** Create a new request instance with optional configuration overrides. Used internally by all setter methods. */
476
516
  public clone<
477
517
  NewData extends true | false = HasPayload,
478
518
  NewParams extends true | false = HasParams,
@@ -537,6 +577,7 @@ export class Request<
537
577
  return cloned;
538
578
  }
539
579
 
580
+ /** Abort all in-flight requests sharing this request's abort key. */
540
581
  public abort = () => {
541
582
  const { requestManager } = this.client;
542
583
  requestManager.abortByKey(scopeKey(this.abortKey, this.scope));
@@ -544,6 +585,7 @@ export class Request<
544
585
  return this.clone();
545
586
  };
546
587
 
588
+ /** Extract the current cache data for this request into a portable hydration payload (useful for SSR). */
547
589
  public dehydrate = (config?: {
548
590
  /** in case of using adapter without cache we can provide response to dehydrate */
549
591
  response?: ResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>;
@@ -561,7 +603,7 @@ export class Request<
561
603
  staleTime: this.staleTime,
562
604
  cacheKey: this.cacheKey,
563
605
  scope: this.scope,
564
- timestamp: +new Date(),
606
+ timestamp: Date.now(),
565
607
  hydrated: true,
566
608
  cache: true,
567
609
  response,
@@ -582,7 +624,7 @@ export class Request<
582
624
  staleTime: this.staleTime,
583
625
  cacheKey: this.cacheKey,
584
626
  scope: this.scope,
585
- timestamp: +new Date(),
627
+ timestamp: Date.now(),
586
628
  hydrated: true,
587
629
  cache: true,
588
630
  response: {
@@ -667,7 +709,7 @@ export class Request<
667
709
  * ```
668
710
  */
669
711
  public send: RequestSendType<this> = async (options?: RequestSendOptionsType<this>) => {
670
- const { dispatcherType, cachePolicy = "network-only", ...configuration } = options || {};
712
+ const { dispatcherType: _dispatcherType, cachePolicy = "network-only", ...configuration } = options || {};
671
713
 
672
714
  const request = this.clone(configuration) as unknown as this;
673
715
 
@@ -698,6 +740,7 @@ export class Request<
698
740
  return sendRequest(request, sendRequestOptions);
699
741
  };
700
742
 
743
+ /** Reconstruct a Request instance from a previously serialized JSON representation. */
701
744
  static fromJSON = <
702
745
  NewResponse,
703
746
  NewPayload,
@@ -1,3 +1,6 @@
1
+ import type { RequestResponseType, ResponseSuccessType, ResponseErrorType } from "adapter";
2
+ import type { ClientInstance } from "client";
3
+ import type { RequestEventType, RequestProgressEventType, RequestResponseEventType } from "managers";
1
4
  /* eslint-disable @typescript-eslint/no-shadow */
2
5
  import type {
3
6
  NullableKeys,
@@ -17,10 +20,8 @@ import type {
17
20
  ExtractAdapterMethodType,
18
21
  TypeWithDefaults,
19
22
  } from "types";
23
+
20
24
  import type { Request } from "./request";
21
- import type { RequestResponseType, ResponseSuccessType, ResponseErrorType } from "adapter";
22
- import type { RequestEventType, RequestProgressEventType, RequestResponseEventType } from "managers";
23
- import type { ClientInstance } from "client";
24
25
 
25
26
  // Instance
26
27
 
@@ -36,6 +37,38 @@ export type RequestInstanceProperties = {
36
37
  hasPayload?: boolean;
37
38
  };
38
39
 
40
+ /**
41
+ * The **constraint** form of a Request type. Mindset: "any Request that matches this partial shape".
42
+ *
43
+ * Use `RequestInstance` when you are writing a **reusable abstraction** that accepts requests from
44
+ * the outside - generic helpers (`<T extends RequestInstance>`), reusable UI components / hooks,
45
+ * `sdk.$configure({...})` callbacks, mocking utilities, interceptors, return types, etc.
46
+ *
47
+ * Unspecified generic parameters default to `any` **on purpose**: an omitted field means
48
+ * "I do not care about that field, the caller picks anything". This is exactly what you want
49
+ * for a constraint - any concrete `Request` satisfies it. Partial constraints work too:
50
+ * `RequestInstance<{ response: User[] }>` accepts every request that returns `User[]`,
51
+ * regardless of payload, params, queryParams, error, etc.
52
+ *
53
+ * For describing a **single endpoint** inside an SDK schema, use {@link RequestModel} instead.
54
+ * `RequestModel` uses safe non-`any` defaults (`unknown`, `undefined`, `Error`, `string`, `false`)
55
+ * so omitted fields stay strict instead of silently collapsing to `any`.
56
+ *
57
+ * @example
58
+ * ```ts
59
+ * // Reusable component: accepts any request whose response is User[]
60
+ * function UserList<T extends RequestInstance<{ response: User[] }>>(props: { request: T }) {
61
+ * // ...
62
+ * }
63
+ *
64
+ * // sdk.$configure callback: accepts any request the SDK happens to dispatch
65
+ * sdk.$configure({
66
+ * "users.$get": (request: RequestInstance) => request.setMock(() => ({ data: [] })),
67
+ * });
68
+ * ```
69
+ *
70
+ * @see {@link RequestModel} - definition counterpart for SDK schema modeling.
71
+ */
39
72
  export type RequestInstance<
40
73
  RequestProperties extends RequestInstanceProperties = {
41
74
  response?: any;
@@ -57,6 +90,75 @@ export type RequestInstance<
57
90
  any
58
91
  >;
59
92
 
93
+ /**
94
+ * The **definition** form of a Request type. Mindset: "**this** specific endpoint".
95
+ *
96
+ * Use `RequestModel` when you are **defining** a request inside an SDK schema or a request
97
+ * factory. Unlike {@link RequestInstance}, every unspecified field stays strict instead of
98
+ * falling back to `any` - because in a definition, an omitted field means "**there is no
99
+ * payload / no query / no params here**", not "anything goes". The type system will reject
100
+ * mismatches at the call site instead of silently erasing them.
101
+ *
102
+ * The `client` field is also injected automatically by `createSdk(client)` at the SDK boundary,
103
+ * so you never need to repeat it inside schema declarations.
104
+ *
105
+ * ### Defaults for omitted fields
106
+ *
107
+ * | Field | Default | Why |
108
+ * | ----------------- | ---------------- | ---------------------------------------------------------------------- |
109
+ * | `response` | `unknown` | Forces narrowing in consumer code; never silently widened. |
110
+ * | `payload` | `undefined` | "No body declared." `.setData()` is required for typed bodies. |
111
+ * | `queryParams` | `undefined` | Same as payload. |
112
+ * | `error` | `Error` | Sensible default; override per-endpoint when the API has a known shape.|
113
+ * | `endpoint` | `string` | Allows literal narrowing without erasure. Pass a string literal. |
114
+ * | `client` | `ClientInstance` | Injected by `createSdk(client)`; you do not need to set this manually. |
115
+ * | `hasPayload` | `false` | "Caller must call `.setData()`." Override only when payload is bound. |
116
+ * | `hasParams` | `false` | Same as `hasPayload` for params. |
117
+ * | `hasQueryParams` | `false` | Same as `hasPayload` for query params. |
118
+ * | `mutationContext` | `undefined` | Optional context; default is "no context". |
119
+ *
120
+ * @example
121
+ * ```ts
122
+ * // Schema describes shape only - client is injected by createSdk(client).
123
+ * type ApiSchema = {
124
+ * users: {
125
+ * $get: RequestModel<{
126
+ * response: User[];
127
+ * endpoint: "/users";
128
+ * }>;
129
+ * $userId: {
130
+ * $get: RequestModel<{
131
+ * response: User;
132
+ * endpoint: "/users/:userId";
133
+ * }>;
134
+ * };
135
+ * };
136
+ * };
137
+ * ```
138
+ *
139
+ * @see {@link RequestInstance} - constraint counterpart for accepting any Request.
140
+ */
141
+ export type RequestModel<
142
+ RequestProperties extends RequestInstanceProperties = {
143
+ response?: unknown;
144
+ payload?: undefined;
145
+ queryParams?: undefined;
146
+ error?: Error;
147
+ client?: ClientInstance;
148
+ },
149
+ > = Request<
150
+ TypeWithDefaults<RequestProperties, "response", unknown>,
151
+ TypeWithDefaults<RequestProperties, "payload", undefined>,
152
+ TypeWithDefaults<RequestProperties, "queryParams", undefined>,
153
+ TypeWithDefaults<RequestProperties, "error", Error>,
154
+ TypeWithDefaults<RequestProperties, "endpoint", string>,
155
+ TypeWithDefaults<RequestProperties, "client", ClientInstance>,
156
+ TypeWithDefaults<RequestProperties, "hasPayload", false>,
157
+ TypeWithDefaults<RequestProperties, "hasParams", false>,
158
+ TypeWithDefaults<RequestProperties, "hasQueryParams", false>,
159
+ undefined
160
+ >;
161
+
60
162
  // Progress
61
163
  export type ProgressEventType = { total: number; loaded: number };
62
164
 
@@ -108,7 +210,7 @@ export type RequestJSON<Request extends RequestInstance> = {
108
210
  */
109
211
  export type RequestOptionsType<GenericEndpoint, AdapterOptions, RequestMethods = HttpMethodsType> = {
110
212
  /**
111
- * Determine the endpoint for request request
213
+ * Determine the endpoint for the request
112
214
  */
113
215
  endpoint: GenericEndpoint;
114
216
  /**
@@ -149,7 +251,7 @@ export type RequestOptionsType<GenericEndpoint, AdapterOptions, RequestMethods =
149
251
  */
150
252
  staleTime?: number;
151
253
  /**
152
- * Should the requests from this request be send one-by-one
254
+ * Should the requests be queued and sent one-by-one
153
255
  */
154
256
  queued?: boolean;
155
257
  /**
@@ -1,8 +1,9 @@
1
1
  import { getErrorMessage } from "adapter";
2
- import { HttpMethods } from "constants/http.constants";
3
2
  import type { AdapterInstance, ProgressType, RequestResponseType, ResponseType } from "adapter";
3
+ import { SAFE_HTTP_METHODS } from "constants/http.constants";
4
4
  import type { Dispatcher } from "dispatcher";
5
5
  import type { ExtractAdapterType, ExtractErrorType } from "types";
6
+
6
7
  import type {
7
8
  OptimisticCallbackResult,
8
9
  ProgressEventType,
@@ -17,18 +18,18 @@ export const scopeKey = (key: string, scope: string | null): string => {
17
18
 
18
19
  export const stringifyKey = (value: unknown): string => {
19
20
  try {
20
- if (typeof value === "string") return value;
21
- if (value === undefined || value === null) return "";
21
+ if (typeof value === "string") {return value;}
22
+ if (value === undefined || value === null) {return "";}
22
23
  const data = JSON.stringify(value);
23
- if (typeof data !== "string") throw new Error();
24
+ if (typeof data !== "string") {throw new TypeError();}
24
25
  return data;
25
- } catch (_) {
26
+ } catch {
26
27
  return "";
27
28
  }
28
29
  };
29
30
 
30
31
  export const getProgressValue = ({ loaded, total }: ProgressEventType): number => {
31
- if (!loaded || !total) return 0;
32
+ if (!loaded || !total) {return 0;}
32
33
  return Number(((loaded * 100) / total).toFixed(0));
33
34
  };
34
35
 
@@ -115,8 +116,8 @@ export const getRequestDispatcher = <Request extends RequestInstance>(
115
116
  dispatcherType: "auto" | "fetch" | "submit" = "auto",
116
117
  ): [Dispatcher<ExtractAdapterType<Request>>, isFetchDispatcher: boolean] => {
117
118
  const { fetchDispatcher, submitDispatcher } = request.client;
118
- const isGet = request.method === HttpMethods.GET;
119
- const isFetchDispatcher = (dispatcherType === "auto" && isGet) || dispatcherType === "fetch";
119
+ const isSafeRead = SAFE_HTTP_METHODS.includes(request.method as string);
120
+ const isFetchDispatcher = (dispatcherType === "auto" && isSafeRead) || dispatcherType === "fetch";
120
121
  const dispatcher = isFetchDispatcher ? fetchDispatcher : submitDispatcher;
121
122
 
122
123
  return [dispatcher, isFetchDispatcher];
@@ -152,17 +153,17 @@ export const sendRequest = async <Request extends RequestInstance>(
152
153
  client: request.client,
153
154
  payload: request.payload,
154
155
  });
155
- } catch (err) {
156
+ } catch (error) {
156
157
  return {
157
158
  data: null,
158
159
  error: new Error(
159
- `Optimistic callback failed: ${err instanceof Error ? err.message : err}`,
160
+ `Optimistic callback failed: ${error instanceof Error ? error.message : error}`,
160
161
  ) as unknown as ExtractErrorType<Request>,
161
162
  status: null,
162
163
  success: false,
163
164
  extra: client.adapter.defaultExtra,
164
- requestTimestamp: +new Date(),
165
- responseTimestamp: +new Date(),
165
+ requestTimestamp: Date.now(),
166
+ responseTimestamp: Date.now(),
166
167
  };
167
168
  }
168
169
  }
@@ -214,10 +215,10 @@ export const sendRequest = async <Request extends RequestInstance>(
214
215
 
215
216
  const handleResponse = (success: boolean, data: ResponseType<any, any, ExtractAdapterType<Request>>) => {
216
217
  // When going offline we can't handle the request as it will be postponed to later resolve
217
- if (!success && isOfflineStatus) return;
218
+ if (!success && isOfflineStatus) {return;}
218
219
 
219
220
  // When request is in retry mode we need to listen for retries end
220
- if (!success && willRetry) return;
221
+ if (!success && willRetry) {return;}
221
222
 
222
223
  options?.onResponse?.(enrichedValues);
223
224
  $hooks.__emit("onResponse", enrichedValues);
@@ -257,8 +258,8 @@ export const sendRequest = async <Request extends RequestInstance>(
257
258
  success: false,
258
259
  error: getErrorMessage("deleted") as unknown as ExtractErrorType<Request>,
259
260
  extra: request.client.adapter.defaultExtra,
260
- requestTimestamp: +new Date(),
261
- responseTimestamp: +new Date(),
261
+ requestTimestamp: Date.now(),
262
+ responseTimestamp: Date.now(),
262
263
  });
263
264
 
264
265
  // Unmount Listeners