@indra211/exios 3.1.0 → 3.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -81,6 +81,7 @@ await exios.get(url, {
81
81
 
82
82
  - **Proxy:** `proxy` wins; `proxy: false` disables proxying; otherwise `HTTP_PROXY` / `HTTPS_PROXY` / `NO_PROXY` (and lowercase variants) are used, like axios. HTTPS targets go through a `CONNECT` tunnel, using the TLS options (`ca`, `rejectUnauthorized`, ...) of your `httpsAgent`. An `https:` proxy (`protocol: 'https'` or `HTTPS_PROXY=https://...`) is reached over TLS. Aborts and timeouts also tear down a `CONNECT` still in progress.
83
83
  - **Redirects:** 303, and 301/302 after a POST, become GET without a body; 307/308 resend the method and body (a one-shot stream body cannot be resent, so the 307/308 is returned). A redirect to another host or port, or from `https:` to `http:`, drops `Authorization`, `Cookie` and `Proxy-Authorization`. A redirect that would have to resend a one-shot stream body is returned instead of followed. Too many redirects reject with `ERR_FR_TOO_MANY_REDIRECTS` (never retried).
84
+ - **Protocols:** only `http:` and `https:`. Any other URL (`file:`, `ftp:`, `data:`, ...), whether requested or reached through a redirect, rejects with `ERR_BAD_REQUEST` (`Unsupported protocol ftp:`) before anything is sent. A malformed `Location` header rejects with `ERR_BAD_RESPONSE`.
84
85
  - **Network errors** keep `code: 'ERR_NETWORK'` (retry and the breaker depend on it); the Node error is in `error.cause`, so `error.cause.code` is `ECONNREFUSED`, `ECONNRESET`, `ENOTFOUND`, ... (axios puts that in `error.code` instead).
85
86
  - **Bodies:** `FormData`, `Blob`, `URLSearchParams`, strings and typed arrays are buffered (so they are resent on retries and redirects, with an exact `Content-Length`); web `ReadableStream` and Node `Readable` bodies (including `fs` streams and the `form-data` package, whose `getHeaders()` boundary is used) are streamed and never retried. If a body stream fails, the request rejects with `ERR_BAD_REQUEST` (the stream's error is in `cause`), and an aborted or timed-out request destroys the body stream.
86
87
 
@@ -196,6 +197,10 @@ try {
196
197
  }
197
198
  ```
198
199
 
200
+ `isExiosError` narrows the error type. Pass your API's error body type to type `err.response.data`: `if (isExiosError<{ message: string }>(err)) err.response?.data.message`.
201
+
202
+ Every option accepts an explicit `undefined`, meaning "use the default". This also type-checks with TypeScript's `exactOptionalPropertyTypes`, so `retry: { retries: process.env.RETRIES ? Number(process.env.RETRIES) : undefined }` works.
203
+
199
204
  `meta.url` is `baseURL + url` without the serialized `params`. A query string you wrote into `url` yourself is kept.
200
205
 
201
206
  `error.toJSON()` (and so `JSON.stringify(error)`) is **log-safe**: the values of `Authorization`, `Proxy-Authorization`, `Cookie`, `Set-Cookie`, `X-Api-Key`, `X-Auth-Token`, `X-XSRF-Token` and `X-CSRF-Token`, `auth.password`, proxy credentials and the request body are replaced with `"[REDACTED]"`. The error object itself (`error.config`) is not modified.
@@ -265,10 +270,10 @@ const [a, b] = await Promise.all([api.get("/me"), api.get("/me")]); // one netwo
265
270
  b.meta.deduped; // true
266
271
  ```
267
272
 
268
- - **What counts as identical:** same method, URL, params, headers, `auth` and `responseType`. Requests with different `Authorization` headers are never shared.
273
+ - **What counts as identical:** same method, URL, params, headers, `auth` and `responseType`, and the same request policy: `timeout`, `totalTimeout`, `validateStatus`, `transformResponse`, `responseEncoding`, `retry`, `breaker`, `adapter` and size limits. The shared request runs with one caller's settings, so callers with different settings never share it. Functions match by identity: the instance's shared defaults match; an inline arrow function written per call does not. Requests with different `Authorization` headers are never shared.
269
274
  - **Methods:** only `GET` and `HEAD` are deduplicated, unless you list others in `dedupe: { methods: [...] }`. Requests with a body, and `responseType: 'stream'`, are never shared.
270
275
  - **Cancellation:** each caller keeps its own `signal` / `CancelToken`. A caller that aborts is rejected at once, and the others still get the response. The network request is aborted only when **every** caller has aborted.
271
- - **Separate results:** every caller gets its own response object, with its own `requestId` and a cloned copy of `data`, and runs its own response interceptors. Errors are passed to every caller.
276
+ - **Separate results:** every caller gets its own response object, with its own `requestId` and a cloned copy of `data`, and runs its own response interceptors. Errors are passed to every caller. When `data` can't be copied exactly (class instances, functions), callers share the same object: treat it as read-only.
272
277
  - **Custom key:** `dedupe: { key: (config) => string | undefined }`. Return `undefined` to skip deduplication for a request.
273
278
  - **Events:** lifecycle events and request interceptors see the first caller's request. `onDownloadProgress` / `onUploadProgress` fire only for that caller.
274
279
 
@@ -292,7 +297,8 @@ res.meta.cached; // true
292
297
  | `key` | method + URL + params + headers hash | `(config) => string \| undefined`; `undefined` skips the cache for that request |
293
298
  | `provider` | built-in memory LRU (100 entries) | Any object with `get` / `set` / `delete` / `clear` (sync or async), plus optional `keys` |
294
299
 
295
- - **What is stored:** only 2xx responses. Errors, request bodies, streams and data that `structuredClone` can't copy are never cached.
300
+ - **What is stored:** only 2xx responses. Errors, request bodies and streams are never cached. Neither is data that `structuredClone` can't copy exactly: class instances (for example from a custom `transformResponse`), functions, or Node `Buffer`s anywhere in the data. Plain objects, arrays, `Date`, `Map`, `Set`, `RegExp`, typed arrays, `ArrayBuffer` and `Blob` are fine.
301
+ - **Transforms:** the key includes `transformResponse` and `responseEncoding`, so differently transformed data is never mixed. An inline `transformResponse` written per call gets a new key each time, so it never hits the cache: define it once and reuse it.
296
302
  - **Isolated data:** every response read from the cache gets its own copy of `data`, so changing it can't affect the cache or other callers.
297
303
  - **Credentials:** the key includes a hash of the request headers and `auth`, so requests made with different credentials never share an entry. Secrets never appear in the key text.
298
304
  - **Cache-Control:** a response with `no-store` or `no-cache` is not stored, and `max-age` shortens the `ttl`. A request sent with `Cache-Control: no-cache` skips the read and refreshes the entry; `no-store` skips both the read and the write.
@@ -345,6 +351,7 @@ Also:
345
351
 
346
352
  ## Not supported
347
353
 
354
+ - `data:` URLs on the `http` adapter (axios decodes them; exios rejects them).
348
355
  - `maxRate` (bandwidth limits), `lookup` / `family` DNS options, HTTP/2 on the `http` adapter.
349
356
  - `redirect: 'manual' | 'error'` and `fetchOptions` on the `xhr` adapter (browsers' XHR always follows redirects); use `adapter: 'fetch'` when you need them.
350
357
  - Distributed or persisted breaker state.
package/dist/index.cjs CHANGED
@@ -239,8 +239,8 @@ function encode(s) {
239
239
  }
240
240
  function isPlainObject(v) {
241
241
  if (v === null || typeof v !== "object") return false;
242
- const proto = Object.getPrototypeOf(v);
243
- return proto === Object.prototype || proto === null;
242
+ const proto2 = Object.getPrototypeOf(v);
243
+ return proto2 === Object.prototype || proto2 === null;
244
244
  }
245
245
  function serializeParams(params, opts = {}) {
246
246
  if (params === void 0 || params === null) return "";
@@ -282,7 +282,17 @@ function buildFullPath(baseURL, url, allowAbsoluteUrls = true) {
282
282
  if (!baseURL) return u;
283
283
  if (allowAbsoluteUrls && ABSOLUTE_URL.test(u)) return u;
284
284
  if (!u) return baseURL;
285
- return `${baseURL.replace(/\/+$/, "")}/${u.replace(/^\/+/, "")}`;
285
+ return `${trimSlashes(baseURL, "end")}/${trimSlashes(u, "start")}`;
286
+ }
287
+ function trimSlashes(s, side) {
288
+ if (side === "start") {
289
+ let i = 0;
290
+ while (s.charCodeAt(i) === 47) i++;
291
+ return s.slice(i);
292
+ }
293
+ let j = s.length;
294
+ while (j > 0 && s.charCodeAt(j - 1) === 47) j--;
295
+ return s.slice(0, j);
286
296
  }
287
297
 
288
298
  // src/core/toFormData.ts
@@ -308,8 +318,8 @@ function toFormData(obj, fd = new FormData()) {
308
318
  // src/core/transforms.ts
309
319
  function isPlainObject2(v) {
310
320
  if (v === null || typeof v !== "object") return false;
311
- const proto = Object.getPrototypeOf(v);
312
- return proto === Object.prototype || proto === null;
321
+ const proto2 = Object.getPrototypeOf(v);
322
+ return proto2 === Object.prototype || proto2 === null;
313
323
  }
314
324
  function isPassThrough(data) {
315
325
  return typeof FormData !== "undefined" && data instanceof FormData || typeof Blob !== "undefined" && data instanceof Blob || data instanceof ArrayBuffer || ArrayBuffer.isView(data) || typeof ReadableStream !== "undefined" && data instanceof ReadableStream || data instanceof URLSearchParams || isNodeStream(data);
@@ -2030,26 +2040,57 @@ function requestTarget(config) {
2030
2040
  );
2031
2041
  return `${(config.method ?? "get").toUpperCase()} ${url}`;
2032
2042
  }
2033
- function defaultRequestKey(config) {
2043
+ function defaultRequestKey(config, scope = "cache") {
2034
2044
  const skip = config.correlationIdHeader?.toLowerCase();
2035
2045
  const parts = [];
2036
2046
  for (const k of Object.keys(config.headers).sort())
2037
2047
  if (k !== skip && !CACHE_DIRECTIVE_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
2038
2048
  if (config.auth) parts.push(`auth:${config.auth.username}:${config.auth.password}`);
2039
2049
  parts.push(`rt:${config.responseType ?? ""}`);
2050
+ parts.push(
2051
+ `shape:${fingerprint([config.transformResponse, config.responseEncoding, config.decompress])}`
2052
+ );
2053
+ if (scope === "dedupe") {
2054
+ parts.push(
2055
+ `policy:${fingerprint([
2056
+ config.timeout,
2057
+ config.totalTimeout,
2058
+ config.validateStatus,
2059
+ config.retry,
2060
+ config.breaker,
2061
+ config.adapter,
2062
+ config.maxContentLength,
2063
+ config.maxRedirects,
2064
+ config.transitional
2065
+ ])}`
2066
+ );
2067
+ }
2040
2068
  return `${requestTarget(config)} #${hash(parts.join("\n"))}`;
2041
2069
  }
2070
+ var fnIds = /* @__PURE__ */ new WeakMap();
2071
+ var nextFnId = 0;
2072
+ function fingerprint(v) {
2073
+ if (typeof v === "function") {
2074
+ let id = fnIds.get(v);
2075
+ if (id === void 0) fnIds.set(v, id = ++nextFnId);
2076
+ return `f${id}`;
2077
+ }
2078
+ if (v === null || typeof v !== "object") return v === void 0 ? "u" : JSON.stringify(v);
2079
+ if (Array.isArray(v)) return `[${v.map(fingerprint).join(",")}]`;
2080
+ const o = v;
2081
+ return `{${Object.keys(o).filter((k) => o[k] !== void 0).sort().map((k) => `${k}:${fingerprint(o[k])}`).join(",")}}`;
2082
+ }
2042
2083
  function keyURL(key) {
2043
2084
  const sp = key.indexOf(" ");
2044
2085
  const h = key.lastIndexOf(" #");
2045
2086
  return sp > 0 && h > sp ? key.slice(sp + 1, h) : void 0;
2046
2087
  }
2047
- function keyFor(config, opts) {
2088
+ function keyFor(config, opts, scope = "cache") {
2048
2089
  if (!opts.methods.includes(config.method)) return void 0;
2049
2090
  if (config.responseType === "stream") return void 0;
2050
2091
  if (opts.key) return opts.key(config);
2051
2092
  if (config.data !== void 0) return void 0;
2052
- return defaultRequestKey(config);
2093
+ return defaultRequestKey(config, scope);
2053
2094
  }
2054
2095
  function checkMethods(name, m) {
2055
2096
  if (!Array.isArray(m)) bad(name, m, "an array");
@@ -2094,12 +2135,46 @@ function parseCacheControl(value) {
2094
2135
  function cloneData(data) {
2095
2136
  if (data === null || typeof data !== "object") return { ok: true, value: data };
2096
2137
  if (typeof structuredClone !== "function") return { ok: false, value: data };
2138
+ if (!clonesFaithfully(data, /* @__PURE__ */ new Set())) return { ok: false, value: data };
2097
2139
  try {
2098
2140
  return { ok: true, value: structuredClone(data) };
2099
2141
  } catch {
2100
2142
  return { ok: false, value: data };
2101
2143
  }
2102
2144
  }
2145
+ var proto = (v) => Object.getPrototypeOf(v);
2146
+ var VIEW_TYPES = [
2147
+ "Int8Array",
2148
+ "Uint8Array",
2149
+ "Uint8ClampedArray",
2150
+ "Int16Array",
2151
+ "Uint16Array",
2152
+ "Int32Array",
2153
+ "Uint32Array",
2154
+ "Float32Array",
2155
+ "Float64Array",
2156
+ "BigInt64Array",
2157
+ "BigUint64Array",
2158
+ "DataView"
2159
+ ];
2160
+ var isType = (v, name) => {
2161
+ const C = globalThis[name];
2162
+ return typeof C === "function" && v instanceof C;
2163
+ };
2164
+ function clonesFaithfully(v, seen) {
2165
+ if (typeof v === "function" || typeof v === "symbol") return false;
2166
+ if (v === null || typeof v !== "object") return true;
2167
+ if (seen.has(v)) return true;
2168
+ seen.add(v);
2169
+ if (Array.isArray(v)) return proto(v) === Array.prototype && v.every((x) => clonesFaithfully(x, seen));
2170
+ if (v instanceof Map) return proto(v) === Map.prototype && [...v].every(([k, x]) => clonesFaithfully(k, seen) && clonesFaithfully(x, seen));
2171
+ if (v instanceof Set) return proto(v) === Set.prototype && [...v].every((x) => clonesFaithfully(x, seen));
2172
+ const p = proto(v);
2173
+ if (p === Object.prototype || p === null)
2174
+ return Object.values(v).every((x) => clonesFaithfully(x, seen));
2175
+ return p === Date.prototype || p === RegExp.prototype || p === ArrayBuffer.prototype || VIEW_TYPES.some((name) => p === globalThis[name]?.prototype) || // exact built-ins only: byte-array subclasses would come back as Uint8Array
2176
+ isType(v, "Blob") || isType(v, "FormData");
2177
+ }
2103
2178
  function reportCacheError(op, err) {
2104
2179
  if (typeof console !== "undefined") console.error(`[exios] cache provider ${op} failed:`, err);
2105
2180
  }
@@ -2254,7 +2329,7 @@ var Exios = class {
2254
2329
  const cacheCfg = resolveCache(config.cache);
2255
2330
  const dedupeCfg = resolveDedupe(config.dedupe);
2256
2331
  const cacheKey = cacheCfg ? keyFor(config, cacheCfg) : void 0;
2257
- const dedupeKey = dedupeCfg ? keyFor(config, dedupeCfg) : void 0;
2332
+ const dedupeKey = dedupeCfg ? keyFor(config, dedupeCfg, "dedupe") : void 0;
2258
2333
  const provider = cacheCfg ? cacheCfg.provider ?? this.memoryCache : void 0;
2259
2334
  const reqCC = cacheCfg && cacheCfg.respectCacheControl ? parseCacheControl(config.headers["cache-control"]) : void 0;
2260
2335
  if (cacheKey !== void 0 && provider && !reqCC?.has("no-cache") && !reqCC?.has("no-store")) {
package/dist/index.d.cts CHANGED
@@ -40,6 +40,7 @@ declare namespace exios {
40
40
  type DedupeConfig = Pkg.DedupeConfig;
41
41
  type ExiosCache = Pkg.ExiosCache;
42
42
  type MemoryCache = Pkg.MemoryCache;
43
+ type Options<T> = Pkg.Options<T>;
43
44
  type CanceledEvent = Pkg.CanceledEvent;
44
45
  type CircuitEvent = Pkg.CircuitEvent;
45
46
  type ErrorEvent = Pkg.ErrorEvent;
package/dist/index.d.ts CHANGED
@@ -29,7 +29,8 @@ declare class CircuitOpenError extends ExiosError {
29
29
  retryAt: number;
30
30
  constructor(origin: string, retryAt: number, config?: InternalConfig);
31
31
  }
32
- declare function isExiosError(v: unknown): v is ExiosError;
32
+ /** Type guard; pass the error body type to narrow `error.response.data`: `isExiosError<ApiError>(err)`. */
33
+ declare function isExiosError<T = any, D = any>(v: unknown): v is ExiosError<T, D>;
33
34
  /** Also true for a canceled error from another copy of the package (dual-package hazard). */
34
35
  declare function isCancel(v: unknown): v is CanceledError;
35
36
 
@@ -66,6 +67,13 @@ type RawHeaders = Record<string, HeaderValue> | Headers;
66
67
  type HeadersDefaults = {
67
68
  common: Record<string, HeaderValue>;
68
69
  } & Record<Lowercase<Method>, Record<string, HeaderValue>>;
70
+ /**
71
+ * Option object where every field may be omitted or set to `undefined` (= keep the default), so it
72
+ * also type-checks under `exactOptionalPropertyTypes`.
73
+ */
74
+ type Options<T> = {
75
+ [K in keyof T]?: T[K] | undefined;
76
+ };
69
77
  type AdapterName = "xhr" | "http" | "fetch";
70
78
  type AdapterFn = (config: InternalConfig) => Promise<ExiosResponse>;
71
79
  type AdapterConfig = AdapterName | AdapterFn | Array<AdapterName | AdapterFn>;
@@ -115,7 +123,7 @@ interface BreakerConfig {
115
123
  onStateChange?: (key: string, from: BreakerState, to: BreakerState) => void;
116
124
  }
117
125
  type BreakerState = "closed" | "open" | "half-open";
118
- type RequestBreakerOverride = false | Pick<Partial<BreakerConfig>, "key" | "isFailure">;
126
+ type RequestBreakerOverride = false | Pick<Options<BreakerConfig>, "key" | "isFailure">;
119
127
  interface ProgressEvent {
120
128
  loaded: number;
121
129
  total?: number;
@@ -129,94 +137,94 @@ interface ProgressEvent {
129
137
  }
130
138
  type Transformer = (this: InternalConfig, data: any, headers: Record<string, string>, status?: number) => any;
131
139
  interface ExiosRequestConfig<D = any> {
132
- url?: string;
133
- method?: Method;
134
- baseURL?: string;
135
- allowAbsoluteUrls?: boolean;
136
- headers?: RawHeaders | (Partial<HeadersDefaults> & Record<string, HeaderValue | Record<string, HeaderValue>>);
137
- params?: any;
140
+ url?: string | undefined;
141
+ method?: Method | undefined;
142
+ baseURL?: string | undefined;
143
+ allowAbsoluteUrls?: boolean | undefined;
144
+ headers?: RawHeaders | (Partial<HeadersDefaults> & Record<string, HeaderValue | Record<string, HeaderValue>>) | undefined;
145
+ params?: any | undefined;
138
146
  paramsSerializer?: ((params: any) => string) | {
139
147
  serialize?: (p: any) => string;
140
148
  indexes?: boolean | null;
141
149
  encode?: (s: string) => string;
142
- };
143
- data?: D;
144
- transformRequest?: Transformer | Transformer[];
145
- transformResponse?: Transformer | Transformer[];
146
- timeout?: number;
147
- timeoutErrorMessage?: string;
148
- withCredentials?: boolean;
150
+ } | undefined;
151
+ data?: D | undefined;
152
+ transformRequest?: Transformer | Transformer[] | undefined;
153
+ transformResponse?: Transformer | Transformer[] | undefined;
154
+ timeout?: number | undefined;
155
+ timeoutErrorMessage?: string | undefined;
156
+ withCredentials?: boolean | undefined;
149
157
  auth?: {
150
158
  username: string;
151
159
  password: string;
152
- };
153
- responseType?: ResponseType;
154
- responseEncoding?: string;
155
- validateStatus?: ((status: number) => boolean) | null;
156
- signal?: AbortSignal;
157
- onDownloadProgress?: (e: ProgressEvent) => void;
158
- maxContentLength?: number;
159
- maxBodyLength?: number;
160
+ } | undefined;
161
+ responseType?: ResponseType | undefined;
162
+ responseEncoding?: string | undefined;
163
+ validateStatus?: (((status: number) => boolean) | null) | undefined;
164
+ signal?: AbortSignal | undefined;
165
+ onDownloadProgress?: ((e: ProgressEvent) => void) | undefined;
166
+ maxContentLength?: number | undefined;
167
+ maxBodyLength?: number | undefined;
160
168
  transitional?: {
161
169
  silentJSONParsing?: boolean;
162
170
  clarifyTimeoutError?: boolean;
163
- };
164
- adapter?: AdapterConfig;
165
- onUploadProgress?: (e: ProgressEvent) => void;
166
- xsrfCookieName?: string;
167
- xsrfHeaderName?: string;
168
- withXSRFToken?: boolean | ((config: InternalConfig) => boolean | undefined);
171
+ } | undefined;
172
+ adapter?: AdapterConfig | undefined;
173
+ onUploadProgress?: ((e: ProgressEvent) => void) | undefined;
174
+ xsrfCookieName?: string | undefined;
175
+ xsrfHeaderName?: string | undefined;
176
+ withXSRFToken?: (boolean | ((config: InternalConfig) => boolean | undefined)) | undefined;
169
177
  /** @deprecated Use `signal` (AbortController), as in axios. */
170
- cancelToken?: CancelToken;
178
+ cancelToken?: CancelToken | undefined;
171
179
  /** Node http adapter: proxy server, or `false` to ignore HTTP(S)_PROXY env vars. */
172
- proxy?: ProxyConfig | false;
180
+ proxy?: ProxyConfig | false | undefined;
173
181
  /** Node http adapter: `http.Agent` used for http: URLs. */
174
- httpAgent?: unknown;
182
+ httpAgent?: unknown | undefined;
175
183
  /** Node http adapter: `https.Agent` used for https: URLs. */
176
- httpsAgent?: unknown;
184
+ httpsAgent?: unknown | undefined;
177
185
  /** Node http adapter: redirects to follow (default 21; 0 = return the 3xx). */
178
- maxRedirects?: number;
179
- beforeRedirect?: (options: Record<string, any>, responseDetails: {
186
+ maxRedirects?: number | undefined;
187
+ beforeRedirect?: ((options: Record<string, any>, responseDetails: {
180
188
  headers: Record<string, string | string[]>;
181
189
  statusCode: number;
182
- }) => void;
190
+ }) => void) | undefined;
183
191
  /** Node http adapter: unix socket path. */
184
- socketPath?: string | null;
192
+ socketPath?: string | null | undefined;
185
193
  /** Node http adapter: decode gzip/deflate/br responses (default true). */
186
- decompress?: boolean;
187
- insecureHTTPParser?: boolean;
188
- fetch?: typeof fetch;
189
- fetchOptions?: Omit<RequestInit, "body" | "headers" | "method" | "signal">;
190
- redirect?: RequestRedirect;
191
- retry?: false | Partial<RetryConfig>;
192
- breaker?: false | Partial<BreakerConfig>;
194
+ decompress?: boolean | undefined;
195
+ insecureHTTPParser?: boolean | undefined;
196
+ fetch?: typeof fetch | undefined;
197
+ fetchOptions?: Omit<RequestInit, "body" | "headers" | "method" | "signal"> | undefined;
198
+ redirect?: RequestRedirect | undefined;
199
+ retry?: false | Options<RetryConfig> | undefined;
200
+ breaker?: false | Options<BreakerConfig> | undefined;
193
201
  /** Id of this logical request (retries share it). Generated when not set. */
194
- requestId?: string;
202
+ requestId?: string | undefined;
195
203
  /** Id that ties this request to a wider operation; often set on an instance. */
196
- correlationId?: string;
204
+ correlationId?: string | undefined;
197
205
  /**
198
206
  * Send `correlationId` (or `requestId` when there is none) in this header, e.g. "x-correlation-id".
199
207
  * Off by default: an extra header can trigger a CORS preflight. A header the caller already set wins.
200
208
  */
201
- correlationIdHeader?: string;
209
+ correlationIdHeader?: string | undefined;
202
210
  /** Free-form data that travels with the request: readable in interceptors, events and adapters. Never sent. */
203
- metadata?: Record<string, unknown>;
211
+ metadata?: Record<string, unknown> | undefined;
204
212
  /**
205
213
  * Time limit (ms) for the whole logical request: every attempt, retry and backoff sleep.
206
214
  * `timeout` still limits each attempt. 0 / undefined = no limit. For `responseType: 'stream'` it ends
207
215
  * when the headers arrive.
208
216
  */
209
- totalTimeout?: number;
217
+ totalTimeout?: number | undefined;
210
218
  /** Share one in-flight request between identical concurrent requests (GET/HEAD by default). Off by default. */
211
- dedupe?: boolean | DedupeConfig;
219
+ dedupe?: boolean | DedupeConfig | undefined;
212
220
  /** Cache successful responses (GET/HEAD by default). Off by default. */
213
- cache?: boolean | Partial<CacheConfig>;
221
+ cache?: boolean | Options<CacheConfig> | undefined;
214
222
  }
215
223
  interface DedupeConfig {
216
224
  /** Methods that may be deduplicated. Default: ["get", "head"]. */
217
- methods?: Lowercase<Method>[];
225
+ methods?: Lowercase<Method>[] | undefined;
218
226
  /** Custom key; return undefined to not deduplicate this request. Default: method + URL + params + headers. */
219
- key?: (config: InternalConfig) => string | undefined;
227
+ key?: ((config: InternalConfig) => string | undefined) | undefined;
220
228
  }
221
229
  /** What a cache provider stores for one response. */
222
230
  interface CacheEntry {
@@ -256,8 +264,8 @@ interface CacheConfig {
256
264
  */
257
265
  interface ExiosDefaults<D = any> extends Omit<ExiosRequestConfig<D>, "headers" | "retry" | "breaker"> {
258
266
  headers: HeadersDefaults & Record<string, HeaderValue | Record<string, HeaderValue>>;
259
- retry: false | Partial<RetryConfig>;
260
- breaker: false | Partial<BreakerConfig>;
267
+ retry: false | Options<RetryConfig>;
268
+ breaker: false | Options<BreakerConfig>;
261
269
  }
262
270
  interface InternalConfig<D = any> extends Omit<ExiosRequestConfig<D>, "headers" | "retry" | "breaker"> {
263
271
  method: Lowercase<Method>;
@@ -502,4 +510,4 @@ declare const exios: ExiosDefault;
502
510
  declare const create: (config?: ExiosRequestConfig) => ExiosStatic;
503
511
 
504
512
  export { CancelToken, CanceledError, CircuitOpenError, ExiosError, InterceptorManager, MemoryCache, create, exios as default, isCancel, isExiosError, mergeConfig, toFormData };
505
- export type { AdapterConfig, AdapterFn, AdapterName, BreakerConfig, BreakerState, CacheConfig, CacheEntry, CacheProvider, CancelTokenSource, CanceledEvent, Canceler, CircuitEvent, DedupeConfig, ErrorEvent, ErrorMeta, ExiosCache, ExiosDefault, ExiosDefaults, ExiosEventListener, ExiosEventMap, ExiosEventName, ExiosInstance, ExiosRequestConfig, ExiosResponse, ExiosStatic, HeaderValue, HeadersDefaults, InterceptorHandler, InterceptorOptions, InternalConfig, Method, Outcome, ProgressEvent, ProxyConfig, RawHeaders, RequestBreakerOverride, RequestEvent, RequestEventBase, ResponseEvent, ResponseMeta, ResponseType, RetryConfig, RetryEvent, TimeoutEvent, Transformer };
513
+ export type { AdapterConfig, AdapterFn, AdapterName, BreakerConfig, BreakerState, CacheConfig, CacheEntry, CacheProvider, CancelTokenSource, CanceledEvent, Canceler, CircuitEvent, DedupeConfig, ErrorEvent, ErrorMeta, ExiosCache, ExiosDefault, ExiosDefaults, ExiosEventListener, ExiosEventMap, ExiosEventName, ExiosInstance, ExiosRequestConfig, ExiosResponse, ExiosStatic, HeaderValue, HeadersDefaults, InterceptorHandler, InterceptorOptions, InternalConfig, Method, Options, Outcome, ProgressEvent, ProxyConfig, RawHeaders, RequestBreakerOverride, RequestEvent, RequestEventBase, ResponseEvent, ResponseMeta, ResponseType, RetryConfig, RetryEvent, TimeoutEvent, Transformer };
package/dist/index.js CHANGED
@@ -213,8 +213,8 @@ function encode(s) {
213
213
  }
214
214
  function isPlainObject(v) {
215
215
  if (v === null || typeof v !== "object") return false;
216
- const proto = Object.getPrototypeOf(v);
217
- return proto === Object.prototype || proto === null;
216
+ const proto2 = Object.getPrototypeOf(v);
217
+ return proto2 === Object.prototype || proto2 === null;
218
218
  }
219
219
  function serializeParams(params, opts = {}) {
220
220
  if (params === void 0 || params === null) return "";
@@ -256,7 +256,17 @@ function buildFullPath(baseURL, url, allowAbsoluteUrls = true) {
256
256
  if (!baseURL) return u;
257
257
  if (allowAbsoluteUrls && ABSOLUTE_URL.test(u)) return u;
258
258
  if (!u) return baseURL;
259
- return `${baseURL.replace(/\/+$/, "")}/${u.replace(/^\/+/, "")}`;
259
+ return `${trimSlashes(baseURL, "end")}/${trimSlashes(u, "start")}`;
260
+ }
261
+ function trimSlashes(s, side) {
262
+ if (side === "start") {
263
+ let i = 0;
264
+ while (s.charCodeAt(i) === 47) i++;
265
+ return s.slice(i);
266
+ }
267
+ let j = s.length;
268
+ while (j > 0 && s.charCodeAt(j - 1) === 47) j--;
269
+ return s.slice(0, j);
260
270
  }
261
271
 
262
272
  // src/core/toFormData.ts
@@ -282,8 +292,8 @@ function toFormData(obj, fd = new FormData()) {
282
292
  // src/core/transforms.ts
283
293
  function isPlainObject2(v) {
284
294
  if (v === null || typeof v !== "object") return false;
285
- const proto = Object.getPrototypeOf(v);
286
- return proto === Object.prototype || proto === null;
295
+ const proto2 = Object.getPrototypeOf(v);
296
+ return proto2 === Object.prototype || proto2 === null;
287
297
  }
288
298
  function isPassThrough(data) {
289
299
  return typeof FormData !== "undefined" && data instanceof FormData || typeof Blob !== "undefined" && data instanceof Blob || data instanceof ArrayBuffer || ArrayBuffer.isView(data) || typeof ReadableStream !== "undefined" && data instanceof ReadableStream || data instanceof URLSearchParams || isNodeStream(data);
@@ -2004,26 +2014,57 @@ function requestTarget(config) {
2004
2014
  );
2005
2015
  return `${(config.method ?? "get").toUpperCase()} ${url}`;
2006
2016
  }
2007
- function defaultRequestKey(config) {
2017
+ function defaultRequestKey(config, scope = "cache") {
2008
2018
  const skip = config.correlationIdHeader?.toLowerCase();
2009
2019
  const parts = [];
2010
2020
  for (const k of Object.keys(config.headers).sort())
2011
2021
  if (k !== skip && !CACHE_DIRECTIVE_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
2012
2022
  if (config.auth) parts.push(`auth:${config.auth.username}:${config.auth.password}`);
2013
2023
  parts.push(`rt:${config.responseType ?? ""}`);
2024
+ parts.push(
2025
+ `shape:${fingerprint([config.transformResponse, config.responseEncoding, config.decompress])}`
2026
+ );
2027
+ if (scope === "dedupe") {
2028
+ parts.push(
2029
+ `policy:${fingerprint([
2030
+ config.timeout,
2031
+ config.totalTimeout,
2032
+ config.validateStatus,
2033
+ config.retry,
2034
+ config.breaker,
2035
+ config.adapter,
2036
+ config.maxContentLength,
2037
+ config.maxRedirects,
2038
+ config.transitional
2039
+ ])}`
2040
+ );
2041
+ }
2014
2042
  return `${requestTarget(config)} #${hash(parts.join("\n"))}`;
2015
2043
  }
2044
+ var fnIds = /* @__PURE__ */ new WeakMap();
2045
+ var nextFnId = 0;
2046
+ function fingerprint(v) {
2047
+ if (typeof v === "function") {
2048
+ let id = fnIds.get(v);
2049
+ if (id === void 0) fnIds.set(v, id = ++nextFnId);
2050
+ return `f${id}`;
2051
+ }
2052
+ if (v === null || typeof v !== "object") return v === void 0 ? "u" : JSON.stringify(v);
2053
+ if (Array.isArray(v)) return `[${v.map(fingerprint).join(",")}]`;
2054
+ const o = v;
2055
+ return `{${Object.keys(o).filter((k) => o[k] !== void 0).sort().map((k) => `${k}:${fingerprint(o[k])}`).join(",")}}`;
2056
+ }
2016
2057
  function keyURL(key) {
2017
2058
  const sp = key.indexOf(" ");
2018
2059
  const h = key.lastIndexOf(" #");
2019
2060
  return sp > 0 && h > sp ? key.slice(sp + 1, h) : void 0;
2020
2061
  }
2021
- function keyFor(config, opts) {
2062
+ function keyFor(config, opts, scope = "cache") {
2022
2063
  if (!opts.methods.includes(config.method)) return void 0;
2023
2064
  if (config.responseType === "stream") return void 0;
2024
2065
  if (opts.key) return opts.key(config);
2025
2066
  if (config.data !== void 0) return void 0;
2026
- return defaultRequestKey(config);
2067
+ return defaultRequestKey(config, scope);
2027
2068
  }
2028
2069
  function checkMethods(name, m) {
2029
2070
  if (!Array.isArray(m)) bad(name, m, "an array");
@@ -2068,12 +2109,46 @@ function parseCacheControl(value) {
2068
2109
  function cloneData(data) {
2069
2110
  if (data === null || typeof data !== "object") return { ok: true, value: data };
2070
2111
  if (typeof structuredClone !== "function") return { ok: false, value: data };
2112
+ if (!clonesFaithfully(data, /* @__PURE__ */ new Set())) return { ok: false, value: data };
2071
2113
  try {
2072
2114
  return { ok: true, value: structuredClone(data) };
2073
2115
  } catch {
2074
2116
  return { ok: false, value: data };
2075
2117
  }
2076
2118
  }
2119
+ var proto = (v) => Object.getPrototypeOf(v);
2120
+ var VIEW_TYPES = [
2121
+ "Int8Array",
2122
+ "Uint8Array",
2123
+ "Uint8ClampedArray",
2124
+ "Int16Array",
2125
+ "Uint16Array",
2126
+ "Int32Array",
2127
+ "Uint32Array",
2128
+ "Float32Array",
2129
+ "Float64Array",
2130
+ "BigInt64Array",
2131
+ "BigUint64Array",
2132
+ "DataView"
2133
+ ];
2134
+ var isType = (v, name) => {
2135
+ const C = globalThis[name];
2136
+ return typeof C === "function" && v instanceof C;
2137
+ };
2138
+ function clonesFaithfully(v, seen) {
2139
+ if (typeof v === "function" || typeof v === "symbol") return false;
2140
+ if (v === null || typeof v !== "object") return true;
2141
+ if (seen.has(v)) return true;
2142
+ seen.add(v);
2143
+ if (Array.isArray(v)) return proto(v) === Array.prototype && v.every((x) => clonesFaithfully(x, seen));
2144
+ if (v instanceof Map) return proto(v) === Map.prototype && [...v].every(([k, x]) => clonesFaithfully(k, seen) && clonesFaithfully(x, seen));
2145
+ if (v instanceof Set) return proto(v) === Set.prototype && [...v].every((x) => clonesFaithfully(x, seen));
2146
+ const p = proto(v);
2147
+ if (p === Object.prototype || p === null)
2148
+ return Object.values(v).every((x) => clonesFaithfully(x, seen));
2149
+ return p === Date.prototype || p === RegExp.prototype || p === ArrayBuffer.prototype || VIEW_TYPES.some((name) => p === globalThis[name]?.prototype) || // exact built-ins only: byte-array subclasses would come back as Uint8Array
2150
+ isType(v, "Blob") || isType(v, "FormData");
2151
+ }
2077
2152
  function reportCacheError(op, err) {
2078
2153
  if (typeof console !== "undefined") console.error(`[exios] cache provider ${op} failed:`, err);
2079
2154
  }
@@ -2228,7 +2303,7 @@ var Exios = class {
2228
2303
  const cacheCfg = resolveCache(config.cache);
2229
2304
  const dedupeCfg = resolveDedupe(config.dedupe);
2230
2305
  const cacheKey = cacheCfg ? keyFor(config, cacheCfg) : void 0;
2231
- const dedupeKey = dedupeCfg ? keyFor(config, dedupeCfg) : void 0;
2306
+ const dedupeKey = dedupeCfg ? keyFor(config, dedupeCfg, "dedupe") : void 0;
2232
2307
  const provider = cacheCfg ? cacheCfg.provider ?? this.memoryCache : void 0;
2233
2308
  const reqCC = cacheCfg && cacheCfg.respectCacheControl ? parseCacheControl(config.headers["cache-control"]) : void 0;
2234
2309
  if (cacheKey !== void 0 && provider && !reqCC?.has("no-cache") && !reqCC?.has("no-store")) {
@@ -173,8 +173,8 @@ function encode(s) {
173
173
  }
174
174
  function isPlainObject(v) {
175
175
  if (v === null || typeof v !== "object") return false;
176
- const proto = Object.getPrototypeOf(v);
177
- return proto === Object.prototype || proto === null;
176
+ const proto2 = Object.getPrototypeOf(v);
177
+ return proto2 === Object.prototype || proto2 === null;
178
178
  }
179
179
  function serializeParams(params, opts2 = {}) {
180
180
  if (params === void 0 || params === null) return "";
@@ -216,7 +216,17 @@ function buildFullPath(baseURL, url, allowAbsoluteUrls = true) {
216
216
  if (!baseURL) return u;
217
217
  if (allowAbsoluteUrls && ABSOLUTE_URL.test(u)) return u;
218
218
  if (!u) return baseURL;
219
- return `${baseURL.replace(/\/+$/, "")}/${u.replace(/^\/+/, "")}`;
219
+ return `${trimSlashes(baseURL, "end")}/${trimSlashes(u, "start")}`;
220
+ }
221
+ function trimSlashes(s, side) {
222
+ if (side === "start") {
223
+ let i = 0;
224
+ while (s.charCodeAt(i) === 47) i++;
225
+ return s.slice(i);
226
+ }
227
+ let j = s.length;
228
+ while (j > 0 && s.charCodeAt(j - 1) === 47) j--;
229
+ return s.slice(0, j);
220
230
  }
221
231
 
222
232
  // src/core/toFormData.ts
@@ -242,8 +252,8 @@ function toFormData(obj, fd = new FormData()) {
242
252
  // src/core/transforms.ts
243
253
  function isPlainObject2(v) {
244
254
  if (v === null || typeof v !== "object") return false;
245
- const proto = Object.getPrototypeOf(v);
246
- return proto === Object.prototype || proto === null;
255
+ const proto2 = Object.getPrototypeOf(v);
256
+ return proto2 === Object.prototype || proto2 === null;
247
257
  }
248
258
  function isPassThrough(data) {
249
259
  return typeof FormData !== "undefined" && data instanceof FormData || typeof Blob !== "undefined" && data instanceof Blob || data instanceof ArrayBuffer || ArrayBuffer.isView(data) || typeof ReadableStream !== "undefined" && data instanceof ReadableStream || data instanceof URLSearchParams || isNodeStream(data);
@@ -748,6 +758,7 @@ function canReplay(next) {
748
758
  }
749
759
 
750
760
  // src/adapters/http/index.ts
761
+ var SUPPORTED_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:"]);
751
762
  var CHUNK = 64 * 1024;
752
763
  var DEFAULT_ACCEPT_ENCODING = "gzip, compress, deflate, br";
753
764
  function requestOptions(hop, config) {
@@ -835,6 +846,8 @@ async function httpAdapter(config) {
835
846
  e.cause = err;
836
847
  throw e;
837
848
  }
849
+ if (!SUPPORTED_PROTOCOLS.has(url.protocol))
850
+ throw new ExiosError(`Unsupported protocol ${url.protocol}`, ExiosError.ERR_BAD_REQUEST, config);
838
851
  const hop = { url, method: prepared.method, headers, body };
839
852
  return new Promise((resolve, reject) => {
840
853
  const signal = config.signal;
@@ -929,7 +942,28 @@ async function httpAdapter(config) {
929
942
  async function onResponse(incoming) {
930
943
  const resHeaders = headersOf(incoming);
931
944
  const status = incoming.statusCode ?? 0;
932
- const next = maxRedirects > 0 ? nextRedirect(current, status, incoming.headers.location) : null;
945
+ let next = null;
946
+ if (maxRedirects > 0) {
947
+ try {
948
+ next = nextRedirect(current, status, incoming.headers.location);
949
+ } catch (err) {
950
+ incoming.resume();
951
+ const e = new ExiosError(
952
+ `Invalid redirect location: ${incoming.headers.location}`,
953
+ ExiosError.ERR_BAD_RESPONSE,
954
+ config,
955
+ req
956
+ );
957
+ e.cause = err;
958
+ return fail(e);
959
+ }
960
+ }
961
+ if (next && !SUPPORTED_PROTOCOLS.has(next.url.protocol)) {
962
+ incoming.resume();
963
+ return fail(
964
+ new ExiosError(`Unsupported protocol ${next.url.protocol}`, ExiosError.ERR_BAD_REQUEST, config, req)
965
+ );
966
+ }
933
967
  if (next && canReplay(next)) {
934
968
  if (++redirects > maxRedirects) {
935
969
  incoming.resume();
@@ -2564,26 +2598,57 @@ function requestTarget(config) {
2564
2598
  );
2565
2599
  return `${(config.method ?? "get").toUpperCase()} ${url}`;
2566
2600
  }
2567
- function defaultRequestKey(config) {
2601
+ function defaultRequestKey(config, scope = "cache") {
2568
2602
  const skip = config.correlationIdHeader?.toLowerCase();
2569
2603
  const parts = [];
2570
2604
  for (const k of Object.keys(config.headers).sort())
2571
2605
  if (k !== skip && !CACHE_DIRECTIVE_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
2572
2606
  if (config.auth) parts.push(`auth:${config.auth.username}:${config.auth.password}`);
2573
2607
  parts.push(`rt:${config.responseType ?? ""}`);
2608
+ parts.push(
2609
+ `shape:${fingerprint([config.transformResponse, config.responseEncoding, config.decompress])}`
2610
+ );
2611
+ if (scope === "dedupe") {
2612
+ parts.push(
2613
+ `policy:${fingerprint([
2614
+ config.timeout,
2615
+ config.totalTimeout,
2616
+ config.validateStatus,
2617
+ config.retry,
2618
+ config.breaker,
2619
+ config.adapter,
2620
+ config.maxContentLength,
2621
+ config.maxRedirects,
2622
+ config.transitional
2623
+ ])}`
2624
+ );
2625
+ }
2574
2626
  return `${requestTarget(config)} #${hash(parts.join("\n"))}`;
2575
2627
  }
2628
+ var fnIds = /* @__PURE__ */ new WeakMap();
2629
+ var nextFnId = 0;
2630
+ function fingerprint(v) {
2631
+ if (typeof v === "function") {
2632
+ let id = fnIds.get(v);
2633
+ if (id === void 0) fnIds.set(v, id = ++nextFnId);
2634
+ return `f${id}`;
2635
+ }
2636
+ if (v === null || typeof v !== "object") return v === void 0 ? "u" : JSON.stringify(v);
2637
+ if (Array.isArray(v)) return `[${v.map(fingerprint).join(",")}]`;
2638
+ const o = v;
2639
+ return `{${Object.keys(o).filter((k) => o[k] !== void 0).sort().map((k) => `${k}:${fingerprint(o[k])}`).join(",")}}`;
2640
+ }
2576
2641
  function keyURL(key) {
2577
2642
  const sp = key.indexOf(" ");
2578
2643
  const h = key.lastIndexOf(" #");
2579
2644
  return sp > 0 && h > sp ? key.slice(sp + 1, h) : void 0;
2580
2645
  }
2581
- function keyFor(config, opts2) {
2646
+ function keyFor(config, opts2, scope = "cache") {
2582
2647
  if (!opts2.methods.includes(config.method)) return void 0;
2583
2648
  if (config.responseType === "stream") return void 0;
2584
2649
  if (opts2.key) return opts2.key(config);
2585
2650
  if (config.data !== void 0) return void 0;
2586
- return defaultRequestKey(config);
2651
+ return defaultRequestKey(config, scope);
2587
2652
  }
2588
2653
  function checkMethods(name, m) {
2589
2654
  if (!Array.isArray(m)) bad(name, m, "an array");
@@ -2628,12 +2693,46 @@ function parseCacheControl(value) {
2628
2693
  function cloneData(data) {
2629
2694
  if (data === null || typeof data !== "object") return { ok: true, value: data };
2630
2695
  if (typeof structuredClone !== "function") return { ok: false, value: data };
2696
+ if (!clonesFaithfully(data, /* @__PURE__ */ new Set())) return { ok: false, value: data };
2631
2697
  try {
2632
2698
  return { ok: true, value: structuredClone(data) };
2633
2699
  } catch {
2634
2700
  return { ok: false, value: data };
2635
2701
  }
2636
2702
  }
2703
+ var proto = (v) => Object.getPrototypeOf(v);
2704
+ var VIEW_TYPES = [
2705
+ "Int8Array",
2706
+ "Uint8Array",
2707
+ "Uint8ClampedArray",
2708
+ "Int16Array",
2709
+ "Uint16Array",
2710
+ "Int32Array",
2711
+ "Uint32Array",
2712
+ "Float32Array",
2713
+ "Float64Array",
2714
+ "BigInt64Array",
2715
+ "BigUint64Array",
2716
+ "DataView"
2717
+ ];
2718
+ var isType = (v, name) => {
2719
+ const C = globalThis[name];
2720
+ return typeof C === "function" && v instanceof C;
2721
+ };
2722
+ function clonesFaithfully(v, seen) {
2723
+ if (typeof v === "function" || typeof v === "symbol") return false;
2724
+ if (v === null || typeof v !== "object") return true;
2725
+ if (seen.has(v)) return true;
2726
+ seen.add(v);
2727
+ if (Array.isArray(v)) return proto(v) === Array.prototype && v.every((x) => clonesFaithfully(x, seen));
2728
+ if (v instanceof Map) return proto(v) === Map.prototype && [...v].every(([k, x]) => clonesFaithfully(k, seen) && clonesFaithfully(x, seen));
2729
+ if (v instanceof Set) return proto(v) === Set.prototype && [...v].every((x) => clonesFaithfully(x, seen));
2730
+ const p = proto(v);
2731
+ if (p === Object.prototype || p === null)
2732
+ return Object.values(v).every((x) => clonesFaithfully(x, seen));
2733
+ return p === Date.prototype || p === RegExp.prototype || p === ArrayBuffer.prototype || VIEW_TYPES.some((name) => p === globalThis[name]?.prototype) || // exact built-ins only: byte-array subclasses would come back as Uint8Array
2734
+ isType(v, "Blob") || isType(v, "FormData");
2735
+ }
2637
2736
  function reportCacheError(op, err) {
2638
2737
  if (typeof console !== "undefined") console.error(`[exios] cache provider ${op} failed:`, err);
2639
2738
  }
@@ -2788,7 +2887,7 @@ var Exios = class {
2788
2887
  const cacheCfg = resolveCache(config.cache);
2789
2888
  const dedupeCfg = resolveDedupe(config.dedupe);
2790
2889
  const cacheKey = cacheCfg ? keyFor(config, cacheCfg) : void 0;
2791
- const dedupeKey = dedupeCfg ? keyFor(config, dedupeCfg) : void 0;
2890
+ const dedupeKey = dedupeCfg ? keyFor(config, dedupeCfg, "dedupe") : void 0;
2792
2891
  const provider = cacheCfg ? cacheCfg.provider ?? this.memoryCache : void 0;
2793
2892
  const reqCC = cacheCfg && cacheCfg.respectCacheControl ? parseCacheControl(config.headers["cache-control"]) : void 0;
2794
2893
  if (cacheKey !== void 0 && provider && !reqCC?.has("no-cache") && !reqCC?.has("no-store")) {
@@ -137,8 +137,8 @@ function encode(s) {
137
137
  }
138
138
  function isPlainObject(v) {
139
139
  if (v === null || typeof v !== "object") return false;
140
- const proto = Object.getPrototypeOf(v);
141
- return proto === Object.prototype || proto === null;
140
+ const proto2 = Object.getPrototypeOf(v);
141
+ return proto2 === Object.prototype || proto2 === null;
142
142
  }
143
143
  function serializeParams(params, opts2 = {}) {
144
144
  if (params === void 0 || params === null) return "";
@@ -180,7 +180,17 @@ function buildFullPath(baseURL, url, allowAbsoluteUrls = true) {
180
180
  if (!baseURL) return u;
181
181
  if (allowAbsoluteUrls && ABSOLUTE_URL.test(u)) return u;
182
182
  if (!u) return baseURL;
183
- return `${baseURL.replace(/\/+$/, "")}/${u.replace(/^\/+/, "")}`;
183
+ return `${trimSlashes(baseURL, "end")}/${trimSlashes(u, "start")}`;
184
+ }
185
+ function trimSlashes(s, side) {
186
+ if (side === "start") {
187
+ let i = 0;
188
+ while (s.charCodeAt(i) === 47) i++;
189
+ return s.slice(i);
190
+ }
191
+ let j = s.length;
192
+ while (j > 0 && s.charCodeAt(j - 1) === 47) j--;
193
+ return s.slice(0, j);
184
194
  }
185
195
 
186
196
  // src/core/toFormData.ts
@@ -206,8 +216,8 @@ function toFormData(obj, fd = new FormData()) {
206
216
  // src/core/transforms.ts
207
217
  function isPlainObject2(v) {
208
218
  if (v === null || typeof v !== "object") return false;
209
- const proto = Object.getPrototypeOf(v);
210
- return proto === Object.prototype || proto === null;
219
+ const proto2 = Object.getPrototypeOf(v);
220
+ return proto2 === Object.prototype || proto2 === null;
211
221
  }
212
222
  function isPassThrough(data) {
213
223
  return typeof FormData !== "undefined" && data instanceof FormData || typeof Blob !== "undefined" && data instanceof Blob || data instanceof ArrayBuffer || ArrayBuffer.isView(data) || typeof ReadableStream !== "undefined" && data instanceof ReadableStream || data instanceof URLSearchParams || isNodeStream(data);
@@ -712,6 +722,7 @@ function canReplay(next) {
712
722
  }
713
723
 
714
724
  // src/adapters/http/index.ts
725
+ var SUPPORTED_PROTOCOLS = /* @__PURE__ */ new Set(["http:", "https:"]);
715
726
  var CHUNK = 64 * 1024;
716
727
  var DEFAULT_ACCEPT_ENCODING = "gzip, compress, deflate, br";
717
728
  function requestOptions(hop, config) {
@@ -799,6 +810,8 @@ async function httpAdapter(config) {
799
810
  e.cause = err;
800
811
  throw e;
801
812
  }
813
+ if (!SUPPORTED_PROTOCOLS.has(url.protocol))
814
+ throw new ExiosError(`Unsupported protocol ${url.protocol}`, ExiosError.ERR_BAD_REQUEST, config);
802
815
  const hop = { url, method: prepared.method, headers, body };
803
816
  return new Promise((resolve, reject) => {
804
817
  const signal = config.signal;
@@ -893,7 +906,28 @@ async function httpAdapter(config) {
893
906
  async function onResponse(incoming) {
894
907
  const resHeaders = headersOf(incoming);
895
908
  const status = incoming.statusCode ?? 0;
896
- const next = maxRedirects > 0 ? nextRedirect(current, status, incoming.headers.location) : null;
909
+ let next = null;
910
+ if (maxRedirects > 0) {
911
+ try {
912
+ next = nextRedirect(current, status, incoming.headers.location);
913
+ } catch (err) {
914
+ incoming.resume();
915
+ const e = new ExiosError(
916
+ `Invalid redirect location: ${incoming.headers.location}`,
917
+ ExiosError.ERR_BAD_RESPONSE,
918
+ config,
919
+ req
920
+ );
921
+ e.cause = err;
922
+ return fail(e);
923
+ }
924
+ }
925
+ if (next && !SUPPORTED_PROTOCOLS.has(next.url.protocol)) {
926
+ incoming.resume();
927
+ return fail(
928
+ new ExiosError(`Unsupported protocol ${next.url.protocol}`, ExiosError.ERR_BAD_REQUEST, config, req)
929
+ );
930
+ }
897
931
  if (next && canReplay(next)) {
898
932
  if (++redirects > maxRedirects) {
899
933
  incoming.resume();
@@ -2528,26 +2562,57 @@ function requestTarget(config) {
2528
2562
  );
2529
2563
  return `${(config.method ?? "get").toUpperCase()} ${url}`;
2530
2564
  }
2531
- function defaultRequestKey(config) {
2565
+ function defaultRequestKey(config, scope = "cache") {
2532
2566
  const skip = config.correlationIdHeader?.toLowerCase();
2533
2567
  const parts = [];
2534
2568
  for (const k of Object.keys(config.headers).sort())
2535
2569
  if (k !== skip && !CACHE_DIRECTIVE_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
2536
2570
  if (config.auth) parts.push(`auth:${config.auth.username}:${config.auth.password}`);
2537
2571
  parts.push(`rt:${config.responseType ?? ""}`);
2572
+ parts.push(
2573
+ `shape:${fingerprint([config.transformResponse, config.responseEncoding, config.decompress])}`
2574
+ );
2575
+ if (scope === "dedupe") {
2576
+ parts.push(
2577
+ `policy:${fingerprint([
2578
+ config.timeout,
2579
+ config.totalTimeout,
2580
+ config.validateStatus,
2581
+ config.retry,
2582
+ config.breaker,
2583
+ config.adapter,
2584
+ config.maxContentLength,
2585
+ config.maxRedirects,
2586
+ config.transitional
2587
+ ])}`
2588
+ );
2589
+ }
2538
2590
  return `${requestTarget(config)} #${hash(parts.join("\n"))}`;
2539
2591
  }
2592
+ var fnIds = /* @__PURE__ */ new WeakMap();
2593
+ var nextFnId = 0;
2594
+ function fingerprint(v) {
2595
+ if (typeof v === "function") {
2596
+ let id = fnIds.get(v);
2597
+ if (id === void 0) fnIds.set(v, id = ++nextFnId);
2598
+ return `f${id}`;
2599
+ }
2600
+ if (v === null || typeof v !== "object") return v === void 0 ? "u" : JSON.stringify(v);
2601
+ if (Array.isArray(v)) return `[${v.map(fingerprint).join(",")}]`;
2602
+ const o = v;
2603
+ return `{${Object.keys(o).filter((k) => o[k] !== void 0).sort().map((k) => `${k}:${fingerprint(o[k])}`).join(",")}}`;
2604
+ }
2540
2605
  function keyURL(key) {
2541
2606
  const sp = key.indexOf(" ");
2542
2607
  const h = key.lastIndexOf(" #");
2543
2608
  return sp > 0 && h > sp ? key.slice(sp + 1, h) : void 0;
2544
2609
  }
2545
- function keyFor(config, opts2) {
2610
+ function keyFor(config, opts2, scope = "cache") {
2546
2611
  if (!opts2.methods.includes(config.method)) return void 0;
2547
2612
  if (config.responseType === "stream") return void 0;
2548
2613
  if (opts2.key) return opts2.key(config);
2549
2614
  if (config.data !== void 0) return void 0;
2550
- return defaultRequestKey(config);
2615
+ return defaultRequestKey(config, scope);
2551
2616
  }
2552
2617
  function checkMethods(name, m) {
2553
2618
  if (!Array.isArray(m)) bad(name, m, "an array");
@@ -2592,12 +2657,46 @@ function parseCacheControl(value) {
2592
2657
  function cloneData(data) {
2593
2658
  if (data === null || typeof data !== "object") return { ok: true, value: data };
2594
2659
  if (typeof structuredClone !== "function") return { ok: false, value: data };
2660
+ if (!clonesFaithfully(data, /* @__PURE__ */ new Set())) return { ok: false, value: data };
2595
2661
  try {
2596
2662
  return { ok: true, value: structuredClone(data) };
2597
2663
  } catch {
2598
2664
  return { ok: false, value: data };
2599
2665
  }
2600
2666
  }
2667
+ var proto = (v) => Object.getPrototypeOf(v);
2668
+ var VIEW_TYPES = [
2669
+ "Int8Array",
2670
+ "Uint8Array",
2671
+ "Uint8ClampedArray",
2672
+ "Int16Array",
2673
+ "Uint16Array",
2674
+ "Int32Array",
2675
+ "Uint32Array",
2676
+ "Float32Array",
2677
+ "Float64Array",
2678
+ "BigInt64Array",
2679
+ "BigUint64Array",
2680
+ "DataView"
2681
+ ];
2682
+ var isType = (v, name) => {
2683
+ const C = globalThis[name];
2684
+ return typeof C === "function" && v instanceof C;
2685
+ };
2686
+ function clonesFaithfully(v, seen) {
2687
+ if (typeof v === "function" || typeof v === "symbol") return false;
2688
+ if (v === null || typeof v !== "object") return true;
2689
+ if (seen.has(v)) return true;
2690
+ seen.add(v);
2691
+ if (Array.isArray(v)) return proto(v) === Array.prototype && v.every((x) => clonesFaithfully(x, seen));
2692
+ if (v instanceof Map) return proto(v) === Map.prototype && [...v].every(([k, x]) => clonesFaithfully(k, seen) && clonesFaithfully(x, seen));
2693
+ if (v instanceof Set) return proto(v) === Set.prototype && [...v].every((x) => clonesFaithfully(x, seen));
2694
+ const p = proto(v);
2695
+ if (p === Object.prototype || p === null)
2696
+ return Object.values(v).every((x) => clonesFaithfully(x, seen));
2697
+ return p === Date.prototype || p === RegExp.prototype || p === ArrayBuffer.prototype || VIEW_TYPES.some((name) => p === globalThis[name]?.prototype) || // exact built-ins only: byte-array subclasses would come back as Uint8Array
2698
+ isType(v, "Blob") || isType(v, "FormData");
2699
+ }
2601
2700
  function reportCacheError(op, err) {
2602
2701
  if (typeof console !== "undefined") console.error(`[exios] cache provider ${op} failed:`, err);
2603
2702
  }
@@ -2752,7 +2851,7 @@ var Exios = class {
2752
2851
  const cacheCfg = resolveCache(config.cache);
2753
2852
  const dedupeCfg = resolveDedupe(config.dedupe);
2754
2853
  const cacheKey = cacheCfg ? keyFor(config, cacheCfg) : void 0;
2755
- const dedupeKey = dedupeCfg ? keyFor(config, dedupeCfg) : void 0;
2854
+ const dedupeKey = dedupeCfg ? keyFor(config, dedupeCfg, "dedupe") : void 0;
2756
2855
  const provider = cacheCfg ? cacheCfg.provider ?? this.memoryCache : void 0;
2757
2856
  const reqCC = cacheCfg && cacheCfg.respectCacheControl ? parseCacheControl(config.headers["cache-control"]) : void 0;
2758
2857
  if (cacheKey !== void 0 && provider && !reqCC?.has("no-cache") && !reqCC?.has("no-store")) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@indra211/exios",
3
- "version": "3.1.0",
3
+ "version": "3.1.2",
4
4
  "description": "Zero-dependency axios-compatible HTTP client (XHR in browsers, Node http in Node, fetch fallback) with retry and a circuit breaker.",
5
5
  "license": "MIT",
6
6
  "author": {