@zayne-labs/callapi 1.9.12 → 1.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -11,8 +11,8 @@
11
11
  <!-- <a href="https://deno.bundlejs.com/badge?q=@zayne-labs/callapi,@zayne-labs/callapi&treeshake=%5B*%5D,%5B%7B+createFetchClient+%7D%5D&config=%7B%22compression%22:%7B%22type%22:%22brotli%22,%22quality%22:11%7D%7D"><img src="https://deno.bundlejs.com/badge?q=@zayne-labs/callapi,@zayne-labs/callapi&treeshake=%5B*%5D,%5B%7B+createFetchClient+%7D%5D&config=%7B%22compression%22:%7B%22type%22:%22brotli%22,%22quality%22:11%7D%7D" alt="bundle size"></a> -->
12
12
  <a href="https://www.npmjs.com/package/@zayne-labs/callapi"><img src="https://img.shields.io/npm/v/@zayne-labs/callapi?style=flat&color=EFBA5F" alt="npm version"></a>
13
13
  <a href="https://github.com/zayne-labs/callapi/blob/master/LICENSE"><img src="https://img.shields.io/npm/l/@zayne-labs/callapi?style=flat&color=EFBA5F" alt="license"></a>
14
- <a href="https://github.com/zayne-labs/callapi/graphs/commit-activity"><img src="https://img.shields.io/github/commit-activity/m/zayne-labs/callapi?style=flat&color=EFBA5F" alt="commit activity"></a>
15
14
  <a href="https://www.npmjs.com/package/@zayne-labs/callapi"><img src="https://img.shields.io/npm/dm/@zayne-labs/callapi?style=flat&color=EFBA5F" alt="downloads per month"></a>
15
+ <a href="https://github.com/zayne-labs/callapi/graphs/commit-activity"><img src="https://img.shields.io/github/commit-activity/m/zayne-labs/callapi?style=flat&color=EFBA5F" alt="commit activity"></a>
16
16
  <a href="https://deepwiki.com/zayne-labs/callapi"><img src="https://deepwiki.com/badge.svg" alt="Ask DeepWiki"></a>
17
17
  <a href="https://code2tutorial.com/tutorial/02b6c57c-4847-4e76-b91e-d64dde370609/index.md"><img src="https://img.shields.io/badge/Code2Tutorial-blue?color=blue&logo=victoriametrics" alt="Code2Tutorial"></a>
18
18
  </p>
@@ -58,7 +58,7 @@ type CustomAuth = {
58
58
  prefix: PossibleAuthValueOrGetter;
59
59
  value: PossibleAuthValueOrGetter;
60
60
  };
61
- type Auth = BearerOrTokenAuth | BasicAuth | CustomAuth;
61
+ type Auth = PossibleAuthValueOrGetter | BearerOrTokenAuth | BasicAuth | CustomAuth;
62
62
  //#endregion
63
63
  //#region src/constants/common.d.ts
64
64
  declare const fetchSpecificKeys: (keyof RequestInit | "duplex")[];
@@ -170,8 +170,7 @@ type HTTPErrorDetails<TErrorData> = Pick<CallApiExtraOptions, "defaultHTTPErrorM
170
170
  };
171
171
  declare class HTTPError<TErrorData = Record<string, unknown>> extends Error {
172
172
  errorData: HTTPErrorDetails<TErrorData>["errorData"];
173
- httpErrorSymbol: symbol;
174
- isHTTPError: boolean;
173
+ readonly httpErrorSymbol: symbol;
175
174
  name: "HTTPError";
176
175
  response: HTTPErrorDetails<TErrorData>["response"];
177
176
  constructor(errorDetails: HTTPErrorDetails<TErrorData>, errorOptions?: ErrorOptions);
@@ -188,14 +187,14 @@ type ValidationErrorDetails = {
188
187
  };
189
188
  declare class ValidationError extends Error {
190
189
  errorData: ValidationErrorDetails["issues"];
191
- name: string;
190
+ name: "ValidationError";
192
191
  response: ValidationErrorDetails["response"];
193
- validationErrorSymbol: symbol;
192
+ readonly validationErrorSymbol: symbol;
194
193
  constructor(details: ValidationErrorDetails, errorOptions?: ErrorOptions);
195
194
  /**
196
- * @description Checks if the given error is an instance of HTTPError
195
+ * @description Checks if the given error is an instance of ValidationError
197
196
  * @param error - The error to check
198
- * @returns true if the error is an instance of HTTPError, false otherwise
197
+ * @returns true if the error is an instance of ValidationError, false otherwise
199
198
  */
200
199
  static isError(error: unknown): error is ValidationError;
201
200
  }
@@ -321,7 +320,8 @@ interface URLOptions {
321
320
  }
322
321
  //#endregion
323
322
  //#region src/validation.d.ts
324
- type InferSchemaResult<TSchema, TFallbackResult = unknown> = undefined extends TSchema ? TFallbackResult : TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TSchema> : TSchema extends AnyFunction<infer TResult> ? Awaited<TResult> : TFallbackResult;
323
+ type InferSchemaOutputResult<TSchema, TFallbackResult = unknown> = undefined extends TSchema ? TFallbackResult : TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<TSchema> : TSchema extends AnyFunction<infer TResult> ? Awaited<TResult> : TFallbackResult;
324
+ type InferSchemaInputResult<TSchema, TFallbackResult = unknown> = undefined extends TSchema ? TFallbackResult : TSchema extends StandardSchemaV1 ? StandardSchemaV1.InferInput<TSchema> : TSchema extends AnyFunction<infer TResult> ? Awaited<TResult> : TFallbackResult;
325
325
  interface CallApiSchemaConfig {
326
326
  /**
327
327
  * The base url of the schema. By default it's the baseURL of the callApi instance.
@@ -1130,7 +1130,7 @@ interface RetryOptions<TErrorData> {
1130
1130
  /**
1131
1131
  * @description Makes a type partial if the output type of TSchema is not provided or has undefined in the union, otherwise makes it required
1132
1132
  */
1133
- type MakeSchemaOptionRequiredIfDefined<TSchemaOption extends CallApiSchema[keyof CallApiSchema], TObject> = undefined extends InferSchemaResult<TSchemaOption, undefined> ? TObject : Required<TObject>;
1133
+ type MakeSchemaOptionRequiredIfDefined<TSchemaOption extends CallApiSchema[keyof CallApiSchema], TObject> = undefined extends InferSchemaInputResult<TSchemaOption, undefined> ? TObject : Required<TObject>;
1134
1134
  type ApplyURLBasedConfig<TSchemaConfig extends CallApiSchemaConfig, TSchemaRouteKeys extends string> = TSchemaConfig["prefix"] extends string ? `${TSchemaConfig["prefix"]}${TSchemaRouteKeys}` : TSchemaConfig["baseURL"] extends string ? `${TSchemaConfig["baseURL"]}${TSchemaRouteKeys}` : TSchemaRouteKeys;
1135
1135
  type ApplyStrictConfig<TSchemaConfig extends CallApiSchemaConfig, TSchemaRouteKeys extends string> = TSchemaConfig["strict"] extends true ? TSchemaRouteKeys :
1136
1136
  // eslint-disable-next-line perfectionist/sort-union-types -- Don't sort union types
@@ -1148,7 +1148,7 @@ type InferBodyOption<TSchema extends CallApiSchema> = MakeSchemaOptionRequiredIf
1148
1148
  /**
1149
1149
  * Body of the request, can be a object or any other supported body type.
1150
1150
  */
1151
- body?: InferSchemaResult<TSchema["body"], Body>;
1151
+ body?: InferSchemaInputResult<TSchema["body"], Body>;
1152
1152
  }>;
1153
1153
  type MethodUnion = UnmaskType<"CONNECT" | "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT" | "TRACE" | AnyString>;
1154
1154
  type InferMethodFromURL<TInitURL> = string extends TInitURL ? MethodUnion : TInitURL extends `@${infer TMethod extends RouteKeyMethods}/${string}` ? Uppercase<TMethod> : MethodUnion;
@@ -1157,16 +1157,16 @@ type InferMethodOption<TSchema extends CallApiSchema, TInitURL> = MakeSchemaOpti
1157
1157
  * HTTP method for the request.
1158
1158
  * @default "GET"
1159
1159
  */
1160
- method?: InferSchemaResult<TSchema["method"], InferMethodFromURL<TInitURL>>;
1160
+ method?: InferSchemaInputResult<TSchema["method"], InferMethodFromURL<TInitURL>>;
1161
1161
  }>;
1162
1162
  type HeadersOption = UnmaskType<Record<"Authorization", CommonAuthorizationHeaders | undefined> | Record<"Content-Type", CommonContentTypes | undefined> | Record<CommonRequestHeaders, string | undefined> | Record<string, string | undefined> | Array<[string, string]>>;
1163
1163
  type InferHeadersOption<TSchema extends CallApiSchema> = MakeSchemaOptionRequiredIfDefined<TSchema["headers"], {
1164
1164
  /**
1165
1165
  * Headers to be used in the request.
1166
1166
  */
1167
- headers?: InferSchemaResult<TSchema["headers"], HeadersOption> | ((context: {
1167
+ headers?: InferSchemaInputResult<TSchema["headers"], HeadersOption> | ((context: {
1168
1168
  baseHeaders: NonNullable<HeadersOption>;
1169
- }) => InferSchemaResult<TSchema["headers"], HeadersOption>);
1169
+ }) => InferSchemaInputResult<TSchema["headers"], HeadersOption>);
1170
1170
  }>;
1171
1171
  type InferRequestOptions<TSchema extends CallApiSchema, TInitURL extends InferInitURL<BaseCallApiSchemaRoutes, CallApiSchemaConfig>> = InferBodyOption<TSchema> & InferHeadersOption<TSchema> & InferMethodOption<TSchema, TInitURL>;
1172
1172
  interface Register {}
@@ -1197,13 +1197,13 @@ type InferMetaOption<TSchema extends CallApiSchema> = MakeSchemaOptionRequiredIf
1197
1197
  * });
1198
1198
  * ```
1199
1199
  */
1200
- meta?: InferSchemaResult<TSchema["meta"], GlobalMeta>;
1200
+ meta?: InferSchemaInputResult<TSchema["meta"], GlobalMeta>;
1201
1201
  }>;
1202
1202
  type InferQueryOption<TSchema extends CallApiSchema> = MakeSchemaOptionRequiredIfDefined<TSchema["query"], {
1203
1203
  /**
1204
1204
  * Parameters to be appended to the URL (i.e: /:id)
1205
1205
  */
1206
- query?: InferSchemaResult<TSchema["query"], Query>;
1206
+ query?: InferSchemaInputResult<TSchema["query"], Query>;
1207
1207
  }>;
1208
1208
  type EmptyString = "";
1209
1209
  type EmptyTuple = readonly [];
@@ -1213,15 +1213,15 @@ type ExtractRouteParamNames<TCurrentRoute, TParamNamesAccumulator extends String
1213
1213
  type ConvertParamNamesToRecord<TParamNames extends StringTuple> = Prettify<TParamNames extends (readonly [infer TFirstParamName extends string, ...infer TRemainingParamNames extends StringTuple]) ? Record<TFirstParamName, AllowedQueryParamValues> & ConvertParamNamesToRecord<TRemainingParamNames> : NonNullable<unknown>>;
1214
1214
  type ConvertParamNamesToTuple<TParamNames extends StringTuple> = TParamNames extends readonly [string, ...infer TRemainingParamNames extends StringTuple] ? [AllowedQueryParamValues, ...ConvertParamNamesToTuple<TRemainingParamNames>] : [];
1215
1215
  type InferParamsFromRoute<TCurrentRoute> = ExtractRouteParamNames<TCurrentRoute> extends StringTuple ? ExtractRouteParamNames<TCurrentRoute> extends EmptyTuple ? Params : ConvertParamNamesToRecord<ExtractRouteParamNames<TCurrentRoute>> | ConvertParamNamesToTuple<ExtractRouteParamNames<TCurrentRoute>> : Params;
1216
- 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 InferSchemaResult<TParamsSchemaOption, null> ? TObject : Required<TObject> : TObject>;
1216
+ 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 InferSchemaInputResult<TParamsSchemaOption, null> ? TObject : Required<TObject> : TObject>;
1217
1217
  type InferParamsOption<TSchema extends CallApiSchema, TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TCurrentRouteSchemaKey extends string> = MakeParamsOptionRequired<TSchema["params"], TBaseSchemaRoutes, TCurrentRouteSchemaKey, {
1218
1218
  /**
1219
1219
  * Parameters to be appended to the URL (i.e: /:id)
1220
1220
  */
1221
- params?: InferSchemaResult<TSchema["params"], InferParamsFromRoute<TCurrentRouteSchemaKey>>;
1221
+ params?: InferSchemaInputResult<TSchema["params"], InferParamsFromRoute<TCurrentRouteSchemaKey>>;
1222
1222
  }>;
1223
1223
  type InferExtraOptions<TSchema extends CallApiSchema, TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, TCurrentRouteSchemaKey extends string> = InferMetaOption<TSchema> & InferParamsOption<TSchema, TBaseSchemaRoutes, TCurrentRouteSchemaKey> & InferQueryOption<TSchema>;
1224
- type InferPluginOptions<TPluginArray extends CallApiPlugin[]> = UnionToIntersection<TPluginArray extends Array<infer TPlugin> ? TPlugin extends CallApiPlugin ? TPlugin["defineExtraOptions"] extends AnyFunction<infer TReturnedSchema> ? InferSchemaResult<TReturnedSchema> : never : never : never>;
1224
+ type InferPluginOptions<TPluginArray extends CallApiPlugin[]> = UnionToIntersection<TPluginArray extends Array<infer TPlugin> ? TPlugin extends CallApiPlugin ? TPlugin["defineExtraOptions"] extends AnyFunction<infer TReturnedSchema> ? InferSchemaOutputResult<TReturnedSchema> : never : never : never>;
1225
1225
  type ExtractKeys<TUnion, TSelectedUnion extends TUnion> = Extract<TUnion, TSelectedUnion>;
1226
1226
  type ResultModeOption<TErrorData, TResultMode extends ResultModeUnion> = TErrorData extends false ? {
1227
1227
  resultMode: "onlySuccessWithException";
@@ -1272,27 +1272,10 @@ type SharedExtraOptions<TData = DefaultDataType, TErrorData = DefaultDataType, T
1272
1272
  * Supports multiple authentication patterns:
1273
1273
  * - String: Direct authorization header value
1274
1274
  * - Auth object: Structured authentication configuration
1275
- * - null: Explicitly removes authorization
1276
- *
1277
- * @example
1278
- * ```ts
1279
- * // Bearer token authentication
1280
- * auth: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9..."
1281
- *
1282
- * // Basic authentication
1283
- * auth: "Basic dXNlcm5hbWU6cGFzc3dvcmQ="
1284
- *
1285
- * // Using Auth object for dynamic authentication
1286
- * auth: {
1287
- * type: "bearer",
1288
- * token: () => getAccessToken()
1289
- * }
1290
1275
  *
1291
- * // Remove inherited auth from base config
1292
- * auth: null
1293
1276
  * ```
1294
1277
  */
1295
- auth?: string | Auth | null;
1278
+ auth?: Auth;
1296
1279
  /**
1297
1280
  * Custom function to serialize request body objects into strings.
1298
1281
  *
@@ -1797,5 +1780,5 @@ type CallApiConfig<TData = DefaultDataType, TErrorData = DefaultDataType, TResul
1797
1780
  type CallApiParameters<TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends ThrowOnErrorUnion = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TBaseSchemaRoutes extends BaseCallApiSchemaRoutes = BaseCallApiSchemaRoutes, TSchema extends CallApiSchema = CallApiSchema, TBaseSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TInitURL extends InitURLOrURLObject = InitURLOrURLObject, TCurrentRouteSchemaKey extends string = string, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray, TPluginArray extends CallApiPlugin[] = DefaultPluginArray> = [initURL: TInitURL, config?: CallApiConfig<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TBaseSchemaRoutes, TSchema, TBaseSchemaConfig, TSchemaConfig, TInitURL, TCurrentRouteSchemaKey, TBasePluginArray, TPluginArray>];
1798
1781
  type CallApiResult<TData, TErrorData, TResultMode extends ResultModeUnion, TThrowOnError extends ThrowOnErrorUnion, TResponseType extends ResponseTypeUnion> = Promise<GetCallApiResult<TData, TErrorData, TResultMode, TThrowOnError, TResponseType>>;
1799
1782
  //#endregion
1800
- export { AnyFunction, AnyString, ApplyStrictConfig, ApplyURLBasedConfig, BaseCallApiConfig, BaseCallApiExtraOptions, BaseCallApiSchemaAndConfig, BaseCallApiSchemaRoutes, CallApiConfig, CallApiExtraOptions, CallApiExtraOptionsForHooks, CallApiParameters, CallApiPlugin, CallApiRequestOptions, CallApiRequestOptionsForHooks, CallApiResult, CallApiResultErrorVariant, CallApiResultSuccessVariant, CallApiSchema, CallApiSchemaConfig, DedupeOptions, DefaultDataType, DefaultPluginArray, DefaultThrowOnError, ErrorContext, GetCurrentRouteSchema, GetCurrentRouteSchemaKey, GetResponseType, HTTPError, Hooks, HooksOrHooksArray, InferInitURL, InferParamsFromRoute, InferSchemaResult, PluginExtraOptions, PluginHooks, PluginHooksWithMoreOptions, PluginSetupContext, PossibleHTTPError, PossibleJavaScriptError, PossibleJavaScriptOrValidationError, PossibleValidationError, Register, RequestContext, RequestStreamContext, ResponseContext, ResponseErrorContext, ResponseStreamContext, ResponseTypeMap, ResponseTypeUnion, ResultModeUnion, RetryOptions, SuccessContext, ThrowOnErrorUnion, URLOptions, ValidationError, Writeable, fallBackRouteSchemaKey };
1801
- //# sourceMappingURL=common-DzOcclPA.d.ts.map
1783
+ export { AnyFunction, AnyString, ApplyStrictConfig, ApplyURLBasedConfig, BaseCallApiConfig, BaseCallApiExtraOptions, BaseCallApiSchemaAndConfig, BaseCallApiSchemaRoutes, CallApiConfig, CallApiExtraOptions, CallApiExtraOptionsForHooks, CallApiParameters, CallApiPlugin, CallApiRequestOptions, CallApiRequestOptionsForHooks, CallApiResult, CallApiResultErrorVariant, CallApiResultSuccessVariant, CallApiSchema, CallApiSchemaConfig, DedupeOptions, DefaultDataType, DefaultPluginArray, DefaultThrowOnError, ErrorContext, GetCurrentRouteSchema, GetCurrentRouteSchemaKey, GetResponseType, HTTPError, Hooks, HooksOrHooksArray, InferInitURL, InferParamsFromRoute, InferSchemaOutputResult, PluginExtraOptions, PluginHooks, PluginHooksWithMoreOptions, PluginSetupContext, PossibleHTTPError, PossibleJavaScriptError, PossibleJavaScriptOrValidationError, PossibleValidationError, Register, RequestContext, RequestStreamContext, ResponseContext, ResponseErrorContext, ResponseStreamContext, ResponseTypeMap, ResponseTypeUnion, ResultModeUnion, RetryOptions, SuccessContext, ThrowOnErrorUnion, URLOptions, ValidationError, Writeable, fallBackRouteSchemaKey };
1784
+ //# sourceMappingURL=common-CO8LGZIl.d.ts.map
@@ -1,8 +1,8 @@
1
- import { AnyFunction, AnyString, ApplyStrictConfig, ApplyURLBasedConfig, BaseCallApiConfig, BaseCallApiExtraOptions, BaseCallApiSchemaAndConfig, BaseCallApiSchemaRoutes, CallApiConfig, CallApiExtraOptions, CallApiExtraOptionsForHooks, CallApiParameters, CallApiPlugin, CallApiRequestOptions, CallApiRequestOptionsForHooks, CallApiResult, CallApiResultErrorVariant, CallApiResultSuccessVariant, CallApiSchema, CallApiSchemaConfig, DedupeOptions, DefaultDataType, DefaultPluginArray, DefaultThrowOnError, ErrorContext, GetCurrentRouteSchema, GetCurrentRouteSchemaKey, GetResponseType, HTTPError, Hooks, HooksOrHooksArray, InferInitURL, InferParamsFromRoute, InferSchemaResult, PluginExtraOptions, PluginHooks, PluginHooksWithMoreOptions, PluginSetupContext, PossibleHTTPError, PossibleJavaScriptError, PossibleJavaScriptOrValidationError, PossibleValidationError, Register, RequestContext, RequestStreamContext, ResponseContext, ResponseErrorContext, ResponseStreamContext, ResponseTypeMap, ResponseTypeUnion, ResultModeUnion, RetryOptions, SuccessContext, ThrowOnErrorUnion, URLOptions, ValidationError, Writeable, fallBackRouteSchemaKey } from "./common-DzOcclPA.js";
1
+ import { AnyFunction, AnyString, ApplyStrictConfig, ApplyURLBasedConfig, BaseCallApiConfig, BaseCallApiExtraOptions, BaseCallApiSchemaAndConfig, BaseCallApiSchemaRoutes, CallApiConfig, CallApiExtraOptions, CallApiExtraOptionsForHooks, CallApiParameters, CallApiPlugin, CallApiRequestOptions, CallApiRequestOptionsForHooks, CallApiResult, CallApiResultErrorVariant, CallApiResultSuccessVariant, CallApiSchema, CallApiSchemaConfig, DedupeOptions, DefaultDataType, DefaultPluginArray, DefaultThrowOnError, ErrorContext, GetCurrentRouteSchema, GetCurrentRouteSchemaKey, GetResponseType, HTTPError, Hooks, HooksOrHooksArray, InferInitURL, InferParamsFromRoute, InferSchemaOutputResult, PluginExtraOptions, PluginHooks, PluginHooksWithMoreOptions, PluginSetupContext, PossibleHTTPError, PossibleJavaScriptError, PossibleJavaScriptOrValidationError, PossibleValidationError, Register, RequestContext, RequestStreamContext, ResponseContext, ResponseErrorContext, ResponseStreamContext, ResponseTypeMap, ResponseTypeUnion, ResultModeUnion, RetryOptions, SuccessContext, ThrowOnErrorUnion, URLOptions, ValidationError, Writeable, fallBackRouteSchemaKey } from "./common-CO8LGZIl.js";
2
2
 
3
3
  //#region src/createFetchClient.d.ts
4
4
 
5
- declare const createFetchClient: <TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBaseThrowOnError extends ThrowOnErrorUnion = DefaultThrowOnError, TBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion, const TBaseSchemaAndConfig extends BaseCallApiSchemaAndConfig = BaseCallApiSchemaAndConfig, const TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray, TComputedBaseSchemaConfig extends CallApiSchemaConfig = NonNullable<Writeable<TBaseSchemaAndConfig["config"], "deep">>, TComputedBaseSchemaRoutes extends BaseCallApiSchemaRoutes = Writeable<TBaseSchemaAndConfig["routes"], "deep">>(initBaseConfig?: BaseCallApiConfig<TBaseData, TBaseErrorData, TBaseResultMode, TBaseThrowOnError, TBaseResponseType, TBaseSchemaAndConfig, TBasePluginArray>) => <TData = TBaseData, TErrorData = TBaseErrorData, TResultMode extends ResultModeUnion = TBaseResultMode, TThrowOnError extends ThrowOnErrorUnion = TBaseThrowOnError, TResponseType extends ResponseTypeUnion = 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>(initURL: TInitURL, config?: CallApiConfig<InferSchemaResult<TSchema["data"], GetResponseType<TData, TResponseType>>, InferSchemaResult<TSchema["errorData"], GetResponseType<TErrorData, TResponseType>>, TResultMode, TThrowOnError, TResponseType, TComputedBaseSchemaRoutes, TSchema, TComputedBaseSchemaConfig, TSchemaConfig, TInitURL, TCurrentRouteSchemaKey, TBasePluginArray, TPluginArray> | undefined) => CallApiResult<InferSchemaResult<TSchema["data"], TData>, InferSchemaResult<TSchema["errorData"], TErrorData>, TResultMode, TThrowOnError, TResponseType>;
5
+ declare const createFetchClient: <TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBaseThrowOnError extends ThrowOnErrorUnion = DefaultThrowOnError, TBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion, const TBaseSchemaAndConfig extends BaseCallApiSchemaAndConfig = BaseCallApiSchemaAndConfig, const TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray, TComputedBaseSchemaConfig extends CallApiSchemaConfig = NonNullable<Writeable<TBaseSchemaAndConfig["config"], "deep">>, TComputedBaseSchemaRoutes extends BaseCallApiSchemaRoutes = Writeable<TBaseSchemaAndConfig["routes"], "deep">>(initBaseConfig?: BaseCallApiConfig<TBaseData, TBaseErrorData, TBaseResultMode, TBaseThrowOnError, TBaseResponseType, TBaseSchemaAndConfig, TBasePluginArray>) => <TData = TBaseData, TErrorData = TBaseErrorData, TResultMode extends ResultModeUnion = TBaseResultMode, TThrowOnError extends ThrowOnErrorUnion = TBaseThrowOnError, TResponseType extends ResponseTypeUnion = 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>(initURL: TInitURL, config?: CallApiConfig<InferSchemaOutputResult<TSchema["data"], GetResponseType<TData, TResponseType>>, InferSchemaOutputResult<TSchema["errorData"], GetResponseType<TErrorData, TResponseType>>, TResultMode, TThrowOnError, TResponseType, TComputedBaseSchemaRoutes, TSchema, TComputedBaseSchemaConfig, TSchemaConfig, TInitURL, TCurrentRouteSchemaKey, TBasePluginArray, TPluginArray> | undefined) => CallApiResult<InferSchemaOutputResult<TSchema["data"], TData>, InferSchemaOutputResult<TSchema["errorData"], TErrorData>, TResultMode, TThrowOnError, TResponseType>;
6
6
  declare const callApi: <TData = unknown, TErrorData = unknown, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends ThrowOnErrorUnion = boolean, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, 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<{
7
7
  [x: AnyString]: CallApiSchema | undefined;
8
8
  "@delete/"?: CallApiSchema | undefined;
@@ -38,14 +38,14 @@ declare const callApi: <TData = unknown, TErrorData = unknown, TResultMode exten
38
38
  "@patch/"?: CallApiSchema | undefined;
39
39
  "@post/"?: CallApiSchema | undefined;
40
40
  "@put/"?: CallApiSchema | undefined;
41
- }[TCurrentRouteSchemaKey], "deep">>>, const TPluginArray extends CallApiPlugin[] = DefaultPluginArray>(initURL: TInitURL, config?: CallApiConfig<InferSchemaResult<TSchema["data"], GetResponseType<TData, TResponseType, ResponseTypeMap<TData>>>, InferSchemaResult<TSchema["errorData"], GetResponseType<TErrorData, TResponseType, ResponseTypeMap<TErrorData>>>, TResultMode, TThrowOnError, TResponseType, {
41
+ }[TCurrentRouteSchemaKey], "deep">>>, const TPluginArray extends CallApiPlugin[] = DefaultPluginArray>(initURL: TInitURL, config?: CallApiConfig<InferSchemaOutputResult<TSchema["data"], GetResponseType<TData, TResponseType, ResponseTypeMap<TData>>>, InferSchemaOutputResult<TSchema["errorData"], GetResponseType<TErrorData, TResponseType, ResponseTypeMap<TErrorData>>>, TResultMode, TThrowOnError, TResponseType, {
42
42
  [x: AnyString]: CallApiSchema | undefined;
43
43
  "@delete/"?: CallApiSchema | undefined;
44
44
  "@get/"?: CallApiSchema | undefined;
45
45
  "@patch/"?: CallApiSchema | undefined;
46
46
  "@post/"?: CallApiSchema | undefined;
47
47
  "@put/"?: CallApiSchema | undefined;
48
- }, TSchema, CallApiSchemaConfig, TSchemaConfig, TInitURL, TCurrentRouteSchemaKey, DefaultPluginArray, TPluginArray> | undefined) => CallApiResult<InferSchemaResult<TSchema["data"], TData>, InferSchemaResult<TSchema["errorData"], TErrorData>, TResultMode, TThrowOnError, TResponseType>;
48
+ }, TSchema, CallApiSchemaConfig, TSchemaConfig, TInitURL, TCurrentRouteSchemaKey, DefaultPluginArray, TPluginArray> | undefined) => CallApiResult<InferSchemaOutputResult<TSchema["data"], TData>, InferSchemaOutputResult<TSchema["errorData"], TErrorData>, TResultMode, TThrowOnError, TResponseType>;
49
49
  //#endregion
50
50
  //#region src/defineHelpers.d.ts
51
51
  declare const defineSchema: <const TBaseSchemaRoutes extends BaseCallApiSchemaRoutes, const TSchemaConfig extends CallApiSchemaConfig>(routes: TBaseSchemaRoutes, config?: TSchemaConfig) => {
@@ -58,5 +58,5 @@ declare const definePlugin: <const TPlugin extends CallApiPlugin | AnyFunction<C
58
58
  declare const defineBaseConfig: <const TBaseConfig extends BaseCallApiConfig>(baseConfig: TBaseConfig) => Writeable<typeof baseConfig, "deep">;
59
59
  declare const defineParameters: <TData = DefaultDataType, TErrorData = DefaultDataType, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends ThrowOnErrorUnion = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TBaseSchemaRoutes extends BaseCallApiSchemaRoutes = BaseCallApiSchemaRoutes, TSchema extends CallApiSchema = CallApiSchema, TBaseSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TSchemaConfig extends CallApiSchemaConfig = CallApiSchemaConfig, TInitURL extends InferInitURL<BaseCallApiSchemaRoutes, TSchemaConfig> = InferInitURL<BaseCallApiSchemaRoutes, TSchemaConfig>, TCurrentRouteSchemaKey extends string = string, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray, TPluginArray extends CallApiPlugin[] = DefaultPluginArray>(...parameters: CallApiParameters<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TBaseSchemaRoutes, TSchema, TBaseSchemaConfig, TSchemaConfig, TInitURL, TCurrentRouteSchemaKey, TBasePluginArray, TPluginArray>) => CallApiParameters<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TBaseSchemaRoutes, TSchema, TBaseSchemaConfig, TSchemaConfig, TInitURL, TCurrentRouteSchemaKey, TBasePluginArray, TPluginArray>;
60
60
  //#endregion
61
- export { type BaseCallApiConfig, type BaseCallApiExtraOptions, type BaseCallApiSchemaRoutes, type CallApiConfig, type CallApiExtraOptions, type CallApiExtraOptionsForHooks, type CallApiParameters, type CallApiPlugin, type CallApiRequestOptions, type CallApiRequestOptionsForHooks, type CallApiResult, type CallApiResultErrorVariant, type CallApiResultSuccessVariant, type CallApiSchema, type CallApiSchemaConfig, type DedupeOptions, type ErrorContext, HTTPError, type Hooks, type HooksOrHooksArray, type InferParamsFromRoute, type InferSchemaResult, type PluginExtraOptions, type PluginHooks, type PluginHooksWithMoreOptions, type PluginSetupContext, type PossibleHTTPError, type PossibleJavaScriptError, type PossibleJavaScriptOrValidationError, type PossibleValidationError, type Register, type RequestContext, type RequestStreamContext, type ResponseContext, type ResponseErrorContext, type ResponseStreamContext, type ResponseTypeUnion, type ResultModeUnion, type RetryOptions, type SuccessContext, type URLOptions, ValidationError, callApi, createFetchClient, defineBaseConfig, defineParameters, definePlugin, defineSchema, defineSchemaConfig, defineSchemaRoutes, fallBackRouteSchemaKey };
61
+ export { type BaseCallApiConfig, type BaseCallApiExtraOptions, type BaseCallApiSchemaRoutes, type CallApiConfig, type CallApiExtraOptions, type CallApiExtraOptionsForHooks, type CallApiParameters, type CallApiPlugin, type CallApiRequestOptions, type CallApiRequestOptionsForHooks, type CallApiResult, type CallApiResultErrorVariant, type CallApiResultSuccessVariant, type CallApiSchema, type CallApiSchemaConfig, type DedupeOptions, type ErrorContext, HTTPError, type Hooks, type HooksOrHooksArray, type InferParamsFromRoute, type InferSchemaOutputResult, type PluginExtraOptions, type PluginHooks, type PluginHooksWithMoreOptions, type PluginSetupContext, type PossibleHTTPError, type PossibleJavaScriptError, type PossibleJavaScriptOrValidationError, type PossibleValidationError, type Register, type RequestContext, type RequestStreamContext, type ResponseContext, type ResponseErrorContext, type ResponseStreamContext, type ResponseTypeUnion, type ResultModeUnion, type RetryOptions, type SuccessContext, type URLOptions, ValidationError, callApi, createFetchClient, defineBaseConfig, defineParameters, definePlugin, defineSchema, defineSchemaConfig, defineSchemaRoutes, fallBackRouteSchemaKey };
62
62
  //# sourceMappingURL=index.d.ts.map
package/dist/esm/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { HTTPError, ValidationError, createCombinedSignal, createTimeoutSignal, defineEnum, deterministicHashFn, extraOptionDefaults, getBody, getFetchImpl, getHeaders, isArray, isBoolean, isFunction, isHTTPErrorInstance, isObject, isPlainObject, isReadableStream, isString, isValidationErrorInstance, requestOptionDefaults, splitBaseConfig, splitConfig, toArray, toQueryString, waitFor } from "./utils-B5rSU71M.js";
1
+ import { HTTPError, ValidationError, createCombinedSignal, createTimeoutSignal, defineEnum, deterministicHashFn, extraOptionDefaults, getBody, getFetchImpl, getHeaders, isArray, isBoolean, isFunction, isHTTPErrorInstance, isObject, isPlainObject, isReadableStream, isString, isValidationErrorInstance, requestOptionDefaults, splitBaseConfig, splitConfig, toArray, toQueryString, waitFor } from "./utils-zvYT8TK8.js";
2
2
 
3
3
  //#region src/result.ts
4
4
  const getResponseType = (response, parser) => ({
@@ -12,9 +12,24 @@ const getResponseType = (response, parser) => ({
12
12
  stream: () => response.body,
13
13
  text: () => response.text()
14
14
  });
15
+ const textTypes = new Set([
16
+ "image/svg",
17
+ "application/xml",
18
+ "application/xhtml",
19
+ "application/html"
20
+ ]);
21
+ const JSON_REGEX = /^application\/(?:[\w!#$%&*.^`~-]*\+)?json(;.+)?$/i;
22
+ const detectResponseType = (response) => {
23
+ const initContentType = response.headers.get("content-type");
24
+ if (!initContentType) return extraOptionDefaults().responseType;
25
+ const contentType = initContentType.split(";")[0] ?? "";
26
+ if (JSON_REGEX.test(contentType)) return "json";
27
+ if (textTypes.has(contentType) || contentType.startsWith("text/")) return "text";
28
+ return "blob";
29
+ };
15
30
  const resolveResponseData = (response, responseType, parser) => {
16
31
  const selectedParser = parser ?? extraOptionDefaults().responseParser;
17
- const selectedResponseType = responseType ?? extraOptionDefaults().responseType;
32
+ const selectedResponseType = responseType ?? detectResponseType(response);
18
33
  const RESPONSE_TYPE_LOOKUP = getResponseType(response, selectedParser);
19
34
  if (!Object.hasOwn(RESPONSE_TYPE_LOOKUP, selectedResponseType)) throw new Error(`Invalid response type: ${responseType}`);
20
35
  return RESPONSE_TYPE_LOOKUP[selectedResponseType]();
@@ -30,14 +45,11 @@ const getResultModeMap = (details) => {
30
45
  };
31
46
  const resolveSuccessResult = (data, info) => {
32
47
  const { response, resultMode } = info;
33
- const details = {
48
+ return getResultModeMap({
34
49
  data,
35
50
  error: null,
36
51
  response
37
- };
38
- const resultModeMap = getResultModeMap(details);
39
- const successResult = resultModeMap[resultMode ?? "all"]();
40
- return successResult;
52
+ })[resultMode ?? "all"]();
41
53
  };
42
54
  const resolveErrorResult = (error, info) => {
43
55
  const { cloneResponse, message: customErrorMessage, resultMode } = info;
@@ -77,8 +89,7 @@ const resolveErrorResult = (error, info) => {
77
89
  response: cloneResponse ? response.clone() : response
78
90
  };
79
91
  }
80
- const resultModeMap = getResultModeMap(errorDetails);
81
- const generalErrorResult = resultModeMap[resultMode ?? "all"]();
92
+ const generalErrorResult = getResultModeMap(errorDetails)[resultMode ?? "all"]();
82
93
  return {
83
94
  errorDetails,
84
95
  generalErrorResult
@@ -255,12 +266,8 @@ const createDedupeStrategy = async (context) => {
255
266
  const dedupeStrategy = globalOptions.dedupeStrategy ?? extraOptionDefaults().dedupeStrategy;
256
267
  const resolvedDedupeStrategy = isFunction(dedupeStrategy) ? dedupeStrategy(context) : dedupeStrategy;
257
268
  const getDedupeKey = () => {
258
- const shouldHaveDedupeKey = resolvedDedupeStrategy === "cancel" || resolvedDedupeStrategy === "defer";
259
- if (!shouldHaveDedupeKey) return null;
260
- if (globalOptions.dedupeKey) {
261
- const resolvedDedupeKey = isFunction(globalOptions.dedupeKey) ? globalOptions.dedupeKey(context) : globalOptions.dedupeKey;
262
- return resolvedDedupeKey;
263
- }
269
+ if (!(resolvedDedupeStrategy === "cancel" || resolvedDedupeStrategy === "defer")) return null;
270
+ if (globalOptions.dedupeKey) return isFunction(globalOptions.dedupeKey) ? globalOptions.dedupeKey(context) : globalOptions.dedupeKey;
264
271
  return `${globalOptions.fullURL}-${deterministicHashFn({
265
272
  options: globalOptions,
266
273
  request: globalRequest
@@ -283,8 +290,7 @@ const createDedupeStrategy = async (context) => {
283
290
  return `Duplicate request detected - Aborted previous request to '${globalOptions.fullURL}' as a new request with identical options was initiated`;
284
291
  };
285
292
  const handleRequestCancelStrategy = () => {
286
- const shouldCancelRequest = prevRequestInfo && resolvedDedupeStrategy === "cancel";
287
- if (!shouldCancelRequest) return;
293
+ if (!(prevRequestInfo && resolvedDedupeStrategy === "cancel")) return;
288
294
  const message = getAbortErrorMessage();
289
295
  const reason = new DOMException(message, "AbortError");
290
296
  prevRequestInfo.controller.abort(reason);
@@ -306,11 +312,10 @@ const createDedupeStrategy = async (context) => {
306
312
  controller: newFetchController,
307
313
  responsePromise
308
314
  });
309
- const streamableResponse = toStreamableResponse({
315
+ return toStreamableResponse({
310
316
  ...streamableContext,
311
317
  response: await responsePromise
312
318
  });
313
- return streamableResponse;
314
319
  };
315
320
  const removeDedupeKeyFromCache = () => {
316
321
  $RequestInfoCacheOrNull?.delete(dedupeKey);
@@ -328,10 +333,9 @@ const createDedupeStrategy = async (context) => {
328
333
  //#region src/validation.ts
329
334
  const handleValidatorFunction = async (validator, inputData) => {
330
335
  try {
331
- const result = await validator(inputData);
332
336
  return {
333
337
  issues: void 0,
334
- value: result
338
+ value: await validator(inputData)
335
339
  };
336
340
  } catch (error) {
337
341
  return {
@@ -358,8 +362,7 @@ const routeKeyMethods = defineEnum([
358
362
  const handleSchemaValidation = async (schema, validationOptions) => {
359
363
  const { inputValue, response, schemaConfig } = validationOptions;
360
364
  if (!schema || schemaConfig?.disableRuntimeValidation) return inputValue;
361
- const validResult = await standardSchemaParser(schema, inputValue, response);
362
- return validResult;
365
+ return await standardSchemaParser(schema, inputValue, response);
363
366
  };
364
367
  const extraOptionsToBeValidated = [
365
368
  "meta",
@@ -459,8 +462,7 @@ const getResolvedSchema = (context) => {
459
462
  };
460
463
  const getResolvedSchemaConfig = (context) => {
461
464
  const { baseExtraOptions, extraOptions } = context;
462
- const resolvedSchemaConfig = isFunction(extraOptions.schemaConfig) ? extraOptions.schemaConfig({ baseSchemaConfig: baseExtraOptions.schema?.config ?? {} }) : extraOptions.schemaConfig ?? baseExtraOptions.schema?.config;
463
- return resolvedSchemaConfig;
465
+ return isFunction(extraOptions.schemaConfig) ? extraOptions.schemaConfig({ baseSchemaConfig: baseExtraOptions.schema?.config ?? {} }) : extraOptions.schemaConfig ?? baseExtraOptions.schema?.config;
464
466
  };
465
467
  const getCurrentRouteSchemaKeyAndMainInitURL = (context) => {
466
468
  const { baseExtraOptions, extraOptions, initURL } = context;
@@ -485,8 +487,7 @@ const getCurrentRouteSchemaKeyAndMainInitURL = (context) => {
485
487
  //#region src/plugins.ts
486
488
  const getResolvedPlugins = (context) => {
487
489
  const { baseConfig, options } = context;
488
- const resolvedPlugins = isFunction(options.plugins) ? options.plugins({ basePlugins: baseConfig.plugins ?? [] }) : options.plugins ?? [];
489
- return resolvedPlugins;
490
+ return isFunction(options.plugins) ? options.plugins({ basePlugins: baseConfig.plugins ?? [] }) : options.plugins ?? [];
490
491
  };
491
492
  const initializePlugins = async (context) => {
492
493
  const { baseConfig, config, initURL, options, request } = context;
@@ -559,8 +560,7 @@ const initializePlugins = async (context) => {
559
560
  const flattenedHookArray = [...hookRegistry].flat();
560
561
  if (flattenedHookArray.length === 0) continue;
561
562
  const hooksExecutionMode = options.hooksExecutionMode ?? extraOptionDefaults().hooksExecutionMode;
562
- const composedHook = composeAllHooks(flattenedHookArray, hooksExecutionMode);
563
- resolvedHooks[key] = composedHook;
563
+ resolvedHooks[key] = composeAllHooks(flattenedHookArray, hooksExecutionMode);
564
564
  }
565
565
  return {
566
566
  resolvedCurrentRouteSchemaKey,
@@ -575,8 +575,7 @@ const initializePlugins = async (context) => {
575
575
  //#region src/retry.ts
576
576
  const getLinearDelay = (currentAttemptCount, options) => {
577
577
  const retryDelay = options.retryDelay ?? options.retry?.delay;
578
- const resolveRetryDelay = (isFunction(retryDelay) ? retryDelay(currentAttemptCount) : retryDelay) ?? extraOptionDefaults().retryDelay;
579
- return resolveRetryDelay;
578
+ return (isFunction(retryDelay) ? retryDelay(currentAttemptCount) : retryDelay) ?? extraOptionDefaults().retryDelay;
580
579
  };
581
580
  const getExponentialDelay = (currentAttemptCount, options) => {
582
581
  const retryDelay = options.retryDelay ?? options.retry?.delay ?? extraOptionDefaults().retryDelay;
@@ -601,14 +600,12 @@ const createRetryStrategy = (ctx) => {
601
600
  const retryCondition = options.retryCondition ?? options.retry?.condition ?? extraOptionDefaults().retryCondition;
602
601
  const maximumRetryAttempts = options.retryAttempts ?? options.retry?.attempts ?? extraOptionDefaults().retryAttempts;
603
602
  const customRetryCondition = await retryCondition(ctx);
604
- const baseShouldRetry = currentAttemptCount <= maximumRetryAttempts && customRetryCondition;
605
- if (!baseShouldRetry) return false;
603
+ if (!(currentAttemptCount <= maximumRetryAttempts && customRetryCondition)) return false;
606
604
  const retryMethods = new Set(options.retryMethods ?? options.retry?.methods ?? extraOptionDefaults().retryMethods);
607
605
  const includesMethod = isString(ctx.request.method) && retryMethods.size > 0 ? retryMethods.has(ctx.request.method) : true;
608
606
  const retryStatusCodes = new Set(options.retryStatusCodes ?? options.retry?.statusCodes ?? extraOptionDefaults().retryStatusCodes);
609
607
  const includesStatusCodes = Boolean(ctx.response) && retryStatusCodes.size > 0 ? retryStatusCodes.has(ctx.response.status) : true;
610
- const shouldRetry = includesMethod && includesStatusCodes;
611
- return shouldRetry;
608
+ return includesMethod && includesStatusCodes;
612
609
  };
613
610
  return {
614
611
  currentAttemptCount,
@@ -627,8 +624,7 @@ const mergeUrlWithParams = (url, params) => {
627
624
  if (!params) return url;
628
625
  let newUrl = url;
629
626
  if (isArray(params)) {
630
- const urlParts = newUrl.split(slash);
631
- const matchedParamsArray = urlParts.filter((part) => part.startsWith(colon) || part.startsWith(openBrace) && part.endsWith(closeBrace));
627
+ const matchedParamsArray = newUrl.split(slash).filter((part) => part.startsWith(colon) || part.startsWith(openBrace) && part.endsWith(closeBrace));
632
628
  for (const [paramIndex, matchedParam] of matchedParamsArray.entries()) {
633
629
  const stringParamValue = String(params[paramIndex]);
634
630
  newUrl = newUrl.replace(matchedParam, stringParamValue);
@@ -699,18 +695,15 @@ const getMethod = (ctx) => {
699
695
  const normalizeURL = (initURL) => {
700
696
  const methodFromURL = extractMethodFromURL(initURL);
701
697
  if (!methodFromURL) return initURL;
702
- const normalizedURL = initURL.replace(`@${methodFromURL}/`, "/");
703
- return normalizedURL;
698
+ return initURL.replace(`@${methodFromURL}/`, "/");
704
699
  };
705
700
  const getFullAndNormalizedURL = (options) => {
706
701
  const { baseURL, initURL, params, query } = options;
707
702
  const normalizedInitURL = normalizeURL(initURL);
708
703
  const urlWithMergedParams = mergeUrlWithParams(normalizedInitURL, params);
709
704
  const urlWithMergedQueryAndParams = mergeUrlWithQuery(urlWithMergedParams, query);
710
- const shouldPrependBaseURL = !urlWithMergedQueryAndParams.startsWith("http") && baseURL;
711
- const fullURL = shouldPrependBaseURL ? `${baseURL}${urlWithMergedQueryAndParams}` : urlWithMergedQueryAndParams;
712
705
  return {
713
- fullURL,
706
+ fullURL: !urlWithMergedQueryAndParams.startsWith("http") && baseURL ? `${baseURL}${urlWithMergedQueryAndParams}` : urlWithMergedQueryAndParams,
714
707
  normalizedInitURL
715
708
  };
716
709
  };
@@ -723,12 +716,11 @@ const createFetchClient = (initBaseConfig = {}) => {
723
716
  const callApi$1 = async (...parameters) => {
724
717
  const [initURLOrURLObject, initConfig = {}] = parameters;
725
718
  const [fetchOptions, extraOptions] = splitConfig(initConfig);
726
- const resolvedBaseConfig = isFunction(initBaseConfig) ? initBaseConfig({
719
+ const baseConfig = isFunction(initBaseConfig) ? initBaseConfig({
727
720
  initURL: initURLOrURLObject.toString(),
728
721
  options: extraOptions,
729
722
  request: fetchOptions
730
723
  }) : initBaseConfig;
731
- const baseConfig = resolvedBaseConfig;
732
724
  const config = initConfig;
733
725
  const [baseFetchOptions, baseExtraOptions] = splitBaseConfig(baseConfig);
734
726
  const shouldSkipAutoMergeForOptions = baseExtraOptions.skipAutoMergeFor === "all" || baseExtraOptions.skipAutoMergeFor === "options";
@@ -855,11 +847,10 @@ const createFetchClient = (initBaseConfig = {}) => {
855
847
  ...successContext,
856
848
  error: null
857
849
  }));
858
- const successResult = resolveSuccessResult(successContext.data, {
850
+ return resolveSuccessResult(successContext.data, {
859
851
  response: successContext.response,
860
852
  resultMode: options.resultMode
861
853
  });
862
- return successResult;
863
854
  } catch (error) {
864
855
  const errorInfo = {
865
856
  cloneResponse: options.cloneResponse,
@@ -881,14 +872,13 @@ const createFetchClient = (initBaseConfig = {}) => {
881
872
  };
882
873
  const handleRetryOrGetErrorResult = async () => {
883
874
  const { currentAttemptCount, getDelay, shouldAttemptRetry } = createRetryStrategy(errorContext);
884
- const shouldRetry = await shouldAttemptRetry();
885
- if (shouldRetry) {
875
+ if (await shouldAttemptRetry()) {
886
876
  const retryContext = {
887
877
  ...errorContext,
888
878
  retryAttemptCount: currentAttemptCount
889
879
  };
890
- const hookError$1 = await executeHooksInCatchBlock([options.onRetry?.(retryContext)], hookInfo);
891
- if (hookError$1) return hookError$1;
880
+ const hookError = await executeHooksInCatchBlock([options.onRetry?.(retryContext)], hookInfo);
881
+ if (hookError) return hookError;
892
882
  const delay = getDelay();
893
883
  await waitFor(delay);
894
884
  const updatedOptions = {
@@ -900,25 +890,19 @@ const createFetchClient = (initBaseConfig = {}) => {
900
890
  if (shouldThrowOnError) throw error;
901
891
  return generalErrorResult;
902
892
  };
903
- if (isValidationErrorInstance(error)) {
904
- const hookError$1 = await executeHooksInCatchBlock([
905
- options.onValidationError?.(errorContext),
906
- options.onRequestError?.(errorContext),
907
- options.onError?.(errorContext)
908
- ], hookInfo);
909
- return hookError$1 ?? await handleRetryOrGetErrorResult();
910
- }
911
- if (isHTTPErrorInstance(error)) {
912
- const hookError$1 = await executeHooksInCatchBlock([
913
- options.onResponseError?.(errorContext),
914
- options.onError?.(errorContext),
915
- options.onResponse?.({
916
- ...errorContext,
917
- data: null
918
- })
919
- ], hookInfo);
920
- return hookError$1 ?? await handleRetryOrGetErrorResult();
921
- }
893
+ if (isValidationErrorInstance(error)) return await executeHooksInCatchBlock([
894
+ options.onValidationError?.(errorContext),
895
+ options.onRequestError?.(errorContext),
896
+ options.onError?.(errorContext)
897
+ ], hookInfo) ?? await handleRetryOrGetErrorResult();
898
+ if (isHTTPErrorInstance(error)) return await executeHooksInCatchBlock([
899
+ options.onResponseError?.(errorContext),
900
+ options.onError?.(errorContext),
901
+ options.onResponse?.({
902
+ ...errorContext,
903
+ data: null
904
+ })
905
+ ], hookInfo) ?? await handleRetryOrGetErrorResult();
922
906
  let message = error?.message;
923
907
  if (error instanceof DOMException && error.name === "AbortError") {
924
908
  message = getAbortErrorMessage();
@@ -928,8 +912,7 @@ const createFetchClient = (initBaseConfig = {}) => {
928
912
  message = `Request timed out after ${options.timeout}ms`;
929
913
  !shouldThrowOnError && console.error(`${error.name}:`, message);
930
914
  }
931
- const hookError = await executeHooksInCatchBlock([options.onRequestError?.(errorContext), options.onError?.(errorContext)], hookInfo);
932
- return hookError ?? getCustomizedErrorResult(await handleRetryOrGetErrorResult(), { message });
915
+ return await executeHooksInCatchBlock([options.onRequestError?.(errorContext), options.onError?.(errorContext)], hookInfo) ?? getCustomizedErrorResult(await handleRetryOrGetErrorResult(), { message });
933
916
  } finally {
934
917
  removeDedupeKeyFromCache();
935
918
  }