@zayne-labs/callapi 1.11.31 → 1.11.33

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.
@@ -37,14 +37,13 @@ type CommonContentTypes = "application/epub+zip" | "application/gzip" | "applica
37
37
  //#region src/auth.d.ts
38
38
  type PossibleAuthValue = Awaitable<string | null | undefined>;
39
39
  type PossibleAuthValueOrGetter = PossibleAuthValue | (() => PossibleAuthValue);
40
- type BearerOrTokenAuth = {
41
- type?: "Bearer";
42
- bearer?: PossibleAuthValueOrGetter;
43
- token?: never;
44
- } | {
45
- type?: "Token";
46
- bearer?: never;
47
- token?: PossibleAuthValueOrGetter;
40
+ type BearerAuth = {
41
+ type: "Bearer";
42
+ value: PossibleAuthValueOrGetter;
43
+ };
44
+ type TokenAuth = {
45
+ type: "Token";
46
+ value: PossibleAuthValueOrGetter;
48
47
  };
49
48
  type BasicAuth = {
50
49
  type: "Basic";
@@ -71,7 +70,7 @@ type CustomAuth = {
71
70
  prefix: PossibleAuthValueOrGetter;
72
71
  value: PossibleAuthValueOrGetter;
73
72
  };
74
- type Auth = PossibleAuthValueOrGetter | BearerOrTokenAuth | BasicAuth | CustomAuth;
73
+ type AuthOption = PossibleAuthValueOrGetter | BearerAuth | TokenAuth | BasicAuth | CustomAuth;
75
74
  //#endregion
76
75
  //#region src/stream.d.ts
77
76
  type StreamProgressEvent = {
@@ -93,255 +92,85 @@ type StreamProgressEvent = {
93
92
  transferredBytes: number;
94
93
  };
95
94
  //#endregion
96
- //#region src/middlewares.d.ts
97
- type FetchImpl = UnmaskType<(input: string | Request | URL, init?: RequestInit) => Promise<Response>>;
98
- interface Middlewares<TCallApiContext extends NoInfer<CallApiContext> = DefaultCallApiContext> {
99
- /**
100
- * Wraps the fetch implementation to intercept requests at the network layer.
101
- *
102
- * Takes a context object containing the current fetch function and returns a new fetch function.
103
- * Use it to cache responses, add logging, handle offline mode, or short-circuit requests etc.
104
- * Multiple middleware compose in order: plugins → base config → per-request.
105
- *
106
- * Unlike `customFetchImpl`, middleware can call through to the original fetch.
107
- *
108
- * @example
109
- * ```ts
110
- * // Cache responses
111
- * const cache = new Map();
112
- *
113
- * fetchMiddleware: (ctx) => async (input, init) => {
114
- * const key = input.toString();
115
- * if (cache.has(key)) return cache.get(key).clone();
116
- *
117
- * const response = await ctx.fetchImpl(input, init);
118
- * cache.set(key, response.clone());
119
- * return response;
120
- * }
121
- *
122
- * // Handle offline
123
- * fetchMiddleware: (ctx) => async (input, init) => {
124
- * if (!navigator.onLine) {
125
- * return new Response('{"error": "offline"}', { status: 503 });
126
- * }
127
- * return ctx.fetchImpl(input, init);
128
- * }
129
- * ```
130
- */
131
- fetchMiddleware?: (context: RequestContext<TCallApiContext> & {
132
- fetchImpl: FetchImpl;
133
- }) => FetchImpl;
134
- }
135
- //#endregion
136
- //#region src/types/conditional-types.d.ts
137
- /**
138
- * @description Makes a type partial if the output type of TSchema is not provided or has undefined in the union, otherwise makes it required
139
- */
140
- type MakeSchemaOptionRequiredIfDefined<TSchemaOption extends CallApiSchema[keyof CallApiSchema], TObject> = undefined extends InferSchemaOutput<TSchemaOption, undefined> ? TObject : Required<TObject>;
141
- type ApplyURLBasedConfig<TSchemaConfig extends CallApiSchemaConfig, TSchemaRouteKeys extends string> = TSchemaConfig["prefix"] extends string ? `${TSchemaConfig["prefix"]}${TSchemaRouteKeys}` : TSchemaConfig["baseURL"] extends string ? `${TSchemaConfig["baseURL"]}${TSchemaRouteKeys}` : TSchemaRouteKeys;
142
- type ApplyStrictConfig<TSchemaConfig extends CallApiSchemaConfig, TSchemaRouteKeys extends string> = TSchemaConfig["strict"] extends true ? TSchemaRouteKeys :
143
- // eslint-disable-next-line perfectionist/sort-union-types -- Don't sort union types
144
- TSchemaRouteKeys | Exclude<InitURLOrURLObject, RouteKeyMethodsURLUnion>;
145
- type ApplySchemaConfiguration<TSchemaConfig extends CallApiSchemaConfig, TSchemaRouteKeys extends string> = ApplyStrictConfig<TSchemaConfig, ApplyURLBasedConfig<TSchemaConfig, TSchemaRouteKeys>>;
146
- type InferAllRouteKeys<TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TSchemaConfig extends CallApiSchemaConfig> = ApplySchemaConfiguration<TSchemaConfig, Exclude<Extract<keyof TBaseSchemaRoutes, string>, FallBackRouteSchemaKey>>;
147
- type InferInitURL<TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TSchemaConfig extends CallApiSchemaConfig> = keyof TBaseSchemaRoutes extends never ? InitURLOrURLObject : InferAllRouteKeys<TBaseSchemaRoutes, TSchemaConfig>;
148
- type GetCurrentRouteSchemaKey<TSchemaConfig extends CallApiSchemaConfig, TPath> = TPath extends URL ? string : TSchemaConfig["baseURL"] extends string ? TPath extends `${TSchemaConfig["baseURL"]}${infer TCurrentRoute}` ? TCurrentRoute extends string ? TCurrentRoute : string : TPath extends `${TSchemaConfig["prefix"]}${infer TCurrentRoute}` ? TCurrentRoute extends string ? TCurrentRoute : string : string : TPath;
149
- type GetCurrentRouteSchema<TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TCurrentRouteSchemaKey extends string, TComputedFallBackRouteSchema = TBaseSchemaRoutes[FallBackRouteSchemaKey], TComputedCurrentRouteSchema = TBaseSchemaRoutes[TCurrentRouteSchemaKey], TComputedRouteSchema extends CallApiSchema = NonNullable<Omit<TComputedFallBackRouteSchema, keyof TComputedCurrentRouteSchema> & TComputedCurrentRouteSchema>> = TComputedRouteSchema extends CallApiSchema ? Writeable<TComputedRouteSchema, "deep"> : CallApiSchema;
150
- type JsonPrimitive = boolean | number | string | null | undefined;
151
- type SerializableObject = Record<PropertyKey, unknown>;
152
- type SerializableArray = Array<JsonPrimitive | SerializableObject> | ReadonlyArray<JsonPrimitive | SerializableObject>;
153
- type Body = UnmaskType<Exclude<RequestInit["body"], undefined> | SerializableArray | SerializableObject>;
154
- type InferBodyOption<TSchema extends CallApiSchema> = MakeSchemaOptionRequiredIfDefined<TSchema["body"], {
155
- /**
156
- * Body of the request, can be a object or any other supported body type.
157
- */
158
- body?: InferSchemaOutput<TSchema["body"], Body>;
159
- }>;
160
- type MethodUnion = UnmaskType<"CONNECT" | "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "TRACE" | AnyString>;
161
- type InferMethodFromURL<TInitURL> = string extends TInitURL ? MethodUnion : TInitURL extends `@${infer TMethod extends RouteKeyMethods}/${string}` ? Uppercase<TMethod> : MethodUnion;
162
- type InferMethodOption<TSchema extends CallApiSchema, TInitURL> = MakeSchemaOptionRequiredIfDefined<TSchema["method"], {
163
- /**
164
- * HTTP method for the request.
165
- * @default "GET"
166
- */
167
- method?: InferSchemaOutput<TSchema["method"], InferMethodFromURL<TInitURL>>;
168
- }>;
169
- type HeadersOption = UnmaskType<Record<"Authorization", CommonAuthorizationHeaders | undefined> | Record<"Content-Type", CommonContentTypes | undefined> | Record<CommonRequestHeaders, string | undefined> | Record<string, string | undefined> | Array<[string, string]>>;
170
- type InferHeadersOption<TSchema extends CallApiSchema> = MakeSchemaOptionRequiredIfDefined<TSchema["headers"], {
171
- /**
172
- * Headers to be used in the request.
173
- */
174
- headers?: InferSchemaOutput<TSchema["headers"], HeadersOption> | ((context: {
175
- baseHeaders: NonNullable<HeadersOption>;
176
- }) => InferSchemaOutput<TSchema["headers"], HeadersOption>);
177
- }>;
178
- type InferRequestOptions<TSchema extends CallApiSchema, TInitURL extends InferInitURL<BaseCallApiSchemaRoutes, CallApiSchemaConfig>> = InferBodyOption<TSchema> & InferHeadersOption<TSchema> & InferMethodOption<TSchema, TInitURL>;
179
- type InferMetaOption<TSchema extends CallApiSchema, TCallApiContext extends CallApiContext> = MakeSchemaOptionRequiredIfDefined<TSchema["meta"], {
180
- /**
181
- * - An optional field you can fill with additional information,
182
- * to associate with the request, typically used for logging or tracing.
183
- *
184
- * - A good use case for this, would be to use the info to handle specific cases in any of the shared interceptors.
185
- *
186
- * @example
187
- * ```ts
188
- * const callMainApi = callApi.create({
189
- * baseURL: "https://main-api.com",
190
- * onResponseError: ({ response, options }) => {
191
- * if (options.meta?.userId) {
192
- * console.error(`User ${options.meta.userId} made an error`);
193
- * }
194
- * },
195
- * });
196
- *
197
- * const response = await callMainApi({
198
- * url: "https://example.com/api/data",
199
- * meta: { userId: "123" },
200
- * });
201
- * ```
202
- */
203
- meta?: InferSchemaOutput<TSchema["meta"], TCallApiContext["Meta"]>;
204
- }>;
205
- type InferQueryOption<TSchema extends CallApiSchema> = MakeSchemaOptionRequiredIfDefined<TSchema["query"], {
206
- /**
207
- * Parameters to be appended to the URL (i.e: /:id)
208
- */
209
- query?: InferSchemaOutput<TSchema["query"], Query>;
210
- }>;
211
- type EmptyString = "";
212
- type EmptyTuple = readonly [];
213
- type StringTuple = readonly string[];
214
- type PossibleParamNamePatterns = `${string}:${string}` | `${string}{${string}}${"" | AnyString}`;
215
- 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;
216
- type ConvertParamNamesToRecord<TParamNames extends StringTuple> = Prettify<TParamNames extends (readonly [infer TFirstParamName extends string, ...infer TRemainingParamNames extends StringTuple]) ? Record<TFirstParamName, AllowedQueryParamValues> & ConvertParamNamesToRecord<TRemainingParamNames> : NonNullable<unknown>>;
217
- type ConvertParamNamesToTuple<TParamNames extends StringTuple> = TParamNames extends readonly [string, ...infer TRemainingParamNames extends StringTuple] ? [AllowedQueryParamValues, ...ConvertParamNamesToTuple<TRemainingParamNames>] : [];
218
- type InferParamsFromRoute<TCurrentRoute$1> = ExtractRouteParamNames<TCurrentRoute$1> extends StringTuple ? ExtractRouteParamNames<TCurrentRoute$1> extends EmptyTuple ? Params : ConvertParamNamesToRecord<ExtractRouteParamNames<TCurrentRoute$1>> | ConvertParamNamesToTuple<ExtractRouteParamNames<TCurrentRoute$1>> : Params;
219
- type MakeParamsOptionRequired<TParamsSchemaOption extends CallApiSchema["params"], TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TCurrentRouteSchemaKey extends string, TObject> = MakeSchemaOptionRequiredIfDefined<TParamsSchemaOption, Params extends InferParamsFromRoute<TCurrentRouteSchemaKey> ? TObject : TCurrentRouteSchemaKey extends Extract<keyof TBaseSchemaRoutes, TCurrentRouteSchemaKey> ? undefined extends InferSchemaOutput<TParamsSchemaOption, null> ? TObject : Required<TObject> : TObject>;
220
- type InferParamsOption<TSchema extends CallApiSchema, TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TCurrentRouteSchemaKey extends string> = MakeParamsOptionRequired<TSchema["params"], TBaseSchemaRoutes, TCurrentRouteSchemaKey, {
221
- /**
222
- * Parameters to be appended to the URL (i.e: /:id)
223
- */
224
- params?: InferSchemaOutput<TSchema["params"], InferParamsFromRoute<TCurrentRouteSchemaKey>>;
225
- }>;
226
- type InferExtraOptions<TSchema extends CallApiSchema, TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TCurrentRouteSchemaKey extends string, TCallApiContext extends CallApiContext> = InferMetaOption<TSchema, TCallApiContext> & InferParamsOption<TSchema, TBaseSchemaRoutes, TCurrentRouteSchemaKey> & InferQueryOption<TSchema>;
227
- type InferPluginExtraOptions<TPluginArray extends CallApiPlugin[]> = UnionToIntersection<TPluginArray extends Array<infer TPlugin> ? TPlugin extends CallApiPlugin ? TPlugin["defineExtraOptions"] extends AnyFunction<infer TReturnedSchema> ? InferSchemaOutput<TReturnedSchema> : never : never : never>;
228
- type ResultModeOption<TErrorData, TResultMode extends ResultModeType> = TErrorData extends false ? {
229
- resultMode: "onlyData";
230
- } : TErrorData extends false | undefined ? {
231
- resultMode?: "onlyData";
232
- } : {
233
- resultMode?: TResultMode;
234
- };
235
- type ThrowOnErrorUnion = boolean;
236
- type ThrowOnErrorType<TErrorData, TThrowOnError extends ThrowOnErrorUnion> = TThrowOnError | ((context: ErrorContext<{
237
- ErrorData: TErrorData;
238
- }>) => TThrowOnError);
239
- type ThrowOnErrorOption<TErrorData, TThrowOnError extends ThrowOnErrorUnion> = TErrorData extends false ? {
240
- throwOnError: true;
241
- } : TErrorData extends false | undefined ? {
242
- throwOnError?: true;
243
- } : {
244
- throwOnError?: ThrowOnErrorType<TErrorData, TThrowOnError>;
245
- };
246
- //#endregion
247
95
  //#region src/types/standard-schema.d.ts
248
96
  /**
249
97
  * The Standard Schema interface.
250
98
  * @see https://github.com/standard-schema/standard-schema
251
99
  */
252
- interface StandardSchemaV1<Input = unknown, Output = Input> {
253
- /**
254
- * The Standard Schema properties.
255
- */
256
- readonly "~standard": StandardSchemaV1.Props<Input, Output>;
100
+ /** The Standard Typed interface. This is a base type extended by other specs. */
101
+ interface StandardTypedV1<Input = unknown, Output = Input> {
102
+ /** The Standard properties. */
103
+ readonly "~standard": StandardTypedV1.Props<Input, Output>;
257
104
  }
258
- declare namespace StandardSchemaV1 {
259
- /**
260
- * The Standard Schema properties interface.
261
- */
105
+ declare namespace StandardTypedV1 {
106
+ /** The Standard Typed properties interface. */
262
107
  interface Props<Input = unknown, Output = Input> {
263
- /**
264
- * Inferred types associated with the schema.
265
- */
108
+ /** Inferred types associated with the schema. */
266
109
  readonly types?: Types<Input, Output> | undefined;
267
- /**
268
- * Validates unknown input values.
269
- */
270
- readonly validate: (value: unknown) => Promise<Result<Output>> | Result<Output>;
271
- /**
272
- * The vendor name of the schema library.
273
- */
110
+ /** The vendor name of the schema library. */
274
111
  readonly vendor: string;
275
- /**
276
- * The version number of the standard.
277
- */
112
+ /** The version number of the standard. */
278
113
  readonly version: 1;
279
114
  }
280
- /**
281
- * The result interface of the validate function.
282
- */
115
+ /** The Standard Typed types interface. */
116
+ interface Types<Input = unknown, Output = Input> {
117
+ /** The input type of the schema. */
118
+ readonly input: Input;
119
+ /** The output type of the schema. */
120
+ readonly output: Output;
121
+ }
122
+ /** Infers the input type of a Standard Typed. */
123
+ type InferInput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["input"];
124
+ /** Infers the output type of a Standard Typed. */
125
+ type InferOutput<Schema extends StandardTypedV1> = NonNullable<Schema["~standard"]["types"]>["output"];
126
+ }
127
+ /** The Standard Schema interface. */
128
+ interface StandardSchemaV1<Input = unknown, Output = Input> {
129
+ /** The Standard Schema properties. */
130
+ readonly "~standard": StandardSchemaV1.Props<Input, Output>;
131
+ }
132
+ declare namespace StandardSchemaV1 {
133
+ /** The Standard Schema properties interface. */
134
+ interface Props<Input = unknown, Output = Input> extends StandardTypedV1.Props<Input, Output> {
135
+ /** Validates unknown input values. */
136
+ readonly validate: (value: unknown, options?: StandardSchemaV1.Options) => Promise<Result<Output>> | Result<Output>;
137
+ }
138
+ /** The result interface of the validate function. */
283
139
  type Result<Output> = FailureResult | SuccessResult<Output>;
284
- /**
285
- * The result interface if validation succeeds.
286
- */
140
+ /** The result interface if validation succeeds. */
287
141
  interface SuccessResult<Output> {
288
- /**
289
- * The non-existent issues.
290
- */
142
+ /** A falsy value for `issues` indicates success. */
291
143
  readonly issues?: undefined;
292
- /**
293
- * The typed output value.
294
- */
144
+ /** The typed output value. */
295
145
  readonly value: Output;
296
146
  }
297
- /**
298
- * The result interface if validation fails.
299
- */
147
+ interface Options {
148
+ /** Explicit support for additional vendor-specific parameters, if needed. */
149
+ readonly libraryOptions?: Record<string, unknown> | undefined;
150
+ }
151
+ /** The result interface if validation fails. */
300
152
  interface FailureResult {
301
- /**
302
- * The issues of failed validation.
303
- */
153
+ /** The issues of failed validation. */
304
154
  readonly issues: readonly Issue[];
305
155
  }
306
- /**
307
- * The issue interface of the failure output.
308
- */
156
+ /** The issue interface of the failure output. */
309
157
  interface Issue {
310
- /**
311
- * The error message of the issue.
312
- */
158
+ /** The error message of the issue. */
313
159
  readonly message: string;
314
- /**
315
- * The path of the issue, if any.
316
- */
160
+ /** The path of the issue, if any. */
317
161
  readonly path?: ReadonlyArray<PathSegment | PropertyKey> | undefined;
318
162
  }
319
- /**
320
- * The path segment interface of the issue.
321
- */
163
+ /** The path segment interface of the issue. */
322
164
  interface PathSegment {
323
- /**
324
- * The key representing a path segment.
325
- */
165
+ /** The key representing a path segment. */
326
166
  readonly key: PropertyKey;
327
167
  }
328
- /**
329
- * The Standard Schema types interface.
330
- */
331
- interface Types<Input = unknown, Output = Input> {
332
- /** The input type of the schema. */
333
- readonly input: Input;
334
- /** The output type of the schema. */
335
- readonly output: Output;
336
- }
337
- /**
338
- * Infers the input type of a Standard Schema.
339
- */
340
- type InferInput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["input"];
341
- /**
342
- * Infers the output type of a Standard Schema.
343
- */
344
- type InferOutput<Schema extends StandardSchemaV1> = NonNullable<Schema["~standard"]["types"]>["output"];
168
+ /** The Standard types interface. */
169
+ type Types<Input = unknown, Output = Input> = StandardTypedV1.Types<Input, Output>;
170
+ /** Infers the input type of a Standard. */
171
+ type InferInput<Schema extends StandardTypedV1> = StandardTypedV1.InferInput<Schema>;
172
+ /** Infers the output type of a Standard. */
173
+ type InferOutput<Schema extends StandardTypedV1> = StandardTypedV1.InferOutput<Schema>;
345
174
  }
346
175
  //#endregion
347
176
  //#region src/validation.d.ts
@@ -387,6 +216,7 @@ interface CallApiSchemaConfig {
387
216
  strict?: boolean;
388
217
  }
389
218
  interface CallApiSchema {
219
+ auth?: StandardSchemaV1<AuthOption | undefined> | ((auth: AuthOption) => Awaitable<AuthOption | undefined>);
390
220
  /**
391
221
  * The schema to use for validating the request body.
392
222
  */
@@ -550,6 +380,184 @@ interface URLOptions {
550
380
  query?: Query;
551
381
  }
552
382
  //#endregion
383
+ //#region src/types/conditional-types.d.ts
384
+ /**
385
+ * @description Makes a type partial if the output type of TSchema is not provided or has undefined in the union, otherwise makes it required
386
+ */
387
+ type MakeSchemaOptionRequiredIfDefined<TSchemaOption extends CallApiSchema[keyof CallApiSchema], TObject> = undefined extends InferSchemaOutput<TSchemaOption, undefined> ? TObject : Required<TObject>;
388
+ type ApplyURLBasedConfig<TSchemaConfig extends CallApiSchemaConfig, TSchemaRouteKeys extends string> = TSchemaConfig["prefix"] extends string ? `${TSchemaConfig["prefix"]}${TSchemaRouteKeys}` : TSchemaConfig["baseURL"] extends string ? `${TSchemaConfig["baseURL"]}${TSchemaRouteKeys}` : TSchemaRouteKeys;
389
+ type ApplyStrictConfig<TSchemaConfig extends CallApiSchemaConfig, TSchemaRouteKeys extends string> = TSchemaConfig["strict"] extends true ? TSchemaRouteKeys :
390
+ // eslint-disable-next-line perfectionist/sort-union-types -- Don't sort union types
391
+ TSchemaRouteKeys | Exclude<InitURLOrURLObject, RouteKeyMethodsURLUnion>;
392
+ type ApplySchemaConfiguration<TSchemaConfig extends CallApiSchemaConfig, TSchemaRouteKeys extends string> = ApplyStrictConfig<TSchemaConfig, ApplyURLBasedConfig<TSchemaConfig, TSchemaRouteKeys>>;
393
+ type InferAllRouteKeys<TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TSchemaConfig extends CallApiSchemaConfig> = ApplySchemaConfiguration<TSchemaConfig, Exclude<Extract<keyof TBaseSchemaRoutes, string>, FallBackRouteSchemaKey>>;
394
+ type InferInitURL<TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TSchemaConfig extends CallApiSchemaConfig> = keyof TBaseSchemaRoutes extends never ? InitURLOrURLObject : InferAllRouteKeys<TBaseSchemaRoutes, TSchemaConfig>;
395
+ type GetCurrentRouteSchemaKey<TSchemaConfig extends CallApiSchemaConfig, TPath> = TPath extends URL ? string : TSchemaConfig["baseURL"] extends string ? TPath extends `${TSchemaConfig["baseURL"]}${infer TCurrentRoute}` ? TCurrentRoute extends string ? TCurrentRoute : string : TPath extends `${TSchemaConfig["prefix"]}${infer TCurrentRoute}` ? TCurrentRoute extends string ? TCurrentRoute : string : string : TPath;
396
+ type GetCurrentRouteSchema<TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TCurrentRouteSchemaKey extends string, TComputedFallBackRouteSchema = TBaseSchemaRoutes[FallBackRouteSchemaKey], TComputedCurrentRouteSchema = TBaseSchemaRoutes[TCurrentRouteSchemaKey], TComputedRouteSchema extends CallApiSchema = NonNullable<Omit<TComputedFallBackRouteSchema, keyof TComputedCurrentRouteSchema> & TComputedCurrentRouteSchema>> = TComputedRouteSchema extends CallApiSchema ? Writeable<TComputedRouteSchema, "deep"> : CallApiSchema;
397
+ type JsonPrimitive = boolean | number | string | null | undefined;
398
+ type SerializableObject = Record<PropertyKey, unknown>;
399
+ type SerializableArray = Array<JsonPrimitive | SerializableObject> | ReadonlyArray<JsonPrimitive | SerializableObject>;
400
+ type Body = UnmaskType<Exclude<RequestInit["body"], undefined> | SerializableArray | SerializableObject>;
401
+ type InferBodyOption<TSchema extends CallApiSchema> = MakeSchemaOptionRequiredIfDefined<TSchema["body"], {
402
+ /**
403
+ * Body of the request, can be a object or any other supported body type.
404
+ */
405
+ body?: InferSchemaOutput<TSchema["body"], Body>;
406
+ }>;
407
+ type MethodUnion = UnmaskType<"CONNECT" | "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "TRACE" | AnyString>;
408
+ type InferMethodFromURL<TInitURL> = string extends TInitURL ? MethodUnion : TInitURL extends `@${infer TMethod extends RouteKeyMethods}/${string}` ? Uppercase<TMethod> : MethodUnion;
409
+ type InferMethodOption<TSchema extends CallApiSchema, TInitURL> = MakeSchemaOptionRequiredIfDefined<TSchema["method"], {
410
+ /**
411
+ * HTTP method for the request.
412
+ * @default "GET"
413
+ */
414
+ method?: InferSchemaOutput<TSchema["method"], InferMethodFromURL<TInitURL>>;
415
+ }>;
416
+ type HeadersOption = UnmaskType<Headers | Record<"Authorization", CommonAuthorizationHeaders | undefined> | Record<"Content-Type", CommonContentTypes | undefined> | Record<CommonRequestHeaders, string | undefined> | Record<string, string | undefined> | Array<[string, string]>>;
417
+ type InferHeadersOption<TSchema extends CallApiSchema> = MakeSchemaOptionRequiredIfDefined<TSchema["headers"], {
418
+ /**
419
+ * Headers to be used in the request.
420
+ */
421
+ headers?: InferSchemaOutput<TSchema["headers"], HeadersOption> | ((context: {
422
+ baseHeaders: Extract<HeadersOption, Record<string, unknown>>;
423
+ }) => InferSchemaOutput<TSchema["headers"], HeadersOption>);
424
+ }>;
425
+ type InferRequestOptions<TSchema extends CallApiSchema, TInitURL extends InferInitURL<BaseCallApiSchemaRoutes, CallApiSchemaConfig>> = InferBodyOption<TSchema> & InferHeadersOption<TSchema> & InferMethodOption<TSchema, TInitURL>;
426
+ type InferMetaOption<TSchema extends CallApiSchema, TCallApiContext extends CallApiContext> = MakeSchemaOptionRequiredIfDefined<TSchema["meta"], {
427
+ /**
428
+ * - An optional field you can fill with additional information,
429
+ * to associate with the request, typically used for logging or tracing.
430
+ *
431
+ * - A good use case for this, would be to use the info to handle specific cases in any of the shared interceptors.
432
+ *
433
+ * @example
434
+ * ```ts
435
+ * const callMainApi = callApi.create({
436
+ * baseURL: "https://main-api.com",
437
+ * onResponseError: ({ response, options }) => {
438
+ * if (options.meta?.userId) {
439
+ * console.error(`User ${options.meta.userId} made an error`);
440
+ * }
441
+ * },
442
+ * });
443
+ *
444
+ * const response = await callMainApi({
445
+ * url: "https://example.com/api/data",
446
+ * meta: { userId: "123" },
447
+ * });
448
+ * ```
449
+ */
450
+ meta?: InferSchemaOutput<TSchema["meta"], TCallApiContext["Meta"]>;
451
+ }>;
452
+ type InferAuthOption<TSchema extends CallApiSchema> = MakeSchemaOptionRequiredIfDefined<TSchema["auth"], {
453
+ /**
454
+ * Automatically add an Authorization header value.
455
+ *
456
+ * Supports multiple authentication patterns:
457
+ * - String: Direct authorization header value
458
+ * - Auth object: Structured authentication configuration
459
+ *
460
+ * @example
461
+ * ```ts
462
+ * const callMainApi = callApi.create({
463
+ * baseURL: "https://main-api.com",
464
+ * onRequest: ({ options }) => {
465
+ * if (options.auth) {
466
+ * options.headers.Authorization = options.auth;
467
+ * }
468
+ * },
469
+ * });
470
+ *
471
+ * const response = await callMainApi({
472
+ * url: "https://example.com/api/data",
473
+ * auth: "Bearer 123456",
474
+ * });
475
+ * ```
476
+ */
477
+ auth?: InferSchemaOutput<TSchema["auth"], AuthOption>;
478
+ }>;
479
+ type InferQueryOption<TSchema extends CallApiSchema> = MakeSchemaOptionRequiredIfDefined<TSchema["query"], {
480
+ /**
481
+ * Parameters to be appended to the URL (i.e: /:id)
482
+ */
483
+ query?: InferSchemaOutput<TSchema["query"], Query>;
484
+ }>;
485
+ type EmptyString = "";
486
+ type EmptyTuple = readonly [];
487
+ type StringTuple = readonly string[];
488
+ type PossibleParamNamePatterns = `${string}:${string}` | `${string}{${string}}${"" | AnyString}`;
489
+ type ExtractRouteParamNames<TCurrentRoute, TParamNamesAccumulator extends StringTuple = EmptyTuple> = TCurrentRoute extends PossibleParamNamePatterns ? TCurrentRoute extends `${infer TRoutePrefix}:${infer TParamAndRemainingRoute}` ? TParamAndRemainingRoute extends `${infer TCurrentParam}/${infer TRemainingRoute}` ? TCurrentParam extends EmptyString ? ExtractRouteParamNames<`${TRoutePrefix}/${TRemainingRoute}`, TParamNamesAccumulator> : ExtractRouteParamNames<`${TRoutePrefix}/${TRemainingRoute}`, [...TParamNamesAccumulator, TCurrentParam]> : TParamAndRemainingRoute extends `${infer TCurrentParam}` ? TCurrentParam extends EmptyString ? ExtractRouteParamNames<TRoutePrefix, TParamNamesAccumulator> : ExtractRouteParamNames<TRoutePrefix, [...TParamNamesAccumulator, TCurrentParam]> : ExtractRouteParamNames<TRoutePrefix, TParamNamesAccumulator> : TCurrentRoute extends `${infer TRoutePrefix}{${infer TCurrentParam}}${infer TRemainingRoute}` ? TCurrentParam extends EmptyString ? ExtractRouteParamNames<`${TRoutePrefix}${TRemainingRoute}`, TParamNamesAccumulator> : ExtractRouteParamNames<`${TRoutePrefix}${TRemainingRoute}`, [...TParamNamesAccumulator, TCurrentParam]> : TParamNamesAccumulator : TParamNamesAccumulator;
490
+ type ConvertParamNamesToRecord<TParamNames extends StringTuple> = Prettify<TParamNames extends (readonly [infer TFirstParamName extends string, ...infer TRemainingParamNames extends StringTuple]) ? Record<TFirstParamName, AllowedQueryParamValues> & ConvertParamNamesToRecord<TRemainingParamNames> : NonNullable<unknown>>;
491
+ type ConvertParamNamesToTuple<TParamNames extends StringTuple> = TParamNames extends readonly [string, ...infer TRemainingParamNames extends StringTuple] ? [AllowedQueryParamValues, ...ConvertParamNamesToTuple<TRemainingParamNames>] : [];
492
+ type InferParamsFromRoute<TCurrentRoute> = ExtractRouteParamNames<TCurrentRoute> extends StringTuple ? ExtractRouteParamNames<TCurrentRoute> extends EmptyTuple ? Params : ConvertParamNamesToRecord<ExtractRouteParamNames<TCurrentRoute>> | ConvertParamNamesToTuple<ExtractRouteParamNames<TCurrentRoute>> : Params;
493
+ type MakeParamsOptionRequired<TParamsSchemaOption extends CallApiSchema["params"], TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TCurrentRouteSchemaKey extends string, TObject> = MakeSchemaOptionRequiredIfDefined<TParamsSchemaOption, Params extends InferParamsFromRoute<TCurrentRouteSchemaKey> ? TObject : TCurrentRouteSchemaKey extends Extract<keyof TBaseSchemaRoutes, TCurrentRouteSchemaKey> ? undefined extends InferSchemaOutput<TParamsSchemaOption, null> ? TObject : Required<TObject> : TObject>;
494
+ type InferParamsOption<TSchema extends CallApiSchema, TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TCurrentRouteSchemaKey extends string> = MakeParamsOptionRequired<TSchema["params"], TBaseSchemaRoutes, TCurrentRouteSchemaKey, {
495
+ /**
496
+ * Parameters to be appended to the URL (i.e: /:id)
497
+ */
498
+ params?: InferSchemaOutput<TSchema["params"], InferParamsFromRoute<TCurrentRouteSchemaKey>>;
499
+ }>;
500
+ type InferExtraOptions<TSchema extends CallApiSchema, TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TCurrentRouteSchemaKey extends string, TCallApiContext extends CallApiContext> = InferAuthOption<TSchema> & InferMetaOption<TSchema, TCallApiContext> & InferParamsOption<TSchema, TBaseSchemaRoutes, TCurrentRouteSchemaKey> & InferQueryOption<TSchema>;
501
+ type InferPluginExtraOptions<TPluginArray extends CallApiPlugin[]> = UnionToIntersection<TPluginArray extends Array<infer TPlugin> ? TPlugin extends CallApiPlugin ? TPlugin["defineExtraOptions"] extends AnyFunction<infer TReturnedSchema> ? InferSchemaOutput<TReturnedSchema> : never : never : never>;
502
+ type ResultModeOption<TErrorData, TResultMode extends ResultModeType> = TErrorData extends false ? {
503
+ resultMode: "onlyData";
504
+ } : TErrorData extends false | undefined ? {
505
+ resultMode?: "onlyData";
506
+ } : {
507
+ resultMode?: TResultMode;
508
+ };
509
+ type ThrowOnErrorUnion = boolean;
510
+ type ThrowOnErrorType<TErrorData, TThrowOnError extends ThrowOnErrorUnion> = TThrowOnError | ((context: ErrorContext<{
511
+ ErrorData: TErrorData;
512
+ }>) => TThrowOnError);
513
+ type ThrowOnErrorOption<TErrorData, TThrowOnError extends ThrowOnErrorUnion> = TErrorData extends false ? {
514
+ throwOnError: true;
515
+ } : TErrorData extends false | undefined ? {
516
+ throwOnError?: true;
517
+ } : {
518
+ throwOnError?: ThrowOnErrorType<TErrorData, TThrowOnError>;
519
+ };
520
+ //#endregion
521
+ //#region src/middlewares.d.ts
522
+ type FetchImpl = UnmaskType<(input: string | Request | URL, init?: RequestInit) => Promise<Response>>;
523
+ interface Middlewares<TCallApiContext extends NoInfer<CallApiContext> = DefaultCallApiContext> {
524
+ /**
525
+ * Wraps the fetch implementation to intercept requests at the network layer.
526
+ *
527
+ * Takes a context object containing the current fetch function and returns a new fetch function.
528
+ * Use it to cache responses, add logging, handle offline mode, or short-circuit requests etc.
529
+ * Multiple middleware compose in order: plugins → base config → per-request.
530
+ *
531
+ * Unlike `customFetchImpl`, middleware can call through to the original fetch.
532
+ *
533
+ * @example
534
+ * ```ts
535
+ * // Cache responses
536
+ * const cache = new Map();
537
+ *
538
+ * fetchMiddleware: (ctx) => async (input, init) => {
539
+ * const key = input.toString();
540
+ * if (cache.has(key)) return cache.get(key).clone();
541
+ *
542
+ * const response = await ctx.fetchImpl(input, init);
543
+ * cache.set(key, response.clone());
544
+ * return response;
545
+ * }
546
+ *
547
+ * // Handle offline
548
+ * fetchMiddleware: (ctx) => async (input, init) => {
549
+ * if (!navigator.onLine) {
550
+ * return new Response('{"error": "offline"}', { status: 503 });
551
+ * }
552
+ * return ctx.fetchImpl(input, init);
553
+ * }
554
+ * ```
555
+ */
556
+ fetchMiddleware?: (context: RequestContext<TCallApiContext> & {
557
+ fetchImpl: FetchImpl;
558
+ }) => FetchImpl;
559
+ }
560
+ //#endregion
553
561
  //#region src/plugins.d.ts
554
562
  type PluginSetupContext<TCallApiContext extends CallApiContext = DefaultCallApiContext> = RequestContext<TCallApiContext> & {
555
563
  initURL: string;
@@ -1197,7 +1205,7 @@ type SharedExtraOptions<TCallApiContext extends CallApiContext = DefaultCallApiC
1197
1205
  *
1198
1206
  * ```
1199
1207
  */
1200
- auth?: Auth;
1208
+ auth?: AuthOption;
1201
1209
  /**
1202
1210
  * Custom function to serialize request body objects into strings.
1203
1211
  *
@@ -1846,5 +1854,5 @@ declare const callApi: <TData = unknown, TErrorData = unknown, TResultMode exten
1846
1854
  "@put/"?: CallApiSchema | undefined;
1847
1855
  }, TSchema, CallApiSchemaConfig, TSchemaConfig, TInitURL, TCurrentRouteSchemaKey, DefaultPluginArray, TPluginArray>) => Promise<TComputedResult>;
1848
1856
  //#endregion
1849
- export { Writeable as $, ErrorContext as A, CallApiPlugin as B, InferExtendSchemaContext as C, ValidationError as D, HTTPError as E, ResponseContext as F, BaseSchemaRouteKeyPrefixes as G, PluginSetupContext as H, ResponseErrorContext as I, InferSchemaInput as J, CallApiSchema as K, ResponseStreamContext as L, HooksOrHooksArray as M, RequestContext as N, RetryOptions as O, RequestStreamContext as P, Satisfies as Q, SuccessContext as R, GetExtendSchemaConfigContext as S, Register as T, URLOptions as U, PluginHooks as V, BaseCallApiSchemaRoutes as W, InferParamsFromRoute as X, InferSchemaOutput as Y, AnyFunction as Z, CallApiExtraOptionsForHooks as _, CallApiResultSuccessOrErrorVariant as a, CallApiRequestOptionsForHooks as b, PossibleJavaScriptError as c, ResponseTypeType as d, ResultModeType as f, CallApiExtraOptions as g, CallApiConfig as h, CallApiResultErrorVariant as i, Hooks as j, DedupeOptions as k, PossibleJavaScriptOrValidationError as l, BaseCallApiExtraOptions as m, createFetchClient as n, CallApiResultSuccessVariant as o, BaseCallApiConfig as p, CallApiSchemaConfig as q, createFetchClientWithContext as r, PossibleHTTPError as s, callApi as t, PossibleValidationError as u, CallApiParameters as v, InstanceContext as w, CallApiResultLoose as x, CallApiRequestOptions as y, DefaultCallApiContext as z };
1850
- //# sourceMappingURL=index-DP2YeNBA.d.ts.map
1857
+ export { Writeable as $, ErrorContext as A, CallApiPlugin as B, InferExtendSchemaContext as C, ValidationError as D, HTTPError as E, ResponseContext as F, BaseCallApiSchemaRoutes as G, PluginSetupContext as H, ResponseErrorContext as I, CallApiSchemaConfig as J, BaseSchemaRouteKeyPrefixes as K, ResponseStreamContext as L, HooksOrHooksArray as M, RequestContext as N, RetryOptions as O, RequestStreamContext as P, Satisfies as Q, SuccessContext as R, GetExtendSchemaConfigContext as S, Register as T, InferParamsFromRoute as U, PluginHooks as V, URLOptions as W, InferSchemaOutput as X, InferSchemaInput as Y, AnyFunction as Z, CallApiExtraOptionsForHooks as _, CallApiResultSuccessOrErrorVariant as a, CallApiRequestOptionsForHooks as b, PossibleJavaScriptError as c, ResponseTypeType as d, ResultModeType as f, CallApiExtraOptions as g, CallApiConfig as h, CallApiResultErrorVariant as i, Hooks as j, DedupeOptions as k, PossibleJavaScriptOrValidationError as l, BaseCallApiExtraOptions as m, createFetchClient as n, CallApiResultSuccessVariant as o, BaseCallApiConfig as p, CallApiSchema as q, createFetchClientWithContext as r, PossibleHTTPError as s, callApi as t, PossibleValidationError as u, CallApiParameters as v, InstanceContext as w, CallApiResultLoose as x, CallApiRequestOptions as y, DefaultCallApiContext as z };
1858
+ //# sourceMappingURL=index-YnlEWnbR.d.ts.map
package/dist/index.d.ts CHANGED
@@ -1,3 +1,2 @@
1
- import "./validation-Do6HBp6Z.js";
2
- import { A as ErrorContext, B as CallApiPlugin, C as InferExtendSchemaContext, F as ResponseContext, G as BaseSchemaRouteKeyPrefixes, H as PluginSetupContext, I as ResponseErrorContext, J as InferSchemaInput, K as CallApiSchema, L as ResponseStreamContext, M as HooksOrHooksArray, N as RequestContext, O as RetryOptions, P as RequestStreamContext, R as SuccessContext, S as GetExtendSchemaConfigContext, T as Register, U as URLOptions, V as PluginHooks, W as BaseCallApiSchemaRoutes, X as InferParamsFromRoute, Y as InferSchemaOutput, _ as CallApiExtraOptionsForHooks, a as CallApiResultSuccessOrErrorVariant, b as CallApiRequestOptionsForHooks, c as PossibleJavaScriptError, d as ResponseTypeType, f as ResultModeType, g as CallApiExtraOptions, h as CallApiConfig, i as CallApiResultErrorVariant, j as Hooks, k as DedupeOptions, l as PossibleJavaScriptOrValidationError, m as BaseCallApiExtraOptions, n as createFetchClient, o as CallApiResultSuccessVariant, p as BaseCallApiConfig, q as CallApiSchemaConfig, r as createFetchClientWithContext, s as PossibleHTTPError, t as callApi, u as PossibleValidationError, v as CallApiParameters, w as InstanceContext, x as CallApiResultLoose, y as CallApiRequestOptions, z as DefaultCallApiContext } from "./index-DP2YeNBA.js";
1
+ import { A as ErrorContext, B as CallApiPlugin, C as InferExtendSchemaContext, F as ResponseContext, G as BaseCallApiSchemaRoutes, H as PluginSetupContext, I as ResponseErrorContext, J as CallApiSchemaConfig, K as BaseSchemaRouteKeyPrefixes, L as ResponseStreamContext, M as HooksOrHooksArray, N as RequestContext, O as RetryOptions, P as RequestStreamContext, R as SuccessContext, S as GetExtendSchemaConfigContext, T as Register, U as InferParamsFromRoute, V as PluginHooks, W as URLOptions, X as InferSchemaOutput, Y as InferSchemaInput, _ as CallApiExtraOptionsForHooks, a as CallApiResultSuccessOrErrorVariant, b as CallApiRequestOptionsForHooks, c as PossibleJavaScriptError, d as ResponseTypeType, f as ResultModeType, g as CallApiExtraOptions, h as CallApiConfig, i as CallApiResultErrorVariant, j as Hooks, k as DedupeOptions, l as PossibleJavaScriptOrValidationError, m as BaseCallApiExtraOptions, n as createFetchClient, o as CallApiResultSuccessVariant, p as BaseCallApiConfig, q as CallApiSchema, r as createFetchClientWithContext, s as PossibleHTTPError, t as callApi, u as PossibleValidationError, v as CallApiParameters, w as InstanceContext, x as CallApiResultLoose, y as CallApiRequestOptions, z as DefaultCallApiContext } from "./index-YnlEWnbR.js";
3
2
  export { BaseCallApiConfig, BaseCallApiExtraOptions, BaseCallApiSchemaRoutes, BaseSchemaRouteKeyPrefixes, CallApiConfig, CallApiExtraOptions, CallApiExtraOptionsForHooks, CallApiParameters, CallApiPlugin, CallApiRequestOptions, CallApiRequestOptionsForHooks, CallApiResultLoose as CallApiResult, CallApiResultErrorVariant, CallApiResultSuccessOrErrorVariant, CallApiResultSuccessVariant, CallApiSchema, CallApiSchemaConfig, DedupeOptions, DefaultCallApiContext, ErrorContext, GetExtendSchemaConfigContext, Hooks, HooksOrHooksArray, InferExtendSchemaContext, InferParamsFromRoute, InferSchemaInput, InferSchemaOutput, InstanceContext, PluginHooks, PluginSetupContext, PossibleHTTPError, PossibleJavaScriptError, PossibleJavaScriptOrValidationError, PossibleValidationError, Register, RequestContext, RequestStreamContext, ResponseContext, ResponseErrorContext, ResponseStreamContext, ResponseTypeType, ResultModeType, RetryOptions, SuccessContext, URLOptions, callApi, createFetchClient, createFetchClientWithContext };