@indra211/exios 2.0.1 → 3.1.0

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.
@@ -34,6 +34,36 @@ __export(cjs_node_exports, {
34
34
  });
35
35
  module.exports = __toCommonJS(cjs_node_exports);
36
36
 
37
+ // src/core/redact.ts
38
+ var REDACTED = "[REDACTED]";
39
+ var SENSITIVE_HEADERS = /* @__PURE__ */ new Set([
40
+ "authorization",
41
+ "proxy-authorization",
42
+ "cookie",
43
+ "set-cookie",
44
+ "x-api-key",
45
+ "x-auth-token",
46
+ "x-xsrf-token",
47
+ "x-csrf-token"
48
+ ]);
49
+ function redactHeaders(headers) {
50
+ if (!headers || typeof headers !== "object") return headers;
51
+ const out = {};
52
+ for (const [k, v] of Object.entries(headers))
53
+ out[k] = SENSITIVE_HEADERS.has(k.toLowerCase()) ? REDACTED : v;
54
+ return out;
55
+ }
56
+ function redactConfig(config) {
57
+ if (!config || typeof config !== "object") return config;
58
+ const c = { ...config };
59
+ if (c.headers && typeof c.headers === "object") c.headers = redactHeaders(c.headers);
60
+ if (c.auth) c.auth = { username: c.auth.username, password: REDACTED };
61
+ if (c.proxy && typeof c.proxy === "object" && c.proxy.auth)
62
+ c.proxy = { ...c.proxy, auth: { username: c.proxy.auth.username, password: REDACTED } };
63
+ if (c.data !== void 0) c.data = REDACTED;
64
+ return c;
65
+ }
66
+
37
67
  // src/errors/ExiosError.ts
38
68
  var ExiosError = class _ExiosError extends Error {
39
69
  static ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
@@ -63,13 +93,14 @@ var ExiosError = class _ExiosError extends Error {
63
93
  this.response = response;
64
94
  this.status = response?.status;
65
95
  }
96
+ /** Log-safe: credentials, sensitive headers (Authorization, Cookie, API keys) and the body are redacted. */
66
97
  toJSON() {
67
98
  return {
68
99
  message: this.message,
69
100
  name: this.name,
70
101
  code: this.code,
71
102
  status: this.status,
72
- config: this.config,
103
+ config: redactConfig(this.config),
73
104
  meta: this.meta,
74
105
  stack: this.stack
75
106
  };
@@ -169,8 +200,8 @@ function serializeParams(params, opts2 = {}) {
169
200
  return parts.join("&");
170
201
  }
171
202
  function buildURL(url, params, serializer) {
172
- const hash = url.indexOf("#");
173
- if (hash !== -1) url = url.slice(0, hash);
203
+ const hash2 = url.indexOf("#");
204
+ if (hash2 !== -1) url = url.slice(0, hash2);
174
205
  if (params === void 0 || params === null) return url;
175
206
  let serialized;
176
207
  if (typeof serializer === "function") serialized = serializer(params);
@@ -1743,14 +1774,16 @@ function defaultIsFailure(o) {
1743
1774
  return status >= 500 || status === 408 || status === 429;
1744
1775
  }
1745
1776
  var CircuitBreaker = class {
1746
- constructor(key, cfg, now = Date.now) {
1777
+ constructor(key, cfg, now = Date.now, onTransition) {
1747
1778
  this.key = key;
1748
1779
  this.cfg = cfg;
1749
1780
  this.now = now;
1781
+ this.onTransition = onTransition;
1750
1782
  }
1751
1783
  key;
1752
1784
  cfg;
1753
1785
  now;
1786
+ onTransition;
1754
1787
  _state = "closed";
1755
1788
  epoch = 0;
1756
1789
  openedAt = 0;
@@ -1854,22 +1887,25 @@ var CircuitBreaker = class {
1854
1887
  this.cfg.onStateChange?.(this.key, from, to);
1855
1888
  } catch {
1856
1889
  }
1890
+ this.onTransition?.(this.key, from, to);
1857
1891
  }
1858
1892
  };
1859
1893
  var BreakerRegistry = class {
1860
- constructor(getConfig, now = Date.now) {
1894
+ constructor(getConfig, now = Date.now, onTransition) {
1861
1895
  this.getConfig = getConfig;
1862
1896
  this.now = now;
1897
+ this.onTransition = onTransition;
1863
1898
  }
1864
1899
  getConfig;
1865
1900
  now;
1901
+ onTransition;
1866
1902
  breakers = /* @__PURE__ */ new Map();
1867
1903
  get(key) {
1868
1904
  const cfg = this.getConfig();
1869
1905
  if (cfg === false) return null;
1870
1906
  let b = this.breakers.get(key);
1871
1907
  if (!b) {
1872
- b = new CircuitBreaker(key, cfg, this.now);
1908
+ b = new CircuitBreaker(key, cfg, this.now, this.onTransition);
1873
1909
  this.breakers.set(key, b);
1874
1910
  }
1875
1911
  return b;
@@ -1974,6 +2010,7 @@ async function runWithRetry(attempt, cfg, config, hooks) {
1974
2010
  cancelBody(outcome.response?.data);
1975
2011
  if (hooks.signal?.aborted) throw abortError(hooks.signal);
1976
2012
  cfg.onRetry?.({ ...outcome, attempt: attempts, delayMs: delay });
2013
+ hooks.onRetry?.({ ...outcome, attempt: attempts, delayMs: delay });
1977
2014
  await sleep(delay, hooks.signal);
1978
2015
  hooks.beforeRetry?.();
1979
2016
  }
@@ -1995,7 +2032,7 @@ function defaultBreakerKey(config) {
1995
2032
  return full;
1996
2033
  }
1997
2034
  }
1998
- async function dispatchRequest(config, registry2) {
2035
+ async function dispatchRequest(config, registry2, observer) {
1999
2036
  const token = config.cancelToken;
2000
2037
  if (token) {
2001
2038
  if (token.reason) {
@@ -2012,7 +2049,8 @@ async function dispatchRequest(config, registry2) {
2012
2049
  try {
2013
2050
  const response = await dispatchRequest(
2014
2051
  { ...config, signal: joined.signal, cancelToken: void 0 },
2015
- registry2
2052
+ registry2,
2053
+ observer
2016
2054
  );
2017
2055
  if (isOneShotBody(response.data)) {
2018
2056
  response.data = whenBodyDone(response.data, release);
@@ -2031,6 +2069,7 @@ async function dispatchRequest(config, registry2) {
2031
2069
  const breaker = bcfg === false ? null : registry2.get(bcfg.key ? bcfg.key(config) : defaultBreakerKey(config));
2032
2070
  const ticket = breaker?.acquire(config);
2033
2071
  let attempts = 0;
2072
+ let responseTimeMs;
2034
2073
  try {
2035
2074
  let adapter;
2036
2075
  try {
@@ -2043,15 +2082,31 @@ async function dispatchRequest(config, registry2) {
2043
2082
  try {
2044
2083
  result = await runWithRetry(
2045
2084
  () => {
2046
- attempts++;
2047
- return adapter(config);
2085
+ const n = ++attempts;
2086
+ const t0 = Date.now();
2087
+ const failed = (e) => {
2088
+ responseTimeMs = Date.now() - t0;
2089
+ if (isExiosError(e)) observer?.onAttemptError?.(n, e);
2090
+ throw e;
2091
+ };
2092
+ let result2;
2093
+ try {
2094
+ result2 = Promise.resolve(adapter(config));
2095
+ } catch (e) {
2096
+ return failed(e);
2097
+ }
2098
+ return result2.then((r) => {
2099
+ responseTimeMs = Date.now() - t0;
2100
+ return r;
2101
+ }, failed);
2048
2102
  },
2049
2103
  ticket?.probe ? false : config.retry,
2050
2104
  // half-open probes get exactly one attempt
2051
2105
  config,
2052
2106
  {
2053
2107
  signal: config.signal,
2054
- beforeRetry: breaker && ticket ? () => breaker.check(ticket) : void 0
2108
+ beforeRetry: breaker && ticket ? () => breaker.check(ticket) : void 0,
2109
+ onRetry: observer?.onRetry
2055
2110
  }
2056
2111
  );
2057
2112
  } catch (e) {
@@ -2070,6 +2125,7 @@ async function dispatchRequest(config, registry2) {
2070
2125
  if (outcome.error) throw outcome.error;
2071
2126
  const response = outcome.response;
2072
2127
  response.meta.attempts = attempts;
2128
+ if (responseTimeMs !== void 0) response.meta.responseTimeMs = responseTimeMs;
2073
2129
  const { status } = response;
2074
2130
  if (config.validateStatus && !config.validateStatus(status)) {
2075
2131
  const err = new ExiosError(
@@ -2088,6 +2144,53 @@ async function dispatchRequest(config, registry2) {
2088
2144
  }
2089
2145
  }
2090
2146
 
2147
+ // src/core/events.ts
2148
+ var EventHub = class {
2149
+ listeners = /* @__PURE__ */ new Map();
2150
+ on(name, listener) {
2151
+ if (typeof listener !== "function")
2152
+ throw new TypeError(`exios: listener for "${name}" must be a function`);
2153
+ let set = this.listeners.get(name);
2154
+ if (!set) this.listeners.set(name, set = /* @__PURE__ */ new Set());
2155
+ set.add(listener);
2156
+ return () => this.off(name, listener);
2157
+ }
2158
+ once(name, listener) {
2159
+ const off = this.on(name, (e) => {
2160
+ off();
2161
+ listener(e);
2162
+ });
2163
+ return off;
2164
+ }
2165
+ off(name, listener) {
2166
+ const set = this.listeners.get(name);
2167
+ if (!set) return;
2168
+ if (listener === void 0) set.clear();
2169
+ else set.delete(listener);
2170
+ if (set.size === 0) this.listeners.delete(name);
2171
+ }
2172
+ has(name) {
2173
+ return this.listeners.has(name);
2174
+ }
2175
+ listenerCount(name) {
2176
+ return this.listeners.get(name)?.size ?? 0;
2177
+ }
2178
+ /** Build the payload only when someone listens: `emit('x', () => ({ ... }))`. */
2179
+ emit(name, payload) {
2180
+ const set = this.listeners.get(name);
2181
+ if (!set) return;
2182
+ const event = payload();
2183
+ for (const l of [...set]) {
2184
+ try {
2185
+ l(event);
2186
+ } catch (err) {
2187
+ if (typeof console !== "undefined")
2188
+ console.error(`[exios] "${name}" listener threw:`, err);
2189
+ }
2190
+ }
2191
+ }
2192
+ };
2193
+
2091
2194
  // src/core/InterceptorManager.ts
2092
2195
  var InterceptorManager = class {
2093
2196
  handlers = [];
@@ -2218,7 +2321,14 @@ var isPlainObject3 = (v) => {
2218
2321
  return p === Object.prototype || p === null;
2219
2322
  };
2220
2323
  var isBucket = (k) => HEADER_BUCKETS.includes(k.toLowerCase());
2221
- var SHALLOW_MERGE = /* @__PURE__ */ new Set(["auth", "transitional", "fetchOptions"]);
2324
+ var SHALLOW_MERGE = /* @__PURE__ */ new Set([
2325
+ "auth",
2326
+ "transitional",
2327
+ "fetchOptions",
2328
+ "metadata",
2329
+ "cache",
2330
+ "dedupe"
2331
+ ]);
2222
2332
  function setCI(target, k, v) {
2223
2333
  const lk = k.toLowerCase();
2224
2334
  for (const existing of Object.keys(target)) {
@@ -2324,7 +2434,231 @@ function assertRequestBreaker(b) {
2324
2434
  }
2325
2435
  }
2326
2436
 
2437
+ // src/core/dedupe.ts
2438
+ var InflightRequests = class {
2439
+ flights = /* @__PURE__ */ new Map();
2440
+ get size() {
2441
+ return this.flights.size;
2442
+ }
2443
+ /**
2444
+ * Join the flight for `key`, starting it with `start(signal)` when there is none. `start` receives a
2445
+ * signal owned by the flight, never a caller's. Resolves with `leader: true` for the caller that started it.
2446
+ */
2447
+ join(key, config, start) {
2448
+ const token = config.cancelToken;
2449
+ if (token?.reason) {
2450
+ token.reason.config ??= config;
2451
+ return Promise.reject(token.reason);
2452
+ }
2453
+ const tokenSignal = token?.toAbortSignal();
2454
+ const signals = [config.signal, tokenSignal].filter((s) => !!s);
2455
+ const aborted = signals.find((s) => s.aborted);
2456
+ if (aborted) {
2457
+ tokenSignal?.unsubscribe();
2458
+ return Promise.reject(abortError(aborted, config));
2459
+ }
2460
+ let flight = this.flights.get(key);
2461
+ const leader = !flight;
2462
+ if (!flight) {
2463
+ const controller = new AbortController();
2464
+ const f2 = { controller, subscribers: 0, promise: void 0 };
2465
+ f2.promise = start(controller.signal).finally(() => {
2466
+ if (this.flights.get(key) === f2) this.flights.delete(key);
2467
+ });
2468
+ this.flights.set(key, f2);
2469
+ flight = f2;
2470
+ }
2471
+ const f = flight;
2472
+ f.subscribers++;
2473
+ return new Promise((resolve, reject) => {
2474
+ let settled = false;
2475
+ const detach = () => {
2476
+ settled = true;
2477
+ for (const s of signals) s.removeEventListener("abort", onAbort);
2478
+ tokenSignal?.unsubscribe();
2479
+ };
2480
+ const onAbort = (ev) => {
2481
+ if (settled) return;
2482
+ detach();
2483
+ const reason = abortError(ev.target, config);
2484
+ reject(reason);
2485
+ if (--f.subscribers === 0) {
2486
+ if (this.flights.get(key) === f) this.flights.delete(key);
2487
+ f.controller.abort(reason);
2488
+ }
2489
+ };
2490
+ for (const s of signals) s.addEventListener("abort", onAbort, { once: true });
2491
+ f.promise.then(
2492
+ (response) => {
2493
+ if (settled) return;
2494
+ detach();
2495
+ f.subscribers--;
2496
+ resolve({ response, leader });
2497
+ },
2498
+ (err) => {
2499
+ if (settled) return;
2500
+ detach();
2501
+ f.subscribers--;
2502
+ reject(err);
2503
+ }
2504
+ );
2505
+ });
2506
+ }
2507
+ };
2508
+
2509
+ // src/core/requestCache.ts
2510
+ var SAFE_METHODS = Object.freeze(["get", "head"]);
2511
+ var MemoryCache = class {
2512
+ map = /* @__PURE__ */ new Map();
2513
+ maxEntries;
2514
+ constructor(options = {}) {
2515
+ const max = options.maxEntries ?? 100;
2516
+ if (!Number.isInteger(max) || max < 1) bad("maxEntries", max, "an integer >= 1");
2517
+ this.maxEntries = max;
2518
+ }
2519
+ get size() {
2520
+ return this.map.size;
2521
+ }
2522
+ get(key) {
2523
+ const entry = this.map.get(key);
2524
+ if (!entry) return void 0;
2525
+ this.map.delete(key);
2526
+ if (entry.expiresAt <= Date.now()) return void 0;
2527
+ this.map.set(key, entry);
2528
+ return entry;
2529
+ }
2530
+ set(key, entry) {
2531
+ this.map.delete(key);
2532
+ this.map.set(key, entry);
2533
+ while (this.map.size > this.maxEntries)
2534
+ this.map.delete(this.map.keys().next().value);
2535
+ }
2536
+ delete(key) {
2537
+ this.map.delete(key);
2538
+ }
2539
+ clear() {
2540
+ this.map.clear();
2541
+ }
2542
+ keys() {
2543
+ return [...this.map.keys()];
2544
+ }
2545
+ };
2546
+ function hash(str) {
2547
+ let h1 = 3735928559;
2548
+ let h2 = 1103547991;
2549
+ for (let i = 0; i < str.length; i++) {
2550
+ const ch = str.charCodeAt(i);
2551
+ h1 = Math.imul(h1 ^ ch, 2654435761);
2552
+ h2 = Math.imul(h2 ^ ch, 1597334677);
2553
+ }
2554
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
2555
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
2556
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
2557
+ }
2558
+ var CACHE_DIRECTIVE_HEADERS = /* @__PURE__ */ new Set(["cache-control", "pragma"]);
2559
+ function requestTarget(config) {
2560
+ const url = buildURL(
2561
+ buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls),
2562
+ config.params,
2563
+ config.paramsSerializer
2564
+ );
2565
+ return `${(config.method ?? "get").toUpperCase()} ${url}`;
2566
+ }
2567
+ function defaultRequestKey(config) {
2568
+ const skip = config.correlationIdHeader?.toLowerCase();
2569
+ const parts = [];
2570
+ for (const k of Object.keys(config.headers).sort())
2571
+ if (k !== skip && !CACHE_DIRECTIVE_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
2572
+ if (config.auth) parts.push(`auth:${config.auth.username}:${config.auth.password}`);
2573
+ parts.push(`rt:${config.responseType ?? ""}`);
2574
+ return `${requestTarget(config)} #${hash(parts.join("\n"))}`;
2575
+ }
2576
+ function keyURL(key) {
2577
+ const sp = key.indexOf(" ");
2578
+ const h = key.lastIndexOf(" #");
2579
+ return sp > 0 && h > sp ? key.slice(sp + 1, h) : void 0;
2580
+ }
2581
+ function keyFor(config, opts2) {
2582
+ if (!opts2.methods.includes(config.method)) return void 0;
2583
+ if (config.responseType === "stream") return void 0;
2584
+ if (opts2.key) return opts2.key(config);
2585
+ if (config.data !== void 0) return void 0;
2586
+ return defaultRequestKey(config);
2587
+ }
2588
+ function checkMethods(name, m) {
2589
+ if (!Array.isArray(m)) bad(name, m, "an array");
2590
+ return m.map((x) => String(x).toLowerCase());
2591
+ }
2592
+ function resolveDedupe(v) {
2593
+ if (v === void 0 || v === false) return false;
2594
+ if (v === true) return { methods: [...SAFE_METHODS] };
2595
+ if (typeof v !== "object" || v === null) bad("dedupe", v, "a boolean or an object");
2596
+ if (v.key !== void 0 && typeof v.key !== "function") bad("dedupe.key", v.key, "a function");
2597
+ return { methods: checkMethods("dedupe.methods", v.methods ?? SAFE_METHODS), key: v.key };
2598
+ }
2599
+ function resolveCache(v) {
2600
+ if (v === void 0 || v === false) return false;
2601
+ const o = v === true ? {} : v;
2602
+ if (typeof o !== "object" || o === null) bad("cache", v, "a boolean or an object");
2603
+ const ttl = o.ttl ?? 6e4;
2604
+ if (typeof ttl !== "number" || !(ttl > 0) || !Number.isFinite(ttl))
2605
+ bad("cache.ttl", ttl, "a finite number > 0");
2606
+ if (o.key !== void 0 && typeof o.key !== "function") bad("cache.key", o.key, "a function");
2607
+ const p = o.provider;
2608
+ if (p !== void 0 && (typeof p !== "object" || p === null || typeof p.get !== "function" || typeof p.set !== "function"))
2609
+ bad("cache.provider", p, "an object with get/set/delete/clear");
2610
+ return {
2611
+ ttl,
2612
+ methods: checkMethods("cache.methods", o.methods ?? SAFE_METHODS),
2613
+ key: o.key,
2614
+ provider: p,
2615
+ respectCacheControl: o.respectCacheControl ?? true
2616
+ };
2617
+ }
2618
+ function parseCacheControl(value) {
2619
+ const out = /* @__PURE__ */ new Map();
2620
+ const raw = Array.isArray(value) ? value.join(",") : value;
2621
+ if (typeof raw !== "string") return out;
2622
+ for (const part of raw.split(",")) {
2623
+ const [k, v] = part.split("=", 2).map((s) => s.trim());
2624
+ if (k) out.set(k.toLowerCase(), v === void 0 ? true : v.replace(/^"|"$/g, ""));
2625
+ }
2626
+ return out;
2627
+ }
2628
+ function cloneData(data) {
2629
+ if (data === null || typeof data !== "object") return { ok: true, value: data };
2630
+ if (typeof structuredClone !== "function") return { ok: false, value: data };
2631
+ try {
2632
+ return { ok: true, value: structuredClone(data) };
2633
+ } catch {
2634
+ return { ok: false, value: data };
2635
+ }
2636
+ }
2637
+ function reportCacheError(op, err) {
2638
+ if (typeof console !== "undefined") console.error(`[exios] cache provider ${op} failed:`, err);
2639
+ }
2640
+
2641
+ // src/core/requestId.ts
2642
+ var seq = 0;
2643
+ function createRequestId() {
2644
+ const c = globalThis.crypto;
2645
+ if (typeof c?.randomUUID === "function") {
2646
+ try {
2647
+ return c.randomUUID();
2648
+ } catch {
2649
+ }
2650
+ }
2651
+ seq = (seq + 1) % Number.MAX_SAFE_INTEGER;
2652
+ return `${Date.now().toString(36)}-${seq.toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
2653
+ }
2654
+
2327
2655
  // src/core/Exios.ts
2656
+ var CIRCUIT_EVENTS = {
2657
+ open: "circuitOpen",
2658
+ "half-open": "circuitHalfOpen",
2659
+ closed: "circuitClose"
2660
+ };
2661
+ var TIMEOUT_CODES = /* @__PURE__ */ new Set(["ECONNABORTED", "ETIMEDOUT"]);
2328
2662
  var isThenable = (v) => typeof v === "object" && v !== null && typeof v.then === "function";
2329
2663
  var Exios = class {
2330
2664
  defaults;
@@ -2334,15 +2668,71 @@ var Exios = class {
2334
2668
  };
2335
2669
  breaker;
2336
2670
  registry;
2671
+ events = new EventHub();
2672
+ memoryCache = new MemoryCache();
2673
+ inflight = new InflightRequests();
2674
+ /** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
2675
+ cache;
2337
2676
  constructor(defaults) {
2338
2677
  this.defaults = defaults;
2339
2678
  this.registry = new BreakerRegistry(
2340
- () => resolveBreaker(this.defaults.breaker)
2679
+ () => resolveBreaker(this.defaults.breaker),
2680
+ Date.now,
2681
+ (key, from, to) => this.events.emit(CIRCUIT_EVENTS[to], () => ({
2682
+ key,
2683
+ from,
2684
+ to,
2685
+ timestamp: Date.now()
2686
+ }))
2341
2687
  );
2342
2688
  this.breaker = {
2343
2689
  state: (key) => this.registry.state(key),
2344
2690
  reset: (key) => this.registry.reset(key)
2345
2691
  };
2692
+ const provider = () => {
2693
+ const c = this.defaults.cache;
2694
+ return typeof c === "object" && c?.provider || this.memoryCache;
2695
+ };
2696
+ this.cache = {
2697
+ clear: async () => {
2698
+ await provider().clear();
2699
+ },
2700
+ delete: async (key) => {
2701
+ await provider().delete(key);
2702
+ },
2703
+ key: (cfg = {}) => {
2704
+ const resolved = finalizeConfig(resolveConfig(mergeConfig(this.defaults, cfg)));
2705
+ const c = resolveCache(resolved.cache) || resolveCache(true);
2706
+ return c ? keyFor(resolved, c) : void 0;
2707
+ },
2708
+ invalidate: async (match) => {
2709
+ const p = provider();
2710
+ if (typeof p.keys !== "function")
2711
+ throw new ExiosError(
2712
+ "cache.invalidate needs a cache provider with keys()",
2713
+ ExiosError.ERR_NOT_SUPPORT
2714
+ );
2715
+ let test;
2716
+ if (typeof match === "function") test = match;
2717
+ else if (match instanceof RegExp) test = (k) => match.test(k);
2718
+ else {
2719
+ const target = requestTarget({ ...this.defaults, url: match, params: void 0 });
2720
+ const prefix = target.slice(target.indexOf(" ") + 1);
2721
+ test = (k) => {
2722
+ const u = keyURL(k);
2723
+ return u !== void 0 && (u === prefix || u.startsWith(prefix + "/") || u.startsWith(prefix + "?"));
2724
+ };
2725
+ }
2726
+ let n = 0;
2727
+ for (const k of [...await p.keys()]) {
2728
+ if (test(k)) {
2729
+ await p.delete(k);
2730
+ n++;
2731
+ }
2732
+ }
2733
+ return n;
2734
+ }
2735
+ };
2346
2736
  }
2347
2737
  async request(configOrUrl, config) {
2348
2738
  const cfg = typeof configOrUrl === "string" ? { ...config, url: configOrUrl } : { ...configOrUrl };
@@ -2355,7 +2745,7 @@ var Exios = class {
2355
2745
  synchronous = synchronous && h.synchronous;
2356
2746
  requestChain.unshift(h);
2357
2747
  });
2358
- const dispatch = (c) => dispatchRequest(finalizeConfig(c), this.registry);
2748
+ const dispatch = (c) => this.dispatch(finalizeConfig(c));
2359
2749
  let promise;
2360
2750
  if (synchronous) {
2361
2751
  promise = this.runSync(requestChain, resolved, dispatch);
@@ -2373,6 +2763,232 @@ var Exios = class {
2373
2763
  });
2374
2764
  return promise;
2375
2765
  }
2766
+ /** Subscribe to a lifecycle event; returns a function that unsubscribes. */
2767
+ on(name, listener) {
2768
+ return this.events.on(name, listener);
2769
+ }
2770
+ /** Like `on`, but the listener runs at most once. */
2771
+ once(name, listener) {
2772
+ return this.events.once(name, listener);
2773
+ }
2774
+ /** Remove one listener, or every listener of `name` when `listener` is omitted. */
2775
+ off(name, listener) {
2776
+ this.events.off(name, listener);
2777
+ }
2778
+ /**
2779
+ * After request interceptors: ids → cache read → dedupe → network → cache write.
2780
+ * Cache hits and deduplicated followers make no network request and emit no lifecycle events.
2781
+ */
2782
+ async dispatch(config) {
2783
+ const start = Date.now();
2784
+ config.requestId ??= createRequestId();
2785
+ const totalTimeout = config.totalTimeout ?? 0;
2786
+ if (typeof totalTimeout !== "number" || !(totalTimeout >= 0) || !Number.isFinite(totalTimeout))
2787
+ bad("totalTimeout", totalTimeout, "a non-negative finite number");
2788
+ const cacheCfg = resolveCache(config.cache);
2789
+ const dedupeCfg = resolveDedupe(config.dedupe);
2790
+ const cacheKey = cacheCfg ? keyFor(config, cacheCfg) : void 0;
2791
+ const dedupeKey = dedupeCfg ? keyFor(config, dedupeCfg) : void 0;
2792
+ const provider = cacheCfg ? cacheCfg.provider ?? this.memoryCache : void 0;
2793
+ const reqCC = cacheCfg && cacheCfg.respectCacheControl ? parseCacheControl(config.headers["cache-control"]) : void 0;
2794
+ if (cacheKey !== void 0 && provider && !reqCC?.has("no-cache") && !reqCC?.has("no-store")) {
2795
+ let entry;
2796
+ try {
2797
+ entry = await provider.get(cacheKey);
2798
+ } catch (e) {
2799
+ reportCacheError("get", e);
2800
+ }
2801
+ if (entry && entry.expiresAt > Date.now()) {
2802
+ const copy2 = cloneData(entry.data);
2803
+ return this.localResponse(config, start, {
2804
+ data: copy2.value,
2805
+ status: entry.status,
2806
+ statusText: entry.statusText,
2807
+ headers: { ...entry.headers },
2808
+ request: null,
2809
+ meta: { attempts: 0, cached: true }
2810
+ });
2811
+ }
2812
+ }
2813
+ const header = config.correlationIdHeader?.toLowerCase();
2814
+ if (header && config.headers[header] === void 0)
2815
+ config.headers = { ...config.headers, [header]: config.correlationId ?? config.requestId };
2816
+ const network = async (c) => {
2817
+ const response2 = await this.network(c, start, totalTimeout);
2818
+ if (cacheKey !== void 0 && provider && cacheCfg && !reqCC?.has("no-store"))
2819
+ this.store(provider, cacheKey, response2, cacheCfg);
2820
+ return response2;
2821
+ };
2822
+ if (dedupeKey === void 0) return network(config);
2823
+ const { response, leader } = await this.inflight.join(
2824
+ dedupeKey,
2825
+ config,
2826
+ (signal) => network({ ...config, signal, cancelToken: void 0 })
2827
+ );
2828
+ if (leader) return response;
2829
+ const copy = cloneData(response.data);
2830
+ return this.localResponse(config, start, {
2831
+ ...response,
2832
+ data: copy.value,
2833
+ headers: { ...response.headers },
2834
+ meta: { attempts: response.meta.attempts, deduped: true }
2835
+ });
2836
+ }
2837
+ /** A response made without a network request of its own (cache hit, deduplicated follower). */
2838
+ localResponse(config, start, r) {
2839
+ r.meta.requestId = config.requestId;
2840
+ if (config.correlationId !== void 0) r.meta.correlationId = config.correlationId;
2841
+ r.meta.durationMs = Date.now() - start;
2842
+ return { ...r, config };
2843
+ }
2844
+ /** Store a successful response; provider failures are reported, never thrown. */
2845
+ store(provider, key, response, cfg) {
2846
+ if (response.status < 200 || response.status >= 300) return;
2847
+ let ttl = cfg.ttl;
2848
+ if (cfg.respectCacheControl) {
2849
+ const cc = parseCacheControl(response.headers["cache-control"]);
2850
+ if (cc.has("no-store") || cc.has("no-cache")) return;
2851
+ const maxAge = Number(cc.get("max-age"));
2852
+ if (cc.has("max-age") && Number.isFinite(maxAge)) ttl = Math.min(ttl, maxAge * 1e3);
2853
+ }
2854
+ if (ttl <= 0) return;
2855
+ const copy = cloneData(response.data);
2856
+ if (!copy.ok) return;
2857
+ const now = Date.now();
2858
+ try {
2859
+ const r = provider.set(key, {
2860
+ status: response.status,
2861
+ statusText: response.statusText,
2862
+ headers: { ...response.headers },
2863
+ data: copy.value,
2864
+ storedAt: now,
2865
+ expiresAt: now + ttl
2866
+ });
2867
+ if (isThenable(r)) Promise.resolve(r).catch((e) => reportCacheError("set", e));
2868
+ } catch (e) {
2869
+ reportCacheError("set", e);
2870
+ }
2871
+ }
2872
+ /** totalTimeout, timing, error context and lifecycle events around dispatchRequest. */
2873
+ async network(config, start, totalTimeout) {
2874
+ const requestId = config.requestId;
2875
+ const { correlationId, metadata } = config;
2876
+ const hub = this.events;
2877
+ const url = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
2878
+ const base = () => ({
2879
+ requestId,
2880
+ correlationId,
2881
+ method: config.method,
2882
+ url,
2883
+ config,
2884
+ metadata,
2885
+ timestamp: Date.now()
2886
+ });
2887
+ const observer = {
2888
+ onRetry: (o) => hub.emit("retry", () => ({
2889
+ ...base(),
2890
+ attempt: o.attempt,
2891
+ delayMs: o.delayMs,
2892
+ error: o.error,
2893
+ status: o.response?.status ?? o.error?.response?.status
2894
+ })),
2895
+ onAttemptError: (attempt, error) => {
2896
+ if (TIMEOUT_CODES.has(error.code ?? ""))
2897
+ hub.emit("timeout", () => ({
2898
+ ...base(),
2899
+ kind: "attempt",
2900
+ attempt,
2901
+ timeoutMs: config.timeout ?? 0,
2902
+ error
2903
+ }));
2904
+ }
2905
+ };
2906
+ let timer;
2907
+ let totalFired = false;
2908
+ let joined;
2909
+ let dispatchConfig = config;
2910
+ if (totalTimeout > 0) {
2911
+ const ac = new AbortController();
2912
+ timer = setTimeout(() => {
2913
+ totalFired = true;
2914
+ ac.abort(new Error("totalTimeout"));
2915
+ }, totalTimeout);
2916
+ joined = combineSignals(config.signal, ac.signal);
2917
+ dispatchConfig = { ...config, signal: joined.signal };
2918
+ }
2919
+ let deferCleanup = false;
2920
+ hub.emit("request", base);
2921
+ try {
2922
+ let response;
2923
+ try {
2924
+ response = await dispatchRequest(dispatchConfig, this.registry, observer);
2925
+ } catch (e) {
2926
+ if (!totalFired || config.signal?.aborted || !isCancel(e)) throw e;
2927
+ const err = new ExiosError(
2928
+ `total timeout of ${totalTimeout}ms exceeded`,
2929
+ config.transitional?.clarifyTimeoutError ? ExiosError.ETIMEDOUT : ExiosError.ECONNABORTED,
2930
+ config,
2931
+ e.request
2932
+ );
2933
+ err.cause = e;
2934
+ err.meta.attempts = e.meta.attempts;
2935
+ hub.emit("timeout", () => ({
2936
+ ...base(),
2937
+ kind: "total",
2938
+ attempt: err.meta.attempts,
2939
+ timeoutMs: totalTimeout,
2940
+ error: err
2941
+ }));
2942
+ throw err;
2943
+ }
2944
+ if (joined && isOneShotBody(response.data)) {
2945
+ response.data = whenBodyDone(response.data, joined.cleanup);
2946
+ deferCleanup = true;
2947
+ }
2948
+ const durationMs = Date.now() - start;
2949
+ const meta = response.meta;
2950
+ meta.requestId = requestId;
2951
+ if (correlationId !== void 0) meta.correlationId = correlationId;
2952
+ meta.durationMs = durationMs;
2953
+ hub.emit("response", () => ({
2954
+ ...base(),
2955
+ response,
2956
+ status: response.status,
2957
+ attempts: meta.attempts,
2958
+ durationMs,
2959
+ responseTimeMs: meta.responseTimeMs ?? durationMs
2960
+ }));
2961
+ return response;
2962
+ } catch (e) {
2963
+ const durationMs = Date.now() - start;
2964
+ let attempts = 0;
2965
+ if (isExiosError(e)) {
2966
+ const meta = e.meta;
2967
+ meta.requestId ??= requestId;
2968
+ if (correlationId !== void 0) meta.correlationId ??= correlationId;
2969
+ meta.method ??= config.method;
2970
+ meta.url ??= url;
2971
+ meta.durationMs ??= durationMs;
2972
+ attempts = meta.attempts;
2973
+ }
2974
+ if (isCancel(e)) {
2975
+ hub.emit("canceled", () => ({ ...base(), error: e, attempts, durationMs }));
2976
+ } else {
2977
+ hub.emit("error", () => ({
2978
+ ...base(),
2979
+ error: e,
2980
+ code: isExiosError(e) ? e.code : void 0,
2981
+ status: isExiosError(e) ? e.status ?? e.response?.status : void 0,
2982
+ attempts,
2983
+ durationMs
2984
+ }));
2985
+ }
2986
+ throw e;
2987
+ } finally {
2988
+ if (timer !== void 0) clearTimeout(timer);
2989
+ if (joined && !deferCleanup) joined.cleanup();
2990
+ }
2991
+ }
2376
2992
  /** Runs every request interceptor in this tick with promise-chain semantics, then dispatches. */
2377
2993
  runSync(chain, config, dispatch) {
2378
2994
  let value = config;
@@ -2450,6 +3066,9 @@ var Exios = class {
2450
3066
  };
2451
3067
  var METHODS = [
2452
3068
  "request",
3069
+ "on",
3070
+ "once",
3071
+ "off",
2453
3072
  "getUri",
2454
3073
  "get",
2455
3074
  "delete",
@@ -2480,7 +3099,10 @@ function detachDefaults(d) {
2480
3099
  "transitional",
2481
3100
  "fetchOptions",
2482
3101
  "auth",
2483
- "breaker"
3102
+ "breaker",
3103
+ "metadata",
3104
+ "cache",
3105
+ "dedupe"
2484
3106
  ]) {
2485
3107
  if (isPlainObject4(out[k])) out[k] = { ...out[k] };
2486
3108
  }
@@ -2510,6 +3132,7 @@ function createInstance(defaults) {
2510
3132
  });
2511
3133
  instance.interceptors = context.interceptors;
2512
3134
  instance.breaker = context.breaker;
3135
+ instance.cache = context.cache;
2513
3136
  instance.create = (cfg) => createInstance(detachDefaults(mergeConfig(context.defaults, cfg)));
2514
3137
  return instance;
2515
3138
  }
@@ -2525,7 +3148,8 @@ var statics = {
2525
3148
  isExiosError,
2526
3149
  isCancel,
2527
3150
  mergeConfig,
2528
- toFormData
3151
+ toFormData,
3152
+ MemoryCache
2529
3153
  };
2530
3154
  var exios = Object.assign(
2531
3155
  createInstance(createDefaults()),