@zayne-labs/callapi 1.7.18 → 1.8.1

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,774 +0,0 @@
1
- type AnyString = string & {
2
- z_placeholder?: never;
3
- };
4
- type AnyFunction<TResult = unknown> = (...args: any[]) => TResult;
5
- type Prettify<TObject> = NonNullable<unknown> & {
6
- [Key in keyof TObject]: TObject[Key];
7
- };
8
- type UnmaskType<TValue> = {
9
- _: TValue;
10
- }["_"];
11
- type Awaitable<TValue> = Promise<TValue> | TValue;
12
- type CommonRequestHeaders = "Access-Control-Allow-Credentials" | "Access-Control-Allow-Headers" | "Access-Control-Allow-Methods" | "Access-Control-Allow-Origin" | "Access-Control-Expose-Headers" | "Access-Control-Max-Age" | "Age" | "Allow" | "Cache-Control" | "Clear-Site-Data" | "Content-Disposition" | "Content-Encoding" | "Content-Language" | "Content-Length" | "Content-Location" | "Content-Range" | "Content-Security-Policy-Report-Only" | "Content-Security-Policy" | "Cookie" | "Cross-Origin-Embedder-Policy" | "Cross-Origin-Opener-Policy" | "Cross-Origin-Resource-Policy" | "Date" | "ETag" | "Expires" | "Last-Modified" | "Location" | "Permissions-Policy" | "Pragma" | "Retry-After" | "Save-Data" | "Sec-CH-Prefers-Color-Scheme" | "Sec-CH-Prefers-Reduced-Motion" | "Sec-CH-UA-Arch" | "Sec-CH-UA-Bitness" | "Sec-CH-UA-Form-Factor" | "Sec-CH-UA-Full-Version-List" | "Sec-CH-UA-Full-Version" | "Sec-CH-UA-Mobile" | "Sec-CH-UA-Model" | "Sec-CH-UA-Platform-Version" | "Sec-CH-UA-Platform" | "Sec-CH-UA-WoW64" | "Sec-CH-UA" | "Sec-Fetch-Dest" | "Sec-Fetch-Mode" | "Sec-Fetch-Site" | "Sec-Fetch-User" | "Sec-GPC" | "Server-Timing" | "Server" | "Service-Worker-Navigation-Preload" | "Set-Cookie" | "Strict-Transport-Security" | "Timing-Allow-Origin" | "Trailer" | "Transfer-Encoding" | "Upgrade" | "Vary" | "Warning" | "WWW-Authenticate" | "X-Content-Type-Options" | "X-DNS-Prefetch-Control" | "X-Frame-Options" | "X-Permitted-Cross-Domain-Policies" | "X-Powered-By" | "X-Robots-Tag" | "X-XSS-Protection" | AnyString;
13
- type CommonAuthorizationHeaders = `${"Basic" | "Bearer" | "Token"} ${string}`;
14
- 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" | AnyString;
15
-
16
- type ValueOrFunctionResult<TValue> = TValue | (() => TValue);
17
- type ValidAuthValue = ValueOrFunctionResult<Awaitable<string | null | undefined>>;
18
- /**
19
- * Bearer Or Token authentication
20
- *
21
- * The value of `bearer` will be added to a header as
22
- * `auth: Bearer some-auth-token`,
23
- *
24
- * The value of `token` will be added to a header as
25
- * `auth: Token some-auth-token`,
26
- */
27
- type BearerOrTokenAuth = {
28
- type?: "Bearer";
29
- bearer?: ValidAuthValue;
30
- token?: never;
31
- } | {
32
- type?: "Token";
33
- bearer?: never;
34
- token?: ValidAuthValue;
35
- };
36
- /**
37
- * Basic auth
38
- */
39
- type BasicAuth = {
40
- type: "Basic";
41
- username: ValidAuthValue;
42
- password: ValidAuthValue;
43
- };
44
- /**
45
- * Custom auth
46
- *
47
- * @param prefix - prefix of the header
48
- * @param authValue - value of the header
49
- *
50
- * @example
51
- * ```ts
52
- * {
53
- * type: "Custom",
54
- * prefix: "Token",
55
- * authValue: "token"
56
- * }
57
- * ```
58
- */
59
- type CustomAuth = {
60
- type: "Custom";
61
- prefix: ValidAuthValue;
62
- value: ValidAuthValue;
63
- };
64
- type Auth = BearerOrTokenAuth | BasicAuth | CustomAuth;
65
-
66
- declare const fetchSpecificKeys: (keyof RequestInit | "duplex")[];
67
-
68
- type ErrorDetails<TErrorData> = {
69
- defaultErrorMessage: CallApiExtraOptions["defaultErrorMessage"];
70
- errorData: TErrorData;
71
- response: Response;
72
- };
73
- declare class HTTPError<TErrorData = Record<string, unknown>> extends Error {
74
- errorData: ErrorDetails<TErrorData>["errorData"];
75
- httpErrorSymbol: symbol;
76
- isHTTPError: boolean;
77
- name: "HTTPError";
78
- response: ErrorDetails<TErrorData>["response"];
79
- constructor(errorDetails: ErrorDetails<TErrorData>, errorOptions?: ErrorOptions);
80
- /**
81
- * @description Checks if the given error is an instance of HTTPError
82
- * @param error - The error to check
83
- * @returns true if the error is an instance of HTTPError, false otherwise
84
- */
85
- static isError<TErrorData>(error: unknown): error is HTTPError<TErrorData>;
86
- }
87
-
88
- /**
89
- * The Standard Schema interface.
90
- * @see https://github.com/standard-schema/standard-schema
91
- */
92
- interface StandardSchemaV1<Input = unknown, Output = Input> {
93
- /**
94
- * The Standard Schema properties.
95
- */
96
- readonly "~standard": StandardSchemaV1.Props<Input, Output>;
97
- }
98
- declare namespace StandardSchemaV1 {
99
- /**
100
- * The Standard Schema properties interface.
101
- */
102
- interface Props<Input = unknown, Output = Input> {
103
- /**
104
- * Inferred types associated with the schema.
105
- */
106
- readonly types?: Types<Input, Output> | undefined;
107
- /**
108
- * Validates unknown input values.
109
- */
110
- readonly validate: (value: unknown) => Promise<Result<Output>> | Result<Output>;
111
- /**
112
- * The vendor name of the schema library.
113
- */
114
- readonly vendor: string;
115
- /**
116
- * The version number of the standard.
117
- */
118
- readonly version: 1;
119
- }
120
- /**
121
- * The result interface of the validate function.
122
- */
123
- type Result<Output> = FailureResult | SuccessResult<Output>;
124
- /**
125
- * The result interface if validation succeeds.
126
- */
127
- interface SuccessResult<Output> {
128
- /**
129
- * The non-existent issues.
130
- */
131
- readonly issues?: undefined;
132
- /**
133
- * The typed output value.
134
- */
135
- readonly value: Output;
136
- }
137
- /**
138
- * The result interface if validation fails.
139
- */
140
- interface FailureResult {
141
- /**
142
- * The issues of failed validation.
143
- */
144
- readonly issues: readonly Issue[];
145
- }
146
- /**
147
- * The issue interface of the failure output.
148
- */
149
- interface Issue {
150
- /**
151
- * The error message of the issue.
152
- */
153
- readonly message: string;
154
- /**
155
- * The path of the issue, if any.
156
- */
157
- readonly path?: ReadonlyArray<PathSegment | PropertyKey> | undefined;
158
- }
159
- /**
160
- * The path segment interface of the issue.
161
- */
162
- interface PathSegment {
163
- /**
164
- * The key representing a path segment.
165
- */
166
- readonly key: PropertyKey;
167
- }
168
- /**
169
- * The Standard Schema types interface.
170
- */
171
- interface Types<Input = unknown, Output = Input> {
172
- /** The input type of the schema. */
173
- readonly input: Input;
174
- /** The output type of the schema. */
175
- readonly output: Output;
176
- }
177
- /**
178
- * Infers the input type of a Standard Schema.
179
- */
180
- type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["input"];
181
- /**
182
- * Infers the output type of a Standard Schema.
183
- */
184
- type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];
185
- }
186
-
187
- interface CallApiSchemas {
188
- /**
189
- * The schema to use for validating the request body.
190
- */
191
- body?: StandardSchemaV1<Body>;
192
- /**
193
- * The schema to use for validating the response data.
194
- */
195
- data?: StandardSchemaV1;
196
- /**
197
- * The schema to use for validating the response error data.
198
- */
199
- errorData?: StandardSchemaV1;
200
- /**
201
- * The schema to use for validating the request headers.
202
- */
203
- headers?: StandardSchemaV1<Headers>;
204
- /**
205
- * The schema to use for validating the request url.
206
- */
207
- initURL?: StandardSchemaV1<InitURL>;
208
- /**
209
- * The schema to use for validating the meta option.
210
- */
211
- meta?: StandardSchemaV1<GlobalMeta>;
212
- /**
213
- * The schema to use for validating the request method.
214
- */
215
- method?: StandardSchemaV1<Method>;
216
- /**
217
- * The schema to use for validating the request url parameter.
218
- */
219
- params?: StandardSchemaV1<Params>;
220
- /**
221
- * The schema to use for validating the request url querys.
222
- */
223
- query?: StandardSchemaV1<Query>;
224
- }
225
- interface CallApiValidators<TData = unknown, TErrorData = unknown> {
226
- /**
227
- * Custom function to validate the response data.
228
- */
229
- data?: (value: unknown) => TData;
230
- /**
231
- * Custom function to validate the response error data, stemming from the api.
232
- * This only runs if the api actually sends back error status codes, else it will be ignored, in which case you should only use the `responseValidator` option.
233
- */
234
- errorData?: (value: unknown) => TErrorData;
235
- }
236
- type InferSchemaResult<TSchema, TData = NonNullable<unknown>> = TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TSchema> : TData;
237
-
238
- type Params = UnmaskType<Record<string, boolean | number | string> | Array<boolean | number | string>>;
239
- type Query = UnmaskType<Record<string, boolean | number | string>>;
240
- type InitURL = UnmaskType<string | URL>;
241
- interface UrlOptions<TSchemas extends CallApiSchemas> {
242
- /**
243
- * URL to be used in the request.
244
- */
245
- readonly initURL?: string;
246
- /**
247
- * Parameters to be appended to the URL (i.e: /:id)
248
- */
249
- params?: InferSchemaResult<TSchemas["params"], Params>;
250
- /**
251
- * Query parameters to append to the URL.
252
- */
253
- query?: InferSchemaResult<TSchemas["query"], Query>;
254
- }
255
-
256
- type UnionToIntersection<TUnion> = (TUnion extends unknown ? (param: TUnion) => void : never) extends (param: infer TParam) => void ? TParam : never;
257
- type InferPluginOptions<TPluginArray extends CallApiPlugin[]> = UnionToIntersection<TPluginArray extends Array<infer TPlugin> ? TPlugin extends CallApiPlugin ? TPlugin["createExtraOptions"] extends AnyFunction<infer TResult> ? InferSchemaResult<TResult, TResult> : NonNullable<unknown> : NonNullable<unknown> : NonNullable<unknown>>;
258
- type PluginInitContext<TMoreOptions = DefaultMoreOptions> = Prettify<SharedHookContext<TMoreOptions> & {
259
- initURL: InitURL | undefined;
260
- }>;
261
- type PluginInitResult = Partial<Omit<PluginInitContext, "request"> & {
262
- request: CallApiRequestOptions;
263
- }>;
264
- type PluginHooksWithMoreOptions<TMoreOptions = DefaultMoreOptions> = HooksOrHooksArray<never, never, TMoreOptions>;
265
- type PluginHooks<TData = never, TErrorData = never, TMoreOptions = DefaultMoreOptions> = HooksOrHooksArray<TData, TErrorData, TMoreOptions>;
266
- interface CallApiPlugin {
267
- /**
268
- * Defines additional options that can be passed to callApi
269
- */
270
- createExtraOptions?: (...params: never[]) => unknown;
271
- /**
272
- * A description for the plugin
273
- */
274
- description?: string;
275
- /**
276
- * Hooks / Interceptors for the plugin
277
- */
278
- hooks?: PluginHooks;
279
- /**
280
- * A unique id for the plugin
281
- */
282
- id: string;
283
- /**
284
- * A function that will be called when the plugin is initialized. This will be called before the any of the other internal functions.
285
- */
286
- init?: (context: PluginInitContext) => Awaitable<PluginInitResult> | Awaitable<void>;
287
- /**
288
- * A name for the plugin
289
- */
290
- name: string;
291
- /**
292
- * A version for the plugin
293
- */
294
- version?: string;
295
- }
296
- declare const definePlugin: <TPlugin extends CallApiPlugin | AnyFunction<CallApiPlugin>>(plugin: TPlugin) => TPlugin;
297
- type Plugins<TPluginArray extends CallApiPlugin[]> = TPluginArray;
298
-
299
- type DefaultDataType = unknown;
300
- type DefaultMoreOptions = NonNullable<unknown>;
301
- type DefaultPluginArray = CallApiPlugin[];
302
- type DefaultThrowOnError = boolean;
303
-
304
- type Parser = (responseString: string) => Awaitable<Record<string, unknown>>;
305
- declare const getResponseType: <TResponse>(response: Response, parser: Parser) => {
306
- arrayBuffer: () => Promise<ArrayBuffer>;
307
- blob: () => Promise<Blob>;
308
- formData: () => Promise<FormData>;
309
- json: () => Promise<TResponse>;
310
- stream: () => ReadableStream<Uint8Array<ArrayBufferLike>> | null;
311
- text: () => Promise<string>;
312
- };
313
- type InitResponseTypeMap<TResponse = unknown> = ReturnType<typeof getResponseType<TResponse>>;
314
- type ResponseTypeUnion = keyof InitResponseTypeMap | null;
315
- type ResponseTypeMap<TResponse> = {
316
- [Key in keyof InitResponseTypeMap<TResponse>]: Awaited<ReturnType<InitResponseTypeMap<TResponse>[Key]>>;
317
- };
318
- type GetResponseType<TResponse, TResponseType extends ResponseTypeUnion, TComputedResponseTypeMap extends ResponseTypeMap<TResponse> = ResponseTypeMap<TResponse>> = null extends TResponseType ? TComputedResponseTypeMap["json"] : TResponseType extends NonNullable<ResponseTypeUnion> ? TComputedResponseTypeMap[TResponseType] : never;
319
- type CallApiResultSuccessVariant<TData> = {
320
- data: TData;
321
- error: null;
322
- response: Response;
323
- };
324
- type PossibleJavaScriptError = UnmaskType<{
325
- errorData: PossibleJavaScriptError["originalError"];
326
- message: string;
327
- name: "AbortError" | "Error" | "SyntaxError" | "TimeoutError" | "TypeError" | (`${string}Error` & {});
328
- originalError: DOMException | Error | SyntaxError | TypeError;
329
- }>;
330
- type PossibleHTTPError<TErrorData> = Prettify<UnmaskType<{
331
- errorData: TErrorData;
332
- message: string;
333
- name: "HTTPError";
334
- originalError: HTTPError;
335
- }>>;
336
- type CallApiResultErrorVariant<TErrorData> = {
337
- data: null;
338
- error: PossibleHTTPError<TErrorData>;
339
- response: Response;
340
- } | {
341
- data: null;
342
- error: PossibleJavaScriptError;
343
- response: null;
344
- };
345
- type ResultModeMap<TData = DefaultDataType, TErrorData = DefaultDataType, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TComputedData = GetResponseType<TData, TResponseType>, TComputedErrorData = GetResponseType<TErrorData, TResponseType>> = UnmaskType<{
346
- all: CallApiResultSuccessVariant<TComputedData> | CallApiResultErrorVariant<TComputedErrorData>;
347
- allWithException: CallApiResultSuccessVariant<TComputedData>;
348
- onlySuccess: CallApiResultErrorVariant<TComputedErrorData>["data"] | CallApiResultSuccessVariant<TComputedData>["data"];
349
- onlySuccessWithException: CallApiResultSuccessVariant<TComputedData>["data"];
350
- }>;
351
- type ResultModeUnion = keyof ResultModeMap | null;
352
- type GetCallApiResult<TData, TErrorData, TResultMode extends ResultModeUnion, TThrowOnError extends boolean, TResponseType extends ResponseTypeUnion> = TErrorData extends false ? ResultModeMap<TData, TErrorData, TResponseType>["onlySuccessWithException"] : TErrorData extends false | undefined ? ResultModeMap<TData, TErrorData, TResponseType>["onlySuccessWithException"] : TErrorData extends false | null ? ResultModeMap<TData, TErrorData, TResponseType>["onlySuccess"] : null extends TResultMode ? TThrowOnError extends true ? ResultModeMap<TData, TErrorData, TResponseType>["allWithException"] : ResultModeMap<TData, TErrorData, TResponseType>["all"] : TResultMode extends NonNullable<ResultModeUnion> ? ResultModeMap<TData, TErrorData, TResponseType>[TResultMode] : never;
353
-
354
- type StreamProgressEvent = {
355
- /**
356
- * Current chunk of data being streamed
357
- */
358
- chunk: Uint8Array;
359
- /**
360
- * Progress in percentage
361
- */
362
- progress: number;
363
- /**
364
- * Total size of data in bytes
365
- */
366
- totalBytes: number;
367
- /**
368
- * Amount of data transferred so far
369
- */
370
- transferredBytes: number;
371
- };
372
- declare global {
373
- interface ReadableStream<R> {
374
- [Symbol.asyncIterator]: () => AsyncIterableIterator<R>;
375
- }
376
- }
377
-
378
- type WithMoreOptions<TMoreOptions = DefaultMoreOptions> = {
379
- options: CombinedCallApiExtraOptions & Partial<TMoreOptions>;
380
- };
381
- type Hooks<TData = DefaultDataType, TErrorData = DefaultDataType, TMoreOptions = DefaultMoreOptions> = {
382
- /**
383
- * Hook that will be called when any error occurs within the request/response lifecycle, regardless of whether the error is from the api or not.
384
- * It is basically a combination of `onRequestError` and `onResponseError` hooks
385
- */
386
- onError?: (context: ErrorContext<TErrorData> & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;
387
- /**
388
- * Hook that will be called just before the request is made, allowing for modifications or additional operations.
389
- */
390
- onRequest?: (context: Prettify<RequestContext & WithMoreOptions<TMoreOptions>>) => Awaitable<unknown>;
391
- /**
392
- * Hook that will be called when an error occurs during the fetch request.
393
- */
394
- onRequestError?: (context: Prettify<RequestErrorContext & WithMoreOptions<TMoreOptions>>) => Awaitable<unknown>;
395
- /**
396
- * Hook that will be called when upload stream progress is tracked
397
- */
398
- onRequestStream?: (context: Prettify<RequestStreamContext & WithMoreOptions<TMoreOptions>>) => Awaitable<unknown>;
399
- /**
400
- * Hook that will be called when any response is received from the api, whether successful or not
401
- */
402
- onResponse?: (context: ResponseContext<TData, TErrorData> & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;
403
- /**
404
- * Hook that will be called when an error response is received from the api.
405
- */
406
- onResponseError?: (context: Prettify<ResponseErrorContext<TErrorData> & WithMoreOptions<TMoreOptions>>) => Awaitable<unknown>;
407
- /**
408
- * Hook that will be called when download stream progress is tracked
409
- */
410
- onResponseStream?: (context: Prettify<ResponseStreamContext & WithMoreOptions<TMoreOptions>>) => Awaitable<unknown>;
411
- /**
412
- * Hook that will be called when a request is retried.
413
- */
414
- onRetry?: (response: RetryContext<TErrorData> & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;
415
- /**
416
- * Hook that will be called when a successful response is received from the api.
417
- */
418
- onSuccess?: (context: Prettify<SuccessContext<TData> & WithMoreOptions<TMoreOptions>>) => Awaitable<unknown>;
419
- };
420
- type HooksOrHooksArray<TData = DefaultDataType, TErrorData = DefaultDataType, TMoreOptions = DefaultMoreOptions> = {
421
- [Key in keyof Hooks<TData, TErrorData, TMoreOptions>]: Hooks<TData, TErrorData, TMoreOptions>[Key] | Array<Hooks<TData, TErrorData, TMoreOptions>[Key]>;
422
- };
423
- type SharedHookContext<TMoreOptions = DefaultMoreOptions> = {
424
- /**
425
- * Config object passed to createFetchClient
426
- */
427
- baseConfig: BaseCallApiExtraOptions & CallApiRequestOptions;
428
- /**
429
- * Config object passed to the callApi instance
430
- */
431
- config: CallApiExtraOptions & CallApiRequestOptions;
432
- /**
433
- * Merged options consisting of extra options from createFetchClient, the callApi instance and default options.
434
- *
435
- */
436
- options: CombinedCallApiExtraOptions & Partial<TMoreOptions>;
437
- /**
438
- * Merged request consisting of request options from createFetchClient, the callApi instance and default request options.
439
- */
440
- request: CallApiRequestOptionsForHooks;
441
- };
442
- type RequestContext = UnmaskType<SharedHookContext>;
443
- type ResponseContext<TData, TErrorData> = UnmaskType<Prettify<SharedHookContext & {
444
- data: TData;
445
- error: null;
446
- response: Response;
447
- }> | Prettify<SharedHookContext & {
448
- data: null;
449
- error: PossibleHTTPError<TErrorData>;
450
- response: Response;
451
- }>>;
452
- type SuccessContext<TData> = UnmaskType<Prettify<SharedHookContext & {
453
- data: TData;
454
- response: Response;
455
- }>>;
456
- type RequestErrorContext = UnmaskType<Prettify<SharedHookContext & {
457
- error: PossibleJavaScriptError;
458
- response: null;
459
- }>>;
460
- type ResponseErrorContext<TErrorData> = UnmaskType<Prettify<SharedHookContext & {
461
- error: PossibleHTTPError<TErrorData>;
462
- response: Response;
463
- }>>;
464
- type RetryContext<TErrorData> = UnmaskType<Prettify<ErrorContext<TErrorData> & {
465
- retryAttemptCount: number;
466
- }>>;
467
- type ErrorContext<TErrorData> = UnmaskType<Prettify<SharedHookContext & {
468
- error: PossibleHTTPError<TErrorData>;
469
- response: Response;
470
- }> | Prettify<SharedHookContext & {
471
- error: PossibleJavaScriptError;
472
- response: null;
473
- }>>;
474
- type RequestStreamContext = UnmaskType<Prettify<SharedHookContext & {
475
- event: StreamProgressEvent;
476
- requestInstance: Request;
477
- }>>;
478
- type ResponseStreamContext = UnmaskType<Prettify<SharedHookContext & {
479
- event: StreamProgressEvent;
480
- response: Response;
481
- }>>;
482
-
483
- type RetryCondition<TErrorData> = (context: ErrorContext<TErrorData>) => Awaitable<boolean>;
484
- type InnerRetryKeys<TErrorData> = Exclude<keyof RetryOptions<TErrorData>, "~retryAttemptCount" | "retry">;
485
- type InnerRetryOptions<TErrorData> = {
486
- [Key in InnerRetryKeys<TErrorData> as Key extends `retry${infer TRest}` ? Uncapitalize<TRest> extends "attempts" ? never : Uncapitalize<TRest> : Key]?: RetryOptions<TErrorData>[Key];
487
- } & {
488
- attempts: NonNullable<RetryOptions<TErrorData>["retryAttempts"]>;
489
- };
490
- interface RetryOptions<TErrorData> {
491
- /**
492
- * Keeps track of the number of times the request has already been retried
493
- * @deprecated This property is used internally to track retries. Please abstain from modifying it.
494
- */
495
- readonly ["~retryAttemptCount"]?: number;
496
- /**
497
- * All retry options in a single object instead of separate properties
498
- */
499
- retry?: InnerRetryOptions<TErrorData>;
500
- /**
501
- * Number of allowed retry attempts on HTTP errors
502
- * @default 0
503
- */
504
- retryAttempts?: number;
505
- /**
506
- * Callback whose return value determines if a request should be retried or not
507
- */
508
- retryCondition?: RetryCondition<TErrorData>;
509
- /**
510
- * Delay between retries in milliseconds
511
- * @default 1000
512
- */
513
- retryDelay?: number | ((currentAttemptCount: number) => number);
514
- /**
515
- * Maximum delay in milliseconds. Only applies to exponential strategy
516
- * @default 10000
517
- */
518
- retryMaxDelay?: number;
519
- /**
520
- * HTTP methods that are allowed to retry
521
- * @default ["GET", "POST"]
522
- */
523
- retryMethods?: Method[];
524
- /**
525
- * HTTP status codes that trigger a retry
526
- */
527
- retryStatusCodes?: number[];
528
- /**
529
- * Strategy to use when retrying
530
- * @default "linear"
531
- */
532
- retryStrategy?: "exponential" | "linear";
533
- }
534
-
535
- /**
536
- * @description Makes a type required if TSchema type is undefined or if the output type of TSchema contains undefined, otherwise keeps it as is
537
- */
538
- type MakeSchemaOptionRequired<TSchema extends StandardSchemaV1 | undefined, TObject> = undefined extends TSchema ? TObject : undefined extends InferSchemaResult<TSchema> ? TObject : Required<TObject>;
539
- type JsonPrimitive = boolean | number | string | null | undefined;
540
- type SerializableObject = Record<keyof object, unknown>;
541
- type SerializableArray = Array<JsonPrimitive | SerializableArray | SerializableObject> | ReadonlyArray<JsonPrimitive | SerializableArray | SerializableObject>;
542
- type Body = UnmaskType<RequestInit["body"] | SerializableArray | SerializableObject>;
543
- type BodyOption<TSchemas extends CallApiSchemas> = MakeSchemaOptionRequired<TSchemas["body"], {
544
- /**
545
- * Body of the request, can be a object or any other supported body type.
546
- */
547
- body?: InferSchemaResult<TSchemas["body"], Body>;
548
- }>;
549
- type Method = UnmaskType<"CONNECT" | "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "TRACE" | AnyString>;
550
- type MethodOption<TSchemas extends CallApiSchemas> = MakeSchemaOptionRequired<TSchemas["method"], {
551
- /**
552
- * HTTP method for the request.
553
- * @default "GET"
554
- */
555
- method?: InferSchemaResult<TSchemas["method"], Method>;
556
- }>;
557
- type Headers = UnmaskType<Record<"Authorization", CommonAuthorizationHeaders> | Record<"Content-Type", CommonContentTypes> | Record<CommonRequestHeaders, string | undefined> | Record<string, string | undefined> | RequestInit["headers"]>;
558
- type HeadersOption<TSchemas extends CallApiSchemas> = MakeSchemaOptionRequired<TSchemas["headers"], {
559
- /**
560
- * Headers to be used in the request.
561
- */
562
- headers?: InferSchemaResult<TSchemas["headers"], Headers>;
563
- }>;
564
- interface Register {
565
- }
566
- type GlobalMeta = Register extends {
567
- meta?: infer TMeta extends Record<string, unknown>;
568
- } ? TMeta : never;
569
- type MetaOption<TSchemas extends CallApiSchemas> = {
570
- /**
571
- * - An optional field you can fill with additional information,
572
- * to associate with the request, typically used for logging or tracing.
573
- *
574
- * - A good use case for this, would be to use the info to handle specific cases in any of the shared interceptors.
575
- *
576
- * @example
577
- * ```ts
578
- * const callMainApi = callApi.create({
579
- * baseURL: "https://main-api.com",
580
- * onResponseError: ({ response, options }) => {
581
- * if (options.meta?.userId) {
582
- * console.error(`User ${options.meta.userId} made an error`);
583
- * }
584
- * },
585
- * });
586
- *
587
- * const response = await callMainApi({
588
- * url: "https://example.com/api/data",
589
- * meta: { userId: "123" },
590
- * });
591
- * ```
592
- */
593
- meta?: InferSchemaResult<TSchemas["meta"], GlobalMeta>;
594
- };
595
- type ExtractKeys<T, U extends T> = Extract<T, U>;
596
- type ResultModeOption<TErrorData, TResultMode extends ResultModeUnion> = TErrorData extends false ? {
597
- resultMode: "onlySuccessWithException";
598
- } : TErrorData extends false | undefined ? {
599
- resultMode?: "onlySuccessWithException";
600
- } : TErrorData extends false | null ? {
601
- resultMode?: ExtractKeys<ResultModeUnion, "onlySuccess" | "onlySuccessWithException">;
602
- } : null extends TResultMode ? {
603
- resultMode?: TResultMode;
604
- } : {
605
- resultMode: TResultMode;
606
- };
607
- type ThrowOnErrorOption<TErrorData> = TErrorData extends false ? {
608
- throwOnError: true;
609
- } : TErrorData extends false | undefined ? {
610
- throwOnError?: true;
611
- } : NonNullable<unknown>;
612
-
613
- type FetchSpecificKeysUnion = Exclude<(typeof fetchSpecificKeys)[number], "body" | "headers" | "method">;
614
- type ModifiedRequestInit = RequestInit & {
615
- duplex?: "half";
616
- };
617
- type CallApiRequestOptions<TSchemas extends CallApiSchemas = DefaultMoreOptions> = Prettify<BodyOption<TSchemas> & HeadersOption<TSchemas> & MethodOption<TSchemas> & Pick<ModifiedRequestInit, FetchSpecificKeysUnion>>;
618
- type CallApiRequestOptionsForHooks<TSchemas extends CallApiSchemas = DefaultMoreOptions> = Omit<CallApiRequestOptions<TSchemas>, "headers"> & {
619
- headers?: Record<string, string | undefined>;
620
- };
621
- type FetchImpl = UnmaskType<(input: string | Request | URL, init?: RequestInit) => Promise<Response>>;
622
- type ExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends boolean = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TPluginArray extends CallApiPlugin[] = DefaultPluginArray, TSchemas extends CallApiSchemas = DefaultMoreOptions> = {
623
- /**
624
- * Authorization header value.
625
- */
626
- auth?: string | Auth | null;
627
- /**
628
- * Base URL to be prepended to all request URLs
629
- */
630
- baseURL?: string;
631
- /**
632
- * Custom function to serialize the body object into a string.
633
- */
634
- bodySerializer?: (bodyData: Record<string, unknown>) => string;
635
- /**
636
- * Whether or not to clone the response, so response.json() and the like can be read again else where.
637
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Response/clone
638
- * @default false
639
- */
640
- cloneResponse?: boolean;
641
- /**
642
- * Custom fetch implementation
643
- */
644
- customFetchImpl?: FetchImpl;
645
- /**
646
- * Custom request key to be used to identify a request in the fetch deduplication strategy.
647
- * @default the full request url + string formed from the request options
648
- */
649
- dedupeKey?: string;
650
- /**
651
- * Defines the deduplication strategy for the request, can be set to "none" | "defer" | "cancel".
652
- * - If set to "cancel", the previous pending request with the same request key will be cancelled and lets the new request through.
653
- * - If set to "defer", all new request with the same request key will be share the same response, until the previous one is completed.
654
- * - If set to "none", deduplication is disabled.
655
- * @default "cancel"
656
- */
657
- dedupeStrategy?: "cancel" | "defer" | "none";
658
- /**
659
- * Default error message to use if none is provided from a response.
660
- * @default "Failed to fetch data from server!"
661
- */
662
- defaultErrorMessage?: string;
663
- /**
664
- * If true, forces the calculation of the total byte size from the request or response body, in case the content-length header is not present or is incorrect.
665
- * @default false
666
- */
667
- forceCalculateStreamSize?: boolean | {
668
- request?: boolean;
669
- response?: boolean;
670
- };
671
- /**
672
- * Resolved request URL
673
- */
674
- readonly fullURL?: string;
675
- /**
676
- * Defines the mode in which the composed hooks are executed".
677
- * - If set to "parallel", main and plugin hooks will be executed in parallel.
678
- * - If set to "sequential", the plugin hooks will be executed first, followed by the main hook.
679
- * @default "parallel"
680
- */
681
- mergedHooksExecutionMode?: "parallel" | "sequential";
682
- /**
683
- * - Controls what order in which the composed hooks execute
684
- * @default "mainHooksAfterPlugins"
685
- */
686
- mergedHooksExecutionOrder?: "mainHooksAfterPlugins" | "mainHooksBeforePlugins";
687
- /**
688
- * An array of CallApi plugins. It allows you to extend the behavior of the library.
689
- */
690
- plugins?: Plugins<TPluginArray>;
691
- /**
692
- * Custom function to parse the response string
693
- */
694
- responseParser?: (responseString: string) => Awaitable<Record<string, unknown>>;
695
- /**
696
- * Expected response type, affects how response is parsed
697
- * @default "json"
698
- */
699
- responseType?: TResponseType;
700
- /**
701
- * Mode of the result, can influence how results are handled or returned.
702
- * Can be set to "all" | "onlySuccess" | "onlyError" | "onlyResponse".
703
- * @default "all"
704
- */
705
- resultMode?: TResultMode;
706
- /**
707
- * Type-safe schemas for the response validation.
708
- */
709
- schemas?: TSchemas;
710
- /**
711
- * If true or the function returns true, throws errors instead of returning them
712
- * The function is passed the error object and can be used to conditionally throw the error
713
- * @default false
714
- */
715
- throwOnError?: TThrowOnError | ((context: ErrorContext<TErrorData>) => TThrowOnError);
716
- /**
717
- * Request timeout in milliseconds
718
- */
719
- timeout?: number;
720
- /**
721
- * Custom validation functions for response validation
722
- */
723
- validators?: CallApiValidators<TData, TErrorData>;
724
- } & HooksOrHooksArray<TData, TErrorData, Partial<InferPluginOptions<TPluginArray>>> & Partial<InferPluginOptions<TPluginArray>> & MetaOption<TSchemas> & RetryOptions<TErrorData> & ResultModeOption<TErrorData, TResultMode> & ThrowOnErrorOption<TErrorData> & UrlOptions<TSchemas>;
725
- type CallApiExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends boolean = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TPluginArray extends CallApiPlugin[] = DefaultPluginArray, TSchemas extends CallApiSchemas = DefaultMoreOptions> = ExtraOptions<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TPluginArray, TSchemas> & {
726
- plugins?: Plugins<TPluginArray> | ((context: {
727
- basePlugins: Plugins<TPluginArray>;
728
- }) => Plugins<TPluginArray>);
729
- schemas?: TSchemas | ((context: {
730
- baseSchemas: TSchemas | undefined;
731
- }) => TSchemas);
732
- validators?: CallApiValidators<TData, TErrorData> | ((context: {
733
- baseValidators: CallApiValidators<TData, TErrorData> | undefined;
734
- }) => CallApiValidators<TData, TErrorData>);
735
- };
736
- declare const optionsEnumToOmitFromBase: "dedupeKey"[];
737
- type BaseCallApiExtraOptions<TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBaseThrowOnError extends boolean = DefaultThrowOnError, TBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray, TBaseSchemas extends CallApiSchemas = DefaultMoreOptions> = Omit<Partial<CallApiExtraOptions<TBaseData, TBaseErrorData, TBaseResultMode, TBaseThrowOnError, TBaseResponseType, TBasePluginArray, TBaseSchemas>>, (typeof optionsEnumToOmitFromBase)[number]> & {
738
- /**
739
- * Specifies which configuration parts should skip automatic merging between base and main configs.
740
- * Use this when you need manual control over how configs are combined.
741
- *
742
- * @values
743
- * - "all" - Disables automatic merging for both request and options
744
- * - "options" - Disables automatic merging of options only
745
- * - "request" - Disables automatic merging of request only
746
- *
747
- * @example
748
- * ```ts
749
- * const client = createFetchClient((ctx) => ({
750
- * skipAutoMergeFor: "options",
751
- *
752
- * // Now you can manually merge options in your config function
753
- * ...ctx.options,
754
- * }));
755
- * ```
756
- */
757
- skipAutoMergeFor?: "all" | "options" | "request";
758
- };
759
- type CombinedExtraOptionsWithoutHooks = Omit<BaseCallApiExtraOptions & CallApiExtraOptions, keyof Hooks>;
760
- interface CombinedCallApiExtraOptions extends CombinedExtraOptionsWithoutHooks, Hooks {
761
- }
762
- type BaseCallApiConfig<TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBaseThrowOnError extends boolean = DefaultThrowOnError, TBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray, TBaseSchemas extends CallApiSchemas = DefaultMoreOptions> = (CallApiRequestOptions<TBaseSchemas> & BaseCallApiExtraOptions<TBaseData, TBaseErrorData, TBaseResultMode, TBaseThrowOnError, TBaseResponseType, TBasePluginArray, TBaseSchemas>) | ((context: {
763
- initURL: string;
764
- options: CallApiExtraOptions;
765
- request: CallApiRequestOptions;
766
- }) => CallApiRequestOptions<TBaseSchemas> & BaseCallApiExtraOptions<TBaseData, TBaseErrorData, TBaseResultMode, TBaseThrowOnError, TBaseResponseType, TBasePluginArray, TBaseSchemas>);
767
- type CallApiConfig<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends boolean = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TPluginArray extends CallApiPlugin[] = DefaultPluginArray, TSchemas extends CallApiSchemas = DefaultMoreOptions> = CallApiRequestOptions<TSchemas> & CallApiExtraOptions<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TPluginArray, TSchemas>;
768
- type CallApiParameters<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends boolean = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TPluginArray extends CallApiPlugin[] = DefaultPluginArray, TSchemas extends CallApiSchemas = DefaultMoreOptions> = [
769
- initURL: InferSchemaResult<TSchemas["initURL"], InitURL>,
770
- config?: CallApiConfig<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TPluginArray, TSchemas>
771
- ];
772
- type CallApiResult<TData, TErrorData, TResultMode extends ResultModeUnion, TThrowOnError extends boolean, TResponseType extends ResponseTypeUnion> = Promise<GetCallApiResult<TData, TErrorData, TResultMode, TThrowOnError, TResponseType>>;
773
-
774
- export { type CallApiExtraOptions as A, type BaseCallApiConfig as B, type CallApiPlugin as C, type DefaultPluginArray as D, type ErrorContext as E, type CallApiRequestOptions as F, type CallApiRequestOptionsForHooks as G, HTTPError as H, type InferSchemaResult as I, type CombinedCallApiExtraOptions as J, type Register as K, type PluginInitContext as P, type ResultModeUnion as R, type SharedHookContext as S, type ResponseTypeUnion as a, type CallApiSchemas as b, type CallApiConfig as c, type CallApiResult as d, type DefaultDataType as e, type DefaultThrowOnError as f, type DefaultMoreOptions as g, type CallApiParameters as h, definePlugin as i, type PluginHooks as j, type PluginHooksWithMoreOptions as k, type RetryOptions as l, type PossibleHTTPError as m, type PossibleJavaScriptError as n, type CallApiResultErrorVariant as o, type CallApiResultSuccessVariant as p, type Hooks as q, type HooksOrHooksArray as r, type RequestContext as s, type RequestErrorContext as t, type RequestStreamContext as u, type ResponseContext as v, type ResponseErrorContext as w, type ResponseStreamContext as x, type SuccessContext as y, type BaseCallApiExtraOptions as z };