UNPKG

@zayne-labs/callapi

Version:

A lightweight wrapper over fetch with quality of life improvements like built-in request cancellation, retries, interceptors and more

690 lines (675 loc) 25.1 kB
//#region src/types/type-helpers.ts const defineEnum = (value) => Object.freeze(value); //#endregion //#region src/utils/guards.ts const isArray = (value) => Array.isArray(value); const isBoolean = (value) => typeof value === "boolean"; const isBlob = (value) => value instanceof Blob; const isObject = (value) => { return typeof value === "object" && value !== null; }; const hasObjectPrototype = (value) => { return Object.prototype.toString.call(value) === "[object Object]"; }; /** * @description Copied from TanStack Query's isPlainObject * @see https://github.com/TanStack/query/blob/main/packages/query-core/src/utils.ts#L321 */ const isPlainObject = (value) => { if (!hasObjectPrototype(value)) return false; const constructor = value?.constructor; if (constructor === void 0) return true; const prototype = constructor.prototype; if (!hasObjectPrototype(prototype)) return false; if (!Object.hasOwn(prototype, "isPrototypeOf")) return false; if (Object.getPrototypeOf(value) !== Object.prototype) return false; return true; }; const isValidJsonString = (value) => { if (!isString(value)) return false; try { JSON.parse(value); return true; } catch { return false; } }; const isSerializableObject = (value) => { return isPlainObject(value) || isArray(value) || typeof value?.toJSON === "function"; }; const isFunction = (value) => typeof value === "function"; const isQueryString = (value) => isString(value) && value.includes("="); const isString = (value) => typeof value === "string"; const isPromise = (value) => value instanceof Promise; const isReadableStream = (value) => { return value instanceof ReadableStream; }; //#endregion //#region src/auth.ts const resolveAuthValue = (value) => isFunction(value) ? value() : value; const getAuthHeader = async (auth) => { if (auth === void 0) return; if (isPromise(auth) || isFunction(auth) || !isObject(auth)) { const authValue = await resolveAuthValue(auth); if (authValue === void 0) return; return { Authorization: `Bearer ${authValue}` }; } switch (auth.type) { case "Basic": { const [username, password] = await Promise.all([resolveAuthValue(auth.username), resolveAuthValue(auth.password)]); if (username === void 0 || password === void 0) return; return { Authorization: `Basic ${globalThis.btoa(`${username}:${password}`)}` }; } case "Bearer": { const value = await resolveAuthValue(auth.value); if (value === void 0) return; return { Authorization: `Bearer ${value}` }; } case "Custom": { const [prefix, value] = await Promise.all([resolveAuthValue(auth.prefix), resolveAuthValue(auth.value)]); if (value === void 0) return; return { Authorization: `${prefix} ${value}` }; } case "Token": { const value = await resolveAuthValue(auth.value); if (value === void 0) return; return { Authorization: `Token ${value}` }; } default: return; } }; //#endregion //#region src/constants/common.ts const fetchSpecificKeys = defineEnum([ "body", "integrity", "duplex", "method", "headers", "signal", "cache", "redirect", "window", "credentials", "keepalive", "referrer", "priority", "mode", "referrerPolicy" ]); //#endregion //#region src/utils/external/body.ts const toStringOrStringify = (value) => { return isString(value) ? value : JSON.stringify(value); }; const toQueryString = (data) => { const queryString = new URLSearchParams(); for (const [key, value] of Object.entries(data)) { if (value == null) continue; if (isArray(value)) { for (const innerValue of value) queryString.append(key, toStringOrStringify(innerValue)); continue; } queryString.set(key, toStringOrStringify(value)); } return queryString.toString(); }; const toBlobOrString = (value) => { return isBlob(value) ? value : String(value); }; /** * @description Converts a plain object to FormData. * * Handles various data types: * - **Primitives** (string, number, boolean): Converted to strings * - **Blobs/Files**: Added directly to FormData * - **Arrays**: Each item is appended (allows multiple values for same key) * - **Objects**: JSON stringified before adding to FormData * * @example * ```ts * // Basic usage * const formData = toFormData({ * name: "John", * age: 30, * active: true * }); * * // With arrays * const formData = toFormData({ * tags: ["javascript", "typescript"], * name: "John" * }); * * // With files * const formData = toFormData({ * avatar: fileBlob, * name: "John" * }); * * // With nested objects (one level only) * const formData = toFormData({ * user: { name: "John", age: 30 }, * settings: { theme: "dark" } * }); */ const toFormData = (data) => { const formData = new FormData(); for (const [key, value] of Object.entries(data)) { if (isArray(value)) { for (const innerValue of value) formData.append(key, toBlobOrString(innerValue)); continue; } if (isObject(value) && !isBlob(value)) { formData.set(key, JSON.stringify(value)); continue; } formData.set(key, toBlobOrString(value)); } return formData; }; //#endregion //#region src/constants/validation.ts const fallBackRouteSchemaKey = "@default"; //#endregion //#region src/utils/external/error.ts const httpErrorSymbol = Symbol("HTTPError"); var HTTPError = class HTTPError extends Error { errorData; httpErrorSymbol = httpErrorSymbol; name = "HTTPError"; response; constructor(errorDetails, errorOptions) { const { defaultHTTPErrorMessage, errorData, response } = errorDetails; const selectedDefaultErrorMessage = (isString(defaultHTTPErrorMessage) ? defaultHTTPErrorMessage : defaultHTTPErrorMessage?.({ errorData, response })) ?? (response.statusText || extraOptionDefaults.defaultHTTPErrorMessage); const message = errorData?.message ?? selectedDefaultErrorMessage; super(message, errorOptions); this.errorData = errorData; this.response = response; } /** * @description Checks if the given error is an instance of HTTPError * @param error - The error to check * @returns true if the error is an instance of HTTPError, false otherwise */ static isError(error) { if (!isObject(error)) return false; if (error instanceof HTTPError) return true; const actualError = error; return actualError.httpErrorSymbol === httpErrorSymbol && actualError.name === "HTTPError"; } }; const prettifyPath = (path) => { if (!path || path.length === 0) return ""; return ` → at ${path.map((segment) => isObject(segment) ? segment.key : segment).join(".")}`; }; const prettifyValidationIssues = (issues) => { return issues.map((issue) => `✖ ${issue.message}${prettifyPath(issue.path)}`).join(" | "); }; const validationErrorSymbol = Symbol("ValidationErrorSymbol"); var ValidationError = class ValidationError extends Error { errorData; issueCause; name = "ValidationError"; response; validationErrorSymbol = validationErrorSymbol; constructor(details, errorOptions) { const { issueCause, issues, response } = details; const prettyMessage = prettifyValidationIssues(issues); const message = `(${issueCause.toUpperCase()}) - ${prettyMessage}`; super(message, errorOptions); this.errorData = issues; this.response = response; this.issueCause = issueCause; } /** * @description Checks if the given error is an instance of ValidationError * @param error - The error to check * @returns true if the error is an instance of ValidationError, false otherwise */ static isError(error) { if (!isObject(error)) return false; if (error instanceof ValidationError) return true; const actualError = error; return actualError.validationErrorSymbol === validationErrorSymbol && actualError.name === "ValidationError"; } }; //#endregion //#region src/validation.ts const handleValidatorFunction = async (validator, inputData) => { try { return { issues: void 0, value: await validator(inputData) }; } catch (error) { return { issues: toArray(error), value: void 0 }; } }; const standardSchemaParser = async (fullSchema, schemaName, options) => { const { inputValue, response } = options; const schema = fullSchema?.[schemaName]; if (!schema) return inputValue; const result = isFunction(schema) ? await handleValidatorFunction(schema, inputValue) : await schema["~standard"].validate(inputValue); if (result.issues) throw new ValidationError({ issueCause: schemaName, issues: result.issues, response: response ?? null }); return result.value; }; const routeKeyMethods = defineEnum([ "delete", "get", "patch", "post", "put" ]); const handleSchemaValidation = async (fullSchema, schemaName, validationOptions) => { const { inputValue, response, schemaConfig } = validationOptions; const disableRuntimeValidationBooleanObject = isObject(schemaConfig?.disableRuntimeValidation) ? schemaConfig.disableRuntimeValidation : {}; if (schemaConfig?.disableRuntimeValidation === true || disableRuntimeValidationBooleanObject[schemaName] === true) return inputValue; const validResult = await standardSchemaParser(fullSchema, schemaName, { inputValue, response }); const disableResultApplicationBooleanObject = isObject(schemaConfig?.disableRuntimeValidationTransform) ? schemaConfig.disableRuntimeValidationTransform : {}; if (schemaConfig?.disableRuntimeValidationTransform === true || disableResultApplicationBooleanObject[schemaName] === true) return inputValue; return validResult; }; const extraOptionsToBeValidated = [ "meta", "params", "query", "auth" ]; const requestOptionsToBeValidated = [ "body", "headers", "method" ]; const handleOptionsValidation = async (validationOptions) => { const { options, request, schema, schemaConfig } = validationOptions; const resolvedOptionsToBeValidated = options ? extraOptionsToBeValidated : requestOptionsToBeValidated; const resolvedOptions = options ?? request; const validationResultArray = await Promise.all(resolvedOptionsToBeValidated.map((schemaName) => handleSchemaValidation(schema, schemaName, { inputValue: resolvedOptions[schemaName], schemaConfig }))); const validatedResultObject = {}; for (const [index, schemaName] of resolvedOptionsToBeValidated.entries()) { const validationResult = validationResultArray[index]; if (validationResult === void 0) continue; validatedResultObject[schemaName] = validationResult; } return validatedResultObject; }; const handleConfigValidation = async (validationOptions) => { const { baseExtraOptions, currentRouteSchemaKey, extraOptions, options, request } = validationOptions; const { currentRouteSchema, resolvedSchema } = getResolvedSchema({ baseExtraOptions, currentRouteSchemaKey, extraOptions }); const resolvedSchemaConfig = getResolvedSchemaConfig({ baseExtraOptions, extraOptions }); if (resolvedSchemaConfig?.strict === true && !currentRouteSchema) throw new ValidationError({ issueCause: "schemaConfig-(strict)", issues: [{ message: `Strict Mode - No schema found for route '${currentRouteSchemaKey}' ` }], response: null }); const [extraOptionsValidationResult, requestOptionsValidationResult] = await Promise.all([handleOptionsValidation({ options, schema: resolvedSchema, schemaConfig: resolvedSchemaConfig }), handleOptionsValidation({ request, schema: resolvedSchema, schemaConfig: resolvedSchemaConfig })]); return { extraOptionsValidationResult, requestOptionsValidationResult, resolvedSchema, resolvedSchemaConfig }; }; const getResolvedSchema = (context) => { const { baseExtraOptions, currentRouteSchemaKey, extraOptions } = context; const fallbackRouteSchema = baseExtraOptions.schema?.routes[fallBackRouteSchemaKey]; const currentRouteSchema = baseExtraOptions.schema?.routes[currentRouteSchemaKey]; const resolvedRouteSchema = { ...fallbackRouteSchema, ...currentRouteSchema }; return { currentRouteSchema, resolvedSchema: isFunction(extraOptions.schema) ? extraOptions.schema({ baseSchemaRoutes: baseExtraOptions.schema?.routes ?? {}, currentRouteSchema: resolvedRouteSchema ?? {}, currentRouteSchemaKey }) : extraOptions.schema ?? resolvedRouteSchema }; }; const getResolvedSchemaConfig = (context) => { const { baseExtraOptions, extraOptions } = context; return isFunction(extraOptions.schemaConfig) ? extraOptions.schemaConfig({ baseSchemaConfig: baseExtraOptions.schema?.config ?? {} }) : extraOptions.schemaConfig ?? baseExtraOptions.schema?.config; }; const removeLeadingSlash = (value) => value.startsWith("/") ? value.slice(1) : value; const extractURLParts = (initURL) => { return { methodFromURL: extractMethodFromURL(initURL), pathWithoutMethod: normalizeURL(initURL, { retainLeadingSlashForRelativeURLs: false }) }; }; const mergeURLParts = (options) => { const { method, path } = options; return method ? `${atSymbol}${method}/${removeLeadingSlash(path)}` : path; }; const getCurrentRouteSchemaKeyAndMainInitURL = (context) => { const { baseExtraOptions, extraOptions, initURL } = context; const schemaConfig = getResolvedSchemaConfig({ baseExtraOptions, extraOptions }); let currentRouteSchemaKey = initURL; let mainInitURL = initURL; const { methodFromURL, pathWithoutMethod } = extractURLParts(initURL); const prefixWithoutLeadingSlash = schemaConfig?.prefix && removeLeadingSlash(schemaConfig.prefix); if (prefixWithoutLeadingSlash && pathWithoutMethod.startsWith(prefixWithoutLeadingSlash)) { currentRouteSchemaKey = mergeURLParts({ method: methodFromURL, path: pathWithoutMethod.slice(prefixWithoutLeadingSlash.length) }); mainInitURL = mergeURLParts({ method: methodFromURL, path: pathWithoutMethod.replace(prefixWithoutLeadingSlash, schemaConfig.baseURL ?? "") }); } if (schemaConfig?.baseURL && pathWithoutMethod.startsWith(schemaConfig.baseURL)) currentRouteSchemaKey = mergeURLParts({ method: methodFromURL, path: pathWithoutMethod.slice(schemaConfig.baseURL.length) }); return { currentRouteSchemaKey, mainInitURL }; }; //#endregion //#region src/url.ts const slash = "/"; const colon = ":"; const openBrace = "{"; const closeBrace = "}"; const mergeUrlWithParams = (url, params) => { if (!params) return url; let newUrl = url; if (isArray(params)) { const matchedParamsArray = newUrl.split(slash).filter((part) => part.startsWith(colon) || part.startsWith(openBrace) && part.endsWith(closeBrace)); for (const [paramIndex, matchedParam] of matchedParamsArray.entries()) { const stringParamValue = String(params[paramIndex]); newUrl = newUrl.replace(matchedParam, stringParamValue); } return newUrl; } for (const [paramKey, paramValue] of Object.entries(params)) { const colonPattern = `${colon}${paramKey}`; const bracePattern = `${openBrace}${paramKey}${closeBrace}`; const stringValue = String(paramValue); newUrl = newUrl.replace(colonPattern, stringValue); newUrl = newUrl.replace(bracePattern, stringValue); } return newUrl; }; const questionMark = "?"; const ampersand = "&"; const mergeUrlWithQuery = (url, query) => { if (!query) return url; const queryString = toQueryString(query); if (queryString.length === 0) return url; if (url.endsWith(questionMark)) return `${url}${queryString}`; if (url.includes(questionMark)) return `${url}${ampersand}${queryString}`; return `${url}${questionMark}${queryString}`; }; /** * @description Extracts the HTTP method from method-prefixed route patterns. * * Analyzes URLs that start with method modifiers (e.g., "@get/", "@post/") and extracts * the HTTP method for use in API requests. This enables method specification directly * in route definitions. * * @param initURL - The URL string to analyze for method modifiers * @returns The extracted HTTP method (lowercase) if found, otherwise undefined * * @example * ```typescript * extractMethodFromURL("@get/users"); // Returns: "get" * extractMethodFromURL("@post/users"); // Returns: "post" * ``` */ const extractMethodFromURL = (initURL) => { if (!initURL?.startsWith("@")) return; const methodFromURL = routeKeyMethods.find((method) => initURL.startsWith(`${atSymbol}${method}${slash}`)); if (!methodFromURL) return; return methodFromURL; }; const atSymbol = "@"; const normalizeURL = (initURL, options = {}) => { const { retainLeadingSlashForRelativeURLs = true } = options; const methodFromURL = extractMethodFromURL(initURL); if (!methodFromURL) return initURL; return retainLeadingSlashForRelativeURLs && !initURL.includes("http") ? initURL.replace(`${atSymbol}${methodFromURL}`, "") : initURL.replace(`${atSymbol}${methodFromURL}${slash}`, ""); }; const getFullURL = (initURL, baseURL) => { if (!baseURL || initURL.startsWith("http")) return initURL; return initURL.length > 0 && !initURL.startsWith(slash) && !baseURL.endsWith(slash) ? `${baseURL}${slash}${initURL}` : `${baseURL}${initURL}`; }; const getFullAndNormalizedURL = (options) => { const { baseURL, initURL, params, query } = options; const normalizedInitURL = normalizeURL(initURL); const fullURL = getFullURL(mergeUrlWithQuery(mergeUrlWithParams(normalizedInitURL, params), query), baseURL); if (!URL.canParse(fullURL)) { const errorMessage = !baseURL ? `Invalid URL '${initURL}'. Are you passing a relative url to CallApi without setting the 'baseURL' option?` : `Invalid URL '${fullURL}'. Please validate that you are passing the correct url.`; console.error(errorMessage); } return { fullURL, normalizedInitURL }; }; //#endregion //#region src/utils/external/define.ts const defineSchema = (routes, config) => { return { config: defineSchemaConfig(config), routes: defineSchemaRoutes(routes) }; }; const defineSchemaRoutes = (routes) => { return routes; }; const defineMainSchema = (mainSchema) => { return mainSchema; }; const defineSchemaConfig = (config) => { return config; }; const definePlugin = (plugin) => { return plugin; }; const defineBaseConfig = (baseConfig) => { return baseConfig; }; //#endregion //#region src/utils/external/guards.ts const isHTTPError = (error) => { return isObject(error) && error.name === "HTTPError"; }; const isHTTPErrorInstance = (error) => { return HTTPError.isError(error); }; const isValidationError = (error) => { return isObject(error) && error.name === "ValidationError"; }; const isValidationErrorInstance = (error) => { return ValidationError.isError(error); }; const isJavascriptError = (error) => { return isObject(error) && !isHTTPError(error) && !isValidationError(error); }; //#endregion //#region src/utils/polyfills/combinedSignal.ts const createCombinedSignalPolyfill = (signals) => { const controller = new AbortController(); const handleAbort = (actualSignal) => { if (controller.signal.aborted) return; controller.abort(actualSignal.reason); }; for (const actualSignal of signals) { if (actualSignal.aborted) { handleAbort(actualSignal); break; } actualSignal.addEventListener("abort", () => handleAbort(actualSignal), { signal: controller.signal }); } return controller.signal; }; //#endregion //#region src/utils/polyfills/timeoutSignal.ts const createTimeoutSignalPolyfill = (milliseconds) => { const controller = new AbortController(); const reason = new DOMException("Request timed out", "TimeoutError"); const timeout = setTimeout(() => controller.abort(reason), milliseconds); controller.signal.addEventListener("abort", () => clearTimeout(timeout)); return controller.signal; }; //#endregion //#region src/utils/common.ts const omitKeys = (initialObject, keysToOmit) => { const updatedObject = {}; const keysToOmitSet = new Set(keysToOmit); for (const [key, value] of Object.entries(initialObject)) if (!keysToOmitSet.has(key)) updatedObject[key] = value; return updatedObject; }; const pickKeys = (initialObject, keysToPick) => { const updatedObject = {}; const keysToPickSet = new Set(keysToPick); for (const [key, value] of Object.entries(initialObject)) if (keysToPickSet.has(key)) updatedObject[key] = value; return updatedObject; }; const splitBaseConfig = (baseConfig) => [pickKeys(baseConfig, fetchSpecificKeys), omitKeys(baseConfig, fetchSpecificKeys)]; const splitConfig = (config) => [pickKeys(config, fetchSpecificKeys), omitKeys(config, fetchSpecificKeys)]; const objectifyHeaders = (headers) => { if (!headers) return {}; if (isPlainObject(headers)) return headers; return Object.fromEntries(headers); }; const getResolvedHeaders = (options) => { const { baseHeaders, headers } = options; return objectifyHeaders(isFunction(headers) ? headers({ baseHeaders: objectifyHeaders(baseHeaders) }) : headers ?? baseHeaders); }; const detectContentTypeHeader = (body) => { if (isQueryString(body)) return { "Content-Type": "application/x-www-form-urlencoded" }; if (isSerializableObject(body) || isValidJsonString(body)) return { Accept: "application/json", "Content-Type": "application/json" }; return null; }; const getHeaders = async (options) => { const { auth, body, resolvedHeaders } = options; const authHeaderObject = await getAuthHeader(auth); const resolvedHeadersObject = objectifyHeaders(resolvedHeaders); if (!(Object.hasOwn(resolvedHeadersObject, "Content-Type") || Object.hasOwn(resolvedHeadersObject, "content-type"))) { const contentTypeHeader = detectContentTypeHeader(body); contentTypeHeader && Object.assign(resolvedHeadersObject, contentTypeHeader); } return { ...authHeaderObject, ...resolvedHeadersObject }; }; const getMethod = (ctx) => { const { initURL, method } = ctx; return method?.toUpperCase() ?? extractMethodFromURL(initURL)?.toUpperCase() ?? requestOptionDefaults.method; }; const getBody = (options) => { const { body, bodySerializer, resolvedHeaders } = options; const existingContentType = new Headers(resolvedHeaders).get("content-type"); if (!existingContentType && isSerializableObject(body)) return (bodySerializer ?? extraOptionDefaults.bodySerializer)(body); if (existingContentType === "application/x-www-form-urlencoded" && isSerializableObject(body)) return toQueryString(body); return body; }; const getInitFetchImpl = (customFetchImpl) => { if (customFetchImpl) return customFetchImpl; if (typeof globalThis !== "undefined" && isFunction(globalThis.fetch)) return globalThis.fetch; throw new Error("No fetch implementation found"); }; const getFetchImpl = (context) => { const { customFetchImpl, fetchMiddleware, requestContext } = context; const initFetchImpl = getInitFetchImpl(customFetchImpl); return fetchMiddleware ? fetchMiddleware({ ...requestContext, fetchImpl: initFetchImpl }) : initFetchImpl; }; const waitFor = (delay) => { if (delay === 0) return; return new Promise((resolve) => setTimeout(resolve, delay)); }; const createCombinedSignal = (...signals) => { const cleanedSignals = signals.filter((signal) => signal != null); if (!("any" in AbortSignal)) return createCombinedSignalPolyfill(cleanedSignals); return AbortSignal.any(cleanedSignals); }; const createTimeoutSignal = (milliseconds) => { if (milliseconds == null) return null; if (!("timeout" in AbortSignal)) return createTimeoutSignalPolyfill(milliseconds); return AbortSignal.timeout(milliseconds); }; const deterministicHashFn = (value) => { return JSON.stringify(value, (_, val) => { if (!isPlainObject(val)) return val; const sortedKeys = Object.keys(val).toSorted(); const result = {}; for (const key of sortedKeys) result[key] = val[key]; return result; }); }; const toArray = (value) => isArray(value) ? value : [value]; //#endregion //#region src/constants/defaults.ts const extraOptionDefaults = Object.freeze(defineEnum({ bodySerializer: JSON.stringify, defaultHTTPErrorMessage: "Request failed unexpectedly", dedupeCacheScope: "local", dedupeKey: (ctx) => `${ctx.options.fullURL}-${deterministicHashFn({ options: ctx.options, request: ctx.request })}`, dedupeCacheScopeKey: "default", dedupeStrategy: "cancel", hooksExecutionMode: "parallel", responseParser: JSON.parse, responseType: "json", resultMode: "all", retryAttempts: 0, retryCondition: () => true, retryDelay: 1e3, retryMaxDelay: 1e4, retryMethods: ["GET", "POST"], retryStatusCodes: [], retryStrategy: "linear" })); const requestOptionDefaults = defineEnum({ method: "GET" }); //#endregion export { ValidationError as A, defineSchemaConfig as C, handleConfigValidation as D, getCurrentRouteSchemaKeyAndMainInitURL as E, isArray as F, isBoolean as I, isFunction as L, toFormData as M, toQueryString as N, handleSchemaValidation as O, fetchSpecificKeys as P, isReadableStream as R, defineSchema as S, getFullAndNormalizedURL as T, isValidationError as _, getBody as a, defineMainSchema as b, getMethod as c, splitBaseConfig as d, splitConfig as f, isJavascriptError as g, isHTTPErrorInstance as h, createTimeoutSignal as i, fallBackRouteSchemaKey as j, HTTPError as k, getResolvedHeaders as l, isHTTPError as m, requestOptionDefaults as n, getFetchImpl as o, waitFor as p, createCombinedSignal as r, getHeaders as s, extraOptionDefaults as t, omitKeys as u, isValidationErrorInstance as v, defineSchemaRoutes as w, definePlugin as x, defineBaseConfig as y, isString as z }; //# sourceMappingURL=defaults-CjVryN9a.js.map