@hyper-fetch/core 6.0.1 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/.eslintrc.json +8 -3
  2. package/README.md +5 -5
  3. package/dist/browser/index.js +3711 -0
  4. package/dist/browser/index.js.map +7 -0
  5. package/dist/index.d.ts +1669 -1091
  6. package/dist/index.js +3949 -0
  7. package/dist/index.js.map +7 -0
  8. package/package.json +16 -18
  9. package/src/adapter/adapter.bindings.ts +261 -165
  10. package/src/adapter/adapter.ts +480 -8
  11. package/src/adapter/adapter.types.ts +111 -139
  12. package/src/adapter/adapter.utils.ts +71 -25
  13. package/src/adapter/index.ts +1 -2
  14. package/src/cache/cache.events.ts +58 -14
  15. package/src/cache/cache.ts +158 -91
  16. package/src/cache/cache.types.ts +15 -25
  17. package/src/cache/cache.utils.ts +17 -10
  18. package/src/client/client.create.ts +17 -0
  19. package/src/client/client.ts +247 -266
  20. package/src/client/client.types.ts +43 -21
  21. package/src/client/client.utils.ts +7 -168
  22. package/src/client/index.ts +1 -0
  23. package/src/constants/http.constants.ts +6 -6
  24. package/src/constants/time.constants.ts +10 -10
  25. package/src/dispatcher/dispatcher.constants.ts +5 -5
  26. package/src/dispatcher/dispatcher.events.ts +85 -20
  27. package/src/dispatcher/dispatcher.ts +265 -199
  28. package/src/dispatcher/dispatcher.types.ts +6 -7
  29. package/src/dispatcher/dispatcher.utils.ts +26 -10
  30. package/src/http-adapter/http-adapter.browser.ts +101 -0
  31. package/src/http-adapter/http-adapter.constants.ts +8 -0
  32. package/src/http-adapter/http-adapter.server.ts +134 -0
  33. package/src/http-adapter/http-adapter.ts +11 -0
  34. package/src/http-adapter/http-adapter.types.ts +86 -0
  35. package/src/http-adapter/http-adapter.utils.ts +177 -0
  36. package/src/http-adapter/index.ts +4 -0
  37. package/src/index.ts +2 -1
  38. package/src/managers/app/app.manager.constants.ts +4 -4
  39. package/src/managers/app/app.manager.events.ts +12 -12
  40. package/src/managers/app/app.manager.ts +10 -7
  41. package/src/managers/app/app.manager.utils.ts +12 -2
  42. package/src/managers/logger/logger.manager.constants.ts +13 -18
  43. package/src/managers/logger/logger.manager.ts +37 -49
  44. package/src/managers/logger/logger.manager.types.ts +32 -21
  45. package/src/managers/logger/logger.manager.utils.ts +23 -17
  46. package/src/managers/request/request.manager.events.ts +222 -109
  47. package/src/managers/request/request.manager.ts +5 -2
  48. package/src/managers/request/request.manager.types.ts +35 -7
  49. package/src/managers/request/request.manager.utils.ts +29 -17
  50. package/src/mocker/mocker.ts +115 -81
  51. package/src/mocker/mocker.types.ts +29 -25
  52. package/src/plugin/index.ts +2 -0
  53. package/src/plugin/plugin.ts +159 -0
  54. package/src/plugin/plugin.types.ts +181 -0
  55. package/src/request/request.ts +371 -323
  56. package/src/request/request.types.ts +136 -145
  57. package/src/request/request.utils.ts +31 -30
  58. package/src/types/adapter.types.ts +63 -0
  59. package/src/types/client.types.ts +3 -3
  60. package/src/types/helpers.types.ts +16 -3
  61. package/src/types/hydration.types.ts +16 -0
  62. package/src/types/index.ts +3 -1
  63. package/src/types/request.types.ts +73 -0
  64. package/src/utils/emitter.utils.ts +52 -0
  65. package/src/utils/index.ts +1 -0
  66. package/src/utils/uuid.utils.ts +4 -2
  67. package/tsconfig.base.json +4 -5
  68. package/tsconfig.json +5 -4
  69. package/dist/browser/index.cjs.js +0 -2420
  70. package/dist/browser/index.cjs.js.map +0 -7
  71. package/dist/browser/index.esm.js +0 -2395
  72. package/dist/browser/index.esm.js.map +0 -7
  73. package/dist/index.cjs.js +0 -2579
  74. package/dist/index.cjs.js.map +0 -7
  75. package/dist/index.esm.js +0 -2474
  76. package/dist/index.esm.js.map +0 -7
  77. package/src/adapter/adapter.browser.ts +0 -100
  78. package/src/adapter/adapter.constants.ts +0 -8
  79. package/src/adapter/adapter.server.ts +0 -93
  80. package/src/effect/index.ts +0 -2
  81. package/src/effect/request.effect.ts +0 -31
  82. package/src/effect/request.effect.types.ts +0 -44
  83. package/src/types/fetch.types.ts +0 -50
package/dist/index.d.ts CHANGED
@@ -1,7 +1,10 @@
1
- import EventEmitter from 'events';
1
+ import EventEmitter$1 from 'events';
2
2
 
3
- type NegativeTypes = null | undefined;
4
- type NullableType<T> = T | NegativeTypes;
3
+ type Prettify<T> = {
4
+ [K in keyof T]: T[K];
5
+ } & {};
6
+ type EmptyTypes = null | undefined;
7
+ type NullableType<T> = T | EmptyTypes;
5
8
  type NullableKeys<T> = {
6
9
  [P in keyof T]-?: NullableType<T[P]>;
7
10
  };
@@ -9,241 +12,64 @@ type NonNullableKeys<T> = {
9
12
  [P in keyof T]-?: NonNullable<T[P]>;
10
13
  };
11
14
  type RequiredKeys<T> = {
12
- [P in keyof T]-?: Exclude<T[P], NegativeTypes>;
15
+ [P in keyof T]-?: Exclude<T[P], EmptyTypes>;
13
16
  };
17
+ type TypeWithDefaults<Types extends Record<string, any>, Key extends keyof Types, Value> = Key extends keyof Types ? Exclude<Types[Key], EmptyTypes | void | never> : Value;
18
+ type SyncOrAsync<T> = T | Promise<T>;
14
19
 
15
20
  type HttpMethodsType = "GET" | "POST" | "PUT" | "PATCH" | "DELETE";
16
21
  type HttpStatusType = number;
17
22
 
18
- declare const adapter: AdapterType;
19
-
20
- /**
21
- * App manager handles main application states - focus and online. Those two values can answer questions:
22
- * - Is the tab or current view instance focused and visible for user?
23
- * - Is our application online or offline?
24
- * With the app manager it is not a problem to get the valid answer for this question.
25
- *
26
- * @caution
27
- * Make sure to apply valid focus/online handlers for different environments like for example for native mobile applications.
28
- */
29
- declare class AppManager {
30
- options?: AppManagerOptionsType;
31
- emitter: EventEmitter;
32
- events: {
33
- emitFocus: () => void;
34
- emitBlur: () => void;
35
- emitOnline: () => void;
36
- emitOffline: () => void;
37
- onFocus: (callback: () => void) => VoidFunction;
38
- onBlur: (callback: () => void) => VoidFunction;
39
- onOnline: (callback: () => void) => VoidFunction;
40
- onOffline: (callback: () => void) => VoidFunction;
41
- };
42
- isBrowser: boolean;
43
- isOnline: boolean;
44
- isFocused: boolean;
45
- constructor(options?: AppManagerOptionsType);
46
- private setInitialFocus;
47
- private setInitialOnline;
48
- setFocused: (isFocused: boolean) => void;
49
- setOnline: (isOnline: boolean) => void;
50
- }
51
-
52
- type AppManagerOptionsType = {
53
- initiallyFocused?: boolean | (() => boolean | Promise<boolean>);
54
- initiallyOnline?: boolean | (() => boolean | Promise<boolean>);
55
- focusEvent?: (setFocused: (isFocused: boolean) => void) => void;
56
- onlineEvent?: (setOnline: (isOnline: boolean) => void) => void;
57
- };
58
-
59
- declare const hasWindow: () => boolean;
60
- declare const hasDocument: () => boolean;
61
- declare const onWindowEvent: <K extends keyof WindowEventMap>(key: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions | undefined) => void;
62
- declare const onDocumentEvent: <K extends keyof DocumentEventMap>(key: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions | undefined) => void;
63
-
64
- declare const getAppManagerEvents: (emitter: EventEmitter) => {
65
- emitFocus: () => void;
66
- emitBlur: () => void;
67
- emitOnline: () => void;
68
- emitOffline: () => void;
69
- onFocus: (callback: () => void) => VoidFunction;
70
- onBlur: (callback: () => void) => VoidFunction;
71
- onOnline: (callback: () => void) => VoidFunction;
72
- onOffline: (callback: () => void) => VoidFunction;
73
- };
74
-
75
- declare enum AppEvents {
76
- focus = "focus",
77
- blur = "blur",
78
- online = "online",
79
- offline = "offline"
80
- }
81
- declare const appManagerInitialOptions: RequiredKeys<AppManagerOptionsType>;
82
-
83
- /**
84
- * **Request Manager** is used to emit `request lifecycle events` like - request start, request end, upload and download progress.
85
- * It is also the place of `request aborting` system, here we store all the keys and controllers that are isolated for each client instance.
86
- */
87
- declare class RequestManager {
88
- emitter: EventEmitter;
89
- events: {
90
- emitLoading: (queueKey: string, requestId: string, values: RequestLoadingEventType) => void;
91
- emitRequestStart: (queueKey: string, requestId: string, details: RequestEventType<RequestInstance>) => void;
92
- emitResponseStart: (queueKey: string, requestId: string, details: RequestEventType<RequestInstance>) => void;
93
- emitUploadProgress: (queueKey: string, requestId: string, values: ProgressType, details: RequestEventType<RequestInstance>) => void;
94
- emitDownloadProgress: (queueKey: string, requestId: string, values: ProgressType, details: RequestEventType<RequestInstance>) => void;
95
- emitResponse: <Adapter extends AdapterInstance>(cacheKey: string, requestId: string, response: ResponseReturnType<unknown, unknown, Adapter>, details: ResponseDetailsType) => void;
96
- emitAbort: (abortKey: string, requestId: string, request: RequestInstance) => void;
97
- emitRemove: <T extends RequestInstance>(queueKey: string, requestId: string, details: RequestEventType<T>) => void;
98
- onLoading: (queueKey: string, callback: (values: RequestLoadingEventType) => void) => VoidFunction;
99
- onLoadingById: (requestId: string, callback: (values: RequestLoadingEventType) => void) => VoidFunction;
100
- onRequestStart: <T_1 extends RequestInstance>(queueKey: string, callback: (details: RequestEventType<T_1>) => void) => VoidFunction;
101
- onRequestStartById: <T_2 extends RequestInstance>(requestId: string, callback: (details: RequestEventType<T_2>) => void) => VoidFunction;
102
- onResponseStart: <T_3 extends RequestInstance>(queueKey: string, callback: (details: RequestEventType<T_3>) => void) => VoidFunction;
103
- onResponseStartById: <T_4 extends RequestInstance>(requestId: string, callback: (details: RequestEventType<T_4>) => void) => VoidFunction;
104
- onUploadProgress: <T_5 extends RequestInstance = RequestInstance>(queueKey: string, callback: (values: ProgressType, details: RequestEventType<T_5>) => void) => VoidFunction;
105
- onUploadProgressById: <T_6 extends RequestInstance = RequestInstance>(requestId: string, callback: (values: ProgressType, details: RequestEventType<T_6>) => void) => VoidFunction;
106
- onDownloadProgress: <T_7 extends RequestInstance = RequestInstance>(queueKey: string, callback: (values: ProgressType, details: RequestEventType<T_7>) => void) => VoidFunction;
107
- onDownloadProgressById: <T_8 extends RequestInstance = RequestInstance>(requestId: string, callback: (values: ProgressType, details: RequestEventType<T_8>) => void) => VoidFunction;
108
- onResponse: <Response_1, ErrorType, Adapter_1 extends AdapterInstance>(cacheKey: string, callback: (response: ResponseReturnType<Response_1, ErrorType, Adapter_1>, details: ResponseDetailsType) => void) => VoidFunction;
109
- onResponseById: <Response_2, ErrorType_1, Adapter_2 extends AdapterInstance>(requestId: string, callback: (response: ResponseReturnType<Response_2, ErrorType_1, Adapter_2>, details: ResponseDetailsType) => void) => VoidFunction;
110
- onAbort: (abortKey: string, callback: (request: RequestInstance) => void) => VoidFunction;
111
- onAbortById: (requestId: string, callback: (request: RequestInstance) => void) => VoidFunction;
112
- onRemove: <T_9 extends RequestInstance = RequestInstance>(queueKey: string, callback: (details: RequestEventType<T_9>) => void) => VoidFunction;
113
- onRemoveById: <T_10 extends RequestInstance = RequestInstance>(requestId: string, callback: (details: RequestEventType<T_10>) => void) => VoidFunction;
114
- };
115
- abortControllers: Map<string, Map<string, AbortController>>;
116
- addAbortController: (abortKey: string, requestId: string) => void;
117
- getAbortController: (abortKey: string, requestId: string) => AbortController;
118
- removeAbortController: (abortKey: string, requestId: string) => void;
119
- useAbortController: (abortKey: string, requestId: string) => void;
120
- abortByKey: (abortKey: string) => void;
121
- abortByRequestId: (abortKey: string, requestId: string) => void;
122
- abortAll: () => void;
123
- }
124
-
125
- declare const getLoadingEventKey: (key: string) => string;
126
- declare const getLoadingIdEventKey: (key: string) => string;
127
- declare const getRemoveEventKey: (key: string) => string;
128
- declare const getRemoveIdEventKey: (key: string) => string;
129
- declare const getAbortEventKey: (key: string) => string;
130
- declare const getAbortByIdEventKey: (key: string) => string;
131
- declare const getResponseEventKey: (key: string) => string;
132
- declare const getResponseIdEventKey: (key: string) => string;
133
- declare const getRequestStartEventKey: (key: string) => string;
134
- declare const getRequestStartIdEventKey: (key: string) => string;
135
- declare const getResponseStartEventKey: (key: string) => string;
136
- declare const getResponseStartIdEventKey: (key: string) => string;
137
- declare const getUploadProgressEventKey: (key: string) => string;
138
- declare const getUploadProgressIdEventKey: (key: string) => string;
139
- declare const getDownloadProgressEventKey: (key: string) => string;
140
- declare const getDownloadProgressIdEventKey: (key: string) => string;
141
-
142
- declare const getRequestManagerEvents: (emitter: EventEmitter) => {
143
- /**
144
- * Emiter
145
- */
146
- emitLoading: (queueKey: string, requestId: string, values: RequestLoadingEventType) => void;
147
- emitRequestStart: (queueKey: string, requestId: string, details: RequestEventType<RequestInstance>) => void;
148
- emitResponseStart: (queueKey: string, requestId: string, details: RequestEventType<RequestInstance>) => void;
149
- emitUploadProgress: (queueKey: string, requestId: string, values: ProgressType, details: RequestEventType<RequestInstance>) => void;
150
- emitDownloadProgress: (queueKey: string, requestId: string, values: ProgressType, details: RequestEventType<RequestInstance>) => void;
151
- emitResponse: <Adapter extends AdapterInstance>(cacheKey: string, requestId: string, response: ResponseReturnType<unknown, unknown, Adapter>, details: ResponseDetailsType) => void;
152
- emitAbort: (abortKey: string, requestId: string, request: RequestInstance) => void;
153
- emitRemove: <T extends RequestInstance>(queueKey: string, requestId: string, details: RequestEventType<T>) => void;
154
- /**
155
- * Listeners
156
- */
157
- onLoading: (queueKey: string, callback: (values: RequestLoadingEventType) => void) => VoidFunction;
158
- onLoadingById: (requestId: string, callback: (values: RequestLoadingEventType) => void) => VoidFunction;
159
- onRequestStart: <T_1 extends RequestInstance>(queueKey: string, callback: (details: RequestEventType<T_1>) => void) => VoidFunction;
160
- onRequestStartById: <T_2 extends RequestInstance>(requestId: string, callback: (details: RequestEventType<T_2>) => void) => VoidFunction;
161
- onResponseStart: <T_3 extends RequestInstance>(queueKey: string, callback: (details: RequestEventType<T_3>) => void) => VoidFunction;
162
- onResponseStartById: <T_4 extends RequestInstance>(requestId: string, callback: (details: RequestEventType<T_4>) => void) => VoidFunction;
163
- onUploadProgress: <T_5 extends RequestInstance = RequestInstance>(queueKey: string, callback: (values: ProgressType, details: RequestEventType<T_5>) => void) => VoidFunction;
164
- onUploadProgressById: <T_6 extends RequestInstance = RequestInstance>(requestId: string, callback: (values: ProgressType, details: RequestEventType<T_6>) => void) => VoidFunction;
165
- onDownloadProgress: <T_7 extends RequestInstance = RequestInstance>(queueKey: string, callback: (values: ProgressType, details: RequestEventType<T_7>) => void) => VoidFunction;
166
- onDownloadProgressById: <T_8 extends RequestInstance = RequestInstance>(requestId: string, callback: (values: ProgressType, details: RequestEventType<T_8>) => void) => VoidFunction;
167
- onResponse: <Response_1, ErrorType, Adapter_1 extends AdapterInstance>(cacheKey: string, callback: (response: ResponseReturnType<Response_1, ErrorType, Adapter_1>, details: ResponseDetailsType) => void) => VoidFunction;
168
- onResponseById: <Response_2, ErrorType_1, Adapter_2 extends AdapterInstance>(requestId: string, callback: (response: ResponseReturnType<Response_2, ErrorType_1, Adapter_2>, details: ResponseDetailsType) => void) => VoidFunction;
169
- onAbort: (abortKey: string, callback: (request: RequestInstance) => void) => VoidFunction;
170
- onAbortById: (requestId: string, callback: (request: RequestInstance) => void) => VoidFunction;
171
- onRemove: <T_9 extends RequestInstance = RequestInstance>(queueKey: string, callback: (details: RequestEventType<T_9>) => void) => VoidFunction;
172
- onRemoveById: <T_10 extends RequestInstance = RequestInstance>(requestId: string, callback: (details: RequestEventType<T_10>) => void) => VoidFunction;
173
- };
174
-
175
- type RequestLoadingEventType = {
176
- queueKey: string;
177
- requestId: string;
178
- loading: boolean;
179
- isRetry: boolean;
180
- isOffline: boolean;
181
- };
182
- type RequestEventType<T extends RequestInstance> = {
183
- requestId: string;
184
- request: T;
185
- };
186
- type ResponseDetailsType = {
187
- retries: number;
188
- timestamp: number;
189
- isCanceled: boolean;
190
- isOffline: boolean;
191
- };
192
- type RequestRemoveDataType = {
193
- queueKey: string;
194
- requestId: string;
195
- };
196
-
197
- /**
198
- * This class is used across the Hyper Fetch library to provide unified logging system with necessary setup per each client.
199
- * We can set up the logging level based on available values. This manager enable to initialize the logging instance per individual module
200
- * like Client, Request etc. Which can give you better feedback on the logging itself.
201
- */
202
- declare class LoggerManager {
203
- private client;
204
- private options?;
205
- logger: LoggerFunctionType;
206
- severity: SeverityType;
207
- emitter: EventEmitter;
208
- constructor(client: Pick<ClientInstance, "debug">, options?: LoggerOptionsType);
209
- setSeverity: (severity: SeverityType) => void;
210
- init: (module: string) => LoggerType;
211
- }
212
-
213
- declare const getTime: () => string;
214
- declare const logger: LoggerFunctionType;
23
+ type ExtractAdapterOptionsType<T> = T extends Adapter<infer O, any, any, any, any, any, any, any, any, any, any> ? O : never;
24
+ type ExtractAdapterMethodType<T> = T extends Adapter<any, infer M, any, any, any, any, any, any, any, any, any> ? M : never;
25
+ type ExtractAdapterStatusType<T> = T extends Adapter<any, any, infer S, any, any, any, any, any, any, any, any> ? S : never;
26
+ type ExtractAdapterExtraType<T> = T extends Adapter<any, any, any, infer A, any, any, any, any, any, any, any> ? A : never;
27
+ type ExtractAdapterQueryParamsType<T> = T extends Adapter<any, any, any, any, infer Q, any, any, any, any, any, any> ? Q : never;
28
+ type ExtractAdapterDefaultQueryParamsType<T> = T extends Adapter<any, any, any, any, any, infer Q, any, any, any, any, any> ? Q : never;
29
+ type ExtractAdapterEndpointType<T> = T extends Adapter<any, any, any, any, any, any, infer E, any, any, any, any> ? E : never;
30
+ type ExtractAdapterEndpointMapperType<T> = T extends Adapter<any, any, any, any, any, any, any, infer EM, any, any, any> ? EM : never;
31
+ type ExtractAdapterQueryParamsMapperType<T> = T extends Adapter<any, any, any, any, any, any, any, any, infer QPM, any, any> ? QPM : never;
32
+ type ExtractAdapterHeaderMapperType<T> = T extends Adapter<any, any, any, any, any, any, any, any, any, infer HM, any> ? HM : never;
33
+ type ExtractAdapterPayloadMapperType<T> = T extends Adapter<any, any, any, any, any, any, any, any, any, any, infer PM> ? PM : never;
34
+ type ExtractUnionAdapter<AdapterType extends AdapterInstance, Values extends {
35
+ method?: any;
36
+ options?: any;
37
+ status?: any;
38
+ extra?: any;
39
+ queryParams?: any;
40
+ endpointType?: any;
41
+ defaultQueryParams?: any;
42
+ }> = Extract<AdapterType, Adapter<Values["options"], Values["method"], Values["status"], Values["extra"], Values["queryParams"], Values["defaultQueryParams"], Values["endpointType"]>> extends AdapterInstance ? Extract<AdapterType, Adapter<Values["options"], Values["method"], Values["status"], Values["extra"], Values["queryParams"], Values["defaultQueryParams"], Values["endpointType"]>> : never;
215
43
 
216
- type SeverityType = 0 | 1 | 2 | 3;
217
- type LoggerType = Record<LoggerLevelType, (message: LoggerMessageType, ...extra: LoggerMessageType[]) => void>;
218
- type LoggerFunctionType = (log: LogType) => void;
219
- type LoggerOptionsType = {
220
- logger?: LoggerFunctionType;
221
- severity?: SeverityType;
222
- };
223
- type LogType = {
224
- module: string;
225
- level: LoggerLevelType;
226
- message: LoggerMessageType;
227
- extra?: LoggerMessageType[];
228
- enabled: boolean;
229
- severity: SeverityType;
230
- };
231
- type LoggerLevelType = "error" | "warning" | "info" | "debug";
232
- type LoggerMessageType = string | Record<string, unknown> | Array<unknown>;
233
- type LoggerRequestEventData = {
234
- requestId: string;
235
- request: RequestInstance;
236
- };
237
- type LoggerResponseEventData<Adapter extends AdapterInstance> = {
238
- requestId: string;
239
- request: RequestInstance;
240
- response: ResponseReturnType<unknown, unknown, Adapter>;
241
- details: ResponseDetailsType;
242
- };
44
+ type ExtractClientGlobalError<T extends ClientInstance> = T extends Client$1<infer P, any> ? P : never;
45
+ type ExtractClientAdapterType<T extends ClientInstance> = T extends Client$1<any, infer P> ? P : never;
243
46
 
244
- declare const loggerStyles: Record<LoggerLevelType, string>;
245
- declare const loggerIconLevels: Record<LoggerLevelType, string>;
246
- declare const severity: Record<LoggerLevelType, number>;
47
+ type ExtractAdapterResolvedType<T extends RequestInstance> = ResponseType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>;
48
+ type ExtractResponseType<T> = T extends Request<infer D, any, any, any, any, any, any, any, any> ? D : never;
49
+ type ExtractPayloadType<T> = T extends Request<any, infer D, any, any, any, any, any, any, any> ? D : never;
50
+ type ExtractQueryParamsType<T> = T extends Request<any, any, infer Q, any, any, any, any, any, any> ? Q : never;
51
+ type ExtractErrorType<T> = T extends Request<any, any, any, infer G, any, infer C, any, any, any> ? G | ExtractClientGlobalError<C> : never;
52
+ type ExtractGlobalErrorType<T> = T extends Request<any, any, any, any, any, infer C, any, any, any> ? ExtractClientGlobalError<C> : never;
53
+ type ExtractLocalErrorType<T> = T extends Request<any, any, any, infer E, any, any, any, any, any> ? E : never;
54
+ type ExtractParamsType<T> = T extends Request<any, any, any, any, infer E, any, any, any, any> ? E extends string ? ExtractRouteParams<E> : never : never;
55
+ type ExtractEndpointType<T> = T extends Request<any, any, any, any, infer E, any, any, any, any> ? E : never;
56
+ type ExtractClientType<T> = T extends Request<any, any, any, any, any, infer C, any, any, any> ? C : never;
57
+ type ExtractAdapterType<T> = T extends Request<any, any, any, any, any, infer C, any, any, any> ? ExtractClientAdapterType<C> : never;
58
+ type ExtractHasPayloadType<T> = T extends Request<any, any, any, any, any, any, infer D, any, any> ? D : never;
59
+ type ExtractHasParamsType<T> = T extends Request<any, any, any, any, any, any, any, infer P, any> ? P : never;
60
+ type ExtractHasQueryParamsType<T> = T extends Request<any, any, any, any, any, any, any, any, infer Q> ? Q : never;
61
+ type ExtendRequest<Req extends RequestInstance, Properties extends {
62
+ response?: any;
63
+ payload?: any;
64
+ queryParams?: any;
65
+ globalError?: any;
66
+ localError?: any;
67
+ endpoint?: ExtractAdapterEndpointType<ExtractAdapterType<Req>>;
68
+ client?: Client$1<any, any>;
69
+ hasData?: true | false;
70
+ hasParams?: true | false;
71
+ hasQuery?: true | false;
72
+ }> = Request<TypeWithDefaults<Properties, "response", ExtractResponseType<Req>>, TypeWithDefaults<Properties, "payload", ExtractPayloadType<Req>>, TypeWithDefaults<Properties, "queryParams", ExtractQueryParamsType<Req>>, TypeWithDefaults<Properties, "localError", ExtractLocalErrorType<Req>>, Properties["endpoint"] extends string ? Properties["endpoint"] : ExtractEndpointType<Req>, Properties["client"] extends ClientInstance ? Properties["client"] : ExtractClientType<Req>, Properties["hasData"] extends true ? true : ExtractHasPayloadType<Req>, Properties["hasParams"] extends true ? true : ExtractHasParamsType<Req>, Properties["hasQuery"] extends true ? true : ExtractHasQueryParamsType<Req>>;
247
73
 
248
74
  /**
249
75
  * Cache class handles the data exchange with the dispatchers.
@@ -252,37 +78,44 @@ declare const severity: Record<LoggerLevelType, number>;
252
78
  * Keys used to save the values are created dynamically on the Request class
253
79
  *
254
80
  */
255
- declare class Cache<C extends ClientInstance> {
256
- client: C;
257
- options?: CacheOptionsType;
81
+ declare class Cache<Adapter extends AdapterInstance> {
82
+ options?: CacheOptionsType | undefined;
258
83
  emitter: EventEmitter;
259
84
  events: ReturnType<typeof getCacheEvents>;
260
85
  storage: CacheStorageType;
261
86
  lazyStorage?: CacheAsyncStorageType;
262
- clearKey: string;
87
+ version: string;
263
88
  garbageCollectors: Map<string, NodeJS.Timeout>;
264
89
  private logger;
265
- constructor(client: C, options?: CacheOptionsType);
90
+ private client;
91
+ constructor(options?: CacheOptionsType | undefined);
92
+ initialize: (client: ClientInstance<{
93
+ adapter: Adapter;
94
+ }>) => this;
266
95
  /**
267
96
  * Set the cache data to the storage
268
97
  * @param request
269
98
  * @param response
270
99
  * @returns
271
100
  */
272
- set: <Request_1 extends RequestInstance>(request: RequestInstance | RequestJSON<any>, response: CacheMethodType<ResponseReturnType<ExtractResponseType<Request_1>, ExtractErrorType<Request_1>, ExtractAdapterType<Request_1>> & ResponseDetailsType>) => void;
101
+ set: <Request extends RequestCacheType<RequestInstance>>(request: Request, response: CacheSetState<ResponseType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>> & ResponseDetailsType> & {
102
+ hydrated?: boolean;
103
+ }) => void;
273
104
  /**
274
105
  * Update the cache data with partial response data
275
106
  * @param request
276
107
  * @param partialResponse
108
+ * @param isTriggeredExtrenally - informs whether an update was triggered due to internal logic or externally, e.g.
109
+ * via plugin.
277
110
  * @returns
278
111
  */
279
- update: <Request_1 extends RequestInstance>(request: RequestInstance | RequestJSON<RequestInstance>, partialResponse: CacheMethodType<Partial<ResponseReturnType<ExtractResponseType<Request_1>, ExtractErrorType<Request_1>, ExtractAdapterType<Request_1>> & ResponseDetailsType>>) => void;
112
+ update: <Request extends RequestCacheType<RequestInstance>>(request: Request, partialResponse: CacheSetState<Partial<ResponseType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>> & ResponseDetailsType>>) => void;
280
113
  /**
281
114
  * Get particular record from storage by cacheKey. It will trigger lazyStorage to emit lazy load event for reading it's data.
282
115
  * @param cacheKey
283
116
  * @returns
284
117
  */
285
- get: <Response_1, Error_1, Adapter extends AdapterInstance>(cacheKey: string) => CacheValueType<Response_1, Error_1, Adapter>;
118
+ get: <Response, Error>(cacheKey: string) => CacheValueType<Response, Error, Adapter> | undefined;
286
119
  /**
287
120
  * Get sync storage keys, lazyStorage keys will not be included
288
121
  * @returns
@@ -295,32 +128,38 @@ declare class Cache<C extends ClientInstance> {
295
128
  delete: (cacheKey: string) => void;
296
129
  /**
297
130
  * Invalidate cache by cacheKey or partial matching with RegExp
298
- * @param cacheKey
131
+ * It emits invalidation event for each matching cacheKey and sets staleTime to 0 to indicate out of time cache
132
+ * @param key - cacheKey or Request instance or RegExp for partial matching
299
133
  */
300
- invalidate: (cacheKey: string | RegExp) => Promise<void>;
134
+ invalidate: (cacheKeys: string | RegExp | RequestInstance | Array<string | RegExp | RequestInstance>) => void;
301
135
  /**
302
136
  * Used to receive data from lazy storage
303
137
  * @param cacheKey
304
138
  */
305
- getLazyResource: <Response_1, Error_1, Adapter extends AdapterInstance>(cacheKey: string) => Promise<CacheValueType<Response_1, Error_1, Adapter>>;
139
+ getLazyResource: <Response, Error>(cacheKey: string) => Promise<CacheValueType<Response, Error, Adapter> | undefined>;
306
140
  /**
307
141
  * Used to receive keys from sync storage and lazy storage
308
142
  * @param cacheKey
309
143
  */
310
144
  getLazyKeys: () => Promise<string[]>;
145
+ /**
146
+ * Used to receive keys from sync storage and lazy storage
147
+ * @param cacheKey
148
+ */
149
+ getAllKeys: () => Promise<string[]>;
311
150
  /**
312
151
  * Schedule garbage collection for given key
313
152
  * @param cacheKey
314
153
  * @returns
315
154
  */
316
- scheduleGarbageCollector: (cacheKey: string) => Promise<void>;
155
+ scheduleGarbageCollector: (cacheKey: string) => void;
317
156
  /**
318
157
  * Clear cache storages
319
158
  */
320
159
  clear: () => Promise<void>;
321
160
  }
322
161
 
323
- type CacheOptionsType<C extends ClientInstance = ClientInstance> = {
162
+ type CacheOptionsType = {
324
163
  /**
325
164
  * Assign your custom sync storage
326
165
  */
@@ -330,26 +169,18 @@ type CacheOptionsType<C extends ClientInstance = ClientInstance> = {
330
169
  */
331
170
  lazyStorage?: CacheAsyncStorageType;
332
171
  /**
333
- * Key to clear lazy storage data
172
+ * Key to clear lazy storage data, often used for versioning
173
+ * If the new key is different from the old one, the cache will be cleared
334
174
  */
335
- clearKey?: string;
336
- /**
337
- * Initialization callback
338
- */
339
- onInitialization?: (cache: Cache<C>) => void;
340
- /**
341
- * Callback for every change in the storage
342
- */
343
- onChange?: <Response = any, Error = any, Adapter extends AdapterInstance = AdapterInstance>(key: string, data: CacheValueType<Response, Error, Adapter>) => void;
344
- /**
345
- * Callback for every delete in the storage
346
- */
347
- onDelete?: (key: string) => void;
175
+ version?: string;
348
176
  };
349
- type CacheValueType<Response = any, Error = any, Adapter extends AdapterInstance = AdapterInstance> = ResponseReturnType<Response, Error, Adapter> & ResponseDetailsType & {
177
+ type CacheValueType<Response = any, Error = any, Adapter extends AdapterInstance = AdapterInstance> = ResponseType<Response, Error, Adapter> & ResponseDetailsType & {
178
+ cacheKey: string;
179
+ staleTime: number;
180
+ version: string;
350
181
  cacheTime: number;
351
- clearKey: string;
352
- garbageCollection: number;
182
+ cached: boolean;
183
+ hydrated?: boolean;
353
184
  };
354
185
  type CacheAsyncStorageType = {
355
186
  set: <Response, Error, Adapter extends AdapterInstance>(key: string, data: CacheValueType<Response, Error, Adapter>) => Promise<void>;
@@ -365,1107 +196,1854 @@ type CacheStorageType = {
365
196
  clear: () => void;
366
197
  };
367
198
  type CacheInitialData = Record<string, CacheValueType>;
368
- type CacheMethodType<CacheData> = CacheData | ((previousData: CacheData | null) => CacheData);
199
+ type CacheSetState<CacheData> = CacheData | ((previousData: CacheData | null) => CacheData);
200
+ type RequestCacheType<R extends RequestInstance> = Pick<R, "cacheKey" | "cache" | "staleTime" | "cacheTime">;
369
201
 
370
- declare const getCacheData: <T extends RequestInstance>(previousResponse: ExtractAdapterReturnType<T>, response: ExtractAdapterReturnType<T> & ResponseDetailsType) => ExtractAdapterReturnType<T> & ResponseDetailsType;
371
- declare const getInvalidateEventKey: (key: string) => string;
372
- declare const getCacheKey: (key: string) => string;
373
- declare const getCacheIdKey: (key: string) => string;
202
+ declare const getCacheData: <T extends RequestInstance>(previousResponse: ExtractAdapterResolvedType<T> | undefined, response: ExtractAdapterResolvedType<T> & ResponseDetailsType) => ExtractAdapterResolvedType<T> & ResponseDetailsType;
203
+ declare const getInvalidateKey: () => string;
204
+ declare const getInvalidateByKey: (key: string) => string;
205
+ declare const getDeleteKey: () => string;
206
+ declare const getDeleteByKey: (key: string) => string;
207
+ declare const getCacheByKey: (key: string) => string;
208
+ declare const getCacheKey: () => string;
374
209
 
375
- declare const getCacheEvents: (emitter: EventEmitter) => {
210
+ declare const getCacheEvents: (emitter: EventEmitter$1) => {
376
211
  /**
377
212
  * Set cache data
378
- * @param cacheKey
379
213
  * @param data
380
214
  */
381
- emitCacheData: <Response_1, Error_1, Adapter extends AdapterInstance>(cacheKey: string, data: CacheValueType<Response_1, Error_1, Adapter>) => void;
215
+ emitCacheData: <Response, Error, Adapter extends AdapterInstance>(data: CacheValueType<Response, Error, Adapter> & {
216
+ cached: boolean;
217
+ }, isTriggeredExternally?: boolean) => void;
382
218
  /**
383
219
  * Invalidate cache values event
384
220
  */
385
- emitInvalidation: (cacheKey: string) => void;
386
- /** StatusType
221
+ emitInvalidation: (cacheKey: string, isTriggeredExternally?: boolean) => void;
222
+ /**
223
+ * Delete of cache values
224
+ */
225
+ emitDelete: (cacheKey: string, isTriggeredExternally?: boolean) => void;
226
+ /**
227
+ * Cache data listener
228
+ * @param callback
229
+ * @returns
230
+ */
231
+ onData: <Response, Error, Adapter extends AdapterInstance>(callback: (data: CacheValueType<Response, Error, Adapter> & {
232
+ cached: boolean;
233
+ }) => void) => VoidFunction;
234
+ /**
387
235
  * Cache data listener
388
236
  * @param cacheKey
389
237
  * @param callback
390
238
  * @returns
391
239
  */
392
- onData: <Response_2, Error_2, Adapter_1 extends AdapterInstance>(cacheKey: string, callback: (data: CacheValueType<Response_2, Error_2, Adapter_1>) => void) => VoidFunction;
240
+ onDataByKey: <Response, Error, Adapter extends AdapterInstance>(cacheKey: string, callback: (data: CacheValueType<Response, Error, Adapter>) => void) => VoidFunction;
241
+ /**
242
+ * Cache invalidation listener
243
+ * @param callback
244
+ * @returns
245
+ */
246
+ onInvalidate: (callback: (cacheKey: string) => void) => VoidFunction;
393
247
  /**
394
248
  * Cache invalidation listener
395
249
  * @param cacheKey
396
250
  * @param callback
397
251
  * @returns
398
252
  */
399
- onInvalidate: (cacheKey: string, callback: () => void) => VoidFunction;
253
+ onInvalidateByKey: (cacheKey: string, callback: () => void) => VoidFunction;
254
+ onDelete: (callback: (cacheKey: string) => void) => VoidFunction;
255
+ onDeleteByKey: (cacheKey: string, callback: () => void) => VoidFunction;
400
256
  };
401
257
 
402
- declare enum DispatcherRequestType {
403
- oneByOne = "one-by-one",
404
- allAtOnce = "all-at-once",
405
- previousCanceled = "previous-canceled",
406
- deduplicated = "deduplicated"
407
- }
408
-
409
- declare const getDispatcherEvents: (emitter: EventEmitter) => {
410
- setDrained: <Request_1 extends RequestInstance>(queueKey: string, values: QueueDataType<Request_1>) => void;
411
- setQueueStatus: <Request_2 extends RequestInstance>(queueKey: string, values: QueueDataType<Request_2>) => void;
412
- setQueueChanged: <Request_3 extends RequestInstance>(queueKey: string, values: QueueDataType<Request_3>) => void;
413
- onDrained: <Request_4 extends RequestInstance>(queueKey: string, callback: (values: QueueDataType<Request_4>) => void) => VoidFunction;
414
- onQueueStatus: <Request_5 extends RequestInstance>(queueKey: string, callback: (values: QueueDataType<Request_5>) => void) => VoidFunction;
415
- onQueueChange: <Request_6 extends RequestInstance>(queueKey: string, callback: (values: QueueDataType<Request_6>) => void) => VoidFunction;
258
+ type HydrationOptions = RequestCacheType<RequestInstance> & {
259
+ override: boolean;
260
+ };
261
+ type HydrateDataType<Data = any, Error = any, Adapter extends AdapterInstance = any> = HydrationOptions & {
262
+ /** Hydration timestamp */
263
+ timestamp: number;
264
+ /** Hydrated response */
265
+ response: ResponseType<Data, Error, Adapter>;
266
+ /** Hydrated flag */
267
+ hydrated: true;
416
268
  };
417
269
 
270
+ declare const getAdapterBindings: <T extends AdapterInstance>({ request: baseRequest, requestId, resolve, onStartTime, internalErrorMapping, }: {
271
+ request: RequestInstance;
272
+ requestId: string;
273
+ resolve: (value: ResponseSuccessType<any, T> | ResponseErrorType<any, T>) => void;
274
+ onStartTime: (timestamp: number) => void;
275
+ internalErrorMapping: (error: ReturnType<typeof getErrorMessage>) => any;
276
+ }) => Promise<{
277
+ request: RequestInstance;
278
+ requestId: string;
279
+ url: string;
280
+ endpoint: any;
281
+ queryParams: any;
282
+ payload: any;
283
+ headers: any;
284
+ adapter: AdapterInstance;
285
+ adapterOptions: ExtractAdapterOptionsType<T> | undefined;
286
+ getAbortController: () => AbortController | undefined;
287
+ getRequestStartTimestamp: () => number | null;
288
+ getResponseStartTimestamp: () => number | null;
289
+ createAbortListener: ({ status, extra, onAbort, }: {
290
+ status: ExtractAdapterStatusType<T>;
291
+ extra: ExtractAdapterExtraType<T>;
292
+ onAbort?: () => void;
293
+ }) => () => void;
294
+ onBeforeRequest: () => void;
295
+ onRequestStart: (progress?: ProgressDataType) => number;
296
+ onRequestProgress: (progress: ProgressDataType) => number;
297
+ onRequestEnd: () => number;
298
+ onResponseStart: (progress?: ProgressDataType) => number;
299
+ onResponseProgress: (progress: ProgressDataType) => number;
300
+ onResponseEnd: () => number;
301
+ onSuccess: ({ data, error, status, extra, }: {
302
+ data: any;
303
+ status: ExtractAdapterStatusType<T>;
304
+ extra: ExtractAdapterExtraType<T>;
305
+ error?: ExtractErrorType<T>;
306
+ }) => Promise<ResponseSuccessType<ExtractResponseType<T>, T>>;
307
+ onAbortError: ({ status, extra, }: {
308
+ status: ExtractAdapterStatusType<T>;
309
+ extra: ExtractAdapterExtraType<T>;
310
+ }) => Promise<ResponseErrorType<any, T>>;
311
+ onTimeoutError: ({ status, extra, }: {
312
+ status: ExtractAdapterStatusType<T>;
313
+ extra: ExtractAdapterExtraType<T>;
314
+ }) => Promise<ResponseErrorType<any, T>>;
315
+ onUnexpectedError: ({ status, extra, }: {
316
+ status: ExtractAdapterStatusType<T>;
317
+ extra: ExtractAdapterExtraType<T>;
318
+ }) => Promise<ResponseErrorType<any, T>>;
319
+ onError: ({ error, status, extra, }: {
320
+ error: any;
321
+ status: ExtractAdapterStatusType<T>;
322
+ extra: ExtractAdapterExtraType<T>;
323
+ }) => Promise<ResponseErrorType<any, T>>;
324
+ }>;
325
+ declare function getAdapterOnError<T extends AdapterInstance>({ request, requestId, startTime, resolve, logger, }: {
326
+ request: RequestInstance;
327
+ requestId: string;
328
+ startTime: number;
329
+ logger: LoggerMethods;
330
+ resolve: (value: ResponseSuccessType<any, T> | ResponseErrorType<any, T>) => void;
331
+ }): ({ error, status, extra, }: {
332
+ error: any;
333
+ status: ExtractAdapterStatusType<T>;
334
+ extra: ExtractAdapterExtraType<T>;
335
+ }) => Promise<ResponseErrorType<any, T>>;
336
+
418
337
  /**
419
- * Dispatcher class was made to store controlled request Fetches, and firing them all-at-once or one-by-one in request queue.
420
- * Generally requests should be flushed at the same time, the queue provide mechanism to fire them in the order.
338
+ * Base Adapter
421
339
  */
422
- declare class Dispatcher {
423
- client: ClientInstance;
424
- options?: DispatcherOptionsType;
425
- emitter: EventEmitter;
426
- events: {
427
- setDrained: <Request_1 extends RequestInstance>(queueKey: string, values: QueueDataType<Request_1>) => void;
428
- setQueueStatus: <Request_2 extends RequestInstance>(queueKey: string, values: QueueDataType<Request_2>) => void;
429
- setQueueChanged: <Request_3 extends RequestInstance>(queueKey: string, values: QueueDataType<Request_3>) => void;
430
- onDrained: <Request_4 extends RequestInstance>(queueKey: string, callback: (values: QueueDataType<Request_4>) => void) => VoidFunction;
431
- onQueueStatus: <Request_5 extends RequestInstance>(queueKey: string, callback: (values: QueueDataType<Request_5>) => void) => VoidFunction;
432
- onQueueChange: <Request_6 extends RequestInstance>(queueKey: string, callback: (values: QueueDataType<Request_6>) => void) => VoidFunction;
340
+ type AdapterInstance = Adapter<any, any, any, any, any, any, any, any, any, any, any>;
341
+ type AdapterGenericType<AdapterOptions, MethodType extends string, StatusType extends number | string, Extra extends Record<string, any>, QueryParams = QueryParamsType | string | EmptyTypes, DefaultQueryParams = undefined, EndpointType = string, EndpointMapperType extends EndpointMapper<EndpointType> | DefaultMapperType = DefaultMapperType, QueryParamsMapperType extends QueryParamsMapper<QueryParams> | DefaultMapperType = DefaultMapperType, HeaderMapperType extends HeaderMappingType | DefaultMapperType = DefaultMapperType, PayloadMapperType extends AdapterPayloadMappingType | DefaultMapperType = DefaultMapperType> = {
342
+ adapterOptions: AdapterOptions;
343
+ methodType: MethodType;
344
+ statusType: StatusType;
345
+ extra: Extra;
346
+ queryParams?: QueryParams;
347
+ defaultQueryParams?: DefaultQueryParams;
348
+ endpointType: EndpointType;
349
+ endpointMapperType?: EndpointMapperType;
350
+ queryParamsMapperType?: QueryParamsMapperType;
351
+ headerMapperType?: HeaderMapperType;
352
+ payloadMapperType?: PayloadMapperType;
353
+ };
354
+ type DeclareAdapterType<Properties extends AdapterGenericType<any, any, any, any, any, any, any, any, any, any>> = Adapter<TypeWithDefaults<Properties, "adapterOptions", any>, TypeWithDefaults<Properties, "methodType", any>, TypeWithDefaults<Properties, "statusType", any>, TypeWithDefaults<Properties, "extra", any>, TypeWithDefaults<Properties, "queryParams", QueryParamsType | string | EmptyTypes>, TypeWithDefaults<Properties, "defaultQueryParams", undefined>, TypeWithDefaults<Properties, "endpointType", string>, TypeWithDefaults<Properties, "endpointMapperType", DefaultMapperType>, TypeWithDefaults<Properties, "queryParamsMapperType", DefaultMapperType>, TypeWithDefaults<Properties, "headerMapperType", DefaultMapperType>, NonNullable<TypeWithDefaults<Properties, "payloadMapperType", DefaultMapperType>>>;
355
+ type AdapterFetcherType<Adapter extends AdapterInstance> = (options: Omit<Awaited<ReturnType<typeof getAdapterBindings<Adapter>>>, "payload"> & {
356
+ url: string;
357
+ endpoint: ReturnType<ExtractAdapterEndpointMapperType<Adapter>>;
358
+ queryParams: ReturnType<ExtractAdapterQueryParamsMapperType<Adapter>>;
359
+ headers: ReturnType<ExtractAdapterHeaderMapperType<Adapter>>;
360
+ payload: ReturnType<ExtractAdapterPayloadMapperType<Adapter>>;
361
+ requestId: string;
362
+ request: RequestInstance;
363
+ }) => void;
364
+ type HeaderMappingType<Config = never> = (request: RequestInstance, config?: Config) => HeadersInit;
365
+ type EndpointMapper<EndpointType, Config = never> = (endpoint: EndpointType, config?: Config) => string;
366
+ type QueryParamsMapper<QueryParams, Config = never> = (queryParams: QueryParams | EmptyTypes, config?: Config) => any;
367
+ type AdapterPayloadMappingType<Config = never> = (options: {
368
+ request: RequestInstance;
369
+ payload: unknown;
370
+ }, config?: Config) => any;
371
+ type DefaultEndpointMapper = (endpoint: string) => string;
372
+ type DefaultQueryParamsMapper = (queryParams: QueryParamsType | string | EmptyTypes) => QueryParamsType | string | EmptyTypes;
373
+ type DefaultHeaderMapper = (request: RequestInstance) => HeadersInit;
374
+ type DefaultPayloadMapper = (options: {
375
+ request: RequestInstance;
376
+ payload: unknown;
377
+ }) => string;
378
+ type QueryParamValuesType = number | string | boolean | null | undefined | Record<any, any>;
379
+ type QueryParamType = QueryParamValuesType | Array<QueryParamValuesType> | Record<string, QueryParamValuesType>;
380
+ type QueryParamsType = Record<string, QueryParamType>;
381
+ type RequestResponseType<Request extends RequestInstance> = {
382
+ data: ExtractResponseType<Request> | null;
383
+ error: ExtractErrorType<Request> | null;
384
+ status: ExtractAdapterStatusType<ExtractAdapterType<Request>> | null;
385
+ success: true | false;
386
+ extra: ExtractAdapterExtraType<ExtractAdapterType<Request>> | null;
387
+ responseTimestamp: number;
388
+ requestTimestamp: number;
389
+ };
390
+ type ResponseType<GenericDataType, GenericErrorType, Adapter extends AdapterInstance> = {
391
+ data: GenericDataType | null;
392
+ error: GenericErrorType | null;
393
+ status: ExtractAdapterStatusType<Adapter> | null;
394
+ success: true | false;
395
+ extra: ExtractAdapterExtraType<Adapter> | null;
396
+ responseTimestamp: number;
397
+ requestTimestamp: number;
398
+ };
399
+ type ResponseSuccessType<GenericDataType, Adapter extends AdapterInstance> = {
400
+ data: GenericDataType;
401
+ error: null;
402
+ status: ExtractAdapterStatusType<Adapter> | null;
403
+ success: true;
404
+ extra: ExtractAdapterExtraType<Adapter> | null;
405
+ responseTimestamp: number;
406
+ requestTimestamp: number;
407
+ };
408
+ type ResponseErrorType<GenericErrorType, Adapter extends AdapterInstance> = {
409
+ data: null;
410
+ error: GenericErrorType;
411
+ status: ExtractAdapterStatusType<Adapter> | null;
412
+ success: false;
413
+ extra: ExtractAdapterExtraType<Adapter> | null;
414
+ responseTimestamp: number;
415
+ requestTimestamp: number;
416
+ };
417
+ type ProgressDataType = {
418
+ total?: number;
419
+ loaded?: number;
420
+ };
421
+ type ProgressType = {
422
+ progress: number;
423
+ timeLeft: number | null;
424
+ sizeLeft: number;
425
+ total: number;
426
+ loaded: number;
427
+ startTimestamp: number;
428
+ };
429
+
430
+ declare class TimeoutError extends Error {
431
+ constructor();
432
+ }
433
+ declare class AbortError extends Error {
434
+ constructor();
435
+ }
436
+ declare class DeletedError extends Error {
437
+ constructor();
438
+ }
439
+ declare class RequestProcessingError extends Error {
440
+ description?: string;
441
+ constructor(description?: string);
442
+ }
443
+ declare class UnexpectedError extends Error {
444
+ description?: string;
445
+ constructor(description?: string);
446
+ }
447
+ declare const getErrorMessage: (errorCase?: "timeout" | "abort" | "deleted" | "processing" | "unexpected") => TimeoutError | AbortError | DeletedError | RequestProcessingError | UnexpectedError;
448
+ declare const stringifyValue: (response: string | unknown) => string;
449
+ declare const getAdapterHeaders: (request: RequestInstance) => HeadersInit;
450
+ declare const getAdapterPayload: (data: unknown) => string | FormData;
451
+
452
+ type DefaultMapperType = <V, C>(value: V, config: C) => V;
453
+ declare const defaultMapper: DefaultMapperType;
454
+ declare class Adapter<AdapterOptions, MethodType extends string, StatusType extends number | string, Extra extends Record<string, any>, QueryParams = QueryParamsType | string | EmptyTypes, DefaultQueryParams = undefined, EndpointType = string, EndpointMapperType extends EndpointMapper<EndpointType> | DefaultMapperType = DefaultMapperType, QueryParamsMapperType extends QueryParamsMapper<QueryParams> | DefaultMapperType = DefaultMapperType, HeaderMapperType extends HeaderMappingType | DefaultMapperType = DefaultMapperType, PayloadMapperType extends AdapterPayloadMappingType | DefaultMapperType = DefaultMapperType> {
455
+ options: {
456
+ name: string;
457
+ defaultMethod: MethodType;
458
+ defaultExtra: Extra;
459
+ systemErrorStatus: StatusType;
460
+ systemErrorExtra: Extra;
461
+ defaultRequestOptions?: RequestOptionsType<EndpointType, AdapterOptions, MethodType>;
433
462
  };
434
- storage: DispatcherStorageType;
435
- private requestCount;
436
- private runningRequests;
437
- private logger;
438
- constructor(client: ClientInstance, options?: DispatcherOptionsType);
439
- /**
440
- * Start request handling by queueKey
441
- */
442
- start: (queueKey: string) => void;
443
- /**
444
- * Pause request queue, but not cancel already started requests
445
- */
446
- pause: (queueKey: string) => void;
447
- /**
448
- * Stop request queue and cancel all started requests - those will be treated like not started
449
- */
450
- stop: (queueKey: string) => void;
463
+ /** Fetching function */
464
+ unstable_fetcher: AdapterFetcherType<Adapter<AdapterOptions, MethodType, StatusType, Extra, QueryParams, DefaultQueryParams, EndpointType, EndpointMapperType, QueryParamsMapperType, HeaderMapperType, PayloadMapperType>>;
465
+ /**
466
+ * ********************
467
+ * Defaults
468
+ * ********************
469
+ */
470
+ name: string;
471
+ defaultMethod: MethodType;
472
+ defaultExtra: Extra;
473
+ systemErrorStatus: StatusType;
474
+ systemErrorExtra: Extra;
475
+ defaultRequestOptions?: RequestOptionsType<EndpointType, AdapterOptions, MethodType>;
476
+ logger: LoggerMethods;
477
+ initialized: boolean;
478
+ client: ClientInstance;
479
+ unstable_onInitializeCallback?: (options: {
480
+ client: ClientInstance;
481
+ }) => void;
482
+ unstable_queryParamsMapperConfig: Parameters<QueryParamsMapperType>[1];
483
+ unstable_headerMapperConfig: Parameters<HeaderMapperType>[1];
484
+ unstable_payloadMapperConfig: Parameters<PayloadMapperType>[1];
485
+ unstable_endpointMapperConfig: Parameters<EndpointMapperType>[1];
486
+ constructor(options: {
487
+ name: string;
488
+ defaultMethod: MethodType;
489
+ defaultExtra: Extra;
490
+ systemErrorStatus: StatusType;
491
+ systemErrorExtra: Extra;
492
+ defaultRequestOptions?: RequestOptionsType<EndpointType, AdapterOptions, MethodType>;
493
+ });
494
+ initialize: (client: ClientInstance) => this;
495
+ onInitialize: (callback: (options: {
496
+ client: ClientInstance;
497
+ }) => void) => this;
498
+ /**
499
+ * ********************
500
+ * Options Setters
501
+ * ********************
502
+ */
503
+ unstable_internalErrorMapping: (error: ReturnType<typeof getErrorMessage>) => any;
504
+ /** Method to get default headers and to map them based on the data format exchange, by default it handles FormData / JSON formats. */
505
+ unstable_headerMapper: HeaderMapperType;
506
+ /** Method to get request data and transform them to the required format. It handles FormData and JSON by default. */
507
+ unstable_payloadMapper: PayloadMapperType;
508
+ /** Method to get the endpoint for the adapter request. */
509
+ unstable_endpointMapper: EndpointMapperType;
510
+ /** Method to get request data and transform them to the required format. */
511
+ unstable_queryParamsMapper: QueryParamsMapperType;
512
+ /** Get default adapter options for the request. */
513
+ unstable_getAdapterDefaults?: (request: ExtendRequest<RequestInstance, {
514
+ client: Client$1<any, Adapter<AdapterOptions, MethodType, StatusType, Extra, QueryParams, DefaultQueryParams, EndpointType, EndpointMapperType, QueryParamsMapperType, HeaderMapperType, PayloadMapperType>>;
515
+ }>) => AdapterOptions;
516
+ /** Get default request options for the request. */
517
+ unstable_getRequestDefaults?: (options: RequestOptionsType<EndpointType, AdapterOptions, MethodType>) => Partial<RequestOptionsType<EndpointType, AdapterOptions, MethodType>>;
518
+ /**
519
+ * Get formatted endpoint name of the request.
520
+ * Helpful in displaying long endpoints like in case of graphql schemas etc.
521
+ */
522
+ unstable_devtoolsEndpointGetter: (endpoint: string) => string;
523
+ /**
524
+ * ********************
525
+ * Methods
526
+ * ********************
527
+ */
528
+ setDefaultMethod: (method: MethodType) => this;
529
+ setDefaultExtra: (extra: Extra) => this;
530
+ setDevtoolsEndpointGetter: (callback: (endpoint: string) => string) => this;
451
531
  /**
452
- * Return all
532
+ * This method allows to configure global defaults for the request configuration like method, auth, deduplication etc.
453
533
  */
454
- getQueuesKeys: () => string[];
534
+ setRequestDefaults: (callback: typeof this.unstable_getRequestDefaults) => this;
455
535
  /**
456
- * Return queue state object
536
+ * Set the adapter default options added to every sent request
457
537
  */
458
- getQueue: <Request_1 extends RequestInstance = RequestInstance>(queueKey: string) => QueueDataType<Request_1>;
538
+ setAdapterDefaults: (callback: (request: ExtendRequest<RequestInstance, {
539
+ client: Client$1<any, Adapter<AdapterOptions, MethodType, StatusType, Extra, QueryParams, DefaultQueryParams, EndpointType, EndpointMapperType, QueryParamsMapperType, HeaderMapperType, PayloadMapperType>>;
540
+ }>) => AdapterOptions) => this;
541
+ setInternalErrorMapping: (callback: (error: ReturnType<typeof getErrorMessage>) => any) => this;
459
542
  /**
460
- * Return request from queue state
543
+ * Set the custom header mapping function
461
544
  */
462
- getRequest: <Request_1 extends RequestInstance = RequestInstance>(queueKey: string, requestId: string) => QueueElementType<Request_1>;
545
+ setHeaderMapper: <NewMapper extends HeaderMappingType>(headerMapper: NewMapper) => Adapter<AdapterOptions, MethodType, StatusType, Extra, QueryParams, DefaultQueryParams, EndpointType, EndpointMapperType, QueryParamsMapperType, NewMapper, PayloadMapperType>;
463
546
  /**
464
- * Get value of the active queue status based on the stopped status
547
+ * Set the request payload mapping function which gets triggered before request is send
465
548
  */
466
- getIsActiveQueue: (queueKey: string) => boolean;
549
+ setPayloadMapper: <NewMapper extends AdapterPayloadMappingType>(payloadMapper: NewMapper) => Adapter<AdapterOptions, MethodType, StatusType, Extra, QueryParams, DefaultQueryParams, EndpointType, EndpointMapperType, QueryParamsMapperType, HeaderMapperType, NewMapper>;
467
550
  /**
468
- * Add new element to storage
551
+ * Set the request payload mapping function which get triggered before request get sent
469
552
  */
470
- addQueueElement: <Request_1 extends RequestInstance = RequestInstance>(queueKey: string, dispatcherDump: QueueElementType<Request_1>) => void;
553
+ setEndpointMapper: <NewEndpointMapper extends EndpointMapper<EndpointType>>(endpointMapper: NewEndpointMapper) => Adapter<AdapterOptions, MethodType, StatusType, Extra, QueryParams, DefaultQueryParams, EndpointType, NewEndpointMapper, QueryParamsMapperType, HeaderMapperType, PayloadMapperType>;
471
554
  /**
472
- * Set new queue storage value
555
+ * Set the query params mapping function which get triggered before request get sent
473
556
  */
474
- setQueue: <Request_1 extends RequestInstance = RequestInstance>(queueKey: string, queue: QueueDataType<Request_1>) => QueueDataType<Request_1>;
557
+ setQueryParamsMapper: <NewQueryParamsMapper extends QueryParamsMapper<QueryParams>>(queryParamsMapper: NewQueryParamsMapper) => Adapter<AdapterOptions, MethodType, StatusType, Extra, QueryParams, DefaultQueryParams, EndpointType, EndpointMapperType, NewQueryParamsMapper, HeaderMapperType, PayloadMapperType>;
558
+ setQueryParamsMapperConfig: <NewQueryParamsMapperConfig extends Parameters<QueryParamsMapperType>[1]>(config: NewQueryParamsMapperConfig) => this;
559
+ setHeaderMapperConfig: <NewHeaderMapperConfig extends Parameters<HeaderMapperType>[1]>(config: NewHeaderMapperConfig) => this;
560
+ setEndpointMapperConfig: <NewEndpointMapperConfig extends Parameters<EndpointMapperType>[1]>(config: NewEndpointMapperConfig) => this;
561
+ setPayloadMapperConfig: <NewPayloadMapperConfig extends Parameters<PayloadMapperType>[1]>(config: NewPayloadMapperConfig) => this;
475
562
  /**
476
- * Clear requests from queue cache
563
+ * ********************
564
+ * Fetching
565
+ * ********************
477
566
  */
478
- clearQueue: (queueKey: string) => {
479
- requests: any[];
480
- stopped: boolean;
481
- };
482
- /**
483
- * Method used to flush the queue requests
567
+ setFetcher(fetcher: AdapterFetcherType<Adapter<AdapterOptions, MethodType, StatusType, Extra, QueryParams, DefaultQueryParams, EndpointType, EndpointMapperType, QueryParamsMapperType, HeaderMapperType, PayloadMapperType>>): this;
568
+ fetch(request: ExtendRequest<RequestInstance, {
569
+ client: Client$1<any, Adapter<AdapterOptions, MethodType, StatusType, Extra, QueryParams, DefaultQueryParams, EndpointType, EndpointMapperType, QueryParamsMapperType, HeaderMapperType, PayloadMapperType>>;
570
+ }>, requestId: string): Promise<RequestResponseType<RequestInstance>>;
571
+ }
572
+
573
+ declare const mocker: <T extends AdapterInstance>({ request, requestId, onError, onResponseEnd, onTimeoutError, onRequestEnd, createAbortListener, onResponseProgress, onRequestProgress, onResponseStart, onBeforeRequest, onRequestStart, onSuccess, onAbortError, adapter, }: Awaited<ReturnType<typeof getAdapterBindings<T>>>) => Promise<void>;
574
+
575
+ type PartialBy<T, K extends keyof T> = Omit<T, K> & Partial<Pick<T, K>>;
576
+ type MockerConfigType = {
577
+ /** Informs how long the request should take before returning a timeout error (in milliseconds) */
578
+ timeout?: number;
579
+ /** Simulates how long the request to the server should take (in milliseconds) */
580
+ requestTime?: number;
581
+ /** Indicates how long the response from the server should take (in milliseconds).
582
+ * If their combined total takes longer than provided timeout, each value will be automatically
583
+ * adjusted to last half of the timeout time */
584
+ responseTime?: number;
585
+ /** total number of 'bytes' to be uploaded. */
586
+ totalUploaded?: number;
587
+ /** total number of 'bytes' to be downloaded. */
588
+ totalDownloaded?: number;
589
+ };
590
+ type MockResponseType<Response, Error, AdapterType extends AdapterInstance> = PartialBy<Omit<ResponseType<Response, Error, AdapterType>, "data" | "error" | "responseTimestamp" | "requestTimestamp">, "extra" | "success"> & ({
591
+ data: Response;
592
+ error?: Error;
593
+ } | {
594
+ data?: Response;
595
+ error: Error;
596
+ });
597
+
598
+ /**
599
+ * Request is a class that represents a request sent to the server. It contains all the necessary information to make a request, like endpoint, method, headers, data, and much more.
600
+ * It is executed at any time via methods like `send` or `exec`.
601
+ *
602
+ * We can set it up with options like endpoint, method, headers and more.
603
+ * We can choose some of advanced settings like cache, invalidation patterns, concurrency, retries and much, much more.
604
+ *
605
+ * @info We should not use this class directly in the standard development flow.
606
+ * We can initialize it using the `createRequest` method on the **Client** class.
607
+ *
608
+ * @attention The most important thing about the request is that it keeps data in the format that can be dumped.
609
+ * This is necessary for the persistence and different dispatcher storage types.
610
+ * This class doesn't have any callback methods by design and communicate with dispatcher and cache by events.
611
+ *
612
+ * It should be serializable to JSON and deserializable back to the class.
613
+ * Serialization should not affect the result of the request, so it's methods and functional part should be only syntax sugar for given runtime.
614
+ */
615
+ declare class Request<Response, Payload, QueryParams, LocalError, Endpoint extends string, Client extends ClientInstance, HasPayload extends true | false = false, HasParams extends true | false = false, HasQuery extends true | false = false> {
616
+ readonly client: Client;
617
+ readonly requestOptions: RequestOptionsType<Endpoint, ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>, ExtractAdapterMethodType<ExtractClientAdapterType<Client>>>;
618
+ readonly initialRequestConfiguration?: RequestConfigurationType<Payload, Endpoint extends string ? ExtractRouteParams<Endpoint> : never, QueryParams, Endpoint, ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>, ExtractAdapterMethodType<ExtractClientAdapterType<Client>>> | undefined;
619
+ endpoint: Endpoint;
620
+ headers?: HeadersInit;
621
+ auth: boolean;
622
+ method: ExtractAdapterMethodType<ExtractClientAdapterType<Client>>;
623
+ params: ExtractRouteParams<Endpoint> | EmptyTypes;
624
+ payload: PayloadType<Payload>;
625
+ queryParams: QueryParams | EmptyTypes;
626
+ options?: ExtractAdapterOptionsType<ExtractClientAdapterType<Client>> | undefined;
627
+ cancelable: boolean;
628
+ retry: number;
629
+ retryTime: number;
630
+ cacheTime: number;
631
+ cache: boolean;
632
+ staleTime: number;
633
+ queued: boolean;
634
+ offline: boolean;
635
+ abortKey: string;
636
+ cacheKey: string;
637
+ queryKey: string;
638
+ used: boolean;
639
+ deduplicate: boolean;
640
+ deduplicateTime: number | null;
641
+ isMockerEnabled: boolean;
642
+ unstable_mock?: {
643
+ fn: (options: {
644
+ request: RequestInstance;
645
+ requestId: string;
646
+ }) => MockResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>;
647
+ config: MockerConfigType;
648
+ };
649
+ /** @internal */
650
+ unstable_payloadMapper?: PayloadMapperType<Payload>;
651
+ /** @internal */
652
+ unstable_requestMapper?: RequestMapper<any, any>;
653
+ /** @internal */
654
+ unstable_responseMapper?: ResponseMapper<this, any, any>;
655
+ private updatedAbortKey;
656
+ private updatedCacheKey;
657
+ private updatedQueryKey;
658
+ constructor(client: Client, requestOptions: RequestOptionsType<Endpoint, ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>, ExtractAdapterMethodType<ExtractClientAdapterType<Client>>>, initialRequestConfiguration?: RequestConfigurationType<Payload, Endpoint extends string ? ExtractRouteParams<Endpoint> : never, QueryParams, Endpoint, ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>, ExtractAdapterMethodType<ExtractClientAdapterType<Client>>> | undefined);
659
+ setHeaders: (headers: HeadersInit) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
660
+ setAuth: (auth: boolean) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
661
+ setParams: <P extends ExtractParamsType<this>>(params: P) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, P extends null ? false : true, HasQuery>;
662
+ setPayload: <P extends Payload>(payload: P) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, P extends null ? false : true, HasParams, HasQuery>;
663
+ setQueryParams: (queryParams: QueryParams) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, true>;
664
+ setOptions: (options: ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, true>;
665
+ setCancelable: (cancelable: boolean) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
666
+ setRetry: (retry: RequestOptionsType<Endpoint, ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>, ExtractAdapterMethodType<ExtractClientAdapterType<Client>>>["retry"]) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
667
+ setRetryTime: (retryTime: RequestOptionsType<Endpoint, ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>, ExtractAdapterMethodType<ExtractClientAdapterType<Client>>>["retryTime"]) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
668
+ setCacheTime: (cacheTime: RequestOptionsType<Endpoint, ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>, ExtractAdapterMethodType<ExtractClientAdapterType<Client>>>["cacheTime"]) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
669
+ setCache: (cache: RequestOptionsType<Endpoint, ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>, ExtractAdapterMethodType<ExtractClientAdapterType<Client>>>["cache"]) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
670
+ setStaleTime: (staleTime: RequestOptionsType<Endpoint, ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>, ExtractAdapterMethodType<ExtractClientAdapterType<Client>>>["staleTime"]) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
671
+ setQueued: (queued: boolean) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
672
+ setAbortKey: (abortKey: string) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
673
+ setCacheKey: (cacheKey: string) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
674
+ setQueryKey: (queryKey: string) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
675
+ setDeduplicate: (deduplicate: boolean) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
676
+ setDeduplicateTime: (deduplicateTime: number) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
677
+ setUsed: (used: boolean) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
678
+ setOffline: (offline: boolean) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
679
+ setMock: (fn: (options: {
680
+ request: Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
681
+ requestId: string;
682
+ }) => SyncOrAsync<MockResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>>, config?: MockerConfigType) => this;
683
+ clearMock: () => this;
684
+ setMockingEnabled: (isMockerEnabled: boolean) => this;
685
+ /**
686
+ * Map data before it gets send to the server
687
+ * @param payloadMapper
688
+ * @returns
484
689
  */
485
- flushQueue: (queueKey: string) => Promise<void>;
690
+ setPayloadMapper: <MappedPayload extends unknown>(payloadMapper: (data: Payload) => MappedPayload) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
486
691
  /**
487
- * Flush all available requests from all queues
692
+ * Map request before it gets send to the server
693
+ * @param requestMapper mapper of the request
694
+ * @returns new request
488
695
  */
489
- flush: () => Promise<void>;
696
+ setRequestMapper: <NewRequest extends RequestInstance>(requestMapper: RequestMapper<this, NewRequest>) => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
490
697
  /**
491
- * Clear all running requests and storage
698
+ * Map the response to the new interface
699
+ * @param responseMapper our mapping callback
700
+ * @returns new response
492
701
  */
493
- clear: () => void;
702
+ setResponseMapper: <Properties extends Pick<RequestGenericType<QueryParams>, "response" | "error">>(responseMapper?: ResponseMapper<this, TypeWithDefaults<Properties, "response", Response>, TypeWithDefaults<Properties, "error", LocalError>>) => Request<TypeWithDefaults<Properties, "response", Response>, Payload, QueryParams, TypeWithDefaults<Properties, "error", LocalError>, Endpoint, Client, HasPayload, HasParams, HasQuery>;
703
+ private paramsMapper;
704
+ toJSON(): RequestJSON<this>;
705
+ clone<NewData extends true | false = HasPayload, NewParams extends true | false = HasParams, NewQueryParams extends true | false = HasQuery>(configuration?: RequestConfigurationType<Payload, (typeof this)["params"], QueryParams, Endpoint, ExtractAdapterOptionsType<ExtractClientAdapterType<Client>>, ExtractAdapterMethodType<ExtractClientAdapterType<Client>>>): Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, NewData, NewParams, NewQueryParams>;
706
+ abort: () => Request<Response, Payload, QueryParams, LocalError, Endpoint, Client, HasPayload, HasParams, HasQuery>;
707
+ dehydrate: (config?: {
708
+ /** in case of using adapter without cache we can provide response to dehydrate */
709
+ response?: ResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>>;
710
+ /** override cache data */
711
+ override?: boolean;
712
+ }) => HydrateDataType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>> | undefined;
713
+ /**
714
+ * Read the response from cache data
715
+ *
716
+ * If it returns error and data at the same time, it means that latest request was failed
717
+ * and we show previous data from cache together with error received from actual request
718
+ */
719
+ read(): ResponseType<Response, LocalError | ExtractClientGlobalError<Client>, ExtractClientAdapterType<Client>> | undefined;
494
720
  /**
495
- * Start particular request
721
+ * Method to use the request WITHOUT adding it to cache and queues. This mean it will make simple request without queue side effects.
722
+ * @param options
723
+ * @disableReturns
724
+ * @returns
725
+ * ```tsx
726
+ * Promise<[Data | null, Error | null, HttpStatus]>
727
+ * ```
496
728
  */
497
- startRequest: (queueKey: string, requestId: string) => void;
729
+ exec: RequestSendType<this>;
498
730
  /**
499
- * Stop particular request
731
+ * Method used to perform requests with usage of cache and queues
732
+ * @param options
733
+ * @param requestCallback
734
+ * @disableReturns
735
+ * @returns
736
+ * ```tsx
737
+ * Promise<[Data | null, Error | null, HttpStatus]>
738
+ * ```
500
739
  */
501
- stopRequest: (queueKey: string, requestId: string) => void;
740
+ send: RequestSendType<this>;
741
+ static fromJSON: <NewResponse, NewPayload, NewQueryParams, NewLocalError, NewEndpoint extends string, NewClient extends ClientInstance, NewHasPayload extends true | false = false, NewHasParams extends true | false = false, NewHasQuery extends true | false = false>(client: NewClient, json: RequestJSON<Request<NewResponse, NewPayload, NewQueryParams, NewLocalError, NewEndpoint, NewClient, NewHasPayload, NewHasParams, NewHasQuery>>) => Request<NewResponse, NewPayload, NewQueryParams, NewLocalError, NewEndpoint, NewClient, NewHasPayload, NewHasParams, NewHasQuery>;
742
+ }
743
+
744
+ type RequestInstanceProperties = {
745
+ response?: any;
746
+ payload?: any;
747
+ error?: any;
748
+ client?: ClientInstance;
749
+ queryParams?: any;
750
+ endpoint?: string;
751
+ hasParams?: boolean;
752
+ hasQueryParams?: boolean;
753
+ hasPayload?: boolean;
754
+ };
755
+ type RequestInstance<RequestProperties extends RequestInstanceProperties = {
756
+ response?: any;
757
+ payload?: any;
758
+ queryParams?: any;
759
+ error?: any;
760
+ client?: ClientInstance;
761
+ }> = Request<TypeWithDefaults<RequestProperties, "response", any>, TypeWithDefaults<RequestProperties, "payload", any>, TypeWithDefaults<RequestProperties, "queryParams", any>, TypeWithDefaults<RequestProperties, "error", any>, TypeWithDefaults<RequestProperties, "endpoint", any>, TypeWithDefaults<RequestProperties, "client", ClientInstance>, TypeWithDefaults<RequestProperties, "hasParams", any>, TypeWithDefaults<RequestProperties, "hasQueryParams", any>, TypeWithDefaults<RequestProperties, "hasPayload", any>>;
762
+ type ProgressEventType = {
763
+ total: number;
764
+ loaded: number;
765
+ };
766
+ /**
767
+ * Dump of the request used to later recreate it
768
+ */
769
+ type RequestJSON<Request extends RequestInstance> = {
770
+ requestOptions: RequestOptionsType<ExtractEndpointType<Request>, ExtractAdapterOptionsType<ExtractAdapterType<Request>>, ExtractAdapterMethodType<ExtractAdapterType<Request>>>;
771
+ endpoint: ExtractEndpointType<Request>;
772
+ method: ExtractAdapterMethodType<ExtractAdapterType<Request>>;
773
+ headers?: HeadersInit;
774
+ auth: boolean;
775
+ cancelable: boolean;
776
+ retry: number;
777
+ retryTime: number;
778
+ cacheTime: number;
779
+ cache: boolean;
780
+ staleTime: number;
781
+ queued: boolean;
782
+ offline: boolean;
783
+ disableResponseInterceptors: boolean | undefined;
784
+ disableRequestInterceptors: boolean | undefined;
785
+ options?: ExtractAdapterOptionsType<ExtractAdapterType<Request>>;
786
+ payload: PayloadType<ExtractPayloadType<Request>>;
787
+ params: ExtractParamsType<Request> | EmptyTypes;
788
+ queryParams: ExtractQueryParamsType<Request> | EmptyTypes;
789
+ abortKey: string;
790
+ cacheKey: string;
791
+ queryKey: string;
792
+ used: boolean;
793
+ updatedAbortKey: boolean;
794
+ updatedCacheKey: boolean;
795
+ updatedQueryKey: boolean;
796
+ deduplicate: boolean;
797
+ deduplicateTime: number | null;
798
+ isMockerEnabled: boolean;
799
+ hasMock: boolean;
800
+ };
801
+ /**
802
+ * Configuration options for request creation
803
+ */
804
+ type RequestOptionsType<GenericEndpoint, AdapterOptions, RequestMethods = HttpMethodsType> = {
502
805
  /**
503
- * Get currently running requests from all queueKeys
806
+ * Determine the endpoint for request request
504
807
  */
505
- getAllRunningRequest: () => RunningRequestValueType[];
808
+ endpoint: GenericEndpoint;
506
809
  /**
507
- * Get currently running requests
810
+ * Custom headers for request
508
811
  */
509
- getRunningRequests: (queueKey: string) => RunningRequestValueType[];
812
+ headers?: HeadersInit;
510
813
  /**
511
- * Get running request by id
814
+ * Should the onAuth method get called on this request
512
815
  */
513
- getRunningRequest: (queueKey: string, requestId: string) => RunningRequestValueType;
816
+ auth?: boolean;
514
817
  /**
515
- * Add request to the running requests list
818
+ * Request method picked from method names handled by adapter
819
+ * With default adapter it is GET | POST | PATCH | PUT | DELETE
516
820
  */
517
- addRunningRequest: (queueKey: string, requestId: string, request: RequestInstance) => void;
821
+ method?: RequestMethods;
518
822
  /**
519
- * Get the value based on the currently running requests
823
+ * Should enable cancelable mode in the Dispatcher
520
824
  */
521
- hasRunningRequests: (queueKey: string) => boolean;
825
+ cancelable?: boolean;
522
826
  /**
523
- * Check if request is currently processing
827
+ * Retry count when request is failed
524
828
  */
525
- hasRunningRequest: (queueKey: string, requestId: string) => boolean;
829
+ retry?: number;
526
830
  /**
527
- * Cancel all started requests, but do NOT remove it from main storage
831
+ * Retry time delay between retries
528
832
  */
529
- cancelRunningRequests: (queueKey: string) => void;
833
+ retryTime?: number;
530
834
  /**
531
- * Cancel started request, but do NOT remove it from main storage
835
+ * Should we trigger garbage collection or leave data in memory
532
836
  */
533
- cancelRunningRequest: (queueKey: string, requestId: string) => void;
837
+ cacheTime?: number;
534
838
  /**
535
- * Delete all started requests, but do NOT clear it from queue and do NOT cancel them
839
+ * Should we save the response to cache
536
840
  */
537
- deleteRunningRequests: (queueKey: string) => void;
841
+ cache?: boolean;
538
842
  /**
539
- * Delete request by id, but do NOT clear it from queue and do NOT cancel them
843
+ * Time for which the cache is considered up-to-date
540
844
  */
541
- deleteRunningRequest: (queueKey: string, requestId: string) => void;
845
+ staleTime?: number;
542
846
  /**
543
- * Get count of requests from the same queueKey
847
+ * Should the requests from this request be send one-by-one
544
848
  */
545
- getQueueRequestCount: (queueKey: string) => number;
849
+ queued?: boolean;
546
850
  /**
547
- * Add request count to the queueKey
851
+ * Do we want to store request made in offline mode for latter use when we go back online
548
852
  */
549
- incrementQueueRequestCount: (queueKey: string) => void;
853
+ offline?: boolean;
550
854
  /**
551
- * Create storage element from request
855
+ * Disable post-request interceptors
552
856
  */
553
- createStorageElement: <Request_1 extends RequestInstance>(request: Request_1) => QueueElementType<Request_1>;
857
+ disableResponseInterceptors?: boolean;
554
858
  /**
555
- * Add request to the dispatcher handler
859
+ * Disable pre-request interceptors
556
860
  */
557
- add: (request: RequestInstance) => string;
861
+ disableRequestInterceptors?: boolean;
558
862
  /**
559
- * Delete from the storage and cancel request
863
+ * Additional options for your adapter, by default XHR options
560
864
  */
561
- delete: (queueKey: string, requestId: string, abortKey: string) => QueueDataType<RequestInstance>;
865
+ options?: AdapterOptions;
562
866
  /**
563
- * Request can run for some time, once it's done, we have to check if it's successful or if it was aborted
564
- * It can be different once the previous call was set as cancelled and removed from queue before this request got resolved
867
+ * Key which will be used to cancel requests. Autogenerated by default.
565
868
  */
566
- performRequest: (storageElement: QueueElementType) => Promise<void | QueueDataType<RequestInstance>>;
567
- }
568
-
569
- type DispatcherOptionsType = {
570
- storage?: DispatcherStorageType;
571
- onInitialization?: (dispatcherInstance: Dispatcher) => void;
572
- onUpdateStorage?: <Request extends RequestInstance>(queueKey: string, data: QueueDataType<Request>) => void;
573
- onDeleteFromStorage?: <Request extends RequestInstance>(queueKey: string, data: QueueDataType<Request>) => void;
574
- onClearStorage?: (dispatcherInstance: Dispatcher) => void;
869
+ abortKey?: string;
870
+ /**
871
+ * Key which will be used to cache requests. Autogenerated by default.
872
+ */
873
+ cacheKey?: string;
874
+ /**
875
+ * Key which will be used to queue requests. Autogenerated by default.
876
+ */
877
+ queryKey?: string;
878
+ /**
879
+ * Should we deduplicate two requests made at the same time into one
880
+ */
881
+ deduplicate?: boolean;
882
+ /**
883
+ * Time of pooling for the deduplication to be active (default 10ms)
884
+ */
885
+ deduplicateTime?: number;
575
886
  };
576
- type QueueElementType<Request extends RequestInstance = RequestInstance> = {
577
- requestId: string;
578
- request: Request;
579
- retries: number;
580
- timestamp: number;
581
- stopped: boolean;
887
+ type PayloadMapperType<Payload> = <NewDataType>(payload: Payload) => NewDataType;
888
+ type PayloadType<Payload> = Payload | EmptyTypes;
889
+ type RequestConfigurationType<Payload, Params, QueryParams, GenericEndpoint extends string, AdapterOptions, MethodsType> = {
890
+ used?: boolean;
891
+ params?: Params | EmptyTypes;
892
+ queryParams?: QueryParams | EmptyTypes;
893
+ payload?: PayloadType<Payload>;
894
+ headers?: HeadersInit;
895
+ updatedAbortKey?: boolean;
896
+ updatedCacheKey?: boolean;
897
+ updatedQueryKey?: boolean;
898
+ updatedEffectKey?: boolean;
899
+ } & Partial<NullableKeys<RequestOptionsType<GenericEndpoint, AdapterOptions, MethodsType>>>;
900
+ type ParamType = string | number;
901
+ type ParamsType = Record<string, ParamType>;
902
+ type ExtractRouteParams<T extends string> = string extends T ? EmptyTypes : T extends `${string}:${infer Param}/${infer Rest}` ? {
903
+ [k in Param | keyof ExtractRouteParams<Rest>]: ParamType;
904
+ } : T extends `${string}:${infer Param}` ? {
905
+ [k in Param]: ParamType;
906
+ } : EmptyTypes;
907
+ /**
908
+ * If the request endpoint parameters are not filled it will throw an error
909
+ */
910
+ type FetchParamsType<Params, HasParams extends true | false> = Params extends EmptyTypes | void | never ? {
911
+ params?: EmptyTypes;
912
+ } : HasParams extends true ? {
913
+ params?: EmptyTypes;
914
+ } : {
915
+ params: Params;
582
916
  };
583
- type QueueDataType<Request extends RequestInstance = RequestInstance> = {
584
- requests: QueueElementType<Request>[];
585
- stopped: boolean;
917
+ /**
918
+ * If the request data is not filled it will throw an error
919
+ */
920
+ type FetchPayloadType<Payload, HasPayload extends true | false> = Payload extends EmptyTypes | void | never ? {
921
+ payload?: EmptyTypes;
922
+ } : HasPayload extends true ? {
923
+ payload?: EmptyTypes;
924
+ } : {
925
+ payload: Payload;
586
926
  };
587
- type DispatcherStorageType = {
588
- set: <Request extends RequestInstance = RequestInstance>(key: string, data: QueueDataType<Request>) => void;
589
- get: <Request extends RequestInstance = RequestInstance>(key: string) => QueueDataType<Request> | undefined;
590
- keys: () => string[] | IterableIterator<string>;
591
- delete: (key: string) => void;
592
- clear: () => void;
927
+ /**
928
+ * It will check if the query params are already set
929
+ */
930
+ type FetchQueryParamsType<QueryParams, HasQuery extends true | false = false> = HasQuery extends true ? {
931
+ queryParams?: EmptyTypes | undefined;
932
+ } : HasQuery extends true ? {
933
+ queryParams?: EmptyTypes;
934
+ } : QueryParams extends EmptyTypes | void | never ? {
935
+ queryParams?: QueryParams;
936
+ } : {
937
+ queryParams: QueryParams;
593
938
  };
594
- type RunningRequestValueType = {
595
- requestId: string;
596
- request: RequestInstance;
597
- timestamp: number;
939
+ type RequestDynamicSendOptionsType<Request extends RequestInstance> = Omit<Partial<RequestOptionsType<string, ExtractAdapterOptionsType<ExtractAdapterType<Request>>>>, "params" | "data" | "endpoint" | "method"> & {
940
+ dispatcherType?: "auto" | "fetch" | "submit";
941
+ };
942
+ type RequestSendOptionsType<Request extends RequestInstance> = FetchQueryParamsType<ExtractQueryParamsType<Request>, ExtractHasQueryParamsType<Request>> & FetchParamsType<ExtractParamsType<Request>, ExtractHasParamsType<Request>> & FetchPayloadType<ExtractPayloadType<Request>, ExtractHasPayloadType<Request>> & FetchQueryParamsType<ExtractQueryParamsType<Request>, ExtractHasQueryParamsType<Request>> & RequestSendActionsType<Request> & RequestDynamicSendOptionsType<Request>;
943
+ type RequestSendActionsType<Request extends RequestInstance> = {
944
+ onBeforeSent?: (eventData: RequestEventType<Request>) => void;
945
+ onRequestStart?: (eventData: RequestEventType<Request>) => void;
946
+ onResponseStart?: (eventData: RequestEventType<Request>) => void;
947
+ onUploadProgress?: (eventData: RequestProgressEventType<Request>) => void;
948
+ onDownloadProgress?: (eventData: RequestProgressEventType<Request>) => void;
949
+ onResponse?: (eventData: RequestResponseEventType<Request>) => void;
950
+ onRemove?: (eventData: RequestEventType<Request>) => void;
598
951
  };
952
+ type IsNegativeType<T> = void extends T ? EmptyTypes : undefined extends T ? EmptyTypes : null extends T ? EmptyTypes : T;
953
+ type RequestSendType<Request extends RequestInstance> = IsNegativeType<RequestSendOptionsType<Request>["payload"]> extends EmptyTypes | void | never ? IsNegativeType<RequestSendOptionsType<Request>["params"]> extends EmptyTypes | void | never ? IsNegativeType<RequestSendOptionsType<Request>["queryParams"]> extends EmptyTypes | void | never ? (options?: RequestSendOptionsType<Request>) => Promise<RequestResponseType<Request>> : (options: RequestSendOptionsType<Request>) => Promise<RequestResponseType<Request>> : (options: RequestSendOptionsType<Request>) => Promise<RequestResponseType<Request>> : (options: RequestSendOptionsType<Request>) => Promise<RequestResponseType<Request>>;
954
+ type RequestMapper<Request extends RequestInstance, NewRequest extends RequestInstance> = (request: Request, requestId: string) => NewRequest | Promise<NewRequest>;
955
+ type ResponseMapper<Request extends RequestInstance, NewResponse, NewError> = (response: ResponseType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>>) => ResponseType<NewResponse, NewError, ExtractAdapterType<Request>> | Promise<ResponseType<NewResponse, NewError, ExtractAdapterType<Request>>>;
599
956
 
600
- declare const getDispatcherDrainedEventKey: (key: string) => string;
601
- declare const getDispatcherStatusEventKey: (key: string) => string;
602
- declare const getDispatcherChangeEventKey: (key: string) => string;
603
- declare const getIsEqualTimestamp: (currentTimestamp: number, threshold: number, queueTimestamp?: number) => boolean;
604
- declare const canRetryRequest: (currentRetries: number, retry: number | undefined) => boolean;
605
- declare const getRequestType: (request: RequestInstance, latestRequest: QueueElementType | undefined) => DispatcherRequestType;
957
+ declare enum DispatcherMode {
958
+ ONE_BY_ONE = "one-by-one",
959
+ ALL_AT_ONCE = "all-at-once",
960
+ PREVIOUS_CANCELED = "previous-canceled",
961
+ DEDUPLICATED = "deduplicated"
962
+ }
606
963
 
607
- /**
608
- * **Client** is a class that allows you to configure the connection with the server and then use it to create
609
- * requests which, when called using the appropriate method, will cause the server to be queried for the endpoint and
610
- * method specified in the request.
611
- */
612
- declare class Client<GlobalErrorType extends ClientErrorType = Error, Adapter extends AdapterInstance = AdapterType, EndpointMapper extends DefaultEndpointMapper = DefaultEndpointMapper> {
613
- options: ClientOptionsType<Client<GlobalErrorType, Adapter, EndpointMapper>>;
614
- readonly url: string;
615
- debug: boolean;
616
- __onErrorCallbacks: ResponseInterceptorType[];
617
- __onSuccessCallbacks: ResponseInterceptorType[];
618
- __onResponseCallbacks: ResponseInterceptorType[];
619
- __onAuthCallbacks: RequestInterceptorType[];
620
- __onRequestCallbacks: RequestInterceptorType[];
621
- requestManager: RequestManager;
622
- appManager: AppManager;
623
- loggerManager: LoggerManager;
624
- adapter: Adapter;
625
- cache: Cache<this>;
626
- fetchDispatcher: Dispatcher;
627
- submitDispatcher: Dispatcher;
628
- defaultMethod: ExtractAdapterMethodType<Adapter>;
629
- defaultExtra: ExtractAdapterExtraType<Adapter>;
630
- isMockEnabled: boolean;
631
- effects: RequestEffectInstance[];
632
- queryParamsConfig?: QueryStringifyOptionsType;
633
- adapterDefaultOptions?: (request: RequestInstance) => ExtractAdapterOptionsType<Adapter>;
634
- requestDefaultOptions?: (options: RequestOptionsType<string, ExtractAdapterOptionsType<Adapter>, ExtractAdapterMethodType<Adapter>>) => Partial<RequestOptionsType<string, ExtractAdapterOptionsType<Adapter>, ExtractAdapterMethodType<Adapter>>>;
635
- abortKeyMapper?: (request: RequestInstance) => string;
636
- cacheKeyMapper?: (request: RequestInstance) => string;
637
- queueKeyMapper?: (request: RequestInstance) => string;
638
- effectKeyMapper?: (request: RequestInstance) => string;
964
+ declare const getDispatcherEvents: (emitter: EventEmitter$1) => {
965
+ emitDrained: <Request extends RequestInstance>(values: QueueDataType<Request>, isTriggeredExternally?: boolean) => void;
966
+ emitQueueStatusChanged: <Request extends RequestInstance>(values: QueueDataType<Request>, isTriggeredExternally?: boolean) => void;
967
+ emitQueueChanged: <Request extends RequestInstance>(values: QueueDataType<Request>, isTriggeredExternally?: boolean) => void;
639
968
  /**
640
- * Method to stringify query params from objects.
969
+ * When queue becomes empty
970
+ * @param callback
971
+ * @returns
641
972
  */
642
- stringifyQueryParams: StringifyCallbackType;
973
+ onDrained: <Request extends RequestInstance>(callback: (values: QueueDataType<Request>) => void) => VoidFunction;
643
974
  /**
644
- * Method to get default headers and to map them based on the data format exchange, by default it handles FormData / JSON formats.
975
+ * When queue becomes empty
976
+ * @param queryKey
977
+ * @param callback
978
+ * @returns
645
979
  */
646
- headerMapper: HeaderMappingType;
980
+ onDrainedByKey: <Request extends RequestInstance>(queryKey: string, callback: (values: QueueDataType<Request>) => void) => VoidFunction;
647
981
  /**
648
- * Method to get request data and transform them to the required format. It handles FormData and JSON by default.
982
+ * When queue status change from enabled to paused or vice versa
983
+ * @param callback
984
+ * @returns
649
985
  */
650
- payloadMapper: AdapterPayloadMappingType;
986
+ onQueueStatusChange: <Request extends RequestInstance>(callback: (values: QueueDataType<Request>) => void) => VoidFunction;
651
987
  /**
652
- * Method to get request data and transform them to the required format. It handles FormData and JSON by default.
988
+ * When queue status change from enabled to paused or vice versa
989
+ * @param queryKey
990
+ * @param callback
991
+ * @returns
653
992
  */
654
- endpointMapper: EndpointMapper;
655
- logger: LoggerType;
656
- constructor(options: ClientOptionsType<Client<GlobalErrorType, Adapter, EndpointMapper>>);
993
+ onQueueStatusChangeByKey: <Request extends RequestInstance>(queryKey: string, callback: (values: QueueDataType<Request>) => void) => VoidFunction;
657
994
  /**
658
- * This method allows to configure global defaults for the request configuration like method, auth, deduplication etc.
995
+ * When new elements are added or removed from the queue
996
+ * @param queryKey
997
+ * @param callback
998
+ * @returns
659
999
  */
660
- setRequestDefaultOptions: (callback: (request: RequestInstance) => Partial<RequestOptionsType<string, ExtractAdapterOptionsType<Adapter>, ExtractAdapterMethodType<Adapter>>>) => Client<GlobalErrorType, Adapter, EndpointMapper>;
661
- setAdapterDefaultOptions: (callback: (request: RequestInstance) => ExtractAdapterOptionsType<Adapter>) => Client<GlobalErrorType, Adapter, EndpointMapper>;
1000
+ onQueueChange: <Request extends RequestInstance>(callback: (values: QueueDataType<Request>) => void) => VoidFunction;
662
1001
  /**
663
- * This method enables the logger usage and display the logs in console
1002
+ * When new elements are added or removed from the queue
1003
+ * @param queryKey
1004
+ * @param callback
1005
+ * @returns
664
1006
  */
665
- setDebug: (debug: boolean) => Client<GlobalErrorType, Adapter, EndpointMapper>;
1007
+ onQueueChangeByKey: <Request extends RequestInstance>(queryKey: string, callback: (values: QueueDataType<Request>) => void) => VoidFunction;
1008
+ };
1009
+
1010
+ /**
1011
+ * Dispatcher controls and manages the requests that are going to be executed with adapter. It manages them based on the options provided with request.
1012
+ * This class can also run them with different modes like deduplication, cancelation, queueing or run-all-at-once mode. With it's help we can pause,
1013
+ * stop, start and cancel requests.
1014
+ */
1015
+ declare class Dispatcher<Adapter extends AdapterInstance> {
1016
+ options?: DispatcherOptionsType | undefined;
1017
+ emitter: EventEmitter;
1018
+ events: {
1019
+ emitDrained: <Request extends RequestInstance>(values: QueueDataType<Request>, isTriggeredExternally?: boolean) => void;
1020
+ emitQueueStatusChanged: <Request extends RequestInstance>(values: QueueDataType<Request>, isTriggeredExternally?: boolean) => void;
1021
+ emitQueueChanged: <Request extends RequestInstance>(values: QueueDataType<Request>, isTriggeredExternally?: boolean) => void;
1022
+ onDrained: <Request extends RequestInstance>(callback: (values: QueueDataType<Request>) => void) => VoidFunction;
1023
+ onDrainedByKey: <Request extends RequestInstance>(queryKey: string, callback: (values: QueueDataType<Request>) => void) => VoidFunction;
1024
+ onQueueStatusChange: <Request extends RequestInstance>(callback: (values: QueueDataType<Request>) => void) => VoidFunction;
1025
+ onQueueStatusChangeByKey: <Request extends RequestInstance>(queryKey: string, callback: (values: QueueDataType<Request>) => void) => VoidFunction;
1026
+ onQueueChange: <Request extends RequestInstance>(callback: (values: QueueDataType<Request>) => void) => VoidFunction;
1027
+ onQueueChangeByKey: <Request extends RequestInstance>(queryKey: string, callback: (values: QueueDataType<Request>) => void) => VoidFunction;
1028
+ };
1029
+ storage: DispatcherStorageType;
1030
+ private requestCount;
1031
+ private runningRequests;
1032
+ private logger;
1033
+ private client;
1034
+ constructor(options?: DispatcherOptionsType | undefined);
1035
+ initialize: (client: ClientInstance<{
1036
+ adapter: Adapter;
1037
+ }>) => this;
666
1038
  /**
667
- * Set the logger severity of the messages displayed to the console
1039
+ * Start request handling by queryKey
668
1040
  */
669
- setLoggerSeverity: (severity: SeverityType) => Client<GlobalErrorType, Adapter, EndpointMapper>;
1041
+ start: (queryKey: string) => void;
670
1042
  /**
671
- * Set the new logger instance to the Client
1043
+ * Pause request queue, but do not cancel already started requests
672
1044
  */
673
- setLogger: (callback: (Client: ClientInstance) => LoggerManager) => Client<GlobalErrorType, Adapter, EndpointMapper>;
1045
+ pause: (queryKey: string) => void;
674
1046
  /**
675
- * Set config for the query params stringify method, we can set here, among others, arrayFormat, skipNull, encode, skipEmptyString and more
1047
+ * Stop request queue and cancel all started requests - those will be treated like not started
676
1048
  */
677
- setQueryParamsConfig: (queryParamsConfig: QueryStringifyOptionsType) => Client<GlobalErrorType, Adapter, EndpointMapper>;
1049
+ stop: (queryKey: string) => void;
678
1050
  /**
679
- * Set the custom query params stringify method to the Client
680
- * @param stringifyFn Custom callback handling query params stringify
1051
+ * Return all
681
1052
  */
682
- setStringifyQueryParams: (stringifyFn: StringifyCallbackType) => Client<GlobalErrorType, Adapter, EndpointMapper>;
1053
+ getQueuesKeys: () => string[];
683
1054
  /**
684
- * Set the custom header mapping function
1055
+ * Return queue state object
685
1056
  */
686
- setHeaderMapper: (headerMapper: HeaderMappingType) => Client<GlobalErrorType, Adapter, EndpointMapper>;
1057
+ getQueue: <Request extends RequestInstance = RequestInstance>(queryKey: string) => QueueDataType<Request>;
687
1058
  /**
688
- * Set the request payload mapping function which get triggered before request get send
1059
+ * Return request from queue state
689
1060
  */
690
- setPayloadMapper: (payloadMapper: AdapterPayloadMappingType) => Client<GlobalErrorType, Adapter, EndpointMapper>;
1061
+ getRequest: <Request extends RequestInstance = RequestInstance>(queryKey: string, requestId: string) => QueueItemType<Request> | undefined;
691
1062
  /**
692
- * Set globally if mocking should be enabled or disabled for all client requests.
693
- * @param isMockEnabled
1063
+ * Get value of the active queue status based on the stopped status
694
1064
  */
695
- setEnableGlobalMocking: (isMockEnabled: boolean) => this;
1065
+ getIsActiveQueue: (queryKey: string) => boolean;
696
1066
  /**
697
- * Set the request payload mapping function which get triggered before request get send
1067
+ * Add new element to storage
698
1068
  */
699
- setEndpointMapper: <NewEndpointMapper extends DefaultEndpointMapper>(endpointMapper: NewEndpointMapper) => Client<GlobalErrorType, Adapter, NewEndpointMapper>;
1069
+ addQueueItem: <Request extends RequestInstance = RequestInstance>(queryKey: string, element: QueueItemType<Request>) => void;
700
1070
  /**
701
- * Set custom http adapter to handle graphql, rest, firebase or others
1071
+ * Set new queue storage value
702
1072
  */
703
- setAdapter: <NewAdapter extends AdapterInstance, Returns extends AdapterInstance | ClientInstance>(callback: (client: this) => Returns extends AdapterInstance ? NewAdapter : Client<GlobalErrorType, NewAdapter, EndpointMapper>) => Client<GlobalErrorType, Returns extends AdapterInstance ? NewAdapter : ExtractAdapterType<NewAdapter>, EndpointMapper>;
1073
+ setQueue: <Request extends RequestInstance = RequestInstance>(queryKey: string, queue: QueueDataType<Request>) => QueueDataType<Request>;
704
1074
  /**
705
- * Set default method for requests.
1075
+ * Clear requests from queue cache
706
1076
  */
707
- setDefaultMethod: (defaultMethod: ExtractAdapterMethodType<Adapter>) => ClientInstance;
1077
+ clearQueue: (queryKey: string) => {
1078
+ queryKey: string;
1079
+ requests: never[];
1080
+ stopped: boolean;
1081
+ };
708
1082
  /**
709
- * Set default additional data for initial state.
1083
+ * Method used to flush the queue requests
710
1084
  */
711
- setDefaultExtra: (defaultExtra: ExtractAdapterExtraType<Adapter>) => ClientInstance;
1085
+ flushQueue: (queryKey: string) => Promise<void>;
712
1086
  /**
713
- * Method of manipulating requests before sending the request. We can for example add custom header with token to the request which request had the auth set to true.
1087
+ * Flush all available requests from all queues
714
1088
  */
715
- onAuth: (callback: RequestInterceptorType) => Client<GlobalErrorType, Adapter, EndpointMapper>;
716
- /**
717
- * Method for removing listeners on auth.
718
- * */
719
- removeOnAuthInterceptors: (callbacks: RequestInterceptorType[]) => Client<GlobalErrorType, Adapter, EndpointMapper>;
1089
+ flush: () => Promise<void>;
720
1090
  /**
721
- * Method for intercepting error responses. It can be used for example to refresh tokens.
1091
+ * Clear all running requests and storage
722
1092
  */
723
- onError: <ErrorType = null>(callback: ResponseInterceptorType<any, GlobalErrorType | ErrorType, Adapter>) => Client<GlobalErrorType, Adapter, EndpointMapper>;
724
- /**
725
- * Method for removing listeners on error.
726
- * */
727
- removeOnErrorInterceptors: (callbacks: ResponseInterceptorType<any, null | GlobalErrorType, Adapter>[]) => Client<GlobalErrorType, Adapter, EndpointMapper>;
1093
+ clear: () => void;
728
1094
  /**
729
- * Method for intercepting success responses.
1095
+ * Start particular request
730
1096
  */
731
- onSuccess: <ErrorType = null>(callback: ResponseInterceptorType<any, GlobalErrorType | ErrorType, Adapter>) => Client<GlobalErrorType, Adapter, EndpointMapper>;
732
- /**
733
- * Method for removing listeners on success.
734
- * */
735
- removeOnSuccessInterceptors: (callbacks: ResponseInterceptorType<any, null | GlobalErrorType, Adapter>[]) => Client<GlobalErrorType, Adapter, EndpointMapper>;
1097
+ startRequest: (queryKey: string, requestId: string) => void;
736
1098
  /**
737
- * Method of manipulating requests before sending the request.
1099
+ * Stop particular request
738
1100
  */
739
- onRequest: (callback: RequestInterceptorType) => Client<GlobalErrorType, Adapter, EndpointMapper>;
1101
+ stopRequest: (queryKey: string, requestId: string) => void;
740
1102
  /**
741
- * Method for removing listeners on request.
742
- * */
743
- removeOnRequestInterceptors: (callbacks: RequestInterceptorType[]) => Client<GlobalErrorType, Adapter, EndpointMapper>;
744
- /**
745
- * Method for intercepting any responses.
1103
+ * Get currently running requests from all queryKeys
746
1104
  */
747
- onResponse: <ErrorType = null>(callback: ResponseInterceptorType<any, GlobalErrorType | ErrorType, Adapter>) => Client<GlobalErrorType, Adapter, EndpointMapper>;
1105
+ getAllRunningRequests: () => RunningRequestValueType[];
748
1106
  /**
749
- * Method for removing listeners on request.
750
- * */
751
- removeOnResponseInterceptors: (callbacks: ResponseInterceptorType<any, null | GlobalErrorType, Adapter>[]) => Client<GlobalErrorType, Adapter, EndpointMapper>;
1107
+ * Get currently running requests
1108
+ */
1109
+ getRunningRequests: (queryKey: string) => RunningRequestValueType[];
752
1110
  /**
753
- * Add persistent effects which trigger on the request lifecycle
1111
+ * Get running request by id
754
1112
  */
755
- addEffect: (effect: RequestEffectInstance | RequestEffectInstance[]) => this;
1113
+ getRunningRequest: (queryKey: string, requestId: string) => RunningRequestValueType | undefined;
756
1114
  /**
757
- * Remove effects from Client
1115
+ * Add request to the running requests list
758
1116
  */
759
- removeEffect: (effect: RequestEffectInstance | string) => this;
1117
+ addRunningRequest: (queryKey: string, requestId: string, request: RequestInstance) => RunningRequestValueType;
760
1118
  /**
761
- * Key setters
1119
+ * Get the value based on the currently running requests
762
1120
  */
763
- setAbortKeyMapper: (callback: (request: RequestInstance) => string) => void;
764
- setCacheKeyMapper: (callback: (request: RequestInstance) => string) => void;
765
- setQueueKeyMapper: (callback: (request: RequestInstance) => string) => void;
766
- setEffectKeyMapper: (callback: (request: RequestInstance) => string) => void;
1121
+ hasRunningRequests: (queryKey: string) => boolean;
767
1122
  /**
768
- * Helper used by http adapter to apply the modifications on response error
1123
+ * Check if request is currently processing
769
1124
  */
770
- __modifyAuth: (request: RequestInstance) => Promise<RequestInstance>;
1125
+ hasRunningRequest: (queryKey: string, requestId: string) => boolean;
771
1126
  /**
772
- * Private helper to run async pre-request processing
1127
+ * Cancel all started requests, but do NOT remove it from main storage
773
1128
  */
774
- __modifyRequest: (request: RequestInstance) => Promise<RequestInstance>;
1129
+ cancelRunningRequests: (queryKey: string) => void;
775
1130
  /**
776
- * Private helper to run async on-error response processing
1131
+ * Cancel started request, but do NOT remove it from main storage
777
1132
  */
778
- __modifyErrorResponse: (response: ResponseReturnType<any, GlobalErrorType, Adapter>, request: RequestInstance) => Promise<ResponseReturnType<any, GlobalErrorType, Adapter>>;
1133
+ cancelRunningRequest: (queryKey: string, requestId: string) => void;
779
1134
  /**
780
- * Private helper to run async on-success response processing
1135
+ * Delete all started requests, but do NOT clear it from queue and do NOT cancel them
781
1136
  */
782
- __modifySuccessResponse: (response: ResponseReturnType<any, GlobalErrorType, Adapter>, request: RequestInstance) => Promise<ResponseReturnType<any, GlobalErrorType, Adapter>>;
1137
+ deleteRunningRequests: (queryKey: string) => void;
783
1138
  /**
784
- * Private helper to run async response processing
1139
+ * Delete request by id, but do NOT clear it from queue and do NOT cancel them
785
1140
  */
786
- __modifyResponse: (response: ResponseReturnType<any, GlobalErrorType, Adapter>, request: RequestInstance) => Promise<ResponseReturnType<any, GlobalErrorType, Adapter>>;
1141
+ deleteRunningRequest: (queryKey: string, requestId: string) => void;
787
1142
  /**
788
- * Clears the Client instance and remove all listeners on it's dependencies
1143
+ * Get count of requests from the same queryKey
789
1144
  */
790
- clear: () => void;
1145
+ getQueueRequestCount: (queryKey: string) => number;
791
1146
  /**
792
- * Create requests based on the Client setup
1147
+ * Add request count to the queryKey
793
1148
  */
794
- createRequest: <Response_1, Payload = undefined, LocalError = undefined, QueryParams = ExtractAdapterQueryParamsType<Adapter>>() => <EndpointType extends ExtractAdapterEndpointType<Adapter>, AdapterOptions extends ExtractAdapterOptionsType<Adapter>, MethodType extends ExtractAdapterMethodType<Adapter>>(params: RequestOptionsType<EndpointType, AdapterOptions, MethodType>) => Request<Response_1, Payload, QueryParams, GlobalErrorType, LocalError, EndpointType extends string ? EndpointType : string, ExtractUnionAdapter<Adapter, {
795
- method: MethodType;
796
- options: AdapterOptions;
797
- queryParams: QueryParams;
798
- }> extends null ? Adapter : ExtractUnionAdapter<Adapter, {
799
- method: MethodType;
800
- options: AdapterOptions;
801
- queryParams: QueryParams;
802
- }>, false, false, false>;
803
- }
804
-
805
- type ClientErrorType = Record<string, any> | string;
806
- type ClientInstance = Client<any, AdapterType<any, any, any, any>>;
807
- type ExtractAdapterTypeFromClient<T> = T extends Client<any, infer A> ? A : never;
808
- /**
809
- * Configuration setup for the client
810
- */
811
- type ClientOptionsType<C extends ClientInstance> = {
1149
+ incrementQueueRequestCount: (queryKey: string) => void;
812
1150
  /**
813
- * Url to your server
1151
+ * Create storage element from request
814
1152
  */
815
- url: string;
1153
+ createStorageItem: <Request extends RequestInstance>(request: Request) => QueueItemType<Request>;
816
1154
  /**
817
- * Custom adapter initialization prop
1155
+ * Add request to the dispatcher handler
818
1156
  */
819
- adapter?: AdapterType;
1157
+ add: (request: RequestInstance) => string;
820
1158
  /**
821
- * Custom cache initialization prop
1159
+ * Delete from the storage and cancel request
822
1160
  */
823
- cache?: (client: C) => C["cache"];
1161
+ delete: (queryKey: string, requestId: string, abortKey: string) => QueueDataType<RequestInstance> | undefined;
824
1162
  /**
825
- * Custom app manager initialization prop
1163
+ * Request can run for some time, once it's done, we have to check if it's successful or if it was aborted
1164
+ * It can be different once the previous call was set as cancelled and removed from queue before this request got resolved
826
1165
  */
827
- appManager?: (client: C) => C["appManager"];
1166
+ performRequest: (storageItem: QueueItemType) => Promise<void | QueueDataType<RequestInstance>>;
1167
+ }
1168
+
1169
+ type DispatcherOptionsType = {
1170
+ storage?: DispatcherStorageType;
1171
+ };
1172
+ type QueueItemType<Request extends RequestInstance = RequestInstance> = {
1173
+ requestId: string;
1174
+ request: Request;
1175
+ retries: number;
1176
+ timestamp: number;
1177
+ stopped: boolean;
1178
+ /** Resolved when we receive response */
1179
+ resolved: boolean;
1180
+ };
1181
+ type QueueDataType<Request extends RequestInstance = RequestInstance> = {
1182
+ queryKey: string;
1183
+ requests: QueueItemType<Request>[];
1184
+ stopped: boolean;
1185
+ };
1186
+ type DispatcherStorageType = {
1187
+ set: <Request extends RequestInstance = RequestInstance>(key: string, data: QueueDataType<Request>) => void;
1188
+ get: <Request extends RequestInstance = RequestInstance>(key: string) => QueueDataType<Request> | undefined;
1189
+ keys: () => string[] | IterableIterator<string>;
1190
+ entries: () => [string, QueueDataType] | IterableIterator<[string, QueueDataType<any>]>;
1191
+ delete: (key: string) => void;
1192
+ clear: () => void;
1193
+ };
1194
+ type RunningRequestValueType = {
1195
+ requestId: string;
1196
+ request: RequestInstance;
1197
+ timestamp: number;
1198
+ };
1199
+
1200
+ declare const getDispatcherDrainedKey: () => string;
1201
+ declare const getDispatcherDrainedByKey: (key: string) => string;
1202
+ declare const getDispatcherStatusKey: () => string;
1203
+ declare const getDispatcherStatusByKey: (key: string) => string;
1204
+ declare const getDispatcherChangeKey: () => string;
1205
+ declare const getDispatcherChangeByKey: (key: string) => string;
1206
+ declare const getIsEqualTimestamp: (currentTimestamp: number, threshold: number, queueTimestamp?: number) => boolean;
1207
+ declare const canRetryRequest: (currentRetries: number, retry: number | undefined) => boolean;
1208
+ declare const getRequestType: (request: RequestInstance, latestRequest: QueueItemType | undefined) => DispatcherMode;
1209
+
1210
+ declare const stringifyKey: (value: unknown) => string;
1211
+ declare const getProgressValue: ({ loaded, total }: ProgressEventType) => number;
1212
+ declare const getRequestEta: (startDate: Date, progressDate: Date, { total, loaded }: ProgressEventType) => {
1213
+ sizeLeft: number;
1214
+ timeLeft: number | null;
1215
+ };
1216
+ declare const getProgressData: (requestStartTime: Date, progressDate: Date, progressEvent: ProgressEventType) => ProgressType;
1217
+ declare const getSimpleKey: (request: RequestInstance | RequestJSON<RequestInstance>) => string;
1218
+ /**
1219
+ * Cache instance for individual request that collects individual requests responses from
1220
+ * the same endpoint (they may differ base on the custom key, endpoint params etc)
1221
+ * @param request
1222
+ * @param useInitialValues
1223
+ * @returns
1224
+ */
1225
+ declare const getRequestKey: (request: RequestInstance | RequestJSON<RequestInstance>, useInitialValues?: boolean) => string;
1226
+ declare const getRequestDispatcher: <Request extends RequestInstance>(request: Request, dispatcherType?: "auto" | "fetch" | "submit") => [Dispatcher<ExtractAdapterType<Request>>, isFetchDispatcher: boolean];
1227
+ declare const sendRequest: <Request extends RequestInstance>(request: Request, options?: RequestSendOptionsType<Request>) => Promise<ResponseType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>>>;
1228
+
1229
+ declare const getUniqueRequestId: (request: Pick<RequestInstance, "queryKey">) => string;
1230
+
1231
+ declare class EventEmitter extends EventEmitter$1 {
1232
+ emitCallbacks: Array<(event: string, data: any, isTriggeredExternally?: true) => void>;
1233
+ constructor(options?: ConstructorParameters<typeof EventEmitter$1>[0]);
1234
+ emit(type: string, data: any, isTriggeredExternally: boolean): boolean;
1235
+ onEmit: (callback: (event: string, data: any, isTriggeredExternally?: true) => void) => () => void;
1236
+ onListener: (event: string, listener: (count: number) => void) => () => void;
1237
+ on: (event: string | symbol, listener: (...args: any[]) => void) => this;
1238
+ off: (event: string | symbol, listener: (...args: any[]) => void) => this;
1239
+ addListener: (event: string | symbol, listener: (...args: any[]) => void) => this;
1240
+ removeListener: (event: string | symbol, listener: (...args: any[]) => void) => this;
1241
+ }
1242
+
1243
+ /**
1244
+ * App manager handles main application states - focus and online. Those two values can answer questions:
1245
+ * - Is the tab or current view instance focused and visible for user?
1246
+ * - Is our application online or offline?
1247
+ * With the app manager it is not a problem to get the valid answer for this question.
1248
+ *
1249
+ * @caution
1250
+ * Make sure to apply valid focus/online handlers for different environments like for example for native mobile applications.
1251
+ */
1252
+ declare class AppManager {
1253
+ options?: AppManagerOptionsType | undefined;
1254
+ emitter: EventEmitter;
1255
+ events: {
1256
+ emitFocus: () => void;
1257
+ emitBlur: () => void;
1258
+ emitOnline: () => void;
1259
+ emitOffline: () => void;
1260
+ onFocus: (callback: () => void) => VoidFunction;
1261
+ onBlur: (callback: () => void) => VoidFunction;
1262
+ onOnline: (callback: () => void) => VoidFunction;
1263
+ onOffline: (callback: () => void) => VoidFunction;
1264
+ };
1265
+ isBrowser: boolean;
1266
+ isOnline: boolean;
1267
+ isFocused: boolean;
1268
+ constructor(options?: AppManagerOptionsType | undefined);
1269
+ initialize: () => void;
1270
+ private setInitialFocus;
1271
+ private setInitialOnline;
1272
+ setFocused: (isFocused: boolean) => void;
1273
+ setOnline: (isOnline: boolean) => void;
1274
+ }
1275
+
1276
+ type AppManagerOptionsType = {
1277
+ initiallyFocused?: boolean | (() => boolean | Promise<boolean>);
1278
+ initiallyOnline?: boolean | (() => boolean | Promise<boolean>);
1279
+ focusEvent?: (setFocused: (isFocused: boolean) => void) => void;
1280
+ onlineEvent?: (setOnline: (isOnline: boolean) => void) => void;
1281
+ };
1282
+
1283
+ declare const hasWindow: () => boolean;
1284
+ declare const hasDocument: () => boolean;
1285
+ declare const onWindowEvent: <K extends keyof WindowEventMap>(key: K, listener: (this: Window, ev: WindowEventMap[K]) => any, options?: boolean | AddEventListenerOptions | undefined) => VoidFunction;
1286
+ declare const onDocumentEvent: <K extends keyof DocumentEventMap>(key: K, listener: (this: Document, ev: DocumentEventMap[K]) => any, options?: boolean | AddEventListenerOptions | undefined) => VoidFunction;
1287
+
1288
+ declare const getAppManagerEvents: (emitter: EventEmitter$1) => {
1289
+ emitFocus: () => void;
1290
+ emitBlur: () => void;
1291
+ emitOnline: () => void;
1292
+ emitOffline: () => void;
1293
+ onFocus: (callback: () => void) => VoidFunction;
1294
+ onBlur: (callback: () => void) => VoidFunction;
1295
+ onOnline: (callback: () => void) => VoidFunction;
1296
+ onOffline: (callback: () => void) => VoidFunction;
1297
+ };
1298
+
1299
+ declare enum AppEvents {
1300
+ FOCUS = "focus",
1301
+ BLUR = "blur",
1302
+ ONLINE = "online",
1303
+ OFFLINE = "offline"
1304
+ }
1305
+ declare const appManagerInitialOptions: RequiredKeys<AppManagerOptionsType>;
1306
+
1307
+ /**
1308
+ * **Request Manager** is used to emit `request lifecycle events` like - request start, request end, upload and download progress.
1309
+ * It is also the place of `request aborting` system, here we store all the keys and controllers that are isolated for each client instance.
1310
+ */
1311
+ declare class RequestManager {
1312
+ emitter: EventEmitter;
1313
+ events: {
1314
+ emitDeduplicated: (data: RequestDeduplicatedEventType<RequestInstance>, isTriggeredExternally?: boolean) => void;
1315
+ emitLoading: (data: RequestLoadingEventType<RequestInstance>, isTriggeredExternally?: boolean) => void;
1316
+ emitRequestStart: (data: RequestEventType<RequestInstance>, isTriggeredExternally?: boolean) => void;
1317
+ emitResponseStart: (data: RequestEventType<RequestInstance>, isTriggeredExternally?: boolean) => void;
1318
+ emitUploadProgress: (data: RequestProgressEventType<RequestInstance>, isTriggeredExternally?: boolean) => void;
1319
+ emitDownloadProgress: (data: RequestProgressEventType<RequestInstance>, isTriggeredExternally?: boolean) => void;
1320
+ emitResponse: <Adapter extends AdapterInstance>(data: RequestResponseEventType<ExtendRequest<RequestInstance, {
1321
+ client: Client$1<any, Adapter>;
1322
+ }>>, isTriggeredExternally?: boolean) => void;
1323
+ emitAbort: (data: RequestEventType<RequestInstance>, isTriggeredExternally?: boolean) => void;
1324
+ emitRemove: (data: RequestRemovedEventType<RequestInstance>, isTriggeredExternally?: boolean) => void;
1325
+ onDeduplicated: <T extends RequestInstance>(callback: (data: RequestDeduplicatedEventType<T>) => void) => VoidFunction;
1326
+ onDeduplicatedByQueue: <T extends RequestInstance>(queryKey: string, callback: (data: RequestDeduplicatedEventType<T>) => void) => VoidFunction;
1327
+ onDeduplicatedByCache: <T extends RequestInstance>(cacheKey: string, callback: (data: RequestDeduplicatedEventType<T>) => void) => VoidFunction;
1328
+ onDeduplicatedById: <T extends RequestInstance>(requestId: string, callback: (data: RequestDeduplicatedEventType<T>) => void) => VoidFunction;
1329
+ onLoading: <T extends RequestInstance>(callback: (data: RequestLoadingEventType<T>) => void) => VoidFunction;
1330
+ onLoadingByQueue: <T extends RequestInstance>(queryKey: string, callback: (data: RequestLoadingEventType<T>) => void) => VoidFunction;
1331
+ onLoadingByCache: <T extends RequestInstance>(cacheKey: string, callback: (data: RequestLoadingEventType<T>) => void) => VoidFunction;
1332
+ onLoadingById: <T extends RequestInstance>(requestId: string, callback: (data: RequestLoadingEventType<T>) => void) => VoidFunction;
1333
+ onRequestStart: <T extends RequestInstance>(callback: (details: RequestEventType<T>) => void) => VoidFunction;
1334
+ onRequestStartByQueue: <T extends RequestInstance>(queryKey: string, callback: (details: RequestEventType<T>) => void) => VoidFunction;
1335
+ onRequestStartById: <T extends RequestInstance>(requestId: string, callback: (details: RequestEventType<T>) => void) => VoidFunction;
1336
+ onResponseStart: <T extends RequestInstance>(callback: (details: RequestEventType<T>) => void) => VoidFunction;
1337
+ onResponseStartByQueue: <T extends RequestInstance>(queryKey: string, callback: (details: RequestEventType<T>) => void) => VoidFunction;
1338
+ onResponseStartById: <T extends RequestInstance>(requestId: string, callback: (details: RequestEventType<T>) => void) => VoidFunction;
1339
+ onUploadProgress: <T extends RequestInstance = RequestInstance>(callback: (data: RequestProgressEventType<T>) => void) => VoidFunction;
1340
+ onUploadProgressByQueue: <T extends RequestInstance = RequestInstance>(queryKey: string, callback: (data: RequestProgressEventType<T>) => void) => VoidFunction;
1341
+ onUploadProgressById: <T extends RequestInstance = RequestInstance>(requestId: string, callback: (data: RequestProgressEventType<T>) => void) => VoidFunction;
1342
+ onDownloadProgress: <T extends RequestInstance = RequestInstance>(callback: (data: RequestProgressEventType<T>) => void) => VoidFunction;
1343
+ onDownloadProgressByQueue: <T extends RequestInstance = RequestInstance>(queryKey: string, callback: (data: RequestProgressEventType<T>) => void) => VoidFunction;
1344
+ onDownloadProgressById: <T extends RequestInstance = RequestInstance>(requestId: string, callback: (data: RequestProgressEventType<T>) => void) => VoidFunction;
1345
+ onResponse: <T extends RequestInstance>(callback: (data: RequestResponseEventType<T>) => void) => VoidFunction;
1346
+ onResponseByCache: <T extends RequestInstance>(cacheKey: string, callback: (data: RequestResponseEventType<T>) => void) => VoidFunction;
1347
+ onResponseById: <T extends RequestInstance>(requestId: string, callback: (data: RequestResponseEventType<T>) => void) => VoidFunction;
1348
+ onAbort: <T extends RequestInstance = RequestInstance>(callback: (request: RequestEventType<T>) => void) => VoidFunction;
1349
+ onAbortByKey: <T extends RequestInstance = RequestInstance>(abortKey: string, callback: (request: RequestEventType<T>) => void) => VoidFunction;
1350
+ onAbortById: <T extends RequestInstance = RequestInstance>(requestId: string, callback: (data: RequestEventType<T>) => void) => VoidFunction;
1351
+ onRemove: <T extends RequestInstance = RequestInstance>(callback: (data: RequestRemovedEventType<T>) => void) => VoidFunction;
1352
+ onRemoveByQueue: <T extends RequestInstance = RequestInstance>(queryKey: string, callback: (data: RequestRemovedEventType<T>) => void) => VoidFunction;
1353
+ onRemoveById: <T extends RequestInstance = RequestInstance>(requestId: string, callback: (data: RequestRemovedEventType<T>) => void) => VoidFunction;
1354
+ };
1355
+ constructor();
1356
+ abortControllers: Map<string, Map<string, AbortController>>;
1357
+ addAbortController: (abortKey: string, requestId: string) => void;
1358
+ getAbortController: (abortKey: string, requestId: string) => AbortController | undefined;
1359
+ removeAbortController: (abortKey: string, requestId: string) => void;
1360
+ useAbortController: (abortKey: string, requestId: string) => void;
1361
+ abortByKey: (abortKey: string) => void;
1362
+ abortByRequestId: (abortKey: string, requestId: string) => void;
1363
+ abortAll: () => void;
1364
+ }
1365
+
1366
+ declare const getLoadingKey: () => string;
1367
+ declare const getLoadingByQueryKey: (queryKey: string) => string;
1368
+ declare const getLoadingByCacheKey: (cacheKey: string) => string;
1369
+ declare const getLoadingByIdKey: (id: string) => string;
1370
+ declare const getRemoveKey: () => string;
1371
+ declare const getRemoveByQueryKey: (queryKey: string) => string;
1372
+ declare const getRemoveByIdKey: (id: string) => string;
1373
+ declare const getAbortKey: () => string;
1374
+ declare const getAbortByAbortKey: (abortKey: string) => string;
1375
+ declare const getAbortByIdKey: (id: string) => string;
1376
+ declare const getResponseKey: () => string;
1377
+ declare const getResponseByCacheKey: (cacheKey: string) => string;
1378
+ declare const getResponseByIdKey: (id: string) => string;
1379
+ declare const getRequestStartKey: () => string;
1380
+ declare const getRequestStarByQueryKey: (queryKey: string) => string;
1381
+ declare const getRequestStartByIdKey: (id: string) => string;
1382
+ declare const getResponseStartKey: () => string;
1383
+ declare const getResponseStartByQueryKey: (queryKey: string) => string;
1384
+ declare const getResponseStartByIdKey: (id: string) => string;
1385
+ declare const getUploadProgressKey: () => string;
1386
+ declare const getUploadProgressByQueryKey: (queryKey: string) => string;
1387
+ declare const getUploadProgressByIdKey: (id: string) => string;
1388
+ declare const getDownloadProgressKey: () => string;
1389
+ declare const getDownloadProgressByQueryKey: (queryKey: string) => string;
1390
+ declare const getDownloadProgressByIdKey: (id: string) => string;
1391
+ declare const getRequestDeduplicatedKey: () => string;
1392
+ declare const getRequestDeduplicatedByQueryKey: (queryKey: string) => string;
1393
+ declare const getRequestDeduplicatedByCacheKey: (cacheKey: string) => string;
1394
+ declare const getRequestDeduplicatedByIdKey: (id: string) => string;
1395
+
1396
+ declare const getRequestManagerEvents: (emitter: EventEmitter$1) => {
828
1397
  /**
829
- * Custom fetch dispatcher initialization prop
1398
+ * Emiter
830
1399
  */
831
- fetchDispatcher?: (client: C) => C["submitDispatcher"];
1400
+ emitDeduplicated: (data: RequestDeduplicatedEventType<RequestInstance>, isTriggeredExternally?: boolean) => void;
1401
+ emitLoading: (data: RequestLoadingEventType<RequestInstance>, isTriggeredExternally?: boolean) => void;
1402
+ emitRequestStart: (data: RequestEventType<RequestInstance>, isTriggeredExternally?: boolean) => void;
1403
+ emitResponseStart: (data: RequestEventType<RequestInstance>, isTriggeredExternally?: boolean) => void;
1404
+ emitUploadProgress: (data: RequestProgressEventType<RequestInstance>, isTriggeredExternally?: boolean) => void;
1405
+ emitDownloadProgress: (data: RequestProgressEventType<RequestInstance>, isTriggeredExternally?: boolean) => void;
1406
+ emitResponse: <Adapter extends AdapterInstance>(data: RequestResponseEventType<ExtendRequest<RequestInstance, {
1407
+ client: Client$1<any, Adapter>;
1408
+ }>>, isTriggeredExternally?: boolean) => void;
1409
+ emitAbort: (data: RequestEventType<RequestInstance>, isTriggeredExternally?: boolean) => void;
1410
+ emitRemove: (data: RequestRemovedEventType<RequestInstance>, isTriggeredExternally?: boolean) => void;
832
1411
  /**
833
- * Custom submit dispatcher initialization prop
1412
+ * Listeners
834
1413
  */
835
- submitDispatcher?: (client: C) => C["fetchDispatcher"];
1414
+ onDeduplicated: <T extends RequestInstance>(callback: (data: RequestDeduplicatedEventType<T>) => void) => VoidFunction;
1415
+ onDeduplicatedByQueue: <T extends RequestInstance>(queryKey: string, callback: (data: RequestDeduplicatedEventType<T>) => void) => VoidFunction;
1416
+ onDeduplicatedByCache: <T extends RequestInstance>(cacheKey: string, callback: (data: RequestDeduplicatedEventType<T>) => void) => VoidFunction;
1417
+ onDeduplicatedById: <T extends RequestInstance>(requestId: string, callback: (data: RequestDeduplicatedEventType<T>) => void) => VoidFunction;
1418
+ onLoading: <T extends RequestInstance>(callback: (data: RequestLoadingEventType<T>) => void) => VoidFunction;
1419
+ onLoadingByQueue: <T extends RequestInstance>(queryKey: string, callback: (data: RequestLoadingEventType<T>) => void) => VoidFunction;
1420
+ onLoadingByCache: <T extends RequestInstance>(cacheKey: string, callback: (data: RequestLoadingEventType<T>) => void) => VoidFunction;
1421
+ onLoadingById: <T extends RequestInstance>(requestId: string, callback: (data: RequestLoadingEventType<T>) => void) => VoidFunction;
1422
+ onRequestStart: <T extends RequestInstance>(callback: (details: RequestEventType<T>) => void) => VoidFunction;
1423
+ onRequestStartByQueue: <T extends RequestInstance>(queryKey: string, callback: (details: RequestEventType<T>) => void) => VoidFunction;
1424
+ onRequestStartById: <T extends RequestInstance>(requestId: string, callback: (details: RequestEventType<T>) => void) => VoidFunction;
1425
+ onResponseStart: <T extends RequestInstance>(callback: (details: RequestEventType<T>) => void) => VoidFunction;
1426
+ onResponseStartByQueue: <T extends RequestInstance>(queryKey: string, callback: (details: RequestEventType<T>) => void) => VoidFunction;
1427
+ onResponseStartById: <T extends RequestInstance>(requestId: string, callback: (details: RequestEventType<T>) => void) => VoidFunction;
1428
+ onUploadProgress: <T extends RequestInstance = RequestInstance>(callback: (data: RequestProgressEventType<T>) => void) => VoidFunction;
1429
+ onUploadProgressByQueue: <T extends RequestInstance = RequestInstance>(queryKey: string, callback: (data: RequestProgressEventType<T>) => void) => VoidFunction;
1430
+ onUploadProgressById: <T extends RequestInstance = RequestInstance>(requestId: string, callback: (data: RequestProgressEventType<T>) => void) => VoidFunction;
1431
+ onDownloadProgress: <T extends RequestInstance = RequestInstance>(callback: (data: RequestProgressEventType<T>) => void) => VoidFunction;
1432
+ onDownloadProgressByQueue: <T extends RequestInstance = RequestInstance>(queryKey: string, callback: (data: RequestProgressEventType<T>) => void) => VoidFunction;
1433
+ onDownloadProgressById: <T extends RequestInstance = RequestInstance>(requestId: string, callback: (data: RequestProgressEventType<T>) => void) => VoidFunction;
1434
+ onResponse: <T extends RequestInstance>(callback: (data: RequestResponseEventType<T>) => void) => VoidFunction;
1435
+ onResponseByCache: <T extends RequestInstance>(cacheKey: string, callback: (data: RequestResponseEventType<T>) => void) => VoidFunction;
1436
+ onResponseById: <T extends RequestInstance>(requestId: string, callback: (data: RequestResponseEventType<T>) => void) => VoidFunction;
1437
+ onAbort: <T extends RequestInstance = RequestInstance>(callback: (request: RequestEventType<T>) => void) => VoidFunction;
1438
+ onAbortByKey: <T extends RequestInstance = RequestInstance>(abortKey: string, callback: (request: RequestEventType<T>) => void) => VoidFunction;
1439
+ onAbortById: <T extends RequestInstance = RequestInstance>(requestId: string, callback: (data: RequestEventType<T>) => void) => VoidFunction;
1440
+ onRemove: <T extends RequestInstance = RequestInstance>(callback: (data: RequestRemovedEventType<T>) => void) => VoidFunction;
1441
+ onRemoveByQueue: <T extends RequestInstance = RequestInstance>(queryKey: string, callback: (data: RequestRemovedEventType<T>) => void) => VoidFunction;
1442
+ onRemoveById: <T extends RequestInstance = RequestInstance>(requestId: string, callback: (data: RequestRemovedEventType<T>) => void) => VoidFunction;
836
1443
  };
837
- type RequestInterceptorType = (request: RequestInstance) => Promise<RequestInstance> | RequestInstance;
838
- type ResponseInterceptorType<Response = any, Error = any, Adapter extends AdapterInstance = AdapterType> = (response: ResponseReturnType<Response, Error, Adapter>, request: RequestInstance) => Promise<ResponseReturnType<any, any, Adapter>> | ResponseReturnType<any, any, Adapter>;
839
- type StringifyCallbackType = (queryParams: QueryParamsType | string | NegativeTypes) => string;
840
- type DefaultEndpointMapper = (endpoint: any) => string;
841
-
842
- declare const stringifyValue: (response: string | unknown) => string;
843
- declare const interceptRequest: (interceptors: RequestInterceptorType[], request: RequestInstance) => Promise<RequestInstance>;
844
- declare const interceptResponse: <GlobalErrorType, Adapter extends AdapterInstance>(interceptors: ResponseInterceptorType[], response: ResponseReturnType<any, GlobalErrorType, Adapter>, request: RequestInstance) => Promise<ResponseReturnType<any, GlobalErrorType, Adapter>>;
845
- declare const getAdapterHeaders: (request: RequestInstance) => HeadersInit;
846
- declare const getAdapterPayload: (data: unknown) => string | FormData;
847
- declare const stringifyQueryParams: (queryParams: QueryParamsType | string | NegativeTypes, options?: QueryStringifyOptionsType) => string;
848
1444
 
849
- declare const stringifyDefaultOptions: {
850
- readonly strict: true;
851
- readonly encode: true;
852
- readonly arrayFormat: "bracket";
853
- readonly arraySeparator: "bracket";
854
- readonly sort: false;
855
- readonly skipNull: true;
856
- readonly skipEmptyString: true;
1445
+ type RequestLoadingEventType<T extends RequestInstance> = {
1446
+ loading: boolean;
1447
+ isRetry: boolean;
1448
+ isOffline: boolean;
1449
+ } & RequestEventType<T>;
1450
+ type RequestProgressEventType<T extends RequestInstance> = ProgressType & RequestEventType<T>;
1451
+ type RequestEventType<T extends RequestInstance> = {
1452
+ request: T;
1453
+ requestId: string;
1454
+ };
1455
+ type RequestRemovedEventType<T extends RequestInstance> = {
1456
+ request: T;
1457
+ requestId: string;
1458
+ /** @true when we receive any response, @false if removed before response is received */
1459
+ resolved: boolean;
1460
+ };
1461
+ type RequestResponseEventType<T extends RequestInstance> = {
1462
+ request: T;
1463
+ requestId: string;
1464
+ response: ResponseType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>;
1465
+ details: ResponseDetailsType;
1466
+ };
1467
+ type RequestDeduplicatedEventType<T extends RequestInstance> = RequestEventType<T> & {
1468
+ deduplicatedRequest: T;
1469
+ };
1470
+ type ResponseDetailsType = {
1471
+ /** If it's retry request we can see which attempt is it */
1472
+ retries: number;
1473
+ /** If request was canceled */
1474
+ isCanceled: boolean;
1475
+ /** If error from offline status */
1476
+ isOffline: boolean;
1477
+ /** When added to dispatcher's queue (pre-middleware which could take time) */
1478
+ addedTimestamp: number;
1479
+ /** When request is picked from queue and started to be sent */
1480
+ triggerTimestamp: number;
1481
+ /** When adapter triggers request (after all middlewares) */
1482
+ requestTimestamp: number;
1483
+ /** When we receive response */
1484
+ responseTimestamp: number;
857
1485
  };
858
1486
 
859
- declare const mocker: <T extends AdapterInstance = AdapterType<Partial<XMLHttpRequest>, HttpMethodsType, number, AdapterExtraType, string | QueryParamsType, string>>(request: RequestInstance, { onError, onResponseEnd, onTimeoutError, onRequestEnd, createAbortListener, onResponseProgress, onRequestProgress, onResponseStart, onBeforeRequest, onRequestStart, onSuccess, }: Pick<{
860
- fullUrl: string;
861
- data: any;
862
- headers: HeadersInit;
863
- payload: any;
864
- config: ExtractAdapterOptionsType<T>;
865
- getAbortController: () => AbortController;
866
- getRequestStartTimestamp: () => number;
867
- getResponseStartTimestamp: () => number;
868
- createAbortListener: (status: ExtractAdapterStatusType<T>, abortExtra: ExtractAdapterExtraType<T>, callback: () => void, resolve: (value: ResponseReturnErrorType<ExtractErrorType<T>, T>) => void) => () => void;
869
- onBeforeRequest: () => void;
870
- onRequestStart: (progress?: ProgressDataType) => number;
871
- onRequestProgress: (progress: ProgressDataType) => number;
872
- onRequestEnd: () => number;
873
- onResponseStart: (progress?: ProgressDataType) => number;
874
- onResponseProgress: (progress: ProgressDataType) => number;
875
- onResponseEnd: () => number;
876
- onSuccess: (responseData: any, status: ExtractAdapterStatusType<T>, extra: ExtractAdapterExtraType<T>, resolve: (value: ResponseReturnErrorType<any, T>) => void) => Promise<ResponseReturnSuccessType<ExtractResponseType<T>, T>>;
877
- onAbortError: (status: ExtractAdapterStatusType<T>, extra: ExtractAdapterExtraType<T>, resolve: (value: ResponseReturnErrorType<ExtractErrorType<T>, T>) => void) => Promise<ResponseReturnErrorType<any, T>>;
878
- onTimeoutError: (status: ExtractAdapterStatusType<T>, extra: ExtractAdapterExtraType<T>, resolve: (value: ResponseReturnErrorType<ExtractErrorType<T>, T>) => void) => Promise<ResponseReturnErrorType<any, T>>;
879
- onUnexpectedError: (status: ExtractAdapterStatusType<T>, extra: ExtractAdapterExtraType<T>, resolve: (value: ResponseReturnErrorType<ExtractErrorType<T>, T>) => void) => Promise<ResponseReturnErrorType<any, T>>;
880
- onError: (error: any, status: ExtractAdapterStatusType<T>, extra: ExtractAdapterExtraType<T>, resolve: (value: ResponseReturnErrorType<any, T>) => void) => Promise<ResponseReturnErrorType<any, T>>;
881
- makeRequest: (apiCall: (resolve: (value: ResponseReturnType<any, any, T> | PromiseLike<ResponseReturnType<any, any, T>>) => void) => void) => Promise<ResponseReturnType<any, any, T>>;
882
- }, "onRequestStart" | "onResponseStart" | "onError" | "onSuccess" | "onResponseEnd" | "onTimeoutError" | "onRequestEnd" | "createAbortListener" | "onResponseProgress" | "onRequestProgress" | "onBeforeRequest">) => Promise<ResponseReturnType<any, any, any>>;
1487
+ /**
1488
+ * This class is used across the Hyper Fetch library to provide unified logging system with necessary setup per each client.
1489
+ * We can set up the logging level based on available values. This manager enable to initialize the logging instance per individual module
1490
+ * like Client, Request etc. Which can give you better feedback on the logging itself.
1491
+ */
1492
+ declare class LoggerManager {
1493
+ private options?;
1494
+ logger: LoggerType;
1495
+ level: LogLevel;
1496
+ modules: string[] | undefined;
1497
+ emitter: EventEmitter$1;
1498
+ private client;
1499
+ constructor(options?: LoggerOptionsType | undefined);
1500
+ setSeverity: (level: LogLevel) => void;
1501
+ setModules: (modules: string[] | undefined) => void;
1502
+ initialize: (client: Pick<ClientInstance, "debug">, module: string) => LoggerMethods;
1503
+ private log;
1504
+ }
883
1505
 
884
- type RequestMockType<Response> = {
885
- data: Response | Response[] | (() => Response);
886
- status?: number | string;
887
- success?: boolean;
888
- config?: {
889
- timeout?: boolean;
890
- requestTime?: number;
891
- responseTime?: number;
892
- totalUploaded?: number;
893
- totalDownloaded?: number;
894
- };
895
- extra?: any;
1506
+ declare const getTime: () => string;
1507
+ declare const logger: LoggerType;
1508
+
1509
+ type LogLevel = "debug" | "info" | "warning" | "error";
1510
+ type LoggerOptionsType = {
1511
+ logger?: LoggerType;
1512
+ level?: LogLevel;
1513
+ modules?: string[];
1514
+ };
1515
+ type LogData<Data extends Record<string, any>> = {
1516
+ /** Some Message / https://google.com */
1517
+ title: string;
1518
+ /** Some contextual data */
1519
+ extra: Data;
1520
+ };
1521
+ type LoggerArgs = LogDataTypes & {
1522
+ /** "debug" | "info" | "warning" | "error" */
1523
+ level: LogLevel;
1524
+ /** Client / Request / Cache / Dispatcher / useFetch etc. */
1525
+ module: string;
896
1526
  };
897
- type RequestDataMockTypes<Response, Request extends RequestInstance> = RequestMockType<Response> | RequestMockType<Response>[] | ((r: Request) => RequestMockType<Response>) | ((r: Request) => RequestMockType<Response>)[] | ((r: Request) => Promise<RequestMockType<Response>>) | ((r: Request) => Promise<RequestMockType<Response>>)[];
898
- type GeneratorReturnMockTypes<Response, Request extends RequestInstance> = RequestMockType<Response> | ((r: Request) => RequestMockType<Response>) | ((r: Request) => Promise<RequestMockType<Response>>);
1527
+ type LoggerType = (data: LoggerArgs) => void;
1528
+ type LoggerMethods = Record<LogLevel, (data: LogDataTypes) => void>;
1529
+ type LogRequestEventType = LogData<{
1530
+ request: RequestInstance;
1531
+ [key: string]: unknown;
1532
+ }>;
1533
+ type LogResponseEventType = LogData<{
1534
+ request: RequestInstance;
1535
+ response: ResponseType<any, any, AdapterInstance>;
1536
+ requestId: string;
1537
+ [key: string]: unknown;
1538
+ }>;
1539
+ type LogSystemEventType = LogData<{
1540
+ [key: string]: unknown;
1541
+ }>;
1542
+ type LogDataTypes = ({
1543
+ type: "request";
1544
+ } & LogRequestEventType) | ({
1545
+ type: "response";
1546
+ } & LogResponseEventType) | ({
1547
+ type: "system";
1548
+ } & LogSystemEventType);
1549
+
1550
+ declare const logLevelOrder: LogLevel[];
1551
+ declare const loggerStyles: Record<LogLevel, string>;
1552
+ declare const loggerColors: Record<LogLevel, string>;
1553
+
1554
+ declare const getResponseHeaders: (headersString: string) => Record<string, string>;
1555
+ declare const parseResponse: (response: string | unknown) => any;
1556
+ declare const handleResponse: (responseChunks: any[], responseType: HttpAdapterRequest["responseType"], responseEncoding: BufferEncoding) => any;
1557
+ declare const parseErrorResponse: <T extends RequestInstance>(response: unknown) => ExtractErrorType<T>;
1558
+ declare const stringifyQueryParams: (queryParams: QueryParamsType | string | EmptyTypes, options?: QueryStringifyOptionsType) => string;
899
1559
 
900
1560
  /**
901
- * Fetch request it is designed to prepare the necessary setup to execute the request to the server.
902
- * We can set up basic options for example endpoint, method, headers and advanced settings like cache, invalidation patterns, concurrency, retries and much, much more.
903
- * :::info Usage
904
- * We should not use this class directly in the standard development flow. We can initialize it using the `createRequest` method on the **Client** class.
905
- * :::
906
- *
907
- * @attention
908
- * The most important thing about the request is that it keeps data in the format that can be dumped. This is necessary for the persistence and different dispatcher storage types.
909
- * This class doesn't have any callback methods by design and communicate with dispatcher and cache by events.
1561
+ * Base Adapter
910
1562
  */
911
- declare class Request<Response, Payload, QueryParams, GlobalError, // Global Error Type
912
- LocalError, // Additional Error for specific endpoint
913
- Endpoint extends string, Adapter extends AdapterInstance = AdapterType, HasData extends true | false = false, HasParams extends true | false = false, HasQuery extends true | false = false> {
914
- readonly client: Client<GlobalError, Adapter>;
915
- readonly requestOptions: RequestOptionsType<Endpoint, ExtractAdapterOptionsType<Adapter>, ExtractAdapterMethodType<Adapter>>;
916
- readonly requestJSON?: RequestCurrentType<Payload, QueryParams, Endpoint, ExtractAdapterOptionsType<Adapter>, ExtractAdapterMethodType<Adapter>> | undefined;
917
- endpoint: Endpoint;
918
- headers?: HeadersInit;
919
- auth: boolean;
920
- method: ExtractAdapterMethodType<Adapter>;
921
- params: ExtractRouteParams<Endpoint> | NegativeTypes;
922
- data: PayloadType<Payload>;
923
- queryParams: QueryParams | NegativeTypes;
924
- options?: ExtractAdapterOptionsType<Adapter> | undefined;
925
- cancelable: boolean;
926
- retry: number;
927
- retryTime: number;
928
- garbageCollection: number;
929
- cache: boolean;
930
- cacheTime: number;
931
- queued: boolean;
932
- offline: boolean;
933
- abortKey: string;
934
- cacheKey: string;
935
- queueKey: string;
936
- effectKey: string;
937
- used: boolean;
938
- deduplicate: boolean;
939
- deduplicateTime: number;
940
- dataMapper?: PayloadMapperType<Payload>;
941
- mock?: Generator<GeneratorReturnMockTypes<Response, this>, GeneratorReturnMockTypes<Response, this>, GeneratorReturnMockTypes<Response, this>>;
942
- mockData?: RequestDataMockTypes<Response, this>;
943
- isMockEnabled: boolean;
944
- requestMapper?: RequestMapper<this, any>;
945
- responseMapper?: ResponseMapper<this, any, any>;
946
- private updatedAbortKey;
947
- private updatedCacheKey;
948
- private updatedQueueKey;
949
- private updatedEffectKey;
950
- constructor(client: Client<GlobalError, Adapter>, requestOptions: RequestOptionsType<Endpoint, ExtractAdapterOptionsType<Adapter>, ExtractAdapterMethodType<Adapter>>, requestJSON?: RequestCurrentType<Payload, QueryParams, Endpoint, ExtractAdapterOptionsType<Adapter>, ExtractAdapterMethodType<Adapter>> | undefined);
951
- setHeaders: (headers: HeadersInit) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
952
- setAuth: (auth: boolean) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
953
- setParams: <P extends ExtractRouteParams<Endpoint>>(params: P) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, P extends null ? false : true, HasQuery>;
954
- setData: <D extends Payload>(data: D) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, D extends null ? false : true, HasParams, HasQuery>;
955
- setQueryParams: (queryParams: QueryParams) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, true>;
956
- setOptions: (options: ExtractAdapterOptionsType<Adapter>) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, true>;
957
- setCancelable: (cancelable: boolean) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
958
- setRetry: (retry: RequestOptionsType<Endpoint, ExtractAdapterOptionsType<Adapter>, ExtractAdapterMethodType<Adapter>>["retry"]) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
959
- setRetryTime: (retryTime: RequestOptionsType<Endpoint, ExtractAdapterOptionsType<Adapter>, ExtractAdapterMethodType<Adapter>>["retryTime"]) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
960
- setGarbageCollection: (garbageCollection: RequestOptionsType<Endpoint, ExtractAdapterOptionsType<Adapter>, ExtractAdapterMethodType<Adapter>>["garbageCollection"]) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
961
- setCache: (cache: RequestOptionsType<Endpoint, ExtractAdapterOptionsType<Adapter>, ExtractAdapterMethodType<Adapter>>["cache"]) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
962
- setCacheTime: (cacheTime: RequestOptionsType<Endpoint, ExtractAdapterOptionsType<Adapter>, ExtractAdapterMethodType<Adapter>>["cacheTime"]) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
963
- setQueued: (queued: boolean) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
964
- setAbortKey: (abortKey: string) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
965
- setCacheKey: (cacheKey: string) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
966
- setQueueKey: (queueKey: string) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
967
- setEffectKey: (effectKey: string) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
968
- setDeduplicate: (deduplicate: boolean) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
969
- setDeduplicateTime: (deduplicateTime: number) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
970
- setUsed: (used: boolean) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
971
- setOffline: (offline: boolean) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
972
- setMock: (mockData: RequestDataMockTypes<Response, this>) => this;
973
- removeMock: () => this;
974
- setEnableMocking: (isMockEnabled: boolean) => this;
975
- /**
976
- * Mappers
1563
+ type HttpAdapterType = DeclareAdapterType<{
1564
+ adapterOptions: HttpAdapterOptionsType;
1565
+ methodType: HttpMethodsType;
1566
+ statusType: HttpStatusType;
1567
+ extra: HttpAdapterExtraType;
1568
+ queryParams: QueryParamsType | string | null;
1569
+ endpointType: string;
1570
+ queryParamsMapperType: typeof stringifyQueryParams;
1571
+ }>;
1572
+ /**
1573
+ * Options
1574
+ */
1575
+ interface HttpAdapterRequest extends Omit<XMLHttpRequest, "responseType"> {
1576
+ responseType: XMLHttpRequestResponseType | "stream";
1577
+ }
1578
+ type HttpAdapterOptionsType = Partial<HttpAdapterRequest>;
1579
+ type HttpAdapterExtraType = {
1580
+ headers: Record<string, string>;
1581
+ };
1582
+ type HttpAdapterHeadersProps = {
1583
+ isFormData: boolean;
1584
+ headers: HeadersInit | undefined;
1585
+ };
1586
+ type QueryStringifyOptionsType = {
1587
+ /**
1588
+ * Strict URI encoding
977
1589
  */
1590
+ strict?: boolean;
978
1591
  /**
979
- * Map data before it gets send to the server
980
- * @param dataMapper
981
- * @returns
1592
+ * Encode keys and values
982
1593
  */
983
- setDataMapper: <DataMapper extends (data: Payload) => any | Promise<any>>(dataMapper: DataMapper) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
1594
+ encode?: boolean;
984
1595
  /**
985
- * Map request before it gets send to the server
986
- * @param requestMapper mapper of the request
987
- * @returns new request
1596
+ * Array encoding type
988
1597
  */
989
- setRequestMapper: <NewRequest extends RequestInstance>(requestMapper: RequestMapper<this, NewRequest>) => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
1598
+ arrayFormat?: "bracket" | "index" | "comma" | "separator" | "bracket-separator" | "none";
990
1599
  /**
991
- * Map the response to the new interface
992
- * @param responseMapper our mapping callback
993
- * @returns new response
1600
+ * Array format separator
994
1601
  */
995
- setResponseMapper: <NewResponse = Response, NewError = GlobalError | LocalError>(responseMapper?: ResponseMapper<this, NewResponse, NewError>) => Request<NewResponse, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
996
- private paramsMapper;
997
- toJSON(): RequestJSON<this, ExtractAdapterOptionsType<Adapter>, QueryParams>;
998
- clone<D extends true | false = HasData, P extends true | false = HasParams, Q extends true | false = HasQuery>(options?: RequestCurrentType<Payload, QueryParams, Endpoint, ExtractAdapterOptionsType<Adapter>, ExtractAdapterMethodType<Adapter>>): Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, D, P, Q>;
999
- abort: () => Request<Response, Payload, QueryParams, GlobalError, LocalError, Endpoint, Adapter, HasData, HasParams, HasQuery>;
1602
+ arraySeparator?: string;
1000
1603
  /**
1001
- * Method to use the request WITHOUT adding it to cache and queues. This mean it will make simple request without queue side effects.
1002
- * @param options
1003
- * @disableReturns
1004
- * @returns
1005
- * ```tsx
1006
- * Promise<[Data | null, Error | null, HttpStatus]>
1007
- * ```
1604
+ * Skip keys with null values
1008
1605
  */
1009
- exec: RequestSendType<this>;
1606
+ skipNull?: boolean;
1010
1607
  /**
1011
- * Method used to perform requests with usage of cache and queues
1012
- * @param options
1013
- * @param requestCallback
1014
- * @disableReturns
1015
- * @returns
1016
- * ```tsx
1017
- * Promise<[Data | null, Error | null, HttpStatus]>
1018
- * ```
1608
+ * Skip keys with empty string
1019
1609
  */
1020
- send: RequestSendType<this>;
1021
- }
1022
-
1023
- type AdapterProgressEventType = {
1024
- total: number;
1025
- loaded: number;
1026
- };
1027
- type AdapterProgressType = {
1028
- progress: number;
1029
- timeLeft: number;
1030
- sizeLeft: number;
1031
- };
1032
- /**
1033
- * Dump of the request used to later recreate it
1034
- */
1035
- type RequestJSON<Request extends RequestInstance, AdapterOptions = unknown, QueryParams = QueryParamsType, Params = ExtractParamsType<Request>> = {
1036
- requestOptions: RequestOptionsType<string, AdapterOptions | ExtractAdapterType<Request>, ExtractAdapterMethodType<ExtractAdapterType<Request>>>;
1037
- endpoint: string;
1038
- method: ExtractAdapterMethodType<ExtractAdapterType<Request>>;
1039
- headers?: HeadersInit;
1040
- auth: boolean;
1041
- cancelable: boolean;
1042
- retry: number;
1043
- retryTime: number;
1044
- garbageCollection: number;
1045
- cache: boolean;
1046
- cacheTime: number;
1047
- queued: boolean;
1048
- offline: boolean;
1049
- disableResponseInterceptors: boolean | undefined;
1050
- disableRequestInterceptors: boolean | undefined;
1051
- options?: AdapterOptions | ExtractAdapterOptionsType<ExtractAdapterType<Request>>;
1052
- data: PayloadType<ExtractPayloadType<Request>>;
1053
- params: Params | NegativeTypes;
1054
- queryParams: QueryParams | NegativeTypes;
1055
- abortKey: string;
1056
- cacheKey: string;
1057
- queueKey: string;
1058
- effectKey: string;
1059
- used: boolean;
1060
- updatedAbortKey: boolean;
1061
- updatedCacheKey: boolean;
1062
- updatedQueueKey: boolean;
1063
- updatedEffectKey: boolean;
1064
- deduplicate: boolean;
1065
- deduplicateTime: number;
1610
+ skipEmptyString?: boolean;
1611
+ /**
1612
+ * Parsing function for date type query param
1613
+ */
1614
+ dateParser?: (value: QueryParamType) => string;
1615
+ /**
1616
+ * Parsing function for object type query param
1617
+ */
1618
+ objectParser?: (value: QueryParamType) => string;
1066
1619
  };
1620
+ type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "base64url" | "latin1" | "binary" | "hex";
1621
+
1622
+ declare const HttpAdapter: () => HttpAdapterType;
1623
+
1624
+ declare const defaultTimeout: number;
1625
+ declare const xhrExtra: HttpAdapterExtraType;
1626
+
1067
1627
  /**
1068
- * Configuration options for request creation
1628
+ * **Client** is a class that allows you to configure the connection with the server and then use it to create
1629
+ * requests. It allows you to set global defaults for the requests configuration, query params configuration.
1630
+ * It is also orchestrator for all of the HyperFetch modules like Cache, Dispatcher, AppManager, LoggerManager,
1631
+ * RequestManager and more.
1069
1632
  */
1070
- type RequestOptionsType<GenericEndpoint extends string, AdapterOptions extends Record<string, any>, RequestMethods = HttpMethodsType> = {
1633
+ declare class Client$1<GlobalErrorType extends ClientErrorType = Error, Adapter extends AdapterInstance = HttpAdapterType> {
1634
+ options: ClientOptionsType<Client$1<GlobalErrorType, Adapter>>;
1635
+ readonly url: string;
1636
+ debug: boolean;
1637
+ unstable_onErrorCallbacks: ResponseInterceptorType<ClientInstance>[];
1638
+ unstable_onSuccessCallbacks: ResponseInterceptorType<ClientInstance>[];
1639
+ unstable_onResponseCallbacks: ResponseInterceptorType<ClientInstance>[];
1640
+ unstable_onAuthCallbacks: RequestInterceptorType[];
1641
+ unstable_onRequestCallbacks: RequestInterceptorType[];
1642
+ loggerManager: LoggerManager;
1643
+ requestManager: RequestManager;
1644
+ appManager: AppManager;
1645
+ adapter: Adapter;
1646
+ cache: Cache<Adapter>;
1647
+ fetchDispatcher: Dispatcher<Adapter>;
1648
+ submitDispatcher: Dispatcher<Adapter>;
1649
+ isMockerEnabled: boolean;
1650
+ plugins: PluginInstance[];
1651
+ /** @internal */
1652
+ unstable_abortKeyMapper: (request: RequestInstance) => string;
1653
+ /** @internal */
1654
+ unstable_cacheKeyMapper: (request: RequestInstance) => string;
1655
+ /** @internal */
1656
+ unstable_queryKeyMapper: (request: RequestInstance) => string;
1657
+ /** @internal */
1658
+ unstable_requestIdMapper: (request: RequestInstance) => string;
1659
+ logger: LoggerMethods;
1660
+ constructor(options: ClientOptionsType<Client$1<GlobalErrorType, Adapter>>);
1071
1661
  /**
1072
- * Determine the endpoint for request request
1662
+ * This method enables the logger usage and display the logs in console
1073
1663
  */
1074
- endpoint: GenericEndpoint;
1664
+ setDebug: (enabled: boolean) => Client$1<GlobalErrorType, Adapter>;
1075
1665
  /**
1076
- * Custom headers for request
1666
+ * Set the logger severity of the messages displayed to the console
1077
1667
  */
1078
- headers?: HeadersInit;
1668
+ setLogLevel: (severity: LogLevel) => Client$1<GlobalErrorType, Adapter>;
1079
1669
  /**
1080
- * Should the onAuth method get called on this request
1670
+ * Set the new logger instance to the Client
1081
1671
  */
1082
- auth?: boolean;
1672
+ setLogger: (callback: (Client: ClientInstance) => LoggerManager) => Client$1<GlobalErrorType, Adapter>;
1083
1673
  /**
1084
- * Request method GET | POST | PATCH | PUT | DELETE or set of method names handled by adapter
1674
+ * Set globally if mocking should be enabled or disabled for all client requests.
1675
+ * @param isMockerEnabled
1085
1676
  */
1086
- method?: RequestMethods;
1677
+ setEnableGlobalMocking: (isMockerEnabled: boolean) => this;
1087
1678
  /**
1088
- * Should enable cancelable mode in the Dispatcher
1679
+ * Set custom http adapter to handle graphql, rest, firebase or others
1089
1680
  */
1090
- cancelable?: boolean;
1681
+ setAdapter: <NewAdapter extends AdapterInstance>(adapter: NewAdapter) => Client$1<GlobalErrorType, NewAdapter>;
1091
1682
  /**
1092
- * Retry count when request is failed
1683
+ * Method of manipulating requests before sending the request. We can for example add custom header with token to the request which request had the auth set to true.
1093
1684
  */
1094
- retry?: number;
1685
+ onAuth: (callback: RequestInterceptorType) => Client$1<GlobalErrorType, Adapter>;
1095
1686
  /**
1096
- * Retry time delay between retries
1687
+ * Method for removing listeners on auth.
1688
+ * */
1689
+ removeOnAuthInterceptors: (callbacks: RequestInterceptorType[]) => Client$1<GlobalErrorType, Adapter>;
1690
+ /**
1691
+ * Method for intercepting error responses. It can be used for example to refresh tokens.
1097
1692
  */
1098
- retryTime?: number;
1693
+ onError: <ErrorType = null>(callback: ResponseInterceptorType<ClientInstance, any, ErrorType | GlobalErrorType>) => Client$1<GlobalErrorType, Adapter>;
1099
1694
  /**
1100
- * Should we trigger garbage collection or leave data in memory
1695
+ * Method for removing listeners on error.
1696
+ * */
1697
+ removeOnErrorInterceptors: (callbacks: ResponseInterceptorType<ClientInstance, any, null | GlobalErrorType>[]) => Client$1<GlobalErrorType, Adapter>;
1698
+ /**
1699
+ * Method for intercepting success responses.
1101
1700
  */
1102
- garbageCollection?: number;
1701
+ onSuccess: <ErrorType = null>(callback: ResponseInterceptorType<ClientInstance, any, ErrorType | GlobalErrorType>) => Client$1<GlobalErrorType, Adapter>;
1103
1702
  /**
1104
- * Should we save the response to cache
1703
+ * Method for removing listeners on success.
1704
+ * */
1705
+ removeOnSuccessInterceptors: (callbacks: ResponseInterceptorType<ClientInstance, any, null | GlobalErrorType>[]) => Client$1<GlobalErrorType, Adapter>;
1706
+ /**
1707
+ * Method of manipulating requests before sending the request.
1105
1708
  */
1106
- cache?: boolean;
1709
+ onRequest: (callback: RequestInterceptorType) => Client$1<GlobalErrorType, Adapter>;
1107
1710
  /**
1108
- * Time for which the cache is considered up-to-date
1711
+ * Method for removing listeners on request.
1712
+ * */
1713
+ removeOnRequestInterceptors: (callbacks: RequestInterceptorType[]) => Client$1<GlobalErrorType, Adapter>;
1714
+ /**
1715
+ * Method for intercepting any responses.
1109
1716
  */
1110
- cacheTime?: number;
1717
+ onResponse: <ErrorType = null>(callback: ResponseInterceptorType<ClientInstance, any, ErrorType | GlobalErrorType>) => Client$1<GlobalErrorType, Adapter>;
1111
1718
  /**
1112
- * Should the requests from this request be send one-by-one
1719
+ * Method for removing listeners on request.
1720
+ * */
1721
+ removeOnResponseInterceptors: (callbacks: ResponseInterceptorType<ClientInstance, any, null | GlobalErrorType>[]) => Client$1<GlobalErrorType, Adapter>;
1722
+ /**
1723
+ * Add persistent plugins which trigger on the request lifecycle
1113
1724
  */
1114
- queued?: boolean;
1725
+ addPlugin: (plugin: PluginInstance) => this;
1115
1726
  /**
1116
- * Do we want to store request made in offline mode for latter use when we go back online
1727
+ * Remove plugins from Client
1117
1728
  */
1118
- offline?: boolean;
1729
+ removePlugin: (plugin: PluginInstance) => this;
1730
+ triggerPlugins: <Key extends keyof PluginMethods<Client$1>>(key: Key, data: PluginMethodParameters<Key, Client$1>) => this;
1119
1731
  /**
1120
- * Disable post-request interceptors
1732
+ * Key setters
1121
1733
  */
1122
- disableResponseInterceptors?: boolean;
1734
+ setAbortKeyMapper: (callback: (request: RequestInstance) => string) => this;
1735
+ setCacheKeyMapper: (callback: (request: RequestInstance) => string) => this;
1736
+ setQueryKeyMapper: (callback: (request: RequestInstance) => string) => this;
1737
+ setRequestIdMapper: (callback: (request: RequestInstance) => string) => this;
1123
1738
  /**
1124
- * Disable pre-request interceptors
1739
+ * Helper used by http adapter to apply the modifications on response error
1740
+ * @private
1125
1741
  */
1126
- disableRequestInterceptors?: boolean;
1742
+ unstable_modifyAuth: (request: RequestInstance) => Promise<RequestInstance>;
1127
1743
  /**
1128
- * Additional options for your adapter, by default XHR options
1744
+ * Private helper to run async pre-request processing
1745
+ * @private
1129
1746
  */
1130
- options?: AdapterOptions;
1747
+ unstable_modifyRequest: (request: RequestInstance) => Promise<RequestInstance>;
1131
1748
  /**
1132
- * Key which will be used to cancel requests. Autogenerated by default.
1749
+ * Private helper to run async on-error response processing
1750
+ * @private
1133
1751
  */
1134
- abortKey?: string;
1752
+ unstable_modifyErrorResponse: (response: ResponseType<any, GlobalErrorType, Adapter>, request: RequestInstance) => Promise<ResponseType<any, GlobalErrorType, AdapterInstance>>;
1135
1753
  /**
1136
- * Key which will be used to cache requests. Autogenerated by default.
1754
+ * Private helper to run async on-success response processing
1755
+ * @private
1137
1756
  */
1138
- cacheKey?: string;
1757
+ unstable_modifySuccessResponse: (response: ResponseType<any, GlobalErrorType, Adapter>, request: RequestInstance) => Promise<ResponseType<any, GlobalErrorType, AdapterInstance>>;
1139
1758
  /**
1140
- * Key which will be used to queue requests. Autogenerated by default.
1759
+ * Private helper to run async response processing
1760
+ * @private
1141
1761
  */
1142
- queueKey?: string;
1762
+ unstable_modifyResponse: (response: ResponseType<any, GlobalErrorType, Adapter>, request: RequestInstance) => Promise<ResponseType<any, GlobalErrorType, AdapterInstance>>;
1143
1763
  /**
1144
- * Key which will be used to use effects. Autogenerated by default.
1764
+ * Clears the Client instance and remove all listeners on it's dependencies
1145
1765
  */
1146
- effectKey?: string;
1766
+ clear: () => void;
1147
1767
  /**
1148
- * Should we deduplicate two requests made at the same time into one
1768
+ * Hydrate your SSR cache data
1769
+ * @param hydrationData
1770
+ * @param options
1149
1771
  */
1150
- deduplicate?: boolean;
1772
+ hydrate: (hydrationData: (HydrateDataType | EmptyTypes)[], options?: Partial<HydrationOptions> | ((item: HydrateDataType) => Partial<HydrationOptions>)) => void;
1151
1773
  /**
1152
- * Time of pooling for the deduplication to be active (default 10ms)
1774
+ * Create requests based on the Client setup
1775
+ *
1776
+ * @template Response Your response
1153
1777
  */
1154
- deduplicateTime?: number;
1155
- };
1156
- type PayloadMapperType<Payload> = <NewDataType>(data: Payload) => NewDataType;
1157
- type PayloadType<Payload> = Payload | NegativeTypes;
1158
- type RequestCurrentType<Payload, QueryParams, GenericEndpoint extends string, AdapterOptions, MethodsType = HttpMethodsType> = {
1159
- used?: boolean;
1160
- params?: ExtractRouteParams<GenericEndpoint> | NegativeTypes;
1161
- queryParams?: QueryParams | NegativeTypes;
1162
- data?: PayloadType<Payload>;
1163
- headers?: HeadersInit;
1164
- updatedAbortKey?: boolean;
1165
- updatedCacheKey?: boolean;
1166
- updatedQueueKey?: boolean;
1167
- updatedEffectKey?: boolean;
1168
- } & Partial<NullableKeys<RequestOptionsType<GenericEndpoint, AdapterOptions, MethodsType>>>;
1169
- type ParamType = string | number;
1170
- type ParamsType = Record<string, ParamType>;
1171
- type ExtractRouteParams<T extends string> = string extends T ? NegativeTypes : T extends `${string}:${infer Param}/${infer Rest}` ? {
1172
- [k in Param | keyof ExtractRouteParams<Rest>]: ParamType;
1173
- } : T extends `${string}:${infer Param}` ? {
1174
- [k in Param]: ParamType;
1175
- } : NegativeTypes;
1176
- type FetchOptionsType<AdapterOptions> = Omit<Partial<RequestOptionsType<string, AdapterOptions>>, "endpoint" | "method">;
1177
- /**
1178
- * It will check if the query params are already set
1179
- */
1180
- type FetchQueryParamsType<QueryParams, HasQuery extends true | false = false> = HasQuery extends true ? {
1181
- queryParams?: NegativeTypes;
1182
- } : {
1183
- queryParams?: QueryParams;
1184
- };
1185
- /**
1186
- * If the request endpoint parameters are not filled it will throw an error
1187
- */
1188
- type FetchParamsType<Endpoint extends string, HasParams extends true | false> = ExtractRouteParams<Endpoint> extends NegativeTypes ? {
1189
- params?: NegativeTypes;
1190
- } : HasParams extends true ? {
1191
- params?: NegativeTypes;
1192
- } : {
1193
- params: NonNullable<ExtractRouteParams<Endpoint>>;
1194
- };
1195
- /**
1196
- * If the request data is not filled it will throw an error
1197
- */
1198
- type FetchPayloadType<Payload, HasData extends true | false> = Payload extends NegativeTypes ? {
1199
- data?: NegativeTypes;
1200
- } : HasData extends true ? {
1201
- data?: NegativeTypes;
1202
- } : {
1203
- data: NonNullable<Payload>;
1204
- };
1205
- type RequestQueueOptions = {
1206
- dispatcherType?: "auto" | "fetch" | "submit";
1207
- };
1208
- type RequestSendOptionsType<Request extends RequestInstance> = FetchQueryParamsType<ExtractRequestQueryParamsType<Request>, ExtractHasQueryParamsType<Request>> & FetchParamsType<ExtractEndpointType<Request>, ExtractHasParamsType<Request>> & FetchPayloadType<ExtractPayloadType<Request>, ExtractHasDataType<Request>> & Omit<FetchOptionsType<ExtractAdapterType<Request>>, "params" | "data"> & FetchSendActionsType<Request> & RequestQueueOptions;
1209
- type FetchSendActionsType<Request extends RequestInstance> = {
1210
- onSettle?: (requestId: string, request: Request) => void;
1211
- onRequestStart?: (details: RequestEventType<Request>) => void;
1212
- onResponseStart?: (details: RequestEventType<Request>) => void;
1213
- onUploadProgress?: (values: ProgressType, details: RequestEventType<Request>) => void;
1214
- onDownloadProgress?: (values: ProgressType, details: RequestEventType<Request>) => void;
1215
- onResponse?: (response: ResponseReturnType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>>, details: ResponseDetailsType) => void;
1216
- onRemove?: (details: RequestEventType<Request>) => void;
1217
- };
1218
- type RequestSendType<Request extends RequestInstance> = RequestSendOptionsType<Request>["data"] extends NegativeTypes ? RequestSendOptionsType<Request>["params"] extends NegativeTypes ? (options?: RequestSendOptionsType<Request>) => Promise<ResponseReturnType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>>> : (options: RequestSendOptionsType<Request>) => Promise<ResponseReturnType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>>> : (options: RequestSendOptionsType<Request>) => Promise<ResponseReturnType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>>>;
1219
- type RequestInstance = Request<any, any, any, any, any, any, AdapterType<any, any, any, any, any>, any, any, any>;
1220
- type RequestMapper<Request extends RequestInstance, NewRequest extends RequestInstance> = (request: Request, requestId: string) => NewRequest | Promise<NewRequest>;
1221
- type ResponseMapper<Request extends RequestInstance, NewResponse, NewError> = (response: ResponseReturnType<ExtractResponseType<Request>, ExtractErrorType<Request>, ExtractAdapterType<Request>>) => ResponseReturnType<NewResponse, NewError, ExtractAdapterType<Request>> | Promise<ResponseReturnType<NewResponse, NewError, ExtractAdapterType<Request>>>;
1778
+ createRequest: <RequestProperties extends RequestGenericType<ExtractAdapterQueryParamsType<Adapter>> = {
1779
+ error?: Error;
1780
+ }>(_USE_DOUBLE_INITIALIZATION?: never) => <EndpointType extends ExtractAdapterEndpointType<Adapter>, AdapterOptions extends ExtractAdapterOptionsType<Adapter>, MethodType extends ExtractAdapterMethodType<Adapter>>(params: RequestOptionsType<EndpointType, AdapterOptions, MethodType>) => Request<TypeWithDefaults<RequestProperties, "response", undefined>, TypeWithDefaults<RequestProperties, "payload", undefined>, TypeWithDefaults<RequestProperties, "queryParams", ExtractAdapterDefaultQueryParamsType<Adapter>>, TypeWithDefaults<RequestProperties, "error", GlobalErrorType>, TypeWithDefaults<RequestProperties, "endpoint", EndpointType> extends string ? TypeWithDefaults<RequestProperties, "endpoint", EndpointType> : any, Client$1<GlobalErrorType, ExtractUnionAdapter<Adapter, {
1781
+ method: MethodType;
1782
+ options: AdapterOptions;
1783
+ queryParams: TypeWithDefaults<RequestProperties, "queryParams", ExtractAdapterDefaultQueryParamsType<Adapter>>;
1784
+ }> extends EmptyTypes ? Adapter : ExtractUnionAdapter<Adapter, {
1785
+ method: MethodType;
1786
+ options: AdapterOptions;
1787
+ queryParams: TypeWithDefaults<RequestProperties, "queryParams", ExtractAdapterDefaultQueryParamsType<Adapter>>;
1788
+ }>>, false, false, false>;
1789
+ }
1222
1790
 
1223
- declare const stringifyKey: (value: unknown) => string;
1224
- declare const getProgressValue: ({ loaded, total }: AdapterProgressEventType) => number;
1225
- declare const getRequestEta: (startDate: Date, progressDate: Date, { total, loaded }: AdapterProgressEventType) => {
1226
- sizeLeft: number;
1227
- timeLeft: number | null;
1791
+ type ClientErrorType = Record<string, any> | string;
1792
+ type ClientInstanceProperties = {
1793
+ error?: any;
1794
+ adapter?: AdapterInstance;
1228
1795
  };
1229
- declare const getProgressData: (requestStartTime: Date, progressDate: Date, progressEvent: AdapterProgressEventType) => ProgressType;
1230
- declare const getSimpleKey: (request: RequestInstance | RequestJSON<RequestInstance>) => string;
1231
- /**
1232
- * Cache instance for individual request that collects individual requests responses from
1233
- * the same endpoint (they may differ base on the custom key, endpoint params etc)
1234
- * @param request
1235
- * @param useInitialValues
1236
- * @returns
1237
- */
1238
- declare const getRequestKey: (request: RequestInstance | RequestJSON<RequestInstance>, useInitialValues?: boolean) => string;
1239
- declare const getRequestDispatcher: <Request_1 extends RequestInstance>(request: Request_1, dispatcherType?: "auto" | "fetch" | "submit") => [Dispatcher, boolean];
1240
- declare const sendRequest: <Request_1 extends RequestInstance>(request: Request_1, options?: RequestSendOptionsType<Request_1>) => Promise<ResponseReturnType<ExtractResponseType<Request_1>, ExtractErrorType<Request_1>, ExtractAdapterType<Request_1>>>;
1241
-
1242
- /**
1243
- * Base Adapter
1244
- */
1245
- type AdapterInstance = AdapterType<any, any, any, any, any, any>;
1246
- type AdapterType<AdapterOptions = AdapterOptionsType, MethodType = HttpMethodsType, StatusType = HttpStatusType, Extra extends Record<string, any> = AdapterExtraType, QueryParams = QueryParamsType | string, EndpointType = string> = (request: RequestInstance, requestId: string, DO_NOT_USE?: {
1247
- method?: MethodType;
1248
- options?: AdapterOptions;
1249
- status?: StatusType;
1250
- extra?: Extra;
1796
+ type ClientInstance<ClientProperties extends ClientInstanceProperties = {
1797
+ error?: any;
1798
+ adapter?: AdapterInstance;
1799
+ }> = Client$1<TypeWithDefaults<ClientProperties, "error", any>, TypeWithDefaults<ClientProperties, "adapter", AdapterInstance>>;
1800
+ type RequestGenericType<QueryParams> = {
1801
+ response?: any;
1802
+ payload?: any;
1803
+ error?: any;
1251
1804
  queryParams?: QueryParams;
1252
- endpointType?: EndpointType;
1253
- }) => Promise<ResponseReturnType<any, any, any>>;
1254
- /**
1255
- * Extractors
1256
- */
1257
- type ExtractAdapterOptionsType<T> = T extends AdapterType<infer O, any, any, any, any> ? O : never;
1258
- type ExtractAdapterMethodType<T> = T extends AdapterType<any, infer M, any, any, any> ? M : never;
1259
- type ExtractAdapterStatusType<T> = T extends AdapterType<any, any, infer S, any, any> ? S : never;
1260
- type ExtractAdapterExtraType<T> = T extends AdapterType<any, any, any, infer A, any> ? A : never;
1261
- type ExtractAdapterQueryParamsType<T> = T extends AdapterType<any, any, any, any, infer Q> ? Q : never;
1262
- type ExtractAdapterEndpointType<T> = T extends AdapterType<any, any, any, any, any, infer E> ? E : never;
1263
- type ExtractUnionAdapter<Adapter extends AdapterInstance, Values extends {
1264
- method?: any;
1265
- options?: any;
1266
- status?: any;
1267
- extra?: any;
1268
- queryParams?: any;
1269
- endpointType?: any;
1270
- }> = Extract<Adapter, AdapterType<Values["options"], Values["method"], Values["status"], Values["extra"], Values["queryParams"], Values["endpointType"]>> extends AdapterInstance ? Extract<Adapter, AdapterType<Values["options"], Values["method"], Values["status"], Values["extra"], Values["queryParams"], Values["endpointType"]>> : never;
1805
+ endpoint?: string;
1806
+ params?: Record<string, string | number>;
1807
+ };
1271
1808
  /**
1272
- * Options
1809
+ * Configuration setup for the client
1273
1810
  */
1274
- type AdapterOptionsType = Partial<XMLHttpRequest>;
1275
- type AdapterExtraType = {
1276
- headers: Record<string, string>;
1277
- };
1278
- type AdapterPayloadMappingType = (data: unknown) => string | FormData;
1279
- type ResponseReturnType<GenericDataType, GenericErrorType, Adapter extends AdapterInstance> = {
1280
- data: GenericDataType | null;
1281
- error: GenericErrorType | null;
1282
- status: ExtractAdapterStatusType<Adapter> | null;
1283
- success: boolean;
1284
- extra: ExtractAdapterExtraType<Adapter> | null;
1285
- };
1286
- type ResponseReturnSuccessType<GenericDataType, Adapter extends AdapterInstance> = {
1287
- data: GenericDataType;
1288
- error: null;
1289
- status: ExtractAdapterStatusType<Adapter> | null;
1290
- success: boolean;
1291
- extra: ExtractAdapterExtraType<Adapter> | null;
1292
- };
1293
- type ResponseReturnErrorType<GenericErrorType, Adapter extends AdapterInstance> = {
1294
- data: null;
1295
- error: GenericErrorType;
1296
- status: ExtractAdapterStatusType<Adapter> | null;
1297
- success: boolean;
1298
- extra: ExtractAdapterExtraType<Adapter> | null;
1299
- };
1300
- type QueryParamValuesType = number | string | boolean | null | undefined | Record<any, any>;
1301
- type QueryParamType = QueryParamValuesType | Array<QueryParamValuesType> | Record<string, QueryParamValuesType>;
1302
- type QueryParamsType = Record<string, QueryParamType>;
1303
- type HeaderMappingType = <T extends RequestInstance>(request: T) => HeadersInit;
1304
- type AdapterHeadersProps = {
1305
- isFormData: boolean;
1306
- headers: HeadersInit | undefined;
1307
- };
1308
- type QueryStringifyOptionsType = {
1309
- /**
1310
- * Strict URI encoding
1311
- */
1312
- strict?: boolean;
1313
- /**
1314
- * Encode keys and values
1315
- */
1316
- encode?: boolean;
1317
- /**
1318
- * Array encoding type
1319
- */
1320
- arrayFormat?: "bracket" | "index" | "comma" | "separator" | "bracket-separator" | "none";
1811
+ type ClientOptionsType<C extends ClientInstance> = {
1321
1812
  /**
1322
- * Array format separator
1813
+ * Url to your server
1323
1814
  */
1324
- arraySeparator?: string;
1815
+ url: string;
1325
1816
  /**
1326
- * Skip keys with null values
1817
+ * Custom cache initialization prop
1327
1818
  */
1328
- skipNull?: boolean;
1819
+ cache?: () => C["cache"];
1329
1820
  /**
1330
- * Skip keys with empty string
1821
+ * Custom app manager initialization prop
1331
1822
  */
1332
- skipEmptyString?: boolean;
1823
+ appManager?: () => C["appManager"];
1333
1824
  /**
1334
- * Parsing function for date type query param
1825
+ * Custom fetch dispatcher initialization prop
1335
1826
  */
1336
- dateParser?: (value: QueryParamType) => string;
1827
+ fetchDispatcher?: () => C["submitDispatcher"];
1337
1828
  /**
1338
- * Parsing function for object type query param
1829
+ * Custom submit dispatcher initialization prop
1339
1830
  */
1340
- objectParser?: (value: QueryParamType) => string;
1341
- };
1342
- type ProgressDataType = {
1343
- total?: number;
1344
- loaded?: number;
1345
- };
1346
- type ProgressType = {
1347
- progress: number;
1348
- timeLeft: number | null;
1349
- sizeLeft: number;
1350
- total: number;
1351
- loaded: number;
1352
- startTimestamp: number;
1831
+ submitDispatcher?: () => C["fetchDispatcher"];
1353
1832
  };
1354
- type AdapterBindingsReturnType = {
1355
- fullUrl: string;
1356
- config: any;
1357
- };
1358
-
1359
- declare const getErrorMessage: (errorCase?: "timeout" | "abort" | "deleted") => Error;
1360
- declare const getResponseHeaders: (headersString: string) => Record<string, string>;
1361
- declare const parseResponse: (response: string | unknown) => any;
1362
- declare const parseErrorResponse: <T extends RequestInstance>(response: unknown) => ExtractErrorType<T>;
1363
-
1364
- declare const getAdapterBindings: <T extends AdapterInstance = AdapterType<Partial<XMLHttpRequest>, HttpMethodsType, number, AdapterExtraType, string | QueryParamsType, string>>(req: RequestInstance, requestId: string, systemErrorStatus: ExtractAdapterStatusType<T>, systemErrorExtra: ExtractAdapterExtraType<T>) => Promise<{
1365
- fullUrl: string;
1366
- data: any;
1367
- headers: HeadersInit;
1368
- payload: any;
1369
- config: ExtractAdapterOptionsType<T>;
1370
- getAbortController: () => AbortController;
1371
- getRequestStartTimestamp: () => number;
1372
- getResponseStartTimestamp: () => number;
1373
- createAbortListener: (status: ExtractAdapterStatusType<T>, abortExtra: ExtractAdapterExtraType<T>, callback: () => void, resolve: (value: ResponseReturnErrorType<ExtractErrorType<T>, T>) => void) => () => void;
1374
- onBeforeRequest: () => void;
1375
- onRequestStart: (progress?: ProgressDataType) => number;
1376
- onRequestProgress: (progress: ProgressDataType) => number;
1377
- onRequestEnd: () => number;
1378
- onResponseStart: (progress?: ProgressDataType) => number;
1379
- onResponseProgress: (progress: ProgressDataType) => number;
1380
- onResponseEnd: () => number;
1381
- onSuccess: (responseData: any, status: ExtractAdapterStatusType<T>, extra: ExtractAdapterExtraType<T>, resolve: (value: ResponseReturnErrorType<any, T>) => void) => Promise<ResponseReturnSuccessType<ExtractResponseType<T>, T>>;
1382
- onAbortError: (status: ExtractAdapterStatusType<T>, extra: ExtractAdapterExtraType<T>, resolve: (value: ResponseReturnErrorType<ExtractErrorType<T>, T>) => void) => Promise<ResponseReturnErrorType<any, T>>;
1383
- onTimeoutError: (status: ExtractAdapterStatusType<T>, extra: ExtractAdapterExtraType<T>, resolve: (value: ResponseReturnErrorType<ExtractErrorType<T>, T>) => void) => Promise<ResponseReturnErrorType<any, T>>;
1384
- onUnexpectedError: (status: ExtractAdapterStatusType<T>, extra: ExtractAdapterExtraType<T>, resolve: (value: ResponseReturnErrorType<ExtractErrorType<T>, T>) => void) => Promise<ResponseReturnErrorType<any, T>>;
1385
- onError: (error: any, status: ExtractAdapterStatusType<T>, extra: ExtractAdapterExtraType<T>, resolve: (value: ResponseReturnErrorType<any, T>) => void) => Promise<ResponseReturnErrorType<any, T>>;
1386
- makeRequest: (apiCall: (resolve: (value: ResponseReturnType<any, any, T> | PromiseLike<ResponseReturnType<any, any, T>>) => void) => void) => Promise<ResponseReturnType<any, any, T>>;
1387
- }>;
1388
-
1389
- declare const defaultTimeout: number;
1390
- declare const xhrExtra: AdapterExtraType;
1833
+ type RequestInterceptorType = (request: RequestInstance) => Promise<RequestInstance> | RequestInstance;
1834
+ type ResponseInterceptorType<Client extends ClientInstance, Response = any, Error = any> = (response: ResponseType<Response, Error, ExtractClientAdapterType<Client>>, request: ExtendRequest<RequestInstance, {
1835
+ client: Client;
1836
+ }>) => Promise<ResponseType<any, any, ExtractClientAdapterType<Client>>> | ResponseType<any, any, ExtractClientAdapterType<Client>>;
1837
+ type ModifyQueryParamsCallbackType<QueryParams, ModifiedQueryParams> = (queryParams: QueryParams) => ModifiedQueryParams;
1391
1838
 
1392
- type ExtractAdapterReturnType<T extends RequestInstance> = ResponseReturnType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>;
1393
- type ExtractResponseType<T> = T extends Request<infer D, any, any, any, any, any, any, any, any, any> ? D : never;
1394
- type ExtractPayloadType<T> = T extends Request<any, infer D, any, any, any, any, any, any, any, any> ? D : never;
1395
- type ExtractRequestQueryParamsType<T> = T extends Request<any, any, infer Q, any, any, any, any, any, any, any> ? Q : never;
1396
- type ExtractErrorType<T> = T extends Request<any, any, any, infer G, infer L, any, any, any, any, any> ? G | L : never;
1397
- type ExtractGlobalErrorType<T> = T extends Request<any, any, any, infer E, any, any, any, any, any, any> ? E : never;
1398
- type ExtractLocalErrorType<T> = T extends Request<any, any, any, any, infer E, any, any, any, any, any> ? E : never;
1399
- type ExtractParamsType<T> = T extends Request<any, any, any, any, any, infer P, any, any, any, any> ? ExtractRouteParams<P> : never;
1400
- type ExtractEndpointType<T> = T extends Request<any, any, any, any, any, infer E, any, any, any, any> ? E : never;
1401
- type ExtractAdapterType<T> = T extends Request<any, any, any, any, any, any, infer A, any, any, any> ? A : never;
1402
- type ExtractHasDataType<T> = T extends Request<any, any, any, any, any, any, any, infer D, any, any> ? D : never;
1403
- type ExtractHasParamsType<T> = T extends Request<any, any, any, any, any, any, any, any, infer P, any> ? P : never;
1404
- type ExtractHasQueryParamsType<T> = T extends Request<any, any, any, any, any, any, any, any, any, infer Q> ? Q : never;
1839
+ declare const interceptRequest: (interceptors: RequestInterceptorType[], request: RequestInstance) => Promise<RequestInstance>;
1840
+ declare const interceptResponse: <GlobalErrorType, Client extends ClientInstance>(interceptors: ResponseInterceptorType<Client>[], response: ResponseType<any, GlobalErrorType, ExtractClientAdapterType<Client>>, request: ExtendRequest<RequestInstance, {
1841
+ client: Client;
1842
+ }>) => Promise<ResponseType<any, GlobalErrorType, ExtractClientAdapterType<Client>>>;
1405
1843
 
1406
- type ExtractClientGlobalError<T> = T extends Client<infer G, any> ? G : never;
1407
- type ExtractClientAdapterType<T> = T extends Client<any, infer A> ? A : never;
1844
+ declare const stringifyDefaultOptions: {
1845
+ readonly strict: true;
1846
+ readonly encode: true;
1847
+ readonly arrayFormat: "bracket";
1848
+ readonly arraySeparator: "bracket";
1849
+ readonly sort: false;
1850
+ readonly skipNull: true;
1851
+ readonly skipEmptyString: true;
1852
+ };
1408
1853
 
1409
- declare class RequestEffect<T extends RequestInstance> {
1410
- config: RequestEffectOptionsType<T>;
1411
- constructor(config: RequestEffectOptionsType<T>);
1412
- getEffectKey: () => string;
1413
- onTrigger: (request: T) => void;
1414
- onStart: (request: T) => void;
1415
- onSuccess: (response: ResponseReturnSuccessType<ExtractResponseType<T>, ExtractAdapterType<T>>, request: T) => void;
1416
- onError: (response: ResponseReturnErrorType<ExtractErrorType<T>, ExtractAdapterType<T>>, request: T) => void;
1417
- onFinished: (response: ResponseReturnType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>, request: T) => void;
1418
- }
1854
+ type ClientGenericType = {
1855
+ error?: ClientErrorType;
1856
+ };
1857
+ declare function createClient<ClientProperties extends ClientGenericType = {
1858
+ error?: ClientErrorType;
1859
+ }>(options: ClientOptionsType<Client$1<NonNullable<TypeWithDefaults<ClientProperties, "error", ClientErrorType>>>>): Client$1<NonNullable<TypeWithDefaults<ClientProperties, "error", ClientErrorType>>, HttpAdapterType>;
1419
1860
 
1420
- type RequestEffectLifecycle = "trigger" | "start" | "success" | "error" | "finished";
1421
- type RequestEffectInstance = RequestEffect<RequestInstance>;
1422
- type RequestEffectOptionsType<T extends RequestInstance> = {
1861
+ declare class Plugin<Client extends ClientInstance = ClientInstance, PluginData = void> {
1862
+ config: PluginOptionsType<PluginData>;
1863
+ name: string;
1864
+ data: PluginData;
1865
+ client: Client | undefined;
1866
+ private pluginMethods;
1867
+ constructor(config: PluginOptionsType<PluginData>);
1868
+ initialize: (client: Client) => this;
1869
+ trigger: <Key extends keyof PluginMethods<Client>>(method: Key, data: PluginMethodParameters<Key, Client>) => void;
1870
+ /**
1871
+ * Callback that will be executed when plugin is mounted
1872
+ */
1873
+ onMount: (callback: PluginMethods<Client>["onMount"]) => this;
1423
1874
  /**
1424
- * It should match effectKey on the request for which given effect should be triggered.
1875
+ * Callback that will be executed when plugin is unmounted
1425
1876
  */
1426
- effectKey: string;
1877
+ onUnmount: (callback: PluginMethods<Client>["onUnmount"]) => this;
1878
+ /**
1879
+ * Callback that will be executed when request is created
1880
+ */
1881
+ onRequestCreate: (callback: PluginMethods<Client>["onRequestCreate"]) => this;
1427
1882
  /**
1428
1883
  * Callback that will be executed when request gets triggered
1429
1884
  */
1430
- onTrigger?: (request: RequestInstance) => void;
1885
+ onRequestTrigger: (callback: PluginMethods<Client>["onRequestTrigger"]) => this;
1431
1886
  /**
1432
1887
  * Callback that will be executed when request starts
1433
1888
  */
1434
- onStart?: (request: RequestInstance) => void;
1889
+ onRequestStart: (callback: PluginMethods<Client>["onRequestStart"]) => this;
1435
1890
  /**
1436
1891
  * Callback that will be executed when response is successful
1437
1892
  */
1438
- onSuccess?: (response: ResponseReturnSuccessType<ExtractResponseType<T>, ExtractAdapterType<T>>, request: RequestInstance) => void;
1893
+ onRequestSuccess: (callback: PluginMethods<Client>["onRequestSuccess"]) => this;
1439
1894
  /**
1440
1895
  * Callback that will be executed when response is failed
1441
1896
  */
1442
- onError?: (response: ResponseReturnErrorType<ExtractErrorType<T>, ExtractAdapterType<T>>, request: RequestInstance) => void;
1897
+ onRequestError: (callback: PluginMethods<Client>["onRequestError"]) => this;
1443
1898
  /**
1444
1899
  * Callback that will be executed when response is finished
1445
1900
  */
1446
- onFinished?: (response: ResponseReturnType<ExtractResponseType<T>, ExtractErrorType<T>, ExtractAdapterType<T>>, request: RequestInstance) => void;
1901
+ onRequestFinished: (callback: PluginMethods<Client>["onRequestFinished"]) => this;
1902
+ onDispatcherCleared: (callback: PluginMethods<Client>["onDispatcherCleared"]) => this;
1903
+ onDispatcherQueueDrained: (callback: PluginMethods<Client>["onDispatcherQueueDrained"]) => this;
1904
+ onDispatcherQueueRunning: (callback: PluginMethods<Client>["onDispatcherQueueRunning"]) => this;
1905
+ onDispatcherItemAdded: (callback: PluginMethods<Client>["onDispatcherItemAdded"]) => this;
1906
+ onDispatcherItemDeleted: (callback: PluginMethods<Client>["onDispatcherItemDeleted"]) => this;
1907
+ onDispatcherQueueCreated: (callback: PluginMethods<Client>["onDispatcherQueueCreated"]) => this;
1908
+ onDispatcherQueueCleared: (callback: PluginMethods<Client>["onDispatcherQueueCleared"]) => this;
1909
+ onCacheItemChange: (callback: PluginMethods<Client>["onCacheItemChange"]) => this;
1910
+ onCacheItemDelete: (callback: PluginMethods<Client>["onCacheItemDelete"]) => this;
1911
+ onAdapterFetch: (callback: PluginMethods<Client>["onAdapterFetch"]) => this;
1912
+ }
1913
+
1914
+ type PluginLifecycle = "trigger" | "start" | "success" | "error" | "finished";
1915
+ type PluginInstance = Plugin<any, any>;
1916
+ type PluginRequest<C extends ClientInstance> = ExtendRequest<RequestInstance, {
1917
+ client: C;
1918
+ }>;
1919
+ type PluginOptionsType<PluginData> = {
1920
+ /**
1921
+ * Name of the plugin
1922
+ */
1923
+ name: string;
1924
+ /**
1925
+ * Data stored in a plugin
1926
+ */
1927
+ data?: PluginData;
1447
1928
  };
1929
+ type PluginMethods<Client extends ClientInstance> = {
1930
+ onMount?: (data: {
1931
+ client: Client;
1932
+ }) => void;
1933
+ onUnmount?: (data: {
1934
+ client: Client;
1935
+ }) => void;
1936
+ onRequestCreate?: (data: {
1937
+ request: PluginRequest<Client>;
1938
+ }) => void;
1939
+ onRequestTrigger?: (data: {
1940
+ request: PluginRequest<Client>;
1941
+ }) => void;
1942
+ onRequestStart?: (data: {
1943
+ request: PluginRequest<Client>;
1944
+ }) => void;
1945
+ onRequestSuccess?: (data: {
1946
+ response: ResponseSuccessType<ExtractResponseType<PluginRequest<Client>>, ExtractAdapterType<PluginRequest<Client>>>;
1947
+ request: PluginRequest<Client>;
1948
+ }) => void;
1949
+ onRequestError?: (data: {
1950
+ response: ResponseErrorType<ExtractErrorType<PluginRequest<Client>>, ExtractAdapterType<PluginRequest<Client>>>;
1951
+ request: PluginRequest<Client>;
1952
+ }) => void;
1953
+ onRequestFinished?: (data: {
1954
+ response: ResponseType<ExtractResponseType<PluginRequest<Client>>, ExtractErrorType<PluginRequest<Client>>, ExtractAdapterType<PluginRequest<Client>>>;
1955
+ request: PluginRequest<Client>;
1956
+ }) => void;
1957
+ onCacheItemChange?: <Requests extends {
1958
+ cacheKey: string;
1959
+ response: any;
1960
+ error: any;
1961
+ }>(data: {
1962
+ cache: Cache<ExtractClientAdapterType<Client>>;
1963
+ cacheKey: Requests["cacheKey"];
1964
+ prevData: CacheValueType<Requests["response"], Requests["error"], ExtractClientAdapterType<Client>> | null;
1965
+ newData: CacheValueType<Requests["response"], Requests["error"], ExtractClientAdapterType<Client>>;
1966
+ }) => void;
1967
+ onCacheItemDelete?: (data: {
1968
+ cacheKey: string;
1969
+ cache: Cache<ExtractClientAdapterType<Client>>;
1970
+ }) => void;
1971
+ onCacheItemInvalidate?: (data: {
1972
+ cacheKey: string;
1973
+ cache: Cache<ExtractClientAdapterType<Client>>;
1974
+ }) => void;
1975
+ onDispatcherCleared?: (data: {
1976
+ dispatcher: Dispatcher<ExtractClientAdapterType<Client>>;
1977
+ }) => void;
1978
+ onDispatcherQueueDrained?: (data: {
1979
+ dispatcher: Dispatcher<ExtractClientAdapterType<Client>>;
1980
+ queue: QueueDataType<ExtendRequest<RequestInstance, {
1981
+ client: Client;
1982
+ }>>;
1983
+ }) => void;
1984
+ onDispatcherItemAdded?: (data: {
1985
+ dispatcher: Dispatcher<ExtractClientAdapterType<Client>>;
1986
+ queue: QueueDataType<ExtendRequest<RequestInstance, {
1987
+ client: Client;
1988
+ }>>;
1989
+ queueItem: QueueItemType<ExtendRequest<RequestInstance, {
1990
+ client: Client;
1991
+ }>>;
1992
+ }) => void;
1993
+ onDispatcherItemDeleted?: (data: {
1994
+ dispatcher: Dispatcher<ExtractClientAdapterType<Client>>;
1995
+ queue: QueueDataType<ExtendRequest<RequestInstance, {
1996
+ client: Client;
1997
+ }>>;
1998
+ queueItem: QueueItemType<ExtendRequest<RequestInstance, {
1999
+ client: Client;
2000
+ }>>;
2001
+ }) => void;
2002
+ onDispatcherQueueRunning?: (data: {
2003
+ dispatcher: Dispatcher<ExtractClientAdapterType<Client>>;
2004
+ queue: QueueDataType<ExtendRequest<RequestInstance, {
2005
+ client: Client;
2006
+ }>>;
2007
+ status: "paused" | "stopped" | "running";
2008
+ }) => void;
2009
+ onDispatcherQueueCreated?: (data: {
2010
+ dispatcher: Dispatcher<ExtractClientAdapterType<Client>>;
2011
+ queue: QueueDataType<ExtendRequest<RequestInstance, {
2012
+ client: Client;
2013
+ }>>;
2014
+ }) => void;
2015
+ onDispatcherQueueCleared?: (data: {
2016
+ dispatcher: Dispatcher<ExtractClientAdapterType<Client>>;
2017
+ queue: QueueDataType<ExtendRequest<RequestInstance, {
2018
+ client: Client;
2019
+ }>>;
2020
+ }) => void;
2021
+ onAdapterFetch?: (data: {
2022
+ request: RequestInstance;
2023
+ requestId: string;
2024
+ adapter: AdapterInstance;
2025
+ }) => void;
2026
+ };
2027
+ type PluginMethodParameters<Key extends keyof PluginMethods<Client>, Client extends ClientInstance> = Parameters<NonNullable<PluginMethods<Client>[Key]>>[0];
1448
2028
 
1449
- declare enum DateInterval {
1450
- second = 1000,
1451
- minute = 60000,
1452
- hour = 3600000,
1453
- day = 86400000,
1454
- week = 604800000,
1455
- month30 = 2592000000,
1456
- month31 = 2678400000,
1457
- year = 31536000000,
1458
- yearLeap = 31622400000
2029
+ declare enum Time {
2030
+ SEC = 1000,
2031
+ MIN = 60000,
2032
+ HOUR = 3600000,
2033
+ DAY = 86400000,
2034
+ WEEK = 604800000,
2035
+ MONTH_30 = 2592000000,
2036
+ MONTH_31 = 2678400000,
2037
+ YEAR = 31536000000,
2038
+ YEAR_LEAP = 31622400000
1459
2039
  }
1460
2040
 
1461
- declare enum HttpMethodsEnum {
1462
- get = "GET",
1463
- post = "POST",
1464
- put = "PUT",
1465
- patch = "PATCH",
1466
- delete = "DELETE"
2041
+ declare enum HttpMethods {
2042
+ GET = "GET",
2043
+ POST = "POST",
2044
+ PUT = "PUT",
2045
+ PATCH = "PATCH",
2046
+ DELETE = "DELETE"
1467
2047
  }
1468
2048
 
1469
- declare const getUniqueRequestId: (key: string) => string;
1470
-
1471
- export { AdapterBindingsReturnType, AdapterExtraType, AdapterHeadersProps, AdapterInstance, AdapterOptionsType, AdapterPayloadMappingType, AdapterProgressEventType, AdapterProgressType, AdapterType, AppEvents, AppManager, AppManagerOptionsType, Cache, CacheAsyncStorageType, CacheInitialData, CacheMethodType, CacheOptionsType, CacheStorageType, CacheValueType, Client, ClientErrorType, ClientInstance, ClientOptionsType, DateInterval, DefaultEndpointMapper, Dispatcher, DispatcherOptionsType, DispatcherRequestType, DispatcherStorageType, ExtractAdapterEndpointType, ExtractAdapterExtraType, ExtractAdapterMethodType, ExtractAdapterOptionsType, ExtractAdapterQueryParamsType, ExtractAdapterReturnType, ExtractAdapterStatusType, ExtractAdapterType, ExtractAdapterTypeFromClient, ExtractClientAdapterType, ExtractClientGlobalError, ExtractEndpointType, ExtractErrorType, ExtractGlobalErrorType, ExtractHasDataType, ExtractHasParamsType, ExtractHasQueryParamsType, ExtractLocalErrorType, ExtractParamsType, ExtractPayloadType, ExtractRequestQueryParamsType, ExtractResponseType, ExtractRouteParams, ExtractUnionAdapter, FetchOptionsType, FetchParamsType, FetchPayloadType, FetchQueryParamsType, FetchSendActionsType, GeneratorReturnMockTypes, HeaderMappingType, HttpMethodsEnum, HttpMethodsType, HttpStatusType, LogType, LoggerFunctionType, LoggerLevelType, LoggerManager, LoggerMessageType, LoggerOptionsType, LoggerRequestEventData, LoggerResponseEventData, LoggerType, NegativeTypes, NonNullableKeys, NullableKeys, NullableType, ParamType, ParamsType, PayloadMapperType, PayloadType, ProgressDataType, ProgressType, QueryParamType, QueryParamValuesType, QueryParamsType, QueryStringifyOptionsType, QueueDataType, QueueElementType, Request, RequestCurrentType, RequestDataMockTypes, RequestEffect, RequestEffectInstance, RequestEffectLifecycle, RequestEffectOptionsType, RequestEventType, RequestInstance, RequestInterceptorType, RequestJSON, RequestLoadingEventType, RequestManager, RequestMapper, RequestMockType, RequestOptionsType, RequestQueueOptions, RequestRemoveDataType, RequestSendOptionsType, RequestSendType, RequiredKeys, ResponseDetailsType, ResponseInterceptorType, ResponseMapper, ResponseReturnErrorType, ResponseReturnSuccessType, ResponseReturnType, RunningRequestValueType, SeverityType, StringifyCallbackType, adapter, appManagerInitialOptions, canRetryRequest, defaultTimeout, getAbortByIdEventKey, getAbortEventKey, getAdapterBindings, getAdapterHeaders, getAdapterPayload, getAppManagerEvents, getCacheData, getCacheEvents, getCacheIdKey, getCacheKey, getDispatcherChangeEventKey, getDispatcherDrainedEventKey, getDispatcherEvents, getDispatcherStatusEventKey, getDownloadProgressEventKey, getDownloadProgressIdEventKey, getErrorMessage, getInvalidateEventKey, getIsEqualTimestamp, getLoadingEventKey, getLoadingIdEventKey, getProgressData, getProgressValue, getRemoveEventKey, getRemoveIdEventKey, getRequestDispatcher, getRequestEta, getRequestKey, getRequestManagerEvents, getRequestStartEventKey, getRequestStartIdEventKey, getRequestType, getResponseEventKey, getResponseHeaders, getResponseIdEventKey, getResponseStartEventKey, getResponseStartIdEventKey, getSimpleKey, getTime, getUniqueRequestId, getUploadProgressEventKey, getUploadProgressIdEventKey, hasDocument, hasWindow, interceptRequest, interceptResponse, logger, loggerIconLevels, loggerStyles, mocker, onDocumentEvent, onWindowEvent, parseErrorResponse, parseResponse, sendRequest, severity, stringifyDefaultOptions, stringifyKey, stringifyQueryParams, stringifyValue, xhrExtra };
2049
+ export { AbortError, Adapter, type AdapterFetcherType, type AdapterGenericType, type AdapterInstance, type AdapterPayloadMappingType, AppEvents, AppManager, type AppManagerOptionsType, type BufferEncoding, Cache, type CacheAsyncStorageType, type CacheInitialData, type CacheOptionsType, type CacheSetState, type CacheStorageType, type CacheValueType, Client$1 as Client, type ClientErrorType, type ClientGenericType, type ClientInstance, type ClientInstanceProperties, type ClientOptionsType, type DeclareAdapterType, type DefaultEndpointMapper, type DefaultHeaderMapper, type DefaultMapperType, type DefaultPayloadMapper, type DefaultQueryParamsMapper, DeletedError, Dispatcher, DispatcherMode, type DispatcherOptionsType, type DispatcherStorageType, type EmptyTypes, type EndpointMapper, EventEmitter, type ExtendRequest, type ExtractAdapterDefaultQueryParamsType, type ExtractAdapterEndpointMapperType, type ExtractAdapterEndpointType, type ExtractAdapterExtraType, type ExtractAdapterHeaderMapperType, type ExtractAdapterMethodType, type ExtractAdapterOptionsType, type ExtractAdapterPayloadMapperType, type ExtractAdapterQueryParamsMapperType, type ExtractAdapterQueryParamsType, type ExtractAdapterResolvedType, type ExtractAdapterStatusType, type ExtractAdapterType, type ExtractClientAdapterType, type ExtractClientGlobalError, type ExtractClientType, type ExtractEndpointType, type ExtractErrorType, type ExtractGlobalErrorType, type ExtractHasParamsType, type ExtractHasPayloadType, type ExtractHasQueryParamsType, type ExtractLocalErrorType, type ExtractParamsType, type ExtractPayloadType, type ExtractQueryParamsType, type ExtractResponseType, type ExtractRouteParams, type ExtractUnionAdapter, type FetchParamsType, type FetchPayloadType, type FetchQueryParamsType, type HeaderMappingType, HttpAdapter, type HttpAdapterExtraType, type HttpAdapterHeadersProps, type HttpAdapterOptionsType, type HttpAdapterRequest, type HttpAdapterType, HttpMethods, type HttpMethodsType, type HttpStatusType, type HydrateDataType, type HydrationOptions, type LogData, type LogDataTypes, type LogLevel, type LogRequestEventType, type LogResponseEventType, type LogSystemEventType, type LoggerArgs, LoggerManager, type LoggerMethods, type LoggerOptionsType, type LoggerType, type MockResponseType, type MockerConfigType, type ModifyQueryParamsCallbackType, type NonNullableKeys, type NullableKeys, type NullableType, type ParamType, type ParamsType, type PayloadMapperType, type PayloadType, Plugin, type PluginInstance, type PluginLifecycle, type PluginMethodParameters, type PluginMethods, type PluginOptionsType, type PluginRequest, type Prettify, type ProgressDataType, type ProgressEventType, type ProgressType, type QueryParamType, type QueryParamValuesType, type QueryParamsMapper, type QueryParamsType, type QueryStringifyOptionsType, type QueueDataType, type QueueItemType, Request, type RequestCacheType, type RequestConfigurationType, type RequestDeduplicatedEventType, type RequestDynamicSendOptionsType, type RequestEventType, type RequestGenericType, type RequestInstance, type RequestInstanceProperties, type RequestInterceptorType, type RequestJSON, type RequestLoadingEventType, RequestManager, type RequestMapper, type RequestOptionsType, RequestProcessingError, type RequestProgressEventType, type RequestRemovedEventType, type RequestResponseEventType, type RequestResponseType, type RequestSendActionsType, type RequestSendOptionsType, type RequestSendType, type RequiredKeys, type ResponseDetailsType, type ResponseErrorType, type ResponseInterceptorType, type ResponseMapper, type ResponseSuccessType, type ResponseType, type RunningRequestValueType, type SyncOrAsync, Time, TimeoutError, type TypeWithDefaults, UnexpectedError, appManagerInitialOptions, canRetryRequest, createClient, defaultMapper, defaultTimeout, getAbortByAbortKey, getAbortByIdKey, getAbortKey, getAdapterBindings, getAdapterHeaders, getAdapterOnError, getAdapterPayload, getAppManagerEvents, getCacheByKey, getCacheData, getCacheEvents, getCacheKey, getDeleteByKey, getDeleteKey, getDispatcherChangeByKey, getDispatcherChangeKey, getDispatcherDrainedByKey, getDispatcherDrainedKey, getDispatcherEvents, getDispatcherStatusByKey, getDispatcherStatusKey, getDownloadProgressByIdKey, getDownloadProgressByQueryKey, getDownloadProgressKey, getErrorMessage, getInvalidateByKey, getInvalidateKey, getIsEqualTimestamp, getLoadingByCacheKey, getLoadingByIdKey, getLoadingByQueryKey, getLoadingKey, getProgressData, getProgressValue, getRemoveByIdKey, getRemoveByQueryKey, getRemoveKey, getRequestDeduplicatedByCacheKey, getRequestDeduplicatedByIdKey, getRequestDeduplicatedByQueryKey, getRequestDeduplicatedKey, getRequestDispatcher, getRequestEta, getRequestKey, getRequestManagerEvents, getRequestStarByQueryKey, getRequestStartByIdKey, getRequestStartKey, getRequestType, getResponseByCacheKey, getResponseByIdKey, getResponseHeaders, getResponseKey, getResponseStartByIdKey, getResponseStartByQueryKey, getResponseStartKey, getSimpleKey, getTime, getUniqueRequestId, getUploadProgressByIdKey, getUploadProgressByQueryKey, getUploadProgressKey, handleResponse, hasDocument, hasWindow, interceptRequest, interceptResponse, logLevelOrder, logger, loggerColors, loggerStyles, mocker, onDocumentEvent, onWindowEvent, parseErrorResponse, parseResponse, sendRequest, stringifyDefaultOptions, stringifyKey, stringifyQueryParams, stringifyValue, xhrExtra };