@zayne-labs/callapi 1.11.26 → 1.11.28

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