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