@zayne-labs/callapi-plugins 4.0.27 → 4.0.29

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/index.d.ts CHANGED
@@ -1,1855 +1,2 @@
1
- import * as _zayne_labs_callapi_utils0 from "@zayne-labs/callapi/utils";
2
- import { AnyFunction } from "@zayne-labs/toolkit-type-helpers";
3
-
4
- //#region ../callapi/dist/validation-Dq--Q5zC.d.ts
5
- //#region src/constants/common.d.ts
6
- declare const fetchSpecificKeys: readonly (keyof RequestInit | "duplex")[];
7
- //#endregion
8
- //#region src/constants/validation.d.ts
9
- declare const fallBackRouteSchemaKey = "@default";
10
- type FallBackRouteSchemaKey = typeof fallBackRouteSchemaKey;
11
- //#endregion
12
- //#endregion
13
- //#region ../callapi/dist/index-HHFgKKcn.d.ts
14
- //#region src/types/type-helpers.d.ts
15
- type AnyString = string & NonNullable<unknown>;
16
- type AnyNumber = number & NonNullable<unknown>;
17
- type AnyFunction$1<TResult$1 = unknown> = (...args: any[]) => TResult$1;
18
- type Prettify<TObject> = NonNullable<unknown> & { [Key in keyof TObject]: TObject[Key] };
19
- type WriteableLevel = "deep" | "shallow";
20
- /**
21
- * Makes all properties in an object type writeable (removes readonly modifiers).
22
- * Supports both shallow and deep modes, and handles special cases like arrays, tuples, and unions.
23
- * @template TObject - The object type to make writeable
24
- * @template TVariant - The level of writeable transformation ("shallow" | "deep")
25
- */
26
- type ArrayOrObject = Record<number | string | symbol, unknown> | unknown[] | readonly unknown[];
27
- type Writeable<TObject, TLevel extends WriteableLevel = "shallow"> = TObject extends ArrayOrObject ? { -readonly [Key in keyof TObject]: TLevel extends "deep" ? NonNullable<TObject[Key]> extends ArrayOrObject ? Writeable<TObject[Key], "deep"> : TObject[Key] : TObject[Key] } : TObject;
28
- type UnionToIntersection<TUnion> = (TUnion extends unknown ? (param: TUnion) => void : never) extends ((param: infer TParam) => void) ? TParam : never;
29
- type UnmaskType<TValue$1> = {
30
- _: TValue$1;
31
- }["_"];
32
- type RemovePrefix<TPrefix extends "dedupe" | "retry", TKey extends string> = TKey extends `${TPrefix}${infer TRest}` ? Uncapitalize<TRest> : TKey;
33
- type Awaitable<TValue$1> = Promise<TValue$1> | TValue$1;
34
- type DistributiveOmit<TObject, TKeysToOmit extends keyof TObject> = TObject extends unknown ? Omit<TObject, TKeysToOmit> : never;
35
- 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;
36
- type CommonAuthorizationHeaders = `${"Basic" | "Bearer" | "Token"} ${string}`;
37
- 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;
38
- //#endregion
39
- //#region src/auth.d.ts
40
- type PossibleAuthValue = Awaitable<string | null | undefined>;
41
- type PossibleAuthValueOrGetter = PossibleAuthValue | (() => PossibleAuthValue);
42
- type BearerOrTokenAuth = {
43
- type?: "Bearer";
44
- bearer?: PossibleAuthValueOrGetter;
45
- token?: never;
46
- } | {
47
- type?: "Token";
48
- bearer?: never;
49
- token?: PossibleAuthValueOrGetter;
50
- };
51
- type BasicAuth = {
52
- type: "Basic";
53
- username: PossibleAuthValueOrGetter;
54
- password: PossibleAuthValueOrGetter;
55
- };
56
- /**
57
- * Custom auth
58
- *
59
- * @param prefix - prefix of the header
60
- * @param authValue - value of the header
61
- *
62
- * @example
63
- * ```ts
64
- * {
65
- * type: "Custom",
66
- * prefix: "Token",
67
- * authValue: "token"
68
- * }
69
- * ```
70
- */
71
- type CustomAuth = {
72
- type: "Custom";
73
- prefix: PossibleAuthValueOrGetter;
74
- value: PossibleAuthValueOrGetter;
75
- };
76
- type Auth = PossibleAuthValueOrGetter | BearerOrTokenAuth | BasicAuth | CustomAuth;
77
- //#endregion
78
- //#region src/dedupe.d.ts
79
- type DedupeStrategyUnion = UnmaskType<"cancel" | "defer" | "none">;
80
- type DedupeOptionKeys = Exclude<keyof DedupeOptions, "dedupe">;
81
- type InnerDedupeOptions = { [Key in DedupeOptionKeys as RemovePrefix<"dedupe", Key>]?: DedupeOptions[Key] };
82
- type DedupeOptions = {
83
- /**
84
- * All dedupe options in a single object instead of separate properties
85
- */
86
- dedupe?: InnerDedupeOptions;
87
- /**
88
- * Controls the scope of request deduplication caching.
89
- *
90
- * - `"global"`: Shares deduplication cache across all `createFetchClient` instances with the same `dedupeCacheScopeKey`.
91
- * Useful for applications with multiple API clients that should share deduplication state.
92
- * - `"local"`: Limits deduplication to requests within the same `createFetchClient` instance.
93
- * Provides better isolation and is recommended for most use cases.
94
- *
95
- *
96
- * **Real-world Scenarios:**
97
- * - Use `"global"` when you have multiple API clients (user service, auth service, etc.) that might make overlapping requests
98
- * - Use `"local"` (default) for single-purpose clients or when you want strict isolation between different parts of your app
99
- *
100
- * @example
101
- * ```ts
102
- * // Local scope - each client has its own deduplication cache
103
- * const userClient = createFetchClient({ baseURL: "/api/users" });
104
- * const postClient = createFetchClient({ baseURL: "/api/posts" });
105
- * // These clients won't share deduplication state
106
- *
107
- * // Global scope - share cache across related clients
108
- * const userClient = createFetchClient({
109
- * baseURL: "/api/users",
110
- * dedupeCacheScope: "global",
111
- * });
112
- * const postClient = createFetchClient({
113
- * baseURL: "/api/posts",
114
- * dedupeCacheScope: "global",
115
- * });
116
- * // These clients will share deduplication state
117
- * ```
118
- *
119
- * @default "local"
120
- */
121
- dedupeCacheScope?: "global" | "local";
122
- /**
123
- * Unique namespace for the global deduplication cache when using `dedupeCacheScope: "global"`.
124
- *
125
- * This creates logical groupings of deduplication caches. All instances with the same key
126
- * will share the same cache namespace, allowing fine-grained control over which clients
127
- * share deduplication state.
128
- *
129
- * **Best Practices:**
130
- * - Use descriptive names that reflect the logical grouping (e.g., "user-service", "analytics-api")
131
- * - Keep scope keys consistent across related API clients
132
- * - Consider using different scope keys for different environments (dev, staging, prod)
133
- * - Avoid overly broad scope keys that might cause unintended cache sharing
134
- *
135
- * **Cache Management:**
136
- * - Each scope key maintains its own independent cache
137
- * - Caches are automatically cleaned up when no references remain
138
- * - Consider the memory implications of multiple global scopes
139
- *
140
- * @example
141
- * ```ts
142
- * // Group related API clients together
143
- * const userClient = createFetchClient({
144
- * baseURL: "/api/users",
145
- * dedupeCacheScope: "global",
146
- * dedupeCacheScopeKey: "user-service"
147
- * });
148
- * const profileClient = createFetchClient({
149
- * baseURL: "/api/profiles",
150
- * dedupeCacheScope: "global",
151
- * dedupeCacheScopeKey: "user-service" // Same scope - will share cache
152
- * });
153
- *
154
- * // Separate analytics client with its own cache
155
- * const analyticsClient = createFetchClient({
156
- * baseURL: "/api/analytics",
157
- * dedupeCacheScope: "global",
158
- * dedupeCacheScopeKey: "analytics-service" // Different scope
159
- * });
160
- *
161
- * // Environment-specific scoping
162
- * const apiClient = createFetchClient({
163
- * dedupeCacheScope: "global",
164
- * dedupeCacheScopeKey: `api-${process.env.NODE_ENV}` // "api-development", "api-production", etc.
165
- * });
166
- * ```
167
- *
168
- * @default "default"
169
- */
170
- dedupeCacheScopeKey?: "default" | AnyString | ((context: RequestContext) => string | undefined);
171
- /**
172
- * Custom key generator for request deduplication.
173
- *
174
- * Override the default key generation strategy to control exactly which requests
175
- * are considered duplicates. The default key combines URL, method, body, and
176
- * relevant headers (excluding volatile ones like 'Date', 'Authorization', etc.).
177
- *
178
- * **Default Key Generation:**
179
- * The auto-generated key includes:
180
- * - Full request URL (including query parameters)
181
- * - HTTP method (GET, POST, etc.)
182
- * - Request body (for POST/PUT/PATCH requests)
183
- * - Stable headers (excludes Date, Authorization, User-Agent, etc.)
184
- *
185
- * **Custom Key Best Practices:**
186
- * - Include only the parts of the request that should affect deduplication
187
- * - Avoid including volatile data (timestamps, random IDs, etc.)
188
- * - Consider performance - simpler keys are faster to compute and compare
189
- * - Ensure keys are deterministic for the same logical request
190
- * - Use consistent key formats across your application
191
- *
192
- * **Performance Considerations:**
193
- * - Function-based keys are computed on every request - keep them lightweight
194
- * - String keys are fastest but least flexible
195
- * - Consider caching expensive key computations if needed
196
- *
197
- * @example
198
- * ```ts
199
- * import { callApi } from "@zayne-labs/callapi";
200
- *
201
- * // Simple static key - useful for singleton requests
202
- * const config = callApi("/api/config", {
203
- * dedupeKey: "app-config",
204
- * dedupeStrategy: "defer" // Share the same config across all requests
205
- * });
206
- *
207
- * // URL and method only - ignore headers and body
208
- * const userData = callApi("/api/user/123", {
209
- * dedupeKey: (context) => `${context.options.method}:${context.options.fullURL}`
210
- * });
211
- *
212
- * // Include specific headers in deduplication
213
- * const apiCall = callApi("/api/data", {
214
- * dedupeKey: (context) => {
215
- * const authHeader = context.request.headers.get("Authorization");
216
- * return `${context.options.fullURL}-${authHeader}`;
217
- * }
218
- * });
219
- *
220
- * // User-specific deduplication
221
- * const userSpecificCall = callApi("/api/dashboard", {
222
- * dedupeKey: (context) => {
223
- * const userId = context.options.fullURL.match(/user\/(\d+)/)?.[1];
224
- * return `dashboard-${userId}`;
225
- * }
226
- * });
227
- *
228
- * // Ignore certain query parameters
229
- * const searchCall = callApi("/api/search?q=test&timestamp=123456", {
230
- * dedupeKey: (context) => {
231
- * const url = new URL(context.options.fullURL);
232
- * url.searchParams.delete("timestamp"); // Remove volatile param
233
- * return `search:${url.toString()}`;
234
- * }
235
- * });
236
- * ```
237
- *
238
- * @default Auto-generated from request details
239
- */
240
- dedupeKey?: string | ((context: RequestContext) => string | undefined);
241
- /**
242
- * Strategy for handling duplicate requests. Can be a static string or callback function.
243
- *
244
- * **Available Strategies:**
245
- * - `"cancel"`: Cancel previous request when new one starts (good for search)
246
- * - `"defer"`: Share response between duplicate requests (good for config loading)
247
- * - `"none"`: No deduplication, all requests execute independently
248
- *
249
- * @example
250
- * ```ts
251
- * // Static strategies
252
- * const searchClient = createFetchClient({
253
- * dedupeStrategy: "cancel" // Cancel previous searches
254
- * });
255
- *
256
- * const configClient = createFetchClient({
257
- * dedupeStrategy: "defer" // Share config across components
258
- * });
259
- *
260
- * // Dynamic strategy based on request
261
- * const smartClient = createFetchClient({
262
- * dedupeStrategy: (context) => {
263
- * return context.options.method === "GET" ? "defer" : "cancel";
264
- * }
265
- * });
266
- *
267
- * // Search-as-you-type with cancel strategy
268
- * const handleSearch = async (query: string) => {
269
- * try {
270
- * const { data } = await callApi("/api/search", {
271
- * method: "POST",
272
- * body: { query },
273
- * dedupeStrategy: "cancel",
274
- * dedupeKey: "search" // Cancel previous searches, only latest one goes through
275
- * });
276
- *
277
- * updateSearchResults(data);
278
- * } catch (error) {
279
- * if (error.name === "AbortError") {
280
- * // Previous search cancelled - (expected behavior)
281
- * return;
282
- * }
283
- * console.error("Search failed:", error);
284
- * }
285
- * };
286
- *
287
- * ```
288
- *
289
- * @default "cancel"
290
- */
291
- dedupeStrategy?: DedupeStrategyUnion | ((context: RequestContext) => DedupeStrategyUnion);
292
- };
293
- //#endregion
294
- //#region src/middlewares.d.ts
295
- type FetchImpl = UnmaskType<(input: string | Request | URL, init?: RequestInit) => Promise<Response>>;
296
- interface Middlewares {
297
- /**
298
- * Wraps the fetch implementation to intercept requests at the network layer.
299
- *
300
- * Takes a context object containing the current fetch function and returns a new fetch function.
301
- * Use it to cache responses, add logging, handle offline mode, or short-circuit requests etc.
302
- * Multiple middleware compose in order: plugins → base config → per-request.
303
- *
304
- * Unlike `customFetchImpl`, middleware can call through to the original fetch.
305
- *
306
- * @example
307
- * ```ts
308
- * // Cache responses
309
- * const cache = new Map();
310
- * fetchMiddleware: (ctx) => async (input, init) => {
311
- * const key = input.toString();
312
- * if (cache.has(key)) return cache.get(key).clone();
313
- *
314
- * const response = await ctx.fetchImpl(input, init);
315
- * cache.set(key, response.clone());
316
- * return response;
317
- * }
318
- *
319
- * // Handle offline
320
- * fetchMiddleware: (ctx) => async (input, init) => {
321
- * if (!navigator.onLine) {
322
- * return new Response('{"error": "offline"}', { status: 503 });
323
- * }
324
- * return ctx.fetchImpl(input, init);
325
- * }
326
- * ```
327
- */
328
- fetchMiddleware?: (context: RequestContext & {
329
- fetchImpl: FetchImpl;
330
- }) => FetchImpl;
331
- }
332
- //#endregion
333
- //#region src/url.d.ts
334
- type AllowedQueryParamValues = UnmaskType<boolean | number | string>;
335
- type RecordStyleParams = UnmaskType<Record<string, AllowedQueryParamValues>>;
336
- type TupleStyleParams = UnmaskType<AllowedQueryParamValues[]>;
337
- type Params = UnmaskType<RecordStyleParams | TupleStyleParams>;
338
- type Query = UnmaskType<Record<string, AllowedQueryParamValues>>;
339
- type InitURLOrURLObject = AnyString | RouteKeyMethodsURLUnion | URL;
340
- interface URLOptions {
341
- /**
342
- * Base URL for all API requests. Will only be prepended to relative URLs.
343
- *
344
- * Absolute URLs (starting with http/https) will not be prepended by the baseURL.
345
- *
346
- * @example
347
- * ```ts
348
- * // Set base URL for all requests
349
- * baseURL: "https://api.example.com/v1"
350
- *
351
- * // Then use relative URLs in requests
352
- * callApi("/users") // → https://api.example.com/v1/users
353
- * callApi("/posts/123") // → https://api.example.com/v1/posts/123
354
- *
355
- * // Environment-specific base URLs
356
- * baseURL: process.env.NODE_ENV === "production"
357
- * ? "https://api.example.com"
358
- * : "http://localhost:3000/api"
359
- * ```
360
- */
361
- baseURL?: string;
362
- /**
363
- * Resolved request URL after processing baseURL, parameters, and query strings (readonly)
364
- *
365
- * This is the final URL that will be used for the HTTP request, computed from
366
- * baseURL, initURL, params, and query parameters.
367
- *
368
- */
369
- readonly fullURL?: string;
370
- /**
371
- * The original URL string passed to the callApi instance (readonly)
372
- *
373
- * This preserves the original URL as provided, including any method modifiers like "@get/" or "@post/".
374
- *
375
- */
376
- readonly initURL?: string;
377
- /**
378
- * The URL string after normalization, with method modifiers removed(readonly)
379
- *
380
- * Method modifiers like "@get/", "@post/" are stripped to create a clean URL
381
- * for parameter substitution and final URL construction.
382
- *
383
- */
384
- readonly initURLNormalized?: string;
385
- /**
386
- * Parameters to be substituted into URL path segments.
387
- *
388
- * Supports both object-style (named parameters) and array-style (positional parameters)
389
- * for flexible URL parameter substitution.
390
- *
391
- * @example
392
- * ```typescript
393
- * // Object-style parameters (recommended)
394
- * const namedParams: URLOptions = {
395
- * initURL: "/users/:userId/posts/:postId",
396
- * params: { userId: "123", postId: "456" }
397
- * };
398
- * // Results in: /users/123/posts/456
399
- *
400
- * // Array-style parameters (positional)
401
- * const positionalParams: URLOptions = {
402
- * initURL: "/users/:userId/posts/:postId",
403
- * params: ["123", "456"] // Maps in order: userId=123, postId=456
404
- * };
405
- * // Results in: /users/123/posts/456
406
- *
407
- * // Single parameter
408
- * const singleParam: URLOptions = {
409
- * initURL: "/users/:id",
410
- * params: { id: "user-123" }
411
- * };
412
- * // Results in: /users/user-123
413
- * ```
414
- */
415
- params?: Params;
416
- /**
417
- * Query parameters to append to the URL as search parameters.
418
- *
419
- * These will be serialized into the URL query string using standard
420
- * URL encoding practices.
421
- *
422
- * @example
423
- * ```typescript
424
- * // Basic query parameters
425
- * const queryOptions: URLOptions = {
426
- * initURL: "/users",
427
- * query: {
428
- * page: 1,
429
- * limit: 10,
430
- * search: "john doe",
431
- * active: true
432
- * }
433
- * };
434
- * // Results in: /users?page=1&limit=10&search=john%20doe&active=true
435
- *
436
- * // Filtering and sorting
437
- * const filterOptions: URLOptions = {
438
- * initURL: "/products",
439
- * query: {
440
- * category: "electronics",
441
- * minPrice: 100,
442
- * maxPrice: 500,
443
- * sortBy: "price",
444
- * order: "asc"
445
- * }
446
- * };
447
- * // Results in: /products?category=electronics&minPrice=100&maxPrice=500&sortBy=price&order=asc
448
- * ```
449
- */
450
- query?: Query;
451
- }
452
- //#endregion
453
- //#region src/types/conditional-types.d.ts
454
- /**
455
- * @description Makes a type partial if the output type of TSchema is not provided or has undefined in the union, otherwise makes it required
456
- */
457
- type MakeSchemaOptionRequiredIfDefined<TSchemaOption extends CallApiSchema[keyof CallApiSchema], TObject> = undefined extends InferSchemaOutput<TSchemaOption, undefined> ? TObject : Required<TObject>;
458
- type ApplyURLBasedConfig<TSchemaConfig$1 extends CallApiSchemaConfig, TSchemaRouteKeys extends string> = TSchemaConfig$1["prefix"] extends string ? `${TSchemaConfig$1["prefix"]}${TSchemaRouteKeys}` : TSchemaConfig$1["baseURL"] extends string ? `${TSchemaConfig$1["baseURL"]}${TSchemaRouteKeys}` : TSchemaRouteKeys;
459
- type ApplyStrictConfig<TSchemaConfig$1 extends CallApiSchemaConfig, TSchemaRouteKeys extends string> = TSchemaConfig$1["strict"] extends true ? TSchemaRouteKeys :
460
- // eslint-disable-next-line perfectionist/sort-union-types -- Don't sort union types
461
- TSchemaRouteKeys | Exclude<InitURLOrURLObject, RouteKeyMethodsURLUnion>;
462
- type ApplySchemaConfiguration<TSchemaConfig$1 extends CallApiSchemaConfig, TSchemaRouteKeys extends string> = ApplyStrictConfig<TSchemaConfig$1, ApplyURLBasedConfig<TSchemaConfig$1, TSchemaRouteKeys>>;
463
- type InferAllRouteKeys<TBaseSchemaRoutes$1 extends BaseCallApiSchemaRoutes, TSchemaConfig$1 extends CallApiSchemaConfig> = ApplySchemaConfiguration<TSchemaConfig$1, Exclude<Extract<keyof TBaseSchemaRoutes$1, string>, FallBackRouteSchemaKey>>;
464
- type InferInitURL<TBaseSchemaRoutes$1 extends BaseCallApiSchemaRoutes, TSchemaConfig$1 extends CallApiSchemaConfig> = keyof TBaseSchemaRoutes$1 extends never ? InitURLOrURLObject : InferAllRouteKeys<TBaseSchemaRoutes$1, TSchemaConfig$1>;
465
- type GetCurrentRouteSchema<TBaseSchemaRoutes$1 extends BaseCallApiSchemaRoutes, TCurrentRouteSchemaKey$1 extends string, TComputedFallBackRouteSchema = TBaseSchemaRoutes$1[FallBackRouteSchemaKey], TComputedCurrentRouteSchema = TBaseSchemaRoutes$1[TCurrentRouteSchemaKey$1], TComputedRouteSchema extends CallApiSchema = NonNullable<Omit<TComputedFallBackRouteSchema, keyof TComputedCurrentRouteSchema> & TComputedCurrentRouteSchema>> = TComputedRouteSchema extends CallApiSchema ? Writeable<TComputedRouteSchema, "deep"> : CallApiSchema;
466
- type JsonPrimitive = boolean | number | string | null | undefined;
467
- type SerializableObject = Record<PropertyKey, unknown>;
468
- type SerializableArray = Array<JsonPrimitive | SerializableObject> | ReadonlyArray<JsonPrimitive | SerializableObject>;
469
- type Body = UnmaskType<Exclude<RequestInit["body"], undefined> | SerializableArray | SerializableObject>;
470
- type InferBodyOption<TSchema$1 extends CallApiSchema> = MakeSchemaOptionRequiredIfDefined<TSchema$1["body"], {
471
- /**
472
- * Body of the request, can be a object or any other supported body type.
473
- */
474
- body?: InferSchemaOutput<TSchema$1["body"], Body>;
475
- }>;
476
- type MethodUnion = UnmaskType<"CONNECT" | "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "TRACE" | AnyString>;
477
- type InferMethodFromURL<TInitURL$1> = string extends TInitURL$1 ? MethodUnion : TInitURL$1 extends `@${infer TMethod extends RouteKeyMethods}/${string}` ? Uppercase<TMethod> : MethodUnion;
478
- type InferMethodOption<TSchema$1 extends CallApiSchema, TInitURL$1> = MakeSchemaOptionRequiredIfDefined<TSchema$1["method"], {
479
- /**
480
- * HTTP method for the request.
481
- * @default "GET"
482
- */
483
- method?: InferSchemaOutput<TSchema$1["method"], InferMethodFromURL<TInitURL$1>>;
484
- }>;
485
- type HeadersOption = UnmaskType<Record<"Authorization", CommonAuthorizationHeaders | undefined> | Record<"Content-Type", CommonContentTypes | undefined> | Record<CommonRequestHeaders, string | undefined> | Record<string, string | undefined> | Array<[string, string]>>;
486
- type InferHeadersOption<TSchema$1 extends CallApiSchema> = MakeSchemaOptionRequiredIfDefined<TSchema$1["headers"], {
487
- /**
488
- * Headers to be used in the request.
489
- */
490
- headers?: InferSchemaOutput<TSchema$1["headers"], HeadersOption> | ((context: {
491
- baseHeaders: NonNullable<HeadersOption>;
492
- }) => InferSchemaOutput<TSchema$1["headers"], HeadersOption>);
493
- }>;
494
- type InferRequestOptions<TSchema$1 extends CallApiSchema, TInitURL$1 extends InferInitURL<BaseCallApiSchemaRoutes, CallApiSchemaConfig>> = InferBodyOption<TSchema$1> & InferHeadersOption<TSchema$1> & InferMethodOption<TSchema$1, TInitURL$1>;
495
- type InferMetaOption<TSchema$1 extends CallApiSchema, TCallApiContext$1 extends CallApiContext> = MakeSchemaOptionRequiredIfDefined<TSchema$1["meta"], {
496
- /**
497
- * - An optional field you can fill with additional information,
498
- * to associate with the request, typically used for logging or tracing.
499
- *
500
- * - A good use case for this, would be to use the info to handle specific cases in any of the shared interceptors.
501
- *
502
- * @example
503
- * ```ts
504
- * const callMainApi = callApi.create({
505
- * baseURL: "https://main-api.com",
506
- * onResponseError: ({ response, options }) => {
507
- * if (options.meta?.userId) {
508
- * console.error(`User ${options.meta.userId} made an error`);
509
- * }
510
- * },
511
- * });
512
- *
513
- * const response = await callMainApi({
514
- * url: "https://example.com/api/data",
515
- * meta: { userId: "123" },
516
- * });
517
- * ```
518
- */
519
- meta?: InferSchemaOutput<TSchema$1["meta"], TCallApiContext$1["Meta"]>;
520
- }>;
521
- type InferQueryOption<TSchema$1 extends CallApiSchema> = MakeSchemaOptionRequiredIfDefined<TSchema$1["query"], {
522
- /**
523
- * Parameters to be appended to the URL (i.e: /:id)
524
- */
525
- query?: InferSchemaOutput<TSchema$1["query"], Query>;
526
- }>;
527
- type EmptyString = "";
528
- type EmptyTuple = readonly [];
529
- type StringTuple = readonly string[];
530
- type PossibleParamNamePatterns = `${string}:${string}` | `${string}{${string}}${"" | AnyString}`;
531
- type ExtractRouteParamNames<TCurrentRoute$1, TParamNamesAccumulator extends StringTuple = EmptyTuple> = TCurrentRoute$1 extends PossibleParamNamePatterns ? TCurrentRoute$1 extends `${infer TRoutePrefix}:${infer TParamAndRemainingRoute}` ? TParamAndRemainingRoute extends `${infer TCurrentParam}/${infer TRemainingRoute}` ? TCurrentParam extends EmptyString ? ExtractRouteParamNames<`${TRoutePrefix}/${TRemainingRoute}`, TParamNamesAccumulator> : ExtractRouteParamNames<`${TRoutePrefix}/${TRemainingRoute}`, [...TParamNamesAccumulator, TCurrentParam]> : TParamAndRemainingRoute extends `${infer TCurrentParam}` ? TCurrentParam extends EmptyString ? ExtractRouteParamNames<TRoutePrefix, TParamNamesAccumulator> : ExtractRouteParamNames<TRoutePrefix, [...TParamNamesAccumulator, TCurrentParam]> : ExtractRouteParamNames<TRoutePrefix, TParamNamesAccumulator> : TCurrentRoute$1 extends `${infer TRoutePrefix}{${infer TCurrentParam}}${infer TRemainingRoute}` ? TCurrentParam extends EmptyString ? ExtractRouteParamNames<`${TRoutePrefix}${TRemainingRoute}`, TParamNamesAccumulator> : ExtractRouteParamNames<`${TRoutePrefix}${TRemainingRoute}`, [...TParamNamesAccumulator, TCurrentParam]> : TParamNamesAccumulator : TParamNamesAccumulator;
532
- type ConvertParamNamesToRecord<TParamNames extends StringTuple> = Prettify<TParamNames extends (readonly [infer TFirstParamName extends string, ...infer TRemainingParamNames extends StringTuple]) ? Record<TFirstParamName, AllowedQueryParamValues> & ConvertParamNamesToRecord<TRemainingParamNames> : NonNullable<unknown>>;
533
- type ConvertParamNamesToTuple<TParamNames extends StringTuple> = TParamNames extends readonly [string, ...infer TRemainingParamNames extends StringTuple] ? [AllowedQueryParamValues, ...ConvertParamNamesToTuple<TRemainingParamNames>] : [];
534
- type InferParamsFromRoute<TCurrentRoute$1> = ExtractRouteParamNames<TCurrentRoute$1> extends StringTuple ? ExtractRouteParamNames<TCurrentRoute$1> extends EmptyTuple ? Params : ConvertParamNamesToRecord<ExtractRouteParamNames<TCurrentRoute$1>> | ConvertParamNamesToTuple<ExtractRouteParamNames<TCurrentRoute$1>> : Params;
535
- type MakeParamsOptionRequired<TParamsSchemaOption extends CallApiSchema["params"], TBaseSchemaRoutes$1 extends BaseCallApiSchemaRoutes, TCurrentRouteSchemaKey$1 extends string, TObject> = MakeSchemaOptionRequiredIfDefined<TParamsSchemaOption, Params extends InferParamsFromRoute<TCurrentRouteSchemaKey$1> ? TObject : TCurrentRouteSchemaKey$1 extends Extract<keyof TBaseSchemaRoutes$1, TCurrentRouteSchemaKey$1> ? undefined extends InferSchemaOutput<TParamsSchemaOption, null> ? TObject : Required<TObject> : TObject>;
536
- type InferParamsOption<TSchema$1 extends CallApiSchema, TBaseSchemaRoutes$1 extends BaseCallApiSchemaRoutes, TCurrentRouteSchemaKey$1 extends string> = MakeParamsOptionRequired<TSchema$1["params"], TBaseSchemaRoutes$1, TCurrentRouteSchemaKey$1, {
537
- /**
538
- * Parameters to be appended to the URL (i.e: /:id)
539
- */
540
- params?: InferSchemaOutput<TSchema$1["params"], InferParamsFromRoute<TCurrentRouteSchemaKey$1>>;
541
- }>;
542
- type InferExtraOptions<TSchema$1 extends CallApiSchema, TBaseSchemaRoutes$1 extends BaseCallApiSchemaRoutes, TCurrentRouteSchemaKey$1 extends string, TCallApiContext$1 extends CallApiContext> = InferMetaOption<TSchema$1, TCallApiContext$1> & InferParamsOption<TSchema$1, TBaseSchemaRoutes$1, TCurrentRouteSchemaKey$1> & InferQueryOption<TSchema$1>;
543
- type InferPluginOptions<TPluginArray$1 extends CallApiPlugin[]> = UnionToIntersection<TPluginArray$1 extends Array<infer TPlugin> ? TPlugin extends CallApiPlugin ? TPlugin["defineExtraOptions"] extends AnyFunction$1<infer TReturnedSchema> ? InferSchemaOutput<TReturnedSchema> : never : never : never>;
544
- type ResultModeOption<TErrorData$1, TResultMode$1 extends ResultModeType> = TErrorData$1 extends false ? {
545
- resultMode: "onlyData";
546
- } : TErrorData$1 extends false | undefined ? {
547
- resultMode?: "onlyData";
548
- } : {
549
- resultMode?: TResultMode$1;
550
- };
551
- type ThrowOnErrorUnion = boolean;
552
- type ThrowOnErrorType<TErrorData$1, TThrowOnError$1 extends ThrowOnErrorUnion> = TThrowOnError$1 | ((context: ErrorContext<{
553
- ErrorData: TErrorData$1;
554
- }>) => TThrowOnError$1);
555
- type ThrowOnErrorOption<TErrorData$1, TThrowOnError$1 extends ThrowOnErrorUnion> = TErrorData$1 extends false ? {
556
- throwOnError: true;
557
- } : TErrorData$1 extends false | undefined ? {
558
- throwOnError?: true;
559
- } : {
560
- throwOnError?: ThrowOnErrorType<TErrorData$1, TThrowOnError$1>;
561
- };
562
- //#endregion
563
- //#region src/types/standard-schema.d.ts
564
- /**
565
- * The Standard Schema interface.
566
- * @see https://github.com/standard-schema/standard-schema
567
- */
568
- interface StandardSchemaV1<Input$1 = unknown, Output$1 = Input$1> {
569
- /**
570
- * The Standard Schema properties.
571
- */
572
- readonly "~standard": StandardSchemaV1.Props<Input$1, Output$1>;
573
- }
574
- declare namespace StandardSchemaV1 {
575
- /**
576
- * The Standard Schema properties interface.
577
- */
578
- interface Props<Input = unknown, Output = Input> {
579
- /**
580
- * Inferred types associated with the schema.
581
- */
582
- readonly types?: Types<Input, Output> | undefined;
583
- /**
584
- * Validates unknown input values.
585
- */
586
- readonly validate: (value: unknown) => Promise<Result<Output>> | Result<Output>;
587
- /**
588
- * The vendor name of the schema library.
589
- */
590
- readonly vendor: string;
591
- /**
592
- * The version number of the standard.
593
- */
594
- readonly version: 1;
595
- }
596
- /**
597
- * The result interface of the validate function.
598
- */
599
- type Result<Output> = FailureResult | SuccessResult<Output>;
600
- /**
601
- * The result interface if validation succeeds.
602
- */
603
- interface SuccessResult<Output> {
604
- /**
605
- * The non-existent issues.
606
- */
607
- readonly issues?: undefined;
608
- /**
609
- * The typed output value.
610
- */
611
- readonly value: Output;
612
- }
613
- /**
614
- * The result interface if validation fails.
615
- */
616
- interface FailureResult {
617
- /**
618
- * The issues of failed validation.
619
- */
620
- readonly issues: readonly Issue[];
621
- }
622
- /**
623
- * The issue interface of the failure output.
624
- */
625
- interface Issue {
626
- /**
627
- * The error message of the issue.
628
- */
629
- readonly message: string;
630
- /**
631
- * The path of the issue, if any.
632
- */
633
- readonly path?: ReadonlyArray<PathSegment | PropertyKey> | undefined;
634
- }
635
- /**
636
- * The path segment interface of the issue.
637
- */
638
- interface PathSegment {
639
- /**
640
- * The key representing a path segment.
641
- */
642
- readonly key: PropertyKey;
643
- }
644
- /**
645
- * The Standard Schema types interface.
646
- */
647
- interface Types<Input = unknown, Output = Input> {
648
- /** The input type of the schema. */
649
- readonly input: Input;
650
- /** The output type of the schema. */
651
- readonly output: Output;
652
- }
653
- /**
654
- * Infers the input type of a Standard Schema.
655
- */
656
- type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["input"];
657
- /**
658
- * Infers the output type of a Standard Schema.
659
- */
660
- type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];
661
- }
662
- //#endregion
663
- //#region src/utils/external/error.d.ts
664
- type HTTPErrorDetails<TErrorData$1> = Pick<CallApiExtraOptions, "defaultHTTPErrorMessage"> & {
665
- errorData: TErrorData$1;
666
- response: Response;
667
- };
668
- declare class HTTPError<TErrorData$1 = Record<string, unknown>> extends Error {
669
- errorData: HTTPErrorDetails<TErrorData$1>["errorData"];
670
- readonly httpErrorSymbol: symbol;
671
- name: "HTTPError";
672
- response: HTTPErrorDetails<TErrorData$1>["response"];
673
- constructor(errorDetails: HTTPErrorDetails<TErrorData$1>, errorOptions?: ErrorOptions);
674
- /**
675
- * @description Checks if the given error is an instance of HTTPError
676
- * @param error - The error to check
677
- * @returns true if the error is an instance of HTTPError, false otherwise
678
- */
679
- static isError<TErrorData>(error: unknown): error is HTTPError<TErrorData$1>;
680
- }
681
- type SafeExtract<TUnion, TKey extends TUnion> = Extract<TUnion, TKey>;
682
- type ValidationErrorDetails = {
683
- /**
684
- * The cause of the validation error.
685
- *
686
- * It's either the name the schema for which validation failed, or the name of the schema config option that led to the validation error.
687
- */
688
- issueCause: "unknown" | `schemaConfig-(${SafeExtract<keyof CallApiSchemaConfig, "strict">})` | keyof CallApiSchema;
689
- /**
690
- * The issues that caused the validation error.
691
- */
692
- issues: readonly StandardSchemaV1.Issue[];
693
- /**
694
- * The response from server, if any.
695
- */
696
- response: Response | null;
697
- };
698
- declare class ValidationError extends Error {
699
- errorData: ValidationErrorDetails["issues"];
700
- issueCause: ValidationErrorDetails["issueCause"];
701
- name: "ValidationError";
702
- response: ValidationErrorDetails["response"];
703
- readonly validationErrorSymbol: symbol;
704
- constructor(details: ValidationErrorDetails, errorOptions?: ErrorOptions);
705
- /**
706
- * @description Checks if the given error is an instance of ValidationError
707
- * @param error - The error to check
708
- * @returns true if the error is an instance of ValidationError, false otherwise
709
- */
710
- static isError(error: unknown): error is ValidationError;
711
- }
712
- //#endregion
713
- //#region src/result.d.ts
714
- type Parser<TData$1> = (responseString: string) => Awaitable<TData$1>;
715
- declare const getResponseType: <TResponse>(response: Response, parser: Parser<TResponse>) => {
716
- arrayBuffer: () => Promise<ArrayBuffer>;
717
- blob: () => Promise<Blob>;
718
- formData: () => Promise<FormData>;
719
- json: () => Promise<TResponse>;
720
- stream: () => ReadableStream<Uint8Array<ArrayBuffer>> | null;
721
- text: () => Promise<string>;
722
- };
723
- type InitResponseTypeMap<TResponse$1 = unknown> = ReturnType<typeof getResponseType<TResponse$1>>;
724
- type ResponseTypeUnion = keyof InitResponseTypeMap;
725
- type ResponseTypePlaceholder = null;
726
- type ResponseTypeType = ResponseTypePlaceholder | ResponseTypeUnion;
727
- type ResponseTypeMap<TResponse$1> = { [Key in keyof InitResponseTypeMap<TResponse$1>]: Awaited<ReturnType<InitResponseTypeMap<TResponse$1>[Key]>> };
728
- type GetResponseType<TResponse$1, TResponseType$1 extends ResponseTypeType, TComputedResponseTypeMap extends ResponseTypeMap<TResponse$1> = ResponseTypeMap<TResponse$1>> = null extends TResponseType$1 ? TComputedResponseTypeMap["json"] : TResponseType$1 extends NonNullable<ResponseTypeType> ? TComputedResponseTypeMap[TResponseType$1] : never;
729
- type CallApiResultSuccessVariant<TData$1> = {
730
- data: NoInfer<TData$1>;
731
- error: null;
732
- response: Response;
733
- };
734
- type PossibleJavaScriptError = UnmaskType<{
735
- errorData: false;
736
- message: string;
737
- name: "AbortError" | "Error" | "SyntaxError" | "TimeoutError" | "TypeError" | AnyString;
738
- originalError: DOMException | Error | SyntaxError | TypeError;
739
- }>;
740
- type PossibleHTTPError<TErrorData$1> = UnmaskType<{
741
- errorData: NoInfer<TErrorData$1>;
742
- message: string;
743
- name: "HTTPError";
744
- originalError: HTTPError;
745
- }>;
746
- type PossibleValidationError = UnmaskType<{
747
- errorData: ValidationError["errorData"];
748
- issueCause: ValidationError["issueCause"];
749
- message: string;
750
- name: "ValidationError";
751
- originalError: ValidationError;
752
- }>;
753
- type PossibleJavaScriptOrValidationError = UnmaskType<PossibleJavaScriptError | PossibleValidationError>;
754
- type CallApiResultErrorVariant<TErrorData$1> = {
755
- data: null;
756
- error: PossibleHTTPError<TErrorData$1>;
757
- response: Response;
758
- } | {
759
- data: null;
760
- error: PossibleJavaScriptOrValidationError;
761
- response: Response | null;
762
- };
763
- type CallApiSuccessOrErrorVariant<TData$1, TError> = CallApiResultErrorVariant<TError> | CallApiResultSuccessVariant<TData$1>;
764
- type ResultModeMapWithoutException<TData$1, TErrorData$1, TResponseType$1 extends ResponseTypeType, TComputedData = GetResponseType<TData$1, TResponseType$1>, TComputedErrorData = GetResponseType<TErrorData$1, TResponseType$1>, TComputedResult$1 extends CallApiSuccessOrErrorVariant<TComputedData, TComputedErrorData> = CallApiSuccessOrErrorVariant<TComputedData, TComputedErrorData>> = UnmaskType<{
765
- all: TComputedResult$1;
766
- onlyData: TComputedResult$1["data"];
767
- onlyResponse: TComputedResult$1["response"];
768
- withoutResponse: DistributiveOmit<TComputedResult$1, "response">;
769
- }>;
770
- type ResultModeMapWithException<TData$1, TResponseType$1 extends ResponseTypeType, TComputedData = GetResponseType<TData$1, TResponseType$1>, TComputedResult$1 extends CallApiResultSuccessVariant<TComputedData> = CallApiResultSuccessVariant<TComputedData>> = {
771
- all: TComputedResult$1;
772
- onlyData: TComputedResult$1["data"];
773
- onlyResponse: TComputedResult$1["response"];
774
- withoutResponse: DistributiveOmit<TComputedResult$1, "response">;
775
- };
776
- type ResultModeMap<TData$1 = DefaultDataType, TErrorData$1 = DefaultDataType, TResponseType$1 extends ResponseTypeType = ResponseTypeType, TThrowOnError$1 extends ThrowOnErrorUnion = DefaultThrowOnError> = TThrowOnError$1 extends true ? ResultModeMapWithException<TData$1, TResponseType$1> : ResultModeMapWithoutException<TData$1, TErrorData$1, TResponseType$1>;
777
- type ResultModePlaceholder = null;
778
- type ResultModeUnion = keyof ResultModeMap;
779
- type ResultModeType = ResultModePlaceholder | ResultModeUnion;
780
- //#endregion
781
- //#region src/retry.d.ts
782
- declare const defaultRetryStatusCodesLookup: () => Readonly<{
783
- 408: "Request Timeout";
784
- 409: "Conflict";
785
- 425: "Too Early";
786
- 429: "Too Many Requests";
787
- 500: "Internal Server Error";
788
- 502: "Bad Gateway";
789
- 503: "Service Unavailable";
790
- 504: "Gateway Timeout";
791
- }>;
792
- type RetryStatusCodes = UnmaskType<AnyNumber | keyof ReturnType<typeof defaultRetryStatusCodesLookup>>;
793
- type RetryCondition<TErrorData$1> = (context: ErrorContext<{
794
- ErrorData: TErrorData$1;
795
- }>) => Awaitable<boolean>;
796
- type RetryOptionKeys<TErrorData$1> = Exclude<keyof RetryOptions<TErrorData$1>, "~retryAttemptCount" | "retry">;
797
- type InnerRetryOptions<TErrorData$1> = { [Key in RetryOptionKeys<TErrorData$1> as RemovePrefix<"retry", Key>]?: RetryOptions<TErrorData$1>[Key] };
798
- interface RetryOptions<TErrorData$1> {
799
- /**
800
- * Keeps track of the number of times the request has already been retried
801
- * @internal
802
- * @deprecated **NOTE**: This property is used internally to track retries. Please abstain from modifying it.
803
- */
804
- readonly ["~retryAttemptCount"]?: number;
805
- /**
806
- * All retry options in a single object instead of separate properties
807
- */
808
- retry?: InnerRetryOptions<TErrorData$1>;
809
- /**
810
- * Number of allowed retry attempts on HTTP errors
811
- * @default 0
812
- */
813
- retryAttempts?: number;
814
- /**
815
- * Callback whose return value determines if a request should be retried or not
816
- */
817
- retryCondition?: RetryCondition<TErrorData$1>;
818
- /**
819
- * Delay between retries in milliseconds
820
- * @default 1000
821
- */
822
- retryDelay?: number | ((currentAttemptCount: number) => number);
823
- /**
824
- * Maximum delay in milliseconds. Only applies to exponential strategy
825
- * @default 10000
826
- */
827
- retryMaxDelay?: number;
828
- /**
829
- * HTTP methods that are allowed to retry
830
- * @default ["GET", "POST"]
831
- */
832
- retryMethods?: MethodUnion[];
833
- /**
834
- * HTTP status codes that trigger a retry
835
- */
836
- retryStatusCodes?: RetryStatusCodes[];
837
- /**
838
- * Strategy to use when retrying
839
- * @default "linear"
840
- */
841
- retryStrategy?: "exponential" | "linear";
842
- }
843
- //#endregion
844
- //#region src/types/common.d.ts
845
- interface Register {}
846
- type GlobalMeta = Register extends {
847
- meta?: infer TMeta extends DefaultMetaObject;
848
- } ? TMeta : DefaultMetaObject;
849
- type CallApiContext = {
850
- Data?: DefaultDataType;
851
- ErrorData?: DefaultDataType;
852
- InferredPluginOptions?: unknown;
853
- Meta?: DefaultMetaObject;
854
- ResultMode?: ResultModeType;
855
- };
856
- type FetchSpecificKeysUnion = Exclude<(typeof fetchSpecificKeys)[number], "body" | "headers" | "method">;
857
- type ModifiedRequestInit = RequestInit & {
858
- duplex?: "half";
859
- };
860
- type CallApiRequestOptions = Prettify<{
861
- /**
862
- * Body of the request, can be a object or any other supported body type.
863
- */
864
- body?: Body;
865
- /**
866
- * Headers to be used in the request.
867
- */
868
- headers?: HeadersOption;
869
- /**
870
- * HTTP method for the request.
871
- * @default "GET"
872
- */
873
- method?: MethodUnion;
874
- } & Pick<ModifiedRequestInit, FetchSpecificKeysUnion>>;
875
- type CallApiRequestOptionsForHooks = Omit<CallApiRequestOptions, "headers"> & {
876
- headers: Record<string, string | undefined>;
877
- };
878
- type SharedExtraOptions<TCallApiContext$1 extends CallApiContext = DefaultCallApiContext, TData$1 = DefaultDataType, TErrorData$1 = DefaultDataType, TResultMode$1 extends ResultModeType = ResultModeType, TThrowOnError$1 extends ThrowOnErrorUnion = DefaultThrowOnError, TResponseType$1 extends ResponseTypeType = ResponseTypeType, TPluginArray$1 extends CallApiPlugin[] = DefaultPluginArray, TComputedPluginOptions = InferPluginOptions<TPluginArray$1> & TCallApiContext$1["InferredPluginOptions"], TComputedInferredPluginOptions extends Pick<Required<CallApiContext>, "InferredPluginOptions"> = {
879
- InferredPluginOptions: TComputedPluginOptions;
880
- }> = DedupeOptions & HookConfigOptions & HooksOrHooksArray<TComputedInferredPluginOptions, TData$1, TErrorData$1> & Middlewares & Partial<TComputedInferredPluginOptions["InferredPluginOptions"]> & ResultModeOption<TErrorData$1, TResultMode$1> & RetryOptions<TErrorData$1> & ThrowOnErrorOption<TErrorData$1, TThrowOnError$1> & URLOptions & {
881
- /**
882
- * Automatically add an Authorization header value.
883
- *
884
- * Supports multiple authentication patterns:
885
- * - String: Direct authorization header value
886
- * - Auth object: Structured authentication configuration
887
- *
888
- * ```
889
- */
890
- auth?: Auth;
891
- /**
892
- * Custom function to serialize request body objects into strings.
893
- *
894
- * Useful for custom serialization formats or when the default JSON
895
- * serialization doesn't meet your needs.
896
- *
897
- * @example
898
- * ```ts
899
- * // Custom form data serialization
900
- * bodySerializer: (data) => {
901
- * const formData = new URLSearchParams();
902
- * Object.entries(data).forEach(([key, value]) => {
903
- * formData.append(key, String(value));
904
- * });
905
- * return formData.toString();
906
- * }
907
- *
908
- * // XML serialization
909
- * bodySerializer: (data) => {
910
- * return `<request>${Object.entries(data)
911
- * .map(([key, value]) => `<${key}>${value}</${key}>`)
912
- * .join('')}</request>`;
913
- * }
914
- *
915
- * // Custom JSON with specific formatting
916
- * bodySerializer: (data) => JSON.stringify(data, null, 2)
917
- * ```
918
- */
919
- bodySerializer?: (bodyData: Record<string, unknown>) => string;
920
- /**
921
- * Whether to clone the response so it can be read multiple times.
922
- *
923
- * By default, response streams can only be consumed once. Enable this when you need
924
- * to read the response in multiple places (e.g., in hooks and main code).
925
- *
926
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Response/clone
927
- * @default false
928
- */
929
- cloneResponse?: boolean;
930
- /**
931
- * Custom fetch implementation to replace the default fetch function.
932
- *
933
- * Useful for testing, adding custom behavior, or using alternative HTTP clients
934
- * that implement the fetch API interface.
935
- *
936
- * @example
937
- * ```ts
938
- * // Use node-fetch in Node.js environments
939
- * import fetch from 'node-fetch';
940
- *
941
- * // Mock fetch for testing
942
- * customFetchImpl: async (url, init) => {
943
- * return new Response(JSON.stringify({ mocked: true }), {
944
- * status: 200,
945
- * headers: { 'Content-Type': 'application/json' }
946
- * });
947
- * }
948
- *
949
- * // Add custom logging to all requests
950
- * customFetchImpl: async (url, init) => {
951
- * console.log(`Fetching: ${url}`);
952
- * const response = await fetch(url, init);
953
- * console.log(`Response: ${response.status}`);
954
- * return response;
955
- * }
956
- *
957
- * // Use with custom HTTP client
958
- * customFetchImpl: async (url, init) => {
959
- * // Convert to your preferred HTTP client format
960
- * return await customHttpClient.request({
961
- * url: url.toString(),
962
- * method: init?.method || 'GET',
963
- * headers: init?.headers,
964
- * body: init?.body
965
- * });
966
- * }
967
- * ```
968
- */
969
- customFetchImpl?: FetchImpl;
970
- /**
971
- * Default HTTP error message when server doesn't provide one.
972
- *
973
- * Can be a static string or a function that receives error context
974
- * to generate dynamic error messages based on the response.
975
- *
976
- * @default "Failed to fetch data from server!"
977
- *
978
- * @example
979
- * ```ts
980
- * // Static error message
981
- * defaultHTTPErrorMessage: "API request failed. Please try again."
982
- *
983
- * // Dynamic error message based on status code
984
- * defaultHTTPErrorMessage: ({ response }) => {
985
- * switch (response.status) {
986
- * case 401: return "Authentication required. Please log in.";
987
- * case 403: return "Access denied. Insufficient permissions.";
988
- * case 404: return "Resource not found.";
989
- * case 429: return "Too many requests. Please wait and try again.";
990
- * case 500: return "Server error. Please contact support.";
991
- * default: return `Request failed with status ${response.status}`;
992
- * }
993
- * }
994
- *
995
- * // Include error data in message
996
- * defaultHTTPErrorMessage: ({ errorData, response }) => {
997
- * const userMessage = errorData?.message || "Unknown error occurred";
998
- * return `${userMessage} (Status: ${response.status})`;
999
- * }
1000
- * ```
1001
- */
1002
- defaultHTTPErrorMessage?: string | ((context: Pick<HTTPError<TErrorData$1>, "errorData" | "response">) => string);
1003
- /**
1004
- * Forces calculation of total byte size from request/response body streams.
1005
- *
1006
- * Useful when the Content-Length header is missing or incorrect, and you need
1007
- * accurate size information for progress tracking or bandwidth monitoring.
1008
- *
1009
- * @default false
1010
- *
1011
- */
1012
- forcefullyCalculateStreamSize?: boolean | {
1013
- request?: boolean;
1014
- response?: boolean;
1015
- };
1016
- /**
1017
- * Optional metadata field for associating additional information with requests.
1018
- *
1019
- * Useful for logging, tracing, or handling specific cases in shared interceptors.
1020
- * The meta object is passed through to all hooks and can be accessed in error handlers.
1021
- *
1022
- * @example
1023
- * ```ts
1024
- * const callMainApi = callApi.create({
1025
- * baseURL: "https://main-api.com",
1026
- * onResponseError: ({ response, options }) => {
1027
- * if (options.meta?.userId) {
1028
- * console.error(`User ${options.meta.userId} made an error`);
1029
- * }
1030
- * },
1031
- * });
1032
- *
1033
- * const response = await callMainApi({
1034
- * url: "https://example.com/api/data",
1035
- * meta: { userId: "123" },
1036
- * });
1037
- *
1038
- * // Use case: Request tracking
1039
- * const result = await callMainApi({
1040
- * url: "https://example.com/api/data",
1041
- * meta: {
1042
- * requestId: generateId(),
1043
- * source: "user-dashboard",
1044
- * priority: "high"
1045
- * }
1046
- * });
1047
- *
1048
- * // Use case: Feature flags
1049
- * const client = callApi.create({
1050
- * baseURL: "https://api.example.com",
1051
- * meta: {
1052
- * features: ["newUI", "betaFeature"],
1053
- * experiment: "variantA"
1054
- * }
1055
- * });
1056
- * ```
1057
- */
1058
- meta?: TCallApiContext$1["Meta"] extends DefaultMetaObject ? TCallApiContext$1["Meta"] : DefaultCallApiContext["Meta"];
1059
- /**
1060
- * Custom function to parse response strings into actual value instead of the default response.json().
1061
- *
1062
- * Useful when you need custom parsing logic for specific response formats.
1063
- *
1064
- * @example
1065
- * ```ts
1066
- * responseParser: (responseString) => {
1067
- * return JSON.parse(responseString);
1068
- * }
1069
- *
1070
- * // Parse XML responses
1071
- * responseParser: (responseString) => {
1072
- * const parser = new DOMParser();
1073
- * const doc = parser.parseFromString(responseString, "text/xml");
1074
- * return xmlToObject(doc);
1075
- * }
1076
- *
1077
- * // Parse CSV responses
1078
- * responseParser: (responseString) => {
1079
- * const lines = responseString.split('\n');
1080
- * const headers = lines[0].split(',');
1081
- * const data = lines.slice(1).map(line => {
1082
- * const values = line.split(',');
1083
- * return headers.reduce((obj, header, index) => {
1084
- * obj[header] = values[index];
1085
- * return obj;
1086
- * }, {});
1087
- * });
1088
- * return data;
1089
- * }
1090
- *
1091
- * ```
1092
- */
1093
- responseParser?: (responseString: string) => Awaitable<TData$1>;
1094
- /**
1095
- * Expected response type, determines how the response body is parsed.
1096
- *
1097
- * Different response types trigger different parsing methods:
1098
- * - **"json"**: Parses as JSON using response.json()
1099
- * - **"text"**: Returns as plain text using response.text()
1100
- * - **"blob"**: Returns as Blob using response.blob()
1101
- * - **"arrayBuffer"**: Returns as ArrayBuffer using response.arrayBuffer()
1102
- * - **"stream"**: Returns the response body stream directly
1103
- *
1104
- * @default "json"
1105
- *
1106
- * @example
1107
- * ```ts
1108
- * // JSON API responses (default)
1109
- * responseType: "json"
1110
- *
1111
- * // Plain text responses
1112
- * responseType: "text"
1113
- * // Usage: const csvData = await callApi("/export.csv", { responseType: "text" });
1114
- *
1115
- * // File downloads
1116
- * responseType: "blob"
1117
- * // Usage: const file = await callApi("/download/file.pdf", { responseType: "blob" });
1118
- *
1119
- * // Binary data
1120
- * responseType: "arrayBuffer"
1121
- * // Usage: const buffer = await callApi("/binary-data", { responseType: "arrayBuffer" });
1122
- *
1123
- * // Streaming responses
1124
- * responseType: "stream"
1125
- * // Usage: const stream = await callApi("/large-dataset", { responseType: "stream" });
1126
- * ```
1127
- */
1128
- responseType?: TResponseType$1;
1129
- /**
1130
- * Controls what data is included in the returned result object.
1131
- *
1132
- * Different modes return different combinations of data, error, and response:
1133
- * - **"all"**: Returns { data, error, response } - complete result information
1134
- * - **"onlyData"**: Returns only data (null for errors)
1135
- *
1136
- * When combined with throwOnError: true, null/error variants are automatically removed:
1137
- * - **"all" + throwOnError: true**: Returns { data, error: null, response } (error property is null, throws instead)
1138
- * - **"onlyData" + throwOnError: true**: Returns data (never null, throws on error)
1139
- *
1140
- * @default "all"
1141
- *
1142
- * @example
1143
- * ```ts
1144
- * // Complete result with all information (default)
1145
- * const { data, error, response } = await callApi("/users", { resultMode: "all" });
1146
- * if (error) {
1147
- * console.error("Request failed:", error);
1148
- * } else {
1149
- * console.log("Users:", data);
1150
- * }
1151
- *
1152
- * // Complete result but throws on errors (throwOnError removes error from type)
1153
- * try {
1154
- * const { data, response } = await callApi("/users", {
1155
- * resultMode: "all",
1156
- * throwOnError: true
1157
- * });
1158
- * console.log("Users:", data); // data is never null here
1159
- * } catch (error) {
1160
- * console.error("Request failed:", error);
1161
- * }
1162
- *
1163
- * // Only data, returns null on errors
1164
- * const users = await callApi("/users", { resultMode: "onlyData" });
1165
- * if (users) {
1166
- * console.log("Users:", users);
1167
- * } else {
1168
- * console.log("Request failed");
1169
- * }
1170
- *
1171
- * // Only data, throws on errors (throwOnError removes null from type)
1172
- * try {
1173
- * const users = await callApi("/users", {
1174
- * resultMode: "onlyData",
1175
- * throwOnError: true
1176
- * });
1177
- * console.log("Users:", users); // users is never null here
1178
- * } catch (error) {
1179
- * console.error("Request failed:", error);
1180
- * }
1181
- * ```
1182
- */
1183
- resultMode?: TResultMode$1;
1184
- /**
1185
- * Controls whether errors are thrown as exceptions or returned in the result.
1186
- *
1187
- * Can be a boolean or a function that receives the error and decides whether to throw.
1188
- * When true, errors are thrown as exceptions instead of being returned in the result object.
1189
- *
1190
- * @default false
1191
- *
1192
- * @example
1193
- * ```ts
1194
- * // Always throw errors
1195
- * throwOnError: true
1196
- * try {
1197
- * const data = await callApi("/users");
1198
- * console.log("Users:", data);
1199
- * } catch (error) {
1200
- * console.error("Request failed:", error);
1201
- * }
1202
- *
1203
- * // Never throw errors (default)
1204
- * throwOnError: false
1205
- * const { data, error } = await callApi("/users");
1206
- * if (error) {
1207
- * console.error("Request failed:", error);
1208
- * }
1209
- *
1210
- * // Conditionally throw based on error type
1211
- * throwOnError: (error) => {
1212
- * // Throw on client errors (4xx) but not server errors (5xx)
1213
- * return error.response?.status >= 400 && error.response?.status < 500;
1214
- * }
1215
- *
1216
- * // Throw only on specific status codes
1217
- * throwOnError: (error) => {
1218
- * const criticalErrors = [401, 403, 404];
1219
- * return criticalErrors.includes(error.response?.status);
1220
- * }
1221
- *
1222
- * // Throw on validation errors but not network errors
1223
- * throwOnError: (error) => {
1224
- * return error.type === "validation";
1225
- * }
1226
- * ```
1227
- */
1228
- throwOnError?: ThrowOnErrorType<TErrorData$1, TThrowOnError$1>;
1229
- /**
1230
- * Request timeout in milliseconds. Request will be aborted if it takes longer.
1231
- *
1232
- * Useful for preventing requests from hanging indefinitely and providing
1233
- * better user experience with predictable response times.
1234
- *
1235
- * @example
1236
- * ```ts
1237
- * // 5 second timeout
1238
- * timeout: 5000
1239
- *
1240
- * // Different timeouts for different endpoints
1241
- * const quickApi = createFetchClient({ timeout: 3000 }); // 3s for fast endpoints
1242
- * const slowApi = createFetchClient({ timeout: 30000 }); // 30s for slow operations
1243
- *
1244
- * // Per-request timeout override
1245
- * await callApi("/quick-data", { timeout: 1000 });
1246
- * await callApi("/slow-report", { timeout: 60000 });
1247
- *
1248
- * // No timeout (use with caution)
1249
- * timeout: 0
1250
- * ```
1251
- */
1252
- timeout?: number;
1253
- };
1254
- type BaseCallApiExtraOptions<TBaseCallApiContext$1 extends CallApiContext = DefaultCallApiContext, TBaseData$1 = DefaultDataType, TBaseErrorData$1 = DefaultDataType, TBaseResultMode$1 extends ResultModeType = ResultModeType, TBaseThrowOnError$1 extends ThrowOnErrorUnion = DefaultThrowOnError, TBaseResponseType$1 extends ResponseTypeType = ResponseTypeType, TBasePluginArray$1 extends CallApiPlugin[] = DefaultPluginArray, TBaseSchemaAndConfig$1 extends BaseCallApiSchemaAndConfig = BaseCallApiSchemaAndConfig> = SharedExtraOptions<TBaseCallApiContext$1, TBaseData$1, TBaseErrorData$1, TBaseResultMode$1, TBaseThrowOnError$1, TBaseResponseType$1, TBasePluginArray$1> & {
1255
- /**
1256
- * Array of base CallApi plugins to extend library functionality.
1257
- *
1258
- * Base plugins are applied to all instances created from this base configuration
1259
- * and provide foundational functionality like authentication, logging, or caching.
1260
- *
1261
- * @example
1262
- * ```ts
1263
- * // Add logging plugin
1264
- *
1265
- * // Create base client with common plugins
1266
- * const callApi = createFetchClient({
1267
- * baseURL: "https://api.example.com",
1268
- * plugins: [loggerPlugin({ enabled: true })]
1269
- * });
1270
- *
1271
- * // All requests inherit base plugins
1272
- * await callApi("/users");
1273
- * await callApi("/posts");
1274
- *
1275
- * ```
1276
- */
1277
- plugins?: TBasePluginArray$1;
1278
- /**
1279
- * Base validation schemas for the client configuration.
1280
- *
1281
- * Defines validation rules for requests and responses that apply to all
1282
- * instances created from this base configuration. Provides type safety
1283
- * and runtime validation for API interactions.
1284
- */
1285
- schema?: TBaseSchemaAndConfig$1;
1286
- /**
1287
- * Controls which configuration parts skip automatic merging between base and instance configs.
1288
- *
1289
- * By default, CallApi automatically merges base configuration with instance configuration.
1290
- * This option allows you to disable automatic merging for specific parts when you need
1291
- * manual control over how configurations are combined.
1292
- *
1293
- * @enum
1294
- * - **"all"**: Disables automatic merging for both request options and extra options
1295
- * - **"options"**: Disables automatic merging of extra options only (hooks, plugins, etc.)
1296
- * - **"request"**: Disables automatic merging of request options only (headers, body, etc.)
1297
- *
1298
- * @example
1299
- * ```ts
1300
- * // Skip all automatic merging - full manual control
1301
- * const client = callApi.create((ctx) => ({
1302
- * skipAutoMergeFor: "all",
1303
- *
1304
- * // Manually decide what to merge
1305
- * baseURL: ctx.options.baseURL, // Keep base URL
1306
- * timeout: 5000, // Override timeout
1307
- * headers: {
1308
- * ...ctx.request.headers, // Merge headers manually
1309
- * "X-Custom": "value" // Add custom header
1310
- * }
1311
- * }));
1312
- *
1313
- * // Skip options merging - manual plugin/hook control
1314
- * const client = callApi.create((ctx) => ({
1315
- * skipAutoMergeFor: "options",
1316
- *
1317
- * // Manually control which plugins to use
1318
- * plugins: [
1319
- * ...ctx.options.plugins?.filter(p => p.name !== "unwanted") || [],
1320
- * customPlugin
1321
- * ],
1322
- *
1323
- * // Request options still auto-merge
1324
- * method: "POST"
1325
- * }));
1326
- *
1327
- * // Skip request merging - manual request control
1328
- * const client = callApi.create((ctx) => ({
1329
- * skipAutoMergeFor: "request",
1330
- *
1331
- * // Extra options still auto-merge (plugins, hooks, etc.)
1332
- *
1333
- * // Manually control request options
1334
- * headers: {
1335
- * "Content-Type": "application/json",
1336
- * // Don't merge base headers
1337
- * },
1338
- * method: ctx.request.method || "GET"
1339
- * }));
1340
- *
1341
- * // Use case: Conditional merging based on request
1342
- * const client = createFetchClient((ctx) => ({
1343
- * skipAutoMergeFor: "options",
1344
- *
1345
- * // Only use auth plugin for protected routes
1346
- * plugins: ctx.initURL.includes("/protected/")
1347
- * ? [...(ctx.options.plugins || []), authPlugin]
1348
- * : ctx.options.plugins?.filter(p => p.name !== "auth") || []
1349
- * }));
1350
- * ```
1351
- */
1352
- skipAutoMergeFor?: "all" | "options" | "request";
1353
- };
1354
- type InferExtendSchemaContext<TBaseSchemaRoutes$1 extends BaseCallApiSchemaRoutes, TCurrentRouteSchemaKey$1 extends string> = {
1355
- baseSchemaRoutes: TBaseSchemaRoutes$1;
1356
- currentRouteSchema: GetCurrentRouteSchema<TBaseSchemaRoutes$1, TCurrentRouteSchemaKey$1>;
1357
- };
1358
- type GetExtendSchemaConfigContext<TBaseSchemaConfig extends CallApiSchemaConfig> = {
1359
- baseSchemaConfig: TBaseSchemaConfig;
1360
- };
1361
- type InferExtendPluginContext<TBasePluginArray$1 extends CallApiPlugin[]> = {
1362
- basePlugins: TBasePluginArray$1;
1363
- };
1364
- type CallApiExtraOptions<TCallApiContext$1 extends CallApiContext = DefaultCallApiContext, TData$1 = DefaultDataType, TErrorData$1 = DefaultDataType, TResultMode$1 extends ResultModeType = ResultModeType, TThrowOnError$1 extends ThrowOnErrorUnion = DefaultThrowOnError, TResponseType$1 extends ResponseTypeType = ResponseTypeType, TBasePluginArray$1 extends CallApiPlugin[] = DefaultPluginArray, TPluginArray$1 extends CallApiPlugin[] = DefaultPluginArray, TBaseSchemaRoutes$1 extends BaseCallApiSchemaRoutes = BaseCallApiSchemaRoutes, TSchema$1 extends CallApiSchema = CallApiSchema, TBaseSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TSchemaConfig$1 extends CallApiSchemaConfig = CallApiSchemaConfig, TCurrentRouteSchemaKey$1 extends string = string, TComputedPluginContext = InferExtendPluginContext<TBasePluginArray$1>, TComputedSchemaContext = InferExtendSchemaContext<TBaseSchemaRoutes$1, TCurrentRouteSchemaKey$1>, TComputedSchemaConfigContext = GetExtendSchemaConfigContext<TBaseSchemaConfig>> = SharedExtraOptions<TCallApiContext$1, TData$1, TErrorData$1, TResultMode$1, TThrowOnError$1, TResponseType$1, TPluginArray$1> & {
1365
- /**
1366
- * Array of instance-specific CallApi plugins or a function to configure plugins.
1367
- *
1368
- * Instance plugins are added to the base plugins and provide functionality
1369
- * specific to this particular API instance. Can be a static array or a function
1370
- * that receives base plugins and returns the instance plugins.
1371
- *
1372
- */
1373
- plugins?: TPluginArray$1 | ((context: TComputedPluginContext) => TPluginArray$1);
1374
- /**
1375
- * For instance-specific validation schemas
1376
- *
1377
- * Defines validation rules specific to this API instance, extending or overriding the base schema.
1378
- *
1379
- * Can be a static schema object or a function that receives base schema context and returns instance schemas.
1380
- *
1381
- */
1382
- schema?: TSchema$1 | ((context: TComputedSchemaContext) => TSchema$1);
1383
- /**
1384
- * Instance-specific schema configuration or a function to configure schema behavior.
1385
- *
1386
- * Controls how validation schemas are applied and behave for this specific API instance.
1387
- * Can override base schema configuration or extend it with instance-specific validation rules.
1388
- *
1389
- */
1390
- schemaConfig?: TSchemaConfig$1 | ((context: TComputedSchemaConfigContext) => TSchemaConfig$1);
1391
- };
1392
- type CallApiExtraOptionsForHooks<TCallApiContext$1 extends CallApiContext = DefaultCallApiContext> = Hooks & Omit<CallApiExtraOptions<TCallApiContext$1>, keyof Hooks>;
1393
- type InstanceContext = {
1394
- initURL: string;
1395
- options: CallApiExtraOptions;
1396
- request: CallApiRequestOptions;
1397
- };
1398
- type BaseCallApiConfig<TBaseCallApiContext$1 extends CallApiContext = DefaultCallApiContext, TBaseData$1 = DefaultDataType, TBaseErrorData$1 = DefaultDataType, TBaseResultMode$1 extends ResultModeType = ResultModeType, TBaseThrowOnError$1 extends ThrowOnErrorUnion = DefaultThrowOnError, TBaseResponseType$1 extends ResponseTypeType = ResponseTypeType, TBaseSchemaAndConfig$1 extends BaseCallApiSchemaAndConfig = BaseCallApiSchemaAndConfig, TBasePluginArray$1 extends CallApiPlugin[] = DefaultPluginArray, TComputedBaseConfig = BaseCallApiExtraOptions<TBaseCallApiContext$1, TBaseData$1, TBaseErrorData$1, TBaseResultMode$1, TBaseThrowOnError$1, TBaseResponseType$1, TBasePluginArray$1, TBaseSchemaAndConfig$1>> = (CallApiRequestOptions & TComputedBaseConfig) | ((context: InstanceContext) => CallApiRequestOptions & TComputedBaseConfig);
1399
- type CallApiConfig<TCallApiContext$1 extends CallApiContext = DefaultCallApiContext, TData$1 = DefaultDataType, TErrorData$1 = DefaultDataType, TResultMode$1 extends ResultModeType = ResultModeType, TThrowOnError$1 extends ThrowOnErrorUnion = DefaultThrowOnError, TResponseType$1 extends ResponseTypeType = ResponseTypeType, TBaseSchemaRoutes$1 extends BaseCallApiSchemaRoutes = BaseCallApiSchemaRoutes, TSchema$1 extends CallApiSchema = CallApiSchema, TBaseSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TSchemaConfig$1 extends CallApiSchemaConfig = CallApiSchemaConfig, TInitURL$1 extends InitURLOrURLObject = InitURLOrURLObject, TCurrentRouteSchemaKey$1 extends string = string, TBasePluginArray$1 extends CallApiPlugin[] = DefaultPluginArray, TPluginArray$1 extends CallApiPlugin[] = DefaultPluginArray> = InferExtraOptions<TSchema$1, TBaseSchemaRoutes$1, TCurrentRouteSchemaKey$1, TCallApiContext$1> & InferRequestOptions<TSchema$1, TInitURL$1> & Omit<CallApiExtraOptions<TCallApiContext$1, TData$1, TErrorData$1, TResultMode$1, TThrowOnError$1, TResponseType$1, TBasePluginArray$1, TPluginArray$1, TBaseSchemaRoutes$1, TSchema$1, TBaseSchemaConfig, TSchemaConfig$1, TCurrentRouteSchemaKey$1>, keyof InferExtraOptions<CallApiSchema, BaseCallApiSchemaRoutes, string, CallApiContext>> & Omit<CallApiRequestOptions, keyof InferRequestOptions<CallApiSchema, string>>;
1400
- //#endregion
1401
- //#region src/stream.d.ts
1402
- type StreamProgressEvent = {
1403
- /**
1404
- * Current chunk of data being streamed
1405
- */
1406
- chunk: Uint8Array;
1407
- /**
1408
- * Progress in percentage
1409
- */
1410
- progress: number;
1411
- /**
1412
- * Total size of data in bytes
1413
- */
1414
- totalBytes: number;
1415
- /**
1416
- * Amount of data transferred so far
1417
- */
1418
- transferredBytes: number;
1419
- };
1420
- declare global {
1421
- interface ReadableStream<R> {
1422
- [Symbol.asyncIterator]: () => AsyncIterableIterator<R>;
1423
- }
1424
- }
1425
- //#endregion
1426
- //#region src/hooks.d.ts
1427
- interface Hooks<TCallApiContext$1 extends Pick<CallApiContext, "Data" | "ErrorData" | "InferredPluginOptions" | "Meta"> = DefaultCallApiContext, TData$1 = TCallApiContext$1["Data"], TErrorData$1 = TCallApiContext$1["ErrorData"]> {
1428
- /**
1429
- * Hook called when any error occurs within the request/response lifecycle.
1430
- *
1431
- * This is a unified error handler that catches both request errors (network failures,
1432
- * timeouts, etc.) and response errors (HTTP error status codes). It's essentially
1433
- * a combination of `onRequestError` and `onResponseError` hooks.
1434
- *
1435
- * @param context - Error context containing error details, request info, and response (if available)
1436
- * @returns Promise or void - Hook can be async or sync
1437
- */
1438
- onError?: (context: ErrorContext<TCallApiContext$1, TErrorData$1>) => Awaitable<unknown>;
1439
- /**
1440
- * Hook called before the HTTP request is sent and before any internal processing of the request object begins.
1441
- *
1442
- * This is the ideal place to modify request headers, add authentication,
1443
- * implement request logging, or perform any setup before the network call.
1444
- *
1445
- * @param context - Request context with mutable request object and configuration
1446
- * @returns Promise or void - Hook can be async or sync
1447
- *
1448
- */
1449
- onRequest?: (context: RequestContext<TCallApiContext$1>) => Awaitable<unknown>;
1450
- /**
1451
- * Hook called when an error occurs during the fetch request itself.
1452
- *
1453
- * This handles network-level errors like connection failures, timeouts,
1454
- * DNS resolution errors, or other issues that prevent getting an HTTP response.
1455
- * Note that HTTP error status codes (4xx, 5xx) are handled by `onResponseError`.
1456
- *
1457
- * @param context - Request error context with error details and null response
1458
- * @returns Promise or void - Hook can be async or sync
1459
- */
1460
- onRequestError?: (context: RequestErrorContext<TCallApiContext$1>) => Awaitable<unknown>;
1461
- /**
1462
- * Hook called just before the HTTP request is sent and after the request has been processed.
1463
- *
1464
- * @param context - Request context with mutable request object and configuration
1465
- */
1466
- onRequestReady?: (context: RequestContext<TCallApiContext$1>) => Awaitable<unknown>;
1467
- /**
1468
- * Hook called during upload stream progress tracking.
1469
- *
1470
- * This hook is triggered when uploading data (like file uploads) and provides
1471
- * progress information about the upload. Useful for implementing progress bars
1472
- * or upload status indicators.
1473
- *
1474
- * @param context - Request stream context with progress event and request instance
1475
- * @returns Promise or void - Hook can be async or sync
1476
- *
1477
- */
1478
- onRequestStream?: (context: RequestStreamContext<TCallApiContext$1>) => Awaitable<unknown>;
1479
- /**
1480
- * Hook called when any HTTP response is received from the API.
1481
- *
1482
- * This hook is triggered for both successful (2xx) and error (4xx, 5xx) responses.
1483
- * It's useful for response logging, metrics collection, or any processing that
1484
- * should happen regardless of response status.
1485
- *
1486
- * @param context - Response context with either success data or error information
1487
- * @returns Promise or void - Hook can be async or sync
1488
- *
1489
- */
1490
- onResponse?: (context: ResponseContext<TCallApiContext$1, TData$1, TErrorData$1>) => Awaitable<unknown>;
1491
- /**
1492
- * Hook called when an HTTP error response (4xx, 5xx) is received from the API.
1493
- *
1494
- * This handles server-side errors where an HTTP response was successfully received
1495
- * but indicates an error condition. Different from `onRequestError` which handles
1496
- * network-level failures.
1497
- *
1498
- * @param context - Response error context with HTTP error details and response
1499
- * @returns Promise or void - Hook can be async or sync
1500
- */
1501
- onResponseError?: (context: ResponseErrorContext<TCallApiContext$1, TErrorData$1>) => Awaitable<unknown>;
1502
- /**
1503
- * Hook called during download stream progress tracking.
1504
- *
1505
- * This hook is triggered when downloading data (like file downloads) and provides
1506
- * progress information about the download. Useful for implementing progress bars
1507
- * or download status indicators.
1508
- *
1509
- * @param context - Response stream context with progress event and response
1510
- * @returns Promise or void - Hook can be async or sync
1511
- *
1512
- */
1513
- onResponseStream?: (context: ResponseStreamContext<TCallApiContext$1>) => Awaitable<unknown>;
1514
- /**
1515
- * Hook called when a request is being retried.
1516
- *
1517
- * This hook is triggered before each retry attempt, providing information about
1518
- * the previous failure and the current retry attempt number. Useful for implementing
1519
- * custom retry logic, exponential backoff, or retry logging.
1520
- *
1521
- * @param context - Retry context with error details and retry attempt count
1522
- * @returns Promise or void - Hook can be async or sync
1523
- *
1524
- */
1525
- onRetry?: (response: RetryContext<TCallApiContext$1, TErrorData$1>) => Awaitable<unknown>;
1526
- /**
1527
- * Hook called when a successful response (2xx status) is received from the API.
1528
- *
1529
- * This hook is triggered only for successful responses and provides access to
1530
- * the parsed response data. Ideal for success logging, caching, or post-processing
1531
- * of successful API responses.
1532
- *
1533
- * @param context - Success context with parsed response data and response object
1534
- * @returns Promise or void - Hook can be async or sync
1535
- *
1536
- */
1537
- onSuccess?: (context: SuccessContext<TCallApiContext$1, TData$1>) => Awaitable<unknown>;
1538
- /**
1539
- * Hook called when a validation error occurs.
1540
- *
1541
- * This hook is triggered when request or response data fails validation against
1542
- * a defined schema. It provides access to the validation error details and can
1543
- * be used for custom error handling, logging, or fallback behavior.
1544
- *
1545
- * @param context - Validation error context with error details and response (if available)
1546
- * @returns Promise or void - Hook can be async or sync
1547
- *
1548
- */
1549
- onValidationError?: (context: ValidationErrorContext<TCallApiContext$1>) => Awaitable<unknown>;
1550
- }
1551
- type HooksOrHooksArray<TCallApiContext$1 extends CallApiContext = DefaultCallApiContext, TData$1 = TCallApiContext$1["Data"], TErrorData$1 = TCallApiContext$1["ErrorData"]> = { [Key in keyof Hooks<TCallApiContext$1, TData$1, TErrorData$1>]: Hooks<TCallApiContext$1, TData$1, TErrorData$1>[Key] | Array<Hooks<TCallApiContext$1, TData$1, TErrorData$1>[Key]> };
1552
- interface HookConfigOptions {
1553
- /**
1554
- * Controls the execution mode of all composed hooks (main + plugin hooks).
1555
- *
1556
- * - **"parallel"**: All hooks execute simultaneously via Promise.all() for better performance
1557
- * - **"sequential"**: All hooks execute one by one in registration order via await in a loop
1558
- *
1559
- * This affects how ALL hooks execute together, regardless of their source (main or plugin).
1560
- *
1561
- * @default "parallel"
1562
- */
1563
- hooksExecutionMode?: "parallel" | "sequential";
1564
- }
1565
- type RequestContext<TCallApiContext$1 extends Pick<CallApiContext, "InferredPluginOptions" | "Meta"> = DefaultCallApiContext> = {
1566
- /**
1567
- * Base configuration object passed to createFetchClient.
1568
- *
1569
- * Contains the foundational configuration that applies to all requests
1570
- * made by this client instance, such as baseURL, default headers, and
1571
- * global options.
1572
- */
1573
- baseConfig: Exclude<BaseCallApiConfig, AnyFunction$1>;
1574
- /**
1575
- * Instance-specific configuration object passed to the callApi instance.
1576
- *
1577
- * Contains configuration specific to this particular API call, which
1578
- * can override or extend the base configuration.
1579
- */
1580
- config: CallApiConfig;
1581
- /**
1582
- * Merged options combining base config, instance config, and default options.
1583
- *
1584
- * This is the final resolved configuration that will be used for the request,
1585
- * with proper precedence applied (instance > base > defaults).
1586
- */
1587
- options: CallApiExtraOptionsForHooks<TCallApiContext$1>;
1588
- /**
1589
- * Merged request object ready to be sent.
1590
- *
1591
- * Contains the final request configuration including URL, method, headers,
1592
- * body, and other fetch options. This object can be modified in onRequest
1593
- * hooks to customize the outgoing request.
1594
- */
1595
- request: CallApiRequestOptionsForHooks;
1596
- };
1597
- type ValidationErrorContext<TCallApiContext$1 extends Pick<CallApiContext, "InferredPluginOptions" | "Meta"> = DefaultCallApiContext> = UnmaskType<RequestContext<TCallApiContext$1> & {
1598
- error: PossibleValidationError;
1599
- response: Response | null;
1600
- }>;
1601
- type SuccessContext<TCallApiContext$1 extends Pick<CallApiContext, "Data" | "InferredPluginOptions" | "Meta"> = DefaultCallApiContext, TData$1 = TCallApiContext$1["Data"]> = UnmaskType<RequestContext<TCallApiContext$1> & {
1602
- data: NoInfer<TData$1>;
1603
- response: Response;
1604
- }>;
1605
- type ResponseContext<TCallApiContext$1 extends Pick<CallApiContext, "Data" | "ErrorData" | "InferredPluginOptions" | "Meta"> = DefaultCallApiContext, TData$1 = TCallApiContext$1["Data"], TErrorData$1 = TCallApiContext$1["ErrorData"]> = UnmaskType<RequestContext<TCallApiContext$1> & (Prettify<CallApiResultSuccessVariant<TData$1>> | Prettify<Extract<CallApiResultErrorVariant<TErrorData$1>, {
1606
- error: PossibleHTTPError<TErrorData$1>;
1607
- }>>)>;
1608
- type RequestErrorContext<TCallApiContext$1 extends Pick<CallApiContext, "InferredPluginOptions" | "Meta"> = DefaultCallApiContext> = RequestContext<TCallApiContext$1> & {
1609
- error: PossibleJavaScriptError;
1610
- response: null;
1611
- };
1612
- type ErrorContext<TCallApiContext$1 extends Pick<CallApiContext, "ErrorData" | "InferredPluginOptions" | "Meta"> = DefaultCallApiContext, TErrorData$1 = TCallApiContext$1["ErrorData"]> = UnmaskType<RequestContext<TCallApiContext$1> & ({
1613
- error: PossibleHTTPError<TErrorData$1>;
1614
- response: Response;
1615
- } | {
1616
- error: PossibleJavaScriptOrValidationError;
1617
- response: Response | null;
1618
- })>;
1619
- type ResponseErrorContext<TCallApiContext$1 extends Pick<CallApiContext, "ErrorData" | "InferredPluginOptions" | "Meta"> = DefaultCallApiContext, TErrorData$1 = TCallApiContext$1["ErrorData"]> = UnmaskType<Extract<ErrorContext<TCallApiContext$1, TErrorData$1>, {
1620
- error: PossibleHTTPError<TErrorData$1>;
1621
- }> & RequestContext<TCallApiContext$1>>;
1622
- type RetryContext<TCallApiContext$1 extends Pick<CallApiContext, "ErrorData" | "InferredPluginOptions" | "Meta"> = DefaultCallApiContext, TErrorData$1 = TCallApiContext$1["ErrorData"]> = UnmaskType<ErrorContext<TCallApiContext$1, TErrorData$1> & {
1623
- retryAttemptCount: number;
1624
- }>;
1625
- type RequestStreamContext<TCallApiContext$1 extends Pick<CallApiContext, "InferredPluginOptions" | "Meta"> = DefaultCallApiContext> = UnmaskType<RequestContext<TCallApiContext$1> & {
1626
- event: StreamProgressEvent;
1627
- requestInstance: Request;
1628
- }>;
1629
- type ResponseStreamContext<TCallApiContext$1 extends Pick<CallApiContext, "InferredPluginOptions" | "Meta"> = DefaultCallApiContext> = UnmaskType<RequestContext<TCallApiContext$1> & {
1630
- event: StreamProgressEvent;
1631
- response: Response;
1632
- }>;
1633
- //#endregion
1634
- //#region src/plugins.d.ts
1635
- type PluginSetupContext<TCallApiContext$1 extends CallApiContext = DefaultCallApiContext> = RequestContext<TCallApiContext$1> & {
1636
- initURL: string;
1637
- };
1638
- type PluginInitResult = Partial<Omit<PluginSetupContext, "initURL" | "request"> & {
1639
- initURL: InitURLOrURLObject;
1640
- request: CallApiRequestOptions;
1641
- }>;
1642
- type PluginHooks<TCallApiContext$1 extends CallApiContext = DefaultCallApiContext, TData$1 = (unknown extends TCallApiContext$1["Data"] ? never : TCallApiContext$1["Data"]), TErrorData$1 = (unknown extends TCallApiContext$1["ErrorData"] ? never : TCallApiContext$1["ErrorData"])> = HooksOrHooksArray<TCallApiContext$1, TData$1, TErrorData$1>;
1643
- interface CallApiPlugin {
1644
- /**
1645
- * Defines additional options that can be passed to callApi
1646
- */
1647
- defineExtraOptions?: (...params: never[]) => unknown;
1648
- /**
1649
- * A description for the plugin
1650
- */
1651
- description?: string;
1652
- /**
1653
- * Hooks for the plugin
1654
- */
1655
- hooks?: PluginHooks | ((context: PluginSetupContext) => Awaitable<PluginHooks>);
1656
- /**
1657
- * A unique id for the plugin
1658
- */
1659
- id: string;
1660
- /**
1661
- * Middlewares that for the plugin
1662
- */
1663
- middlewares?: Middlewares | ((context: PluginSetupContext) => Awaitable<Middlewares>);
1664
- /**
1665
- * A name for the plugin
1666
- */
1667
- name: string;
1668
- /**
1669
- * Base schema for the client.
1670
- */
1671
- schema?: BaseCallApiSchemaAndConfig;
1672
- /**
1673
- * A function that will be called when the plugin is initialized. This will be called before the any of the other internal functions.
1674
- */
1675
- setup?: (context: PluginSetupContext) => Awaitable<PluginInitResult> | Awaitable<void>;
1676
- /**
1677
- * A version for the plugin
1678
- */
1679
- version?: string;
1680
- }
1681
- //#endregion
1682
- //#region src/types/default-types.d.ts
1683
- type DefaultDataType = unknown;
1684
- type DefaultPluginArray = CallApiPlugin[];
1685
- type DefaultThrowOnError = boolean;
1686
- type DefaultMetaObject = Record<string, unknown>;
1687
- type DefaultCallApiContext = Omit<Required<CallApiContext>, "Meta"> & {
1688
- Meta: GlobalMeta;
1689
- };
1690
- //#endregion
1691
- //#region src/validation.d.ts
1692
- type ResultVariant = "infer-input" | "infer-output";
1693
- type InferSchemaResult<TSchema$1, TFallbackResult, TResultVariant extends ResultVariant> = undefined extends TSchema$1 ? TFallbackResult : TSchema$1 extends StandardSchemaV1 ? TResultVariant extends "infer-input" ? StandardSchemaV1.InferInput<TSchema$1> : StandardSchemaV1.InferOutput<TSchema$1> : TSchema$1 extends AnyFunction$1<infer TResult> ? Awaited<TResult> : TFallbackResult;
1694
- type InferSchemaOutput<TSchema$1, TFallbackResult = unknown> = InferSchemaResult<TSchema$1, TFallbackResult, "infer-output">;
1695
- interface CallApiSchemaConfig {
1696
- /**
1697
- * The base url of the schema. By default it's the baseURL of the callApi instance.
1698
- */
1699
- baseURL?: string;
1700
- /**
1701
- * Disables runtime validation for the schema.
1702
- */
1703
- disableRuntimeValidation?: boolean;
1704
- /**
1705
- * If `true`, the original input value will be used instead of the transformed/validated output.
1706
- *
1707
- * This is useful when you want to validate the input but don't want any transformations
1708
- * applied by the validation schema (e.g., type coercion, default values, etc).
1709
- */
1710
- disableValidationOutputApplication?: boolean;
1711
- /**
1712
- * Optional url prefix that will be substituted for the `baseURL` of the schemaConfig at runtime.
1713
- *
1714
- * This allows you to reuse the same schema against different base URLs (for example,
1715
- * swapping between `/api/v1` and `/api/v2`) without redefining the entire schema.
1716
- */
1717
- prefix?: string;
1718
- /**
1719
- * Controls the strictness of API route validation.
1720
- *
1721
- * When true:
1722
- * - Only routes explicitly defined in the schema will be considered valid to typescript and the runtime.
1723
- * - Attempting to call routes not defined in the schema will result in both type errors and runtime validation errors.
1724
- * - Useful for ensuring API calls conform exactly to your schema definition
1725
- *
1726
- * When false or undefined (default):
1727
- * - All routes will be allowed, whether they are defined in the schema or not
1728
- */
1729
- strict?: boolean;
1730
- }
1731
- interface CallApiSchema {
1732
- /**
1733
- * The schema to use for validating the request body.
1734
- */
1735
- body?: StandardSchemaV1<Body | undefined> | ((body: Body) => Awaitable<Body | undefined>);
1736
- /**
1737
- * The schema to use for validating the response data.
1738
- */
1739
- data?: StandardSchemaV1 | ((data: unknown) => unknown);
1740
- /**
1741
- * The schema to use for validating the response error data.
1742
- */
1743
- errorData?: StandardSchemaV1 | ((errorData: unknown) => unknown);
1744
- /**
1745
- * The schema to use for validating the request headers.
1746
- */
1747
- headers?: StandardSchemaV1<HeadersOption | undefined> | ((headers: HeadersOption) => Awaitable<HeadersOption | undefined>);
1748
- /**
1749
- * The schema to use for validating the meta option.
1750
- */
1751
- meta?: StandardSchemaV1<GlobalMeta | undefined> | ((meta: GlobalMeta) => Awaitable<GlobalMeta | undefined>);
1752
- /**
1753
- * The schema to use for validating the request method.
1754
- */
1755
- method?: StandardSchemaV1<MethodUnion | undefined> | ((method: MethodUnion) => Awaitable<MethodUnion | undefined>);
1756
- /**
1757
- * The schema to use for validating the request url parameters.
1758
- */
1759
- params?: StandardSchemaV1<Params | undefined> | ((params: Params) => Awaitable<Params | undefined>);
1760
- /**
1761
- * The schema to use for validating the request url queries.
1762
- */
1763
- query?: StandardSchemaV1<Query | undefined> | ((query: Query) => Awaitable<Query | undefined>);
1764
- }
1765
- declare const routeKeyMethods: readonly ["delete", "get", "patch", "post", "put"];
1766
- type RouteKeyMethods = (typeof routeKeyMethods)[number];
1767
- type RouteKeyMethodsURLUnion = `@${RouteKeyMethods}/`;
1768
- type BaseSchemaRouteKeyPrefixes = FallBackRouteSchemaKey | RouteKeyMethodsURLUnion;
1769
- type BaseCallApiSchemaRoutes = Partial<Record<AnyString | BaseSchemaRouteKeyPrefixes, CallApiSchema>>;
1770
- type BaseCallApiSchemaAndConfig = {
1771
- config?: CallApiSchemaConfig;
1772
- routes: BaseCallApiSchemaRoutes;
1773
- };
1774
- //#endregion
1775
- //#region src/createFetchClient.d.ts
1776
- //#endregion
1777
- //#region src/logger/logger.d.ts
1778
- type ConsoleLikeObject = {
1779
- error: AnyFunction<void>;
1780
- fail?: AnyFunction<void>;
1781
- log: AnyFunction<void>;
1782
- success?: AnyFunction<void>;
1783
- warn?: AnyFunction<void>;
1784
- };
1785
- type LoggerOptions = {
1786
- /**
1787
- * Custom console object
1788
- */
1789
- consoleObject?: ConsoleLikeObject;
1790
- /**
1791
- * Enable or disable the logger
1792
- * @default true
1793
- */
1794
- enabled?: boolean | {
1795
- onError?: boolean;
1796
- onRequest?: boolean;
1797
- onRequestError?: boolean;
1798
- onResponse?: boolean;
1799
- onResponseError?: boolean;
1800
- onRetry?: boolean;
1801
- onSuccess?: boolean;
1802
- onValidationError?: boolean;
1803
- };
1804
- /**
1805
- * Enable or disable verbose mode
1806
- */
1807
- mode?: "basic" | "verbose";
1808
- };
1809
- declare const defaultConsoleObject: ConsoleLikeObject;
1810
- declare const loggerPlugin: (options?: LoggerOptions) => {
1811
- id: "logger";
1812
- name: "Logger";
1813
- version: "1.1.0";
1814
- hooks: {
1815
- onRequest: (ctx: RequestContext<DefaultCallApiContext>) => void;
1816
- onRequestError: (ctx: RequestContext<DefaultCallApiContext> & {
1817
- error: PossibleJavaScriptError;
1818
- response: null;
1819
- }) => void;
1820
- onResponseError: (ctx: RequestContext<DefaultCallApiContext> & {
1821
- error: {
1822
- errorData: never;
1823
- message: string;
1824
- name: "HTTPError";
1825
- originalError: _zayne_labs_callapi_utils0.HTTPError;
1826
- };
1827
- response: Response;
1828
- }) => void;
1829
- onRetry: (ctx: (RequestContext<DefaultCallApiContext> & ({
1830
- error: PossibleJavaScriptOrValidationError;
1831
- response: Response | null;
1832
- } | {
1833
- error: {
1834
- errorData: never;
1835
- message: string;
1836
- name: "HTTPError";
1837
- originalError: _zayne_labs_callapi_utils0.HTTPError;
1838
- };
1839
- response: Response;
1840
- })) & {
1841
- retryAttemptCount: number;
1842
- }) => void;
1843
- onSuccess: (ctx: RequestContext<DefaultCallApiContext> & {
1844
- data: never;
1845
- response: Response;
1846
- }) => void;
1847
- onValidationError: (ctx: RequestContext<DefaultCallApiContext> & {
1848
- error: PossibleValidationError;
1849
- response: Response | null;
1850
- }) => void;
1851
- };
1852
- };
1853
- //#endregion
1854
- export { LoggerOptions, defaultConsoleObject, loggerPlugin };
1855
- //# sourceMappingURL=index.d.ts.map
1
+ import { n as defaultConsoleObject, r as loggerPlugin, t as LoggerOptions } from "./index-BiLuTHUF.js";
2
+ export { LoggerOptions, defaultConsoleObject, loggerPlugin };