1000fetches 0.1.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs.js +1 -1
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.d.ts +178 -224
- package/dist/index.es.js +45 -107
- package/dist/index.es.js.map +1 -1
- package/package.json +17 -7
package/dist/index.cjs.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});class t extends Error{name="HttpError";status;statusText;data;response;url;method;cause;constructor(t,e,r,s,a,o,n,i){super(`HTTP ${e} ${r}: ${t} (${n} ${o})`,{cause:i}),this.status=e,this.statusText=r,this.data=s,this.response=a,this.url=o,this.method=n}}class e extends Error{name="NetworkError";cause;constructor(t,e){super(t,{cause:e})}}class r extends Error{name="SchemaValidationError";schema;data;cause;constructor(t,e,r,s){super(t,{cause:s}),this.schema=e,this.data=r}}class s extends Error{name="TimeoutError";cause;constructor(t,e){super(t,{cause:e})}}class a extends Error{name="PathParameterError";url;requiredParams;providedParams;cause;constructor(t,e,r,s,a){super(t,{cause:a}),this.url=e,this.requiredParams=r,this.providedParams=s}}class o extends Error{name="InterceptorError";interceptorType;url;method;cause;constructor(t,e,r,s,a){super(t,{cause:a}),this.interceptorType=e,this.url=r,this.method=s}}class n extends Error{name="SerializationError";cause;constructor(t,e){super(t,{cause:e})}}function i(t){return null!==t&&("object"==typeof t||"function"==typeof t)&&"~standard"in t&&"object"==typeof t["~standard"]&&null!==t["~standard"]&&"validate"in t["~standard"]&&"function"==typeof t["~standard"].validate&&"version"in t["~standard"]&&"number"==typeof t["~standard"].version&&"vendor"in t["~standard"]&&"string"==typeof t["~standard"].vendor}function c(){return{validate(t,e){if(!i(t))throw new Error("Invalid schema: Schema must implement the Standard Schema interface");const r=function(t){return{parse:e=>{const r=t["~standard"].validate(e);if(r instanceof Promise)throw new Error("Async Standard Schema validation is not supported");if("issues"in r&&r.issues){const t=Array.from(r.issues).map(t=>t.message).join("; ");throw new Error(`Standard Schema validation failed: ${t}`)}return r.value}}}(t);return r.parse(e)},isSchema:t=>i(t)}}const u={maxRetries:3,retryDelay:300,backoffFactor:2,retryStatusCodes:[429,500,502,503,504],retryNetworkErrors:!0,maxRetryDelay:3e4,shouldRetry:()=>!0};exports.HttpClient=class{baseUrl;defaultHeaders;defaultTimeout;schemaValidator;requestInterceptors;responseInterceptors;defaultRetryOptions;constructor(t={}){this.baseUrl=function(t){const e="undefined"!=typeof window&&void 0!==window.location&&"null"!==window.location.origin;if(!t)return e?window.location.origin:"";if(t.startsWith("/"))return e?new URL(t,window.location.origin).href.replace(/\/$/,""):t.replace(/\/$/,"");try{new URL(t)}catch{throw new Error(`Invalid baseUrl: "${t}". Must be a valid absolute URL or relative path starting with "/".`)}return t.endsWith("/")?t.slice(0,-1):t}(t.baseUrl),this.defaultHeaders=t.headers||{},this.defaultTimeout=t.timeout||3e4,this.schemaValidator=t.schemaValidator||{validate(t,e){if(!i(t))throw new Error("Invalid schema: Schema must implement the Standard Schema interface");return c().validate(t,e)},isSchema:t=>i(t)},this.requestInterceptors=t.requestInterceptors||[],this.responseInterceptors=t.responseInterceptors||[],this.defaultRetryOptions=t.retryOptions}addRequestInterceptor(t){this.requestInterceptors.push(t)}addResponseInterceptor(t){this.responseInterceptors.push(t)}async shouldRetry(a,o,n){if(!1===n)return!1;const i=this.getRetryOptions(n);if(o>=i.maxRetries)return!1;if("function"==typeof i.shouldRetry)try{return await i.shouldRetry(a,o)}catch(c){console.warn("Custom shouldRetry function failed:",c)}return!!(a instanceof e&&i.retryNetworkErrors)||(!!(a instanceof t&&i.retryStatusCodes.includes(a.status))||!(a instanceof r)&&a instanceof s)}getRetryDelay(t,e){const r=e.retryDelay*Math.pow(e.backoffFactor,t),s=Math.min(r,e.maxRetryDelay),a=s+.2*s*(2*Math.random()-1);return Math.max(1,Math.floor(a))}getRetryOptions(t){return!1===t?{...u,maxRetries:0}:!0===t?{...u,...this.defaultRetryOptions}:"object"==typeof t?{...u,...this.defaultRetryOptions,...t}:{...u,...this.defaultRetryOptions}}sleep(t){return new Promise(e=>setTimeout(e,t))}request(t,e,r={}){return function(t){const e=t;return e.data=async()=>(await t).data,e}(this.requestWithRetry(t,e,r))}async requestWithRetry(t,r,s){let a=0;for(;;)try{return await this.executeRequest(t,r,s)}catch(o){if(!(o instanceof Error))throw new e(String(o),void 0);if(await this.shouldRetry(o,a,s.retry)){const t=this.getRetryOptions(s.retry),e=this.getRetryDelay(a,t);await this.sleep(e),a++;continue}throw o}}async executeRequest(i,c,u={}){let d=this.resolveUrl(c,u.pathParams),h={url:d,method:i,params:u.params,headers:this.prepareHeaders(u.headers),body:u.body,fetchOptions:{credentials:u.credentials,cache:u.cache,mode:u.mode,redirect:u.redirect}};for(const t of this.requestInterceptors)try{h=await t(h)}catch(E){throw new o(`Request interceptor failed: ${E instanceof Error?E.message:String(E)}`,"request",d,i,E instanceof Error?E:void 0)}if(d=h.url,h.params&&Object.keys(h.params).length>0){const t=new URLSearchParams;for(const[r,s]of Object.entries(h.params))void 0!==s&&t.append(r,String(s));const e=t.toString();e&&(d+=(d.includes("?")?"&":"?")+e)}const l={method:h.method,headers:h.headers,...h.fetchOptions};if(void 0!==h.body&&("POST"===h.method||"PUT"===h.method||"PATCH"===h.method))if(h.body instanceof FormData||h.body instanceof Blob||h.body instanceof ArrayBuffer||h.body instanceof URLSearchParams||"string"==typeof h.body)l.body=h.body;else try{l.body=JSON.stringify(h.body)}catch(E){throw new n(`Failed to serialize request body: ${E instanceof Error?E.message:"Invalid data structure"}`,E instanceof Error?E:void 0)}const p=u.timeout||this.defaultTimeout,f=new AbortController,m=setTimeout(()=>f.abort(),p),y=h.signal||u.signal;let w;const b=y?(()=>{const t=this.mergeAbortSignals(y,f.signal);return w=t.cleanup,t.signal})():f.signal;try{const t=await fetch(d,{...l,signal:b});let e=await this.processResponse(t,u,i,d);return u.schema&&(e.data=this.validateWithSchema(u.schema,e.data)),e}catch(E){if(E instanceof DOMException&&"AbortError"===E.name||E instanceof Error&&"AbortError"===E.name||E instanceof Error&&E.message.toLowerCase().includes("timeout"))throw new s(`Request timed out after ${p}ms`,E instanceof Error?E:void 0);if(E instanceof t||E instanceof r||E instanceof o||E instanceof a||E instanceof n)throw E;throw new e(E instanceof Error?E.message:String(E),E instanceof Error?E:void 0)}finally{clearTimeout(m),w?.()}}validateWithSchema(t,e,s="Response schema validation failed"){try{return this.schemaValidator.validate(t,e)}catch(a){throw new r(`${s}: ${a instanceof Error?a.message:"Unknown error"}`,t,e,a instanceof Error?a:void 0)}}prepareHeaders(t={}){const e=new Headers;for(const[r,s]of Object.entries(this.defaultHeaders))null!=s&&e.set(r,String(s));for(const[r,s]of Object.entries(t))null!=s&&e.set(r,String(s));return e}extractHeaders(t){const e={};return t.forEach((t,r)=>{e[r]=t}),e}createHttpError(e,r,s,a,o,n){return new t(`Request failed with status code ${e.status}`,e.status,o||e.statusText,r,e,s,a,n)}async parseResponseBody(t,e){const r=t.headers.get("content-type")??"";try{if("text"===e.responseType)return await t.text();if("blob"===e.responseType)return await t.blob();if("arrayBuffer"===e.responseType)return await t.arrayBuffer();if(r.includes("application/json")){const e=await t.text();return e?JSON.parse(e):null}return await t.text()}catch(s){if(204===t.status)return;if(r.includes("application/json")&&s instanceof SyntaxError)throw new Error(`Failed to parse JSON response: ${s.message}`);throw s}}async processResponse(t,e,r,s){const a=this.extractHeaders(t.headers),n=e.validateStatus||(t=>t>=200&&t<300),i=await this.parseResponseBody(t,e);if(!n(t.status))throw this.createHttpError(t,i,s,r);const c={data:i,status:t.status,statusText:t.statusText,headers:a,method:r,url:s,raw:t};let u=c;const d=c.status;for(const l of this.responseInterceptors)try{u=await l(u)}catch(h){throw new o(`Response interceptor failed: ${h instanceof Error?h.message:String(h)}`,"response",s,r,h instanceof Error?h:void 0)}if(u.status!==d&&!n(u.status))throw this.createHttpError(t,u.data,s,r,u.statusText);return u}mergeAbortSignals(t,e){if(t.aborted||e.aborted){const t=new AbortController;return t.abort(),{signal:t.signal}}const r=new AbortController,s=()=>{r.abort(),a()},a=()=>{t.removeEventListener("abort",s),e.removeEventListener("abort",s)};return t.addEventListener("abort",s),e.addEventListener("abort",s),{signal:r.signal,cleanup:a}}get(t,e){return this.request("GET",t,e||{})}post(t,e,r){return this.request("POST",t,{...r||{},body:e})}put(t,e,r){return this.request("PUT",t,{...r||{},body:e})}patch(t,e,r){return this.request("PATCH",t,{...r||{},body:e})}delete(t,e){return this.request("DELETE",t,e||{})}validatePathParams(t,e){if(!e){const e=this.extractRequiredPathParams(t);if(e.length>0)throw new a(`Missing required path parameters for URL "${t}": ${e.join(", ")}. Please provide pathParams: { ${e.map(t=>`${t}: value`).join(", ")} }`,t,e,[]);return}const r=this.extractRequiredPathParams(t),s=Object.keys(e),o=r.filter(t=>!s.includes(t));if(o.length>0)throw new a(`Missing required path parameters: ${o.join(", ")}. Provided: ${s.join(", ")}`,t,r,s)}extractRequiredPathParams(t){if(t.includes("?"))throw new a("Optional path parameters (e.g., :variable?) are not supported",t,[],[]);const e=t.match(/:([a-zA-Z0-9_]+)/g);return e?e.map(t=>t.slice(1)):[]}resolveUrl(t,e){this.validatePathParams(t,e);const r=e?function(t,e={}){return t.replace(/:([a-zA-Z0-9_]+)/g,(r,s)=>{if(void 0===e[s])throw new a(`Missing required path parameter: ${s}`,t,[s],Object.keys(e));return String(e[s])})}(t,e):t;if(/^https?:\/\//i.test(r))return r;const s=r.startsWith("/")?r.slice(1):r;return`${this.baseUrl}/${s}`}},exports.HttpError=t,exports.InterceptorError=o,exports.NetworkError=e,exports.PathParameterError=a,exports.SchemaValidationError=r,exports.SerializationError=n,exports.TimeoutError=s;
|
|
2
2
|
//# sourceMappingURL=index.cjs.js.map
|
package/dist/index.cjs.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs.js","sources":["../src/errors.ts","../src/standard-schema.ts","../src/schema.ts","../src/utils/path.ts","../src/client.ts"],"sourcesContent":["export interface HttpClientError {\n name: string\n message: string\n cause?: Error\n stack?: string\n}\n\nexport class HttpError<TErrorData = unknown>\n extends Error\n implements HttpClientError\n{\n public readonly name = 'HttpError'\n public readonly status: number\n public readonly statusText: string\n public readonly data: TErrorData\n public readonly response: Response\n public readonly url: string\n public readonly method: string\n public override readonly cause?: Error\n\n constructor(\n message: string,\n status: number,\n statusText: string,\n data: TErrorData,\n response: Response,\n url: string,\n method: string,\n cause?: Error\n ) {\n const enhancedMessage = `HTTP ${status} ${statusText}: ${message} (${method} ${url})`\n super(enhancedMessage, { cause })\n this.status = status\n this.statusText = statusText\n this.data = data\n this.response = response\n this.url = url\n this.method = method\n }\n}\n\nexport class NetworkError extends Error implements HttpClientError {\n public readonly name = 'NetworkError'\n public override readonly cause?: Error\n\n constructor(message: string, cause?: Error) {\n super(message, { cause })\n }\n}\n\nexport class SchemaValidationError extends Error implements HttpClientError {\n public readonly name = 'SchemaValidationError'\n public readonly schema: unknown\n public readonly data: unknown\n public override readonly cause?: Error\n\n constructor(message: string, schema: unknown, data: unknown, cause?: Error) {\n super(message, { cause })\n this.schema = schema\n this.data = data\n }\n}\n\nexport class TimeoutError extends Error implements HttpClientError {\n public readonly name = 'TimeoutError'\n public override readonly cause?: Error\n\n constructor(message: string, cause?: Error) {\n super(message, { cause })\n }\n}\n\nexport class PathParameterError extends Error implements HttpClientError {\n public readonly name = 'PathParameterError'\n public readonly url: string\n public readonly requiredParams: string[]\n public readonly providedParams: string[]\n public override readonly cause?: Error\n\n constructor(\n message: string,\n url: string,\n requiredParams: string[],\n providedParams: string[],\n cause?: Error\n ) {\n super(message, { cause })\n this.url = url\n this.requiredParams = requiredParams\n this.providedParams = providedParams\n }\n}\n\nexport class InterceptorError extends Error implements HttpClientError {\n public readonly name = 'InterceptorError'\n public readonly interceptorType: 'request' | 'response'\n public readonly url?: string\n public readonly method?: string\n public override readonly cause?: Error\n\n constructor(\n message: string,\n interceptorType: 'request' | 'response',\n url?: string,\n method?: string,\n cause?: Error\n ) {\n super(message, { cause })\n this.interceptorType = interceptorType\n this.url = url\n this.method = method\n }\n}\n\nexport class SerializationError extends Error implements HttpClientError {\n public readonly name = 'SerializationError'\n public override readonly cause?: Error\n\n constructor(message: string, cause?: Error) {\n super(message, { cause })\n }\n}\n","import { SchemaValidator } from './schema'\n\n/**\n * Standard Schema V1 interface implementation\n *\n * This interface defines the structure for schema validation libraries\n * that conform to the Standard Schema specification.\n *\n * @see https://github.com/standard-schema/standard-schema\n */\nexport interface StandardSchemaV1<Input = unknown, Output = Input> {\n /** The Standard Schema properties containing validation logic and metadata */\n readonly '~standard': StandardSchemaV1.Props<Input, Output>\n}\n\n/**\n * Namespace containing Standard Schema V1 type definitions\n *\n * Provides type-safe interfaces for schema validation results,\n * error handling, and type inference.\n */\nexport namespace StandardSchemaV1 {\n /**\n * Core properties interface for Standard Schema V1\n *\n * Contains the essential metadata and validation function\n * that every Standard Schema implementation must provide.\n */\n export interface Props<Input = unknown, Output = Input> {\n /** The version number of the Standard Schema specification */\n readonly version: 1\n /** The name of the schema validation library (e.g., 'zod', 'valibot') */\n readonly vendor: string\n /**\n * Validates unknown input values against the schema\n *\n * @param value - The value to validate\n * @returns Promise or direct result containing validation outcome\n */\n readonly validate: (\n value: unknown\n ) => Result<Output> | Promise<Result<Output>>\n /** Type information for input and output types */\n readonly types?: Types<Input, Output> | undefined\n }\n\n /**\n * Union type representing the result of schema validation\n *\n * Can be either a successful validation with the validated value,\n * or a failed validation with error details.\n */\n export type Result<Output> = SuccessResult<Output> | FailureResult\n\n /**\n * Interface for successful validation results\n *\n * Contains the validated and typed output value.\n */\n export interface SuccessResult<Output> {\n /** The validated and typed output value */\n readonly value: Output\n /** Undefined since validation succeeded */\n readonly issues?: undefined\n }\n\n /**\n * Interface for failed validation results\n *\n * Contains detailed error information about validation failures.\n */\n export interface FailureResult {\n /** Array of validation error details */\n readonly issues: ReadonlyArray<Issue>\n }\n\n /**\n * Interface for individual validation error details\n *\n * Provides error message and optional path information\n * to help identify where validation failed.\n */\n export interface Issue {\n /** Human-readable error message describing the validation failure */\n readonly message: string\n /**\n * Path to the property that failed validation\n *\n * Useful for nested object validation to pinpoint the exact location\n * of validation failures.\n */\n readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined\n }\n\n /**\n * Interface for path segment information in validation errors\n *\n * Used to provide detailed path information for validation failures\n * in complex nested structures.\n */\n export interface PathSegment {\n /** The property key representing this path segment */\n readonly key: PropertyKey\n }\n\n /**\n * Interface for type information associated with a schema\n *\n * Provides compile-time type information for input and output types\n * to enable better TypeScript integration and IntelliSense support.\n */\n export interface Types<Input = unknown, Output = Input> {\n /** The input type that the schema expects */\n readonly input: Input\n /** The output type that the schema produces after validation */\n readonly output: Output\n }\n\n /**\n * Type utility to infer the input type from a Standard Schema\n *\n * Extracts the input type that a schema expects for validation.\n *\n * @example\n * ```ts\n * type UserInput = StandardSchemaV1.InferInput<typeof userSchema>\n * ```\n */\n export type InferInput<Schema extends StandardSchemaV1> = NonNullable<\n Schema['~standard']['types']\n >['input']\n\n /**\n * Type utility to infer the output type from a Standard Schema\n *\n * Extracts the output type that a schema produces after validation.\n *\n * @example\n * ```ts\n * type UserOutput = StandardSchemaV1.InferOutput<typeof userSchema>\n * ```\n */\n export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<\n Schema['~standard']['types']\n >['output']\n}\n\n/**\n * Type guard to check if an object conforms to the Standard Schema V1 specification\n *\n * Validates that an object has the required structure and properties\n * to be considered a valid Standard Schema implementation.\n *\n * @param obj - The object to check\n * @returns True if the object is a valid Standard Schema V1 implementation\n *\n * @example\n * ```ts\n * if (isStandardSchema(schema)) {\n * // Use the schema with type safety\n * const result = schema['~standard'].validate(data);\n * }\n * ```\n */\nexport function isStandardSchema(obj: unknown): obj is StandardSchemaV1 {\n return (\n obj !== null &&\n (typeof obj === 'object' || typeof obj === 'function') &&\n '~standard' in obj &&\n typeof obj['~standard'] === 'object' &&\n obj['~standard'] !== null &&\n 'validate' in obj['~standard'] &&\n typeof obj['~standard'].validate === 'function' &&\n 'version' in obj['~standard'] &&\n typeof obj['~standard'].version === 'number' &&\n 'vendor' in obj['~standard'] &&\n typeof obj['~standard'].vendor === 'string'\n )\n}\n\n/**\n * Creates an adapter for Standard Schema V1 implementations\n *\n * Converts Standard Schema validation results into a format compatible\n * with the HTTP client's schema validation system.\n *\n * @param schema - The Standard Schema V1 implementation to adapt\n * @returns Adapter object with parse method\n *\n * @example\n * ```ts\n * const zodAdapter = standardSchemaAdapter(zodUserSchema);\n * const validatedUser = zodAdapter.parse(userData);\n * ```\n */\nexport function standardSchemaAdapter<T>(schema: StandardSchemaV1<unknown, T>) {\n return {\n /**\n * Parses and validates data using the Standard Schema\n *\n * @param data - The data to validate\n * @returns The validated and typed data\n * @throws Error if validation fails\n */\n parse: (data: unknown): T => {\n const result = schema['~standard'].validate(data)\n\n if (result instanceof Promise) {\n throw new Error('Async Standard Schema validation is not supported')\n }\n\n if ('issues' in result && result.issues) {\n const errorMessages = Array.from(result.issues)\n .map(issue => issue.message)\n .join('; ')\n throw new Error(`Standard Schema validation failed: ${errorMessages}`)\n }\n\n return result.value as T\n },\n }\n}\n\n/**\n * Creates a schema validator that supports Standard Schema V1 implementations\n *\n * Provides a validator that can work with any schema library that implements\n * the Standard Schema V1 specification, enabling interoperability between\n * different validation libraries.\n *\n * @returns SchemaValidator that supports Standard Schema V1\n *\n * @example\n * ```ts\n * const validator = createStandardSchemaValidator();\n * const client = new HttpClient({ schemaValidator: validator });\n * ```\n */\nexport function createStandardSchemaValidator(): SchemaValidator {\n return {\n /**\n * Validates data against a Standard Schema V1 implementation\n *\n * @param schema - The Standard Schema V1 to validate against\n * @param data - The data to validate\n * @returns The validated and typed data\n * @throws Error if validation fails or schema is invalid\n */\n validate<T>(schema: StandardSchemaV1<unknown, T>, data: unknown): T {\n if (!isStandardSchema(schema)) {\n throw new Error(\n 'Invalid schema: Schema must implement the Standard Schema interface'\n )\n }\n\n const adapter = standardSchemaAdapter<T>(schema)\n return adapter.parse(data)\n },\n\n /**\n * Checks if an object is a valid Standard Schema V1 implementation\n *\n * @param obj - The object to check\n * @returns True if the object is a valid Standard Schema V1\n */\n isSchema(obj: unknown): boolean {\n return isStandardSchema(obj)\n },\n }\n}\n","// Import functions and types needed for Standard Schema support\nimport {\n createStandardSchemaValidator as createStdSchemaValidator,\n isStandardSchema,\n} from './standard-schema'\n\nimport { Schema } from './types'\n\n/**\n * Interface for schema validators that can validate data against schemas.\n *\n * This interface allows you to create custom schema validators that work\n * with different validation libraries (Zod, Valibot, Arktype, etc.).\n */\nexport interface SchemaValidator {\n /**\n * Validate data against a schema.\n *\n * @template T - The expected type after validation\n * @param schema - The schema to validate against\n * @param data - The data to validate\n * @returns The validated data with the correct type\n * @throws {SchemaValidationError} If the data doesn't match the schema\n */\n validate<T>(schema: Schema<T>, data: unknown): T\n\n /**\n * Check if an object is a valid schema.\n *\n * @param obj - The object to check\n * @returns True if the object is a valid schema, false otherwise\n */\n isSchema(obj: unknown): boolean\n}\n\n/**\n * Create a default schema validator that supports Standard Schema.\n *\n * This validator only works with schemas that implement the Standard Schema\n * interface. For full support of Zod, Valibot, and Arktype, use the\n * appropriate validator from their respective packages.\n *\n * @returns A schema validator instance\n *\n * @example\n * ```ts\n * import { createSchemaValidator } from '1000fetches'\n *\n * const validator = createSchemaValidator();\n *\n * // Use with HttpClient\n * const client = new HttpClient({\n * schemaValidator: validator\n * });\n * ```\n */\nexport function createSchemaValidator(): SchemaValidator {\n return {\n validate<T>(schema: Schema<T>, data: unknown): T {\n if (!isStandardSchema(schema)) {\n throw new Error(\n 'Invalid schema: Schema must implement the Standard Schema interface'\n )\n }\n\n return createStdSchemaValidator().validate(schema, data)\n },\n\n isSchema(obj: unknown): boolean {\n return isStandardSchema(obj)\n },\n }\n}\n\nexport { createStdSchemaValidator as createStandardSchemaValidator }\n","import { PathParameterError } from '../errors'\n\ntype ValidateNoOptionalParams<T extends string> =\n T extends `${string}:${string}?${string}`\n ? never // Optional parameters are not supported yet\n : T extends `${string}:${string}/${infer Rest}`\n ? ValidateNoOptionalParams<Rest>\n : T\n\ntype ExtractRouteParams<T extends string> =\n T extends `${string}:${infer Param}/${infer Rest}`\n ? Param | ExtractRouteParams<Rest>\n : T extends `${string}:${infer Param}`\n ? Param\n : never\n\nexport type HasRequiredParams<T extends string> =\n T extends `${string}:${string}` ? true : false\n\nexport type PathParams<Path extends string> =\n ValidateNoOptionalParams<Path> extends never\n ? never // Optional parameters are not supported yet\n : {\n [K in ExtractRouteParams<Path>]: string | number\n }\n\nexport type RequirePathParams<Path extends string, T> =\n HasRequiredParams<Path> extends true\n ? T & { pathParams: PathParams<Path> }\n : T\n\n/**\n * Interpolates parameters into a URL template\n * Similar to React Router's generatePath function\n *\n * @example\n * ```ts\n * const path = generatePath('/users/:id/posts/:postId', { id: '123', postId: '456' });\n * // => '/users/123/posts/456'\n * ```\n */\nexport function generatePath<Path extends string>(\n path: Path,\n params: PathParams<Path> = {} as PathParams<Path>\n): string {\n return path.replace(/:([a-zA-Z0-9_]+)/g, (_match, paramName: string) => {\n if (params[paramName as keyof PathParams<Path>] === undefined) {\n throw new PathParameterError(\n `Missing required path parameter: ${paramName}`,\n path,\n [paramName],\n Object.keys(params)\n )\n }\n return String(params[paramName as keyof PathParams<Path>])\n })\n}\n","import {\n HttpError,\n InterceptorError,\n NetworkError,\n PathParameterError,\n SchemaValidationError,\n SerializationError,\n TimeoutError,\n} from './errors'\nimport { createSchemaValidator, type SchemaValidator } from './schema'\nimport type {\n HttpClientOptions,\n HttpMethod,\n RequestContext,\n RequestInterceptor,\n RequestOptions,\n RequestParamsType,\n ResponseInterceptor,\n ResponseType,\n RetryOptions,\n Schema,\n TypedRequestOptions,\n} from './types'\nimport { generatePath, type PathParams } from './utils'\n\n/**\n * Default retry configuration for HTTP requests\n */\nconst DEFAULT_RETRY_OPTIONS: Required<RetryOptions> = {\n maxRetries: 3,\n retryDelay: 300,\n backoffFactor: 2,\n retryStatusCodes: [429, 500, 502, 503, 504],\n retryNetworkErrors: true,\n maxRetryDelay: 30000,\n shouldRetry: () => true,\n}\n\nfunction validateAndNormalizeBaseUrl(baseUrl?: string): string {\n if (!baseUrl) {\n return ''\n }\n\n try {\n new URL(baseUrl)\n } catch {\n throw new Error(`Invalid baseUrl: \"${baseUrl}\". Must be a valid URL.`)\n }\n\n return baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl\n}\n\n/**\n * A modern, type-safe HTTP client with built-in schema validation, interceptors, retry logic, and compile-time path parameter validation.\n *\n * The HttpClient provides a fluent API for making HTTP requests with full TypeScript support,\n * automatic retry logic, request/response interceptors, and schema validation using popular\n * validation libraries like Zod, Valibot, and Arktype.\n *\n * @example\n * ```ts\n * import { HttpClient } from '1000fetches'\n * import { z } from 'zod'\n *\n * // Create a client instance\n * const client = new HttpClient({\n * baseUrl: 'https://api.example.com',\n * timeout: 5000,\n * headers: { 'Authorization': 'Bearer token' }\n * });\n *\n * const userSchema = z.object({\n * id: z.string(),\n * name: z.string(),\n * email: z.string()\n * });\n *\n * const response = await client.get('/users/:id', {\n * pathParams: { id: '123' },\n * schema: userSchema\n * });\n */\nexport class HttpClient {\n private baseUrl: string\n private defaultHeaders: Record<string, string>\n private defaultTimeout: number\n private schemaValidator: SchemaValidator\n private requestInterceptors: RequestInterceptor[]\n private responseInterceptors: ResponseInterceptor[]\n private defaultRetryOptions?: RetryOptions\n\n /**\n * Create a new HttpClient instance.\n *\n * @param options - Configuration options for the HTTP client\n *\n * @example\n * ```ts\n * // Basic configuration\n * const client = new HttpClient({\n * baseUrl: 'https://api.example.com'\n * });\n *\n * // With custom headers and timeout\n * const client = new HttpClient({\n * baseUrl: 'https://api.example.com',\n * headers: { 'Authorization': 'Bearer token' },\n * timeout: 10000\n * });\n *\n * // With custom schema validator\n * const client = new HttpClient({\n * baseUrl: 'https://api.example.com',\n * schemaValidator: createCustomValidator()\n * });\n *\n * // With retry configuration\n * const client = new HttpClient({\n * baseUrl: 'https://api.example.com',\n * retryOptions: {\n * maxRetries: 5,\n * retryDelay: 1000,\n * retryStatusCodes: [500, 502, 503]\n * }\n * });\n * ```\n */\n constructor(options: HttpClientOptions = {}) {\n this.baseUrl = validateAndNormalizeBaseUrl(options.baseUrl)\n this.defaultHeaders = options.headers || {}\n this.defaultTimeout = options.timeout || 30000 // 30 seconds default\n this.schemaValidator = options.schemaValidator || createSchemaValidator()\n this.requestInterceptors = options.requestInterceptors || []\n this.responseInterceptors = options.responseInterceptors || []\n this.defaultRetryOptions = options.retryOptions\n }\n\n /**\n * Add a request interceptor to modify requests before they're sent.\n *\n * Request interceptors are executed in the order they were added and can modify\n * the request context before it's sent to the server. This is useful for adding\n * authentication headers, logging, or transforming request data.\n *\n * @param interceptor - The interceptor function to add\n *\n * @example\n * ```ts\n * // Add authentication headers to all requests\n * client.addRequestInterceptor((context) => {\n * context.headers.set('Authorization', `Bearer ${getToken()}`);\n * return context;\n * });\n *\n * // Change the base URL for specific endpoints\n * client.addRequestInterceptor((context) => {\n * if (context.url.includes('/special/')) {\n * context.url = context.url.replace('api.example.com', 'special-api.example.com');\n * }\n * return context;\n * });\n *\n * // Log all outgoing requests\n * client.addRequestInterceptor((context) => {\n * console.log(`Making ${context.method} request to ${context.url}`);\n * return context;\n * });\n * ```\n */\n public addRequestInterceptor(interceptor: RequestInterceptor): void {\n this.requestInterceptors.push(interceptor)\n }\n\n /**\n * Add a response interceptor to process responses before they're returned.\n *\n * Response interceptors are executed in the order they were added and can modify\n * the response data before it's returned to the caller. This is useful for\n * transforming data, logging responses, or handling global error conditions.\n *\n * @param interceptor - The interceptor function to add\n *\n * @example\n * ```ts\n * // Log all responses\n * client.addResponseInterceptor((response) => {\n * console.log(`Response from ${response.raw.url}: ${response.status}`);\n * return response;\n * });\n *\n * // Transform response data\n * client.addResponseInterceptor((response) => {\n * if (Array.isArray(response.data)) {\n * response.data = response.data.map(item => transformItem(item));\n * }\n * return response;\n * });\n *\n * // Handle 401 responses by refreshing the token and retrying\n * client.addResponseInterceptor(async (response) => {\n * if (response.status === 401) {\n * await refreshToken();\n * // Make a new request (will use updated token)\n * return await client.request(response.raw.method, response.raw.url);\n * }\n * return response;\n * });\n * ```\n */\n public addResponseInterceptor(interceptor: ResponseInterceptor): void {\n this.responseInterceptors.push(interceptor)\n }\n\n /**\n * Set a custom schema validator for request/response validation\n *\n * @param validator - The schema validator to use for validation\n *\n * @example\n * ```ts\n * // Set a custom validator\n * client.setSchemaValidator(customValidator);\n * ```\n */\n /**\n * Set a custom schema validator for the client.\n *\n * This allows you to use a different validation library or custom validation logic\n * for all requests made by this client instance.\n *\n * @param validator - The schema validator to use for all validation operations\n *\n * @example\n * ```ts\n * import { createCustomValidator } from './custom-validator'\n *\n * // Set a custom validator\n * client.setSchemaValidator(createCustomValidator());\n *\n * // Now all requests will use the custom validator\n * const response = await client.post('/users', userData, {\n * schema: customUserSchema\n * });\n * ```\n */\n public setSchemaValidator(validator: SchemaValidator): void {\n this.schemaValidator = validator\n }\n\n /**\n * Determines if a request should be retried based on error type and retry configuration\n *\n * @param error - The error that occurred during the request\n * @param retryCount - Current retry attempt number\n * @param retryOptions - Retry configuration for this request\n * @returns Promise resolving to whether the request should be retried\n */\n private async shouldRetry(\n error: Error,\n retryCount: number,\n retryOptions: RetryOptions | boolean | undefined\n ): Promise<boolean> {\n if (retryOptions === false) return false\n\n const options = this.getRetryOptions(retryOptions)\n if (retryCount >= options.maxRetries) return false\n\n if (typeof options.shouldRetry === 'function') {\n try {\n return await options.shouldRetry(error, retryCount)\n } catch (retryError) {\n console.warn('Custom shouldRetry function failed:', retryError)\n }\n }\n\n if (error instanceof NetworkError && options.retryNetworkErrors) {\n return true\n }\n\n if (\n error instanceof HttpError &&\n options.retryStatusCodes.includes(error.status)\n ) {\n return true\n }\n\n if (error instanceof SchemaValidationError) {\n return false\n }\n\n if (error instanceof TimeoutError) {\n return true\n }\n\n return false\n }\n\n /**\n * Calculates the delay for the next retry attempt using exponential backoff with jitter\n *\n * @param retryCount - Current retry attempt number\n * @param options - Retry configuration options\n * @returns Delay in milliseconds before the next retry attempt\n */\n private getRetryDelay(\n retryCount: number,\n options: Required<RetryOptions>\n ): number {\n const baseDelay =\n options.retryDelay * Math.pow(options.backoffFactor, retryCount)\n const cappedDelay = Math.min(baseDelay, options.maxRetryDelay)\n\n // Add jitter (±20%) to prevent thundering herd problem\n const jitterRange = cappedDelay * 0.2\n const jitter = jitterRange * (Math.random() * 2 - 1)\n const finalDelay = cappedDelay + jitter\n\n // Ensure we never return negative delays and have a minimum delay of 1ms\n return Math.max(1, Math.floor(finalDelay))\n }\n\n /**\n * Merges provided retry options with default configuration\n *\n * @param retryOptions - Retry options to merge with defaults\n * @returns Complete retry configuration with all required properties\n */\n private getRetryOptions(\n retryOptions?: RetryOptions | boolean\n ): Required<RetryOptions> {\n if (retryOptions === false) {\n return {\n ...DEFAULT_RETRY_OPTIONS,\n maxRetries: 0,\n }\n }\n\n if (retryOptions === true) {\n return {\n ...DEFAULT_RETRY_OPTIONS,\n ...this.defaultRetryOptions,\n }\n }\n\n if (typeof retryOptions === 'object') {\n return {\n ...DEFAULT_RETRY_OPTIONS,\n ...this.defaultRetryOptions,\n ...retryOptions,\n }\n }\n\n return {\n ...DEFAULT_RETRY_OPTIONS,\n ...this.defaultRetryOptions,\n }\n }\n\n /**\n * Creates a promise that resolves after the specified delay\n *\n * @param ms - Delay duration in milliseconds\n * @returns Promise that resolves after the delay\n */\n private sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms))\n }\n\n /**\n * Makes an HTTP request with automatic retry capability\n *\n * @param method - HTTP method to use for the request\n * @param url - URL path for the request (supports path parameters)\n * @param options - Request configuration options\n * @returns Promise resolving to the response data\n *\n * @example\n * ```ts\n * // Simple GET request\n * const response = await client.request('GET', '/users/1');\n *\n * // POST request with body and path parameters\n * const response = await client.request('POST', '/users/:id/posts', {\n * pathParams: { id: 1 },\n * body: { title: 'New Post', content: 'Hello World' },\n * schema: userPostSchema\n * });\n * ```\n */\n public async request<\n Path extends string = string,\n TResponse = unknown,\n TBody = unknown,\n TParams extends RequestParamsType = RequestParamsType,\n >(\n method: HttpMethod,\n url: Path,\n options: TypedRequestOptions<TBody, TResponse, TParams, Path> = {}\n ): Promise<ResponseType<TResponse>> {\n let retryCount = 0\n\n while (true) {\n try {\n return await this.executeRequest<Path, TResponse, TBody, TParams>(\n method,\n url,\n options\n )\n } catch (error) {\n if (!(error instanceof Error)) {\n throw new NetworkError(String(error), undefined)\n }\n\n if (await this.shouldRetry(error, retryCount, options.retry)) {\n const retryOptions = this.getRetryOptions(options.retry)\n const delay = this.getRetryDelay(retryCount, retryOptions)\n await this.sleep(delay)\n\n retryCount++\n continue\n }\n\n throw error\n }\n }\n }\n\n /**\n * Executes a single HTTP request without retry logic\n *\n * @param method - HTTP method for the request\n * @param url - URL path with optional path parameters\n * @param options - Request configuration and validation options\n * @returns Promise resolving to the response data\n */\n private async executeRequest<\n Path extends string = string,\n TResponse = unknown,\n TBody = unknown,\n TParams extends RequestParamsType = RequestParamsType,\n >(\n method: HttpMethod,\n url: Path,\n options: TypedRequestOptions<TBody, TResponse, TParams, Path> = {}\n ): Promise<ResponseType<TResponse>> {\n let resolvedUrl = this.resolveUrl(url, options.pathParams)\n\n let requestContext: RequestContext<TBody> = {\n url: resolvedUrl,\n method,\n params: options.params,\n headers: this.prepareHeaders(options.headers),\n body: options.body,\n fetchOptions: {\n credentials: options.credentials,\n cache: options.cache,\n mode: options.mode,\n redirect: options.redirect,\n },\n }\n\n for (const interceptor of this.requestInterceptors) {\n try {\n requestContext = await interceptor(requestContext)\n } catch (error) {\n throw new InterceptorError(\n `Request interceptor failed: ${error instanceof Error ? error.message : String(error)}`,\n 'request',\n resolvedUrl,\n method,\n error instanceof Error ? error : undefined\n )\n }\n }\n\n resolvedUrl = requestContext.url\n\n if (\n requestContext.params &&\n Object.keys(requestContext.params).length > 0\n ) {\n const searchParams = new URLSearchParams()\n for (const [key, value] of Object.entries(requestContext.params)) {\n if (value !== undefined) {\n searchParams.append(key, String(value))\n }\n }\n const queryString = searchParams.toString()\n if (queryString) {\n resolvedUrl += (resolvedUrl.includes('?') ? '&' : '?') + queryString\n }\n }\n\n const requestInit: RequestInit = {\n method: requestContext.method,\n headers: requestContext.headers,\n ...requestContext.fetchOptions,\n }\n\n if (\n requestContext.body !== undefined &&\n (requestContext.method === 'POST' ||\n requestContext.method === 'PUT' ||\n requestContext.method === 'PATCH')\n ) {\n if (\n requestContext.body instanceof FormData ||\n requestContext.body instanceof Blob ||\n requestContext.body instanceof ArrayBuffer ||\n requestContext.body instanceof URLSearchParams ||\n typeof requestContext.body === 'string'\n ) {\n requestInit.body = requestContext.body as BodyInit\n } else {\n try {\n requestInit.body = JSON.stringify(requestContext.body)\n } catch (error) {\n throw new SerializationError(\n `Failed to serialize request body: ${error instanceof Error ? error.message : 'Invalid data structure'}`,\n error instanceof Error ? error : undefined\n )\n }\n }\n }\n\n const timeoutDuration = options.timeout || this.defaultTimeout\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), timeoutDuration)\n\n const requestSignal = requestContext.signal || options.signal\n let cleanupSignals: VoidFunction | undefined\n const signal = requestSignal\n ? (() => {\n const result = this.mergeAbortSignals(\n requestSignal,\n controller.signal\n )\n cleanupSignals = result.cleanup\n return result.signal\n })()\n : controller.signal\n\n try {\n const response = await fetch(resolvedUrl, {\n ...requestInit,\n signal,\n })\n\n let responseData = await this.processResponse<TResponse>(\n response,\n options,\n method,\n resolvedUrl\n )\n\n if (options.schema) {\n responseData.data = this.validateResponseData<TResponse>(\n options.schema,\n responseData.data\n )\n }\n\n return responseData\n } catch (error) {\n // Check for timeout-related errors more comprehensively\n if (\n (error instanceof DOMException && error.name === 'AbortError') ||\n (error instanceof Error && error.name === 'AbortError') ||\n (error instanceof Error &&\n error.message.toLowerCase().includes('timeout'))\n ) {\n throw new TimeoutError(\n `Request timed out after ${timeoutDuration}ms`,\n error instanceof Error ? error : undefined\n )\n }\n\n if (\n error instanceof HttpError ||\n error instanceof SchemaValidationError ||\n error instanceof InterceptorError ||\n error instanceof PathParameterError ||\n error instanceof SerializationError\n ) {\n throw error\n }\n\n throw new NetworkError(\n error instanceof Error ? error.message : String(error),\n error instanceof Error ? error : undefined\n )\n } finally {\n clearTimeout(timeoutId)\n cleanupSignals?.()\n }\n }\n\n private validateWithSchema<T>(\n schema: Schema<T>,\n data: unknown,\n errorPrefix: string\n ): T {\n try {\n return this.schemaValidator.validate(schema, data)\n } catch (error) {\n throw new SchemaValidationError(\n `${errorPrefix}: ${error instanceof Error ? error.message : 'Unknown error'}`,\n schema,\n data,\n error instanceof Error ? error : undefined\n )\n }\n }\n\n private validateResponseData<T>(schema: Schema<T>, data: unknown): T {\n return this.validateWithSchema(\n schema,\n data,\n 'Response schema validation failed'\n )\n }\n\n /**\n * Public method to validate data against any schema\n *\n * @param schema - Schema to validate against\n * @param data - Data to validate\n * @returns Validated data\n *\n * @example\n * ```ts\n * const validatedUser = client.validateSchema(userSchema, userData);\n * ```\n */\n /**\n * Validate data against a schema using the configured schema validator.\n *\n * This method uses the same schema validator that's configured for the client,\n * ensuring consistent validation behavior across all requests.\n *\n * @template T - The expected type after validation\n * @param schema - The schema to validate against (Zod, Valibot, or Arktype)\n * @param data - The data to validate\n *\n * @returns The validated data with the correct type\n *\n * @throws {SchemaValidationError} If the data doesn't match the schema\n *\n * @example\n * ```ts\n * import { z } from 'zod'\n *\n * const userSchema = z.object({\n * id: z.string(),\n * name: z.string(),\n * email: z.email()\n * });\n *\n * // Validate data manually\n * try {\n * const validatedUser = client.validateSchema(userSchema, userData);\n * console.log('Valid user:', validatedUser);\n * } catch (error) {\n * console.error('Invalid user data:', error);\n * }\n *\n * // This is equivalent to the validation that happens automatically\n * // when you use schema in requests\n * ```\n */\n public validateSchema<T>(schema: Schema<T>, data: unknown): T {\n return this.validateWithSchema(schema, data, 'Schema validation failed')\n }\n\n /**\n * Prepares headers for HTTP requests by merging default and custom headers\n *\n * @param customHeaders - Additional headers to include in the request\n * @returns Headers object with all headers properly set\n */\n private prepareHeaders(customHeaders: Record<string, string> = {}): Headers {\n const headers = new Headers()\n\n for (const [key, value] of Object.entries(this.defaultHeaders)) {\n if (value != null) {\n headers.set(key, String(value))\n }\n }\n\n for (const [key, value] of Object.entries(customHeaders)) {\n if (value != null) {\n headers.set(key, String(value))\n }\n }\n\n return headers\n }\n\n /**\n * Extracts headers from Headers object into a plain record\n *\n * @param headers - Headers object to extract from\n * @returns Record containing header key-value pairs\n */\n private extractHeaders(headers: Headers): Record<string, string> {\n const result: Record<string, string> = {}\n headers.forEach((value, key) => {\n result[key] = value\n })\n return result\n }\n\n /**\n * Creates an HttpError instance with response details\n *\n * @param response - The HTTP response that caused the error\n * @param data - Response data (if any)\n * @param url - The URL that was requested\n * @param method - The HTTP method used\n * @param customStatusText - Optional custom status text\n * @param cause - Optional underlying error that caused this HTTP error\n * @returns HttpError instance with complete error information\n */\n private createHttpError(\n response: globalThis.Response,\n data: unknown,\n url: string,\n method: string,\n customStatusText?: string,\n cause?: Error\n ): HttpError {\n return new HttpError(\n `Request failed with status code ${response.status}`,\n response.status,\n customStatusText || response.statusText,\n data,\n response,\n url,\n method,\n cause\n )\n }\n\n private async parseResponseBody(\n response: globalThis.Response,\n options: RequestOptions\n ): Promise<unknown> {\n const contentType = response.headers.get('content-type') ?? ''\n\n try {\n if (options.responseType === 'text') {\n return await response.text()\n } else if (options.responseType === 'blob') {\n return await response.blob()\n } else if (options.responseType === 'arrayBuffer') {\n return await response.arrayBuffer()\n } else if (contentType.includes('application/json')) {\n const text = await response.text()\n if (!text) {\n return null\n }\n return JSON.parse(text)\n } else {\n return await response.text()\n }\n } catch (e) {\n if (response.status === 204) {\n return undefined\n }\n\n if (\n contentType.includes('application/json') &&\n e instanceof SyntaxError\n ) {\n throw new Error(`Failed to parse JSON response: ${e.message}`)\n }\n\n throw e\n }\n }\n\n private async processResponse<T, TBody = unknown>(\n response: globalThis.Response,\n options: TypedRequestOptions<TBody, T>,\n method: HttpMethod,\n url: string\n ): Promise<ResponseType<T>> {\n const headers = this.extractHeaders(response.headers)\n\n // Check validateStatus first, before response.ok\n const validateStatus =\n options.validateStatus ||\n ((status: number) => status >= 200 && status < 300)\n\n // Parse response body once (for both success and error cases)\n const data = await this.parseResponseBody(response, options)\n\n // Check if this is an error response after parsing\n if (!validateStatus(response.status)) {\n throw this.createHttpError(response, data, url, method)\n }\n\n // Create response object with unknown data initially\n const responseObj: ResponseType<unknown> = {\n data,\n status: response.status,\n statusText: response.statusText,\n headers,\n method,\n url,\n raw: response,\n }\n\n // Apply response interceptors\n let processedResponse = responseObj\n const originalStatus = responseObj.status\n\n for (const interceptor of this.responseInterceptors) {\n try {\n processedResponse = await interceptor(processedResponse)\n } catch (error) {\n throw new InterceptorError(\n `Response interceptor failed: ${error instanceof Error ? error.message : String(error)}`,\n 'response',\n url,\n method,\n error instanceof Error ? error : undefined\n )\n }\n }\n\n // Only re-validate if interceptors changed the status\n if (\n processedResponse.status !== originalStatus &&\n !validateStatus(processedResponse.status)\n ) {\n throw this.createHttpError(\n response,\n processedResponse.data,\n url,\n method,\n processedResponse.statusText\n )\n }\n\n return processedResponse as ResponseType<T>\n }\n\n private mergeAbortSignals(\n signal1: AbortSignal,\n signal2: AbortSignal\n ): { signal: AbortSignal; cleanup?: VoidFunction } {\n if (signal1.aborted || signal2.aborted) {\n const controller = new AbortController()\n controller.abort()\n return { signal: controller.signal }\n }\n\n const controller = new AbortController()\n\n const abortHandler = () => {\n controller.abort()\n cleanup()\n }\n\n const cleanup = () => {\n signal1.removeEventListener('abort', abortHandler)\n signal2.removeEventListener('abort', abortHandler)\n }\n\n signal1.addEventListener('abort', abortHandler)\n signal2.addEventListener('abort', abortHandler)\n\n return { signal: controller.signal, cleanup }\n }\n\n /**\n * Send a GET request with schema validation (type inferred from schema).\n *\n * @example\n * // JSON response\n * const response = await client.get('/users/:id', {\n * pathParams: { id: '123' },\n * schema: z.object({ id: z.string(), name: z.string() })\n * })\n *\n * @example\n * // Blob response\n * const response = await client.get('/avatar', {\n * responseType: 'blob',\n * schema: z.instanceof(Blob)\n * })\n *\n * @example\n * // Text response\n * const response = await client.get('/raw', {\n * responseType: 'text',\n * schema: z.string()\n * })\n */\n public get<\n TResponse,\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n >(\n url: Path,\n options: TypedRequestOptions<void, TResponse, TParams, Path> & {\n schema: Schema<TResponse>\n }\n ): Promise<ResponseType<TResponse>>\n\n /**\n * Send a GET request without schema (response.data is unknown).\n *\n * @example\n * const response = await client.get('/users')\n */\n public get<\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n >(\n url: Path,\n options?: Omit<TypedRequestOptions<void, unknown, TParams, Path>, 'schema'>\n ): Promise<ResponseType<unknown>>\n\n public get<\n TResponse,\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n >(\n url: Path,\n options?: TypedRequestOptions<void, TResponse, TParams, Path>\n ): Promise<ResponseType<TResponse | unknown>> {\n return this.request<Path, TResponse, void, TParams>(\n 'GET',\n url,\n options || {}\n )\n }\n\n /**\n * Send a POST request with schema validation (type inferred from schema).\n *\n * @example\n * const response = await client.post('/users', userData, {\n * schema: z.object({ id: z.string(), name: z.string() })\n * })\n */\n public post<\n TResponse,\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n TBody = unknown,\n >(\n url: Path,\n body: TBody | undefined,\n options: Omit<\n TypedRequestOptions<TBody, TResponse, TParams, Path>,\n 'body'\n > & { schema: Schema<TResponse> }\n ): Promise<ResponseType<TResponse>>\n\n /**\n * Send a POST request without schema (response.data is unknown).\n *\n * @example\n * const response = await client.post('/users', userData)\n */\n public post<\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n TBody = unknown,\n >(\n url: Path,\n body?: TBody,\n options?: Omit<\n TypedRequestOptions<TBody, unknown, TParams, Path>,\n 'body' | 'schema'\n >\n ): Promise<ResponseType<unknown>>\n\n public post<\n TResponse,\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n TBody = unknown,\n >(\n url: Path,\n body?: TBody,\n options?: Omit<TypedRequestOptions<TBody, TResponse, TParams, Path>, 'body'>\n ): Promise<ResponseType<TResponse | unknown>> {\n return this.request<Path, TResponse, TBody, TParams>('POST', url, {\n ...(options || {}),\n body,\n })\n }\n\n /**\n * Send a PUT request with schema validation (type inferred from schema).\n *\n * @example\n * const response = await client.put('/users/:id', updatedData, {\n * pathParams: { id: '123' },\n * schema: z.object({ id: z.string(), name: z.string() })\n * })\n */\n public put<\n TResponse,\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n TBody = unknown,\n >(\n url: Path,\n body: TBody | undefined,\n options: Omit<\n TypedRequestOptions<TBody, TResponse, TParams, Path>,\n 'body'\n > & { schema: Schema<TResponse> }\n ): Promise<ResponseType<TResponse>>\n\n /**\n * Send a PUT request without schema (response.data is unknown).\n *\n * @example\n * const response = await client.put('/users/:id', updatedData, {\n * pathParams: { id: '123' }\n * })\n */\n public put<\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n TBody = unknown,\n >(\n url: Path,\n body?: TBody,\n options?: Omit<\n TypedRequestOptions<TBody, unknown, TParams, Path>,\n 'body' | 'schema'\n >\n ): Promise<ResponseType<unknown>>\n\n public put<\n TResponse,\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n TBody = unknown,\n >(\n url: Path,\n body?: TBody,\n options?: Omit<TypedRequestOptions<TBody, TResponse, TParams, Path>, 'body'>\n ): Promise<ResponseType<TResponse | unknown>> {\n return this.request<Path, TResponse, TBody, TParams>('PUT', url, {\n ...(options || {}),\n body,\n })\n }\n\n /**\n * Send a PATCH request with schema validation (type inferred from schema).\n *\n * @example\n * const response = await client.patch('/users/:id', partialData, {\n * pathParams: { id: '123' },\n * schema: z.object({ id: z.string(), name: z.string() })\n * })\n */\n public patch<\n TResponse,\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n TBody = unknown,\n >(\n url: Path,\n body: TBody | undefined,\n options: Omit<\n TypedRequestOptions<TBody, TResponse, TParams, Path>,\n 'body'\n > & { schema: Schema<TResponse> }\n ): Promise<ResponseType<TResponse>>\n\n /**\n * Send a PATCH request without schema (response.data is unknown).\n *\n * @example\n * const response = await client.patch('/users/:id', partialData, {\n * pathParams: { id: '123' }\n * })\n */\n public patch<\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n TBody = unknown,\n >(\n url: Path,\n body?: TBody,\n options?: Omit<\n TypedRequestOptions<TBody, unknown, TParams, Path>,\n 'body' | 'schema'\n >\n ): Promise<ResponseType<unknown>>\n\n public patch<\n TResponse,\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n TBody = unknown,\n >(\n url: Path,\n body?: TBody,\n options?: Omit<TypedRequestOptions<TBody, TResponse, TParams, Path>, 'body'>\n ): Promise<ResponseType<TResponse | unknown>> {\n return this.request<Path, TResponse, TBody, TParams>('PATCH', url, {\n ...(options || {}),\n body,\n })\n }\n\n /**\n * Send a DELETE request with schema validation (type inferred from schema).\n *\n * @example\n * const response = await client.delete('/users/:id', {\n * pathParams: { id: '123' },\n * schema: z.object({ success: z.boolean() })\n * })\n */\n public delete<\n TResponse,\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n >(\n url: Path,\n options: TypedRequestOptions<void, TResponse, TParams, Path> & {\n schema: Schema<TResponse>\n }\n ): Promise<ResponseType<TResponse>>\n\n /**\n * Send a DELETE request without schema (response.data is unknown).\n *\n * @example\n * const response = await client.delete('/users/:id', {\n * pathParams: { id: '123' }\n * })\n */\n public delete<\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n >(\n url: Path,\n options?: Omit<TypedRequestOptions<void, unknown, TParams, Path>, 'schema'>\n ): Promise<ResponseType<unknown>>\n\n public delete<\n TResponse,\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n >(\n url: Path,\n options?: TypedRequestOptions<void, TResponse, TParams, Path>\n ): Promise<ResponseType<TResponse | unknown>> {\n return this.request<Path, TResponse, void, TParams>(\n 'DELETE',\n url,\n options || {}\n )\n }\n\n /**\n * Validates path parameters against the URL template\n *\n * @param url - URL template with path parameters (e.g., '/users/:id')\n * @param pathParams - Path parameters to validate\n * @throws Error if required path parameters are missing or invalid\n */\n private validatePathParams<Path extends string>(\n url: Path,\n pathParams?: PathParams<Path>\n ): void {\n if (!pathParams) {\n // Check if URL contains required path parameters\n const requiredParams = this.extractRequiredPathParams(url)\n if (requiredParams.length > 0) {\n throw new PathParameterError(\n `Missing required path parameters for URL \"${url}\": ${requiredParams.join(', ')}. ` +\n `Please provide pathParams: { ${requiredParams.map(p => `${p}: value`).join(', ')} }`,\n url,\n requiredParams,\n []\n )\n }\n return\n }\n\n // Validate that all required parameters are provided\n const requiredParams = this.extractRequiredPathParams(url)\n const providedParams = Object.keys(pathParams)\n\n const missingParams = requiredParams.filter(\n param => !providedParams.includes(param)\n )\n if (missingParams.length > 0) {\n throw new PathParameterError(\n `Missing required path parameters: ${missingParams.join(', ')}. ` +\n `Provided: ${providedParams.join(', ')}`,\n url,\n requiredParams,\n providedParams\n )\n }\n\n // const unusedParams = providedParams.filter(\n // param => !requiredParams.includes(param)\n // )\n // if (unusedParams.length > 0) {\n // console.warn(\n // `Unused path parameters provided: ${unusedParams.join(', ')}. ` +\n // `URL \"${url}\" does not contain these parameters.`\n // )\n // }\n }\n\n /**\n * Extracts required path parameters from a URL template\n *\n * @param url - URL template to extract parameters from\n * @returns Array of required parameter names\n */\n private extractRequiredPathParams(url: string): string[] {\n const matches = url.match(/:([a-zA-Z0-9_]+)/g)\n if (!matches) return []\n\n return matches.map(match => match.slice(1))\n }\n\n /**\n * Resolves a URL template with path parameters and base URL\n *\n * @param url - URL template with optional path parameters\n * @param pathParams - Path parameters to interpolate into the URL\n * @returns Fully resolved URL with base URL and path parameters applied\n */\n private resolveUrl<Path extends string>(\n url: Path,\n pathParams?: PathParams<Path>\n ): string {\n this.validatePathParams(url, pathParams)\n\n const interpolatedUrl = pathParams ? generatePath(url, pathParams) : url\n\n if (/^https?:\\/\\//i.test(interpolatedUrl)) {\n return interpolatedUrl\n }\n\n const path = interpolatedUrl.startsWith('/')\n ? interpolatedUrl.slice(1)\n : interpolatedUrl\n\n return `${this.baseUrl}/${path}`\n }\n}\n"],"names":["HttpError","Error","name","status","statusText","data","response","url","method","cause","constructor","message","super","this","NetworkError","SchemaValidationError","schema","TimeoutError","PathParameterError","requiredParams","providedParams","InterceptorError","interceptorType","SerializationError","isStandardSchema","obj","validate","version","vendor","standardSchemaAdapter","parse","result","Promise","issues","errorMessages","Array","from","map","issue","join","value","createStandardSchemaValidator","isSchema","createSchemaValidator","createStdSchemaValidator","generatePath","path","params","replace","_match","paramName","Object","keys","String","DEFAULT_RETRY_OPTIONS","maxRetries","retryDelay","backoffFactor","retryStatusCodes","retryNetworkErrors","maxRetryDelay","shouldRetry","baseUrl","defaultHeaders","defaultTimeout","schemaValidator","requestInterceptors","responseInterceptors","defaultRetryOptions","options","URL","endsWith","slice","validateAndNormalizeBaseUrl","headers","timeout","retryOptions","addRequestInterceptor","interceptor","push","addResponseInterceptor","setSchemaValidator","validator","error","retryCount","getRetryOptions","retryError","console","warn","includes","getRetryDelay","baseDelay","Math","pow","cappedDelay","min","finalDelay","random","max","floor","sleep","ms","resolve","setTimeout","request","executeRequest","retry","delay","resolvedUrl","resolveUrl","pathParams","requestContext","prepareHeaders","body","fetchOptions","credentials","cache","mode","redirect","length","searchParams","URLSearchParams","key","entries","append","queryString","toString","requestInit","FormData","Blob","ArrayBuffer","JSON","stringify","timeoutDuration","controller","AbortController","timeoutId","abort","requestSignal","signal","cleanupSignals","mergeAbortSignals","cleanup","fetch","responseData","processResponse","validateResponseData","DOMException","toLowerCase","clearTimeout","validateWithSchema","errorPrefix","validateSchema","customHeaders","Headers","set","extractHeaders","forEach","createHttpError","customStatusText","parseResponseBody","contentType","get","responseType","text","blob","arrayBuffer","e","SyntaxError","validateStatus","responseObj","raw","processedResponse","originalStatus","signal1","signal2","aborted","abortHandler","removeEventListener","addEventListener","post","put","patch","validatePathParams","extractRequiredPathParams","p","missingParams","filter","param","matches","match","interpolatedUrl","test","startsWith"],"mappings":"gFAOO,MAAMA,UACHC,MAGQC,KAAO,YACPC,OACAC,WACAC,KACAC,SACAC,IACAC,OACSC,MAEzB,WAAAC,CACEC,EACAR,EACAC,EACAC,EACAC,EACAC,EACAC,EACAC,GAGAG,MADwB,QAAQT,KAAUC,MAAeO,MAAYH,KAAUD,KACxD,CAAEE,UACzBI,KAAKV,OAASA,EACdU,KAAKT,WAAaA,EAClBS,KAAKR,KAAOA,EACZQ,KAAKP,SAAWA,EAChBO,KAAKN,IAAMA,EACXM,KAAKL,OAASA,CAChB,EAGK,MAAMM,UAAqBb,MAChBC,KAAO,eACEO,MAEzB,WAAAC,CAAYC,EAAiBF,GAC3BG,MAAMD,EAAS,CAAEF,SACnB,EAGK,MAAMM,UAA8Bd,MACzBC,KAAO,wBACPc,OACAX,KACSI,MAEzB,WAAAC,CAAYC,EAAiBK,EAAiBX,EAAeI,GAC3DG,MAAMD,EAAS,CAAEF,UACjBI,KAAKG,OAASA,EACdH,KAAKR,KAAOA,CACd,EAGK,MAAMY,UAAqBhB,MAChBC,KAAO,eACEO,MAEzB,WAAAC,CAAYC,EAAiBF,GAC3BG,MAAMD,EAAS,CAAEF,SACnB,EAGK,MAAMS,UAA2BjB,MACtBC,KAAO,qBACPK,IACAY,eACAC,eACSX,MAEzB,WAAAC,CACEC,EACAJ,EACAY,EACAC,EACAX,GAEAG,MAAMD,EAAS,CAAEF,UACjBI,KAAKN,IAAMA,EACXM,KAAKM,eAAiBA,EACtBN,KAAKO,eAAiBA,CACxB,EAGK,MAAMC,UAAyBpB,MACpBC,KAAO,mBACPoB,gBACAf,IACAC,OACSC,MAEzB,WAAAC,CACEC,EACAW,EACAf,EACAC,EACAC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AEpC,GAAIF,EAAcnE,OAAS,EACzB,MAAM,IAAIrG,EACR,qCAAqCwK,EAAcnJ,KAAK,oBACzCnB,EAAemB,KAAK,QACnChC,EACAY,EACAC,EAaN,CAQQ,yBAAAoK,CAA0BjL,GAChC,MAAMsL,EAAUtL,EAAIuL,MAAM,qBAC1B,OAAKD,EAEEA,EAAQxJ,IAAIyJ,GAASA,EAAMtH,MAAM,IAFnB,EAGvB,CASQ,UAAAqC,CACNtG,EACAuG,GAEAjG,KAAK0K,mBAAmBhL,EAAKuG,GAE7B,MAAMiF,EAAkBjF,EAAajE,EAAatC,EAAKuG,GAAcvG,EAErE,GAAI,gBAAgByL,KAAKD,GACvB,OAAOA,EAGT,MAAMjJ,EAAOiJ,EAAgBE,WAAW,KACpCF,EAAgBvH,MAAM,GACtBuH,EAEJ,MAAO,GAAGlL,KAAKiD,WAAWhB,GAC5B"}
|
|
1
|
+
{"version":3,"file":"index.cjs.js","sources":["../src/errors.ts","../src/standard-schema.ts","../src/client.ts","../src/schema.ts","../src/utils/path.ts"],"sourcesContent":["interface HttpClientError {\n name: string\n message: string\n cause?: Error\n stack?: string\n}\n\nexport class HttpError<TErrorData = unknown>\n extends Error\n implements HttpClientError\n{\n public readonly name = 'HttpError'\n public readonly status: number\n public readonly statusText: string\n public readonly data: TErrorData\n public readonly response: Response\n public readonly url: string\n public readonly method: string\n public override readonly cause?: Error\n\n constructor(\n message: string,\n status: number,\n statusText: string,\n data: TErrorData,\n response: Response,\n url: string,\n method: string,\n cause?: Error\n ) {\n const enhancedMessage = `HTTP ${status} ${statusText}: ${message} (${method} ${url})`\n super(enhancedMessage, { cause })\n this.status = status\n this.statusText = statusText\n this.data = data\n this.response = response\n this.url = url\n this.method = method\n }\n}\n\nexport class NetworkError extends Error implements HttpClientError {\n public readonly name = 'NetworkError'\n public override readonly cause?: Error\n\n constructor(message: string, cause?: Error) {\n super(message, { cause })\n }\n}\n\nexport class SchemaValidationError extends Error implements HttpClientError {\n public readonly name = 'SchemaValidationError'\n public readonly schema: unknown\n public readonly data: unknown\n public override readonly cause?: Error\n\n constructor(message: string, schema: unknown, data: unknown, cause?: Error) {\n super(message, { cause })\n this.schema = schema\n this.data = data\n }\n}\n\nexport class TimeoutError extends Error implements HttpClientError {\n public readonly name = 'TimeoutError'\n public override readonly cause?: Error\n\n constructor(message: string, cause?: Error) {\n super(message, { cause })\n }\n}\n\nexport class PathParameterError extends Error implements HttpClientError {\n public readonly name = 'PathParameterError'\n public readonly url: string\n public readonly requiredParams: string[]\n public readonly providedParams: string[]\n public override readonly cause?: Error\n\n constructor(\n message: string,\n url: string,\n requiredParams: string[],\n providedParams: string[],\n cause?: Error\n ) {\n super(message, { cause })\n this.url = url\n this.requiredParams = requiredParams\n this.providedParams = providedParams\n }\n}\n\nexport class InterceptorError extends Error implements HttpClientError {\n public readonly name = 'InterceptorError'\n public readonly interceptorType: 'request' | 'response'\n public readonly url?: string\n public readonly method?: string\n public override readonly cause?: Error\n\n constructor(\n message: string,\n interceptorType: 'request' | 'response',\n url?: string,\n method?: string,\n cause?: Error\n ) {\n super(message, { cause })\n this.interceptorType = interceptorType\n this.url = url\n this.method = method\n }\n}\n\nexport class SerializationError extends Error implements HttpClientError {\n public readonly name = 'SerializationError'\n public override readonly cause?: Error\n\n constructor(message: string, cause?: Error) {\n super(message, { cause })\n }\n}\n","import { SchemaValidator } from './schema'\n\n/**\n * Standard Schema V1 interface implementation\n *\n * This interface defines the structure for schema validation libraries\n * that conform to the Standard Schema specification.\n *\n * @see https://github.com/standard-schema/standard-schema\n */\nexport interface StandardSchemaV1<Input = unknown, Output = Input> {\n /** The Standard Schema properties containing validation logic and metadata */\n readonly '~standard': StandardSchemaV1.Props<Input, Output>\n}\n\n/**\n * Namespace containing Standard Schema V1 type definitions\n *\n * Provides type-safe interfaces for schema validation results,\n * error handling, and type inference.\n */\nexport namespace StandardSchemaV1 {\n /**\n * Core properties interface for Standard Schema V1\n *\n * Contains the essential metadata and validation function\n * that every Standard Schema implementation must provide.\n */\n export interface Props<Input = unknown, Output = Input> {\n /** The version number of the Standard Schema specification */\n readonly version: 1\n /** The name of the schema validation library (e.g., 'zod', 'valibot') */\n readonly vendor: string\n /**\n * Validates unknown input values against the schema\n *\n * @param value - The value to validate\n * @returns Promise or direct result containing validation outcome\n */\n readonly validate: (\n value: unknown\n ) => Result<Output> | Promise<Result<Output>>\n /** Type information for input and output types */\n readonly types?: Types<Input, Output> | undefined\n }\n\n /**\n * Union type representing the result of schema validation\n *\n * Can be either a successful validation with the validated value,\n * or a failed validation with error details.\n */\n export type Result<Output> = SuccessResult<Output> | FailureResult\n\n /**\n * Interface for successful validation results\n *\n * Contains the validated and typed output value.\n */\n export interface SuccessResult<Output> {\n /** The validated and typed output value */\n readonly value: Output\n /** Undefined since validation succeeded */\n readonly issues?: undefined\n }\n\n /**\n * Interface for failed validation results\n *\n * Contains detailed error information about validation failures.\n */\n export interface FailureResult {\n /** Array of validation error details */\n readonly issues: ReadonlyArray<Issue>\n }\n\n /**\n * Interface for individual validation error details\n *\n * Provides error message and optional path information\n * to help identify where validation failed.\n */\n export interface Issue {\n /** Human-readable error message describing the validation failure */\n readonly message: string\n /**\n * Path to the property that failed validation\n *\n * Useful for nested object validation to pinpoint the exact location\n * of validation failures.\n */\n readonly path?: ReadonlyArray<PropertyKey | PathSegment> | undefined\n }\n\n /**\n * Interface for path segment information in validation errors\n *\n * Used to provide detailed path information for validation failures\n * in complex nested structures.\n */\n export interface PathSegment {\n /** The property key representing this path segment */\n readonly key: PropertyKey\n }\n\n /**\n * Interface for type information associated with a schema\n *\n * Provides compile-time type information for input and output types\n * to enable better TypeScript integration and IntelliSense support.\n */\n export interface Types<Input = unknown, Output = Input> {\n /** The input type that the schema expects */\n readonly input: Input\n /** The output type that the schema produces after validation */\n readonly output: Output\n }\n\n /**\n * Type utility to infer the input type from a Standard Schema\n *\n * Extracts the input type that a schema expects for validation.\n *\n * @example\n * ```ts\n * type UserInput = StandardSchemaV1.InferInput<typeof userSchema>\n * ```\n */\n export type InferInput<Schema extends StandardSchemaV1> = NonNullable<\n Schema['~standard']['types']\n >['input']\n\n /**\n * Type utility to infer the output type from a Standard Schema\n *\n * Extracts the output type that a schema produces after validation.\n *\n * @example\n * ```ts\n * type UserOutput = StandardSchemaV1.InferOutput<typeof userSchema>\n * ```\n */\n export type InferOutput<Schema extends StandardSchemaV1> = NonNullable<\n Schema['~standard']['types']\n >['output']\n}\n\n/**\n * Type guard to check if an object conforms to the Standard Schema V1 specification\n *\n * Validates that an object has the required structure and properties\n * to be considered a valid Standard Schema implementation.\n *\n * @param obj - The object to check\n * @returns True if the object is a valid Standard Schema V1 implementation\n *\n * @example\n * ```ts\n * if (isStandardSchema(schema)) {\n * // Use the schema with type safety\n * const result = schema['~standard'].validate(data);\n * }\n * ```\n */\nexport function isStandardSchema(obj: unknown): obj is StandardSchemaV1 {\n return (\n obj !== null &&\n (typeof obj === 'object' || typeof obj === 'function') &&\n '~standard' in obj &&\n typeof obj['~standard'] === 'object' &&\n obj['~standard'] !== null &&\n 'validate' in obj['~standard'] &&\n typeof obj['~standard'].validate === 'function' &&\n 'version' in obj['~standard'] &&\n typeof obj['~standard'].version === 'number' &&\n 'vendor' in obj['~standard'] &&\n typeof obj['~standard'].vendor === 'string'\n )\n}\n\n/**\n * Creates an adapter for Standard Schema V1 implementations\n *\n * Converts Standard Schema validation results into a format compatible\n * with the HTTP client's schema validation system.\n *\n * @param schema - The Standard Schema V1 implementation to adapt\n * @returns Adapter object with parse method\n *\n * @example\n * ```ts\n * const zodAdapter = standardSchemaAdapter(zodUserSchema);\n * const validatedUser = zodAdapter.parse(userData);\n * ```\n */\nexport function standardSchemaAdapter<T>(schema: StandardSchemaV1<unknown, T>) {\n return {\n /**\n * Parses and validates data using the Standard Schema\n *\n * @param data - The data to validate\n * @returns The validated and typed data\n * @throws Error if validation fails\n */\n parse: (data: unknown): T => {\n const result = schema['~standard'].validate(data)\n\n if (result instanceof Promise) {\n throw new Error('Async Standard Schema validation is not supported')\n }\n\n if ('issues' in result && result.issues) {\n const errorMessages = Array.from(result.issues)\n .map(issue => issue.message)\n .join('; ')\n throw new Error(`Standard Schema validation failed: ${errorMessages}`)\n }\n\n return result.value as T\n },\n }\n}\n\n/**\n * Creates a schema validator that supports Standard Schema V1 implementations\n *\n * Provides a validator that can work with any schema library that implements\n * the Standard Schema V1 specification, enabling interoperability between\n * different validation libraries.\n *\n * @returns SchemaValidator that supports Standard Schema V1\n *\n * @example\n * ```ts\n * const validator = createStandardSchemaValidator();\n * const client = new HttpClient({ schemaValidator: validator });\n * ```\n */\nexport function createStandardSchemaValidator(): SchemaValidator {\n return {\n /**\n * Validates data against a Standard Schema V1 implementation\n *\n * @param schema - The Standard Schema V1 to validate against\n * @param data - The data to validate\n * @returns The validated and typed data\n * @throws Error if validation fails or schema is invalid\n */\n validate<T>(schema: StandardSchemaV1<unknown, T>, data: unknown): T {\n if (!isStandardSchema(schema)) {\n throw new Error(\n 'Invalid schema: Schema must implement the Standard Schema interface'\n )\n }\n\n const adapter = standardSchemaAdapter<T>(schema)\n return adapter.parse(data)\n },\n\n /**\n * Checks if an object is a valid Standard Schema V1 implementation\n *\n * @param obj - The object to check\n * @returns True if the object is a valid Standard Schema V1\n */\n isSchema(obj: unknown): boolean {\n return isStandardSchema(obj)\n },\n }\n}\n","import {\n HttpError,\n InterceptorError,\n NetworkError,\n PathParameterError,\n SchemaValidationError,\n SerializationError,\n TimeoutError,\n} from './errors'\nimport { createSchemaValidator, type SchemaValidator } from './schema'\nimport type {\n EnforcedPathParamsOptions,\n HttpClientOptions,\n HttpMethod,\n RequestContext,\n RequestInterceptor,\n RequestOptions,\n RequestParamsType,\n ResponseInterceptor,\n ResponsePromise,\n ResponseType,\n RetryOptions,\n Schema,\n TypedRequestOptions,\n} from './types'\nimport { generatePath, type HasRequiredParams, type PathParams } from './utils'\n\n/**\n * Default retry configuration for HTTP requests\n */\nconst DEFAULT_RETRY_OPTIONS: Required<RetryOptions> = {\n maxRetries: 3,\n retryDelay: 300,\n backoffFactor: 2,\n retryStatusCodes: [429, 500, 502, 503, 504],\n retryNetworkErrors: true,\n maxRetryDelay: 30000,\n shouldRetry: () => true,\n}\n\nfunction validateAndNormalizeBaseUrl(baseUrl?: string): string {\n const hasLocation =\n typeof window !== 'undefined' &&\n typeof window.location !== 'undefined' &&\n window.location.origin !== 'null'\n\n if (!baseUrl) {\n // In browser environment, default to location.origin for relative paths\n return hasLocation ? window.location.origin : ''\n }\n\n // Allow relative paths like \"/api\" - they'll be resolved against location.origin or need absolute URLs in Node\n if (baseUrl.startsWith('/')) {\n // In Node.js or non-browser environments, relative paths are preserved as-is\n return hasLocation\n ? new URL(baseUrl, window.location.origin).href.replace(/\\/$/, '')\n : baseUrl.replace(/\\/$/, '')\n }\n\n try {\n new URL(baseUrl)\n } catch {\n throw new Error(\n `Invalid baseUrl: \"${baseUrl}\". Must be a valid absolute URL or relative path starting with \"/\".`\n )\n }\n\n return baseUrl.endsWith('/') ? baseUrl.slice(0, -1) : baseUrl\n}\n\n/**\n * Wraps a response promise with data extraction method\n * @param promise - The base response promise\n * @returns Promise with data method attached\n */\nfunction wrapResponsePromise<T>(\n promise: Promise<ResponseType<T>>\n): ResponsePromise<T> {\n const wrappedPromise = promise as ResponsePromise<T>\n\n wrappedPromise.data = async () => {\n const response = await promise\n return response.data\n }\n\n return wrappedPromise\n}\n\n/**\n * A modern, type-safe HTTP client with built-in schema validation, interceptors, retry logic, and compile-time path parameter validation.\n *\n * The HttpClient provides a fluent API for making HTTP requests with full TypeScript support,\n * automatic retry logic, request/response interceptors, and schema validation using popular\n * validation libraries like Zod, Valibot, and Arktype.\n *\n * @example\n * ```ts\n * import { HttpClient } from '1000fetches'\n * import { z } from 'zod'\n *\n * // Create a client instance\n * const client = new HttpClient({\n * baseUrl: 'https://api.example.com',\n * timeout: 5000,\n * headers: { 'Authorization': 'Bearer token' }\n * });\n *\n * const userSchema = z.object({\n * id: z.string(),\n * name: z.string(),\n * email: z.string()\n * });\n *\n * const response = await client.get('/users/:id', {\n * pathParams: { id: '123' },\n * schema: userSchema\n * });\n */\nexport class HttpClient {\n private baseUrl: string\n private defaultHeaders: Record<string, string>\n private defaultTimeout: number\n private schemaValidator: SchemaValidator\n private requestInterceptors: RequestInterceptor[]\n private responseInterceptors: ResponseInterceptor[]\n private defaultRetryOptions?: RetryOptions\n\n /**\n * Create a new HttpClient instance.\n *\n * @param options - Configuration options for the HTTP client\n *\n * @example\n * ```ts\n * // Basic configuration\n * const client = new HttpClient({\n * baseUrl: 'https://api.example.com'\n * });\n *\n * // With custom headers and timeout\n * const client = new HttpClient({\n * baseUrl: 'https://api.example.com',\n * headers: { 'Authorization': 'Bearer token' },\n * timeout: 10000\n * });\n *\n * // With custom schema validator\n * const client = new HttpClient({\n * baseUrl: 'https://api.example.com',\n * schemaValidator: createCustomValidator()\n * });\n *\n * // With retry configuration\n * const client = new HttpClient({\n * baseUrl: 'https://api.example.com',\n * retryOptions: {\n * maxRetries: 5,\n * retryDelay: 1000,\n * retryStatusCodes: [500, 502, 503]\n * }\n * });\n * ```\n */\n constructor(options: HttpClientOptions = {}) {\n this.baseUrl = validateAndNormalizeBaseUrl(options.baseUrl)\n this.defaultHeaders = options.headers || {}\n this.defaultTimeout = options.timeout || 30000 // 30 seconds default\n this.schemaValidator = options.schemaValidator || createSchemaValidator()\n this.requestInterceptors = options.requestInterceptors || []\n this.responseInterceptors = options.responseInterceptors || []\n this.defaultRetryOptions = options.retryOptions\n }\n\n /**\n * Add a request interceptor to modify requests before they're sent.\n *\n * Request interceptors are executed in the order they were added and can modify\n * the request context before it's sent to the server. This is useful for adding\n * authentication headers, logging, or transforming request data.\n *\n * @param interceptor - The interceptor function to add\n *\n * @example\n * ```ts\n * // Add authentication headers to all requests\n * client.addRequestInterceptor((context) => {\n * context.headers.set('Authorization', `Bearer ${getToken()}`);\n * return context;\n * });\n *\n * // Change the base URL for specific endpoints\n * client.addRequestInterceptor((context) => {\n * if (context.url.includes('/special/')) {\n * context.url = context.url.replace('api.example.com', 'special-api.example.com');\n * }\n * return context;\n * });\n *\n * // Log all outgoing requests\n * client.addRequestInterceptor((context) => {\n * console.log(`Making ${context.method} request to ${context.url}`);\n * return context;\n * });\n * ```\n */\n public addRequestInterceptor(interceptor: RequestInterceptor): void {\n this.requestInterceptors.push(interceptor)\n }\n\n /**\n * Add a response interceptor to process responses before they're returned.\n *\n * Response interceptors are executed in the order they were added and can modify\n * the response data before it's returned to the caller. This is useful for\n * transforming data, logging responses, or handling global error conditions.\n *\n * @param interceptor - The interceptor function to add\n *\n * @example\n * ```ts\n * // Log all responses\n * client.addResponseInterceptor((response) => {\n * console.log(`Response from ${response.raw.url}: ${response.status}`);\n * return response;\n * });\n *\n * // Transform response data\n * client.addResponseInterceptor((response) => {\n * if (Array.isArray(response.data)) {\n * response.data = response.data.map(item => transformItem(item));\n * }\n * return response;\n * });\n *\n * // Handle 401 responses by refreshing the token and retrying\n * client.addResponseInterceptor(async (response) => {\n * if (response.status === 401) {\n * await refreshToken();\n * // Make a new request (will use updated token)\n * return await client.request(response.raw.method, response.raw.url);\n * }\n * return response;\n * });\n * ```\n */\n public addResponseInterceptor(interceptor: ResponseInterceptor): void {\n this.responseInterceptors.push(interceptor)\n }\n\n /**\n * Determines if a request should be retried based on error type and retry configuration\n *\n * @param error - The error that occurred during the request\n * @param retryCount - Current retry attempt number\n * @param retryOptions - Retry configuration for this request\n * @returns Promise resolving to whether the request should be retried\n */\n private async shouldRetry(\n error: Error,\n retryCount: number,\n retryOptions: RetryOptions | boolean | undefined\n ): Promise<boolean> {\n if (retryOptions === false) return false\n\n const options = this.getRetryOptions(retryOptions)\n if (retryCount >= options.maxRetries) return false\n\n if (typeof options.shouldRetry === 'function') {\n try {\n return await options.shouldRetry(error, retryCount)\n } catch (retryError) {\n console.warn('Custom shouldRetry function failed:', retryError)\n }\n }\n\n if (error instanceof NetworkError && options.retryNetworkErrors) {\n return true\n }\n\n if (\n error instanceof HttpError &&\n options.retryStatusCodes.includes(error.status)\n ) {\n return true\n }\n\n if (error instanceof SchemaValidationError) {\n return false\n }\n\n if (error instanceof TimeoutError) {\n return true\n }\n\n return false\n }\n\n /**\n * Calculates the delay for the next retry attempt using exponential backoff with jitter\n *\n * @param retryCount - Current retry attempt number\n * @param options - Retry configuration options\n * @returns Delay in milliseconds before the next retry attempt\n */\n private getRetryDelay(\n retryCount: number,\n options: Required<RetryOptions>\n ): number {\n const baseDelay =\n options.retryDelay * Math.pow(options.backoffFactor, retryCount)\n const cappedDelay = Math.min(baseDelay, options.maxRetryDelay)\n\n // Add jitter (+-20%) to prevent thundering herd problem\n const jitterRange = cappedDelay * 0.2\n const jitter = jitterRange * (Math.random() * 2 - 1)\n const finalDelay = cappedDelay + jitter\n\n return Math.max(1, Math.floor(finalDelay))\n }\n\n /**\n * Merges provided retry options with default configuration\n *\n * @param retryOptions - Retry options to merge with defaults\n * @returns Complete retry configuration with all required properties\n */\n private getRetryOptions(\n retryOptions?: RetryOptions | boolean\n ): Required<RetryOptions> {\n if (retryOptions === false) {\n return {\n ...DEFAULT_RETRY_OPTIONS,\n maxRetries: 0,\n }\n }\n\n if (retryOptions === true) {\n return {\n ...DEFAULT_RETRY_OPTIONS,\n ...this.defaultRetryOptions,\n }\n }\n\n if (typeof retryOptions === 'object') {\n return {\n ...DEFAULT_RETRY_OPTIONS,\n ...this.defaultRetryOptions,\n ...retryOptions,\n }\n }\n\n return {\n ...DEFAULT_RETRY_OPTIONS,\n ...this.defaultRetryOptions,\n }\n }\n\n /**\n * Creates a promise that resolves after the specified delay\n *\n * @param ms - Delay duration in milliseconds\n * @returns Promise that resolves after the delay\n */\n private sleep(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms))\n }\n\n /**\n * Makes an HTTP request with automatic retry capability\n *\n * @param method - HTTP method to use for the request\n * @param url - URL path for the request (supports path parameters)\n * @param options - Request configuration options\n * @returns Promise resolving to the response data with data extraction method\n *\n * @example\n * ```ts\n * // Simple GET request\n * const response = await client.request('GET', '/users/1');\n *\n * // POST request with body and path parameters\n * const response = await client.request('POST', '/users/:id/posts', {\n * pathParams: { id: 1 },\n * body: { title: 'New Post', content: 'Hello World' },\n * schema: userPostSchema\n * });\n *\n * // Data extraction\n * const user = await client.request('GET', '/users/1', { schema: userSchema }).data();\n * ```\n */\n public request<\n Path extends string = string,\n TResponse = unknown,\n TBody = unknown,\n TParams extends RequestParamsType = RequestParamsType,\n >(\n method: HttpMethod,\n url: Path,\n options: TypedRequestOptions<TBody, TResponse, TParams, Path> = {}\n ): ResponsePromise<TResponse> {\n return wrapResponsePromise(\n this.requestWithRetry<Path, TResponse, TBody, TParams>(\n method,\n url,\n options\n )\n )\n }\n\n /**\n * Internal method that handles retry logic for requests\n */\n private async requestWithRetry<\n Path extends string = string,\n TResponse = unknown,\n TBody = unknown,\n TParams extends RequestParamsType = RequestParamsType,\n >(\n method: HttpMethod,\n url: Path,\n options: TypedRequestOptions<TBody, TResponse, TParams, Path>\n ): Promise<ResponseType<TResponse>> {\n let retryCount = 0\n\n while (true) {\n try {\n return await this.executeRequest<Path, TResponse, TBody, TParams>(\n method,\n url,\n options\n )\n } catch (error) {\n if (!(error instanceof Error)) {\n throw new NetworkError(String(error), undefined)\n }\n\n if (await this.shouldRetry(error, retryCount, options.retry)) {\n const retryOptions = this.getRetryOptions(options.retry)\n const delay = this.getRetryDelay(retryCount, retryOptions)\n await this.sleep(delay)\n\n retryCount++\n continue\n }\n\n throw error\n }\n }\n }\n\n /**\n * Executes a single HTTP request without retry logic\n *\n * @param method - HTTP method for the request\n * @param url - URL path with optional path parameters\n * @param options - Request configuration and validation options\n * @returns Promise resolving to the response data\n */\n private async executeRequest<\n Path extends string = string,\n TResponse = unknown,\n TBody = unknown,\n TParams extends RequestParamsType = RequestParamsType,\n >(\n method: HttpMethod,\n url: Path,\n options: TypedRequestOptions<TBody, TResponse, TParams, Path> = {}\n ): Promise<ResponseType<TResponse>> {\n let resolvedUrl = this.resolveUrl(url, options.pathParams)\n\n let requestContext: RequestContext<TBody> = {\n url: resolvedUrl,\n method,\n params: options.params,\n headers: this.prepareHeaders(options.headers),\n body: options.body,\n fetchOptions: {\n credentials: options.credentials,\n cache: options.cache,\n mode: options.mode,\n redirect: options.redirect,\n },\n }\n\n for (const interceptor of this.requestInterceptors) {\n try {\n requestContext = await interceptor(requestContext)\n } catch (error) {\n throw new InterceptorError(\n `Request interceptor failed: ${error instanceof Error ? error.message : String(error)}`,\n 'request',\n resolvedUrl,\n method,\n error instanceof Error ? error : undefined\n )\n }\n }\n\n resolvedUrl = requestContext.url\n\n if (\n requestContext.params &&\n Object.keys(requestContext.params).length > 0\n ) {\n const searchParams = new URLSearchParams()\n for (const [key, value] of Object.entries(requestContext.params)) {\n if (value !== undefined) {\n searchParams.append(key, String(value))\n }\n }\n const queryString = searchParams.toString()\n if (queryString) {\n resolvedUrl += (resolvedUrl.includes('?') ? '&' : '?') + queryString\n }\n }\n\n const requestInit: RequestInit = {\n method: requestContext.method,\n headers: requestContext.headers,\n ...requestContext.fetchOptions,\n }\n\n if (\n requestContext.body !== undefined &&\n (requestContext.method === 'POST' ||\n requestContext.method === 'PUT' ||\n requestContext.method === 'PATCH')\n ) {\n if (\n requestContext.body instanceof FormData ||\n requestContext.body instanceof Blob ||\n requestContext.body instanceof ArrayBuffer ||\n requestContext.body instanceof URLSearchParams ||\n typeof requestContext.body === 'string'\n ) {\n requestInit.body = requestContext.body as BodyInit\n } else {\n try {\n requestInit.body = JSON.stringify(requestContext.body)\n } catch (error) {\n throw new SerializationError(\n `Failed to serialize request body: ${error instanceof Error ? error.message : 'Invalid data structure'}`,\n error instanceof Error ? error : undefined\n )\n }\n }\n }\n\n const timeoutDuration = options.timeout || this.defaultTimeout\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), timeoutDuration)\n\n const requestSignal = requestContext.signal || options.signal\n let cleanupSignals: VoidFunction | undefined\n const signal = requestSignal\n ? (() => {\n const result = this.mergeAbortSignals(\n requestSignal,\n controller.signal\n )\n cleanupSignals = result.cleanup\n return result.signal\n })()\n : controller.signal\n\n try {\n const response = await fetch(resolvedUrl, {\n ...requestInit,\n signal,\n })\n\n let responseData = await this.processResponse<TResponse>(\n response,\n options,\n method,\n resolvedUrl\n )\n\n if (options.schema) {\n responseData.data = this.validateWithSchema<TResponse>(\n options.schema,\n responseData.data\n )\n }\n\n return responseData\n } catch (error) {\n if (\n (error instanceof DOMException && error.name === 'AbortError') ||\n (error instanceof Error && error.name === 'AbortError') ||\n (error instanceof Error &&\n error.message.toLowerCase().includes('timeout'))\n ) {\n throw new TimeoutError(\n `Request timed out after ${timeoutDuration}ms`,\n error instanceof Error ? error : undefined\n )\n }\n\n if (\n error instanceof HttpError ||\n error instanceof SchemaValidationError ||\n error instanceof InterceptorError ||\n error instanceof PathParameterError ||\n error instanceof SerializationError\n ) {\n throw error\n }\n\n throw new NetworkError(\n error instanceof Error ? error.message : String(error),\n error instanceof Error ? error : undefined\n )\n } finally {\n clearTimeout(timeoutId)\n cleanupSignals?.()\n }\n }\n\n private validateWithSchema<T>(\n schema: Schema<T>,\n data: unknown,\n errorPrefix = 'Response schema validation failed'\n ): T {\n try {\n return this.schemaValidator.validate(schema, data)\n } catch (error) {\n throw new SchemaValidationError(\n `${errorPrefix}: ${error instanceof Error ? error.message : 'Unknown error'}`,\n schema,\n data,\n error instanceof Error ? error : undefined\n )\n }\n }\n\n /**\n * Prepares headers for HTTP requests by merging default and custom headers\n *\n * @param customHeaders - Additional headers to include in the request\n * @returns Headers object with all headers properly set\n */\n private prepareHeaders(customHeaders: Record<string, string> = {}): Headers {\n const headers = new Headers()\n\n for (const [key, value] of Object.entries(this.defaultHeaders)) {\n if (value != null) {\n headers.set(key, String(value))\n }\n }\n\n for (const [key, value] of Object.entries(customHeaders)) {\n if (value != null) {\n headers.set(key, String(value))\n }\n }\n\n return headers\n }\n\n /**\n * Extracts headers from Headers object into a plain record\n *\n * @param headers - Headers object to extract from\n * @returns Record containing header key-value pairs\n */\n private extractHeaders(headers: Headers): Record<string, string> {\n const result: Record<string, string> = {}\n headers.forEach((value, key) => {\n result[key] = value\n })\n return result\n }\n\n /**\n * Creates an HttpError instance with response details\n *\n * @param response - The HTTP response that caused the error\n * @param data - Response data (if any)\n * @param url - The URL that was requested\n * @param method - The HTTP method used\n * @param customStatusText - Optional custom status text\n * @param cause - Optional underlying error that caused this HTTP error\n * @returns HttpError instance with complete error information\n */\n private createHttpError(\n response: globalThis.Response,\n data: unknown,\n url: string,\n method: string,\n customStatusText?: string,\n cause?: Error\n ): HttpError {\n return new HttpError(\n `Request failed with status code ${response.status}`,\n response.status,\n customStatusText || response.statusText,\n data,\n response,\n url,\n method,\n cause\n )\n }\n\n private async parseResponseBody(\n response: globalThis.Response,\n options: RequestOptions\n ): Promise<unknown> {\n const contentType = response.headers.get('content-type') ?? ''\n\n try {\n if (options.responseType === 'text') {\n return await response.text()\n } else if (options.responseType === 'blob') {\n return await response.blob()\n } else if (options.responseType === 'arrayBuffer') {\n return await response.arrayBuffer()\n } else if (contentType.includes('application/json')) {\n const text = await response.text()\n if (!text) {\n return null\n }\n return JSON.parse(text)\n } else {\n return await response.text()\n }\n } catch (e) {\n if (response.status === 204) {\n return undefined\n }\n\n if (\n contentType.includes('application/json') &&\n e instanceof SyntaxError\n ) {\n throw new Error(`Failed to parse JSON response: ${e.message}`)\n }\n\n throw e\n }\n }\n\n private async processResponse<T, TBody = unknown>(\n response: globalThis.Response,\n options: TypedRequestOptions<TBody, T>,\n method: HttpMethod,\n url: string\n ): Promise<ResponseType<T>> {\n const headers = this.extractHeaders(response.headers)\n\n const validateStatus =\n options.validateStatus ||\n ((status: number) => status >= 200 && status < 300)\n\n const data = await this.parseResponseBody(response, options)\n\n if (!validateStatus(response.status)) {\n throw this.createHttpError(response, data, url, method)\n }\n\n const responseObj: ResponseType<unknown> = {\n data,\n status: response.status,\n statusText: response.statusText,\n headers,\n method,\n url,\n raw: response,\n }\n\n let processedResponse = responseObj\n const originalStatus = responseObj.status\n\n for (const interceptor of this.responseInterceptors) {\n try {\n processedResponse = await interceptor(processedResponse)\n } catch (error) {\n throw new InterceptorError(\n `Response interceptor failed: ${error instanceof Error ? error.message : String(error)}`,\n 'response',\n url,\n method,\n error instanceof Error ? error : undefined\n )\n }\n }\n\n // Only re-validate if interceptors changed the status\n if (\n processedResponse.status !== originalStatus &&\n !validateStatus(processedResponse.status)\n ) {\n throw this.createHttpError(\n response,\n processedResponse.data,\n url,\n method,\n processedResponse.statusText\n )\n }\n\n return processedResponse as ResponseType<T>\n }\n\n private mergeAbortSignals(\n signal1: AbortSignal,\n signal2: AbortSignal\n ): { signal: AbortSignal; cleanup?: VoidFunction } {\n if (signal1.aborted || signal2.aborted) {\n const controller = new AbortController()\n controller.abort()\n return { signal: controller.signal }\n }\n\n const controller = new AbortController()\n\n const abortHandler = () => {\n controller.abort()\n cleanup()\n }\n\n const cleanup = () => {\n signal1.removeEventListener('abort', abortHandler)\n signal2.removeEventListener('abort', abortHandler)\n }\n\n signal1.addEventListener('abort', abortHandler)\n signal2.addEventListener('abort', abortHandler)\n\n return { signal: controller.signal, cleanup }\n }\n\n /**\n * Send a GET request with schema validation (type inferred from schema).\n *\n * @example\n * // Get full response\n * const response = await client.get('/users/:id', {\n * pathParams: { id: '123' },\n * schema: z.object({ id: z.string(), name: z.string() })\n * })\n *\n * @example\n * // Extract data directly\n * const user = await client.get('/users/:id', {\n * pathParams: { id: '123' },\n * schema: userSchema\n * }).data()\n */\n public get<\n TResponse,\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n >(\n url: Path,\n options: EnforcedPathParamsOptions<void, TResponse, TParams, Path> & {\n schema: Schema<TResponse>\n }\n ): ResponsePromise<TResponse>\n\n /**\n * Send a GET request without schema (response.data is unknown).\n *\n * @example\n * const response = await client.get('/users')\n *\n * @example\n * const data = await client.get('/users').data()\n */\n public get<\n Path extends string,\n TParams extends RequestParamsType = RequestParamsType,\n >(\n url: Path,\n ...args: HasRequiredParams<Path> extends true\n ? [\n options: Omit<\n EnforcedPathParamsOptions<void, unknown, TParams, Path>,\n 'schema'\n >,\n ]\n : [\n options?: Omit<\n EnforcedPathParamsOptions<void, unknown, TParams, Path>,\n 'schema'\n >,\n ]\n ): ResponsePromise<unknown>\n\n public get<\n TResponse,\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n >(\n url: Path,\n options?: EnforcedPathParamsOptions<void, TResponse, TParams, Path>\n ): ResponsePromise<TResponse | unknown> {\n return this.request<Path, TResponse, void, TParams>(\n 'GET',\n url,\n options || {}\n )\n }\n\n /**\n * Send a POST request with schema validation (type inferred from schema).\n *\n * @example\n * const response = await client.post('/users', userData, {\n * schema: z.object({ id: z.string(), name: z.string() })\n * })\n *\n * @example\n * const user = await client.post('/users', userData, { schema: userSchema }).data()\n */\n public post<\n TResponse,\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n TBody = unknown,\n >(\n url: Path,\n body: TBody | undefined,\n options: Omit<\n EnforcedPathParamsOptions<TBody, TResponse, TParams, Path>,\n 'body'\n > & { schema: Schema<TResponse> }\n ): ResponsePromise<TResponse>\n\n /**\n * Send a POST request without schema (response.data is unknown).\n *\n * @example\n * const response = await client.post('/users', userData)\n *\n * @example\n * const data = await client.post('/users', userData).data()\n */\n public post<\n Path extends string,\n TParams extends RequestParamsType = RequestParamsType,\n TBody = unknown,\n >(\n url: Path,\n ...args: HasRequiredParams<Path> extends true\n ?\n | [\n body: TBody,\n options: Omit<\n EnforcedPathParamsOptions<TBody, unknown, TParams, Path>,\n 'body' | 'schema'\n >,\n ]\n | [\n body: undefined,\n options: Omit<\n EnforcedPathParamsOptions<TBody, unknown, TParams, Path>,\n 'body' | 'schema'\n >,\n ]\n : [\n body?: TBody,\n options?: Omit<\n EnforcedPathParamsOptions<TBody, unknown, TParams, Path>,\n 'body' | 'schema'\n >,\n ]\n ): ResponsePromise<unknown>\n\n public post<\n TResponse,\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n TBody = unknown,\n >(\n url: Path,\n body?: TBody,\n options?: Omit<\n EnforcedPathParamsOptions<TBody, TResponse, TParams, Path>,\n 'body'\n >\n ): ResponsePromise<TResponse | unknown> {\n return this.request<Path, TResponse, TBody, TParams>('POST', url, {\n ...(options || {}),\n body,\n })\n }\n\n /**\n * Send a PUT request with schema validation (type inferred from schema).\n *\n * @example\n * const response = await client.put('/users/:id', updatedData, {\n * pathParams: { id: '123' },\n * schema: z.object({ id: z.string(), name: z.string() })\n * })\n *\n * @example\n * const user = await client.put('/users/:id', updatedData, {\n * pathParams: { id: '123' },\n * schema: userSchema\n * }).data()\n */\n public put<\n TResponse,\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n TBody = unknown,\n >(\n url: Path,\n body: TBody | undefined,\n options: Omit<\n EnforcedPathParamsOptions<TBody, TResponse, TParams, Path>,\n 'body'\n > & { schema: Schema<TResponse> }\n ): ResponsePromise<TResponse>\n\n /**\n * Send a PUT request without schema (response.data is unknown).\n *\n * @example\n * const response = await client.put('/users/:id', updatedData, {\n * pathParams: { id: '123' }\n * })\n *\n * @example\n * const data = await client.put('/users/:id', updatedData, {\n * pathParams: { id: '123' }\n * }).data()\n */\n public put<\n Path extends string,\n TParams extends RequestParamsType = RequestParamsType,\n TBody = unknown,\n >(\n url: Path,\n ...args: HasRequiredParams<Path> extends true\n ?\n | [\n body: TBody,\n options: Omit<\n EnforcedPathParamsOptions<TBody, unknown, TParams, Path>,\n 'body' | 'schema'\n >,\n ]\n | [\n body: undefined,\n options: Omit<\n EnforcedPathParamsOptions<TBody, unknown, TParams, Path>,\n 'body' | 'schema'\n >,\n ]\n : [\n body?: TBody,\n options?: Omit<\n EnforcedPathParamsOptions<TBody, unknown, TParams, Path>,\n 'body' | 'schema'\n >,\n ]\n ): ResponsePromise<unknown>\n\n public put<\n TResponse,\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n TBody = unknown,\n >(\n url: Path,\n body?: TBody,\n options?: Omit<\n EnforcedPathParamsOptions<TBody, TResponse, TParams, Path>,\n 'body'\n >\n ): ResponsePromise<TResponse | unknown> {\n return this.request<Path, TResponse, TBody, TParams>('PUT', url, {\n ...(options || {}),\n body,\n })\n }\n\n /**\n * Send a PATCH request with schema validation (type inferred from schema).\n *\n * @example\n * const response = await client.patch('/users/:id', partialData, {\n * pathParams: { id: '123' },\n * schema: z.object({ id: z.string(), name: z.string() })\n * })\n *\n * @example\n * const user = await client.patch('/users/:id', partialData, {\n * pathParams: { id: '123' },\n * schema: userSchema\n * }).data()\n */\n public patch<\n TResponse,\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n TBody = unknown,\n >(\n url: Path,\n body: TBody | undefined,\n options: Omit<\n EnforcedPathParamsOptions<TBody, TResponse, TParams, Path>,\n 'body'\n > & { schema: Schema<TResponse> }\n ): ResponsePromise<TResponse>\n\n /**\n * Send a PATCH request without schema (response.data is unknown).\n *\n * @example\n * const response = await client.patch('/users/:id', partialData, {\n * pathParams: { id: '123' }\n * })\n *\n * @example\n * const data = await client.patch('/users/:id', partialData, {\n * pathParams: { id: '123' }\n * }).data()\n */\n public patch<\n Path extends string,\n TParams extends RequestParamsType = RequestParamsType,\n TBody = unknown,\n >(\n url: Path,\n ...args: HasRequiredParams<Path> extends true\n ?\n | [\n body: TBody,\n options: Omit<\n EnforcedPathParamsOptions<TBody, unknown, TParams, Path>,\n 'body' | 'schema'\n >,\n ]\n | [\n body: undefined,\n options: Omit<\n EnforcedPathParamsOptions<TBody, unknown, TParams, Path>,\n 'body' | 'schema'\n >,\n ]\n : [\n body?: TBody,\n options?: Omit<\n EnforcedPathParamsOptions<TBody, unknown, TParams, Path>,\n 'body' | 'schema'\n >,\n ]\n ): ResponsePromise<unknown>\n\n public patch<\n TResponse,\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n TBody = unknown,\n >(\n url: Path,\n body?: TBody,\n options?: Omit<\n EnforcedPathParamsOptions<TBody, TResponse, TParams, Path>,\n 'body'\n >\n ): ResponsePromise<TResponse | unknown> {\n return this.request<Path, TResponse, TBody, TParams>('PATCH', url, {\n ...(options || {}),\n body,\n })\n }\n\n /**\n * Send a DELETE request with schema validation (type inferred from schema).\n *\n * @example\n * const response = await client.delete('/users/:id', {\n * pathParams: { id: '123' },\n * schema: z.object({ success: z.boolean() })\n * })\n *\n * @example\n * const result = await client.delete('/users/:id', {\n * pathParams: { id: '123' },\n * schema: deleteResultSchema\n * }).data()\n */\n public delete<\n TResponse,\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n >(\n url: Path,\n options: EnforcedPathParamsOptions<void, TResponse, TParams, Path> & {\n schema: Schema<TResponse>\n }\n ): ResponsePromise<TResponse>\n\n /**\n * Send a DELETE request without schema (response.data is unknown).\n *\n * @example\n * const response = await client.delete('/users/:id', {\n * pathParams: { id: '123' }\n * })\n *\n * @example\n * const data = await client.delete('/users/:id', {\n * pathParams: { id: '123' }\n * }).data()\n */\n public delete<\n Path extends string,\n TParams extends RequestParamsType = RequestParamsType,\n >(\n url: Path,\n ...args: HasRequiredParams<Path> extends true\n ? [\n options: Omit<\n EnforcedPathParamsOptions<void, unknown, TParams, Path>,\n 'schema'\n >,\n ]\n : [\n options?: Omit<\n EnforcedPathParamsOptions<void, unknown, TParams, Path>,\n 'schema'\n >,\n ]\n ): ResponsePromise<unknown>\n\n public delete<\n TResponse,\n Path extends string = string,\n TParams extends RequestParamsType = RequestParamsType,\n >(\n url: Path,\n options?: EnforcedPathParamsOptions<void, TResponse, TParams, Path>\n ): ResponsePromise<TResponse | unknown> {\n return this.request<Path, TResponse, void, TParams>(\n 'DELETE',\n url,\n options || {}\n )\n }\n\n /**\n * Validates path parameters against the URL template\n *\n * @param url - URL template with path parameters (e.g., '/users/:id')\n * @param pathParams - Path parameters to validate\n * @throws Error if required path parameters are missing or invalid\n */\n private validatePathParams<Path extends string>(\n url: Path,\n pathParams?: PathParams<Path>\n ): void {\n if (!pathParams) {\n const requiredParams = this.extractRequiredPathParams(url)\n\n if (requiredParams.length > 0) {\n throw new PathParameterError(\n `Missing required path parameters for URL \"${url}\": ${requiredParams.join(', ')}. ` +\n `Please provide pathParams: { ${requiredParams.map(p => `${p}: value`).join(', ')} }`,\n url,\n requiredParams,\n []\n )\n }\n return\n }\n\n const requiredParams = this.extractRequiredPathParams(url)\n const providedParams = Object.keys(pathParams)\n\n const missingParams = requiredParams.filter(\n param => !providedParams.includes(param)\n )\n if (missingParams.length > 0) {\n throw new PathParameterError(\n `Missing required path parameters: ${missingParams.join(', ')}. ` +\n `Provided: ${providedParams.join(', ')}`,\n url,\n requiredParams,\n providedParams\n )\n }\n\n // const unusedParams = providedParams.filter(\n // param => !requiredParams.includes(param)\n // )\n // if (unusedParams.length > 0) {\n // console.warn(\n // `Unused path parameters provided: ${unusedParams.join(', ')}. ` +\n // `URL \"${url}\" does not contain these parameters.`\n // )\n // }\n }\n\n /**\n * Extracts required path parameters from a URL template\n *\n * @param url - URL template to extract parameters from\n * @returns Array of required parameter names\n */\n private extractRequiredPathParams(url: string): string[] {\n if (url.includes('?')) {\n throw new PathParameterError(\n 'Optional path parameters (e.g., :variable?) are not supported',\n url,\n [],\n []\n )\n }\n\n const matches = url.match(/:([a-zA-Z0-9_]+)/g)\n\n return matches ? matches.map(match => match.slice(1)) : []\n }\n\n /**\n * Resolves a URL template with path parameters and base URL\n *\n * @param url - URL template with optional path parameters\n * @param pathParams - Path parameters to interpolate into the URL\n * @returns Fully resolved URL with base URL and path parameters applied\n */\n private resolveUrl<Path extends string>(\n url: Path,\n pathParams?: PathParams<Path>\n ): string {\n this.validatePathParams(url, pathParams)\n\n const interpolatedUrl = pathParams ? generatePath(url, pathParams) : url\n\n if (/^https?:\\/\\//i.test(interpolatedUrl)) {\n return interpolatedUrl\n }\n\n const path = interpolatedUrl.startsWith('/')\n ? interpolatedUrl.slice(1)\n : interpolatedUrl\n\n return `${this.baseUrl}/${path}`\n }\n}\n","import {\n createStandardSchemaValidator as createStdSchemaValidator,\n isStandardSchema,\n} from './standard-schema'\n\nimport { Schema } from './types'\n\n/**\n * Interface for schema validators that can validate data against schemas.\n *\n * This interface allows you to create custom schema validators that work\n * with different validation libraries (Zod, Valibot, Arktype, etc.).\n */\nexport interface SchemaValidator {\n /**\n * Validate data against a schema.\n *\n * @template T - The expected type after validation\n * @param schema - The schema to validate against\n * @param data - The data to validate\n * @returns The validated data with the correct type\n * @throws {SchemaValidationError} If the data doesn't match the schema\n */\n validate<T>(schema: Schema<T>, data: unknown): T\n\n /**\n * Check if an object is a valid schema.\n *\n * @param obj - The object to check\n * @returns True if the object is a valid schema, false otherwise\n */\n isSchema(obj: unknown): boolean\n}\n\n/**\n * Create a default schema validator that supports Standard Schema.\n *\n * This validator only works with schemas that implement the Standard Schema\n * interface. For full support of Zod, Valibot, and Arktype, use the\n * appropriate validator from their respective packages.\n *\n * @returns A schema validator instance\n *\n * @example\n * ```ts\n * import { createSchemaValidator } from '1000fetches'\n *\n * const validator = createSchemaValidator();\n *\n * // Use with HttpClient\n * const client = new HttpClient({\n * schemaValidator: validator\n * });\n * ```\n */\nexport function createSchemaValidator(): SchemaValidator {\n return {\n validate<T>(schema: Schema<T>, data: unknown): T {\n if (!isStandardSchema(schema)) {\n throw new Error(\n 'Invalid schema: Schema must implement the Standard Schema interface'\n )\n }\n\n return createStdSchemaValidator().validate(schema, data)\n },\n\n isSchema(obj: unknown): boolean {\n return isStandardSchema(obj)\n },\n }\n}\n\nexport { createStdSchemaValidator as createStandardSchemaValidator }\n","import { PathParameterError } from '../errors'\n\n/**\n * Strips protocol from URL (e.g., https://, http://)\n */\ntype StripProtocol<T extends string> = T extends `${string}://${infer After}`\n ? After\n : T\n\n/**\n * Strips host and optional port from URL, keeping only the path\n * Handles cases like \"localhost:3000/users\" -> \"/users\"\n */\ntype StripHost<T extends string> = T extends `${infer _Host}/${infer Path}`\n ? `/${Path}`\n : T\n\n/**\n * Strips query string from path (e.g., \"/users?x=1\" -> \"/users\")\n * Only strips ? that comes after the path, not ? that's part of path parameters\n */\ntype StripQuery<T extends string> = T extends `${infer Path}?${infer Query}`\n ? Query extends `${string}=${string}` | `${string}=${string}&${string}`\n ? Path // Only strip if it looks like a query string (key=value)\n : T // Don't strip if it's part of a path parameter\n : T\n\n/**\n * Normalizes URL to path only, stripping protocol, host, port, and query\n */\ntype NormalizePath<T extends string> = StripQuery<StripHost<StripProtocol<T>>>\n\n/**\n * Removes optional suffix from param name (e.g., \"id?\" -> \"id\")\n * This makes optional params work seamlessly as required params\n */\ntype CleanParamName<S extends string> = S extends `${infer Name}?` ? Name : S\n\n/**\n * Extracts all path parameters from a route\n * Optional params like :id? are treated as required params (id)\n */\ntype ExtractRouteParams<T extends string> =\n NormalizePath<T> extends `${infer _Before}:${infer AfterColon}`\n ? AfterColon extends `${infer Param}/${infer Rest}`\n ? CleanParamName<Param> | ExtractRouteParams<`/${Rest}`>\n : CleanParamName<AfterColon>\n : never\n\nexport type HasRequiredParams<T extends string> = [\n ExtractRouteParams<T>,\n] extends [never]\n ? false\n : true\n\n/**\n * PathParams type - extracts parameter names and their types\n */\nexport type PathParams<Path extends string> = {\n [K in ExtractRouteParams<Path>]: string | number\n}\n\n/**\n * RequirePathParams enforces pathParams when needed\n * Optional params are seamlessly treated as required params\n */\nexport type RequirePathParams<Path extends string, T> =\n HasRequiredParams<Path> extends true\n ? T & { pathParams: PathParams<Path> }\n : T\n\n/**\n * Interpolates parameters into a URL template\n * Similar to React Router's generatePath function\n *\n * @example\n * ```ts\n * const path = generatePath('/users/:id/posts/:postId', { id: '123', postId: '456' });\n * // => '/users/123/posts/456'\n * ```\n */\nexport function generatePath<Path extends string>(\n path: Path,\n params: PathParams<Path> = {} as PathParams<Path>\n): string {\n return path.replace(/:([a-zA-Z0-9_]+)/g, (_match, paramName: string) => {\n if (params[paramName as keyof PathParams<Path>] === undefined) {\n throw new PathParameterError(\n `Missing required path parameter: ${paramName}`,\n path,\n [paramName],\n Object.keys(params)\n )\n }\n return String(params[paramName as keyof PathParams<Path>])\n })\n}\n"],"names":["HttpError","Error","name","status","statusText","data","response","url","method","cause","constructor","message","super","this","NetworkError","SchemaValidationError","schema","TimeoutError","PathParameterError","requiredParams","providedParams","InterceptorError","interceptorType","SerializationError","isStandardSchema","obj","validate","version","vendor","createStandardSchemaValidator","adapter","parse","result","Promise","issues","errorMessages","Array","from","map","issue","join","value","standardSchemaAdapter","isSchema","DEFAULT_RETRY_OPTIONS","maxRetries","retryDelay","backoffFactor","retryStatusCodes","retryNetworkErrors","maxRetryDelay","shouldRetry","baseUrl","defaultHeaders","defaultTimeout","schemaValidator","requestInterceptors","responseInterceptors","defaultRetryOptions","options","hasLocation","window","location","origin","startsWith","URL","href","replace","endsWith","slice","validateAndNormalizeBaseUrl","headers","timeout","createStdSchemaValidator","retryOptions","addRequestInterceptor","interceptor","push","addResponseInterceptor","error","retryCount","getRetryOptions","retryError","console","warn","includes","getRetryDelay","baseDelay","Math","pow","cappedDelay","min","finalDelay","random","max","floor","sleep","ms","resolve","setTimeout","request","promise","wrappedPromise","async","wrapResponsePromise","requestWithRetry","executeRequest","String","retry","delay","resolvedUrl","resolveUrl","pathParams","requestContext","params","prepareHeaders","body","fetchOptions","credentials","cache","mode","redirect","Object","keys","length","searchParams","URLSearchParams","key","entries","append","queryString","toString","requestInit","FormData","Blob","ArrayBuffer","JSON","stringify","timeoutDuration","controller","AbortController","timeoutId","abort","requestSignal","signal","cleanupSignals","mergeAbortSignals","cleanup","fetch","responseData","processResponse","validateWithSchema","DOMException","toLowerCase","clearTimeout","errorPrefix","customHeaders","Headers","set","extractHeaders","forEach","createHttpError","customStatusText","parseResponseBody","contentType","get","responseType","text","blob","arrayBuffer","e","SyntaxError","validateStatus","responseObj","raw","processedResponse","originalStatus","signal1","signal2","aborted","abortHandler","removeEventListener","addEventListener","post","put","patch","validatePathParams","extractRequiredPathParams","p","missingParams","filter","param","matches","match","interpolatedUrl","path","_match","paramName","generatePath","test"],"mappings":"gFAOO,MAAMA,UACHC,MAGQC,KAAO,YACPC,OACAC,WACAC,KAC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