@zayne-labs/callapi 1.7.2 → 1.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/index.ts","../../src/error.ts","../../src/utils/guards.ts","../../src/auth.ts","../../src/utils/type-helpers.ts","../../src/types/common.ts","../../src/utils/constants.ts","../../src/utils/common.ts","../../src/stream.ts","../../src/dedupe.ts","../../src/plugins.ts","../../src/response.ts","../../src/retry.ts","../../src/url.ts","../../src/utils/polyfills.ts","../../src/validation.ts","../../src/createFetchClient.ts","../../src/defineParameters.ts"],"sourcesContent":["export { callApi, createFetchClient } from \"./createFetchClient\";\n\nexport { definePlugin, type CallApiPlugin, type PluginInitContext } from \"./plugins\";\n\nexport { defineParameters } from \"./defineParameters\";\n\nexport type { InferSchemaResult, CallApiSchemas } from \"./validation\";\n\nexport { getDefaultOptions } from \"./utils/constants\";\n\nexport type { RetryOptions } from \"./retry\";\n\nexport { HTTPError } from \"./error\";\n\nexport type {\n\tBaseCallApiExtraOptions,\n\tCallApiExtraOptions,\n\tPossibleJavaScriptError,\n\tPossibleHTTPError,\n\tCallApiParameters,\n\tCallApiRequestOptions,\n\tCallApiRequestOptionsForHooks,\n\tCallApiResultErrorVariant,\n\tResultModeUnion,\n\tCallApiResultSuccessVariant,\n\tCombinedCallApiExtraOptions,\n\tErrorContext,\n\tInterceptors,\n\tInterceptorsOrInterceptorArray,\n\tPossibleJavascriptErrorNames,\n\tRegister,\n\tRequestContext,\n\tRequestErrorContext,\n\tResponseContext,\n\tResponseErrorContext,\n\tSuccessContext,\n} from \"./types\";\n","import type {\n\tCallApiExtraOptions,\n\tCallApiResultErrorVariant,\n\tPossibleJavascriptErrorNames,\n\tResultModeMap,\n} from \"./types/common\";\nimport { omitKeys } from \"./utils/common\";\nimport { isHTTPErrorInstance } from \"./utils/guards\";\n\ntype ErrorInfo = {\n\tcloneResponse: CallApiExtraOptions[\"cloneResponse\"];\n\tdefaultErrorMessage: Required<CallApiExtraOptions>[\"defaultErrorMessage\"];\n\terror?: unknown;\n\tmessage?: string;\n\tresultMode: CallApiExtraOptions[\"resultMode\"];\n};\n\nexport const resolveErrorResult = <TCallApiResult = never>(info: ErrorInfo) => {\n\tconst { cloneResponse, defaultErrorMessage, error, message: customErrorMessage, resultMode } = info;\n\n\tlet apiDetails: CallApiResultErrorVariant<unknown> = {\n\t\tdata: null,\n\t\terror: {\n\t\t\terrorData: error as Error,\n\t\t\tmessage: customErrorMessage ?? (error as Error).message,\n\t\t\tname: (error as Error).name as PossibleJavascriptErrorNames,\n\t\t},\n\t\tresponse: null,\n\t};\n\n\tif (isHTTPErrorInstance<never>(error)) {\n\t\tconst { errorData, message = defaultErrorMessage, name, response } = error;\n\n\t\tapiDetails = {\n\t\t\tdata: null,\n\t\t\terror: {\n\t\t\t\terrorData,\n\t\t\t\tmessage,\n\t\t\t\tname,\n\t\t\t},\n\t\t\tresponse: cloneResponse ? response.clone() : response,\n\t\t};\n\t}\n\n\tconst resultModeMap = {\n\t\tall: apiDetails,\n\t\tallWithException: apiDetails as never,\n\t\tallWithoutResponse: omitKeys(apiDetails, [\"response\"]),\n\t\tonlyError: apiDetails.error,\n\t\tonlyResponse: apiDetails.response,\n\t\tonlyResponseWithException: apiDetails.response as never,\n\t\tonlySuccess: apiDetails.data,\n\t\tonlySuccessWithException: apiDetails.data,\n\t} satisfies ResultModeMap;\n\n\tconst getErrorResult = (customErrorInfo?: Pick<ErrorInfo, \"message\">) => {\n\t\tconst errorVariantResult = resultModeMap[resultMode ?? \"all\"] as TCallApiResult;\n\n\t\treturn customErrorInfo\n\t\t\t? {\n\t\t\t\t\t...errorVariantResult,\n\t\t\t\t\terror: {\n\t\t\t\t\t\t...(errorVariantResult as CallApiResultErrorVariant<unknown>).error,\n\t\t\t\t\t\t...customErrorInfo,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: errorVariantResult;\n\t};\n\n\treturn { apiDetails, getErrorResult };\n};\n\ntype ErrorDetails<TErrorResponse> = {\n\tdefaultErrorMessage: string;\n\terrorData: TErrorResponse;\n\tresponse: Response;\n};\n\ntype ErrorOptions = {\n\tcause?: unknown;\n};\n\nexport class HTTPError<TErrorResponse = Record<string, unknown>> extends Error {\n\terrorData: ErrorDetails<TErrorResponse>[\"errorData\"];\n\n\tisHTTPError = true;\n\n\toverride name = \"HTTPError\" as const;\n\n\tresponse: ErrorDetails<TErrorResponse>[\"response\"];\n\n\tconstructor(errorDetails: ErrorDetails<TErrorResponse>, errorOptions?: ErrorOptions) {\n\t\tconst { defaultErrorMessage, errorData, response } = errorDetails;\n\n\t\tsuper((errorData as { message?: string } | undefined)?.message ?? defaultErrorMessage, errorOptions);\n\n\t\tthis.errorData = errorData;\n\t\tthis.response = response;\n\n\t\tError.captureStackTrace(this, this.constructor);\n\t}\n}\n","import { HTTPError } from \"../error\";\nimport type { PossibleHTTPError, PossibleJavaScriptError } from \"../types\";\nimport type { AnyFunction } from \"./type-helpers\";\n\ntype ErrorObjectUnion<TErrorData = unknown> = PossibleHTTPError<TErrorData> | PossibleJavaScriptError;\n\nexport const isHTTPError = <TErrorData>(\n\terror: ErrorObjectUnion<TErrorData> | null\n): error is PossibleHTTPError<TErrorData> => {\n\treturn isPlainObject(error) && error.name === \"HTTPError\";\n};\n\nexport const isHTTPErrorInstance = <TErrorResponse>(\n\terror: unknown\n): error is HTTPError<TErrorResponse> => {\n\treturn (\n\t\t// prettier-ignore\n\t\terror instanceof HTTPError|| (isPlainObject(error) && error.name === \"HTTPError\" && error.isHTTPError === true)\n\t);\n};\n\n// FIXME: Outsource to type-helpers later as a peer dependency\n\nexport const isArray = <TArrayItem>(value: unknown): value is TArrayItem[] => Array.isArray(value);\n\nexport const isObject = (value: unknown) => typeof value === \"object\" && value !== null;\n\nconst hasObjectPrototype = (value: unknown) => {\n\treturn Object.prototype.toString.call(value) === \"[object Object]\";\n};\n\n/**\n * @description Copied from TanStack Query's isPlainObject\n * @see https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L321\n */\nexport const isPlainObject = <TPlainObject extends Record<string, unknown>>(\n\tvalue: unknown\n): value is TPlainObject => {\n\tif (!hasObjectPrototype(value)) {\n\t\treturn false;\n\t}\n\n\t// If has no constructor\n\tconst constructor = (value as object | undefined)?.constructor;\n\tif (constructor === undefined) {\n\t\treturn true;\n\t}\n\n\t// If has modified prototype\n\tconst prototype = constructor.prototype as object;\n\tif (!hasObjectPrototype(prototype)) {\n\t\treturn false;\n\t}\n\n\t// If constructor does not have an Object-specific method\n\tif (!Object.hasOwn(prototype, \"isPrototypeOf\")) {\n\t\treturn false;\n\t}\n\n\t// Handles Objects created by Object.create(<arbitrary prototype>)\n\tif (Object.getPrototypeOf(value) !== Object.prototype) {\n\t\treturn false;\n\t}\n\n\t// It's probably a plain object at this point\n\treturn true;\n};\n\nexport const isJsonString = (value: unknown): value is string => {\n\tif (!isString(value)) {\n\t\treturn false;\n\t}\n\n\ttry {\n\t\tJSON.parse(value);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n};\n\nexport const isSerializable = (value: unknown) => {\n\treturn (\n\t\tisPlainObject(value)\n\t\t|| isArray(value)\n\t\t|| typeof (value as { toJSON: unknown } | undefined)?.toJSON === \"function\"\n\t);\n};\n\nexport const isFunction = <TFunction extends AnyFunction>(value: unknown): value is TFunction =>\n\ttypeof value === \"function\";\n\nexport const isQueryString = (value: unknown): value is string => isString(value) && value.includes(\"=\");\n\nexport const isString = (value: unknown) => typeof value === \"string\";\n\n// https://github.com/unjs/ofetch/blob/main/src/utils.ts\n// TODO Find a way to incorporate this function in checking when to apply the bodySerializer on the body and also whether to add the content type application/json\nexport const isJSONSerializable = (value: unknown) => {\n\tif (value === undefined) {\n\t\treturn false;\n\t}\n\tconst t = typeof value;\n\t// eslint-disable-next-line ts-eslint/no-unnecessary-condition -- No time to make this more type-safe\n\tif (t === \"string\" || t === \"number\" || t === \"boolean\" || t === null) {\n\t\treturn true;\n\t}\n\tif (t !== \"object\") {\n\t\treturn false;\n\t}\n\tif (isArray(value)) {\n\t\treturn true;\n\t}\n\tif ((value as Buffer | null)?.buffer) {\n\t\treturn false;\n\t}\n\n\treturn (\n\t\t(value?.constructor && value.constructor.name === \"Object\")\n\t\t// eslint-disable-next-line ts-eslint/prefer-nullish-coalescing -- Nullish coalescing makes no sense in this boolean context\n\t\t|| typeof (value as { toJSON: () => unknown } | null)?.toJSON === \"function\"\n\t);\n};\n\nexport const isReadableStream = (value: unknown): value is ReadableStream<unknown> => {\n\treturn value instanceof ReadableStream;\n};\n","/* eslint-disable perfectionist/sort-object-types -- Avoid Sorting for now */\n\nimport type { ExtraOptions } from \"./types/common\";\nimport { isFunction, isString } from \"./utils/guards\";\n\ntype ValueOrFunctionResult<TValue> = TValue | (() => TValue);\n\n/**\n * Bearer Or Token authentication\n *\n * The value of `bearer` will be added to a header as\n * `auth: Bearer some-auth-token`,\n *\n * The value of `token` will be added to a header as\n * `auth: Token some-auth-token`,\n */\nexport type BearerOrTokenAuth =\n\t| {\n\t\t\ttype?: \"Bearer\";\n\t\t\tbearer?: ValueOrFunctionResult<string | null>;\n\t\t\ttoken?: never;\n\t }\n\t| {\n\t\t\ttype?: \"Token\";\n\t\t\tbearer?: never;\n\t\t\ttoken?: ValueOrFunctionResult<string | null>;\n\t };\n\n/**\n * Basic auth\n */\nexport type BasicAuth = {\n\ttype: \"Basic\";\n\tusername: ValueOrFunctionResult<string | null | undefined>;\n\tpassword: ValueOrFunctionResult<string | null | undefined>;\n};\n\n/**\n * Custom auth\n *\n * @param prefix - prefix of the header\n * @param authValue - value of the header\n *\n * @example\n * ```ts\n * {\n * type: \"Custom\",\n * prefix: \"Token\",\n * authValue: \"token\"\n * }\n * ```\n */\nexport type CustomAuth = {\n\ttype: \"Custom\";\n\tprefix: ValueOrFunctionResult<string | null | undefined>;\n\tvalue: ValueOrFunctionResult<string | null | undefined>;\n};\n\n// eslint-disable-next-line perfectionist/sort-union-types -- Let the first one be first\nexport type Auth = BearerOrTokenAuth | BasicAuth | CustomAuth;\n\nconst getValue = (value: ValueOrFunctionResult<string | null | undefined>) => {\n\treturn isFunction(value) ? value() : value;\n};\n\ntype AuthorizationHeader = {\n\tAuthorization: string;\n};\n\nexport const getAuthHeader = (auth: ExtraOptions[\"auth\"]): false | AuthorizationHeader | undefined => {\n\tif (auth === undefined) return;\n\n\tif (isString(auth) || auth === null) {\n\t\treturn { Authorization: `Bearer ${auth}` };\n\t}\n\n\tswitch (auth.type) {\n\t\tcase \"Basic\": {\n\t\t\tconst username = getValue(auth.username);\n\t\t\tconst password = getValue(auth.password);\n\n\t\t\tif (username === undefined || password === undefined) return;\n\n\t\t\treturn {\n\t\t\t\tAuthorization: `Basic ${globalThis.btoa(`${username}:${password}`)}`,\n\t\t\t};\n\t\t}\n\n\t\tcase \"Custom\": {\n\t\t\tconst value = getValue(auth.value);\n\n\t\t\tif (value === undefined) return;\n\n\t\t\tconst prefix = getValue(auth.prefix);\n\n\t\t\treturn {\n\t\t\t\tAuthorization: `${prefix} ${value}`,\n\t\t\t};\n\t\t}\n\n\t\tdefault: {\n\t\t\tconst bearer = getValue(auth.bearer);\n\t\t\tconst token = getValue(auth.token);\n\n\t\t\tif (\"token\" in auth && token !== undefined) {\n\t\t\t\treturn { Authorization: `Token ${token}` };\n\t\t\t}\n\n\t\t\treturn bearer !== undefined && { Authorization: `Bearer ${bearer}` };\n\t\t}\n\t}\n};\n","// == These two types allows for adding arbitrary literal types, while still provided autocomplete for defaults.\n// == Usually intersection with \"{}\" or \"NonNullable<unknown>\" would make it work fine, but the placeholder with never type is added to make the AnyWhatever type appear last in a given union.\nexport type AnyString = string & { z_placeholder?: never };\nexport type AnyNumber = number & { z_placeholder?: never };\n\n// eslint-disable-next-line ts-eslint/no-explicit-any -- Any is fine here\nexport type AnyObject = Record<keyof any, any>;\n\n// eslint-disable-next-line ts-eslint/no-explicit-any -- Any is required here so that one can pass custom function type without type errors\nexport type AnyFunction<TResult = unknown> = (...args: any) => TResult;\n\nexport type CallbackFn<in TParams, out TResult = void> = (...params: TParams[]) => TResult;\n\nexport type Prettify<TObject> = NonNullable<unknown> & { [Key in keyof TObject]: TObject[Key] };\n\nexport type Writeable<TObject, TType extends \"deep\" | \"shallow\" = \"shallow\"> = {\n\t-readonly [key in keyof TObject]: TType extends \"shallow\"\n\t\t? TObject[key]\n\t\t: TType extends \"deep\"\n\t\t\t? TObject[key] extends object\n\t\t\t\t? Writeable<TObject[key], TType>\n\t\t\t\t: TObject[key]\n\t\t\t: never;\n};\n\nexport const defineEnum = <const TValue>(value: TValue) => value as Prettify<Writeable<TValue, \"deep\">>;\n\n// == Using this Immediately Indexed Mapped type helper to help show computed type of anything passed to it instead of just the type name\nexport type UnmaskType<TValue> = { _: TValue }[\"_\"];\n\nexport type Awaitable<TValue> = Promise<TValue> | TValue;\n\nexport type CommonRequestHeaders =\n\t| \"Access-Control-Allow-Credentials\"\n\t| \"Access-Control-Allow-Headers\"\n\t| \"Access-Control-Allow-Methods\"\n\t| \"Access-Control-Allow-Origin\"\n\t| \"Access-Control-Expose-Headers\"\n\t| \"Access-Control-Max-Age\"\n\t| \"Age\"\n\t| \"Allow\"\n\t| \"Cache-Control\"\n\t| \"Clear-Site-Data\"\n\t| \"Content-Disposition\"\n\t| \"Content-Encoding\"\n\t| \"Content-Language\"\n\t| \"Content-Length\"\n\t| \"Content-Location\"\n\t| \"Content-Range\"\n\t| \"Content-Security-Policy-Report-Only\"\n\t| \"Content-Security-Policy\"\n\t| \"Cookie\"\n\t| \"Cross-Origin-Embedder-Policy\"\n\t| \"Cross-Origin-Opener-Policy\"\n\t| \"Cross-Origin-Resource-Policy\"\n\t| \"Date\"\n\t| \"ETag\"\n\t| \"Expires\"\n\t| \"Last-Modified\"\n\t| \"Location\"\n\t| \"Permissions-Policy\"\n\t| \"Pragma\"\n\t| \"Retry-After\"\n\t| \"Save-Data\"\n\t| \"Sec-CH-Prefers-Color-Scheme\"\n\t| \"Sec-CH-Prefers-Reduced-Motion\"\n\t| \"Sec-CH-UA-Arch\"\n\t| \"Sec-CH-UA-Bitness\"\n\t| \"Sec-CH-UA-Form-Factor\"\n\t| \"Sec-CH-UA-Full-Version-List\"\n\t| \"Sec-CH-UA-Full-Version\"\n\t| \"Sec-CH-UA-Mobile\"\n\t| \"Sec-CH-UA-Model\"\n\t| \"Sec-CH-UA-Platform-Version\"\n\t| \"Sec-CH-UA-Platform\"\n\t| \"Sec-CH-UA-WoW64\"\n\t| \"Sec-CH-UA\"\n\t| \"Sec-Fetch-Dest\"\n\t| \"Sec-Fetch-Mode\"\n\t| \"Sec-Fetch-Site\"\n\t| \"Sec-Fetch-User\"\n\t| \"Sec-GPC\"\n\t| \"Server-Timing\"\n\t| \"Server\"\n\t| \"Service-Worker-Navigation-Preload\"\n\t| \"Set-Cookie\"\n\t| \"Strict-Transport-Security\"\n\t| \"Timing-Allow-Origin\"\n\t| \"Trailer\"\n\t| \"Transfer-Encoding\"\n\t| \"Upgrade\"\n\t| \"Vary\"\n\t| \"Warning\"\n\t| \"WWW-Authenticate\"\n\t| \"X-Content-Type-Options\"\n\t| \"X-DNS-Prefetch-Control\"\n\t| \"X-Frame-Options\"\n\t| \"X-Permitted-Cross-Domain-Policies\"\n\t| \"X-Powered-By\"\n\t| \"X-Robots-Tag\"\n\t| \"X-XSS-Protection\"\n\t| AnyString;\n\nexport type CommonAuthorizationHeaders = `${\"Basic\" | \"Bearer\" | \"Token\"} ${string}`;\n\nexport type CommonContentTypes =\n\t| \"application/epub+zip\"\n\t| \"application/gzip\"\n\t| \"application/json\"\n\t| \"application/ld+json\"\n\t| \"application/octet-stream\"\n\t| \"application/ogg\"\n\t| \"application/pdf\"\n\t| \"application/rtf\"\n\t| \"application/vnd.ms-fontobject\"\n\t| \"application/wasm\"\n\t| \"application/xhtml+xml\"\n\t| \"application/xml\"\n\t| \"application/zip\"\n\t| \"audio/aac\"\n\t| \"audio/mpeg\"\n\t| \"audio/ogg\"\n\t| \"audio/opus\"\n\t| \"audio/webm\"\n\t| \"audio/x-midi\"\n\t| \"font/otf\"\n\t| \"font/ttf\"\n\t| \"font/woff\"\n\t| \"font/woff2\"\n\t| \"image/avif\"\n\t| \"image/bmp\"\n\t| \"image/gif\"\n\t| \"image/jpeg\"\n\t| \"image/png\"\n\t| \"image/svg+xml\"\n\t| \"image/tiff\"\n\t| \"image/webp\"\n\t| \"image/x-icon\"\n\t| \"model/gltf-binary\"\n\t| \"model/gltf+json\"\n\t| \"text/calendar\"\n\t| \"text/css\"\n\t| \"text/csv\"\n\t| \"text/html\"\n\t| \"text/javascript\"\n\t| \"text/plain\"\n\t| \"video/3gpp\"\n\t| \"video/3gpp2\"\n\t| \"video/av1\"\n\t| \"video/mp2t\"\n\t| \"video/mp4\"\n\t| \"video/mpeg\"\n\t| \"video/ogg\"\n\t| \"video/webm\"\n\t| \"video/x-msvideo\"\n\t| AnyString;\n","/* eslint-disable ts-eslint/consistent-type-definitions -- I need to use interfaces for the sake of user overrides */\nimport type { Auth } from \"../auth\";\nimport type { CallApiPlugin, InferPluginOptions, Plugins } from \"../plugins\";\nimport type { GetResponseType, ResponseTypeUnion } from \"../response\";\nimport type { RetryOptions } from \"../retry\";\nimport type { RequestStreamContext, ResponseStreamContext } from \"../stream\";\nimport type { InitURL, UrlOptions } from \"../url\";\nimport type { ModifiedRequestInit, fetchSpecificKeys } from \"../utils/constants\";\nimport { type Awaitable, type Prettify, type UnmaskType, defineEnum } from \"../utils/type-helpers\";\nimport type { CallApiSchemas, CallApiValidators, InferSchemaResult } from \"../validation\";\nimport type {\n\tBodyOption,\n\tHeadersOption,\n\tMetaOption,\n\tMethodOption,\n\tResultModeOption,\n} from \"./conditional-types\";\nimport type {\n\tDefaultDataType,\n\tDefaultMoreOptions,\n\tDefaultPluginArray,\n\tDefaultThrowOnError,\n} from \"./default-types\";\n\ntype FetchSpecificKeysUnion = Exclude<(typeof fetchSpecificKeys)[number], \"body\" | \"headers\" | \"method\">;\n\nexport type CallApiRequestOptions<TSchemas extends CallApiSchemas = DefaultMoreOptions> = Prettify<\n\tBodyOption<TSchemas>\n\t\t& HeadersOption<TSchemas>\n\t\t& MethodOption<TSchemas>\n\t\t& Pick<ModifiedRequestInit, FetchSpecificKeysUnion>\n>;\n\nexport type CallApiRequestOptionsForHooks<TSchemas extends CallApiSchemas = DefaultMoreOptions> = Omit<\n\tCallApiRequestOptions<TSchemas>,\n\t\"headers\"\n> & {\n\theaders?: Record<string, string | undefined>;\n};\n\nexport type WithMoreOptions<TMoreOptions = DefaultMoreOptions> = {\n\toptions: CombinedCallApiExtraOptions & Partial<TMoreOptions>;\n};\n\nexport interface Interceptors<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTMoreOptions = DefaultMoreOptions,\n> {\n\t/**\n\t * Interceptor that will be called when any error occurs within the request/response lifecycle, regardless of whether the error is from the api or not.\n\t * It is basically a combination of `onRequestError` and `onResponseError` interceptors\n\t */\n\tonError?: (context: ErrorContext<TErrorData> & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;\n\n\t/**\n\t * Interceptor that will be called just before the request is made, allowing for modifications or additional operations.\n\t */\n\tonRequest?: (context: RequestContext & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;\n\n\t/**\n\t * Interceptor that will be called when an error occurs during the fetch request.\n\t */\n\tonRequestError?: (context: RequestErrorContext & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;\n\n\t/**\n\t * Interceptor that will be called when upload stream progress is tracked\n\t */\n\tonRequestStream?: (context: RequestStreamContext & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;\n\n\t/**\n\t * Interceptor that will be called when any response is received from the api, whether successful or not\n\t */\n\tonResponse?: (\n\t\tcontext: ResponseContext<TData, TErrorData> & WithMoreOptions<TMoreOptions>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Interceptor that will be called when an error response is received from the api.\n\t */\n\tonResponseError?: (\n\t\tcontext: ResponseErrorContext<TErrorData> & WithMoreOptions<TMoreOptions>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Interceptor that will be called when download stream progress is tracked\n\t */\n\tonResponseStream?: (\n\t\tcontext: ResponseStreamContext & WithMoreOptions<TMoreOptions>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Interceptor that will be called when a request is retried.\n\t */\n\tonRetry?: (response: ErrorContext<TErrorData> & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;\n\n\t/**\n\t * Interceptor that will be called when a successful response is received from the api.\n\t */\n\tonSuccess?: (context: SuccessContext<TData> & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;\n}\n\n/* eslint-disable perfectionist/sort-union-types -- I need arrays to be last */\nexport type InterceptorsOrInterceptorArray<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTMoreOptions = DefaultMoreOptions,\n> = {\n\t[Key in keyof Interceptors<TData, TErrorData, TMoreOptions>]:\n\t\t| Interceptors<TData, TErrorData, TMoreOptions>[Key]\n\t\t| Array<Interceptors<TData, TErrorData, TMoreOptions>[Key]>;\n};\n/* eslint-enable perfectionist/sort-union-types -- I need arrays to be last */\n\ntype FetchImpl = UnmaskType<(input: string | Request | URL, init?: RequestInit) => Promise<Response>>;\n\nexport type ExtraOptions<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResultMode extends ResultModeUnion = ResultModeUnion,\n\tTThrowOnError extends boolean = DefaultThrowOnError,\n\tTResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTPluginArray extends CallApiPlugin[] = DefaultPluginArray,\n\tTSchemas extends CallApiSchemas = DefaultMoreOptions,\n> = {\n\t/**\n\t * Authorization header value.\n\t */\n\tauth?: string | Auth | null;\n\t/**\n\t * Base URL to be prepended to all request URLs\n\t */\n\tbaseURL?: string;\n\n\t/**\n\t * Custom function to serialize the body object into a string.\n\t */\n\tbodySerializer?: (bodyData: Record<string, unknown>) => string;\n\n\t/**\n\t * Whether or not to clone the response, so response.json() and the like, can be read again else where.\n\t * @see https://developer.mozilla.org/en-US/docs/Web/API/Response/clone\n\t * @default false\n\t */\n\tcloneResponse?: boolean;\n\n\t/**\n\t * Custom fetch implementation\n\t */\n\tcustomFetchImpl?: FetchImpl;\n\n\t/**\n\t * Custom request key to be used to identify a request in the fetch deduplication strategy.\n\t * @default the full request url + string formed from the request options\n\t */\n\tdedupeKey?: string;\n\n\t/**\n\t * Defines the deduplication strategy for the request, can be set to \"none\" | \"defer\" | \"cancel\".\n\t * - If set to \"cancel\", the previous pending request with the same request key will be cancelled and lets the new request through.\n\t * - If set to \"defer\", all new request with the same request key will be share the same response, until the previous one is completed.\n\t * - If set to \"none\", deduplication is disabled.\n\t * @default \"cancel\"\n\t */\n\tdedupeStrategy?: \"cancel\" | \"defer\" | \"none\";\n\n\t/**\n\t * Default error message to use if none is provided from a response.\n\t * @default \"Failed to fetch data from server!\"\n\t */\n\tdefaultErrorMessage?: string;\n\n\t/**\n\t * If true, forces the calculation of the total byte size from the request or response body, in case the content-length header is not present or is incorrect.\n\t * @default false\n\t */\n\tforceStreamSizeCalc?: boolean | { request?: boolean; response?: boolean };\n\n\t/**\n\t * Resolved request URL\n\t */\n\treadonly fullURL?: string;\n\n\t/**\n\t * Defines the mode in which the merged hooks are executed, can be set to \"parallel\" | \"sequential\".\n\t * - If set to \"parallel\", main and plugin hooks will be executed in parallel.\n\t * - If set to \"sequential\", the plugin hooks will be executed first, followed by the main hook.\n\t * @default \"parallel\"\n\t */\n\tmergedHooksExecutionMode?: \"parallel\" | \"sequential\";\n\n\t/**\n\t * - Controls what order in which the merged hooks execute\n\t * @default \"mainHooksAfterPlugins\"\n\t */\n\tmergedHooksExecutionOrder?: \"mainHooksAfterPlugins\" | \"mainHooksBeforePlugins\";\n\n\t/**\n\t * An array of CallApi plugins. It allows you to extend the behavior of the library.\n\t */\n\tplugins?: Plugins<TPluginArray>;\n\n\t/**\n\t * Custom function to parse the response string into a object.\n\t */\n\tresponseParser?: (responseString: string) => Awaitable<Record<string, unknown>>;\n\n\t/**\n\t * Expected response type, affects how response is parsed\n\t * @default \"json\"\n\t */\n\tresponseType?: TResponseType;\n\n\t/**\n\t * Mode of the result, can influence how results are handled or returned.\n\t * Can be set to \"all\" | \"onlySuccess\" | \"onlyError\" | \"onlyResponse\".\n\t * @default \"all\"\n\t */\n\tresultMode?: TResultMode;\n\n\t/**\n\t * Type-safe schemas for the response validation.\n\t */\n\tschemas?: TSchemas;\n\n\t/**\n\t * If true or the function returns true, throws errors instead of returning them\n\t * The function is passed the error object and can be used to conditionally throw the error\n\t * @default false\n\t */\n\tthrowOnError?: TThrowOnError | ((context: ErrorContext<TErrorData>) => TThrowOnError);\n\n\t/**\n\t * Request timeout in milliseconds\n\t */\n\ttimeout?: number;\n\n\t/**\n\t * Custom validation functions for response validation\n\t */\n\tvalidators?: CallApiValidators<TData, TErrorData>;\n\t/* eslint-disable perfectionist/sort-intersection-types -- Allow these to be last for the sake of docs */\n} & InterceptorsOrInterceptorArray<TData, TErrorData>\n\t& Partial<InferPluginOptions<TPluginArray>>\n\t& MetaOption<TSchemas>\n\t& RetryOptions<TErrorData>\n\t& ResultModeOption<TErrorData, TResultMode>\n\t& UrlOptions<TSchemas>;\n/* eslint-enable perfectionist/sort-intersection-types -- Allow these to be last for the sake of docs */\n\nexport const optionsEnumToExtendFromBase = defineEnum([\"plugins\", \"validators\", \"schemas\"] satisfies Array<\n\tkeyof ExtraOptions\n>);\n\nexport type CallApiExtraOptions<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResultMode extends ResultModeUnion = ResultModeUnion,\n\tTThrowOnError extends boolean = DefaultThrowOnError,\n\tTResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTPluginArray extends CallApiPlugin[] = DefaultPluginArray,\n\tTSchemas extends CallApiSchemas = DefaultMoreOptions,\n> = ExtraOptions<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TPluginArray, TSchemas> & {\n\t/**\n\t * Options that should extend the base options.\n\t */\n\textend?: Pick<\n\t\tExtraOptions<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TPluginArray, TSchemas>,\n\t\t(typeof optionsEnumToExtendFromBase)[number]\n\t>;\n};\n\nexport const optionsEnumToOmitFromBase = defineEnum([\"extend\", \"dedupeKey\"] satisfies Array<\n\tkeyof CallApiExtraOptions\n>);\n\nexport type BaseCallApiExtraOptions<\n\tTBaseData = DefaultDataType,\n\tTBaseErrorData = DefaultDataType,\n\tTBaseResultMode extends ResultModeUnion = ResultModeUnion,\n\tTBaseThrowOnError extends boolean = DefaultThrowOnError,\n\tTBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTBasePluginArray extends CallApiPlugin[] = DefaultPluginArray,\n\tTBaseSchemas extends CallApiSchemas = DefaultMoreOptions,\n> = Omit<\n\tPartial<\n\t\tCallApiExtraOptions<\n\t\t\tTBaseData,\n\t\t\tTBaseErrorData,\n\t\t\tTBaseResultMode,\n\t\t\tTBaseThrowOnError,\n\t\t\tTBaseResponseType,\n\t\t\tTBasePluginArray,\n\t\t\tTBaseSchemas\n\t\t>\n\t>,\n\t(typeof optionsEnumToOmitFromBase)[number]\n> & {\n\t/**\n\t * If true, the base options will not be merged with the main options by default.\n\t *\n\t * It's recommended to set this to true when you want to handle the options merge manually from the createFetchClient config function signature.\n\t *\n\t * This helps prevent main options from overriding base options by default.\n\t * @default false\n\t */\n\tmergeMainOptionsManuallyFromBase?: boolean;\n};\n\nexport type CombinedCallApiExtraOptions = Interceptors\n\t& Omit<BaseCallApiExtraOptions & CallApiExtraOptions, keyof Interceptors>;\n\nexport type BaseCallApiConfig<\n\tTBaseData = DefaultDataType,\n\tTBaseErrorData = DefaultDataType,\n\tTBaseResultMode extends ResultModeUnion = ResultModeUnion,\n\tTBaseThrowOnError extends boolean = DefaultThrowOnError,\n\tTBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTBasePluginArray extends CallApiPlugin[] = DefaultPluginArray,\n\tTBaseSchemas extends CallApiSchemas = DefaultMoreOptions,\n> =\n\t| (CallApiRequestOptions<TBaseSchemas> // eslint-disable-next-line perfectionist/sort-intersection-types -- Allow\n\t\t\t& BaseCallApiExtraOptions<\n\t\t\t\tTBaseData,\n\t\t\t\tTBaseErrorData,\n\t\t\t\tTBaseResultMode,\n\t\t\t\tTBaseThrowOnError,\n\t\t\t\tTBaseResponseType,\n\t\t\t\tTBasePluginArray,\n\t\t\t\tTBaseSchemas\n\t\t\t>)\n\t| ((context: {\n\t\t\tinitURL: string;\n\t\t\toptions: CallApiExtraOptions;\n\t\t\trequest: CallApiRequestOptions;\n\t }) => CallApiRequestOptions<TBaseSchemas> // eslint-disable-next-line perfectionist/sort-intersection-types -- Allow\n\t\t\t& BaseCallApiExtraOptions<\n\t\t\t\tTBaseData,\n\t\t\t\tTBaseErrorData,\n\t\t\t\tTBaseResultMode,\n\t\t\t\tTBaseThrowOnError,\n\t\t\t\tTBaseResponseType,\n\t\t\t\tTBasePluginArray,\n\t\t\t\tTBaseSchemas\n\t\t\t>);\n\nexport type CallApiConfig<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResultMode extends ResultModeUnion = ResultModeUnion,\n\tTThrowOnError extends boolean = DefaultThrowOnError,\n\tTResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTPluginArray extends CallApiPlugin[] = DefaultPluginArray,\n\tTSchemas extends CallApiSchemas = DefaultMoreOptions,\n> = CallApiRequestOptions<TSchemas> // eslint-disable-next-line perfectionist/sort-intersection-types -- Allow these to be last for the sake of docs\n\t& CallApiExtraOptions<\n\t\tTData,\n\t\tTErrorData,\n\t\tTResultMode,\n\t\tTThrowOnError,\n\t\tTResponseType,\n\t\tTPluginArray,\n\t\tTSchemas\n\t>;\n\nexport type CallApiParameters<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResultMode extends ResultModeUnion = ResultModeUnion,\n\tTThrowOnError extends boolean = DefaultThrowOnError,\n\tTResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTPluginArray extends CallApiPlugin[] = DefaultPluginArray,\n\tTSchemas extends CallApiSchemas = DefaultMoreOptions,\n> = [\n\tinitURL: InferSchemaResult<TSchemas[\"initURL\"], InitURL>,\n\tconfig?: CallApiConfig<\n\t\tTData,\n\t\tTErrorData,\n\t\tTResultMode,\n\t\tTThrowOnError,\n\t\tTResponseType,\n\t\tTPluginArray,\n\t\tTSchemas\n\t>,\n];\n\nexport type RequestContext = UnmaskType<{\n\toptions: CombinedCallApiExtraOptions;\n\trequest: CallApiRequestOptionsForHooks;\n}>;\n\nexport type ResponseContext<TData, TErrorData> = UnmaskType<\n\t| {\n\t\t\tdata: TData;\n\t\t\terror: null;\n\t\t\toptions: CombinedCallApiExtraOptions;\n\t\t\trequest: CallApiRequestOptionsForHooks;\n\t\t\tresponse: Response;\n\t }\n\t// eslint-disable-next-line perfectionist/sort-union-types -- I need the first one to be first\n\t| {\n\t\t\tdata: null;\n\t\t\terror: PossibleHTTPError<TErrorData>;\n\t\t\toptions: CombinedCallApiExtraOptions;\n\t\t\trequest: CallApiRequestOptionsForHooks;\n\t\t\tresponse: Response;\n\t }\n>;\n\nexport type SuccessContext<TData> = UnmaskType<{\n\tdata: TData;\n\toptions: CombinedCallApiExtraOptions;\n\trequest: CallApiRequestOptionsForHooks;\n\tresponse: Response;\n}>;\n\nexport type PossibleJavascriptErrorNames =\n\t| \"AbortError\"\n\t| \"Error\"\n\t| \"SyntaxError\"\n\t| \"TimeoutError\"\n\t| \"TypeError\"\n\t| (`${string}Error` & DefaultMoreOptions);\n\nexport type PossibleJavaScriptError = UnmaskType<{\n\terrorData: DOMException | Error | SyntaxError | TypeError;\n\tmessage: string;\n\tname: PossibleJavascriptErrorNames;\n}>;\n\nexport type PossibleHTTPError<TErrorData> = UnmaskType<{\n\terrorData: TErrorData;\n\tmessage: string;\n\tname: \"HTTPError\";\n}>;\n\nexport type RequestErrorContext = UnmaskType<{\n\terror: PossibleJavaScriptError;\n\toptions: CombinedCallApiExtraOptions;\n\trequest: CallApiRequestOptionsForHooks;\n\tresponse: null;\n}>;\n\nexport type ResponseErrorContext<TErrorData> = UnmaskType<{\n\terror: PossibleHTTPError<TErrorData>;\n\toptions: CombinedCallApiExtraOptions;\n\trequest: CallApiRequestOptionsForHooks;\n\tresponse: Response;\n}>;\n\nexport type ErrorContext<TErrorData> = UnmaskType<\n\t| {\n\t\t\terror: PossibleHTTPError<TErrorData>;\n\t\t\toptions: CombinedCallApiExtraOptions;\n\t\t\trequest: CallApiRequestOptionsForHooks;\n\t\t\tresponse: Response;\n\t }\n\t| {\n\t\t\terror: PossibleJavaScriptError;\n\t\t\toptions: CombinedCallApiExtraOptions;\n\t\t\trequest: CallApiRequestOptionsForHooks;\n\t\t\tresponse: null;\n\t }\n>;\n\nexport type CallApiResultSuccessVariant<TData> = {\n\tdata: TData;\n\terror: null;\n\tresponse: Response;\n};\n\nexport type CallApiResultErrorVariant<TErrorData> =\n\t| {\n\t\t\tdata: null;\n\t\t\terror: PossibleHTTPError<TErrorData>;\n\t\t\tresponse: Response;\n\t }\n\t| {\n\t\t\tdata: null;\n\t\t\terror: PossibleJavaScriptError;\n\t\t\tresponse: null;\n\t };\n\nexport type ResultModeMap<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTComputedData = GetResponseType<TData, TResponseType>,\n\tTComputedErrorData = GetResponseType<TErrorData, TResponseType>,\n> = UnmaskType<{\n\t/* eslint-disable perfectionist/sort-union-types -- I need the first one to be first */\n\tall: CallApiResultSuccessVariant<TComputedData> | CallApiResultErrorVariant<TComputedErrorData>;\n\n\tallWithException: CallApiResultSuccessVariant<TComputedData>;\n\n\tallWithoutResponse:\n\t\t| CallApiResultSuccessVariant<TComputedData>[\"data\" | \"error\"]\n\t\t| CallApiResultErrorVariant<TComputedErrorData>[\"data\" | \"error\"];\n\n\tonlyError:\n\t\t| CallApiResultSuccessVariant<TComputedData>[\"error\"]\n\t\t| CallApiResultErrorVariant<TComputedErrorData>[\"error\"];\n\n\tonlyResponse:\n\t\t| CallApiResultErrorVariant<TComputedErrorData>[\"response\"]\n\t\t| CallApiResultSuccessVariant<TComputedData>[\"response\"];\n\n\tonlyResponseWithException: CallApiResultSuccessVariant<TComputedData>[\"response\"];\n\n\tonlySuccess:\n\t\t| CallApiResultErrorVariant<TComputedErrorData>[\"data\"]\n\t\t| CallApiResultSuccessVariant<TComputedData>[\"data\"];\n\n\tonlySuccessWithException: CallApiResultSuccessVariant<TComputedData>[\"data\"];\n\t/* eslint-enable perfectionist/sort-union-types -- I need the first one to be first */\n}>;\n\nexport type ResultModeUnion = keyof ResultModeMap | undefined;\n\nexport type GetCallApiResult<\n\tTData,\n\tTErrorData,\n\tTResultMode extends ResultModeUnion,\n\tTThrowOnError extends boolean,\n\tTResponseType extends ResponseTypeUnion,\n> = TErrorData extends false | undefined\n\t? ResultModeMap<TData, TErrorData, TResponseType>[\"onlySuccessWithException\"]\n\t: ResultModeUnion | undefined extends TResultMode\n\t\t? TThrowOnError extends true\n\t\t\t? ResultModeMap<TData, TErrorData, TResponseType>[\"allWithException\"]\n\t\t\t: ResultModeMap<TData, TErrorData, TResponseType>[\"all\"]\n\t\t: TResultMode extends NonNullable<ResultModeUnion>\n\t\t\t? TResultMode extends \"onlySuccess\"\n\t\t\t\t? ResultModeMap<TData, TErrorData, TResponseType>[\"onlySuccessWithException\"]\n\t\t\t\t: TResultMode extends \"onlyResponse\"\n\t\t\t\t\t? ResultModeMap<TData, TErrorData, TResponseType>[\"onlyResponseWithException\"]\n\t\t\t\t\t: ResultModeMap<TData, TErrorData, TResponseType>[TResultMode]\n\t\t\t: never;\n\nexport type CallApiResult<\n\tTData,\n\tTErrorData,\n\tTResultMode extends ResultModeUnion,\n\tTThrowOnError extends boolean,\n\tTResponseType extends ResponseTypeUnion,\n> = Promise<GetCallApiResult<TData, TErrorData, TResultMode, TThrowOnError, TResponseType>>;\n","import type {\n\tBaseCallApiExtraOptions,\n\tCallApiRequestOptions,\n\tCombinedCallApiExtraOptions,\n} from \"../types/common\";\nimport { defineEnum } from \"./type-helpers\";\n\nexport type ModifiedRequestInit = RequestInit & { duplex?: \"half\" };\n\nexport const fetchSpecificKeys = defineEnum([\n\t\"body\",\n\t\"integrity\",\n\t\"duplex\",\n\t\"method\",\n\t\"headers\",\n\t\"signal\",\n\t\"cache\",\n\t\"redirect\",\n\t\"window\",\n\t\"credentials\",\n\t\"keepalive\",\n\t\"referrer\",\n\t\"priority\",\n\t\"mode\",\n\t\"referrerPolicy\",\n] satisfies Array<keyof ModifiedRequestInit> as Array<keyof ModifiedRequestInit>);\n\nconst retryStatusCodesLookup = defineEnum({\n\t408: \"Request Timeout\",\n\t409: \"Conflict\",\n\t425: \"Too Early\",\n\t429: \"Too Many Requests\",\n\t500: \"Internal Server Error\",\n\t502: \"Bad Gateway\",\n\t503: \"Service Unavailable\",\n\t504: \"Gateway Timeout\",\n});\n\nexport const defaultRetryMethods = [\"GET\", \"POST\"] satisfies BaseCallApiExtraOptions[\"retryMethods\"];\n\n// prettier-ignore\nexport const defaultRetryStatusCodes = Object.keys(retryStatusCodesLookup).map(Number) as Required<BaseCallApiExtraOptions>[\"retryStatusCodes\"];\n\nexport const defaultExtraOptions = {\n\tbaseURL: \"\",\n\tbodySerializer: JSON.stringify,\n\tdedupeStrategy: \"cancel\",\n\tdefaultErrorMessage: \"Failed to fetch data from server!\",\n\tmergedHooksExecutionMode: \"parallel\",\n\tmergedHooksExecutionOrder: \"mainHooksAfterPlugins\",\n\tresponseType: \"json\",\n\tresultMode: \"all\",\n\tretryAttempts: 0,\n\tretryDelay: 1000,\n\tretryMaxDelay: 10000,\n\tretryMethods: defaultRetryMethods,\n\tretryStatusCodes: defaultRetryStatusCodes,\n\tretryStrategy: \"linear\",\n} satisfies CombinedCallApiExtraOptions;\n\nexport const defaultRequestOptions = {\n\tmethod: \"GET\",\n} satisfies CallApiRequestOptions;\n\nexport const getDefaultOptions = () => defaultExtraOptions;\n\nexport const getDefaultRequest = () => defaultRequestOptions;\n","import { getAuthHeader } from \"../auth\";\nimport {\n\ttype BaseCallApiExtraOptions,\n\ttype CallApiExtraOptions,\n\ttype CallApiRequestOptions,\n\toptionsEnumToOmitFromBase,\n} from \"../types/common\";\nimport { fetchSpecificKeys } from \"./constants\";\nimport { isArray, isFunction, isJsonString, isPlainObject, isQueryString, isSerializable } from \"./guards\";\nimport type { AnyFunction, Awaitable } from \"./type-helpers\";\n\nexport const omitKeys = <\n\tTObject extends Record<string, unknown>,\n\tconst TOmitArray extends Array<keyof TObject>,\n>(\n\tinitialObject: TObject,\n\tkeysToOmit: TOmitArray\n) => {\n\tconst updatedObject = {} as Record<string, unknown>;\n\n\tconst keysToOmitSet = new Set(keysToOmit);\n\n\tfor (const [key, value] of Object.entries(initialObject)) {\n\t\tif (!keysToOmitSet.has(key)) {\n\t\t\tupdatedObject[key] = value;\n\t\t}\n\t}\n\n\treturn updatedObject as Omit<TObject, TOmitArray[number]>;\n};\n\nexport const pickKeys = <\n\tTObject extends Record<string, unknown>,\n\tconst TPickArray extends Array<keyof TObject>,\n>(\n\tinitialObject: TObject,\n\tkeysToPick: TPickArray\n) => {\n\tconst updatedObject = {} as Record<string, unknown>;\n\n\tconst keysToPickSet = new Set(keysToPick);\n\n\tfor (const [key, value] of Object.entries(initialObject)) {\n\t\tif (keysToPickSet.has(key)) {\n\t\t\tupdatedObject[key] = value;\n\t\t}\n\t}\n\n\treturn updatedObject as Pick<TObject, TPickArray[number]>;\n};\n\n// eslint-disable-next-line ts-eslint/no-explicit-any -- Any is required here so that one can pass custom function type without type errors\nexport const splitBaseConfig = (baseConfig: Record<string, any>) =>\n\t[\n\t\tpickKeys(baseConfig, fetchSpecificKeys) as CallApiRequestOptions,\n\t\tomitKeys(baseConfig, [\n\t\t\t...fetchSpecificKeys,\n\t\t\t...optionsEnumToOmitFromBase,\n\t\t]) as BaseCallApiExtraOptions,\n\t] as const;\n\n// eslint-disable-next-line ts-eslint/no-explicit-any -- Any is required here so that one can pass custom function type without type errors\nexport const splitConfig = (config: Record<string, any>) =>\n\t[\n\t\tpickKeys(config, fetchSpecificKeys) as CallApiRequestOptions,\n\t\tomitKeys(config, fetchSpecificKeys) as CallApiExtraOptions,\n\t] as const;\n\ntype ToQueryStringFn = {\n\t(params: CallApiExtraOptions[\"query\"]): string | null;\n\t(params: Required<CallApiExtraOptions>[\"query\"]): string;\n};\n\nexport const toQueryString: ToQueryStringFn = (params) => {\n\tif (!params) {\n\t\tconsole.error(\"toQueryString:\", \"No query params provided!\");\n\n\t\treturn null as never;\n\t}\n\n\treturn new URLSearchParams(params as Record<string, string>).toString();\n};\n\nexport const objectifyHeaders = (headers: CallApiRequestOptions[\"headers\"]) => {\n\tif (!headers || isPlainObject(headers)) {\n\t\treturn headers;\n\t}\n\n\treturn Object.fromEntries(headers);\n};\n\ntype MergeAndResolveHeadersOptions = {\n\tauth: CallApiExtraOptions[\"auth\"];\n\tbaseHeaders?: CallApiRequestOptions[\"headers\"];\n\tbody: CallApiRequestOptions[\"body\"];\n\theaders: CallApiRequestOptions[\"headers\"];\n};\n\nexport const mergeAndResolveHeaders = (options: MergeAndResolveHeadersOptions) => {\n\tconst { auth, baseHeaders, body, headers } = options;\n\n\t// eslint-disable-next-line ts-eslint/prefer-nullish-coalescing -- Nullish coalescing makes no sense in this boolean context\n\tconst shouldResolveHeaders = Boolean(baseHeaders || headers || body || auth);\n\n\t// == Return early if any of the following conditions are not met (so that native fetch would auto set the correct headers):\n\t// == - headers are provided\n\t// == - The body is an object\n\t// == - The auth option is provided\n\tif (!shouldResolveHeaders) return;\n\n\tconst headersObject: Record<string, string | undefined> = {\n\t\t...getAuthHeader(auth),\n\t\t...objectifyHeaders(baseHeaders),\n\t\t...objectifyHeaders(headers),\n\t};\n\n\tif (isQueryString(body)) {\n\t\theadersObject[\"Content-Type\"] = \"application/x-www-form-urlencoded\";\n\n\t\treturn headersObject;\n\t}\n\n\tif (isSerializable(body) || isJsonString(body)) {\n\t\theadersObject[\"Content-Type\"] = \"application/json\";\n\t\theadersObject.Accept = \"application/json\";\n\t}\n\n\treturn headersObject;\n};\n\nexport const combineHooks = <TInterceptor extends AnyFunction | Array<AnyFunction | undefined>>(\n\tbaseInterceptor: TInterceptor | undefined,\n\tinterceptor: TInterceptor | undefined\n) => {\n\tif (isArray(baseInterceptor)) {\n\t\treturn [baseInterceptor, interceptor].flat() as TInterceptor;\n\t}\n\n\treturn interceptor ?? baseInterceptor;\n};\n\nexport const getFetchImpl = (customFetchImpl: CallApiExtraOptions[\"customFetchImpl\"]) => {\n\tif (customFetchImpl) {\n\t\treturn customFetchImpl;\n\t}\n\n\tif (typeof globalThis !== \"undefined\" && isFunction(globalThis.fetch)) {\n\t\treturn globalThis.fetch;\n\t}\n\n\tthrow new Error(\"No fetch implementation found\");\n};\n\nexport const executeHooks = <TInterceptor extends Awaitable<unknown>>(...interceptors: TInterceptor[]) =>\n\tPromise.all(interceptors);\n\nconst PromiseWithResolvers = () => {\n\tlet reject!: (reason?: unknown) => void;\n\tlet resolve!: (value: unknown) => void;\n\n\tconst promise = new Promise((res, rej) => {\n\t\tresolve = res;\n\t\treject = rej;\n\t});\n\n\treturn { promise, reject, resolve };\n};\n\nexport const waitUntil = (delay: number) => {\n\tif (delay === 0) return;\n\n\tconst { promise, resolve } = PromiseWithResolvers();\n\n\tsetTimeout(resolve, delay);\n\n\treturn promise;\n};\n","import type { CallApiRequestOptionsForHooks, CombinedCallApiExtraOptions } from \"./types\";\nimport { executeHooks } from \"./utils/common\";\nimport { isObject } from \"./utils/guards\";\n\nexport type StreamProgressEvent = {\n\t/**\n\t * Current chunk of data being streamed\n\t */\n\tchunk: Uint8Array;\n\t/**\n\t * Progress in percentage\n\t */\n\tprogress: number;\n\t/**\n\t * Total size of data in bytes\n\t */\n\ttotalBytes: number;\n\t/**\n\t * Amount of data transferred so far\n\t */\n\ttransferredBytes: number;\n};\n\nexport type RequestStreamContext = {\n\tevent: StreamProgressEvent;\n\toptions: CombinedCallApiExtraOptions;\n\trequest: CallApiRequestOptionsForHooks;\n\trequestInstance: Request;\n};\n\nexport type ResponseStreamContext = {\n\tevent: StreamProgressEvent;\n\toptions: CombinedCallApiExtraOptions;\n\trequest: CallApiRequestOptionsForHooks;\n\tresponse: Response;\n};\n\ndeclare global {\n\t// eslint-disable-next-line ts-eslint/consistent-type-definitions -- Allow\n\tinterface ReadableStream<R> {\n\t\t[Symbol.asyncIterator]: () => AsyncIterableIterator<R>;\n\t}\n}\n\nconst createProgressEvent = (options: {\n\tchunk: Uint8Array;\n\ttotalBytes: number;\n\ttransferredBytes: number;\n}): StreamProgressEvent => {\n\tconst { chunk, totalBytes, transferredBytes } = options;\n\n\treturn {\n\t\tchunk,\n\t\tprogress: Math.round((transferredBytes / totalBytes) * 100) || 0,\n\t\ttotalBytes,\n\t\ttransferredBytes,\n\t};\n};\n\nconst calculateTotalBytesFromBody = async (\n\trequestBody: Request[\"body\"] | null,\n\texistingTotalBytes: number\n) => {\n\tlet totalBytes = existingTotalBytes;\n\n\tif (!requestBody) {\n\t\treturn totalBytes;\n\t}\n\n\tfor await (const chunk of requestBody) {\n\t\ttotalBytes += chunk.byteLength;\n\t}\n\n\treturn totalBytes;\n};\n\ntype StreamableRequestContext = {\n\toptions: CombinedCallApiExtraOptions;\n\trequest: CallApiRequestOptionsForHooks;\n\trequestInstance: Request;\n};\n\nexport const toStreamableRequest = async (context: StreamableRequestContext) => {\n\tconst { options, request, requestInstance } = context;\n\n\tif (!options.onRequestStream || !requestInstance.body) return;\n\n\tconst contentLength =\n\t\trequestInstance.headers.get(\"content-length\")\n\t\t?? new Headers(request.headers as HeadersInit).get(\"content-length\")\n\t\t?? (request.body as Blob | null)?.size;\n\n\tlet totalBytes = Number(contentLength ?? 0);\n\n\tconst shouldForceContentLengthCalc = isObject(options.forceStreamSizeCalc)\n\t\t? options.forceStreamSizeCalc.request\n\t\t: options.forceStreamSizeCalc;\n\n\t// If no content length is present, we read the total bytes from the body\n\tif (!contentLength && shouldForceContentLengthCalc) {\n\t\ttotalBytes = await calculateTotalBytesFromBody(requestInstance.clone().body, totalBytes);\n\t}\n\n\tlet transferredBytes = 0;\n\n\tawait executeHooks(\n\t\toptions.onRequestStream({\n\t\t\tevent: createProgressEvent({ chunk: new Uint8Array(), totalBytes, transferredBytes }),\n\t\t\toptions,\n\t\t\trequest,\n\t\t\trequestInstance,\n\t\t})\n\t);\n\n\tconst body = requestInstance.body as ReadableStream<Uint8Array> | null;\n\n\tvoid new ReadableStream({\n\t\tstart: async (controller) => {\n\t\t\tif (!body) return;\n\n\t\t\tfor await (const chunk of body) {\n\t\t\t\ttransferredBytes += chunk.byteLength;\n\n\t\t\t\ttotalBytes = Math.max(totalBytes, transferredBytes);\n\n\t\t\t\tawait executeHooks(\n\t\t\t\t\toptions.onRequestStream?.({\n\t\t\t\t\t\tevent: createProgressEvent({ chunk, totalBytes, transferredBytes }),\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\trequestInstance,\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t}\n\t\t\tcontroller.close();\n\t\t},\n\t});\n};\n\ntype StreamableResponseContext = {\n\toptions: CombinedCallApiExtraOptions;\n\trequest: CallApiRequestOptionsForHooks;\n\tresponse: Response;\n};\nexport const toStreamableResponse = async (context: StreamableResponseContext): Promise<Response> => {\n\tconst { options, request, response } = context;\n\n\tif (!options.onResponseStream || !response.body) {\n\t\treturn response;\n\t}\n\n\tconst contentLength = response.headers.get(\"content-length\");\n\n\tlet totalBytes = Number(contentLength ?? 0);\n\n\tconst shouldForceContentLengthCalc = isObject(options.forceStreamSizeCalc)\n\t\t? options.forceStreamSizeCalc.response\n\t\t: options.forceStreamSizeCalc;\n\n\t// If no content length is present and `forceContentLengthCalculation` is enabled, we read the total bytes from the body\n\tif (!contentLength && shouldForceContentLengthCalc) {\n\t\ttotalBytes = await calculateTotalBytesFromBody(response.clone().body, totalBytes);\n\t}\n\n\tlet transferredBytes = 0;\n\n\tawait executeHooks(\n\t\toptions.onResponseStream({\n\t\t\tevent: createProgressEvent({ chunk: new Uint8Array(), totalBytes, transferredBytes }),\n\t\t\toptions,\n\t\t\trequest,\n\t\t\tresponse,\n\t\t})\n\t);\n\n\tconst body = response.body as ReadableStream<Uint8Array> | null;\n\n\tconst stream = new ReadableStream({\n\t\tstart: async (controller) => {\n\t\t\tif (!body) return;\n\n\t\t\tfor await (const chunk of body) {\n\t\t\t\ttransferredBytes += chunk.byteLength;\n\n\t\t\t\ttotalBytes = Math.max(totalBytes, transferredBytes);\n\n\t\t\t\tawait executeHooks(\n\t\t\t\t\toptions.onResponseStream?.({\n\t\t\t\t\t\tevent: createProgressEvent({ chunk, totalBytes, transferredBytes }),\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\tresponse,\n\t\t\t\t\t})\n\t\t\t\t);\n\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t}\n\n\t\t\tcontroller.close();\n\t\t},\n\t});\n\n\treturn new Response(stream, response);\n};\n","import { toStreamableRequest, toStreamableResponse } from \"./stream\";\nimport type {\n\tCallApiRequestOptions,\n\tCallApiRequestOptionsForHooks,\n\tCombinedCallApiExtraOptions,\n} from \"./types/common\";\nimport { getFetchImpl, waitUntil } from \"./utils/common\";\nimport { isReadableStream } from \"./utils/guards\";\n\ntype RequestInfo = {\n\tcontroller: AbortController;\n\tresponsePromise: Promise<Response>;\n};\n\nexport type RequestInfoCache = Map<string | null, RequestInfo>;\n\ntype DedupeContext = {\n\t$RequestInfoCache: RequestInfoCache;\n\tnewFetchController: AbortController;\n\toptions: CombinedCallApiExtraOptions;\n\trequest: CallApiRequestOptions;\n};\n\nexport const createDedupeStrategy = async (context: DedupeContext) => {\n\tconst { $RequestInfoCache, newFetchController, options, request } = context;\n\n\tconst generateDedupeKey = () => {\n\t\tconst shouldHaveDedupeKey =\n\t\t\toptions.dedupeStrategy === \"cancel\" || options.dedupeStrategy === \"defer\";\n\n\t\tif (!shouldHaveDedupeKey) {\n\t\t\treturn null;\n\t\t}\n\n\t\treturn `${options.fullURL}-${JSON.stringify({ options, request })}`;\n\t};\n\n\tconst dedupeKey = options.dedupeKey ?? generateDedupeKey();\n\n\t// == This is to ensure cache operations only occur when key is available\n\tconst $RequestInfoCacheOrNull = dedupeKey !== null ? $RequestInfoCache : null;\n\n\t/******\n\t * == Add a small delay to the execution to ensure proper request deduplication when multiple requests with the same key start simultaneously.\n\t * == This gives time for the cache to be updated with the previous request info before the next request checks it.\n\t ******/\n\tif (dedupeKey !== null) {\n\t\tawait waitUntil(0.1);\n\t}\n\n\tconst prevRequestInfo = $RequestInfoCacheOrNull?.get(dedupeKey);\n\n\tconst handleRequestCancelStrategy = () => {\n\t\tconst shouldCancelRequest = prevRequestInfo && options.dedupeStrategy === \"cancel\";\n\n\t\tif (!shouldCancelRequest) return;\n\n\t\tconst message = options.dedupeKey\n\t\t\t? `Duplicate request detected - Aborting previous request with key '${options.dedupeKey}' as a new request was initiated`\n\t\t\t: `Duplicate request detected - Aborting previous request to '${options.fullURL}' as a new request with identical options was initiated`;\n\n\t\tconst reason = new DOMException(message, \"AbortError\");\n\n\t\tprevRequestInfo.controller.abort(reason);\n\n\t\t// == Adding this just so that eslint forces me put await when calling the function (it looks better that way tbh)\n\t\treturn Promise.resolve();\n\t};\n\n\tconst handleRequestDeferStrategy = async () => {\n\t\tconst fetchApi = getFetchImpl(options.customFetchImpl);\n\n\t\tconst shouldUsePromiseFromCache = prevRequestInfo && options.dedupeStrategy === \"defer\";\n\n\t\tconst requestInstance = new Request(\n\t\t\toptions.fullURL as NonNullable<typeof options.fullURL>,\n\t\t\t(isReadableStream(request.body) && !request.duplex\n\t\t\t\t? { ...request, duplex: \"half\" }\n\t\t\t\t: request) as RequestInit\n\t\t);\n\n\t\tvoid toStreamableRequest({\n\t\t\toptions,\n\t\t\trequest: request as CallApiRequestOptionsForHooks,\n\t\t\trequestInstance: requestInstance.clone(),\n\t\t});\n\n\t\tconst responsePromise = shouldUsePromiseFromCache\n\t\t\t? prevRequestInfo.responsePromise\n\t\t\t: // eslint-disable-next-line unicorn/no-nested-ternary -- Allow\n\t\t\t\tisReadableStream(request.body)\n\t\t\t\t? fetchApi(requestInstance.clone())\n\t\t\t\t: fetchApi(options.fullURL as NonNullable<typeof options.fullURL>, request as RequestInit);\n\n\t\t$RequestInfoCacheOrNull?.set(dedupeKey, { controller: newFetchController, responsePromise });\n\n\t\tconst streamableResponse = toStreamableResponse({\n\t\t\toptions,\n\t\t\trequest: request as CallApiRequestOptionsForHooks,\n\t\t\tresponse: await responsePromise,\n\t\t});\n\n\t\treturn streamableResponse;\n\t};\n\n\tconst removeDedupeKeyFromCache = () => $RequestInfoCacheOrNull?.delete(dedupeKey);\n\n\treturn {\n\t\thandleRequestCancelStrategy,\n\t\thandleRequestDeferStrategy,\n\t\tremoveDedupeKeyFromCache,\n\t};\n};\n","/* eslint-disable ts-eslint/consistent-type-definitions -- I need to use interfaces for the sake of user overrides */\nimport type {\n\tBaseCallApiExtraOptions,\n\tCallApiExtraOptions,\n\tCallApiRequestOptions,\n\tCallApiRequestOptionsForHooks,\n\tCombinedCallApiExtraOptions,\n\tInterceptors,\n\tInterceptorsOrInterceptorArray,\n\tWithMoreOptions,\n} from \"./types/common\";\nimport type { DefaultMoreOptions } from \"./types/default-types\";\nimport type { StandardSchemaV1 } from \"./types/standard-schema\";\nimport type { InitURL } from \"./url\";\nimport { isPlainObject, isString } from \"./utils/guards\";\nimport type { AnyFunction, Awaitable } from \"./utils/type-helpers\";\nimport type { InferSchemaResult } from \"./validation\";\n\ntype UnionToIntersection<TUnion> = (TUnion extends unknown ? (param: TUnion) => void : never) extends (\n\tparam: infer TParam\n) => void\n\t? TParam\n\t: never;\n\ntype InferSchema<TResult> = TResult extends StandardSchemaV1\n\t? InferSchemaResult<TResult, NonNullable<unknown>>\n\t: TResult;\n\nexport type InferPluginOptions<TPluginArray extends CallApiPlugin[]> = UnionToIntersection<\n\tInferSchema<ReturnType<NonNullable<TPluginArray[number][\"createExtraOptions\"]>>>\n>;\n\nexport type PluginInitContext<TMoreOptions = DefaultMoreOptions> = WithMoreOptions<TMoreOptions> & {\n\tbaseConfig: BaseCallApiExtraOptions & CallApiRequestOptions;\n\tconfig: CallApiExtraOptions & CallApiRequestOptions;\n\tinitURL: InitURL | undefined;\n\toptions: CombinedCallApiExtraOptions;\n\trequest: CallApiRequestOptionsForHooks;\n};\n\nexport type PluginInitResult = Partial<\n\tOmit<PluginInitContext, \"request\"> & { request: CallApiRequestOptions }\n>;\n\nexport interface CallApiPlugin<TData = never, TErrorData = never> {\n\t/**\n\t * Defines additional options that can be passed to callApi\n\t */\n\tcreateExtraOptions?: (...params: never[]) => unknown;\n\n\t/**\n\t * A description for the plugin\n\t */\n\tdescription?: string;\n\n\t/**\n\t * Hooks / Interceptors for the plugin\n\t */\n\thooks?: InterceptorsOrInterceptorArray<TData, TErrorData>;\n\n\t/**\n\t * A unique id for the plugin\n\t */\n\tid: string;\n\n\t/**\n\t * A function that will be called when the plugin is initialized. This will be called before the any of the other internal functions.\n\t */\n\tinit?: (context: PluginInitContext) => Awaitable<PluginInitResult> | Awaitable<void>;\n\n\t/**\n\t * A name for the plugin\n\t */\n\tname: string;\n\n\t/**\n\t * A version for the plugin\n\t */\n\tversion?: string;\n}\n\nexport const definePlugin = <\n\t// eslint-disable-next-line perfectionist/sort-union-types -- Let the first one be first\n\tTPlugin extends CallApiPlugin | AnyFunction<CallApiPlugin>,\n>(\n\tplugin: TPlugin\n) => {\n\treturn plugin;\n};\n\nconst createMergedHook = (\n\thooks: Array<AnyFunction | undefined>,\n\tmergedHooksExecutionMode: CombinedCallApiExtraOptions[\"mergedHooksExecutionMode\"]\n) => {\n\tif (hooks.length === 0) return;\n\n\tconst mergedHook = async (ctx: Record<string, unknown>) => {\n\t\tif (mergedHooksExecutionMode === \"sequential\") {\n\t\t\tfor (const hook of hooks) {\n\t\t\t\t// eslint-disable-next-line no-await-in-loop -- This is necessary in this case\n\t\t\t\tawait hook?.(ctx);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif (mergedHooksExecutionMode === \"parallel\") {\n\t\t\tconst hookArray = [...hooks];\n\n\t\t\tawait Promise.all(hookArray.map((uniqueHook) => uniqueHook?.(ctx)));\n\t\t}\n\t};\n\n\treturn mergedHook;\n};\n\n// prettier-ignore\ntype HookRegistries = {\n\t[Key in keyof Interceptors]: Set<Interceptors[Key]>;\n};\n\nexport const hooksEnum = {\n\tonError: new Set(),\n\tonRequest: new Set(),\n\tonRequestError: new Set(),\n\tonRequestStream: new Set(),\n\tonResponse: new Set(),\n\tonResponseError: new Set(),\n\tonResponseStream: new Set(),\n\tonRetry: new Set(),\n\tonSuccess: new Set(),\n} satisfies HookRegistries;\n\nexport type Plugins<TPluginArray extends CallApiPlugin[]> = TPluginArray;\n\nconst getPluginArray = (plugins: Plugins<CallApiPlugin[]> | undefined) => {\n\tif (!plugins) {\n\t\treturn [];\n\t}\n\n\treturn plugins;\n};\n\nexport const initializePlugins = async (\n\tcontext: Omit<PluginInitContext, \"request\"> & { request: CallApiRequestOptions }\n) => {\n\tconst { baseConfig, config, initURL, options, request } = context;\n\n\tconst hookRegistries = structuredClone(hooksEnum);\n\n\tconst addMainHooks = () => {\n\t\tfor (const key of Object.keys(hooksEnum)) {\n\t\t\tconst mainHook = options[key as keyof Interceptors] as never;\n\n\t\t\thookRegistries[key as keyof Interceptors].add(mainHook);\n\t\t}\n\t};\n\n\tconst addPluginHooks = (pluginHooks: Required<CallApiPlugin>[\"hooks\"]) => {\n\t\tfor (const key of Object.keys(hooksEnum)) {\n\t\t\tconst pluginHook = pluginHooks[key as keyof Interceptors] as never;\n\n\t\t\thookRegistries[key as keyof Interceptors].add(pluginHook);\n\t\t}\n\t};\n\n\tif (options.mergedHooksExecutionOrder === \"mainHooksBeforePlugins\") {\n\t\taddMainHooks();\n\t}\n\n\tconst resolvedPlugins = [\n\t\t...getPluginArray(options.plugins),\n\t\t...getPluginArray(options.extend?.plugins),\n\t];\n\n\tlet resolvedUrl = initURL;\n\tlet resolvedOptions = options;\n\tlet resolvedRequestOptions = request;\n\n\tconst executePluginInit = async (pluginInit: CallApiPlugin[\"init\"]) => {\n\t\tif (!pluginInit) return;\n\n\t\tconst initResult = await pluginInit({\n\t\t\tbaseConfig,\n\t\t\tconfig,\n\t\t\tinitURL,\n\t\t\toptions,\n\t\t\trequest: request as CallApiRequestOptionsForHooks,\n\t\t});\n\n\t\tif (!isPlainObject(initResult)) return;\n\n\t\tif (isString(initResult.initURL)) {\n\t\t\tresolvedUrl = initResult.initURL;\n\t\t}\n\n\t\tif (isPlainObject(initResult.request)) {\n\t\t\tresolvedRequestOptions = initResult.request as CallApiRequestOptionsForHooks;\n\t\t}\n\n\t\tif (isPlainObject(initResult.options)) {\n\t\t\tresolvedOptions = initResult.options;\n\t\t}\n\t};\n\n\tfor (const plugin of resolvedPlugins) {\n\t\t// eslint-disable-next-line no-await-in-loop -- Await is necessary in this case.\n\t\tawait executePluginInit(plugin.init);\n\n\t\tif (!plugin.hooks) continue;\n\n\t\taddPluginHooks(plugin.hooks);\n\t}\n\n\tif (\n\t\t!options.mergedHooksExecutionOrder\n\t\t|| options.mergedHooksExecutionOrder === \"mainHooksAfterPlugins\"\n\t) {\n\t\taddMainHooks();\n\t}\n\n\tconst resolvedHooks: Interceptors = {};\n\n\tfor (const [key, hookRegistry] of Object.entries(hookRegistries)) {\n\t\tconst flattenedHookArray = [...hookRegistry].flat().filter(Boolean);\n\n\t\tconst mergedHook = createMergedHook(flattenedHookArray, options.mergedHooksExecutionMode);\n\n\t\tresolvedHooks[key as keyof Interceptors] = mergedHook;\n\t}\n\n\treturn {\n\t\tresolvedHooks,\n\t\tresolvedOptions,\n\t\tresolvedRequestOptions,\n\t\turl: resolvedUrl?.toString(),\n\t};\n};\n","import type { CallApiExtraOptions, CallApiResultSuccessVariant, ResultModeMap } from \"./types\";\nimport { omitKeys } from \"./utils/common\";\nimport type { Awaitable } from \"./utils/type-helpers\";\n\ntype Parser = (responseString: string) => Awaitable<Record<string, unknown>>;\n\nexport const getResponseType = <TResponse>(response: Response, parser?: Parser) => ({\n\tarrayBuffer: () => response.arrayBuffer(),\n\tblob: () => response.blob(),\n\tformData: () => response.formData(),\n\tjson: async () => {\n\t\tif (parser) {\n\t\t\tconst text = await response.text();\n\t\t\treturn parser(text) as TResponse;\n\t\t}\n\n\t\treturn response.json() as Promise<TResponse>;\n\t},\n\tstream: () => response.body,\n\ttext: () => response.text(),\n});\n\ntype InitResponseTypeMap<TResponse = unknown> = ReturnType<typeof getResponseType<TResponse>>;\n\nexport type ResponseTypeUnion = keyof InitResponseTypeMap | undefined;\n\nexport type ResponseTypeMap<TResponse> = {\n\t[Key in keyof InitResponseTypeMap<TResponse>]: Awaited<ReturnType<InitResponseTypeMap<TResponse>[Key]>>;\n};\n\nexport type GetResponseType<\n\tTResponse,\n\tTResponseType extends ResponseTypeUnion,\n\tTComputedMap extends ResponseTypeMap<TResponse> = ResponseTypeMap<TResponse>,\n> = undefined extends TResponseType\n\t? TComputedMap[\"json\"]\n\t: TResponseType extends NonNullable<ResponseTypeUnion>\n\t\t? TComputedMap[TResponseType]\n\t\t: never;\n\nexport const resolveResponseData = async <TResponse>(\n\tresponse: Response,\n\tresponseType: keyof ResponseTypeMap<TResponse>,\n\tparser: Parser | undefined\n) => {\n\tconst RESPONSE_TYPE_LOOKUP = getResponseType<TResponse>(response, parser);\n\n\tif (!Object.hasOwn(RESPONSE_TYPE_LOOKUP, responseType)) {\n\t\tthrow new Error(`Invalid response type: ${responseType}`);\n\t}\n\n\tconst responseData = await RESPONSE_TYPE_LOOKUP[responseType]();\n\n\treturn responseData;\n};\n\ntype SuccessInfo = {\n\tdata: unknown;\n\tresponse: Response;\n\tresultMode: CallApiExtraOptions[\"resultMode\"];\n};\n\n// == The CallApiResult type is used to cast all return statements due to a design limitation in ts.\n// LINK - See https://www.zhenghao.io/posts/type-functions for more info\nexport const resolveSuccessResult = <TCallApiResult>(info: SuccessInfo): TCallApiResult => {\n\tconst { data, response, resultMode } = info;\n\n\tconst apiDetails = { data, error: null, response } satisfies CallApiResultSuccessVariant<unknown>;\n\n\tif (!resultMode) {\n\t\treturn apiDetails as TCallApiResult;\n\t}\n\n\tconst resultModeMap = {\n\t\tall: apiDetails,\n\t\tallWithException: apiDetails,\n\t\tallWithoutResponse: omitKeys(apiDetails, [\"response\"]),\n\t\tonlyError: apiDetails.error,\n\t\tonlyResponse: apiDetails.response,\n\t\tonlyResponseWithException: apiDetails.response,\n\t\tonlySuccess: apiDetails.data,\n\t\tonlySuccessWithException: apiDetails.data,\n\t} satisfies ResultModeMap;\n\n\treturn resultModeMap[resultMode] as TCallApiResult;\n};\n","/* eslint-disable ts-eslint/consistent-type-definitions -- I need to use interfaces for the sake of user overrides */\nimport { resolveErrorResult } from \"./error\";\nimport type { Method } from \"./types\";\nimport type { ErrorContext } from \"./types/common\";\nimport { executeHooks } from \"./utils/common\";\nimport type { AnyNumber, Awaitable } from \"./utils/type-helpers\";\n\ntype RetryCondition<TErrorData> = (context: ErrorContext<TErrorData>) => Awaitable<boolean>;\n\nexport interface RetryOptions<TErrorData> {\n\t/**\n\t * Keeps track of the number of times the request has already been retried\n\t * @deprecated This property is used internally to track retries. Please abstain from modifying it.\n\t */\n\treadonly [\"~retryCount\"]?: number;\n\n\t/**\n\t * Number of allowed retry attempts on HTTP errors\n\t * @default 0\n\t */\n\tretryAttempts?: number;\n\n\t/**\n\t * Callback whose return value determines if a request should be retried or not\n\t */\n\tretryCondition?: RetryCondition<TErrorData>;\n\n\t/**\n\t * Delay between retries in milliseconds\n\t * @default 1000\n\t */\n\tretryDelay?: number;\n\n\t/**\n\t * Maximum delay in milliseconds. Only applies to exponential strategy\n\t * @default 10000\n\t */\n\tretryMaxDelay?: number;\n\n\t/**\n\t * HTTP methods that are allowed to retry\n\t * @default [\"GET\", \"POST\"]\n\t */\n\tretryMethods?: Method[];\n\n\t/**\n\t * HTTP status codes that trigger a retry\n\t * @default [409, 425, 429, 500, 502, 503, 504]\n\t */\n\tretryStatusCodes?: Array<409 | 425 | 429 | 500 | 502 | 503 | 504 | AnyNumber>;\n\n\t/**\n\t * Strategy to use when retrying\n\t * @default \"linear\"\n\t */\n\tretryStrategy?: \"exponential\" | \"linear\";\n}\n\nconst getLinearDelay = <TErrorData>(options: RetryOptions<TErrorData>) => options.retryDelay ?? 1000;\n\nconst getExponentialDelay = <TErrorData>(\n\tcurrentAttemptCount: number,\n\toptions: RetryOptions<TErrorData>\n) => {\n\tconst maxDelay = options.retryMaxDelay ?? 10000;\n\n\tconst exponentialDelay = (options.retryDelay ?? 1000) * 2 ** currentAttemptCount;\n\n\treturn Math.min(exponentialDelay, maxDelay);\n};\n\nexport const createRetryStrategy = <TErrorData>(ctx: ErrorContext<TErrorData>) => {\n\tconst { options } = ctx;\n\n\tconst currentRetryCount = options[\"~retryCount\"] ?? 0;\n\n\tconst getDelay = () => {\n\t\tif (options.retryStrategy === \"exponential\") {\n\t\t\treturn getExponentialDelay(currentRetryCount, options);\n\t\t}\n\n\t\treturn getLinearDelay(options);\n\t};\n\n\tconst shouldAttemptRetry = async () => {\n\t\tconst customRetryCondition = (await options.retryCondition?.(ctx)) ?? true;\n\n\t\tconst maxRetryAttempts = options.retryAttempts ?? 0;\n\n\t\tconst baseRetryCondition = maxRetryAttempts > currentRetryCount && customRetryCondition;\n\n\t\tif (ctx.error.name !== \"HTTPError\") {\n\t\t\treturn baseRetryCondition;\n\t\t}\n\n\t\tconst includesMethod =\n\t\t\t// eslint-disable-next-line no-implicit-coercion -- Boolean doesn't narrow\n\t\t\t!!ctx.request.method && options.retryMethods?.includes(ctx.request.method);\n\n\t\tconst includesCodes =\n\t\t\t// eslint-disable-next-line no-implicit-coercion -- Boolean doesn't narrow\n\t\t\t!!ctx.response?.status && options.retryStatusCodes?.includes(ctx.response.status);\n\n\t\treturn includesCodes && includesMethod && baseRetryCondition;\n\t};\n\n\tconst executeRetryHook = async (shouldThrowOnError: boolean | undefined) => {\n\t\ttry {\n\t\t\treturn await executeHooks(options.onRetry?.(ctx));\n\t\t} catch (error) {\n\t\t\tconst { apiDetails } = resolveErrorResult({\n\t\t\t\tcloneResponse: options.cloneResponse,\n\t\t\t\tdefaultErrorMessage: options.defaultErrorMessage as string,\n\t\t\t\terror,\n\t\t\t\tresultMode: options.resultMode,\n\t\t\t});\n\n\t\t\tif (shouldThrowOnError) {\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\treturn apiDetails;\n\t\t}\n\t};\n\n\treturn {\n\t\texecuteRetryHook,\n\t\tgetDelay,\n\t\tshouldAttemptRetry,\n\t};\n};\n","/* eslint-disable ts-eslint/consistent-type-definitions -- I need to use interfaces for the sake of user overrides */\n\nimport type { CallApiExtraOptions } from \"./types/common\";\nimport { toQueryString } from \"./utils\";\nimport { isArray } from \"./utils/guards\";\nimport type { UnmaskType } from \"./utils/type-helpers\";\nimport type { CallApiSchemas, InferSchemaResult } from \"./validation\";\n\nconst slash = \"/\";\nconst column = \":\";\nconst mergeUrlWithParams = (url: string, params: CallApiExtraOptions[\"params\"]) => {\n\tif (!params) {\n\t\treturn url;\n\t}\n\n\tlet newUrl = url;\n\n\tif (isArray(params)) {\n\t\tconst matchedParamArray = newUrl.split(slash).filter((param) => param.startsWith(column));\n\n\t\tfor (const [index, matchedParam] of matchedParamArray.entries()) {\n\t\t\tconst realParam = params[index] as string;\n\t\t\tnewUrl = newUrl.replace(matchedParam, realParam);\n\t\t}\n\n\t\treturn newUrl;\n\t}\n\n\tfor (const [key, value] of Object.entries(params)) {\n\t\tnewUrl = newUrl.replace(`${column}${key}`, String(value));\n\t}\n\n\treturn newUrl;\n};\n\nconst questionMark = \"?\";\nconst ampersand = \"&\";\nconst mergeUrlWithQuery = (url: string, query: CallApiExtraOptions[\"query\"]): string => {\n\tif (!query) {\n\t\treturn url;\n\t}\n\n\tconst queryString = toQueryString(query);\n\n\tif (queryString?.length === 0) {\n\t\treturn url;\n\t}\n\n\tif (url.endsWith(questionMark)) {\n\t\treturn `${url}${queryString}`;\n\t}\n\n\tif (url.includes(questionMark)) {\n\t\treturn `${url}${ampersand}${queryString}`;\n\t}\n\n\treturn `${url}${questionMark}${queryString}`;\n};\n\nexport const mergeUrlWithParamsAndQuery = (\n\turl: string | undefined,\n\tparams: CallApiExtraOptions[\"params\"],\n\tquery: CallApiExtraOptions[\"query\"]\n) => {\n\tif (!url) return;\n\n\tconst urlWithMergedParams = mergeUrlWithParams(url, params);\n\n\treturn mergeUrlWithQuery(urlWithMergedParams, query);\n};\n\nexport type Params = UnmaskType<\n\t// eslint-disable-next-line perfectionist/sort-union-types -- I need the Record to be first\n\tRecord<string, boolean | number | string> | Array<boolean | number | string>\n>;\n\nexport type Query = UnmaskType<Record<string, boolean | number | string>>;\n\nexport type InitURL = UnmaskType<string | URL>;\n\nexport interface UrlOptions<TSchemas extends CallApiSchemas> {\n\t/**\n\t * URL to be used in the request.\n\t */\n\treadonly initURL?: string;\n\n\t/**\n\t * Parameters to be appended to the URL (i.e: /:id)\n\t */\n\tparams?: InferSchemaResult<TSchemas[\"params\"], Params>;\n\n\t/**\n\t * Query parameters to append to the URL.\n\t */\n\tquery?: InferSchemaResult<TSchemas[\"query\"], Query>;\n}\n","// prettier-ignore\nexport const createCombinedSignal = (...signals: Array<AbortSignal | null | undefined>) => AbortSignal.any(signals.filter(Boolean));\n\nexport const createTimeoutSignal = (milliseconds: number) => AbortSignal.timeout(milliseconds);\n","/* eslint-disable ts-eslint/consistent-type-definitions -- I need to use interfaces for the sake of user overrides */\nimport type { Body, GlobalMeta, Headers, Method } from \"./types\";\nimport type { CombinedCallApiExtraOptions } from \"./types/common\";\nimport type { StandardSchemaV1 } from \"./types/standard-schema\";\nimport type { InitURL, Params, Query } from \"./url\";\n\nexport const standardSchemaParser = async <TSchema extends StandardSchemaV1>(\n\tschema: TSchema,\n\tinputData: StandardSchemaV1.InferInput<TSchema>\n): Promise<StandardSchemaV1.InferOutput<TSchema>> => {\n\tconst result = await schema[\"~standard\"].validate(inputData);\n\n\t// == If the `issues` field exists, it means the validation failed\n\tif (result.issues) {\n\t\tthrow new Error(JSON.stringify(result.issues, null, 2), { cause: result.issues });\n\t}\n\n\treturn result.value;\n};\n\nexport interface CallApiSchemas {\n\t/**\n\t * The schema to use for validating the request body.\n\t */\n\tbody?: StandardSchemaV1<Body>;\n\n\t/**\n\t * The schema to use for validating the response data.\n\t */\n\tdata?: StandardSchemaV1;\n\n\t/**\n\t * The schema to use for validating the response error data.\n\t */\n\terrorData?: StandardSchemaV1;\n\n\t/**\n\t * The schema to use for validating the request headers.\n\t */\n\theaders?: StandardSchemaV1<Headers>;\n\n\t/**\n\t * The schema to use for validating the request url.\n\t */\n\tinitURL?: StandardSchemaV1<InitURL>;\n\n\t/**\n\t * The schema to use for validating the meta option.\n\t */\n\tmeta?: StandardSchemaV1<GlobalMeta>;\n\n\t/**\n\t * The schema to use for validating the request method.\n\t */\n\tmethod?: StandardSchemaV1<Method>;\n\n\t/**\n\t * The schema to use for validating the request url parameter.\n\t */\n\tparams?: StandardSchemaV1<Params>;\n\n\t/**\n\t * The schema to use for validating the request url querys.\n\t */\n\tquery?: StandardSchemaV1<Query>;\n}\n\nexport interface CallApiValidators<TData = unknown, TErrorData = unknown> {\n\t/**\n\t * Custom function to validate the response data.\n\t */\n\tdata?: (value: unknown) => TData;\n\n\t/**\n\t * Custom function to validate the response error data, stemming from the api.\n\t * This only runs if the api actually sends back error status codes, else it will be ignored, in which case you should only use the `responseValidator` option.\n\t */\n\terrorData?: (value: unknown) => TErrorData;\n}\n\nexport type InferSchemaResult<TSchema, TData> = TSchema extends StandardSchemaV1\n\t? StandardSchemaV1.InferOutput<TSchema>\n\t: TData;\n\nexport const createExtensibleSchemasAndValidators = (options: CombinedCallApiExtraOptions) => {\n\tconst schemas =\n\t\toptions.schemas && ({ ...options.schemas, ...options.extend?.schemas } as CallApiSchemas);\n\n\tconst validators = options.validators && { ...options.validators, ...options.extend?.validators };\n\n\treturn { schemas, validators };\n};\n\nexport const handleValidation = async (\n\tresponseData: unknown,\n\tschema: CallApiSchemas[keyof NonNullable<CallApiSchemas>],\n\tvalidator?: CallApiValidators[keyof NonNullable<CallApiValidators>]\n) => {\n\tconst validResponseData = validator ? validator(responseData) : responseData;\n\n\tconst schemaValidResponseData = schema\n\t\t? await standardSchemaParser(schema, validResponseData)\n\t\t: validResponseData;\n\n\treturn schemaValidResponseData;\n};\n","import { type RequestInfoCache, createDedupeStrategy } from \"./dedupe\";\nimport { HTTPError, resolveErrorResult } from \"./error\";\nimport { type CallApiPlugin, type PluginInitContext, hooksEnum, initializePlugins } from \"./plugins\";\nimport { type ResponseTypeUnion, resolveResponseData, resolveSuccessResult } from \"./response\";\nimport { createRetryStrategy } from \"./retry\";\nimport type {\n\tBaseCallApiConfig,\n\tCallApiParameters,\n\tCallApiRequestOptions,\n\tCallApiRequestOptionsForHooks,\n\tCallApiResult,\n\tCombinedCallApiExtraOptions,\n\tErrorContext,\n\tInterceptors,\n\tResultModeUnion,\n\tSuccessContext,\n} from \"./types/common\";\nimport type {\n\tDefaultDataType,\n\tDefaultMoreOptions,\n\tDefaultPluginArray,\n\tDefaultThrowOnError,\n} from \"./types/default-types\";\nimport { mergeUrlWithParamsAndQuery } from \"./url\";\nimport {\n\tcombineHooks,\n\texecuteHooks,\n\tmergeAndResolveHeaders,\n\tsplitBaseConfig,\n\tsplitConfig,\n\twaitUntil,\n} from \"./utils/common\";\nimport { defaultExtraOptions, defaultRequestOptions } from \"./utils/constants\";\nimport { isFunction, isHTTPErrorInstance, isSerializable } from \"./utils/guards\";\nimport { createCombinedSignal, createTimeoutSignal } from \"./utils/polyfills\";\nimport {\n\ttype CallApiSchemas,\n\ttype InferSchemaResult,\n\tcreateExtensibleSchemasAndValidators,\n\thandleValidation,\n} from \"./validation\";\n\nexport const createFetchClient = <\n\tTBaseData = DefaultDataType,\n\tTBaseErrorData = DefaultDataType,\n\tTBaseResultMode extends ResultModeUnion = ResultModeUnion,\n\tTBaseThrowOnError extends boolean = DefaultThrowOnError,\n\tTBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTBasePluginArray extends CallApiPlugin[] = DefaultPluginArray,\n\tTBaseSchemas extends CallApiSchemas = DefaultMoreOptions,\n>(\n\tbaseConfig: BaseCallApiConfig<\n\t\tTBaseData,\n\t\tTBaseErrorData,\n\t\tTBaseResultMode,\n\t\tTBaseThrowOnError,\n\t\tTBaseResponseType,\n\t\tTBasePluginArray,\n\t\tTBaseSchemas\n\t> = {} as never\n) => {\n\tconst $RequestInfoCache: RequestInfoCache = new Map();\n\n\tconst callApi = async <\n\t\tTData = InferSchemaResult<TBaseSchemas[\"data\"], TBaseData>,\n\t\tTErrorData = InferSchemaResult<TBaseSchemas[\"errorData\"], TBaseErrorData>,\n\t\tTResultMode extends ResultModeUnion = TBaseResultMode,\n\t\tTThrowOnError extends boolean = TBaseThrowOnError,\n\t\tTResponseType extends ResponseTypeUnion = TBaseResponseType,\n\t\tTPluginArray extends CallApiPlugin[] = TBasePluginArray,\n\t\tTSchemas extends CallApiSchemas = TBaseSchemas,\n\t>(\n\t\t...parameters: CallApiParameters<\n\t\t\tTData,\n\t\t\tTErrorData,\n\t\t\tTResultMode,\n\t\t\tTThrowOnError,\n\t\t\tTResponseType,\n\t\t\tTPluginArray,\n\t\t\tTSchemas\n\t\t>\n\t): CallApiResult<\n\t\tInferSchemaResult<TSchemas[\"data\"], TData>,\n\t\tInferSchemaResult<TSchemas[\"errorData\"], TErrorData>,\n\t\tTResultMode,\n\t\tTThrowOnError,\n\t\tTResponseType\n\t> => {\n\t\tconst [initURL, config = {} as never] = parameters;\n\n\t\tconst [fetchOptions, extraOptions] = splitConfig(config);\n\n\t\tconst resolvedBaseConfig = isFunction(baseConfig)\n\t\t\t? baseConfig({\n\t\t\t\t\tinitURL: initURL.toString(),\n\t\t\t\t\toptions: extraOptions,\n\t\t\t\t\trequest: fetchOptions,\n\t\t\t\t})\n\t\t\t: baseConfig;\n\n\t\tconst [baseFetchOptions, baseExtraOptions] = splitBaseConfig(resolvedBaseConfig);\n\n\t\tconst initCombinedHooks = {} as Required<Interceptors>;\n\n\t\tfor (const key of Object.keys(hooksEnum)) {\n\t\t\tconst combinedHook = combineHooks(\n\t\t\t\tbaseExtraOptions[key as keyof Interceptors],\n\t\t\t\textraOptions[key as keyof Interceptors]\n\t\t\t);\n\n\t\t\tinitCombinedHooks[key as keyof Interceptors] = combinedHook as never;\n\t\t}\n\n\t\t// == Merged Extra Options\n\t\tconst mergedExtraOptions = {\n\t\t\t...defaultExtraOptions,\n\t\t\t...baseExtraOptions,\n\t\t\t...(!baseExtraOptions.mergeMainOptionsManuallyFromBase && extraOptions),\n\t\t};\n\n\t\t// == Merged Request Options\n\t\tconst mergedRequestOptions = {\n\t\t\t...defaultRequestOptions,\n\t\t\t...baseFetchOptions,\n\t\t\t...fetchOptions,\n\t\t} satisfies CallApiRequestOptions;\n\n\t\tconst { resolvedHooks, resolvedOptions, resolvedRequestOptions, url } = await initializePlugins({\n\t\t\tbaseConfig: resolvedBaseConfig as PluginInitContext[\"config\"],\n\t\t\tconfig: config as PluginInitContext[\"config\"],\n\t\t\tinitURL,\n\t\t\toptions: mergedExtraOptions as CombinedCallApiExtraOptions,\n\t\t\trequest: mergedRequestOptions,\n\t\t});\n\n\t\tconst fullURL = `${resolvedOptions.baseURL}${mergeUrlWithParamsAndQuery(url, resolvedOptions.params, resolvedOptions.query)}`;\n\n\t\t// FIXME - Consider adding an option for refetching a callApi request\n\t\tconst options = {\n\t\t\t...resolvedOptions,\n\t\t\t...resolvedHooks,\n\t\t\tfullURL,\n\t\t\tinitURL: initURL.toString(),\n\t\t} satisfies CombinedCallApiExtraOptions as typeof mergedExtraOptions & typeof resolvedHooks;\n\n\t\tconst newFetchController = new AbortController();\n\n\t\tconst timeoutSignal = options.timeout != null ? createTimeoutSignal(options.timeout) : null;\n\n\t\tconst combinedSignal = createCombinedSignal(\n\t\t\tresolvedRequestOptions.signal,\n\t\t\ttimeoutSignal,\n\t\t\tnewFetchController.signal\n\t\t);\n\n\t\tconst request = {\n\t\t\t...resolvedRequestOptions,\n\n\t\t\tbody: isSerializable(resolvedRequestOptions.body)\n\t\t\t\t? options.bodySerializer(resolvedRequestOptions.body)\n\t\t\t\t: resolvedRequestOptions.body,\n\n\t\t\theaders: mergeAndResolveHeaders({\n\t\t\t\tauth: options.auth,\n\t\t\t\tbaseHeaders: baseFetchOptions.headers,\n\t\t\t\tbody: resolvedRequestOptions.body,\n\t\t\t\theaders: fetchOptions.headers,\n\t\t\t}),\n\n\t\t\tsignal: combinedSignal,\n\t\t} satisfies CallApiRequestOptionsForHooks;\n\n\t\tconst { handleRequestCancelStrategy, handleRequestDeferStrategy, removeDedupeKeyFromCache } =\n\t\t\tawait createDedupeStrategy({ $RequestInfoCache, newFetchController, options, request });\n\n\t\tawait handleRequestCancelStrategy();\n\n\t\ttry {\n\t\t\tawait executeHooks(options.onRequest?.({ options, request }));\n\n\t\t\t// == Apply determined headers again after onRequest incase they were modified\n\t\t\trequest.headers = mergeAndResolveHeaders({\n\t\t\t\tauth: options.auth,\n\t\t\t\tbody: request.body,\n\t\t\t\theaders: request.headers,\n\t\t\t});\n\n\t\t\tconst response = await handleRequestDeferStrategy();\n\n\t\t\tconst { schemas, validators } = createExtensibleSchemasAndValidators(options);\n\t\t\t// == Also clone response when dedupeStrategy is set to \"defer\" or when onRequestStream is set, to avoid error thrown from reading response.(whatever) more than once\n\t\t\tconst shouldCloneResponse = options.dedupeStrategy === \"defer\" || options.cloneResponse;\n\n\t\t\tif (!response.ok) {\n\t\t\t\tconst errorData = await resolveResponseData<TErrorData>(\n\t\t\t\t\tshouldCloneResponse ? response.clone() : response,\n\t\t\t\t\toptions.responseType,\n\t\t\t\t\toptions.responseParser\n\t\t\t\t);\n\n\t\t\t\tconst validErrorData = await handleValidation(\n\t\t\t\t\terrorData,\n\t\t\t\t\tschemas?.errorData,\n\t\t\t\t\tvalidators?.errorData\n\t\t\t\t);\n\n\t\t\t\t// == Push all error handling responsibilities to the catch block if not retrying\n\t\t\t\tthrow new HTTPError({\n\t\t\t\t\tdefaultErrorMessage: options.defaultErrorMessage,\n\t\t\t\t\terrorData: validErrorData,\n\t\t\t\t\tresponse,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst successData = await resolveResponseData<TData>(\n\t\t\t\tshouldCloneResponse ? response.clone() : response,\n\t\t\t\toptions.responseType,\n\t\t\t\toptions.responseParser\n\t\t\t);\n\n\t\t\tconst validSuccessData = await handleValidation(successData, schemas?.data, validators?.data);\n\n\t\t\tconst successContext = {\n\t\t\t\tdata: validSuccessData,\n\t\t\t\toptions,\n\t\t\t\trequest,\n\t\t\t\tresponse,\n\t\t\t} satisfies SuccessContext<unknown>;\n\n\t\t\tawait executeHooks(\n\t\t\t\toptions.onSuccess?.(successContext),\n\n\t\t\t\toptions.onResponse?.({ ...successContext, error: null })\n\t\t\t);\n\n\t\t\treturn await resolveSuccessResult({\n\t\t\t\tdata: successContext.data,\n\t\t\t\tresponse: successContext.response,\n\t\t\t\tresultMode: options.resultMode,\n\t\t\t});\n\n\t\t\t// == Exhaustive Error handling\n\t\t} catch (error) {\n\t\t\tconst { apiDetails, getErrorResult } = resolveErrorResult({\n\t\t\t\tcloneResponse: options.cloneResponse,\n\t\t\t\tdefaultErrorMessage: options.defaultErrorMessage,\n\t\t\t\terror,\n\t\t\t\tresultMode: options.resultMode,\n\t\t\t});\n\n\t\t\tconst errorContext = {\n\t\t\t\terror: apiDetails.error as never,\n\t\t\t\toptions,\n\t\t\t\trequest,\n\t\t\t\tresponse: apiDetails.response as never,\n\t\t\t} satisfies ErrorContext<unknown>;\n\n\t\t\tconst shouldThrowOnError = isFunction(options.throwOnError)\n\t\t\t\t? options.throwOnError(errorContext)\n\t\t\t\t: options.throwOnError;\n\n\t\t\tconst handleRetryOrGetResult = async (customInfo?: { message?: string }) => {\n\t\t\t\tconst { executeRetryHook, getDelay, shouldAttemptRetry } = createRetryStrategy(errorContext);\n\n\t\t\t\tconst shouldRetry = !combinedSignal.aborted && (await shouldAttemptRetry());\n\n\t\t\t\tif (shouldRetry) {\n\t\t\t\t\tawait executeRetryHook(shouldThrowOnError);\n\n\t\t\t\t\tconst delay = getDelay();\n\n\t\t\t\t\tawait waitUntil(delay);\n\n\t\t\t\t\tconst updatedOptions = {\n\t\t\t\t\t\t...config,\n\t\t\t\t\t\t\"~retryCount\": (options[\"~retryCount\"] ?? 0) + 1,\n\t\t\t\t\t} satisfies typeof config;\n\n\t\t\t\t\treturn callApi(initURL, updatedOptions as never) as never;\n\t\t\t\t}\n\n\t\t\t\tif (shouldThrowOnError) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\n\t\t\t\treturn customInfo ? getErrorResult(customInfo) : getErrorResult();\n\t\t\t};\n\n\t\t\tif (isHTTPErrorInstance<TErrorData>(error)) {\n\t\t\t\tawait executeHooks(\n\t\t\t\t\toptions.onResponseError?.(errorContext),\n\n\t\t\t\t\toptions.onError?.(errorContext),\n\n\t\t\t\t\toptions.onResponse?.({ ...errorContext, data: null })\n\t\t\t\t);\n\n\t\t\t\treturn await handleRetryOrGetResult();\n\t\t\t}\n\n\t\t\tif (error instanceof DOMException && error.name === \"AbortError\") {\n\t\t\t\tconst { message, name } = error;\n\n\t\t\t\t!shouldThrowOnError && console.error(`${name}:`, message);\n\n\t\t\t\treturn await handleRetryOrGetResult();\n\t\t\t}\n\n\t\t\tif (error instanceof DOMException && error.name === \"TimeoutError\") {\n\t\t\t\tconst message = `Request timed out after ${options.timeout}ms`;\n\n\t\t\t\t!shouldThrowOnError && console.error(`${error.name}:`, message);\n\n\t\t\t\treturn await handleRetryOrGetResult({ message });\n\t\t\t}\n\n\t\t\tawait executeHooks(\n\t\t\t\t// == At this point only the request errors exist, so the request error interceptor is called\n\t\t\t\toptions.onRequestError?.(errorContext as never),\n\n\t\t\t\t// == Also call the onError interceptor\n\t\t\t\toptions.onError?.(errorContext)\n\t\t\t);\n\n\t\t\treturn await handleRetryOrGetResult();\n\n\t\t\t// == Removing the now unneeded AbortController from store\n\t\t} finally {\n\t\t\tremoveDedupeKeyFromCache();\n\t\t}\n\t};\n\n\treturn callApi;\n};\n\nexport const callApi = createFetchClient();\n","import type { CallApiPlugin } from \"./plugins\";\nimport type { ResponseTypeUnion } from \"./response\";\nimport type { CallApiParameters, ResultModeUnion } from \"./types\";\nimport type { DefaultMoreOptions, DefaultPluginArray, DefaultThrowOnError } from \"./types/default-types\";\nimport type { CallApiSchemas } from \"./validation\";\n\nconst defineParameters = <\n\tTData = unknown,\n\tTErrorData = unknown,\n\tTResultMode extends ResultModeUnion = ResultModeUnion,\n\tTThrowOnError extends boolean = DefaultThrowOnError,\n\tTResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTPluginArray extends CallApiPlugin[] = DefaultPluginArray,\n\tTSchemas extends CallApiSchemas = DefaultMoreOptions,\n>(\n\t...parameters: CallApiParameters<\n\t\tTData,\n\t\tTErrorData,\n\t\tTResultMode,\n\t\tTThrowOnError,\n\t\tTResponseType,\n\t\tTPluginArray,\n\t\tTSchemas\n\t>\n) => {\n\treturn parameters;\n};\n\nexport { defineParameters };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACiBO,IAAM,qBAAqB,CAAyB,SAAoB;AAC9E,QAAM,EAAE,eAAe,qBAAqB,OAAO,SAAS,oBAAoB,WAAW,IAAI;AAE/F,MAAI,aAAiD;AAAA,IACpD,MAAM;AAAA,IACN,OAAO;AAAA,MACN,WAAW;AAAA,MACX,SAAS,sBAAuB,MAAgB;AAAA,MAChD,MAAO,MAAgB;AAAA,IACxB;AAAA,IACA,UAAU;AAAA,EACX;AAEA,MAAI,oBAA2B,KAAK,GAAG;AACtC,UAAM,EAAE,WAAW,UAAU,qBAAqB,MAAM,SAAS,IAAI;AAErE,iBAAa;AAAA,MAC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BAAyB;AAAA,IAC1B;AAAA,EACD;AAEA,SAAOA;AACR;AAEO,IAAM,UAAU,kBAAkB;;;ACzUzC,IAAM,mBAAmB,IASrB,eASC;AACJ,SAAO;AACR;","names":["callApi"]}
1
+ {"version":3,"sources":["../../src/index.ts","../../src/hooks.ts","../../src/auth.ts","../../src/utils/type-helpers.ts","../../src/types/common.ts","../../src/utils/constants.ts","../../src/utils/common.ts","../../src/error.ts","../../src/utils/guards.ts","../../src/stream.ts","../../src/dedupe.ts","../../src/plugins.ts","../../src/response.ts","../../src/retry.ts","../../src/url.ts","../../src/validation.ts","../../src/createFetchClient.ts","../../src/defineParameters.ts"],"sourcesContent":["export { callApi, createFetchClient } from \"./createFetchClient\";\n\nexport {\n\tdefinePlugin,\n\ttype CallApiPlugin,\n\ttype PluginInitContext,\n\ttype PluginHooks,\n\ttype PluginHooksWithMoreOptions,\n} from \"./plugins\";\n\nexport { defineParameters } from \"./defineParameters\";\n\nexport type { CallApiSchemas, InferSchemaResult } from \"./validation\";\n\nexport type { ResponseTypeUnion } from \"./response\";\n\nexport { getDefaultOptions } from \"./utils/constants\";\n\nexport type { RetryOptions } from \"./retry\";\n\nexport { HTTPError, type PossibleHTTPError, type PossibleJavaScriptError } from \"./error\";\n\nexport type {\n\tErrorContext,\n\tHooks,\n\tHooksOrHooksArray,\n\tSharedHookContext,\n\tRequestContext,\n\tRequestErrorContext,\n\tRequestStreamContext,\n\tResponseContext,\n\tResponseErrorContext,\n\tResponseStreamContext,\n\tSuccessContext,\n} from \"./hooks\";\n\nexport type {\n\tBaseCallApiExtraOptions,\n\tCallApiExtraOptions,\n\tCallApiParameters,\n\tCallApiRequestOptions,\n\tCallApiRequestOptionsForHooks,\n\tCallApiResultErrorVariant,\n\tCallApiResultSuccessVariant,\n\tCombinedCallApiExtraOptions,\n\tRegister,\n\tResultModeUnion,\n} from \"./types\";\n","import type { PossibleHTTPError, PossibleJavaScriptError } from \"./error\";\nimport type { StreamProgressEvent } from \"./stream\";\nimport type {\n\tBaseCallApiExtraOptions,\n\tCallApiExtraOptions,\n\tCallApiRequestOptions,\n\tCallApiRequestOptionsForHooks,\n\tCombinedCallApiExtraOptions,\n} from \"./types/common\";\nimport type { DefaultDataType, DefaultMoreOptions } from \"./types/default-types\";\nimport type { AnyFunction, Awaitable, Prettify, UnmaskType } from \"./utils/type-helpers\";\n\nexport type WithMoreOptions<TMoreOptions = DefaultMoreOptions> = {\n\toptions: CombinedCallApiExtraOptions & Partial<TMoreOptions>;\n};\n\nexport type Hooks<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTMoreOptions = DefaultMoreOptions,\n> = {\n\t/**\n\t * Hook that will be called when any error occurs within the request/response lifecycle, regardless of whether the error is from the api or not.\n\t * It is basically a combination of `onRequestError` and `onResponseError` hooks\n\t */\n\tonError?: (context: ErrorContext<TErrorData> & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called just before the request is made, allowing for modifications or additional operations.\n\t */\n\tonRequest?: (context: Prettify<RequestContext & WithMoreOptions<TMoreOptions>>) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when an error occurs during the fetch request.\n\t */\n\tonRequestError?: (\n\t\tcontext: Prettify<RequestErrorContext & WithMoreOptions<TMoreOptions>>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when upload stream progress is tracked\n\t */\n\tonRequestStream?: (\n\t\tcontext: Prettify<RequestStreamContext & WithMoreOptions<TMoreOptions>>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when any response is received from the api, whether successful or not\n\t */\n\tonResponse?: (\n\t\tcontext: ResponseContext<TData, TErrorData> & WithMoreOptions<TMoreOptions>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when an error response is received from the api.\n\t */\n\tonResponseError?: (\n\t\tcontext: Prettify<ResponseErrorContext<TErrorData> & WithMoreOptions<TMoreOptions>>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when download stream progress is tracked\n\t */\n\tonResponseStream?: (\n\t\tcontext: Prettify<ResponseStreamContext & WithMoreOptions<TMoreOptions>>\n\t) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when a request is retried.\n\t */\n\tonRetry?: (response: ErrorContext<TErrorData> & WithMoreOptions<TMoreOptions>) => Awaitable<unknown>;\n\n\t/**\n\t * Hook that will be called when a successful response is received from the api.\n\t */\n\tonSuccess?: (\n\t\tcontext: Prettify<SuccessContext<TData> & WithMoreOptions<TMoreOptions>>\n\t) => Awaitable<unknown>;\n};\n\nexport type HooksOrHooksArray<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTMoreOptions = DefaultMoreOptions,\n> = {\n\t[Key in keyof Hooks<TData, TErrorData, TMoreOptions>]:\n\t\t| Hooks<TData, TErrorData, TMoreOptions>[Key]\n\t\t// eslint-disable-next-line perfectionist/sort-union-types -- I need arrays to be last\n\t\t| Array<Hooks<TData, TErrorData, TMoreOptions>[Key]>;\n};\n\nexport type SharedHookContext<TMoreOptions = DefaultMoreOptions> = {\n\t/**\n\t * Config object passed to createFetchClient\n\t */\n\tbaseConfig: BaseCallApiExtraOptions & CallApiRequestOptions;\n\t/**\n\t * Config object passed to the callApi instance\n\t */\n\tconfig: CallApiExtraOptions & CallApiRequestOptions;\n\t/**\n\t * Merged options consisting of extra options from createFetchClient, the callApi instance and default options.\n\t *\n\t */\n\toptions: CombinedCallApiExtraOptions & Partial<TMoreOptions>;\n\t/**\n\t * Merged request consisting of request options from createFetchClient, the callApi instance and default request options.\n\t */\n\trequest: CallApiRequestOptionsForHooks;\n};\n\nexport type RequestContext = UnmaskType<SharedHookContext>;\n\nexport type ResponseContext<TData, TErrorData> = UnmaskType<\n\t| Prettify<\n\t\t\tSharedHookContext & {\n\t\t\t\tdata: TData;\n\t\t\t\terror: null;\n\t\t\t\tresponse: Response;\n\t\t\t}\n\t >\n\t// eslint-disable-next-line perfectionist/sort-union-types -- I need the first one to be first\n\t| Prettify<\n\t\t\tSharedHookContext & {\n\t\t\t\tdata: null;\n\t\t\t\terror: PossibleHTTPError<TErrorData>;\n\t\t\t\tresponse: Response;\n\t\t\t}\n\t >\n>;\n\nexport type SuccessContext<TData> = UnmaskType<\n\tPrettify<\n\t\tSharedHookContext & {\n\t\t\tdata: TData;\n\t\t\tresponse: Response;\n\t\t}\n\t>\n>;\n\nexport type RequestErrorContext = UnmaskType<\n\tPrettify<\n\t\tSharedHookContext & {\n\t\t\terror: PossibleJavaScriptError;\n\t\t\tresponse: null;\n\t\t}\n\t>\n>;\n\nexport type ResponseErrorContext<TErrorData> = UnmaskType<\n\tPrettify<\n\t\tSharedHookContext & {\n\t\t\terror: PossibleHTTPError<TErrorData>;\n\t\t\tresponse: Response;\n\t\t}\n\t>\n>;\n\nexport type ErrorContext<TErrorData> = UnmaskType<\n\t| Prettify<\n\t\t\tSharedHookContext & {\n\t\t\t\terror: PossibleHTTPError<TErrorData>;\n\t\t\t\tresponse: Response;\n\t\t\t}\n\t >\n\t| Prettify<\n\t\t\tSharedHookContext & {\n\t\t\t\terror: PossibleJavaScriptError;\n\t\t\t\tresponse: null;\n\t\t\t}\n\t >\n>;\n\nexport type RequestStreamContext = UnmaskType<\n\tPrettify<\n\t\tSharedHookContext & {\n\t\t\tevent: StreamProgressEvent;\n\t\t\trequestInstance: Request;\n\t\t}\n\t>\n>;\n\nexport type ResponseStreamContext = UnmaskType<\n\tPrettify<\n\t\tSharedHookContext & {\n\t\t\tevent: StreamProgressEvent;\n\t\t\tresponse: Response;\n\t\t}\n\t>\n>;\n\ntype HookRegistries = {\n\t[Key in keyof Hooks]: Set<Hooks[Key]>;\n};\n\nexport const hookRegistries = {\n\tonError: new Set(),\n\tonRequest: new Set(),\n\tonRequestError: new Set(),\n\tonRequestStream: new Set(),\n\tonResponse: new Set(),\n\tonResponseError: new Set(),\n\tonResponseStream: new Set(),\n\tonRetry: new Set(),\n\tonSuccess: new Set(),\n} satisfies HookRegistries;\n\nexport const composeTwoHooks = (\n\thooks: Array<AnyFunction | undefined>,\n\tmergedHooksExecutionMode: CombinedCallApiExtraOptions[\"mergedHooksExecutionMode\"]\n) => {\n\tif (hooks.length === 0) return;\n\n\tconst mergedHook = async (ctx: Record<string, unknown>) => {\n\t\tif (mergedHooksExecutionMode === \"sequential\") {\n\t\t\tfor (const hook of hooks) {\n\t\t\t\t// eslint-disable-next-line no-await-in-loop -- This is necessary in this case\n\t\t\t\tawait hook?.(ctx);\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\tif (mergedHooksExecutionMode === \"parallel\") {\n\t\t\tconst hookArray = [...hooks];\n\n\t\t\tawait Promise.all(hookArray.map((uniqueHook) => uniqueHook?.(ctx)));\n\t\t}\n\t};\n\n\treturn mergedHook;\n};\n\nexport const executeHooks = <THook extends Awaitable<unknown>>(...hooks: THook[]) => Promise.all(hooks);\n","/* eslint-disable perfectionist/sort-object-types -- Avoid Sorting for now */\n\nimport type { ExtraOptions } from \"./types/common\";\nimport { isFunction, isString } from \"./utils/guards\";\n\ntype ValueOrFunctionResult<TValue> = TValue | (() => TValue);\n\n/**\n * Bearer Or Token authentication\n *\n * The value of `bearer` will be added to a header as\n * `auth: Bearer some-auth-token`,\n *\n * The value of `token` will be added to a header as\n * `auth: Token some-auth-token`,\n */\nexport type BearerOrTokenAuth =\n\t| {\n\t\t\ttype?: \"Bearer\";\n\t\t\tbearer?: ValueOrFunctionResult<string | null>;\n\t\t\ttoken?: never;\n\t }\n\t| {\n\t\t\ttype?: \"Token\";\n\t\t\tbearer?: never;\n\t\t\ttoken?: ValueOrFunctionResult<string | null>;\n\t };\n\n/**\n * Basic auth\n */\nexport type BasicAuth = {\n\ttype: \"Basic\";\n\tusername: ValueOrFunctionResult<string | null | undefined>;\n\tpassword: ValueOrFunctionResult<string | null | undefined>;\n};\n\n/**\n * Custom auth\n *\n * @param prefix - prefix of the header\n * @param authValue - value of the header\n *\n * @example\n * ```ts\n * {\n * type: \"Custom\",\n * prefix: \"Token\",\n * authValue: \"token\"\n * }\n * ```\n */\nexport type CustomAuth = {\n\ttype: \"Custom\";\n\tprefix: ValueOrFunctionResult<string | null | undefined>;\n\tvalue: ValueOrFunctionResult<string | null | undefined>;\n};\n\n// eslint-disable-next-line perfectionist/sort-union-types -- Let the first one be first\nexport type Auth = BearerOrTokenAuth | BasicAuth | CustomAuth;\n\nconst getValue = (value: ValueOrFunctionResult<string | null | undefined>) => {\n\treturn isFunction(value) ? value() : value;\n};\n\ntype AuthorizationHeader = {\n\tAuthorization: string;\n};\n\nexport const getAuthHeader = (auth: ExtraOptions[\"auth\"]): false | AuthorizationHeader | undefined => {\n\tif (auth === undefined) return;\n\n\tif (isString(auth) || auth === null) {\n\t\treturn { Authorization: `Bearer ${auth}` };\n\t}\n\n\tswitch (auth.type) {\n\t\tcase \"Basic\": {\n\t\t\tconst username = getValue(auth.username);\n\t\t\tconst password = getValue(auth.password);\n\n\t\t\tif (username === undefined || password === undefined) return;\n\n\t\t\treturn {\n\t\t\t\tAuthorization: `Basic ${globalThis.btoa(`${username}:${password}`)}`,\n\t\t\t};\n\t\t}\n\n\t\tcase \"Custom\": {\n\t\t\tconst value = getValue(auth.value);\n\n\t\t\tif (value === undefined) return;\n\n\t\t\tconst prefix = getValue(auth.prefix);\n\n\t\t\treturn {\n\t\t\t\tAuthorization: `${prefix} ${value}`,\n\t\t\t};\n\t\t}\n\n\t\tdefault: {\n\t\t\tconst bearer = getValue(auth.bearer);\n\t\t\tconst token = getValue(auth.token);\n\n\t\t\tif (\"token\" in auth && token !== undefined) {\n\t\t\t\treturn { Authorization: `Token ${token}` };\n\t\t\t}\n\n\t\t\treturn bearer !== undefined && { Authorization: `Bearer ${bearer}` };\n\t\t}\n\t}\n};\n","// == These two types allows for adding arbitrary literal types, while still provided autocomplete for defaults.\n// == Usually intersection with \"{}\" or \"NonNullable<unknown>\" would make it work fine, but the placeholder with never type is added to make the AnyWhatever type appear last in a given union.\nexport type AnyString = string & { z_placeholder?: never };\nexport type AnyNumber = number & { z_placeholder?: never };\n\n// eslint-disable-next-line ts-eslint/no-explicit-any -- Any is fine here\nexport type AnyObject = Record<keyof any, any>;\n\n// eslint-disable-next-line ts-eslint/no-explicit-any -- Any is required here so that one can pass custom function type without type errors\nexport type AnyFunction<TResult = unknown> = (...args: any) => TResult;\n\nexport type CallbackFn<in TParams, out TResult = void> = (...params: TParams[]) => TResult;\n\nexport type Prettify<TObject> = NonNullable<unknown> & { [Key in keyof TObject]: TObject[Key] };\n\nexport type Writeable<TObject, TType extends \"deep\" | \"shallow\" = \"shallow\"> = {\n\t-readonly [key in keyof TObject]: TType extends \"shallow\"\n\t\t? TObject[key]\n\t\t: TType extends \"deep\"\n\t\t\t? TObject[key] extends object\n\t\t\t\t? Writeable<TObject[key], TType>\n\t\t\t\t: TObject[key]\n\t\t\t: never;\n};\n\nexport const defineEnum = <const TValue>(value: TValue) => value as Prettify<Writeable<TValue, \"deep\">>;\n\n// == Using this Immediately Indexed Mapped type helper to help show computed type of anything passed to it instead of just the type name\nexport type UnmaskType<TValue> = { _: TValue }[\"_\"];\n\nexport type Awaitable<TValue> = Promise<TValue> | TValue;\n\nexport type CommonRequestHeaders =\n\t| \"Access-Control-Allow-Credentials\"\n\t| \"Access-Control-Allow-Headers\"\n\t| \"Access-Control-Allow-Methods\"\n\t| \"Access-Control-Allow-Origin\"\n\t| \"Access-Control-Expose-Headers\"\n\t| \"Access-Control-Max-Age\"\n\t| \"Age\"\n\t| \"Allow\"\n\t| \"Cache-Control\"\n\t| \"Clear-Site-Data\"\n\t| \"Content-Disposition\"\n\t| \"Content-Encoding\"\n\t| \"Content-Language\"\n\t| \"Content-Length\"\n\t| \"Content-Location\"\n\t| \"Content-Range\"\n\t| \"Content-Security-Policy-Report-Only\"\n\t| \"Content-Security-Policy\"\n\t| \"Cookie\"\n\t| \"Cross-Origin-Embedder-Policy\"\n\t| \"Cross-Origin-Opener-Policy\"\n\t| \"Cross-Origin-Resource-Policy\"\n\t| \"Date\"\n\t| \"ETag\"\n\t| \"Expires\"\n\t| \"Last-Modified\"\n\t| \"Location\"\n\t| \"Permissions-Policy\"\n\t| \"Pragma\"\n\t| \"Retry-After\"\n\t| \"Save-Data\"\n\t| \"Sec-CH-Prefers-Color-Scheme\"\n\t| \"Sec-CH-Prefers-Reduced-Motion\"\n\t| \"Sec-CH-UA-Arch\"\n\t| \"Sec-CH-UA-Bitness\"\n\t| \"Sec-CH-UA-Form-Factor\"\n\t| \"Sec-CH-UA-Full-Version-List\"\n\t| \"Sec-CH-UA-Full-Version\"\n\t| \"Sec-CH-UA-Mobile\"\n\t| \"Sec-CH-UA-Model\"\n\t| \"Sec-CH-UA-Platform-Version\"\n\t| \"Sec-CH-UA-Platform\"\n\t| \"Sec-CH-UA-WoW64\"\n\t| \"Sec-CH-UA\"\n\t| \"Sec-Fetch-Dest\"\n\t| \"Sec-Fetch-Mode\"\n\t| \"Sec-Fetch-Site\"\n\t| \"Sec-Fetch-User\"\n\t| \"Sec-GPC\"\n\t| \"Server-Timing\"\n\t| \"Server\"\n\t| \"Service-Worker-Navigation-Preload\"\n\t| \"Set-Cookie\"\n\t| \"Strict-Transport-Security\"\n\t| \"Timing-Allow-Origin\"\n\t| \"Trailer\"\n\t| \"Transfer-Encoding\"\n\t| \"Upgrade\"\n\t| \"Vary\"\n\t| \"Warning\"\n\t| \"WWW-Authenticate\"\n\t| \"X-Content-Type-Options\"\n\t| \"X-DNS-Prefetch-Control\"\n\t| \"X-Frame-Options\"\n\t| \"X-Permitted-Cross-Domain-Policies\"\n\t| \"X-Powered-By\"\n\t| \"X-Robots-Tag\"\n\t| \"X-XSS-Protection\"\n\t| AnyString;\n\nexport type CommonAuthorizationHeaders = `${\"Basic\" | \"Bearer\" | \"Token\"} ${string}`;\n\nexport type CommonContentTypes =\n\t| \"application/epub+zip\"\n\t| \"application/gzip\"\n\t| \"application/json\"\n\t| \"application/ld+json\"\n\t| \"application/octet-stream\"\n\t| \"application/ogg\"\n\t| \"application/pdf\"\n\t| \"application/rtf\"\n\t| \"application/vnd.ms-fontobject\"\n\t| \"application/wasm\"\n\t| \"application/xhtml+xml\"\n\t| \"application/xml\"\n\t| \"application/zip\"\n\t| \"audio/aac\"\n\t| \"audio/mpeg\"\n\t| \"audio/ogg\"\n\t| \"audio/opus\"\n\t| \"audio/webm\"\n\t| \"audio/x-midi\"\n\t| \"font/otf\"\n\t| \"font/ttf\"\n\t| \"font/woff\"\n\t| \"font/woff2\"\n\t| \"image/avif\"\n\t| \"image/bmp\"\n\t| \"image/gif\"\n\t| \"image/jpeg\"\n\t| \"image/png\"\n\t| \"image/svg+xml\"\n\t| \"image/tiff\"\n\t| \"image/webp\"\n\t| \"image/x-icon\"\n\t| \"model/gltf-binary\"\n\t| \"model/gltf+json\"\n\t| \"text/calendar\"\n\t| \"text/css\"\n\t| \"text/csv\"\n\t| \"text/html\"\n\t| \"text/javascript\"\n\t| \"text/plain\"\n\t| \"video/3gpp\"\n\t| \"video/3gpp2\"\n\t| \"video/av1\"\n\t| \"video/mp2t\"\n\t| \"video/mp4\"\n\t| \"video/mpeg\"\n\t| \"video/ogg\"\n\t| \"video/webm\"\n\t| \"video/x-msvideo\"\n\t| AnyString;\n","import type { Auth } from \"../auth\";\nimport type { PossibleHTTPError, PossibleJavaScriptError } from \"../error\";\nimport type { ErrorContext, Hooks, HooksOrHooksArray } from \"../hooks\";\nimport type { CallApiPlugin, InferPluginOptions, Plugins } from \"../plugins\";\nimport type { GetResponseType, ResponseTypeUnion } from \"../response\";\nimport type { RetryOptions } from \"../retry\";\nimport type { InitURL, UrlOptions } from \"../url\";\nimport type { ModifiedRequestInit, fetchSpecificKeys } from \"../utils/constants\";\nimport { type Awaitable, type Prettify, type UnmaskType, defineEnum } from \"../utils/type-helpers\";\nimport type { CallApiSchemas, CallApiValidators, InferSchemaResult } from \"../validation\";\nimport type {\n\tBodyOption,\n\tHeadersOption,\n\tMetaOption,\n\tMethodOption,\n\tResultModeOption,\n} from \"./conditional-types\";\nimport type {\n\tDefaultDataType,\n\tDefaultMoreOptions,\n\tDefaultPluginArray,\n\tDefaultThrowOnError,\n} from \"./default-types\";\n\ntype FetchSpecificKeysUnion = Exclude<(typeof fetchSpecificKeys)[number], \"body\" | \"headers\" | \"method\">;\n\nexport type CallApiRequestOptions<TSchemas extends CallApiSchemas = DefaultMoreOptions> = Prettify<\n\tBodyOption<TSchemas>\n\t\t& HeadersOption<TSchemas>\n\t\t& MethodOption<TSchemas>\n\t\t& Pick<ModifiedRequestInit, FetchSpecificKeysUnion>\n>;\n\nexport type CallApiRequestOptionsForHooks<TSchemas extends CallApiSchemas = DefaultMoreOptions> = Omit<\n\tCallApiRequestOptions<TSchemas>,\n\t\"headers\"\n> & {\n\theaders?: Record<string, string | undefined>;\n};\n\ntype FetchImpl = UnmaskType<(input: string | Request | URL, init?: RequestInit) => Promise<Response>>;\n\nexport type ExtraOptions<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResultMode extends ResultModeUnion = ResultModeUnion,\n\tTThrowOnError extends boolean = DefaultThrowOnError,\n\tTResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTPluginArray extends CallApiPlugin[] = DefaultPluginArray,\n\tTSchemas extends CallApiSchemas = DefaultMoreOptions,\n> = {\n\t/**\n\t * Authorization header value.\n\t */\n\tauth?: string | Auth | null;\n\t/**\n\t * Base URL to be prepended to all request URLs\n\t */\n\tbaseURL?: string;\n\n\t/**\n\t * Custom function to serialize the body object into a string.\n\t */\n\tbodySerializer?: (bodyData: Record<string, unknown>) => string;\n\n\t/**\n\t * Whether or not to clone the response, so response.json() and the like, can be read again else where.\n\t * @see https://developer.mozilla.org/en-US/docs/Web/API/Response/clone\n\t * @default false\n\t */\n\tcloneResponse?: boolean;\n\n\t/**\n\t * Custom fetch implementation\n\t */\n\tcustomFetchImpl?: FetchImpl;\n\n\t/**\n\t * Custom request key to be used to identify a request in the fetch deduplication strategy.\n\t * @default the full request url + string formed from the request options\n\t */\n\tdedupeKey?: string;\n\n\t/**\n\t * Defines the deduplication strategy for the request, can be set to \"none\" | \"defer\" | \"cancel\".\n\t * - If set to \"cancel\", the previous pending request with the same request key will be cancelled and lets the new request through.\n\t * - If set to \"defer\", all new request with the same request key will be share the same response, until the previous one is completed.\n\t * - If set to \"none\", deduplication is disabled.\n\t * @default \"cancel\"\n\t */\n\tdedupeStrategy?: \"cancel\" | \"defer\" | \"none\";\n\n\t/**\n\t * Default error message to use if none is provided from a response.\n\t * @default \"Failed to fetch data from server!\"\n\t */\n\tdefaultErrorMessage?: string;\n\n\t/**\n\t * If true, forces the calculation of the total byte size from the request or response body, in case the content-length header is not present or is incorrect.\n\t * @default false\n\t */\n\tforceCalculateStreamSize?: boolean | { request?: boolean; response?: boolean };\n\n\t/**\n\t * Resolved request URL\n\t */\n\treadonly fullURL?: string;\n\n\t/**\n\t * Defines the mode in which the composed hooks are executed\".\n\t * - If set to \"parallel\", main and plugin hooks will be executed in parallel.\n\t * - If set to \"sequential\", the plugin hooks will be executed first, followed by the main hook.\n\t * @default \"parallel\"\n\t */\n\tmergedHooksExecutionMode?: \"parallel\" | \"sequential\";\n\n\t/**\n\t * - Controls what order in which the composed hooks execute\n\t * @default \"mainHooksAfterPlugins\"\n\t */\n\tmergedHooksExecutionOrder?: \"mainHooksAfterPlugins\" | \"mainHooksBeforePlugins\";\n\n\t/**\n\t * An array of CallApi plugins. It allows you to extend the behavior of the library.\n\t */\n\tplugins?: Plugins<TPluginArray>;\n\n\t/**\n\t * Custom function to parse the response string\n\t */\n\tresponseParser?: (responseString: string) => Awaitable<Record<string, unknown>>;\n\n\t/**\n\t * Expected response type, affects how response is parsed\n\t * @default \"json\"\n\t */\n\tresponseType?: TResponseType;\n\n\t/**\n\t * Mode of the result, can influence how results are handled or returned.\n\t * Can be set to \"all\" | \"onlySuccess\" | \"onlyError\" | \"onlyResponse\".\n\t * @default \"all\"\n\t */\n\tresultMode?: TResultMode;\n\n\t/**\n\t * Type-safe schemas for the response validation.\n\t */\n\tschemas?: TSchemas;\n\n\t/**\n\t * If true or the function returns true, throws errors instead of returning them\n\t * The function is passed the error object and can be used to conditionally throw the error\n\t * @default false\n\t */\n\tthrowOnError?: TThrowOnError | ((context: ErrorContext<TErrorData>) => TThrowOnError);\n\n\t/**\n\t * Request timeout in milliseconds\n\t */\n\ttimeout?: number;\n\n\t/**\n\t * Custom validation functions for response validation\n\t */\n\tvalidators?: CallApiValidators<TData, TErrorData>;\n\t/* eslint-disable perfectionist/sort-intersection-types -- Allow these to be last for the sake of docs */\n} & HooksOrHooksArray<TData, TErrorData, Partial<InferPluginOptions<TPluginArray>>>\n\t& Partial<InferPluginOptions<TPluginArray>>\n\t& MetaOption<TSchemas>\n\t& RetryOptions<TErrorData>\n\t& ResultModeOption<TErrorData, TResultMode>\n\t& UrlOptions<TSchemas>;\n/* eslint-enable perfectionist/sort-intersection-types -- Allow these to be last for the sake of docs */\n\nexport type CallApiExtraOptions<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResultMode extends ResultModeUnion = ResultModeUnion,\n\tTThrowOnError extends boolean = DefaultThrowOnError,\n\tTResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTPluginArray extends CallApiPlugin[] = DefaultPluginArray,\n\tTSchemas extends CallApiSchemas = DefaultMoreOptions,\n> = ExtraOptions<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TPluginArray, TSchemas> & {\n\tplugins?:\n\t\t| Plugins<TPluginArray>\n\t\t| ((context: { basePlugins: Plugins<TPluginArray> }) => Plugins<TPluginArray>);\n\n\tschemas?: TSchemas | ((context: { baseSchemas: TSchemas }) => TSchemas);\n\n\tvalidators?:\n\t\t| CallApiValidators<TData, TErrorData>\n\t\t| ((context: {\n\t\t\t\tbaseValidators: CallApiValidators<TData, TErrorData>;\n\t\t }) => CallApiValidators<TData, TErrorData>);\n};\n\nexport const optionsEnumToOmitFromBase = defineEnum([\"dedupeKey\"] satisfies Array<\n\tkeyof CallApiExtraOptions\n>);\n\nexport type BaseCallApiExtraOptions<\n\tTBaseData = DefaultDataType,\n\tTBaseErrorData = DefaultDataType,\n\tTBaseResultMode extends ResultModeUnion = ResultModeUnion,\n\tTBaseThrowOnError extends boolean = DefaultThrowOnError,\n\tTBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTBasePluginArray extends CallApiPlugin[] = DefaultPluginArray,\n\tTBaseSchemas extends CallApiSchemas = DefaultMoreOptions,\n> = Omit<\n\tPartial<\n\t\tCallApiExtraOptions<\n\t\t\tTBaseData,\n\t\t\tTBaseErrorData,\n\t\t\tTBaseResultMode,\n\t\t\tTBaseThrowOnError,\n\t\t\tTBaseResponseType,\n\t\t\tTBasePluginArray,\n\t\t\tTBaseSchemas\n\t\t>\n\t>,\n\t(typeof optionsEnumToOmitFromBase)[number]\n> & {\n\t/**\n\t * Specifies which configuration parts should skip automatic merging between base and main configs.\n\t * Use this when you need manual control over how configs are combined.\n\t *\n\t * @values\n\t * - \"all\" - Disables automatic merging for both request and options\n\t * - \"options\" - Disables automatic merging of options only\n\t * - \"request\" - Disables automatic merging of request only\n\t *\n\t * @example\n\t * ```ts\n\t * const client = createFetchClient((ctx) => ({\n\t * skipAutoMergeFor: \"options\",\n\t *\n\t * // Now you can manually merge options in your config function\n\t * ...ctx.options,\n\t * }));\n\t * ```\n\t */\n\tskipAutoMergeFor?: \"all\" | \"options\" | \"request\";\n};\n\ntype CombinedExtraOptionsWithoutHooks = Omit<BaseCallApiExtraOptions & CallApiExtraOptions, keyof Hooks>;\n\n// eslint-disable-next-line ts-eslint/consistent-type-definitions -- Allow this to be an interface\nexport interface CombinedCallApiExtraOptions extends CombinedExtraOptionsWithoutHooks, Hooks {}\n\nexport type BaseCallApiConfig<\n\tTBaseData = DefaultDataType,\n\tTBaseErrorData = DefaultDataType,\n\tTBaseResultMode extends ResultModeUnion = ResultModeUnion,\n\tTBaseThrowOnError extends boolean = DefaultThrowOnError,\n\tTBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTBasePluginArray extends CallApiPlugin[] = DefaultPluginArray,\n\tTBaseSchemas extends CallApiSchemas = DefaultMoreOptions,\n> =\n\t| (CallApiRequestOptions<TBaseSchemas> // eslint-disable-next-line perfectionist/sort-intersection-types -- Allow\n\t\t\t& BaseCallApiExtraOptions<\n\t\t\t\tTBaseData,\n\t\t\t\tTBaseErrorData,\n\t\t\t\tTBaseResultMode,\n\t\t\t\tTBaseThrowOnError,\n\t\t\t\tTBaseResponseType,\n\t\t\t\tTBasePluginArray,\n\t\t\t\tTBaseSchemas\n\t\t\t>)\n\t| ((context: {\n\t\t\tinitURL: string;\n\t\t\toptions: CallApiExtraOptions;\n\t\t\trequest: CallApiRequestOptions;\n\t }) => CallApiRequestOptions<TBaseSchemas> // eslint-disable-next-line perfectionist/sort-intersection-types -- Allow\n\t\t\t& BaseCallApiExtraOptions<\n\t\t\t\tTBaseData,\n\t\t\t\tTBaseErrorData,\n\t\t\t\tTBaseResultMode,\n\t\t\t\tTBaseThrowOnError,\n\t\t\t\tTBaseResponseType,\n\t\t\t\tTBasePluginArray,\n\t\t\t\tTBaseSchemas\n\t\t\t>);\n\nexport type CallApiConfig<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResultMode extends ResultModeUnion = ResultModeUnion,\n\tTThrowOnError extends boolean = DefaultThrowOnError,\n\tTResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTPluginArray extends CallApiPlugin[] = DefaultPluginArray,\n\tTSchemas extends CallApiSchemas = DefaultMoreOptions,\n> = CallApiRequestOptions<TSchemas> // eslint-disable-next-line perfectionist/sort-intersection-types -- Allow these to be last for the sake of docs\n\t& CallApiExtraOptions<\n\t\tTData,\n\t\tTErrorData,\n\t\tTResultMode,\n\t\tTThrowOnError,\n\t\tTResponseType,\n\t\tTPluginArray,\n\t\tTSchemas\n\t>;\n\nexport type CallApiParameters<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResultMode extends ResultModeUnion = ResultModeUnion,\n\tTThrowOnError extends boolean = DefaultThrowOnError,\n\tTResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTPluginArray extends CallApiPlugin[] = DefaultPluginArray,\n\tTSchemas extends CallApiSchemas = DefaultMoreOptions,\n> = [\n\tinitURL: InferSchemaResult<TSchemas[\"initURL\"], InitURL>,\n\tconfig?: CallApiConfig<\n\t\tTData,\n\t\tTErrorData,\n\t\tTResultMode,\n\t\tTThrowOnError,\n\t\tTResponseType,\n\t\tTPluginArray,\n\t\tTSchemas\n\t>,\n];\n\nexport type CallApiResultSuccessVariant<TData> = {\n\tdata: TData;\n\terror: null;\n\tresponse: Response;\n};\n\nexport type CallApiResultErrorVariant<TErrorData> =\n\t| {\n\t\t\tdata: null;\n\t\t\terror: PossibleHTTPError<TErrorData>;\n\t\t\tresponse: Response;\n\t }\n\t| {\n\t\t\tdata: null;\n\t\t\terror: PossibleJavaScriptError;\n\t\t\tresponse: null;\n\t };\n\nexport type ResultModeMap<\n\tTData = DefaultDataType,\n\tTErrorData = DefaultDataType,\n\tTResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTComputedData = GetResponseType<TData, TResponseType>,\n\tTComputedErrorData = GetResponseType<TErrorData, TResponseType>,\n> = UnmaskType<{\n\t/* eslint-disable perfectionist/sort-union-types -- I need the first one to be first */\n\tall: CallApiResultSuccessVariant<TComputedData> | CallApiResultErrorVariant<TComputedErrorData>;\n\n\tallWithException: CallApiResultSuccessVariant<TComputedData>;\n\n\tallWithoutResponse:\n\t\t| CallApiResultSuccessVariant<TComputedData>[\"data\" | \"error\"]\n\t\t| CallApiResultErrorVariant<TComputedErrorData>[\"data\" | \"error\"];\n\n\tonlyError:\n\t\t| CallApiResultSuccessVariant<TComputedData>[\"error\"]\n\t\t| CallApiResultErrorVariant<TComputedErrorData>[\"error\"];\n\n\tonlyResponse:\n\t\t| CallApiResultErrorVariant<TComputedErrorData>[\"response\"]\n\t\t| CallApiResultSuccessVariant<TComputedData>[\"response\"];\n\n\tonlyResponseWithException: CallApiResultSuccessVariant<TComputedData>[\"response\"];\n\n\tonlySuccess:\n\t\t| CallApiResultErrorVariant<TComputedErrorData>[\"data\"]\n\t\t| CallApiResultSuccessVariant<TComputedData>[\"data\"];\n\n\tonlySuccessWithException: CallApiResultSuccessVariant<TComputedData>[\"data\"];\n\t/* eslint-enable perfectionist/sort-union-types -- I need the first one to be first */\n}>;\n\nexport type ResultModeUnion = keyof ResultModeMap | null;\n\nexport type GetCallApiResult<\n\tTData,\n\tTErrorData,\n\tTResultMode extends ResultModeUnion,\n\tTThrowOnError extends boolean,\n\tTResponseType extends ResponseTypeUnion,\n> = TErrorData extends false | undefined\n\t? ResultModeMap<TData, TErrorData, TResponseType>[\"onlySuccessWithException\"]\n\t: null extends TResultMode\n\t\t? TThrowOnError extends true\n\t\t\t? ResultModeMap<TData, TErrorData, TResponseType>[\"allWithException\"]\n\t\t\t: ResultModeMap<TData, TErrorData, TResponseType>[\"all\"]\n\t\t: TResultMode extends NonNullable<ResultModeUnion>\n\t\t\t? TResultMode extends \"onlySuccess\"\n\t\t\t\t? ResultModeMap<TData, TErrorData, TResponseType>[\"onlySuccessWithException\"]\n\t\t\t\t: TResultMode extends \"onlyResponse\"\n\t\t\t\t\t? ResultModeMap<TData, TErrorData, TResponseType>[\"onlyResponseWithException\"]\n\t\t\t\t\t: ResultModeMap<TData, TErrorData, TResponseType>[TResultMode]\n\t\t\t: never;\n\nexport type CallApiResult<\n\tTData,\n\tTErrorData,\n\tTResultMode extends ResultModeUnion,\n\tTThrowOnError extends boolean,\n\tTResponseType extends ResponseTypeUnion,\n> = Promise<GetCallApiResult<TData, TErrorData, TResultMode, TThrowOnError, TResponseType>>;\n","import type {\n\tBaseCallApiExtraOptions,\n\tCallApiRequestOptions,\n\tCombinedCallApiExtraOptions,\n} from \"../types/common\";\nimport { defineEnum } from \"./type-helpers\";\n\nexport type ModifiedRequestInit = RequestInit & { duplex?: \"half\" };\n\nexport const fetchSpecificKeys = defineEnum([\n\t\"body\",\n\t\"integrity\",\n\t\"duplex\",\n\t\"method\",\n\t\"headers\",\n\t\"signal\",\n\t\"cache\",\n\t\"redirect\",\n\t\"window\",\n\t\"credentials\",\n\t\"keepalive\",\n\t\"referrer\",\n\t\"priority\",\n\t\"mode\",\n\t\"referrerPolicy\",\n] satisfies Array<keyof ModifiedRequestInit> as Array<keyof ModifiedRequestInit>);\n\nconst retryStatusCodesLookup = defineEnum({\n\t408: \"Request Timeout\",\n\t409: \"Conflict\",\n\t425: \"Too Early\",\n\t429: \"Too Many Requests\",\n\t500: \"Internal Server Error\",\n\t502: \"Bad Gateway\",\n\t503: \"Service Unavailable\",\n\t504: \"Gateway Timeout\",\n});\n\nexport const defaultRetryMethods = [\"GET\", \"POST\"] satisfies BaseCallApiExtraOptions[\"retryMethods\"];\n\n// prettier-ignore\nexport const defaultRetryStatusCodes = Object.keys(retryStatusCodesLookup).map(Number) as Required<BaseCallApiExtraOptions>[\"retryStatusCodes\"];\n\nexport const defaultExtraOptions = {\n\tbaseURL: \"\",\n\tbodySerializer: JSON.stringify,\n\tdedupeStrategy: \"cancel\",\n\tdefaultErrorMessage: \"Failed to fetch data from server!\",\n\tmergedHooksExecutionMode: \"parallel\",\n\tmergedHooksExecutionOrder: \"mainHooksAfterPlugins\",\n\tresponseType: \"json\",\n\tresultMode: \"all\",\n\tretryAttempts: 0,\n\tretryDelay: 1000,\n\tretryMaxDelay: 10000,\n\tretryMethods: defaultRetryMethods,\n\tretryStatusCodes: defaultRetryStatusCodes,\n\tretryStrategy: \"linear\",\n} satisfies CombinedCallApiExtraOptions;\n\nexport const defaultRequestOptions = {\n\tmethod: \"GET\",\n} satisfies CallApiRequestOptions;\n\nexport const getDefaultOptions = () => defaultExtraOptions;\n\nexport const getDefaultRequest = () => defaultRequestOptions;\n","import { getAuthHeader } from \"../auth\";\nimport {\n\ttype BaseCallApiExtraOptions,\n\ttype CallApiExtraOptions,\n\ttype CallApiRequestOptions,\n\toptionsEnumToOmitFromBase,\n} from \"../types/common\";\nimport { fetchSpecificKeys } from \"./constants\";\nimport { isFunction, isJsonString, isPlainObject, isQueryString, isSerializable } from \"./guards\";\n\nexport const omitKeys = <\n\tTObject extends Record<string, unknown>,\n\tconst TOmitArray extends Array<keyof TObject>,\n>(\n\tinitialObject: TObject,\n\tkeysToOmit: TOmitArray\n) => {\n\tconst updatedObject = {} as Record<string, unknown>;\n\n\tconst keysToOmitSet = new Set(keysToOmit);\n\n\tfor (const [key, value] of Object.entries(initialObject)) {\n\t\tif (!keysToOmitSet.has(key)) {\n\t\t\tupdatedObject[key] = value;\n\t\t}\n\t}\n\n\treturn updatedObject as Omit<TObject, TOmitArray[number]>;\n};\n\nexport const pickKeys = <\n\tTObject extends Record<string, unknown>,\n\tconst TPickArray extends Array<keyof TObject>,\n>(\n\tinitialObject: TObject,\n\tkeysToPick: TPickArray\n) => {\n\tconst updatedObject = {} as Record<string, unknown>;\n\n\tconst keysToPickSet = new Set(keysToPick);\n\n\tfor (const [key, value] of Object.entries(initialObject)) {\n\t\tif (keysToPickSet.has(key)) {\n\t\t\tupdatedObject[key] = value;\n\t\t}\n\t}\n\n\treturn updatedObject as Pick<TObject, TPickArray[number]>;\n};\n\n// eslint-disable-next-line ts-eslint/no-explicit-any -- Any is required here so that one can pass custom function type without type errors\nexport const splitBaseConfig = (baseConfig: Record<string, any>) =>\n\t[\n\t\tpickKeys(baseConfig, fetchSpecificKeys) as CallApiRequestOptions,\n\t\tomitKeys(baseConfig, [\n\t\t\t...fetchSpecificKeys,\n\t\t\t...optionsEnumToOmitFromBase,\n\t\t]) as BaseCallApiExtraOptions,\n\t] as const;\n\n// eslint-disable-next-line ts-eslint/no-explicit-any -- Any is required here so that one can pass custom function type without type errors\nexport const splitConfig = (config: Record<string, any>) =>\n\t[\n\t\tpickKeys(config, fetchSpecificKeys) as CallApiRequestOptions,\n\t\tomitKeys(config, fetchSpecificKeys) as CallApiExtraOptions,\n\t] as const;\n\ntype ToQueryStringFn = {\n\t(params: CallApiExtraOptions[\"query\"]): string | null;\n\t(params: Required<CallApiExtraOptions>[\"query\"]): string;\n};\n\nexport const toQueryString: ToQueryStringFn = (params) => {\n\tif (!params) {\n\t\tconsole.error(\"toQueryString:\", \"No query params provided!\");\n\n\t\treturn null as never;\n\t}\n\n\treturn new URLSearchParams(params as Record<string, string>).toString();\n};\n\nexport const objectifyHeaders = (headers: CallApiRequestOptions[\"headers\"]) => {\n\tif (!headers || isPlainObject(headers)) {\n\t\treturn headers;\n\t}\n\n\treturn Object.fromEntries(headers);\n};\n\ntype MergeAndResolveHeadersOptions = {\n\tauth: CallApiExtraOptions[\"auth\"];\n\tbaseHeaders?: CallApiRequestOptions[\"headers\"];\n\tbody: CallApiRequestOptions[\"body\"];\n\theaders: CallApiRequestOptions[\"headers\"];\n};\n\nexport const mergeAndResolveHeaders = (options: MergeAndResolveHeadersOptions) => {\n\tconst { auth, baseHeaders, body, headers } = options;\n\n\t// eslint-disable-next-line ts-eslint/prefer-nullish-coalescing -- Nullish coalescing makes no sense in this boolean context\n\tconst shouldResolveHeaders = Boolean(baseHeaders || headers || body || auth);\n\n\t// == Return early if any of the following conditions are not met (so that native fetch would auto set the correct headers):\n\t// == - headers are provided\n\t// == - The body is an object\n\t// == - The auth option is provided\n\tif (!shouldResolveHeaders) return;\n\n\tconst headersObject: Record<string, string | undefined> = {\n\t\t...getAuthHeader(auth),\n\t\t...objectifyHeaders(baseHeaders),\n\t\t...objectifyHeaders(headers),\n\t};\n\n\tif (isQueryString(body)) {\n\t\theadersObject[\"Content-Type\"] = \"application/x-www-form-urlencoded\";\n\n\t\treturn headersObject;\n\t}\n\n\tif (isSerializable(body) || isJsonString(body)) {\n\t\theadersObject[\"Content-Type\"] = \"application/json\";\n\t\theadersObject.Accept = \"application/json\";\n\t}\n\n\treturn headersObject;\n};\n\nexport const getFetchImpl = (customFetchImpl: CallApiExtraOptions[\"customFetchImpl\"]) => {\n\tif (customFetchImpl) {\n\t\treturn customFetchImpl;\n\t}\n\n\tif (typeof globalThis !== \"undefined\" && isFunction(globalThis.fetch)) {\n\t\treturn globalThis.fetch;\n\t}\n\n\tthrow new Error(\"No fetch implementation found\");\n};\n\nconst PromiseWithResolvers = () => {\n\tlet reject!: (reason?: unknown) => void;\n\tlet resolve!: (value: unknown) => void;\n\n\tconst promise = new Promise((res, rej) => {\n\t\tresolve = res;\n\t\treject = rej;\n\t});\n\n\treturn { promise, reject, resolve };\n};\n\nexport const waitUntil = (delay: number) => {\n\tif (delay === 0) return;\n\n\tconst { promise, resolve } = PromiseWithResolvers();\n\n\tsetTimeout(resolve, delay);\n\n\treturn promise;\n};\n\nexport const createCombinedSignal = (...signals: Array<AbortSignal | null | undefined>) =>\n\tAbortSignal.any(signals.filter(Boolean));\n\nexport const createTimeoutSignal = (milliseconds: number) => AbortSignal.timeout(milliseconds);\n","import type { CallApiExtraOptions, CallApiResultErrorVariant, ResultModeMap } from \"./types/common\";\nimport { omitKeys } from \"./utils/common\";\nimport { isHTTPErrorInstance } from \"./utils/guards\";\nimport type { UnmaskType } from \"./utils/type-helpers\";\n\ntype ErrorInfo = {\n\tcloneResponse: CallApiExtraOptions[\"cloneResponse\"];\n\tdefaultErrorMessage: Required<CallApiExtraOptions>[\"defaultErrorMessage\"];\n\terror?: unknown;\n\tmessage?: string;\n\tresultMode: CallApiExtraOptions[\"resultMode\"];\n};\n\nexport const resolveErrorResult = <TCallApiResult = never>(info: ErrorInfo) => {\n\tconst { cloneResponse, defaultErrorMessage, error, message: customErrorMessage, resultMode } = info;\n\n\tlet apiDetails: CallApiResultErrorVariant<unknown> = {\n\t\tdata: null,\n\t\terror: {\n\t\t\terrorData: error as Error,\n\t\t\tmessage: customErrorMessage ?? (error as Error).message,\n\t\t\tname: (error as Error).name as PossibleJavaScriptError[\"name\"],\n\t\t},\n\t\tresponse: null,\n\t};\n\n\tif (isHTTPErrorInstance<never>(error)) {\n\t\tconst { errorData, message = defaultErrorMessage, name, response } = error;\n\n\t\tapiDetails = {\n\t\t\tdata: null,\n\t\t\terror: {\n\t\t\t\terrorData,\n\t\t\t\tmessage,\n\t\t\t\tname,\n\t\t\t},\n\t\t\tresponse: cloneResponse ? response.clone() : response,\n\t\t};\n\t}\n\n\tconst resultModeMap = {\n\t\tall: apiDetails,\n\t\tallWithException: apiDetails as never,\n\t\tallWithoutResponse: omitKeys(apiDetails, [\"response\"]),\n\t\tonlyError: apiDetails.error,\n\t\tonlyResponse: apiDetails.response,\n\t\tonlyResponseWithException: apiDetails.response as never,\n\t\tonlySuccess: apiDetails.data,\n\t\tonlySuccessWithException: apiDetails.data,\n\t} satisfies ResultModeMap;\n\n\tconst getErrorResult = (customErrorInfo?: Pick<ErrorInfo, \"message\">) => {\n\t\tconst errorVariantResult = resultModeMap[resultMode ?? \"all\"] as TCallApiResult;\n\n\t\treturn customErrorInfo\n\t\t\t? {\n\t\t\t\t\t...errorVariantResult,\n\t\t\t\t\terror: {\n\t\t\t\t\t\t...(errorVariantResult as CallApiResultErrorVariant<unknown>).error,\n\t\t\t\t\t\t...customErrorInfo,\n\t\t\t\t\t},\n\t\t\t\t}\n\t\t\t: errorVariantResult;\n\t};\n\n\treturn { apiDetails, getErrorResult };\n};\n\ntype ErrorDetails<TErrorResponse> = {\n\tdefaultErrorMessage: string;\n\terrorData: TErrorResponse;\n\tresponse: Response;\n};\n\ntype ErrorOptions = {\n\tcause?: unknown;\n};\n\nexport class HTTPError<TErrorResponse = Record<string, unknown>> {\n\tcause: ErrorOptions[\"cause\"];\n\n\terrorData: ErrorDetails<TErrorResponse>[\"errorData\"];\n\n\tisHTTPError = true;\n\n\tmessage: string;\n\n\tname = \"HTTPError\" as const;\n\n\tresponse: ErrorDetails<TErrorResponse>[\"response\"];\n\n\tconstructor(errorDetails: ErrorDetails<TErrorResponse>, errorOptions?: ErrorOptions) {\n\t\tconst { defaultErrorMessage, errorData, response } = errorDetails;\n\n\t\tthis.message = (errorData as { message?: string } | undefined)?.message ?? defaultErrorMessage;\n\t\terrorOptions?.cause && (this.cause = errorOptions.cause);\n\t\tthis.errorData = errorData;\n\t\tthis.response = response;\n\t\tError.captureStackTrace(this, this.constructor);\n\t}\n}\n\nexport type PossibleJavaScriptError = UnmaskType<{\n\terrorData: DOMException | Error | SyntaxError | TypeError;\n\tmessage: string;\n\tname: \"AbortError\" | \"Error\" | \"SyntaxError\" | \"TimeoutError\" | \"TypeError\" | (`${string}Error` & {});\n}>;\n\nexport type PossibleHTTPError<TErrorData> = UnmaskType<{\n\terrorData: TErrorData;\n\tmessage: string;\n\tname: \"HTTPError\";\n}>;\n","import type { CallApiResultErrorVariant } from \"@/types\";\nimport { HTTPError, type PossibleHTTPError } from \"../error\";\nimport type { AnyFunction } from \"./type-helpers\";\n\nexport const isHTTPError = <TErrorData>(\n\terror: CallApiResultErrorVariant<TErrorData>[\"error\"] | null\n): error is PossibleHTTPError<TErrorData> => {\n\treturn isPlainObject(error) && error.name === \"HTTPError\";\n};\n\nexport const isHTTPErrorInstance = <TErrorResponse>(\n\terror: unknown\n): error is HTTPError<TErrorResponse> => {\n\treturn (\n\t\t// prettier-ignore\n\t\terror instanceof HTTPError|| (isPlainObject(error) && error.name === \"HTTPError\" && error.isHTTPError === true)\n\t);\n};\n\n// FIXME: Outsource to type-helpers later as a peer dependency\n\nexport const isArray = <TArrayItem>(value: unknown): value is TArrayItem[] => Array.isArray(value);\n\nexport const isObject = (value: unknown) => typeof value === \"object\" && value !== null;\n\nconst hasObjectPrototype = (value: unknown) => {\n\treturn Object.prototype.toString.call(value) === \"[object Object]\";\n};\n\n/**\n * @description Copied from TanStack Query's isPlainObject\n * @see https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L321\n */\nexport const isPlainObject = <TPlainObject extends Record<string, unknown>>(\n\tvalue: unknown\n): value is TPlainObject => {\n\tif (!hasObjectPrototype(value)) {\n\t\treturn false;\n\t}\n\n\t// If has no constructor\n\tconst constructor = (value as object | undefined)?.constructor;\n\tif (constructor === undefined) {\n\t\treturn true;\n\t}\n\n\t// If has modified prototype\n\tconst prototype = constructor.prototype as object;\n\tif (!hasObjectPrototype(prototype)) {\n\t\treturn false;\n\t}\n\n\t// If constructor does not have an Object-specific method\n\tif (!Object.hasOwn(prototype, \"isPrototypeOf\")) {\n\t\treturn false;\n\t}\n\n\t// Handles Objects created by Object.create(<arbitrary prototype>)\n\tif (Object.getPrototypeOf(value) !== Object.prototype) {\n\t\treturn false;\n\t}\n\n\t// It's probably a plain object at this point\n\treturn true;\n};\n\nexport const isJsonString = (value: unknown): value is string => {\n\tif (!isString(value)) {\n\t\treturn false;\n\t}\n\n\ttry {\n\t\tJSON.parse(value);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n};\n\nexport const isSerializable = (value: unknown) => {\n\treturn (\n\t\tisPlainObject(value)\n\t\t|| isArray(value)\n\t\t|| typeof (value as { toJSON: unknown } | undefined)?.toJSON === \"function\"\n\t);\n};\n\nexport const isFunction = <TFunction extends AnyFunction>(value: unknown): value is TFunction =>\n\ttypeof value === \"function\";\n\nexport const isQueryString = (value: unknown): value is string => isString(value) && value.includes(\"=\");\n\nexport const isString = (value: unknown) => typeof value === \"string\";\n\n// https://github.com/unjs/ofetch/blob/main/src/utils.ts\n// TODO Find a way to incorporate this function in checking when to apply the bodySerializer on the body and also whether to add the content type application/json\nexport const isJSONSerializable = (value: unknown) => {\n\tif (value === undefined) {\n\t\treturn false;\n\t}\n\tconst t = typeof value;\n\t// eslint-disable-next-line ts-eslint/no-unnecessary-condition -- No time to make this more type-safe\n\tif (t === \"string\" || t === \"number\" || t === \"boolean\" || t === null) {\n\t\treturn true;\n\t}\n\tif (t !== \"object\") {\n\t\treturn false;\n\t}\n\tif (isArray(value)) {\n\t\treturn true;\n\t}\n\tif ((value as Buffer | null)?.buffer) {\n\t\treturn false;\n\t}\n\n\treturn (\n\t\t(value?.constructor && value.constructor.name === \"Object\")\n\t\t// eslint-disable-next-line ts-eslint/prefer-nullish-coalescing -- Nullish coalescing makes no sense in this boolean context\n\t\t|| typeof (value as { toJSON: () => unknown } | null)?.toJSON === \"function\"\n\t);\n};\n\nexport const isReadableStream = (value: unknown): value is ReadableStream<unknown> => {\n\treturn value instanceof ReadableStream;\n};\n","import { type SharedHookContext, executeHooks } from \"./hooks\";\nimport { isObject } from \"./utils/guards\";\n\nexport type StreamProgressEvent = {\n\t/**\n\t * Current chunk of data being streamed\n\t */\n\tchunk: Uint8Array;\n\t/**\n\t * Progress in percentage\n\t */\n\tprogress: number;\n\t/**\n\t * Total size of data in bytes\n\t */\n\ttotalBytes: number;\n\t/**\n\t * Amount of data transferred so far\n\t */\n\ttransferredBytes: number;\n};\n\ndeclare global {\n\t// eslint-disable-next-line ts-eslint/consistent-type-definitions -- Allow\n\tinterface ReadableStream<R> {\n\t\t[Symbol.asyncIterator]: () => AsyncIterableIterator<R>;\n\t}\n}\n\nconst createProgressEvent = (options: {\n\tchunk: Uint8Array;\n\ttotalBytes: number;\n\ttransferredBytes: number;\n}): StreamProgressEvent => {\n\tconst { chunk, totalBytes, transferredBytes } = options;\n\n\treturn {\n\t\tchunk,\n\t\tprogress: Math.round((transferredBytes / totalBytes) * 100) || 0,\n\t\ttotalBytes,\n\t\ttransferredBytes,\n\t};\n};\n\nconst calculateTotalBytesFromBody = async (\n\trequestBody: Request[\"body\"] | null,\n\texistingTotalBytes: number\n) => {\n\tlet totalBytes = existingTotalBytes;\n\n\tif (!requestBody) {\n\t\treturn totalBytes;\n\t}\n\n\tfor await (const chunk of requestBody) {\n\t\ttotalBytes += chunk.byteLength;\n\t}\n\n\treturn totalBytes;\n};\n\ntype ToStreamableRequestContext = SharedHookContext & { requestInstance: Request };\n\nexport const toStreamableRequest = async (context: ToStreamableRequestContext) => {\n\tconst { baseConfig, config, options, request, requestInstance } = context;\n\n\tif (!options.onRequestStream || !requestInstance.body) return;\n\n\tconst contentLength =\n\t\trequestInstance.headers.get(\"content-length\")\n\t\t?? new Headers(request.headers as HeadersInit).get(\"content-length\")\n\t\t?? (request.body as Blob | null)?.size;\n\n\tlet totalBytes = Number(contentLength ?? 0);\n\n\tconst shouldForceContentLengthCalc = isObject(options.forceCalculateStreamSize)\n\t\t? options.forceCalculateStreamSize.request\n\t\t: options.forceCalculateStreamSize;\n\n\t// If no content length is present, we read the total bytes from the body\n\tif (!contentLength && shouldForceContentLengthCalc) {\n\t\ttotalBytes = await calculateTotalBytesFromBody(requestInstance.clone().body, totalBytes);\n\t}\n\n\tlet transferredBytes = 0;\n\n\tawait executeHooks(\n\t\toptions.onRequestStream({\n\t\t\tbaseConfig,\n\t\t\tconfig,\n\t\t\tevent: createProgressEvent({ chunk: new Uint8Array(), totalBytes, transferredBytes }),\n\t\t\toptions,\n\t\t\trequest,\n\t\t\trequestInstance,\n\t\t})\n\t);\n\n\tconst body = requestInstance.body as ReadableStream<Uint8Array> | null;\n\n\tvoid new ReadableStream({\n\t\tstart: async (controller) => {\n\t\t\tif (!body) return;\n\n\t\t\tfor await (const chunk of body) {\n\t\t\t\ttransferredBytes += chunk.byteLength;\n\n\t\t\t\ttotalBytes = Math.max(totalBytes, transferredBytes);\n\n\t\t\t\tawait executeHooks(\n\t\t\t\t\toptions.onRequestStream?.({\n\t\t\t\t\t\tbaseConfig,\n\t\t\t\t\t\tconfig,\n\t\t\t\t\t\tevent: createProgressEvent({ chunk, totalBytes, transferredBytes }),\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\trequestInstance,\n\t\t\t\t\t})\n\t\t\t\t);\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t}\n\t\t\tcontroller.close();\n\t\t},\n\t});\n};\n\ntype StreamableResponseContext = SharedHookContext & { response: Response };\nexport const toStreamableResponse = async (context: StreamableResponseContext): Promise<Response> => {\n\tconst { baseConfig, config, options, request, response } = context;\n\n\tif (!options.onResponseStream || !response.body) {\n\t\treturn response;\n\t}\n\n\tconst contentLength = response.headers.get(\"content-length\");\n\n\tlet totalBytes = Number(contentLength ?? 0);\n\n\tconst shouldForceContentLengthCalc = isObject(options.forceCalculateStreamSize)\n\t\t? options.forceCalculateStreamSize.response\n\t\t: options.forceCalculateStreamSize;\n\n\t// If no content length is present and `forceContentLengthCalculation` is enabled, we read the total bytes from the body\n\tif (!contentLength && shouldForceContentLengthCalc) {\n\t\ttotalBytes = await calculateTotalBytesFromBody(response.clone().body, totalBytes);\n\t}\n\n\tlet transferredBytes = 0;\n\n\tawait executeHooks(\n\t\toptions.onResponseStream({\n\t\t\tbaseConfig,\n\t\t\tconfig,\n\t\t\tevent: createProgressEvent({ chunk: new Uint8Array(), totalBytes, transferredBytes }),\n\t\t\toptions,\n\t\t\trequest,\n\t\t\tresponse,\n\t\t})\n\t);\n\n\tconst body = response.body as ReadableStream<Uint8Array> | null;\n\n\tconst stream = new ReadableStream({\n\t\tstart: async (controller) => {\n\t\t\tif (!body) return;\n\n\t\t\tfor await (const chunk of body) {\n\t\t\t\ttransferredBytes += chunk.byteLength;\n\n\t\t\t\ttotalBytes = Math.max(totalBytes, transferredBytes);\n\n\t\t\t\tawait executeHooks(\n\t\t\t\t\toptions.onResponseStream?.({\n\t\t\t\t\t\tbaseConfig,\n\t\t\t\t\t\tconfig,\n\t\t\t\t\t\tevent: createProgressEvent({ chunk, totalBytes, transferredBytes }),\n\t\t\t\t\t\toptions,\n\t\t\t\t\t\trequest,\n\t\t\t\t\t\tresponse,\n\t\t\t\t\t})\n\t\t\t\t);\n\n\t\t\t\tcontroller.enqueue(chunk);\n\t\t\t}\n\n\t\t\tcontroller.close();\n\t\t},\n\t});\n\n\treturn new Response(stream, response);\n};\n","import type { SharedHookContext } from \"./hooks\";\nimport { toStreamableRequest, toStreamableResponse } from \"./stream\";\nimport type { CallApiRequestOptions, CombinedCallApiExtraOptions } from \"./types/common\";\nimport { getFetchImpl, waitUntil } from \"./utils/common\";\nimport { isReadableStream } from \"./utils/guards\";\n\ntype RequestInfo = {\n\tcontroller: AbortController;\n\tresponsePromise: Promise<Response>;\n};\n\nexport type RequestInfoCache = Map<string | null, RequestInfo>;\n\ntype DedupeContext = SharedHookContext & {\n\t$RequestInfoCache: RequestInfoCache;\n\tnewFetchController: AbortController;\n};\n\nconst generateDedupeKey = (options: CombinedCallApiExtraOptions, request: CallApiRequestOptions) => {\n\tconst shouldHaveDedupeKey = options.dedupeStrategy === \"cancel\" || options.dedupeStrategy === \"defer\";\n\n\tif (!shouldHaveDedupeKey) {\n\t\treturn null;\n\t}\n\n\treturn `${options.fullURL}-${JSON.stringify({ options, request })}`;\n};\n\nexport const createDedupeStrategy = async (context: DedupeContext) => {\n\tconst { $RequestInfoCache, baseConfig, config, newFetchController, options, request } = context;\n\n\tconst dedupeKey = options.dedupeKey ?? generateDedupeKey(options, request);\n\n\t// == This is to ensure cache operations only occur when key is available\n\tconst $RequestInfoCacheOrNull = dedupeKey !== null ? $RequestInfoCache : null;\n\n\t/******\n\t * == Add a small delay to the execution to ensure proper request deduplication when multiple requests with the same key start simultaneously.\n\t * == This gives time for the cache to be updated with the previous request info before the next request checks it.\n\t ******/\n\tif (dedupeKey !== null) {\n\t\tawait waitUntil(0.1);\n\t}\n\n\tconst prevRequestInfo = $RequestInfoCacheOrNull?.get(dedupeKey);\n\n\tconst handleRequestCancelStrategy = () => {\n\t\tconst shouldCancelRequest = prevRequestInfo && options.dedupeStrategy === \"cancel\";\n\n\t\tif (!shouldCancelRequest) return;\n\n\t\tconst message = options.dedupeKey\n\t\t\t? `Duplicate request detected - Aborting previous request with key '${options.dedupeKey}' as a new request was initiated`\n\t\t\t: `Duplicate request detected - Aborting previous request to '${options.fullURL}' as a new request with identical options was initiated`;\n\n\t\tconst reason = new DOMException(message, \"AbortError\");\n\n\t\tprevRequestInfo.controller.abort(reason);\n\n\t\t// == Adding this just so that eslint forces me put await when calling the function (it looks better that way tbh)\n\t\treturn Promise.resolve();\n\t};\n\n\tconst handleRequestDeferStrategy = async () => {\n\t\tconst fetchApi = getFetchImpl(options.customFetchImpl);\n\n\t\tconst shouldUsePromiseFromCache = prevRequestInfo && options.dedupeStrategy === \"defer\";\n\n\t\tconst requestInstance = new Request(\n\t\t\toptions.fullURL as NonNullable<typeof options.fullURL>,\n\t\t\t(isReadableStream(request.body) && !request.duplex\n\t\t\t\t? { ...request, duplex: \"half\" }\n\t\t\t\t: request) as RequestInit\n\t\t);\n\n\t\tawait toStreamableRequest({\n\t\t\tbaseConfig,\n\t\t\tconfig,\n\t\t\toptions,\n\t\t\trequest,\n\t\t\trequestInstance: requestInstance.clone(),\n\t\t});\n\n\t\tconst getFetchApiPromise = () => {\n\t\t\tif (isReadableStream(request.body)) {\n\t\t\t\treturn fetchApi(requestInstance.clone());\n\t\t\t}\n\n\t\t\treturn fetchApi(options.fullURL as NonNullable<typeof options.fullURL>, request as RequestInit);\n\t\t};\n\n\t\tconst responsePromise = shouldUsePromiseFromCache\n\t\t\t? prevRequestInfo.responsePromise\n\t\t\t: getFetchApiPromise();\n\n\t\t$RequestInfoCacheOrNull?.set(dedupeKey, { controller: newFetchController, responsePromise });\n\n\t\tconst streamableResponse = toStreamableResponse({\n\t\t\tbaseConfig,\n\t\t\tconfig,\n\t\t\toptions,\n\t\t\trequest,\n\t\t\tresponse: await responsePromise,\n\t\t});\n\n\t\treturn streamableResponse;\n\t};\n\n\tconst removeDedupeKeyFromCache = () => {\n\t\t$RequestInfoCacheOrNull?.delete(dedupeKey);\n\t};\n\n\treturn {\n\t\thandleRequestCancelStrategy,\n\t\thandleRequestDeferStrategy,\n\t\tremoveDedupeKeyFromCache,\n\t};\n};\n","/* eslint-disable ts-eslint/consistent-type-definitions -- I need to use interfaces for the sake of user overrides */\nimport {\n\ttype Hooks,\n\ttype HooksOrHooksArray,\n\ttype SharedHookContext,\n\tcomposeTwoHooks,\n\thookRegistries,\n} from \"./hooks\";\nimport type {\n\tBaseCallApiExtraOptions,\n\tCallApiExtraOptions,\n\tCallApiRequestOptions,\n\tCallApiRequestOptionsForHooks,\n} from \"./types/common\";\nimport type { DefaultMoreOptions } from \"./types/default-types\";\nimport type { StandardSchemaV1 } from \"./types/standard-schema\";\nimport type { InitURL } from \"./url\";\nimport { isFunction, isPlainObject, isString } from \"./utils/guards\";\nimport type { AnyFunction, Awaitable, Prettify } from \"./utils/type-helpers\";\nimport type { InferSchemaResult } from \"./validation\";\n\ntype UnionToIntersection<TUnion> = (TUnion extends unknown ? (param: TUnion) => void : never) extends (\n\tparam: infer TParam\n) => void\n\t? TParam\n\t: never;\n\ntype InferSchema<TResult> = TResult extends StandardSchemaV1\n\t? InferSchemaResult<TResult, NonNullable<unknown>>\n\t: TResult;\n\nexport type InferPluginOptions<TPluginArray extends CallApiPlugin[]> = UnionToIntersection<\n\tInferSchema<ReturnType<NonNullable<TPluginArray[number][\"createExtraOptions\"]>>>\n>;\n\nexport type PluginInitContext<TMoreOptions = DefaultMoreOptions> = Prettify<\n\tSharedHookContext<TMoreOptions> & { initURL: InitURL | undefined }\n>;\n\nexport type PluginInitResult = Partial<\n\tOmit<PluginInitContext, \"request\"> & { request: CallApiRequestOptions }\n>;\n\nexport type PluginHooksWithMoreOptions<TMoreOptions = DefaultMoreOptions> = HooksOrHooksArray<\n\tnever,\n\tnever,\n\tTMoreOptions\n>;\n\nexport type PluginHooks<\n\tTData = never,\n\tTErrorData = never,\n\tTMoreOptions = DefaultMoreOptions,\n> = HooksOrHooksArray<TData, TErrorData, TMoreOptions>;\n\nexport interface CallApiPlugin {\n\t/**\n\t * Defines additional options that can be passed to callApi\n\t */\n\tcreateExtraOptions?: (...params: never[]) => unknown;\n\n\t/**\n\t * A description for the plugin\n\t */\n\tdescription?: string;\n\n\t/**\n\t * Hooks / Interceptors for the plugin\n\t */\n\thooks?: PluginHooks;\n\n\t/**\n\t * A unique id for the plugin\n\t */\n\tid: string;\n\n\t/**\n\t * A function that will be called when the plugin is initialized. This will be called before the any of the other internal functions.\n\t */\n\tinit?: (context: PluginInitContext) => Awaitable<PluginInitResult> | Awaitable<void>;\n\n\t/**\n\t * A name for the plugin\n\t */\n\tname: string;\n\n\t/**\n\t * A version for the plugin\n\t */\n\tversion?: string;\n}\n\nexport const definePlugin = <\n\t// eslint-disable-next-line perfectionist/sort-union-types -- Let the first one be first\n\tTPlugin extends CallApiPlugin | AnyFunction<CallApiPlugin>,\n>(\n\tplugin: TPlugin\n) => {\n\treturn plugin;\n};\n\nexport type Plugins<TPluginArray extends CallApiPlugin[]> = TPluginArray;\n\nconst resolvePluginArray = (\n\tplugins: CallApiExtraOptions[\"plugins\"] | undefined,\n\tbasePlugins: BaseCallApiExtraOptions[\"plugins\"] | undefined\n) => {\n\tif (!plugins) {\n\t\treturn [];\n\t}\n\n\tif (isFunction(plugins)) {\n\t\treturn plugins({ basePlugins: basePlugins ?? [] });\n\t}\n\n\treturn plugins;\n};\n\nexport const initializePlugins = async (context: PluginInitContext) => {\n\tconst { baseConfig, config, initURL, options, request } = context;\n\n\tconst clonedHookRegistries = structuredClone(hookRegistries);\n\n\tconst addMainHooks = () => {\n\t\tfor (const key of Object.keys(clonedHookRegistries)) {\n\t\t\tconst mainHook = options[key as keyof Hooks] as never;\n\n\t\t\tclonedHookRegistries[key as keyof Hooks].add(mainHook);\n\t\t}\n\t};\n\n\tconst addPluginHooks = (pluginHooks: Required<CallApiPlugin>[\"hooks\"]) => {\n\t\tfor (const key of Object.keys(clonedHookRegistries)) {\n\t\t\tconst pluginHook = pluginHooks[key as keyof Hooks] as never;\n\n\t\t\tclonedHookRegistries[key as keyof Hooks].add(pluginHook);\n\t\t}\n\t};\n\n\tif (options.mergedHooksExecutionOrder === \"mainHooksBeforePlugins\") {\n\t\taddMainHooks();\n\t}\n\n\tconst resolvedPlugins = resolvePluginArray(options.plugins, baseConfig.plugins);\n\n\tlet resolvedUrl = initURL;\n\tlet resolvedOptions = options;\n\tlet resolvedRequestOptions = request;\n\n\tconst executePluginInit = async (pluginInit: CallApiPlugin[\"init\"]) => {\n\t\tif (!pluginInit) return;\n\n\t\tconst initResult = await pluginInit({\n\t\t\tbaseConfig,\n\t\t\tconfig,\n\t\t\tinitURL,\n\t\t\toptions,\n\t\t\trequest,\n\t\t});\n\n\t\tif (!isPlainObject(initResult)) return;\n\n\t\tif (isString(initResult.initURL)) {\n\t\t\tresolvedUrl = initResult.initURL;\n\t\t}\n\n\t\tif (isPlainObject(initResult.request)) {\n\t\t\tresolvedRequestOptions = initResult.request as CallApiRequestOptionsForHooks;\n\t\t}\n\n\t\tif (isPlainObject(initResult.options)) {\n\t\t\tresolvedOptions = initResult.options;\n\t\t}\n\t};\n\n\tfor (const plugin of resolvedPlugins) {\n\t\t// eslint-disable-next-line no-await-in-loop -- Await is necessary in this case.\n\t\tawait executePluginInit(plugin.init);\n\n\t\tif (!plugin.hooks) continue;\n\n\t\taddPluginHooks(plugin.hooks);\n\t}\n\n\tif (\n\t\t!options.mergedHooksExecutionOrder\n\t\t|| options.mergedHooksExecutionOrder === \"mainHooksAfterPlugins\"\n\t) {\n\t\taddMainHooks();\n\t}\n\n\tconst resolvedHooks: Hooks = {};\n\n\tfor (const [key, hookRegistry] of Object.entries(clonedHookRegistries)) {\n\t\tconst flattenedHookArray = [...hookRegistry].flat().filter(Boolean);\n\n\t\tconst composedHook = composeTwoHooks(flattenedHookArray, options.mergedHooksExecutionMode);\n\n\t\tresolvedHooks[key as keyof Hooks] = composedHook;\n\t}\n\n\treturn {\n\t\tresolvedHooks,\n\t\tresolvedOptions,\n\t\tresolvedRequestOptions,\n\t\turl: resolvedUrl?.toString(),\n\t};\n};\n","import type { CallApiExtraOptions, CallApiResultSuccessVariant, ResultModeMap } from \"./types\";\nimport { omitKeys } from \"./utils/common\";\nimport type { Awaitable } from \"./utils/type-helpers\";\n\ntype Parser = (responseString: string) => Awaitable<Record<string, unknown>>;\n\nexport const getResponseType = <TResponse>(response: Response, parser?: Parser) => ({\n\tarrayBuffer: () => response.arrayBuffer(),\n\tblob: () => response.blob(),\n\tformData: () => response.formData(),\n\tjson: async () => {\n\t\tif (parser) {\n\t\t\tconst text = await response.text();\n\t\t\treturn parser(text) as TResponse;\n\t\t}\n\n\t\treturn response.json() as Promise<TResponse>;\n\t},\n\tstream: () => response.body,\n\ttext: () => response.text(),\n});\n\ntype InitResponseTypeMap<TResponse = unknown> = ReturnType<typeof getResponseType<TResponse>>;\n\nexport type ResponseTypeUnion = keyof InitResponseTypeMap | null;\n\nexport type ResponseTypeMap<TResponse> = {\n\t[Key in keyof InitResponseTypeMap<TResponse>]: Awaited<ReturnType<InitResponseTypeMap<TResponse>[Key]>>;\n};\n\nexport type GetResponseType<\n\tTResponse,\n\tTResponseType extends ResponseTypeUnion,\n\tTComputedResponseTypeMap extends ResponseTypeMap<TResponse> = ResponseTypeMap<TResponse>,\n> = null extends TResponseType\n\t? TComputedResponseTypeMap[\"json\"]\n\t: TResponseType extends NonNullable<ResponseTypeUnion>\n\t\t? TComputedResponseTypeMap[TResponseType]\n\t\t: never;\n\nexport const resolveResponseData = async <TResponse>(\n\tresponse: Response,\n\tresponseType: ResponseTypeUnion,\n\tparser: Parser | undefined\n) => {\n\tconst RESPONSE_TYPE_LOOKUP = getResponseType<TResponse>(response, parser);\n\n\tif (!responseType) {\n\t\treturn RESPONSE_TYPE_LOOKUP.json();\n\t}\n\n\tif (!Object.hasOwn(RESPONSE_TYPE_LOOKUP, responseType)) {\n\t\tthrow new Error(`Invalid response type: ${responseType}`);\n\t}\n\n\tconst responseData = await RESPONSE_TYPE_LOOKUP[responseType]();\n\n\treturn responseData;\n};\n\ntype SuccessInfo = {\n\tdata: unknown;\n\tresponse: Response;\n\tresultMode: CallApiExtraOptions[\"resultMode\"];\n};\n\n// == The CallApiResult type is used to cast all return statements due to a design limitation in ts.\n// LINK - See https://www.zhenghao.io/posts/type-functions for more info\nexport const resolveSuccessResult = <TCallApiResult>(info: SuccessInfo): TCallApiResult => {\n\tconst { data, response, resultMode } = info;\n\n\tconst apiDetails = { data, error: null, response } satisfies CallApiResultSuccessVariant<unknown>;\n\n\tif (!resultMode) {\n\t\treturn apiDetails as TCallApiResult;\n\t}\n\n\tconst resultModeMap = {\n\t\tall: apiDetails,\n\t\tallWithException: apiDetails,\n\t\tallWithoutResponse: omitKeys(apiDetails, [\"response\"]),\n\t\tonlyError: apiDetails.error,\n\t\tonlyResponse: apiDetails.response,\n\t\tonlyResponseWithException: apiDetails.response,\n\t\tonlySuccess: apiDetails.data,\n\t\tonlySuccessWithException: apiDetails.data,\n\t} satisfies ResultModeMap;\n\n\treturn resultModeMap[resultMode] as TCallApiResult;\n};\n","/* eslint-disable ts-eslint/consistent-type-definitions -- I need to use interfaces for the sake of user overrides */\nimport { resolveErrorResult } from \"./error\";\nimport { type ErrorContext, executeHooks } from \"./hooks\";\nimport type { Method } from \"./types\";\nimport type { AnyNumber, Awaitable } from \"./utils/type-helpers\";\n\ntype RetryCondition<TErrorData> = (context: ErrorContext<TErrorData>) => Awaitable<boolean>;\n\nexport interface RetryOptions<TErrorData> {\n\t/**\n\t * Keeps track of the number of times the request has already been retried\n\t * @deprecated This property is used internally to track retries. Please abstain from modifying it.\n\t */\n\treadonly [\"~retryCount\"]?: number;\n\n\t/**\n\t * Number of allowed retry attempts on HTTP errors\n\t * @default 0\n\t */\n\tretryAttempts?: number;\n\n\t/**\n\t * Callback whose return value determines if a request should be retried or not\n\t */\n\tretryCondition?: RetryCondition<TErrorData>;\n\n\t/**\n\t * Delay between retries in milliseconds\n\t * @default 1000\n\t */\n\tretryDelay?: number;\n\n\t/**\n\t * Maximum delay in milliseconds. Only applies to exponential strategy\n\t * @default 10000\n\t */\n\tretryMaxDelay?: number;\n\n\t/**\n\t * HTTP methods that are allowed to retry\n\t * @default [\"GET\", \"POST\"]\n\t */\n\tretryMethods?: Method[];\n\n\t/**\n\t * HTTP status codes that trigger a retry\n\t * @default [409, 425, 429, 500, 502, 503, 504]\n\t */\n\tretryStatusCodes?: Array<409 | 425 | 429 | 500 | 502 | 503 | 504 | AnyNumber>;\n\n\t/**\n\t * Strategy to use when retrying\n\t * @default \"linear\"\n\t */\n\tretryStrategy?: \"exponential\" | \"linear\";\n}\n\nconst getLinearDelay = <TErrorData>(options: RetryOptions<TErrorData>) => options.retryDelay ?? 1000;\n\nconst getExponentialDelay = <TErrorData>(\n\tcurrentAttemptCount: number,\n\toptions: RetryOptions<TErrorData>\n) => {\n\tconst maxDelay = options.retryMaxDelay ?? 10000;\n\n\tconst exponentialDelay = (options.retryDelay ?? 1000) * 2 ** currentAttemptCount;\n\n\treturn Math.min(exponentialDelay, maxDelay);\n};\n\nexport const createRetryStrategy = <TErrorData>(ctx: ErrorContext<TErrorData>) => {\n\tconst { options } = ctx;\n\n\tconst currentRetryCount = options[\"~retryCount\"] ?? 0;\n\n\tconst getDelay = () => {\n\t\tif (options.retryStrategy === \"exponential\") {\n\t\t\treturn getExponentialDelay(currentRetryCount, options);\n\t\t}\n\n\t\treturn getLinearDelay(options);\n\t};\n\n\tconst shouldAttemptRetry = async () => {\n\t\tconst customRetryCondition = (await options.retryCondition?.(ctx)) ?? true;\n\n\t\tconst maxRetryAttempts = options.retryAttempts ?? 0;\n\n\t\tconst baseRetryCondition = maxRetryAttempts > currentRetryCount && customRetryCondition;\n\n\t\tif (ctx.error.name !== \"HTTPError\") {\n\t\t\treturn baseRetryCondition;\n\t\t}\n\n\t\tconst includesMethod =\n\t\t\t// eslint-disable-next-line no-implicit-coercion -- Boolean doesn't narrow\n\t\t\t!!ctx.request.method && options.retryMethods?.includes(ctx.request.method);\n\n\t\tconst includesCodes =\n\t\t\t// eslint-disable-next-line no-implicit-coercion -- Boolean doesn't narrow\n\t\t\t!!ctx.response?.status && options.retryStatusCodes?.includes(ctx.response.status);\n\n\t\treturn includesCodes && includesMethod && baseRetryCondition;\n\t};\n\n\tconst executeRetryHook = async (shouldThrowOnError: boolean | undefined) => {\n\t\ttry {\n\t\t\treturn await executeHooks(options.onRetry?.(ctx));\n\t\t} catch (error) {\n\t\t\tconst { apiDetails } = resolveErrorResult({\n\t\t\t\tcloneResponse: options.cloneResponse,\n\t\t\t\tdefaultErrorMessage: options.defaultErrorMessage as string,\n\t\t\t\terror,\n\t\t\t\tresultMode: options.resultMode,\n\t\t\t});\n\n\t\t\tif (shouldThrowOnError) {\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\treturn apiDetails;\n\t\t}\n\t};\n\n\treturn {\n\t\texecuteRetryHook,\n\t\tgetDelay,\n\t\tshouldAttemptRetry,\n\t};\n};\n","/* eslint-disable ts-eslint/consistent-type-definitions -- I need to use interfaces for the sake of user overrides */\nimport type { CallApiExtraOptions } from \"./types/common\";\nimport { toQueryString } from \"./utils\";\nimport { isArray } from \"./utils/guards\";\nimport type { UnmaskType } from \"./utils/type-helpers\";\nimport type { CallApiSchemas, InferSchemaResult } from \"./validation\";\n\nconst slash = \"/\";\nconst column = \":\";\nconst mergeUrlWithParams = (url: string, params: CallApiExtraOptions[\"params\"]) => {\n\tif (!params) {\n\t\treturn url;\n\t}\n\n\tlet newUrl = url;\n\n\tif (isArray(params)) {\n\t\tconst matchedParamArray = newUrl.split(slash).filter((param) => param.startsWith(column));\n\n\t\tfor (const [index, matchedParam] of matchedParamArray.entries()) {\n\t\t\tconst realParam = params[index] as string;\n\t\t\tnewUrl = newUrl.replace(matchedParam, realParam);\n\t\t}\n\n\t\treturn newUrl;\n\t}\n\n\tfor (const [key, value] of Object.entries(params)) {\n\t\tnewUrl = newUrl.replace(`${column}${key}`, String(value));\n\t}\n\n\treturn newUrl;\n};\n\nconst questionMark = \"?\";\nconst ampersand = \"&\";\nconst mergeUrlWithQuery = (url: string, query: CallApiExtraOptions[\"query\"]): string => {\n\tif (!query) {\n\t\treturn url;\n\t}\n\n\tconst queryString = toQueryString(query);\n\n\tif (queryString?.length === 0) {\n\t\treturn url;\n\t}\n\n\tif (url.endsWith(questionMark)) {\n\t\treturn `${url}${queryString}`;\n\t}\n\n\tif (url.includes(questionMark)) {\n\t\treturn `${url}${ampersand}${queryString}`;\n\t}\n\n\treturn `${url}${questionMark}${queryString}`;\n};\n\nexport const mergeUrlWithParamsAndQuery = (\n\turl: string | undefined,\n\tparams: CallApiExtraOptions[\"params\"],\n\tquery: CallApiExtraOptions[\"query\"]\n) => {\n\tif (!url) return;\n\n\tconst urlWithMergedParams = mergeUrlWithParams(url, params);\n\n\treturn mergeUrlWithQuery(urlWithMergedParams, query);\n};\n\nexport type Params = UnmaskType<\n\t// eslint-disable-next-line perfectionist/sort-union-types -- I need the Record to be first\n\tRecord<string, boolean | number | string> | Array<boolean | number | string>\n>;\n\nexport type Query = UnmaskType<Record<string, boolean | number | string>>;\n\nexport type InitURL = UnmaskType<string | URL>;\n\nexport interface UrlOptions<TSchemas extends CallApiSchemas> {\n\t/**\n\t * URL to be used in the request.\n\t */\n\treadonly initURL?: string;\n\n\t/**\n\t * Parameters to be appended to the URL (i.e: /:id)\n\t */\n\tparams?: InferSchemaResult<TSchemas[\"params\"], Params>;\n\n\t/**\n\t * Query parameters to append to the URL.\n\t */\n\tquery?: InferSchemaResult<TSchemas[\"query\"], Query>;\n}\n","/* eslint-disable ts-eslint/consistent-type-definitions -- I need to use interfaces for the sake of user overrides */\nimport type { Body, GlobalMeta, Headers, Method } from \"./types\";\nimport type { StandardSchemaV1 } from \"./types/standard-schema\";\nimport type { InitURL, Params, Query } from \"./url\";\n\nexport const standardSchemaParser = async <TSchema extends StandardSchemaV1>(\n\tschema: TSchema,\n\tinputData: StandardSchemaV1.InferInput<TSchema>\n): Promise<StandardSchemaV1.InferOutput<TSchema>> => {\n\tconst result = await schema[\"~standard\"].validate(inputData);\n\n\t// == If the `issues` field exists, it means the validation failed\n\tif (result.issues) {\n\t\tthrow new Error(JSON.stringify(result.issues, null, 2), { cause: result.issues });\n\t}\n\n\treturn result.value;\n};\n\nexport interface CallApiSchemas {\n\t/**\n\t * The schema to use for validating the request body.\n\t */\n\tbody?: StandardSchemaV1<Body>;\n\n\t/**\n\t * The schema to use for validating the response data.\n\t */\n\tdata?: StandardSchemaV1;\n\n\t/**\n\t * The schema to use for validating the response error data.\n\t */\n\terrorData?: StandardSchemaV1;\n\n\t/**\n\t * The schema to use for validating the request headers.\n\t */\n\theaders?: StandardSchemaV1<Headers>;\n\n\t/**\n\t * The schema to use for validating the request url.\n\t */\n\tinitURL?: StandardSchemaV1<InitURL>;\n\n\t/**\n\t * The schema to use for validating the meta option.\n\t */\n\tmeta?: StandardSchemaV1<GlobalMeta>;\n\n\t/**\n\t * The schema to use for validating the request method.\n\t */\n\tmethod?: StandardSchemaV1<Method>;\n\n\t/**\n\t * The schema to use for validating the request url parameter.\n\t */\n\tparams?: StandardSchemaV1<Params>;\n\n\t/**\n\t * The schema to use for validating the request url querys.\n\t */\n\tquery?: StandardSchemaV1<Query>;\n}\n\nexport interface CallApiValidators<TData = unknown, TErrorData = unknown> {\n\t/**\n\t * Custom function to validate the response data.\n\t */\n\tdata?: (value: unknown) => TData;\n\n\t/**\n\t * Custom function to validate the response error data, stemming from the api.\n\t * This only runs if the api actually sends back error status codes, else it will be ignored, in which case you should only use the `responseValidator` option.\n\t */\n\terrorData?: (value: unknown) => TErrorData;\n}\n\nexport type InferSchemaResult<TSchema, TData> = TSchema extends StandardSchemaV1\n\t? StandardSchemaV1.InferOutput<TSchema>\n\t: TData;\n\nexport const handleValidation = async (\n\tresponseData: unknown,\n\tschema: CallApiSchemas[keyof NonNullable<CallApiSchemas>],\n\tvalidator?: CallApiValidators[keyof NonNullable<CallApiValidators>]\n) => {\n\tconst validResponseData = validator ? validator(responseData) : responseData;\n\n\tconst schemaValidResponseData = schema\n\t\t? await standardSchemaParser(schema, validResponseData)\n\t\t: validResponseData;\n\n\treturn schemaValidResponseData;\n};\n","import { type RequestInfoCache, createDedupeStrategy } from \"./dedupe\";\nimport { HTTPError, resolveErrorResult } from \"./error\";\nimport { type ErrorContext, type SuccessContext, executeHooks } from \"./hooks\";\nimport { type CallApiPlugin, initializePlugins } from \"./plugins\";\nimport { type ResponseTypeUnion, resolveResponseData, resolveSuccessResult } from \"./response\";\nimport { createRetryStrategy } from \"./retry\";\nimport type {\n\tBaseCallApiConfig,\n\tBaseCallApiExtraOptions,\n\tCallApiExtraOptions,\n\tCallApiParameters,\n\tCallApiRequestOptions,\n\tCallApiRequestOptionsForHooks,\n\tCallApiResult,\n\tCombinedCallApiExtraOptions,\n\tResultModeUnion,\n} from \"./types/common\";\nimport type {\n\tDefaultDataType,\n\tDefaultMoreOptions,\n\tDefaultPluginArray,\n\tDefaultThrowOnError,\n} from \"./types/default-types\";\nimport { mergeUrlWithParamsAndQuery } from \"./url\";\nimport {\n\tcreateCombinedSignal,\n\tcreateTimeoutSignal,\n\tmergeAndResolveHeaders,\n\tsplitBaseConfig,\n\tsplitConfig,\n\twaitUntil,\n} from \"./utils/common\";\nimport { defaultExtraOptions, defaultRequestOptions } from \"./utils/constants\";\nimport { isFunction, isHTTPErrorInstance, isSerializable } from \"./utils/guards\";\nimport { type CallApiSchemas, type InferSchemaResult, handleValidation } from \"./validation\";\n\nexport const createFetchClient = <\n\tTBaseData = DefaultDataType,\n\tTBaseErrorData = DefaultDataType,\n\tTBaseResultMode extends ResultModeUnion = ResultModeUnion,\n\tTBaseThrowOnError extends boolean = DefaultThrowOnError,\n\tTBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTBasePluginArray extends CallApiPlugin[] = DefaultPluginArray,\n\tTBaseSchemas extends CallApiSchemas = DefaultMoreOptions,\n>(\n\tinitBaseConfig: BaseCallApiConfig<\n\t\tTBaseData,\n\t\tTBaseErrorData,\n\t\tTBaseResultMode,\n\t\tTBaseThrowOnError,\n\t\tTBaseResponseType,\n\t\tTBasePluginArray,\n\t\tTBaseSchemas\n\t> = {} as never\n) => {\n\tconst $RequestInfoCache: RequestInfoCache = new Map();\n\n\tconst callApi = async <\n\t\tTData = InferSchemaResult<TBaseSchemas[\"data\"], TBaseData>,\n\t\tTErrorData = InferSchemaResult<TBaseSchemas[\"errorData\"], TBaseErrorData>,\n\t\tTResultMode extends ResultModeUnion = TBaseResultMode,\n\t\tTThrowOnError extends boolean = TBaseThrowOnError,\n\t\tTResponseType extends ResponseTypeUnion = TBaseResponseType,\n\t\tTPluginArray extends CallApiPlugin[] = TBasePluginArray,\n\t\tTSchemas extends CallApiSchemas = TBaseSchemas,\n\t>(\n\t\t...parameters: CallApiParameters<\n\t\t\tTData,\n\t\t\tTErrorData,\n\t\t\tTResultMode,\n\t\t\tTThrowOnError,\n\t\t\tTResponseType,\n\t\t\tTPluginArray,\n\t\t\tTSchemas\n\t\t>\n\t): CallApiResult<\n\t\tInferSchemaResult<TSchemas[\"data\"], TData>,\n\t\tInferSchemaResult<TSchemas[\"errorData\"], TErrorData>,\n\t\tTResultMode,\n\t\tTThrowOnError,\n\t\tTResponseType\n\t> => {\n\t\tconst [initURL, initConfig = {}] = parameters;\n\n\t\tconst [fetchOptions, extraOptions] = splitConfig(initConfig);\n\n\t\tconst resolvedBaseConfig = isFunction(initBaseConfig)\n\t\t\t? initBaseConfig({ initURL: initURL.toString(), options: extraOptions, request: fetchOptions })\n\t\t\t: initBaseConfig;\n\n\t\tconst [baseFetchOptions, baseExtraOptions] = splitBaseConfig(resolvedBaseConfig);\n\n\t\t// == Merged Extra Options\n\t\tconst mergedExtraOptions = {\n\t\t\t...defaultExtraOptions,\n\t\t\t...baseExtraOptions,\n\t\t\t...(baseExtraOptions.skipAutoMergeFor !== \"all\"\n\t\t\t\t&& baseExtraOptions.skipAutoMergeFor !== \"options\"\n\t\t\t\t&& extraOptions),\n\t\t};\n\n\t\t// == Merged Request Options\n\t\tconst mergedRequestOptions = {\n\t\t\t...defaultRequestOptions,\n\t\t\t...baseFetchOptions,\n\t\t\t...(baseExtraOptions.skipAutoMergeFor !== \"all\"\n\t\t\t\t&& baseExtraOptions.skipAutoMergeFor !== \"request\"\n\t\t\t\t&& fetchOptions),\n\t\t} satisfies CallApiRequestOptions;\n\n\t\tconst baseConfig = resolvedBaseConfig as BaseCallApiExtraOptions & CallApiRequestOptions;\n\t\tconst config = initConfig as CallApiExtraOptions & CallApiRequestOptions;\n\n\t\tconst { resolvedHooks, resolvedOptions, resolvedRequestOptions, url } = await initializePlugins({\n\t\t\tbaseConfig,\n\t\t\tconfig,\n\t\t\tinitURL,\n\t\t\toptions: mergedExtraOptions as CombinedCallApiExtraOptions,\n\t\t\trequest: mergedRequestOptions as CallApiRequestOptionsForHooks,\n\t\t});\n\n\t\tconst fullURL = `${resolvedOptions.baseURL}${mergeUrlWithParamsAndQuery(url, resolvedOptions.params, resolvedOptions.query)}`;\n\n\t\t// FIXME - Consider adding an option for refetching a callApi request\n\t\tconst options = {\n\t\t\t...resolvedOptions,\n\t\t\t...resolvedHooks,\n\t\t\tfullURL,\n\t\t\tinitURL: initURL.toString(),\n\t\t} satisfies CombinedCallApiExtraOptions as typeof mergedExtraOptions & typeof resolvedHooks;\n\n\t\tconst newFetchController = new AbortController();\n\n\t\tconst timeoutSignal = options.timeout != null ? createTimeoutSignal(options.timeout) : null;\n\n\t\tconst combinedSignal = createCombinedSignal(\n\t\t\tresolvedRequestOptions.signal,\n\t\t\ttimeoutSignal,\n\t\t\tnewFetchController.signal\n\t\t);\n\n\t\tconst request = {\n\t\t\t...resolvedRequestOptions,\n\n\t\t\tbody: isSerializable(resolvedRequestOptions.body)\n\t\t\t\t? options.bodySerializer(resolvedRequestOptions.body)\n\t\t\t\t: resolvedRequestOptions.body,\n\n\t\t\theaders: mergeAndResolveHeaders({\n\t\t\t\tauth: options.auth,\n\t\t\t\tbaseHeaders: baseFetchOptions.headers,\n\t\t\t\tbody: resolvedRequestOptions.body,\n\t\t\t\theaders: fetchOptions.headers,\n\t\t\t}),\n\n\t\t\tsignal: combinedSignal,\n\t\t} satisfies CallApiRequestOptionsForHooks;\n\n\t\tconst { handleRequestCancelStrategy, handleRequestDeferStrategy, removeDedupeKeyFromCache } =\n\t\t\tawait createDedupeStrategy({\n\t\t\t\t$RequestInfoCache,\n\t\t\t\tbaseConfig,\n\t\t\t\tconfig,\n\t\t\t\tnewFetchController,\n\t\t\t\toptions,\n\t\t\t\trequest,\n\t\t\t});\n\n\t\tawait handleRequestCancelStrategy();\n\n\t\ttry {\n\t\t\tawait executeHooks(options.onRequest?.({ baseConfig, config, options, request }));\n\n\t\t\t// == Apply determined headers again after onRequest incase they were modified\n\t\t\trequest.headers = mergeAndResolveHeaders({\n\t\t\t\tauth: options.auth,\n\t\t\t\tbody: request.body,\n\t\t\t\theaders: request.headers,\n\t\t\t});\n\n\t\t\tconst response = await handleRequestDeferStrategy();\n\n\t\t\t// == Also clone response when dedupeStrategy is set to \"defer\" or when onRequestStream is set, to avoid error thrown from reading response.(whatever) more than once\n\t\t\tconst shouldCloneResponse = options.dedupeStrategy === \"defer\" || options.cloneResponse;\n\n\t\t\tconst schemas = (\n\t\t\t\tisFunction(options.schemas)\n\t\t\t\t\t? options.schemas({ baseSchemas: baseExtraOptions.schemas ?? {} })\n\t\t\t\t\t: options.schemas\n\t\t\t) as CallApiSchemas | undefined;\n\n\t\t\tconst validators = isFunction(options.validators)\n\t\t\t\t? options.validators({ baseValidators: baseExtraOptions.validators ?? {} })\n\t\t\t\t: options.validators;\n\n\t\t\tif (!response.ok) {\n\t\t\t\tconst errorData = await resolveResponseData<TErrorData>(\n\t\t\t\t\tshouldCloneResponse ? response.clone() : response,\n\t\t\t\t\toptions.responseType,\n\t\t\t\t\toptions.responseParser\n\t\t\t\t);\n\n\t\t\t\tconst validErrorData = await handleValidation(\n\t\t\t\t\terrorData,\n\t\t\t\t\tschemas?.errorData,\n\t\t\t\t\tvalidators?.errorData\n\t\t\t\t);\n\n\t\t\t\t// == Push all error handling responsibilities to the catch block if not retrying\n\t\t\t\t// eslint-disable-next-line ts-eslint/only-throw-error -- This is intended\n\t\t\t\tthrow new HTTPError({\n\t\t\t\t\tdefaultErrorMessage: options.defaultErrorMessage,\n\t\t\t\t\terrorData: validErrorData,\n\t\t\t\t\tresponse,\n\t\t\t\t});\n\t\t\t}\n\n\t\t\tconst successData = await resolveResponseData<TData>(\n\t\t\t\tshouldCloneResponse ? response.clone() : response,\n\t\t\t\toptions.responseType,\n\t\t\t\toptions.responseParser\n\t\t\t);\n\n\t\t\tconst validSuccessData = await handleValidation(successData, schemas?.data, validators?.data);\n\n\t\t\tconst successContext = {\n\t\t\t\tbaseConfig,\n\t\t\t\tconfig,\n\t\t\t\tdata: validSuccessData,\n\t\t\t\toptions,\n\t\t\t\trequest,\n\t\t\t\tresponse,\n\t\t\t} satisfies SuccessContext<unknown>;\n\n\t\t\tawait executeHooks(\n\t\t\t\toptions.onSuccess?.(successContext),\n\n\t\t\t\toptions.onResponse?.({ ...successContext, error: null })\n\t\t\t);\n\n\t\t\treturn await resolveSuccessResult({\n\t\t\t\tdata: successContext.data,\n\t\t\t\tresponse: successContext.response,\n\t\t\t\tresultMode: options.resultMode,\n\t\t\t});\n\n\t\t\t// == Exhaustive Error handling\n\t\t} catch (error) {\n\t\t\tconst { apiDetails, getErrorResult } = resolveErrorResult({\n\t\t\t\tcloneResponse: options.cloneResponse,\n\t\t\t\tdefaultErrorMessage: options.defaultErrorMessage,\n\t\t\t\terror,\n\t\t\t\tresultMode: options.resultMode,\n\t\t\t});\n\n\t\t\tconst errorContext = {\n\t\t\t\tbaseConfig,\n\t\t\t\tconfig,\n\t\t\t\terror: apiDetails.error as never,\n\t\t\t\toptions,\n\t\t\t\trequest,\n\t\t\t\tresponse: apiDetails.response as never,\n\t\t\t} satisfies ErrorContext<unknown>;\n\n\t\t\tconst shouldThrowOnError = isFunction(options.throwOnError)\n\t\t\t\t? options.throwOnError(errorContext)\n\t\t\t\t: options.throwOnError;\n\n\t\t\tconst handleRetryOrGetResult = async (customInfo?: { message?: string }) => {\n\t\t\t\tconst { executeRetryHook, getDelay, shouldAttemptRetry } = createRetryStrategy(errorContext);\n\n\t\t\t\tconst shouldRetry = !combinedSignal.aborted && (await shouldAttemptRetry());\n\n\t\t\t\tif (shouldRetry) {\n\t\t\t\t\tawait executeRetryHook(shouldThrowOnError);\n\n\t\t\t\t\tconst delay = getDelay();\n\n\t\t\t\t\tawait waitUntil(delay);\n\n\t\t\t\t\tconst updatedOptions = {\n\t\t\t\t\t\t...config,\n\t\t\t\t\t\t\"~retryCount\": (options[\"~retryCount\"] ?? 0) + 1,\n\t\t\t\t\t} satisfies typeof config;\n\n\t\t\t\t\treturn callApi(initURL, updatedOptions as never) as never;\n\t\t\t\t}\n\n\t\t\t\tif (shouldThrowOnError) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\n\t\t\t\treturn customInfo ? getErrorResult(customInfo) : getErrorResult();\n\t\t\t};\n\n\t\t\tif (isHTTPErrorInstance<TErrorData>(error)) {\n\t\t\t\tawait executeHooks(\n\t\t\t\t\toptions.onResponseError?.(errorContext),\n\n\t\t\t\t\toptions.onError?.(errorContext),\n\n\t\t\t\t\toptions.onResponse?.({ ...errorContext, data: null })\n\t\t\t\t);\n\n\t\t\t\treturn await handleRetryOrGetResult();\n\t\t\t}\n\n\t\t\tif (error instanceof DOMException && error.name === \"AbortError\") {\n\t\t\t\tconst { message, name } = error;\n\n\t\t\t\t!shouldThrowOnError && console.error(`${name}:`, message);\n\n\t\t\t\treturn await handleRetryOrGetResult();\n\t\t\t}\n\n\t\t\tif (error instanceof DOMException && error.name === \"TimeoutError\") {\n\t\t\t\tconst message = `Request timed out after ${options.timeout}ms`;\n\n\t\t\t\t!shouldThrowOnError && console.error(`${error.name}:`, message);\n\n\t\t\t\treturn await handleRetryOrGetResult({ message });\n\t\t\t}\n\n\t\t\tawait executeHooks(\n\t\t\t\t// == At this point only the request errors exist, so the request error hook is called\n\t\t\t\toptions.onRequestError?.(errorContext as never),\n\n\t\t\t\t// == Also call the onError hook\n\t\t\t\toptions.onError?.(errorContext)\n\t\t\t);\n\n\t\t\treturn await handleRetryOrGetResult();\n\n\t\t\t// == Removing the now unneeded AbortController from store\n\t\t} finally {\n\t\t\tremoveDedupeKeyFromCache();\n\t\t}\n\t};\n\n\treturn callApi;\n};\n\nexport const callApi = createFetchClient();\n","import type { CallApiPlugin } from \"./plugins\";\nimport type { ResponseTypeUnion } from \"./response\";\nimport type { CallApiParameters, ResultModeUnion } from \"./types\";\nimport type { DefaultMoreOptions, DefaultPluginArray, DefaultThrowOnError } from \"./types/default-types\";\nimport type { CallApiSchemas } from \"./validation\";\n\nconst defineParameters = <\n\tTData = unknown,\n\tTErrorData = unknown,\n\tTResultMode extends ResultModeUnion = ResultModeUnion,\n\tTThrowOnError extends boolean = DefaultThrowOnError,\n\tTResponseType extends ResponseTypeUnion = ResponseTypeUnion,\n\tTPluginArray extends CallApiPlugin[] = DefaultPluginArray,\n\tTSchemas extends CallApiSchemas = DefaultMoreOptions,\n>(\n\t...parameters: CallApiParameters<\n\t\tTData,\n\t\tTErrorData,\n\t\tTResultMode,\n\t\tTThrowOnError,\n\t\tTResponseType,\n\t\tTPluginArray,\n\t\tTSchemas\n\t>\n) => {\n\treturn parameters;\n};\n\nexport { defineParameters };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACmMO,IAAM,iBAAiB;AAAA,EAC7B,SAAS,oBAAI,IAAI;AAAA,EACjB,WAAW,oBAAI,IAAI;AAAA,EACnB,gBAAgB,oBAAI,IAAI;AAAA,EACxB,iBAAiB,oBAAI,IAAI;AAAA,EACzB,YAAY,oBAAI,IAAI;AAAA,EACpB,iBAAiB,oBAAI,IAAI;AAAA,EACzB,kBAAkB,oBAAI,IAAI;AAAA,EAC1B,SAAS,oBAAI,IAAI;AAAA,EACjB,WAAW,oBAAI,IAAI;AACpB;AAEO,IAAM,kBAAkB,CAC9B,OACA,6BACI;AACJ,MAAI,MAAM,WAAW,EAAG;AAExB,QAAM,aAAa,OAAO,QAAiC;AAC1D,QAAI,6BAA6B,cAAc;AAC9C,iBAAW,QAAQ,OAAO;AAEzB,cAAM,OAAO,GAAG;AAAA,MACjB;AAEA;AAAA,IACD;AAEA,QAAI,6BAA6B,YAAY;AAC5C,YAAM,YAAY,CAAC,GAAG,KAAK;AAE3B,YAAM,QAAQ,IAAI,UAAU,IAAI,CAAC,eAAe,aAAa,GAAG,CAAC,CAAC;AA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"]}
@@ -1,9 +1,9 @@
1
- import { R as ResultModeUnion, a as ResponseTypeUnion, C as CallApiPlugin, D as DefaultPluginArray, b as CallApiSchemas, I as InferSchemaResult, c as CallApiConfig, d as CallApiResult, e as DefaultDataType, f as DefaultThrowOnError, g as DefaultMoreOptions, B as BaseCallApiConfig, h as CallApiParameters } from './error-By05WYGj.cjs';
2
- export { l as BaseCallApiExtraOptions, m as CallApiExtraOptions, p as CallApiRequestOptions, q as CallApiRequestOptionsForHooks, r as CallApiResultErrorVariant, s as CallApiResultSuccessVariant, t as CombinedCallApiExtraOptions, E as ErrorContext, H as HTTPError, u as Interceptors, v as InterceptorsOrInterceptorArray, P as PluginInitContext, o as PossibleHTTPError, n as PossibleJavaScriptError, w as PossibleJavascriptErrorNames, x as Register, y as RequestContext, z as RequestErrorContext, A as ResponseContext, F as ResponseErrorContext, k as RetryOptions, S as SuccessContext, i as definePlugin, j as getDefaultOptions } from './error-By05WYGj.cjs';
1
+ import { R as ResultModeUnion, a as ResponseTypeUnion, C as CallApiPlugin, D as DefaultPluginArray, b as CallApiSchemas, I as InferSchemaResult, c as CallApiConfig, d as CallApiResult, e as DefaultDataType, f as DefaultThrowOnError, g as DefaultMoreOptions, B as BaseCallApiConfig, h as CallApiParameters } from './common-BUhBcx_C.cjs';
2
+ export { y as BaseCallApiExtraOptions, z as CallApiExtraOptions, A as CallApiRequestOptions, F as CallApiRequestOptionsForHooks, G as CallApiResultErrorVariant, J as CallApiResultSuccessVariant, K as CombinedCallApiExtraOptions, E as ErrorContext, H as HTTPError, p as Hooks, q as HooksOrHooksArray, j as PluginHooks, k as PluginHooksWithMoreOptions, P as PluginInitContext, n as PossibleHTTPError, o as PossibleJavaScriptError, L as Register, r as RequestContext, s as RequestErrorContext, t as RequestStreamContext, u as ResponseContext, v as ResponseErrorContext, w as ResponseStreamContext, m as RetryOptions, S as SharedHookContext, x as SuccessContext, i as definePlugin, l as getDefaultOptions } from './common-BUhBcx_C.cjs';
3
3
 
4
- declare const createFetchClient: <TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBaseThrowOnError extends boolean = DefaultThrowOnError, TBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray, TBaseSchemas extends CallApiSchemas = DefaultMoreOptions>(baseConfig?: BaseCallApiConfig<TBaseData, TBaseErrorData, TBaseResultMode, TBaseThrowOnError, TBaseResponseType, TBasePluginArray, TBaseSchemas>) => <TData = InferSchemaResult<TBaseSchemas["data"], TBaseData>, TErrorData = InferSchemaResult<TBaseSchemas["errorData"], TBaseErrorData>, TResultMode extends ResultModeUnion = TBaseResultMode, TThrowOnError extends boolean = TBaseThrowOnError, TResponseType extends ResponseTypeUnion = TBaseResponseType, TPluginArray extends CallApiPlugin[] = TBasePluginArray, TSchemas extends CallApiSchemas = TBaseSchemas>(initURL: InferSchemaResult<TSchemas["initURL"], string | URL>, config?: CallApiConfig<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TPluginArray, TSchemas> | undefined) => CallApiResult<InferSchemaResult<TSchemas["data"], TData>, InferSchemaResult<TSchemas["errorData"], TErrorData>, TResultMode, TThrowOnError, TResponseType>;
4
+ declare const createFetchClient: <TBaseData = DefaultDataType, TBaseErrorData = DefaultDataType, TBaseResultMode extends ResultModeUnion = ResultModeUnion, TBaseThrowOnError extends boolean = DefaultThrowOnError, TBaseResponseType extends ResponseTypeUnion = ResponseTypeUnion, TBasePluginArray extends CallApiPlugin[] = DefaultPluginArray, TBaseSchemas extends CallApiSchemas = DefaultMoreOptions>(initBaseConfig?: BaseCallApiConfig<TBaseData, TBaseErrorData, TBaseResultMode, TBaseThrowOnError, TBaseResponseType, TBasePluginArray, TBaseSchemas>) => <TData = InferSchemaResult<TBaseSchemas["data"], TBaseData>, TErrorData = InferSchemaResult<TBaseSchemas["errorData"], TBaseErrorData>, TResultMode extends ResultModeUnion = TBaseResultMode, TThrowOnError extends boolean = TBaseThrowOnError, TResponseType extends ResponseTypeUnion = TBaseResponseType, TPluginArray extends CallApiPlugin[] = TBasePluginArray, TSchemas extends CallApiSchemas = TBaseSchemas>(initURL: InferSchemaResult<TSchemas["initURL"], string | URL>, config?: CallApiConfig<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TPluginArray, TSchemas> | undefined) => CallApiResult<InferSchemaResult<TSchemas["data"], TData>, InferSchemaResult<TSchemas["errorData"], TErrorData>, TResultMode, TThrowOnError, TResponseType>;
5
5
  declare const callApi: <TData = unknown, TErrorData = unknown, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends boolean = boolean, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TPluginArray extends CallApiPlugin[] = DefaultPluginArray, TSchemas extends CallApiSchemas = {}>(initURL: InferSchemaResult<TSchemas["initURL"], string | URL>, config?: CallApiConfig<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TPluginArray, TSchemas> | undefined) => CallApiResult<InferSchemaResult<TSchemas["data"], TData>, InferSchemaResult<TSchemas["errorData"], TErrorData>, TResultMode, TThrowOnError, TResponseType>;
6
6
 
7
7
  declare const defineParameters: <TData = unknown, TErrorData = unknown, TResultMode extends ResultModeUnion = ResultModeUnion, TThrowOnError extends boolean = DefaultThrowOnError, TResponseType extends ResponseTypeUnion = ResponseTypeUnion, TPluginArray extends CallApiPlugin[] = DefaultPluginArray, TSchemas extends CallApiSchemas = DefaultMoreOptions>(...parameters: CallApiParameters<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TPluginArray, TSchemas>) => CallApiParameters<TData, TErrorData, TResultMode, TThrowOnError, TResponseType, TPluginArray, TSchemas>;
8
8
 
9
- export { CallApiParameters, CallApiPlugin, CallApiSchemas, InferSchemaResult, ResultModeUnion, callApi, createFetchClient, defineParameters };
9
+ export { CallApiParameters, CallApiPlugin, CallApiSchemas, InferSchemaResult, ResponseTypeUnion, ResultModeUnion, callApi, createFetchClient, defineParameters };
@@ -27,14 +27,17 @@ __export(utils_exports, {
27
27
  module.exports = __toCommonJS(utils_exports);
28
28
 
29
29
  // src/error.ts
30
- var HTTPError = class extends Error {
30
+ var HTTPError = class {
31
+ cause;
31
32
  errorData;
32
33
  isHTTPError = true;
34
+ message;
33
35
  name = "HTTPError";
34
36
  response;
35
37
  constructor(errorDetails, errorOptions) {
36
38
  const { defaultErrorMessage, errorData, response } = errorDetails;
37
- super(errorData?.message ?? defaultErrorMessage, errorOptions);
39
+ this.message = errorData?.message ?? defaultErrorMessage;
40
+ errorOptions?.cause && (this.cause = errorOptions.cause);
38
41
  this.errorData = errorData;
39
42
  this.response = response;
40
43
  Error.captureStackTrace(this, this.constructor);