@zayne-labs/callapi 1.3.1 → 1.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/{index-BlA2n_X7.d.cts → index-ERam9OPy.d.cts} +84 -81
- package/dist/cjs/index.cjs +1 -1
- package/dist/cjs/index.cjs.map +1 -1
- package/dist/cjs/index.d.cts +7 -7
- package/dist/cjs/options/index.cjs +1 -1
- package/dist/cjs/options/index.cjs.map +1 -1
- package/dist/cjs/options/index.d.cts +9 -9
- package/dist/cjs/utils/index.d.cts +1 -1
- package/dist/esm/{chunk-BJB7GSNU.js → chunk-L7XLLBDP.js} +1 -1
- package/dist/esm/chunk-L7XLLBDP.js.map +1 -0
- package/dist/esm/chunk-YMYY7IIH.js +1 -0
- package/dist/esm/chunk-YMYY7IIH.js.map +1 -0
- package/dist/esm/{index-BlA2n_X7.d.ts → index-ERam9OPy.d.ts} +84 -81
- package/dist/esm/index.d.ts +7 -7
- package/dist/esm/index.js +1 -1
- package/dist/esm/options/index.d.ts +9 -9
- package/dist/esm/options/index.js +1 -1
- package/dist/esm/options/index.js.map +1 -1
- package/dist/esm/utils/index.d.ts +1 -1
- package/dist/esm/utils/index.js +1 -1
- package/package.json +3 -3
- package/dist/esm/chunk-ARVXNKNE.js +0 -1
- package/dist/esm/chunk-ARVXNKNE.js.map +0 -1
- package/dist/esm/chunk-BJB7GSNU.js.map +0 -1
|
@@ -63,44 +63,37 @@ type CommonRequestHeaders = "Access-Control-Allow-Credentials" | "Access-Control
|
|
|
63
63
|
type CommonAuthorizationHeaders = "Basic" | "Bearer" | "Token";
|
|
64
64
|
type CommonContentTypes = "application/epub+zip" | "application/gzip" | "application/json" | "application/ld+json" | "application/octet-stream" | "application/ogg" | "application/pdf" | "application/rtf" | "application/vnd.ms-fontobject" | "application/wasm" | "application/xhtml+xml" | "application/xml" | "application/zip" | "audio/aac" | "audio/mpeg" | "audio/ogg" | "audio/opus" | "audio/webm" | "audio/x-midi" | "font/otf" | "font/ttf" | "font/woff" | "font/woff2" | "image/avif" | "image/bmp" | "image/gif" | "image/jpeg" | "image/png" | "image/svg+xml" | "image/tiff" | "image/webp" | "image/x-icon" | "model/gltf-binary" | "model/gltf+json" | "text/calendar" | "text/css" | "text/csv" | "text/html" | "text/javascript" | "text/plain" | "video/3gpp" | "video/3gpp2" | "video/av1" | "video/mp2t" | "video/mp4" | "video/mpeg" | "video/ogg" | "video/webm" | "video/x-msvideo";
|
|
65
65
|
|
|
66
|
-
type
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
request: CallApiRequestOptionsForHooks;
|
|
66
|
+
type ToQueryStringFn = {
|
|
67
|
+
(params: CallApiConfig["query"]): string | null;
|
|
68
|
+
(params: Required<CallApiConfig>["query"]): string;
|
|
70
69
|
};
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
hooks?: InterceptorsOrInterceptorArray<TData, TErrorData>;
|
|
80
|
-
/**
|
|
81
|
-
* @description A unique id for the plugin
|
|
82
|
-
*/
|
|
83
|
-
id: string;
|
|
84
|
-
/**
|
|
85
|
-
* @description A function that will be called when the plugin is
|
|
86
|
-
* initialized. This will be called before the any
|
|
87
|
-
* of the other internal functions.
|
|
88
|
-
*/
|
|
89
|
-
init?: (context: PluginInitContext<TData, TErrorData>) => Awaitable<{
|
|
90
|
-
options?: CombinedCallApiExtraOptions<TData, TErrorData>;
|
|
91
|
-
request: CallApiRequestOptionsForHooks;
|
|
92
|
-
url?: string;
|
|
93
|
-
}> | Awaitable<void>;
|
|
94
|
-
/**
|
|
95
|
-
* @description A name for the plugin
|
|
96
|
-
*/
|
|
97
|
-
name: string;
|
|
98
|
-
/**
|
|
99
|
-
* @description A version for the plugin
|
|
100
|
-
*/
|
|
101
|
-
version?: string;
|
|
70
|
+
declare const toQueryString: ToQueryStringFn;
|
|
71
|
+
declare const getResponseType: <TResponse>(response: Response, parser?: Required<CallApiExtraOptions>["responseParser"]) => {
|
|
72
|
+
arrayBuffer: () => Promise<TResponse>;
|
|
73
|
+
blob: () => Promise<TResponse>;
|
|
74
|
+
formData: () => Promise<TResponse>;
|
|
75
|
+
json: () => Promise<Record<string, unknown> | TResponse>;
|
|
76
|
+
stream: () => ReadableStream<Uint8Array<ArrayBufferLike>> | null;
|
|
77
|
+
text: () => Promise<TResponse>;
|
|
102
78
|
};
|
|
103
|
-
|
|
79
|
+
type ErrorObjectUnion<TErrorData = unknown> = PossibleHTTPError<TErrorData> | PossibleJavaScriptError;
|
|
80
|
+
declare const isHTTPError: <TErrorData>(error: ErrorObjectUnion<TErrorData> | null) => error is PossibleHTTPError<TErrorData>;
|
|
81
|
+
type ErrorDetails<TErrorResponse> = {
|
|
82
|
+
defaultErrorMessage: string;
|
|
83
|
+
errorData: TErrorResponse;
|
|
84
|
+
response: Response;
|
|
85
|
+
};
|
|
86
|
+
type ErrorOptions = {
|
|
87
|
+
cause?: unknown;
|
|
88
|
+
};
|
|
89
|
+
declare class HTTPError<TErrorResponse = Record<string, unknown>> extends Error {
|
|
90
|
+
errorData: ErrorDetails<TErrorResponse>["errorData"];
|
|
91
|
+
isHTTPError: boolean;
|
|
92
|
+
name: "HTTPError";
|
|
93
|
+
response: ErrorDetails<TErrorResponse>["response"];
|
|
94
|
+
constructor(errorDetails: ErrorDetails<TErrorResponse>, errorOptions?: ErrorOptions);
|
|
95
|
+
}
|
|
96
|
+
declare const isHTTPErrorInstance: <TErrorResponse>(error: unknown) => error is HTTPError<TErrorResponse>;
|
|
104
97
|
|
|
105
98
|
type RetryCondition<TErrorData> = (context: ErrorContext<TErrorData>) => boolean | Promise<boolean>;
|
|
106
99
|
interface RetryOptions<TErrorData> {
|
|
@@ -144,37 +137,45 @@ interface RetryOptions<TErrorData> {
|
|
|
144
137
|
retryStrategy?: "exponential" | "linear";
|
|
145
138
|
}
|
|
146
139
|
|
|
147
|
-
type
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
declare const toQueryString: ToQueryStringFn;
|
|
152
|
-
declare const getResponseType: <TResponse>(response: Response, parser?: Required<CallApiExtraOptions>["responseParser"]) => {
|
|
153
|
-
arrayBuffer: () => Promise<TResponse>;
|
|
154
|
-
blob: () => Promise<TResponse>;
|
|
155
|
-
formData: () => Promise<TResponse>;
|
|
156
|
-
json: () => Promise<Record<string, unknown> | TResponse>;
|
|
157
|
-
stream: () => ReadableStream<Uint8Array<ArrayBufferLike>> | null;
|
|
158
|
-
text: () => Promise<TResponse>;
|
|
159
|
-
};
|
|
160
|
-
type ErrorObjectUnion<TErrorData = unknown> = PossibleHTTPError<TErrorData> | PossibleJavaScriptError;
|
|
161
|
-
declare const isHTTPError: <TErrorData>(error: ErrorObjectUnion<TErrorData> | null) => error is PossibleHTTPError<TErrorData>;
|
|
162
|
-
type ErrorDetails<TErrorResponse> = {
|
|
163
|
-
defaultErrorMessage: string;
|
|
164
|
-
errorData: TErrorResponse;
|
|
165
|
-
response: Response;
|
|
140
|
+
type PluginInitContext<TMoreOptions extends AnyObject = DefaultMoreOptions> = {
|
|
141
|
+
initURL: string;
|
|
142
|
+
options: CombinedCallApiExtraOptions & Partial<TMoreOptions>;
|
|
143
|
+
request: CallApiRequestOptionsForHooks;
|
|
166
144
|
};
|
|
167
|
-
type
|
|
168
|
-
|
|
145
|
+
type CreateExtraOptions<TMoreOptions> = (...params: never[]) => TMoreOptions;
|
|
146
|
+
type CallApiPlugin<TMoreOptions extends AnyObject = DefaultMoreOptions> = {
|
|
147
|
+
/**
|
|
148
|
+
* @description Defines additional options that can be passed to callApi
|
|
149
|
+
*/
|
|
150
|
+
createExtraOptions?: CreateExtraOptions<TMoreOptions>;
|
|
151
|
+
/**
|
|
152
|
+
* @description A description for the plugin
|
|
153
|
+
*/
|
|
154
|
+
description?: string;
|
|
155
|
+
/**
|
|
156
|
+
* Hooks / Interceptors for the plugin
|
|
157
|
+
*/
|
|
158
|
+
hooks?: InterceptorsOrInterceptorArray;
|
|
159
|
+
/**
|
|
160
|
+
* @description A unique id for the plugin
|
|
161
|
+
*/
|
|
162
|
+
id: string;
|
|
163
|
+
/**
|
|
164
|
+
* @description A function that will be called when the plugin is
|
|
165
|
+
* initialized. This will be called before the any
|
|
166
|
+
* of the other internal functions.
|
|
167
|
+
*/
|
|
168
|
+
init?: (context: PluginInitContext) => Awaitable<Partial<PluginInitContext>> | Awaitable<void>;
|
|
169
|
+
/**
|
|
170
|
+
* @description A name for the plugin
|
|
171
|
+
*/
|
|
172
|
+
name: string;
|
|
173
|
+
/**
|
|
174
|
+
* @description A version for the plugin
|
|
175
|
+
*/
|
|
176
|
+
version?: string;
|
|
169
177
|
};
|
|
170
|
-
declare
|
|
171
|
-
errorData: ErrorDetails<TErrorResponse>["errorData"];
|
|
172
|
-
isHTTPError: boolean;
|
|
173
|
-
name: "HTTPError";
|
|
174
|
-
response: ErrorDetails<TErrorResponse>["response"];
|
|
175
|
-
constructor(errorDetails: ErrorDetails<TErrorResponse>, errorOptions?: ErrorOptions);
|
|
176
|
-
}
|
|
177
|
-
declare const isHTTPErrorInstance: <TErrorResponse>(error: unknown) => error is HTTPError<TErrorResponse>;
|
|
178
|
+
declare const definePlugin: <TMoreOptions extends AnyObject = {}, TPlugin extends AnyFunction<CallApiPlugin<TMoreOptions>> | CallApiPlugin<TMoreOptions> = CallApiPlugin<TMoreOptions>>(plugin: TPlugin) => TPlugin;
|
|
178
179
|
|
|
179
180
|
declare const fetchSpecificKeys: ("body" | "cache" | "credentials" | "headers" | "integrity" | "keepalive" | "method" | "mode" | "priority" | "redirect" | "referrer" | "referrerPolicy" | "signal" | "window")[];
|
|
180
181
|
|
|
@@ -199,10 +200,8 @@ interface CallApiRequestOptionsForHooks extends CallApiRequestOptions {
|
|
|
199
200
|
}
|
|
200
201
|
interface Register {
|
|
201
202
|
}
|
|
202
|
-
type
|
|
203
|
-
|
|
204
|
-
} ? TMeta : never;
|
|
205
|
-
interface Interceptors<TData = unknown, TErrorData = unknown> {
|
|
203
|
+
type DefaultDataType = unknown;
|
|
204
|
+
interface Interceptors<TData = DefaultDataType, TErrorData = DefaultDataType> {
|
|
206
205
|
/**
|
|
207
206
|
* @description Interceptor that will be called when any error occurs within the request/response lifecyle, regardless of whether the error is from the api or not.
|
|
208
207
|
* It is basically a combination of `onRequestError` and `onResponseError` interceptors
|
|
@@ -233,12 +232,16 @@ interface Interceptors<TData = unknown, TErrorData = unknown> {
|
|
|
233
232
|
*/
|
|
234
233
|
onSuccess?: (context: SuccessContext<TData>) => Awaitable<unknown>;
|
|
235
234
|
}
|
|
236
|
-
type InterceptorsOrInterceptorArray<TData =
|
|
235
|
+
type InterceptorsOrInterceptorArray<TData = DefaultDataType, TErrorData = DefaultDataType> = {
|
|
237
236
|
[Key in keyof Interceptors<TData, TErrorData>]: Interceptors<TData, TErrorData>[Key] | Array<Interceptors<TData, TErrorData>[Key]>;
|
|
238
237
|
};
|
|
239
238
|
type FetchImpl = UnmaskType<(input: string | Request | URL, init?: RequestInit) => Promise<Response>>;
|
|
240
|
-
type CallApiPluginArray<
|
|
241
|
-
type
|
|
239
|
+
type CallApiPluginArray<TMoreOptions extends AnyObject> = Array<CallApiPlugin<TMoreOptions>>;
|
|
240
|
+
type DefaultMoreOptions = NonNullable<unknown>;
|
|
241
|
+
type Meta = Register extends {
|
|
242
|
+
meta?: infer TMeta extends Record<string, unknown>;
|
|
243
|
+
} ? TMeta : never;
|
|
244
|
+
type ExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends CallApiResultModeUnion = CallApiResultModeUnion, TMoreOptions extends AnyObject = DefaultMoreOptions> = InterceptorsOrInterceptorArray<TData, TErrorData> & Partial<TMoreOptions> & RetryOptions<TErrorData> & {
|
|
242
245
|
/**
|
|
243
246
|
* @description Authorization header value.
|
|
244
247
|
*/
|
|
@@ -330,7 +333,7 @@ type ExtraOptions<TData = unknown, TErrorData = unknown, TResultMode extends Cal
|
|
|
330
333
|
/**
|
|
331
334
|
* @description An array of CallApi plugins. It allows you to extend the behavior of the library.
|
|
332
335
|
*/
|
|
333
|
-
plugins?: CallApiPluginArray<
|
|
336
|
+
plugins?: CallApiPluginArray<TMoreOptions> | ((context: PluginInitContext) => CallApiPluginArray<TMoreOptions>);
|
|
334
337
|
/**
|
|
335
338
|
* @description Query parameters to append to the URL.
|
|
336
339
|
*/
|
|
@@ -371,18 +374,18 @@ type ExtraOptions<TData = unknown, TErrorData = unknown, TResultMode extends Cal
|
|
|
371
374
|
timeout?: number;
|
|
372
375
|
};
|
|
373
376
|
declare const optionsEnumToExtendFromBase: "plugins"[];
|
|
374
|
-
type CallApiExtraOptions<TData =
|
|
377
|
+
type CallApiExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends CallApiResultModeUnion = CallApiResultModeUnion, TMoreOptions extends AnyObject = DefaultMoreOptions> = ExtraOptions<TData, TErrorData, TResultMode, TMoreOptions> & {
|
|
375
378
|
/**
|
|
376
379
|
* @description Options that should extend the base options.
|
|
377
380
|
*/
|
|
378
381
|
extend?: Pick<ExtraOptions<TData, TErrorData, TResultMode, TMoreOptions>, (typeof optionsEnumToExtendFromBase)[number]>;
|
|
379
382
|
};
|
|
380
383
|
declare const optionsEnumToOmitFromBase: ("dedupeKey" | "extend")[];
|
|
381
|
-
type BaseCallApiExtraOptions<TBaseData =
|
|
382
|
-
type CombinedCallApiExtraOptions<TData =
|
|
383
|
-
type CallApiConfig<TData =
|
|
384
|
-
type BaseCallApiConfig<TBaseData =
|
|
385
|
-
type CallApiParameters<TData =
|
|
384
|
+
type BaseCallApiExtraOptions<TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends CallApiResultModeUnion = CallApiResultModeUnion, TMoreOptions extends AnyObject = DefaultMoreOptions> = Omit<CallApiExtraOptions<TBaseData, TBaseErrorData, TBaseResultMode, TMoreOptions>, (typeof optionsEnumToOmitFromBase)[number]>;
|
|
385
|
+
type CombinedCallApiExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends CallApiResultModeUnion = CallApiResultModeUnion, TMoreOptions extends AnyObject = DefaultMoreOptions> = BaseCallApiExtraOptions<TData, TErrorData, TResultMode, TMoreOptions> & CallApiExtraOptions<TData, TErrorData, TResultMode, TMoreOptions>;
|
|
386
|
+
type CallApiConfig<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends CallApiResultModeUnion = CallApiResultModeUnion, TMoreOptions extends AnyObject = DefaultMoreOptions> = CallApiExtraOptions<TData, TErrorData, TResultMode, TMoreOptions> & CallApiRequestOptions;
|
|
387
|
+
type BaseCallApiConfig<TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends CallApiResultModeUnion = CallApiResultModeUnion, TBaseMoreOptions extends AnyObject = DefaultMoreOptions> = BaseCallApiExtraOptions<TBaseData, TBaseErrorData, TBaseResultMode, TBaseMoreOptions> & CallApiRequestOptions;
|
|
388
|
+
type CallApiParameters<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends CallApiResultModeUnion = CallApiResultModeUnion, TMoreOptions extends AnyObject = DefaultMoreOptions> = [initURL: string, config?: CallApiConfig<TData, TErrorData, TResultMode, TMoreOptions>];
|
|
386
389
|
type RequestContext = UnmaskType<{
|
|
387
390
|
options: CombinedCallApiExtraOptions;
|
|
388
391
|
request: CallApiRequestOptionsForHooks;
|
|
@@ -453,7 +456,7 @@ type CallApiResultErrorVariant<TErrorData> = {
|
|
|
453
456
|
error: PossibleJavaScriptError;
|
|
454
457
|
response: null;
|
|
455
458
|
};
|
|
456
|
-
type ResultModeMap<TData =
|
|
459
|
+
type ResultModeMap<TData = DefaultDataType, TErrorData = DefaultDataType> = {
|
|
457
460
|
all: CallApiResultSuccessVariant<TData> | CallApiResultErrorVariant<TErrorData>;
|
|
458
461
|
onlyError: CallApiResultErrorVariant<TErrorData>["error"] | CallApiResultSuccessVariant<TData>["error"];
|
|
459
462
|
onlyResponse: CallApiResultErrorVariant<TErrorData>["response"] | CallApiResultSuccessVariant<TData>["response"];
|
|
@@ -465,4 +468,4 @@ type CallApiResultModeUnion = {
|
|
|
465
468
|
}[keyof ResultModeMap] | undefined;
|
|
466
469
|
type GetCallApiResult<TData, TErrorData, TResultMode> = TErrorData extends false ? ResultModeMap<TData, TErrorData>["onlySuccessWithException"] : undefined extends TResultMode ? ResultModeMap<TData, TErrorData>["all"] : TResultMode extends NonNullable<CallApiResultModeUnion> ? ResultModeMap<TData, TErrorData>[TResultMode] : never;
|
|
467
470
|
|
|
468
|
-
export { type BaseCallApiConfig as B, type CallApiResultModeUnion as C, type ErrorContext as E, type GetCallApiResult as G, HTTPError as H, type PluginInitContext as P, type Register as R, type SuccessContext as S, type CallApiConfig as a, type CallApiPlugin as b, type BaseCallApiExtraOptions as c, definePlugin as d, type CallApiExtraOptions as e, type
|
|
471
|
+
export { type AnyObject as A, type BaseCallApiConfig as B, type CallApiResultModeUnion as C, type DefaultDataType as D, type ErrorContext as E, type GetCallApiResult as G, HTTPError as H, type Interceptors as I, type PluginInitContext as P, type Register as R, type SuccessContext as S, type CallApiConfig as a, type CallApiPlugin as b, type BaseCallApiExtraOptions as c, definePlugin as d, type CallApiExtraOptions as e, type PossibleJavaScriptError as f, type PossibleHTTPError as g, type CallApiParameters as h, type CallApiRequestOptions as i, type CallApiRequestOptionsForHooks as j, type CallApiResultErrorVariant as k, type CallApiResultSuccessVariant as l, type CombinedCallApiExtraOptions as m, type InterceptorsOrInterceptorArray as n, type PossibleJavascriptErrorNames as o, type RequestContext as p, type RequestErrorContext as q, type ResponseContext as r, type ResponseErrorContext as s, type DefaultMoreOptions as t, isHTTPError as u, isHTTPErrorInstance as v, toQueryString as w };
|
package/dist/cjs/index.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e,r=Object.defineProperty,t=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,n={};((e,t)=>{for(var o in t)r(e,o,{get:t[o],enumerable:!0})})(n,{callApi:()=>H,createFetchClient:()=>A,definePlugin:()=>j}),module.exports=(e=n,((e,n,a,i)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let l of o(n))s.call(e,l)||l===a||r(e,l,{get:()=>n[l],enumerable:!(i=t(n,l))||i.enumerable});return e})(r({},"__esModule",{value:!0}),e));var a=e=>Array.isArray(e),i=e=>{if(!(e=>"object"==typeof e&&null!==e)(e))return!1;const r=Object.getPrototypeOf(e);return(null==r||r===Object.prototype||null===Object.getPrototypeOf(r))&&!(Symbol.toStringTag in e)},l=e=>"function"==typeof e,u=e=>"string"==typeof e,c=e=>l(e)?e():e,p=e=>{if(void 0!==e){if(u(e)||null===e)return{Authorization:`Bearer ${e}`};switch(e.type){case"Basic":{const r=c(e.username),t=c(e.password);if(void 0===r||void 0===t)return;return{Authorization:`Basic ${globalThis.btoa(`${r}:${t}`)}`}}case"Custom":{const r=c(e.value);if(void 0===r)return;return{Authorization:`${c(e.prefix)} ${r}`}}default:{const r=c(e.bearer),t=c(e.token);return"token"in e&&void 0!==t?{Authorization:`Token ${t}`}:void 0!==r&&{Authorization:`Bearer ${r}`}}}}},d=["extend","dedupeKey"],f=["body","integrity","method","headers","signal","cache","redirect","window","credentials","keepalive","referrer","priority","mode","referrerPolicy"],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"},m=["GET","POST"],g=Object.keys(y).map(Number),w=(e,r)=>{const t={},o=new Set(r);for(const[r,s]of Object.entries(e))o.has(r)||(t[r]=s);return t},h=(e,r)=>{const t={},o=new Set(r);for(const[r,s]of Object.entries(e))o.has(r)&&(t[r]=s);return t},b=e=>!e||i(e)?e:Object.fromEntries(e),E=e=>{const{auth:r,baseHeaders:t,body:o,headers:s}=e;if(!Boolean(t||s||o||r))return;const n={...p(r),...b(t),...b(s)};return u(a=o)&&a.includes("=")?(n["Content-Type"]="application/x-www-form-urlencoded",n):((i(o)||u(o)&&o.startsWith("{"))&&(n["Content-Type"]="application/json",n.Accept="application/json"),n);var a},
|
|
1
|
+
"use strict";var e,r=Object.defineProperty,t=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,n={};((e,t)=>{for(var o in t)r(e,o,{get:t[o],enumerable:!0})})(n,{callApi:()=>H,createFetchClient:()=>A,definePlugin:()=>j}),module.exports=(e=n,((e,n,a,i)=>{if(n&&"object"==typeof n||"function"==typeof n)for(let l of o(n))s.call(e,l)||l===a||r(e,l,{get:()=>n[l],enumerable:!(i=t(n,l))||i.enumerable});return e})(r({},"__esModule",{value:!0}),e));var a=e=>Array.isArray(e),i=e=>{if(!(e=>"object"==typeof e&&null!==e)(e))return!1;const r=Object.getPrototypeOf(e);return(null==r||r===Object.prototype||null===Object.getPrototypeOf(r))&&!(Symbol.toStringTag in e)},l=e=>"function"==typeof e,u=e=>"string"==typeof e,c=e=>l(e)?e():e,p=e=>{if(void 0!==e){if(u(e)||null===e)return{Authorization:`Bearer ${e}`};switch(e.type){case"Basic":{const r=c(e.username),t=c(e.password);if(void 0===r||void 0===t)return;return{Authorization:`Basic ${globalThis.btoa(`${r}:${t}`)}`}}case"Custom":{const r=c(e.value);if(void 0===r)return;return{Authorization:`${c(e.prefix)} ${r}`}}default:{const r=c(e.bearer),t=c(e.token);return"token"in e&&void 0!==t?{Authorization:`Token ${t}`}:void 0!==r&&{Authorization:`Bearer ${r}`}}}}},d=["extend","dedupeKey"],f=["body","integrity","method","headers","signal","cache","redirect","window","credentials","keepalive","referrer","priority","mode","referrerPolicy"],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"},m=["GET","POST"],g=Object.keys(y).map(Number),w=(e,r)=>{const t={},o=new Set(r);for(const[r,s]of Object.entries(e))o.has(r)||(t[r]=s);return t},h=(e,r)=>{const t={},o=new Set(r);for(const[r,s]of Object.entries(e))o.has(r)&&(t[r]=s);return t},b=e=>!e||i(e)?e:Object.fromEntries(e),E=e=>{const{auth:r,baseHeaders:t,body:o,headers:s}=e;if(!Boolean(t||s||o||r))return;const n={...p(r),...b(t),...b(s)};return u(a=o)&&a.includes("=")?(n["Content-Type"]="application/x-www-form-urlencoded",n):((i(o)||u(o)&&o.startsWith("{"))&&(n["Content-Type"]="application/json",n.Accept="application/json"),n);var a},R=(...e)=>Promise.all(e),S=async(e,r,t,o)=>{const s=((e,r)=>({arrayBuffer:()=>e.arrayBuffer(),blob:()=>e.blob(),formData:()=>e.formData(),json:async()=>{if(r){const t=await e.text();return r(t)}return e.json()},stream:()=>e.body,text:()=>e.text()}))(e,t);if(!Object.hasOwn(s,r))throw new Error(`Invalid response type: ${r}`);const n=await s[r]();return o?o(n):n},O=e=>{const{defaultErrorMessage:r,error:t,message:o,resultMode:s}=e;let n={data:null,error:{errorData:t,message:o??t.message,name:t.name},response:null};if(v(t)){const{errorData:e,message:o=r,name:s,response:a}=t;n={data:null,error:{errorData:e,message:o,name:s},response:a}}return{apiDetails:n,generalErrorResult:{all:n,onlyError:n.error,onlyResponse:n.response,onlySuccess:n.data,onlySuccessWithException:n.data}[s??"all"],resolveCustomErrorInfo:({message:r})=>O({...e,message:r}).generalErrorResult}},q=class extends Error{errorData;isHTTPError=!0;name="HTTPError";response;constructor(e,r){const{defaultErrorMessage:t,errorData:o,response:s}=e;super(o?.message??t,r),this.errorData=o,this.response=s,Error.captureStackTrace(this,this.constructor)}},v=e=>e instanceof q||i(e)&&"HTTPError"===e.name&&!0===e.isHTTPError,T=e=>{if(0===e)return;const{promise:r,resolve:t}=(()=>{let e,r;return{promise:new Promise(((t,o)=>{r=t,e=o})),reject:e,resolve:r}})();return setTimeout(t,e),r},M=(e,r,t,o)=>{const s=(e=>{if(e)return e;if("undefined"!=typeof globalThis&&l(globalThis.fetch))return globalThis.fetch;throw new Error("No fetch implementation found")})(r.customFetchImpl);return o&&"defer"===r.dedupeStrategy?o.responsePromise:s(e,t)},j=e=>e,P=(e,r)=>async t=>{if("sequential"!==r){if("parallel"===r){const r=[...e];await Promise.all(r.map((e=>e?.(t))))}}else for(const r of e)await(r?.(t))},$={onError:new Set,onRequest:new Set,onRequestError:new Set,onResponse:new Set,onResponseError:new Set,onRetry:new Set,onSuccess:new Set},k=(e,r)=>{const t=e.retryCount??0;return{getDelay:()=>"exponential"===e.retryStrategy?((e,r)=>{const t=r.retryMaxDelay??1e4,o=(r.retryDelay??1e3)*2**e;return Math.min(o,t)})(t,e):(e=>e.retryDelay??1e3)(e),shouldAttemptRetry:async()=>{const o=await(e.retryCondition?.(r))??!0,s=(e.retryAttempts??0)>t&&o;if("HTTPError"!==r.error.name)return s;const n=!!r.request.method&&e.retryMethods?.includes(r.request.method);return!!r.response?.status&&e.retryStatusCodes?.includes(r.response.status)&&n&&s}}},D=(e,r)=>{if(!r)return e;const t=(o=r)?new URLSearchParams(o).toString():(console.error("toQueryString:","No query params provided!"),null);var o;return 0===t?.length?e:e.endsWith("?")?`${e}${t}`:e.includes("?")?`${e}&${t}`:`${e}?${t}`},x=(e,r,t)=>{const o=((e,r)=>{if(!r)return e;let t=e;if(a(r)){const e=t.split("/").filter((e=>e.startsWith(":")));for(const[o,s]of e.entries()){const e=r[o];t=t.replace(s,e)}return t}for(const[e,o]of Object.entries(r))t=t.replace(`:${e}`,String(o));return t})(e,r);return D(o,t)},A=(e={})=>{const[r,t]=(e=>[h(e,f),w(e,[...f,...d])])(e),{body:o,headers:s,signal:n,...c}=r,p=new Map,y=async(...e)=>{const[r,d={}]=e,[b,j]=(e=>[h(e,f),w(e,f)])(d),{body:D=o,headers:A,signal:H=n,...C}=b,U={};for(const e of Object.keys($)){const r=(L=t[e],B=j[e],a(L)?[L,B].flat():B??L);U[e]=r}var L,B;const z={baseURL:"",bodySerializer:JSON.stringify,dedupeStrategy:"cancel",defaultErrorMessage:"Failed to fetch data from server!",mergedHooksExecutionMode:"parallel",mergedHooksExecutionOrder:"mainHooksAfterPlugins",responseType:"json",resultMode:"all",retryAttempts:0,retryDelay:1e3,retryMaxDelay:1e4,retryMethods:m,retryStatusCodes:g,retryStrategy:"linear",...t,...j,...U},{resolvedHooks:N,resolvedOptions:I,resolvedRequestOptions:W,url:G}=await(async e=>{const{initURL:r,options:t,request:o}=e,s=structuredClone($),n=()=>{for(const e of Object.keys($)){const r=t[e];s[e].add(r)}},a=e=>{for(const r of Object.keys($)){const t=e[r];s[r].add(t)}};"mainHooksBeforePlugins"===t.mergedHooksExecutionOrder&&n();const c=e=>e?l(e)?e({initURL:r,options:t,request:o}):e:[],p=[...c(t.plugins),...c(t.extend?.plugins)];let d=r,f=t,y=o;const m=async e=>{if(!e)return;const s=await e({initURL:r,options:t,request:o});i(s)&&(u(s.initURL)&&(d=s.initURL),i(s.request)&&(y=s.request),i(s.options)&&(f=s.options))};for(const e of p)await m(e.init),e.hooks&&a(e.hooks);t.mergedHooksExecutionOrder&&"mainHooksAfterPlugins"!==t.mergedHooksExecutionOrder||n();const g={};for(const[e,r]of Object.entries(s)){const o=[...r].flat(),s=P(o,t.mergedHooksExecutionMode);g[e]=s}return{resolvedHooks:g,resolvedOptions:f,resolvedRequestOptions:y,url:d}})({initURL:r,options:z,request:{...c,...C}}),K=`${I.baseURL}${x(G,I.params,I.query)}`,F={...I,...N,fullURL:K,initURL:r},J={body:i(D)?F.bodySerializer(D):D,method:"GET",...W},V=new AbortController,_=null!=F.timeout?(Q=F.timeout,AbortSignal.timeout(Q)):null;var Q;const X=((...e)=>AbortSignal.any(e.filter(Boolean)))(V.signal,_,H),Y={signal:X,...J},Z=F.dedupeKey??((e,r,t)=>"cancel"===t.dedupeStrategy||"defer"===t.dedupeStrategy?`${t.fullURL}-${JSON.stringify({options:t,request:r})}`:null)(0,Y,F);null!==Z&&await T(.1);const ee=null!==Z?p:null,re=ee?.get(Z);((e,r,t)=>{if(t&&"cancel"===r.dedupeStrategy){const e=r.dedupeKey?`Duplicate request detected - Aborting previous request with key '${r.dedupeKey}' as a new request was initiated`:`Duplicate request detected - Aborting previous request to '${r.fullURL}' as a new request with identical options was initiated`,o=new DOMException(e,"AbortError");t.controller.abort(o)}})(0,F,re);try{await R(F.onRequest({options:F,request:Y})),Y.headers=E({auth:F.auth,baseHeaders:s??A,body:D,headers:Y.headers});const e=M(K,F,Y,re);ee?.set(Z,{controller:V,responsePromise:e});const r=await e,t="defer"===F.dedupeStrategy||F.cloneResponse;if(!r.ok){const e=await S(t?r.clone():r,F.responseType,F.responseParser,F.responseErrorValidator);throw new q({defaultErrorMessage:F.defaultErrorMessage,errorData:e,response:r})}const o=await S(t?r.clone():r,F.responseType,F.responseParser,F.responseValidator);return await R(F.onSuccess({data:o,options:F,request:Y,response:F.cloneResponse?r.clone():r}),F.onResponse({data:o,error:null,options:F,request:Y,response:F.cloneResponse?r.clone():r})),await(e=>{const{data:r,response:t,resultMode:o}=e,s={data:r,error:null,response:t};return o?{all:s,onlyError:s.error,onlyResponse:s.response,onlySuccess:s.data,onlySuccessWithException:s.data}[o]:s})({data:o,response:r,resultMode:F.resultMode})}catch(e){const{apiDetails:t,generalErrorResult:o,resolveCustomErrorInfo:s}=O({defaultErrorMessage:F.defaultErrorMessage,error:e,resultMode:F.resultMode}),n={error:t.error,options:F,request:Y,response:t.response},{getDelay:a,shouldAttemptRetry:i}=k(F,n);if(!X.aborted&&await i()){await R(F.onRetry(n));const e=a();await T(e);const t={...d,retryCount:(F.retryCount??0)+1};return await y(r,t)}const u=l(F.throwOnError)?F.throwOnError(n):F.throwOnError,c=()=>{if(u)throw t.error};if(v(e)){const{response:r}=e,t=o.error;return await R(F.onResponseError({error:t,options:F,request:Y,response:F.cloneResponse?r.clone():r}),F.onError({error:t,options:F,request:Y,response:F.cloneResponse?r.clone():r}),F.onResponse({data:null,error:t,options:F,request:Y,response:F.cloneResponse?r.clone():r})),c(),o}if(e instanceof DOMException&&"AbortError"===e.name){const{message:r,name:t}=e;return console.error(`${t}:`,r),c(),o}if(e instanceof DOMException&&"TimeoutError"===e.name){const r=`Request timed out after ${F.timeout}ms`;return console.error(`${e.name}:`,r),c(),s({message:r})}const p=o.error;return await R(F.onRequestError({error:p,options:F,request:Y}),F.onError({error:p,options:F,request:Y,response:null})),c(),o}finally{ee?.delete(Z)}};return y.create=A,y},H=A();//# sourceMappingURL=index.cjs.map
|