@zayne-labs/callapi 0.5.4 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,19 +1,16 @@
1
- import { R as ResultModeUnion, B as BaseConfig, F as FetchConfig, G as GetCallApiResult } from './types-DIDORyP8.js';
2
- import './type-helpers-Dibitydy.js';
1
+ import { R as ResultModeUnion, B as BaseConfig, F as FetchConfig, G as GetCallApiResult } from './types-CfjkQnRk.js';
2
+ import './type-helpers-DpDJiTqb.js';
3
3
 
4
4
  declare const createFetchClient: <TBaseData, TBaseErrorData = unknown, TBaseResultMode extends ResultModeUnion = undefined>(baseConfig?: BaseConfig<TBaseData, TBaseErrorData, TBaseResultMode>) => {
5
5
  <TData = TBaseData, TErrorData = TBaseErrorData, TResultMode extends ResultModeUnion = TBaseResultMode>(url: string, config?: FetchConfig<TData, TErrorData, TResultMode>): Promise<GetCallApiResult<TData, TErrorData, TResultMode>>;
6
6
  create: any;
7
- cancel(url: string, reason?: unknown): void;
8
7
  };
9
8
  declare const callApi: {
10
9
  <TData = unknown, TErrorData = unknown, TResultMode extends ResultModeUnion = undefined>(url: string, config?: FetchConfig<TData, TErrorData, TResultMode> | undefined): Promise<GetCallApiResult<TData, TErrorData, TResultMode>>;
11
10
  create: <TBaseData, TBaseErrorData = unknown, TBaseResultMode extends ResultModeUnion = undefined>(baseConfig?: BaseConfig<TBaseData, TBaseErrorData, TBaseResultMode>) => {
12
11
  <TData = TBaseData, TErrorData = TBaseErrorData, TResultMode extends ResultModeUnion = TBaseResultMode>(url: string, config?: FetchConfig<TData, TErrorData, TResultMode>): Promise<GetCallApiResult<TData, TErrorData, TResultMode>>;
13
12
  create: any;
14
- cancel(url: string, reason?: unknown): void;
15
13
  };
16
- cancel(url: string, reason?: unknown): void;
17
14
  };
18
15
 
19
16
  export { callApi, createFetchClient };
@@ -1,5 +1 @@
1
- export { b as callApi, a as createFetchClient } from './chunk-RRO7PFYR.js';
2
- import './chunk-XE3JEDG3.js';
3
- import './chunk-ZYWIPUWT.js';
4
- //# sourceMappingURL=out.js.map
5
- //# sourceMappingURL=createFetchClient.js.map
1
+ export{callApi,createFetchClient}from"./chunk-KQNDKJNJ.js";import"./chunk-F6RUPSGH.js";import"./chunk-AKFUJ4JG.js";//# sourceMappingURL=createFetchClient.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":""}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"createFetchClient.js"}
@@ -1,3 +1,3 @@
1
1
  export { callApi, createFetchClient } from './createFetchClient.js';
2
- export { $ as $RequestOptions, E as ExtraOptions, F as FetchConfig, H as HTTPError, a as ResponseContext, b as ResponseErrorContext, i as isHTTPError, c as isHTTPErrorInstance, t as toQueryString } from './types-DIDORyP8.js';
3
- import './type-helpers-Dibitydy.js';
2
+ export { $ as $RequestOptions, c as ErrorContext, E as ExtraOptions, F as FetchConfig, a as ResponseContext, b as ResponseErrorContext } from './types-CfjkQnRk.js';
3
+ import './type-helpers-DpDJiTqb.js';
package/dist/esm/index.js CHANGED
@@ -1,5 +1 @@
1
- export { b as callApi, a as createFetchClient } from './chunk-RRO7PFYR.js';
2
- export { m as HTTPError, l as isHTTPError, n as isHTTPErrorInstance, a as toQueryString } from './chunk-XE3JEDG3.js';
3
- import './chunk-ZYWIPUWT.js';
4
- //# sourceMappingURL=out.js.map
5
- //# sourceMappingURL=index.js.map
1
+ export{callApi,createFetchClient}from"./chunk-KQNDKJNJ.js";import"./chunk-F6RUPSGH.js";import"./chunk-AKFUJ4JG.js";//# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":""}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
@@ -0,0 +1,12 @@
1
+ type AnyString = string & {
2
+ placeholder?: never;
3
+ };
4
+ type AnyNumber = number & {
5
+ placeholder?: never;
6
+ };
7
+ type AnyFunction = (...args: any[]) => any;
8
+ type Prettify<TObject> = {
9
+ [Key in keyof TObject]: TObject[Key];
10
+ } & NonNullable<unknown>;
11
+
12
+ export type { AnyFunction as A, Prettify as P, AnyString as a, AnyNumber as b };
@@ -1,4 +1,4 @@
1
- import { A as AnyFunction } from './type-helpers-Dibitydy.js';
1
+ import { A as AnyFunction } from './type-helpers-DpDJiTqb.js';
2
2
 
3
3
  declare const isArray: <TArray>(value: unknown) => value is TArray[];
4
4
  declare const isObject: <TObject extends Record<string, unknown>>(value: unknown) => value is TObject;
@@ -1,3 +1 @@
1
- export { a as isArray, c as isFunction, b as isObject, e as isQueryString, d as isString } from './chunk-ZYWIPUWT.js';
2
- //# sourceMappingURL=out.js.map
3
- //# sourceMappingURL=typeof.js.map
1
+ export{isArray,isFunction,isObject,isQueryString,isString}from"./chunk-AKFUJ4JG.js";//# sourceMappingURL=typeof.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":""}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"typeof.js"}
@@ -1,7 +1,8 @@
1
- import { a as AnyString, b as AnyNumber } from './type-helpers-Dibitydy.js';
1
+ import { a as AnyString, b as AnyNumber, P as Prettify } from './type-helpers-DpDJiTqb.js';
2
2
 
3
+ declare const getRequestKey: <TConfig extends Record<string, unknown>>(url: string, config?: TConfig) => string;
3
4
  type ToQueryStringFn = {
4
- (params: ExtraOptions["query"]): string | null;
5
+ (params: ExtraOptions["query"]): null | string;
5
6
  (params: Required<ExtraOptions>["query"]): string;
6
7
  };
7
8
  declare const toQueryString: ToQueryStringFn;
@@ -10,47 +11,48 @@ declare const objectifyHeaders: (headers: RequestInit["headers"]) => Record<stri
10
11
  declare const defaultRetryCodes: Required<BaseConfig>["retryCodes"];
11
12
  declare const defaultRetryMethods: Required<BaseConfig>["retryMethods"];
12
13
  declare const fetchSpecificKeys: ("body" | "method" | "headers" | "cache" | "credentials" | "integrity" | "keepalive" | "mode" | "priority" | "redirect" | "referrer" | "referrerPolicy" | "signal" | "window")[];
14
+ declare const omitKeys: <TObject extends Record<string, unknown>, const TOmitArray extends Array<keyof TObject>>(initialObject: TObject, keysToOmit: TOmitArray) => Omit<TObject, keyof TOmitArray>;
13
15
  declare const splitConfig: <TObject extends object>(config: TObject) => ["body" extends keyof TObject ? $RequestOptions : $BaseRequestOptions, ExtraOptions];
14
16
  declare const handleResponseType: <TResponse>(response: Response, parser?: Required<ExtraOptions>["responseParser"]) => {
15
- json: () => Promise<Record<string, unknown> | TResponse>;
16
17
  arrayBuffer: () => Promise<TResponse>;
17
18
  blob: () => Promise<TResponse>;
18
19
  formData: () => Promise<TResponse>;
20
+ json: () => Promise<Record<string, unknown> | TResponse>;
19
21
  text: () => Promise<TResponse>;
20
22
  };
21
23
  declare const getResponseData: <TResponse>(response: Response, responseType: keyof ReturnType<typeof handleResponseType>, parser: ExtraOptions["responseParser"]) => Promise<Record<string, unknown> | TResponse>;
22
24
  type data = {
23
- successData: unknown;
24
25
  options: ExtraOptions;
25
26
  response: Response;
27
+ successData: unknown;
26
28
  };
27
29
  declare const resolveSuccessResult: <CallApiResult>(info: data) => CallApiResult;
28
- declare const $resolveErrorResult: <CallApiResult>($info: {
30
+ declare const getResolveErrorResultFn: <CallApiResult>($info: {
29
31
  error?: unknown;
30
32
  options: ExtraOptions;
31
33
  }) => (info?: {
32
- response?: Response;
33
34
  errorData?: unknown;
34
35
  message?: string;
36
+ response?: Response;
35
37
  }) => CallApiResult;
36
38
  declare const isHTTPError: <TErrorData>(error: ApiErrorVariant<TErrorData>["error"] | null) => error is {
37
- name: "HTTPError";
38
39
  errorData: TErrorData;
39
40
  message: string;
41
+ name: "HTTPError";
40
42
  };
41
43
  type ErrorDetails<TErrorResponse> = {
44
+ defaultErrorMessage: string;
42
45
  errorData: TErrorResponse;
43
46
  response: Response;
44
- defaultErrorMessage: string;
45
47
  };
46
48
  type ErrorOptions = {
47
49
  cause?: unknown;
48
50
  };
49
51
  declare class HTTPError<TErrorResponse = Record<string, unknown>> extends Error {
50
- response: ErrorDetails<TErrorResponse>["response"];
51
52
  errorData: ErrorDetails<TErrorResponse>["errorData"];
52
- name: "HTTPError";
53
53
  isHTTPError: boolean;
54
+ name: "HTTPError";
55
+ response: ErrorDetails<TErrorResponse>["response"];
54
56
  constructor(errorDetails: ErrorDetails<TErrorResponse>, errorOptions?: ErrorOptions);
55
57
  }
56
58
  declare const isHTTPErrorInstance: <TErrorResponse>(error: unknown) => error is HTTPError<TErrorResponse>;
@@ -61,99 +63,41 @@ interface $RequestOptions extends Pick<FetchConfig, (typeof fetchSpecificKeys)[n
61
63
  interface $BaseRequestOptions extends Omit<$RequestOptions, "body"> {
62
64
  }
63
65
  interface ExtraOptions<TData = unknown, TErrorData = unknown, TResultMode extends ResultModeUnion = ResultModeUnion> {
64
- /** Optional body of the request, can be a object or any other supported body type. */
65
- body?: Record<string, unknown> | RequestInit["body"];
66
- /**
67
- * @description HTTP method for the request.
68
- * @default "GET"
69
- */
70
- method?: "GET" | "POST" | "PATCH" | "PUT" | "DELETE" | AnyString;
71
- /**
72
- * @description Query parameters to append to the URL.
73
- */
74
- query?: Record<string, string | number | boolean>;
75
66
  /**
76
67
  * @description Authorization header value.
77
68
  */
78
- auth?: string | {
69
+ auth?: {
79
70
  bearer: string;
80
71
  token?: never;
81
72
  } | {
82
- token: string;
83
73
  bearer?: never;
84
- };
74
+ token: string;
75
+ } | string;
85
76
  /**
86
- * @description Custom function to validate the response data.
77
+ * @description Base URL to be prepended to all request URLs
87
78
  */
88
- responseValidator?: (data: unknown) => TData;
79
+ baseURL?: string;
80
+ /** Optional body of the request, can be a object or any other supported body type. */
81
+ body?: Record<string, unknown> | RequestInit["body"];
89
82
  /**
90
83
  * @description Custom function to serialize the body object into a string.
91
84
  */
92
85
  bodySerializer?: (bodyData: Record<string, unknown>) => string;
93
- /**
94
- * @description Custom function to parse the response string into a object.
95
- */
96
- responseParser?: (responseString: string) => Record<string, unknown>;
97
- /**
98
- * @description Mode of the result, can influence how results are handled or returned.
99
- * Can be set to "all" | "onlySuccess" | "onlyError" | "onlyResponse".
100
- * @default "all"
101
- */
102
- resultMode?: TResultMode;
103
86
  /**
104
87
  * @description If true, cancels previous unfinished requests to the same URL.
105
88
  * @default true
106
89
  */
107
90
  cancelRedundantRequests?: boolean;
108
- /**
109
- * @description Base URL to be prepended to all request URLs
110
- */
111
- baseURL?: string;
112
- /**
113
- * @description Request timeout in milliseconds
114
- */
115
- timeout?: number;
116
- /**
117
- * @description Default error message to use if none is provided from a response.
118
- * @default "Failed to fetch data from server!"
119
- */
120
- defaultErrorMessage?: string;
121
91
  /**
122
92
  * @description Whether to clone the response, so response.json and the like can used in the interceptors.
123
93
  * @default false
124
94
  */
125
95
  cloneResponse?: boolean;
126
96
  /**
127
- * If true or the function returns true, throws errors instead of returning them
128
- * The function is passed the error object and can be used to conditionally throw the error
129
- * @default false
130
- */
131
- throwOnError?: boolean | ((error?: Error | HTTPError<TErrorData>) => boolean);
132
- /**
133
- * @description Expected response type, affects how response is parsed
134
- * @default "json"
135
- */
136
- responseType?: keyof ReturnType<typeof handleResponseType>;
137
- /**
138
- * @description Number of retry attempts for failed requests
139
- * @default 0
140
- */
141
- retries?: number;
142
- /**
143
- * @description Delay between retries in milliseconds
144
- * @default 500
145
- */
146
- retryDelay?: number;
147
- /**
148
- * @description HTTP status codes that trigger a retry
149
- * @default [409, 425, 429, 500, 502, 503, 504]
150
- */
151
- retryCodes?: Array<409 | 425 | 429 | 500 | 502 | 503 | 504 | AnyNumber>;
152
- /**
153
- * HTTP methods that are allowed to retry
154
- * @default ["GET", "POST"]
97
+ * @description Default error message to use if none is provided from a response.
98
+ * @default "Failed to fetch data from server!"
155
99
  */
156
- retryMethods?: Array<"GET" | "POST" | AnyString>;
100
+ defaultErrorMessage?: string;
157
101
  /**
158
102
  * @description an optional field you can fill with additional information,
159
103
  * to associate with the request, typically used for logging or tracing.
@@ -177,71 +121,143 @@ interface ExtraOptions<TData = unknown, TErrorData = unknown, TResultMode extend
177
121
  * ```
178
122
  */
179
123
  meta?: Record<string, unknown>;
124
+ /**
125
+ * @description HTTP method for the request.
126
+ * @default "GET"
127
+ */
128
+ method?: "DELETE" | "GET" | "PATCH" | "POST" | "PUT" | AnyString;
129
+ /**
130
+ * @description Interceptor to be called when an error occurs during the fetch request OR when an error response is received from the api
131
+ * It is basically a combination of `onRequestError` and `onResponseError` interceptors
132
+ */
133
+ onError?: (anyErrorContext: ErrorContext<TErrorData>) => Promise<void> | void;
180
134
  /** @description Interceptor to be called just before the request is made, allowing for modifications or additional operations. */
181
135
  onRequest?: (requestContext: {
182
- request: $RequestOptions;
183
136
  options: ExtraOptions;
184
- }) => void | Promise<void>;
137
+ request: $RequestOptions;
138
+ }) => Promise<void> | void;
185
139
  /** @description Interceptor to be called when an error occurs during the fetch request. */
186
140
  onRequestError?: (requestErrorContext: {
187
141
  error: Error;
188
- request: $RequestOptions;
189
142
  options: ExtraOptions;
190
- }) => void | Promise<void>;
143
+ request: $RequestOptions;
144
+ }) => Promise<void> | void;
191
145
  /** @description Interceptor to be called when a successful response is received from the api. */
192
- onResponse?: (responseContext: ResponseContext<TData>) => void | Promise<void>;
146
+ onResponse?: (responseContext: ResponseContext<TData>) => Promise<void> | void;
193
147
  /** @description Interceptor to be called when an error response is received from the api. */
194
- onResponseError?: (responseErrorContext: ResponseErrorContext<TErrorData>) => void | Promise<void>;
148
+ onResponseError?: (responseErrorContext: ResponseErrorContext<TErrorData>) => Promise<void> | void;
149
+ /**
150
+ * @description Query parameters to append to the URL.
151
+ */
152
+ query?: Record<string, boolean | number | string>;
153
+ /**
154
+ * @description Custom function to parse the response string into a object.
155
+ */
156
+ responseParser?: (responseString: string) => Record<string, unknown>;
157
+ /**
158
+ * @description Expected response type, affects how response is parsed
159
+ * @default "json"
160
+ */
161
+ responseType?: keyof ReturnType<typeof handleResponseType>;
162
+ /**
163
+ * @description Custom function to validate the response data.
164
+ */
165
+ responseValidator?: (data: unknown) => TData;
166
+ /**
167
+ * @description Mode of the result, can influence how results are handled or returned.
168
+ * Can be set to "all" | "onlySuccess" | "onlyError" | "onlyResponse".
169
+ * @default "all"
170
+ */
171
+ resultMode?: TResultMode;
172
+ /**
173
+ * @description Number of retry attempts for failed requests
174
+ * @default 0
175
+ */
176
+ retries?: number;
177
+ /**
178
+ * @description HTTP status codes that trigger a retry
179
+ * @default [409, 425, 429, 500, 502, 503, 504]
180
+ */
181
+ retryCodes?: Array<409 | 425 | 429 | 500 | 502 | 503 | 504 | AnyNumber>;
182
+ /**
183
+ * @description Delay between retries in milliseconds
184
+ * @default 500
185
+ */
186
+ retryDelay?: number;
187
+ /**
188
+ * HTTP methods that are allowed to retry
189
+ * @default ["GET", "POST"]
190
+ */
191
+ retryMethods?: Array<"GET" | "POST" | AnyString>;
192
+ /**
193
+ * If true or the function returns true, throws errors instead of returning them
194
+ * The function is passed the error object and can be used to conditionally throw the error
195
+ * @default false
196
+ */
197
+ throwOnError?: ((error?: Error | HTTPError<TErrorData>) => boolean) | boolean;
198
+ /**
199
+ * @description Request timeout in milliseconds
200
+ */
201
+ timeout?: number;
195
202
  }
196
- type ResponseContext<TData> = {
197
- _: {
198
- response: Response;
199
- data: TData;
200
- request: $RequestOptions;
201
- options: ExtraOptions;
202
- };
203
- }["_"];
204
- type ResponseErrorContext<TErrorData> = {
205
- _: {
206
- response: Response;
207
- errorData: TErrorData;
208
- request: $RequestOptions;
209
- options: ExtraOptions;
210
- };
211
- }["_"];
212
- interface FetchConfig<TData = unknown, TErrorData = unknown, TResultMode extends ResultModeUnion = undefined> extends Omit<RequestInit, "method" | "body">, ExtraOptions<TData, TErrorData, TResultMode> {
203
+ type ResponseContext<TData> = Prettify<{
204
+ data: TData;
205
+ options: ExtraOptions;
206
+ request: $RequestOptions;
207
+ response: Response;
208
+ }>;
209
+ type ResponseErrorContext<TErrorData> = Prettify<{
210
+ errorData: TErrorData;
211
+ options: ExtraOptions;
212
+ request: $RequestOptions;
213
+ response: Response;
214
+ }>;
215
+ type ErrorContext<TErrorData> = Prettify<{
216
+ error: Error;
217
+ errorData?: null;
218
+ options: ExtraOptions;
219
+ request: $RequestOptions;
220
+ response: null;
221
+ } | {
222
+ error: null;
223
+ errorData?: TErrorData;
224
+ options: ExtraOptions;
225
+ request: $RequestOptions;
226
+ response: Response;
227
+ }>;
228
+ interface FetchConfig<TData = unknown, TErrorData = unknown, TResultMode extends ResultModeUnion = "all"> extends Omit<RequestInit, "body" | "method">, ExtraOptions<TData, TErrorData, TResultMode> {
213
229
  }
214
- type BaseConfig<TBaseData = unknown, TBaseErrorData = unknown, TBaseResultMode extends ResultModeUnion = undefined> = FetchConfig<TBaseData, TBaseErrorData, TBaseResultMode>;
230
+ type BaseConfig<TBaseData = unknown, TBaseErrorData = unknown, TBaseResultMode extends ResultModeUnion = "all"> = FetchConfig<TBaseData, TBaseErrorData, TBaseResultMode>;
215
231
  type ApiSuccessVariant<TData> = {
216
232
  data: TData;
217
233
  error: null;
218
234
  response: Response;
219
235
  };
220
236
  type PossibleErrorNames = {
221
- _: "AbortError" | "TimeoutError" | "SyntaxError" | "TypeError" | "Error" | "UnknownError";
237
+ _: "AbortError" | "Error" | "SyntaxError" | "TimeoutError" | "TypeError" | "UnknownError";
222
238
  }["_"];
223
239
  type ApiErrorVariant<TErrorData> = {
224
240
  data: null;
225
241
  error: {
226
- name: "HTTPError";
227
- errorData: TErrorData;
242
+ errorData: Error;
228
243
  message: string;
244
+ name: PossibleErrorNames;
229
245
  };
230
- response: Response;
246
+ response: null;
231
247
  } | {
232
248
  data: null;
233
249
  error: {
234
- name: PossibleErrorNames;
235
- errorData: Error;
250
+ errorData: TErrorData;
236
251
  message: string;
252
+ name: "HTTPError";
237
253
  };
238
- response: null;
254
+ response: Response;
239
255
  };
240
256
  type ResultModeMap<TData = unknown, TErrorData = unknown> = {
241
- all: ApiSuccessVariant<TData> | ApiErrorVariant<TErrorData>;
242
- onlySuccess: ApiSuccessVariant<TData>["data"];
257
+ all: ApiErrorVariant<TErrorData> | ApiSuccessVariant<TData>;
243
258
  onlyError: ApiErrorVariant<TErrorData>["error"];
244
259
  onlyResponse: Response;
260
+ onlySuccess: ApiSuccessVariant<TData>["data"];
245
261
  };
246
262
  type ResultModeUnion = {
247
263
  _: {
@@ -250,4 +266,4 @@ type ResultModeUnion = {
250
266
  }["_"];
251
267
  type GetCallApiResult<TData, TErrorData, TResultMode> = TResultMode extends NonNullable<ResultModeUnion> ? ResultModeMap<TData, TErrorData>[TResultMode] : ResultModeMap<TData, TErrorData>["all"];
252
268
 
253
- export { type $RequestOptions as $, type BaseConfig as B, type ExtraOptions as E, type FetchConfig as F, type GetCallApiResult as G, HTTPError as H, type ResultModeUnion as R, type ResponseContext as a, type ResponseErrorContext as b, isHTTPErrorInstance as c, defaultRetryCodes as d, defaultRetryMethods as e, fetchSpecificKeys as f, getResponseData as g, handleResponseType as h, isHTTPError as i, $resolveErrorResult as j, mergeUrlWithParams as m, objectifyHeaders as o, resolveSuccessResult as r, splitConfig as s, toQueryString as t, waitUntil as w };
269
+ export { type $RequestOptions as $, type BaseConfig as B, type ExtraOptions as E, type FetchConfig as F, type GetCallApiResult as G, HTTPError as H, type ResultModeUnion as R, type ResponseContext as a, type ResponseErrorContext as b, type ErrorContext as c, defaultRetryCodes as d, defaultRetryMethods as e, fetchSpecificKeys as f, getRequestKey as g, omitKeys as h, handleResponseType as i, getResponseData as j, getResolveErrorResultFn as k, isHTTPError as l, mergeUrlWithParams as m, isHTTPErrorInstance as n, objectifyHeaders as o, resolveSuccessResult as r, splitConfig as s, toQueryString as t, waitUntil as w };
@@ -1,2 +1,2 @@
1
- export { j as $resolveErrorResult, H as HTTPError, d as defaultRetryCodes, e as defaultRetryMethods, f as fetchSpecificKeys, g as getResponseData, h as handleResponseType, i as isHTTPError, c as isHTTPErrorInstance, m as mergeUrlWithParams, o as objectifyHeaders, r as resolveSuccessResult, s as splitConfig, t as toQueryString, w as waitUntil } from './types-DIDORyP8.js';
2
- import './type-helpers-Dibitydy.js';
1
+ export { H as HTTPError, d as defaultRetryCodes, e as defaultRetryMethods, f as fetchSpecificKeys, g as getRequestKey, k as getResolveErrorResultFn, j as getResponseData, i as handleResponseType, l as isHTTPError, n as isHTTPErrorInstance, m as mergeUrlWithParams, o as objectifyHeaders, h as omitKeys, r as resolveSuccessResult, s as splitConfig, t as toQueryString, w as waitUntil } from './types-CfjkQnRk.js';
2
+ import './type-helpers-DpDJiTqb.js';
package/dist/esm/utils.js CHANGED
@@ -1,4 +1 @@
1
- export { k as $resolveErrorResult, m as HTTPError, d as defaultRetryCodes, e as defaultRetryMethods, f as fetchSpecificKeys, i as getResponseData, h as handleResponseType, l as isHTTPError, n as isHTTPErrorInstance, b as mergeUrlWithParams, c as objectifyHeaders, j as resolveSuccessResult, g as splitConfig, a as toQueryString, o as waitUntil } from './chunk-XE3JEDG3.js';
2
- import './chunk-ZYWIPUWT.js';
3
- //# sourceMappingURL=out.js.map
4
- //# sourceMappingURL=utils.js.map
1
+ export{HTTPError,defaultRetryCodes,defaultRetryMethods,fetchSpecificKeys,getRequestKey,getResolveErrorResultFn,getResponseData,handleResponseType,isHTTPError,isHTTPErrorInstance,mergeUrlWithParams,objectifyHeaders,omitKeys,resolveSuccessResult,splitConfig,toQueryString,waitUntil}from"./chunk-F6RUPSGH.js";import"./chunk-AKFUJ4JG.js";//# sourceMappingURL=utils.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":[],"names":[],"mappings":""}
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"utils.js"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zayne-labs/callapi",
3
- "version": "0.5.4",
3
+ "version": "0.7.0",
4
4
  "type": "module",
5
5
  "description": "A lightweight wrapper over fetch with quality of life improvements like built-in request cancellation, retries, interceptors and more",
6
6
  "main": "./dist/esm/index.js",
@@ -39,24 +39,28 @@
39
39
  "node": ">=18.17.x"
40
40
  },
41
41
  "devDependencies": {
42
- "@arethetypeswrong/cli": "^0.15.3",
42
+ "@arethetypeswrong/cli": "^0.15.4",
43
43
  "@changesets/cli": "^2.27.7",
44
- "@eslint/js": "^9.7.0",
44
+ "@eslint/js": "^9.9.0",
45
45
  "@size-limit/preset-small-lib": "^11.1.4",
46
- "@zayne-labs/tsconfig": "^0.0.7",
47
- "eslint": "^9.7.0",
48
- "eslint-plugin-import-x": "^3.0.1",
49
- "eslint-plugin-jsdoc": "^48.7.0",
50
- "eslint-plugin-sonarjs": "^1.0.3",
51
- "eslint-plugin-unicorn": "^54.0.0",
52
- "globals": "^15.8.0",
53
- "husky": "^9.0.11",
54
- "lint-staged": "^15.2.7",
46
+ "@stylistic/eslint-plugin": "^2.6.4",
47
+ "@zayne-labs/tsconfig": "^0.1.1",
48
+ "eslint": "^9.9.0",
49
+ "eslint-plugin-import-x": "^3.1.0",
50
+ "eslint-plugin-jsdoc": "^50.2.2",
51
+ "eslint-plugin-perfectionist": "^3.2.0",
52
+ "eslint-plugin-sonarjs": "^1.0.4",
53
+ "eslint-plugin-unicorn": "^55.0.0",
54
+ "eslint-typegen": "^0.3.1",
55
+ "globals": "^15.9.0",
56
+ "husky": "^9.1.4",
57
+ "lint-staged": "^15.2.9",
55
58
  "prettier": "^3.3.3",
56
59
  "size-limit": "^11.1.4",
57
- "tsup": "^8.1.0",
58
- "typescript": "5.5.3",
59
- "typescript-eslint": "^7.16.0"
60
+ "terser": "^5.31.6",
61
+ "tsup": "^8.2.4",
62
+ "typescript": "5.5.4",
63
+ "typescript-eslint": "^8.1.0"
60
64
  },
61
65
  "scripts": {
62
66
  "test:check-types": "tsc --pretty --incremental -p tsconfig.json",
@@ -1,8 +0,0 @@
1
- import { g, d, e, c, b as b$1, o, i, m, j, k, n } from './chunk-XE3JEDG3.js';
2
- import { b, e as e$1, d as d$1 } from './chunk-ZYWIPUWT.js';
3
-
4
- var x=F=>{let i$1=new Map,[P,j$1]=g(F??{}),{headers:g$1,body:v,signal:U,...k$1}=P,d$2=async(s,l)=>{let[z,G]=g(l??{}),{signal:h=U,body:o$1=v,headers:T,...H}=z,e$2={bodySerializer:JSON.stringify,responseType:"json",baseURL:"",retries:0,retryDelay:0,retryCodes:d,retryMethods:e,defaultErrorMessage:"Failed to fetch data from server!",cancelRedundantRequests:!0,...j$1,...G},y=i$1.get(s);if(y&&e$2.cancelRedundantRequests){let t=new DOMException(`Automatic cancelation of the previous unfinished request to this same url: ${s}`,"AbortError");y.abort(t);}let b$2=new AbortController;i$1.set(s,b$2);let m$1=e$2.timeout?AbortSignal.timeout(e$2.timeout):null,E=AbortSignal.any([b$2.signal,...m$1?[m$1]:[],...h?[h]:[]]),a={signal:E,method:"GET",body:b(o$1)?e$2.bodySerializer(o$1):o$1,headers:g$1||T||e$2.auth||b(o$1)?{...b(o$1)&&{"Content-Type":"application/json",Accept:"application/json"},...e$1(o$1)&&{"Content-Type":"application/x-www-form-urlencoded"},...d$1(e$2.auth)&&{Authorization:`Bearer ${e$2.auth}`},...b(e$2.auth)&&{Authorization:"bearer"in e$2.auth?`Bearer ${e$2.auth.bearer}`:`Token ${e$2.auth.token}`},...c(g$1),...c(T)}:void 0,...k$1,...H};try{await e$2.onRequest?.({request:a,options:e$2});let t=await fetch(`${e$2.baseURL}${b$1(s,e$2.query)}`,a);if(!t.ok&&!E.aborted&&e$2.retries>0&&e$2.retryCodes.includes(t.status)&&e$2.retryMethods.includes(a.method))return await o(e$2.retryDelay),await d$2(s,{...l,retries:e$2.retries-1});if(!t.ok){let I=await i(e$2.cloneResponse?t.clone():t,e$2.responseType,e$2.responseParser);throw new m({errorData:I,response:t,defaultErrorMessage:e$2.defaultErrorMessage})}let r=await i(e$2.cloneResponse?t.clone():t,e$2.responseType,e$2.responseParser),n=e$2.responseValidator?e$2.responseValidator(r):r;return await e$2.onResponse?.({data:n,response:e$2.cloneResponse?t.clone():t,request:a,options:e$2}),j({successData:n,response:t,options:e$2})}catch(t){let c=k({error:t,options:e$2});if(t instanceof DOMException&&t.name==="TimeoutError"){let r=`Request timed out after ${e$2.timeout}ms`;return console.error(`${t.name}:`,r),c({message:r})}if(t instanceof DOMException&&t.name==="AbortError"){let r=`Request aborted due to ${t.message}`;return console.error(`${t.name}:`,r),c({message:r})}if(n(t)){let{errorData:r,response:n}=t;return await e$2.onResponseError?.({errorData:r,response:e$2.cloneResponse?n.clone():n,request:a,options:e$2}),c({errorData:r,message:r?.message,response:n})}return await e$2.onRequestError?.({request:a,error:t,options:e$2}),c()}finally{i$1.delete(s);}};return d$2.create=x,d$2.cancel=(s,l)=>{l?i$1.get(s)?.abort(l):i$1.get(s)?.abort();},d$2},J=x();
5
-
6
- export { x as a, J as b };
7
- //# sourceMappingURL=out.js.map
8
- //# sourceMappingURL=chunk-RRO7PFYR.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/createFetchClient.ts"],"names":["createFetchClient","baseConfig","abortControllerStore","baseFetchConfig","baseExtraOptions","splitConfig","baseHeaders","baseBody","baseSignal","restOfBaseFetchConfig","callApi","url","config","fetchConfig","extraOptions","signal","body","headers","restOfFetchConfig","options","defaultRetryCodes","defaultRetryMethods","prevFetchController","reason","newFetchController","timeoutSignal","combinedSignal","requestInit","isObject","isQueryString","isString","objectifyHeaders","response","mergeUrlWithParams","waitUntil","errorData","getResponseData","HTTPError","successData","validSuccessData","resolveSuccessResult","error","resolveErrorResult","$resolveErrorResult","message","isHTTPErrorInstance"],"mappings":"oKAwBO,IAAMA,EAKZC,GACI,CACJ,IAAMC,EAAuB,IAAI,IAE3B,CAACC,EAAiBC,CAAgB,EAAIC,EAAYJ,GAAc,CAAC,CAAC,EAElE,CACL,QAASK,EACT,KAAMC,EACN,OAAQC,EACR,GAAGC,CACJ,EAAIN,EAGEO,EAAU,MAKfC,EACAC,IAC+D,CAG/D,GAAM,CAACC,EAAaC,CAAY,EAAIT,EAAYO,GAAU,CAAC,CAAC,EAEtD,CAAE,OAAAG,EAASP,EAAY,KAAAQ,EAAOT,EAAU,QAAAU,EAAS,GAAGC,CAAkB,EAAIL,EAG1EM,EAAU,CACf,eAAgB,KAAK,UACrB,aAAc,OACd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,CAAC,CACtC,CAEA,GAAIH,aAAiB,cAAgBA,EAAM,OAAS,aAAc,CACjE,IAAMG,EAAU,0BAA0BH,EAAM,OAAO,GAEvD,eAAQ,MAAM,GAAGA,EAAM,IAAI,IAAKG,CAAO,EAEhCF,EAAmB,CAAE,QAAAE,CAAQ,CAAC,CACtC,CAEA,GAAIC,EAAgCJ,CAAK,EAAG,CAC3C,GAAM,CAAE,UAAAN,EAAW,SAAAH,CAAS,EAAIS,EAEhC,aAAMtB,EAAQ,kBAAkB,CAC/B,UAAAgB,EACA,SAAUhB,EAAQ,cAAgBa,EAAS,MAAM,EAAIA,EACrD,QAASL,EACT,QAAAR,CACD,CAAC,EAEMuB,EAAmB,CACzB,UAAAP,EACA,QAAUA,GAAmC,QAC7C,SAAAH,CACD,CAAC,CACF,CAGA,aAAMb,EAAQ,iBAAiB,CAAE,QAASQ,EAAa,MAAOc,EAAgB,QAAAtB,CAAQ,CAAC,EAEhFuB,EAAmB,CAG3B,QAAE,CACDxC,EAAqB,OAAOS,CAAG,CAChC,CACD,EAEA,OAAAD,EAAQ,OAASV,EAEjBU,EAAQ,OAAS,CAACC,EAAaY,IAAqB,CACnDA,EAASrB,EAAqB,IAAIS,CAAG,GAAG,MAAMY,CAAM,EAAIrB,EAAqB,IAAIS,CAAG,GAAG,MAAM,CAC9F,EAEOD,CACR,EAEaA,EAAUV,EAAkB","sourcesContent":["import { isObject, isQueryString, isString } from \"./typeof\";\nimport type {\n\t$RequestOptions,\n\tBaseConfig,\n\tExtraOptions,\n\tFetchConfig,\n\tGetCallApiResult,\n\tPossibleErrorObject,\n\tResultModeUnion,\n} from \"./types\";\nimport {\n\t$resolveErrorResult,\n\tHTTPError,\n\tdefaultRetryCodes,\n\tdefaultRetryMethods,\n\tgetResponseData,\n\tisHTTPErrorInstance,\n\tmergeUrlWithParams,\n\tobjectifyHeaders,\n\tresolveSuccessResult,\n\tsplitConfig,\n\twaitUntil,\n} from \"./utils\";\n\nexport const createFetchClient = <\n\tTBaseData,\n\tTBaseErrorData = unknown,\n\tTBaseResultMode extends ResultModeUnion = undefined,\n>(\n\tbaseConfig?: BaseConfig<TBaseData, TBaseErrorData, TBaseResultMode>\n) => {\n\tconst abortControllerStore = new Map<string, AbortController>();\n\n\tconst [baseFetchConfig, baseExtraOptions] = splitConfig(baseConfig ?? {});\n\n\tconst {\n\t\theaders: baseHeaders,\n\t\tbody: baseBody,\n\t\tsignal: baseSignal,\n\t\t...restOfBaseFetchConfig\n\t} = baseFetchConfig;\n\n\t/* eslint-disable complexity */\n\tconst callApi = async <\n\t\tTData = TBaseData,\n\t\tTErrorData = TBaseErrorData,\n\t\tTResultMode extends ResultModeUnion = TBaseResultMode,\n\t>(\n\t\turl: string,\n\t\tconfig?: FetchConfig<TData, TErrorData, TResultMode>\n\t): Promise<GetCallApiResult<TData, TErrorData, TResultMode>> => {\n\t\ttype CallApiResult = GetCallApiResult<TData, TErrorData, TResultMode>;\n\n\t\tconst [fetchConfig, extraOptions] = splitConfig(config ?? {});\n\n\t\tconst { signal = baseSignal, body = baseBody, headers, ...restOfFetchConfig } = fetchConfig;\n\n\t\t// == Default Options\n\t\tconst options = {\n\t\t\tbodySerializer: JSON.stringify,\n\t\t\tresponseType: \"json\",\n\t\t\tbaseURL: \"\",\n\t\t\tretries: 0,\n\t\t\tretryDelay: 0,\n\t\t\tretryCodes: defaultRetryCodes,\n\t\t\tretryMethods: defaultRetryMethods,\n\t\t\tdefaultErrorMessage: \"Failed to fetch data from server!\",\n\t\t\tcancelRedundantRequests: true,\n\t\t\t...baseExtraOptions,\n\t\t\t...extraOptions,\n\t\t} satisfies ExtraOptions;\n\n\t\tconst prevFetchController = abortControllerStore.get(url);\n\n\t\tif (prevFetchController && options.cancelRedundantRequests) {\n\t\t\tconst reason = new DOMException(\n\t\t\t\t`Automatic cancelation of the previous unfinished request to this same url: ${url}`,\n\t\t\t\t\"AbortError\"\n\t\t\t);\n\t\t\tprevFetchController.abort(reason);\n\t\t}\n\n\t\tconst newFetchController = new AbortController();\n\n\t\tabortControllerStore.set(url, newFetchController);\n\n\t\tconst timeoutSignal = options.timeout ? AbortSignal.timeout(options.timeout) : null;\n\n\t\tconst combinedSignal = AbortSignal.any([\n\t\t\tnewFetchController.signal,\n\t\t\t...(timeoutSignal ? [timeoutSignal] : []),\n\t\t\t...(signal ? [signal] : []),\n\t\t]);\n\n\t\tconst requestInit = {\n\t\t\tsignal: combinedSignal,\n\n\t\t\tmethod: \"GET\",\n\n\t\t\tbody: isObject(body) ? options.bodySerializer(body) : body,\n\n\t\t\t// == Return undefined if the following conditions are not met (so that native fetch would auto set the correct headers):\n\t\t\t// - headers are provided\n\t\t\t// - The body is an object\n\t\t\t// - The auth option is provided\n\t\t\theaders:\n\t\t\t\tbaseHeaders || headers || options.auth || isObject(body)\n\t\t\t\t\t? {\n\t\t\t\t\t\t\t...(isObject(body) && {\n\t\t\t\t\t\t\t\t\"Content-Type\": \"application/json\",\n\t\t\t\t\t\t\t\tAccept: \"application/json\",\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...(isQueryString(body) && {\n\t\t\t\t\t\t\t\t\"Content-Type\": \"application/x-www-form-urlencoded\",\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...(isString(options.auth) && {\n\t\t\t\t\t\t\t\tAuthorization: `Bearer ${options.auth}`,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...(isObject(options.auth) && {\n\t\t\t\t\t\t\t\tAuthorization:\n\t\t\t\t\t\t\t\t\t\"bearer\" in options.auth\n\t\t\t\t\t\t\t\t\t\t? `Bearer ${options.auth.bearer}`\n\t\t\t\t\t\t\t\t\t\t: `Token ${options.auth.token}`,\n\t\t\t\t\t\t\t}),\n\t\t\t\t\t\t\t...objectifyHeaders(baseHeaders),\n\t\t\t\t\t\t\t...objectifyHeaders(headers),\n\t\t\t\t\t\t}\n\t\t\t\t\t: undefined,\n\n\t\t\t...restOfBaseFetchConfig,\n\t\t\t...restOfFetchConfig,\n\t\t} satisfies $RequestOptions;\n\n\t\ttry {\n\t\t\tawait options.onRequest?.({ request: requestInit, options });\n\n\t\t\tconst response = await fetch(\n\t\t\t\t`${options.baseURL}${mergeUrlWithParams(url, options.query)}`,\n\t\t\t\trequestInit\n\t\t\t);\n\n\t\t\tconst shouldRetry =\n\t\t\t\t!response.ok &&\n\t\t\t\t!combinedSignal.aborted &&\n\t\t\t\toptions.retries > 0 &&\n\t\t\t\toptions.retryCodes.includes(response.status) &&\n\t\t\t\toptions.retryMethods.includes(requestInit.method);\n\n\t\t\tif (shouldRetry) {\n\t\t\t\tawait waitUntil(options.retryDelay);\n\n\t\t\t\treturn await callApi(url, { ...config, retries: options.retries - 1 });\n\t\t\t}\n\n\t\t\tif (!response.ok) {\n\t\t\t\tconst errorData = await getResponseData<TErrorData>(\n\t\t\t\t\toptions.cloneResponse ? response.clone() : response,\n\t\t\t\t\toptions.responseType,\n\t\t\t\t\toptions.responseParser\n\t\t\t\t);\n\n\t\t\t\t// == Pushing all error handling responsibilities to the catch block\n\t\t\t\tthrow new HTTPError({\n\t\t\t\t\terrorData,\n\t\t\t\t\tresponse,\n\t\t\t\t\tdefaultErrorMessage: options.defaultErrorMessage,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst successData = await getResponseData<TData>(\n\t\t\t\toptions.cloneResponse ? response.clone() : response,\n\t\t\t\toptions.responseType,\n\t\t\t\toptions.responseParser\n\t\t\t);\n\n\t\t\tconst validSuccessData = options.responseValidator\n\t\t\t\t? options.responseValidator(successData)\n\t\t\t\t: successData;\n\n\t\t\tawait options.onResponse?.({\n\t\t\t\tdata: validSuccessData,\n\t\t\t\tresponse: options.cloneResponse ? response.clone() : response,\n\t\t\t\trequest: requestInit,\n\t\t\t\toptions,\n\t\t\t});\n\n\t\t\treturn resolveSuccessResult<CallApiResult>({ successData: validSuccessData, response, options });\n\n\t\t\t// == Exhaustive Error handling\n\t\t} catch (error) {\n\t\t\tconst resolveErrorResult = $resolveErrorResult<CallApiResult>({ error, options });\n\n\t\t\tif (error instanceof DOMException && error.name === \"TimeoutError\") {\n\t\t\t\tconst message = `Request timed out after ${options.timeout}ms`;\n\n\t\t\t\tconsole.error(`${error.name}:`, message);\n\n\t\t\t\treturn resolveErrorResult({ message });\n\t\t\t}\n\n\t\t\tif (error instanceof DOMException && error.name === \"AbortError\") {\n\t\t\t\tconst message = `Request aborted due to ${error.message}`;\n\n\t\t\t\tconsole.error(`${error.name}:`, message);\n\n\t\t\t\treturn resolveErrorResult({ message });\n\t\t\t}\n\n\t\t\tif (isHTTPErrorInstance<TErrorData>(error)) {\n\t\t\t\tconst { errorData, response } = error;\n\n\t\t\t\tawait options.onResponseError?.({\n\t\t\t\t\terrorData,\n\t\t\t\t\tresponse: options.cloneResponse ? response.clone() : response,\n\t\t\t\t\trequest: requestInit,\n\t\t\t\t\toptions,\n\t\t\t\t});\n\n\t\t\t\treturn resolveErrorResult({\n\t\t\t\t\terrorData,\n\t\t\t\t\tmessage: (errorData as PossibleErrorObject)?.message,\n\t\t\t\t\tresponse,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\t// == At this point only the request errors exist, so the request error interceptor is called\n\t\t\tawait options.onRequestError?.({ request: requestInit, error: error as Error, options });\n\n\t\t\treturn resolveErrorResult();\n\n\t\t\t// == Removing the now unneeded AbortController from store\n\t\t} finally {\n\t\t\tabortControllerStore.delete(url);\n\t\t}\n\t};\n\n\tcallApi.create = createFetchClient;\n\n\tcallApi.cancel = (url: string, reason?: unknown) => {\n\t\treason ? abortControllerStore.get(url)?.abort(reason) : abortControllerStore.get(url)?.abort();\n\t};\n\n\treturn callApi;\n};\n\nexport const callApi = createFetchClient();\n"]}
@@ -1,7 +0,0 @@
1
- import { b as b$1, a, c as c$1 } from './chunk-ZYWIPUWT.js';
2
-
3
- var E=r=>r?new URLSearchParams(r).toString():(console.error("No query params provided"),null),b=(r,e)=>{if(!e)return r;let t=E(e);return r.endsWith("?")?`${r}${t}`:r.includes("?")?`${r}&${t}`:`${r}?${t}`},g=r=>!r||b$1(r)?r:Object.fromEntries(a(r)?r:r.entries()),y={408:"Request Timeout",409:"Conflict",425:"Too Early",429:"Too Many Requests",500:"Internal Server Error",502:"Bad Gateway",503:"Service Unavailable",504:"Gateway Timeout"},x=Object.keys(y).map(Number),j=["GET"],l=["body","integrity","method","headers","signal","cache","redirect","window","credentials","keepalive","referrer","priority","mode","referrerPolicy"],T=(r,e)=>{let t=Object.entries(r).filter(([s])=>!e.includes(s));return Object.fromEntries(t)},R=(r,e)=>{let t=new Set(e),s=Object.entries(r).filter(([i])=>t.has(i));return Object.fromEntries(s)},w=r=>[R(r,l),T(r,l)],O=(r,e)=>({json:async()=>e?e(await r.text()):r.json(),arrayBuffer:()=>r.arrayBuffer(),blob:()=>r.blob(),formData:()=>r.formData(),text:()=>r.text()}),P=(r,e,t)=>{let o=O(r,t);if(!Object.hasOwn(o,e))throw new Error(`Invalid response type: ${e}`);return o[e]()},k=r=>{let{options:e,response:t,successData:o}=r,s={data:o,error:null,response:t};return e.resultMode===void 0||e.resultMode==="all"?s:{onlySuccess:s.data,onlyError:s.error,onlyResponse:s.response}[e.resultMode]},h=r=>{let{error:e,options:t}=r;return (s={})=>{let{errorData:n,message:i,response:d}=s;if(c$1(t.throwOnError)?t.throwOnError(e):t.throwOnError)throw e;return {data:null,error:{name:e?.name??"UnknownError",errorData:n??e,message:i??e?.message??t.defaultErrorMessage},response:d??null}}},A=r=>b$1(r)&&r.name==="HTTPError",c=class extends Error{response;errorData;name="HTTPError";isHTTPError=!0;constructor(e,t){let{defaultErrorMessage:o,response:s,errorData:n}=e;super(n.message??o,t),this.errorData=n,this.response=s;}},D=r=>r instanceof c||b$1(r)&&r.name==="HTTPError"&&r.isHTTPError===!0,C=r=>{if(r===0)return;let{promise:e,resolve:t}=Promise.withResolvers();return setTimeout(t,r),e};
4
-
5
- export { E as a, b, g as c, x as d, j as e, l as f, w as g, O as h, P as i, k as j, h as k, A as l, c as m, D as n, C as o };
6
- //# sourceMappingURL=out.js.map
7
- //# sourceMappingURL=chunk-XE3JEDG3.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/utils.ts"],"names":["toQueryString","params","mergeUrlWithParams","url","paramsString","objectifyHeaders","headers","isObject","isArray","retryCodesLookup","defaultRetryCodes","defaultRetryMethods","fetchSpecificKeys","omitKeys","initialObject","keysToOmit","arrayFromFilteredObject","key","pickKeys","keysToPick","keysToPickSet","filteredArray","objectKey","splitConfig","config","handleResponseType","response","parser","getResponseData","responseType","RESPONSE_TYPE_LOOKUP","resolveSuccessResult","info","options","successData","apiDetails","$resolveErrorResult","$info","error","errorData","message","isFunction","isHTTPError","HTTPError","errorDetails","errorOptions","defaultErrorMessage","isHTTPErrorInstance","waitUntil","delay","promise","resolve"],"mappings":"sDAgBO,IAAMA,EAAkCC,GACzCA,EAKE,IAAI,gBAAgBA,CAAgC,EAAE,SAAS,GAJrE,QAAQ,MAAM,0BAA0B,EACjC,MAMIC,EAAqB,CAACC,EAAaF,IAA0C,CACzF,GAAI,CAACA,EACJ,OAAOE,EAGR,IAAMC,EAAeJ,EAAcC,CAAM,EAEzC,OAAIE,EAAI,SAAS,GAAG,EACZ,GAAGA,CAAG,GAAGC,CAAY,GAGzBD,EAAI,SAAS,GAAG,EACZ,GAAGA,CAAG,IAAIC,CAAY,GAGvB,GAAGD,CAAG,IAAIC,CAAY,EAC9B,EAEaC,EAAoBC,GAC5B,CAACA,GAAWC,EAASD,CAAO,EACxBA,EAGD,OAAO,YAAYE,EAAQF,CAAO,EAAIA,EAAUA,EAAQ,QAAQ,CAAC,EAGnEG,EAAmB,CACxB,IAAK,kBACL,IAAK,WACL,IAAK,YACL,IAAK,oBACL,IAAK,wBACL,IAAK,cACL,IAAK,sBACL,IAAK,iBACN,EAEaC,EACZ,OAAO,KAAKD,CAAgB,EAAE,IAAI,MAAM,EAE5BE,EAA4D,CAAC,KAAK,EAElEC,EAAoB,CAChC,OACA,YACA,SACA,UACA,SACA,QACA,WACA,SACA,cACA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EAAEF,EAAQ,UAAU,CACrB,EAGaG,EAAsCC,GAAsD,CACxG,GAAM,CAAE,MAAAC,EAAO,QAAAL,CAAQ,EAAII,EA8B3B,MAtB2B,CAACL,EAAkB,CAAC,IAAqB,CACnE,GAAM,CAAE,UAAAO,EAAW,QAAAC,EAAS,SAAAd,CAAS,EAAIM,EAMzC,GAJ2BS,EAAWR,EAAQ,YAAY,EACvDA,EAAQ,aAAaK,CAAc,EACnCL,EAAQ,aAGV,MAAMK,EAGP,MAAO,CACN,KAAM,KACN,MAAO,CACN,KAAOA,GAA+B,MAAQ,eAC9C,UAAWC,GAAaD,EACxB,QAASE,GAAYF,GAA+B,SAAWL,EAAQ,mBACxE,EACA,SAAUP,GAAY,IACvB,CACD,CAGD,EAEagB,EAA2BJ,GAChC/B,EAAS+B,CAAK,GAAKA,EAAM,OAAS,YAa7BK,EAAN,cAAkE,KAAM,CAC9E,SACA,UAES,KAAO,YAEhB,YAAc,GAEd,YAAYC,EAA4CC,EAA6B,CACpF,GAAM,CAAE,oBAAAC,EAAqB,SAAApB,EAAU,UAAAa,CAAU,EAAIK,EAErD,MAAOL,EAAmC,SAAWO,EAAqBD,CAAY,EAEtF,KAAK,UAAYN,EACjB,KAAK,SAAWb,CACjB,CACD,EAGaqB,EACZT,GAGCA,aAAiBK,GAAcpC,EAAS+B,CAAK,GAAKA,EAAM,OAAS,aAAeA,EAAM,cAAgB,GAI3FU,EAAaC,GAAkB,CAC3C,GAAIA,IAAU,EAAG,OAEjB,GAAM,CAAE,QAAAC,EAAS,QAAAC,CAAQ,EAAI,QAAQ,cAAc,EAEnD,kBAAWA,EAASF,CAAK,EAElBC,CACR","sourcesContent":["import { isArray, isFunction, isObject } from \"./typeof\";\nimport type {\n\t$BaseRequestOptions,\n\t$RequestOptions,\n\tApiErrorVariant,\n\tBaseConfig,\n\tExtraOptions,\n\tFetchConfig,\n\tPossibleErrorObject,\n} from \"./types\";\n\ntype ToQueryStringFn = {\n\t(params: ExtraOptions[\"query\"]): string | null;\n\t(params: Required<ExtraOptions>[\"query\"]): string;\n};\n\nexport const toQueryString: ToQueryStringFn = (params) => {\n\tif (!params) {\n\t\tconsole.error(\"No query params provided\");\n\t\treturn null as never;\n\t}\n\n\treturn new URLSearchParams(params as Record<string, string>).toString();\n};\n\nexport const mergeUrlWithParams = (url: string, params: ExtraOptions[\"query\"]): string => {\n\tif (!params) {\n\t\treturn url;\n\t}\n\n\tconst paramsString = toQueryString(params);\n\n\tif (url.endsWith(\"?\")) {\n\t\treturn `${url}${paramsString}`;\n\t}\n\n\tif (url.includes(\"?\")) {\n\t\treturn `${url}&${paramsString}`;\n\t}\n\n\treturn `${url}?${paramsString}`;\n};\n\nexport const objectifyHeaders = (headers: RequestInit[\"headers\"]): Record<string, string> | undefined => {\n\tif (!headers || isObject(headers)) {\n\t\treturn headers;\n\t}\n\n\treturn Object.fromEntries(isArray(headers) ? headers : headers.entries());\n};\n\nconst retryCodesLookup = {\n\t408: \"Request Timeout\",\n\t409: \"Conflict\",\n\t425: \"Too Early\",\n\t429: \"Too Many Requests\",\n\t500: \"Internal Server Error\",\n\t502: \"Bad Gateway\",\n\t503: \"Service Unavailable\",\n\t504: \"Gateway Timeout\",\n};\n\nexport const defaultRetryCodes: Required<BaseConfig>[\"retryCodes\"] =\n\tObject.keys(retryCodesLookup).map(Number);\n\nexport const defaultRetryMethods: Required<BaseConfig>[\"retryMethods\"] = [\"GET\"];\n\nexport const fetchSpecificKeys = [\n\t\"body\",\n\t\"integrity\",\n\t\"method\",\n\t\"headers\",\n\t\"signal\",\n\t\"cache\",\n\t\"redirect\",\n\t\"window\",\n\t\"credentials\",\n\t\"keepalive\",\n\t\"referrer\",\n\t\"priority\",\n\t\"mode\",\n\t\"referrerPolicy\",\n] satisfies Array<keyof FetchConfig>;\n\nconst omitKeys = <TObject extends Record<string, unknown>, const TOmitArray extends Array<keyof TObject>>(\n\tinitialObject: TObject,\n\tkeysToOmit: TOmitArray\n) => {\n\tconst arrayFromFilteredObject = Object.entries(initialObject).filter(\n\t\t([key]) => !keysToOmit.includes(key)\n\t);\n\n\tconst updatedObject = Object.fromEntries(arrayFromFilteredObject);\n\n\treturn updatedObject as Omit<TObject, keyof TOmitArray>;\n};\n\nconst pickKeys = <TObject extends Record<string, unknown>, const TPickArray extends Array<keyof TObject>>(\n\tinitialObject: TObject,\n\tkeysToPick: TPickArray\n) => {\n\tconst keysToPickSet = new Set(keysToPick);\n\n\tconst arrayFromInitObject = Object.entries(initialObject);\n\n\tconst filteredArray = arrayFromInitObject.filter(([objectKey]) => keysToPickSet.has(objectKey));\n\n\tconst updatedObject = Object.fromEntries(filteredArray);\n\n\treturn updatedObject as Pick<TObject, TPickArray[number]>;\n};\n\nexport const splitConfig = <TObject extends object>(\n\tconfig: TObject\n): [\"body\" extends keyof TObject ? $RequestOptions : $BaseRequestOptions, ExtraOptions] => [\n\tpickKeys(config as Record<string, unknown>, fetchSpecificKeys) as never,\n\tomitKeys(config as Record<string, unknown>, fetchSpecificKeys) as never,\n];\n\nexport const handleResponseType = <TResponse>(\n\tresponse: Response,\n\tparser?: Required<ExtraOptions>[\"responseParser\"]\n) => ({\n\tjson: async () => {\n\t\tif (parser) {\n\t\t\treturn parser(await response.text());\n\t\t}\n\n\t\treturn response.json() as Promise<TResponse>;\n\t},\n\tarrayBuffer: () => response.arrayBuffer() as Promise<TResponse>,\n\tblob: () => response.blob() as Promise<TResponse>,\n\tformData: () => response.formData() as Promise<TResponse>,\n\ttext: () => response.text() as Promise<TResponse>,\n});\n\nexport const getResponseData = <TResponse>(\n\tresponse: Response,\n\tresponseType: keyof ReturnType<typeof handleResponseType>,\n\tparser: ExtraOptions[\"responseParser\"]\n) => {\n\tconst RESPONSE_TYPE_LOOKUP = handleResponseType<TResponse>(response, parser);\n\n\tif (!Object.hasOwn(RESPONSE_TYPE_LOOKUP, responseType)) {\n\t\tthrow new Error(`Invalid response type: ${responseType}`);\n\t}\n\n\treturn RESPONSE_TYPE_LOOKUP[responseType]();\n};\n\ntype data = {\n\tsuccessData: unknown;\n\toptions: ExtraOptions;\n\tresponse: Response;\n};\n\n// == The CallApiResult type is used to cast all return statements due to a design limitation in ts.\n// LINK - See https://www.zhenghao.io/posts/type-functions for more info\nexport const resolveSuccessResult = <CallApiResult>(info: data): CallApiResult => {\n\tconst { options, response, successData } = info;\n\n\tconst apiDetails = {\n\t\tdata: successData,\n\t\terror: null,\n\t\tresponse,\n\t};\n\n\tif (options.resultMode === undefined || options.resultMode === \"all\") {\n\t\treturn apiDetails as CallApiResult;\n\t}\n\n\treturn {\n\t\tonlySuccess: apiDetails.data,\n\t\tonlyError: apiDetails.error,\n\t\tonlyResponse: apiDetails.response,\n\t}[options.resultMode] as CallApiResult;\n};\n\n// == Using curring here so error and options are not required to be passed every time, instead to be captured once by way of closure\nexport const $resolveErrorResult = <CallApiResult>($info: { error?: unknown; options: ExtraOptions }) => {\n\tconst { error, options } = $info;\n\n\ttype ErrorInfo = {\n\t\tresponse?: Response;\n\t\terrorData?: unknown;\n\t\tmessage?: string;\n\t};\n\n\tconst resolveErrorResult = (info: ErrorInfo = {}): CallApiResult => {\n\t\tconst { errorData, message, response } = info;\n\n\t\tconst shouldThrowOnError = isFunction(options.throwOnError)\n\t\t\t? options.throwOnError(error as Error)\n\t\t\t: options.throwOnError;\n\n\t\tif (shouldThrowOnError) {\n\t\t\tthrow error;\n\t\t}\n\n\t\treturn {\n\t\t\tdata: null,\n\t\t\terror: {\n\t\t\t\tname: (error as PossibleErrorObject)?.name ?? \"UnknownError\",\n\t\t\t\terrorData: errorData ?? error,\n\t\t\t\tmessage: message ?? (error as PossibleErrorObject)?.message ?? options.defaultErrorMessage,\n\t\t\t},\n\t\t\tresponse: response ?? null,\n\t\t} as CallApiResult;\n\t};\n\n\treturn resolveErrorResult;\n};\n\nexport const isHTTPError = <TErrorData>(error: ApiErrorVariant<TErrorData>[\"error\"] | null) => {\n\treturn isObject(error) && error.name === \"HTTPError\";\n};\n\ntype ErrorDetails<TErrorResponse> = {\n\terrorData: TErrorResponse;\n\tresponse: Response;\n\tdefaultErrorMessage: string;\n};\n\ntype ErrorOptions = {\n\tcause?: unknown;\n};\n\nexport class HTTPError<TErrorResponse = Record<string, unknown>> extends Error {\n\tresponse: ErrorDetails<TErrorResponse>[\"response\"];\n\terrorData: ErrorDetails<TErrorResponse>[\"errorData\"];\n\n\toverride name = \"HTTPError\" as const;\n\n\tisHTTPError = true;\n\n\tconstructor(errorDetails: ErrorDetails<TErrorResponse>, errorOptions?: ErrorOptions) {\n\t\tconst { defaultErrorMessage, response, errorData } = errorDetails;\n\n\t\tsuper((errorData as { message?: string }).message ?? defaultErrorMessage, errorOptions);\n\n\t\tthis.errorData = errorData;\n\t\tthis.response = response;\n\t}\n}\n\n// prettier-ignore\nexport const isHTTPErrorInstance = <TErrorResponse>(\n\terror: unknown\n): error is HTTPError<TErrorResponse> => {\n\treturn (\n\t\terror instanceof HTTPError || (isObject(error) && error.name === \"HTTPError\" && error.isHTTPError === true)\n\t);\n};\n\nexport const waitUntil = (delay: number) => {\n\tif (delay === 0) return;\n\n\tconst { promise, resolve } = Promise.withResolvers();\n\n\tsetTimeout(resolve, delay);\n\n\treturn promise;\n};\n"]}
@@ -1,5 +0,0 @@
1
- var t=n=>Array.isArray(n),r=n=>typeof n=="object"&&n!==null&&!(n instanceof FormData)&&!Array.isArray(n),o=n=>typeof n=="function",e=n=>typeof n=="string",i=n=>typeof n=="string"&&n.includes("=");
2
-
3
- export { t as a, r as b, o as c, e as d, i as e };
4
- //# sourceMappingURL=out.js.map
5
- //# sourceMappingURL=chunk-ZYWIPUWT.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/typeof.ts"],"names":["isArray","value","isObject","isFunction","isString","isQueryString"],"mappings":"AAEO,IAAMA,EAAmBC,GAAsC,MAAM,QAAQA,CAAK,EAE5EC,EAAqDD,GAEhE,OAAOA,GAAU,UAAYA,IAAU,MAAQ,EAAEA,aAAiB,WAAa,CAAC,MAAM,QAAQA,CAAK,EAIxFE,EAA6CF,GACzD,OAAOA,GAAU,WAELG,EAAYH,GAAmB,OAAOA,GAAU,SAEhDI,EAAiBJ,GAC7B,OAAOA,GAAU,UAAYA,EAAM,SAAS,GAAG","sourcesContent":["import type { AnyFunction } from \"./type-helpers\";\n\nexport const isArray = <TArray>(value: unknown): value is TArray[] => Array.isArray(value);\n\nexport const isObject = <TObject extends Record<string, unknown>>(value: unknown): value is TObject => {\n\treturn (\n\t\ttypeof value === \"object\" && value !== null && !(value instanceof FormData) && !Array.isArray(value)\n\t);\n};\n\nexport const isFunction = <TFunction extends AnyFunction>(value: unknown): value is TFunction =>\n\ttypeof value === \"function\";\n\nexport const isString = (value: unknown) => typeof value === \"string\";\n\nexport const isQueryString = (value: unknown): value is string =>\n\ttypeof value === \"string\" && value.includes(\"=\");\n"]}