@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.
package/dist/index.cjs CHANGED
@@ -24,6 +24,36 @@ __export(cjs_exports, {
24
24
  });
25
25
  module.exports = __toCommonJS(cjs_exports);
26
26
 
27
+ // src/core/redact.ts
28
+ var REDACTED = "[REDACTED]";
29
+ var SENSITIVE_HEADERS = /* @__PURE__ */ new Set([
30
+ "authorization",
31
+ "proxy-authorization",
32
+ "cookie",
33
+ "set-cookie",
34
+ "x-api-key",
35
+ "x-auth-token",
36
+ "x-xsrf-token",
37
+ "x-csrf-token"
38
+ ]);
39
+ function redactHeaders(headers) {
40
+ if (!headers || typeof headers !== "object") return headers;
41
+ const out = {};
42
+ for (const [k, v] of Object.entries(headers))
43
+ out[k] = SENSITIVE_HEADERS.has(k.toLowerCase()) ? REDACTED : v;
44
+ return out;
45
+ }
46
+ function redactConfig(config) {
47
+ if (!config || typeof config !== "object") return config;
48
+ const c = { ...config };
49
+ if (c.headers && typeof c.headers === "object") c.headers = redactHeaders(c.headers);
50
+ if (c.auth) c.auth = { username: c.auth.username, password: REDACTED };
51
+ if (c.proxy && typeof c.proxy === "object" && c.proxy.auth)
52
+ c.proxy = { ...c.proxy, auth: { username: c.proxy.auth.username, password: REDACTED } };
53
+ if (c.data !== void 0) c.data = REDACTED;
54
+ return c;
55
+ }
56
+
27
57
  // src/errors/ExiosError.ts
28
58
  var ExiosError = class _ExiosError extends Error {
29
59
  static ERR_BAD_REQUEST = "ERR_BAD_REQUEST";
@@ -53,13 +83,14 @@ var ExiosError = class _ExiosError extends Error {
53
83
  this.response = response;
54
84
  this.status = response?.status;
55
85
  }
86
+ /** Log-safe: credentials, sensitive headers (Authorization, Cookie, API keys) and the body are redacted. */
56
87
  toJSON() {
57
88
  return {
58
89
  message: this.message,
59
90
  name: this.name,
60
91
  code: this.code,
61
92
  status: this.status,
62
- config: this.config,
93
+ config: redactConfig(this.config),
63
94
  meta: this.meta,
64
95
  stack: this.stack
65
96
  };
@@ -235,8 +266,8 @@ function serializeParams(params, opts = {}) {
235
266
  return parts.join("&");
236
267
  }
237
268
  function buildURL(url, params, serializer) {
238
- const hash = url.indexOf("#");
239
- if (hash !== -1) url = url.slice(0, hash);
269
+ const hash2 = url.indexOf("#");
270
+ if (hash2 !== -1) url = url.slice(0, hash2);
240
271
  if (params === void 0 || params === null) return url;
241
272
  let serialized;
242
273
  if (typeof serializer === "function") serialized = serializer(params);
@@ -1209,14 +1240,16 @@ function defaultIsFailure(o) {
1209
1240
  return status >= 500 || status === 408 || status === 429;
1210
1241
  }
1211
1242
  var CircuitBreaker = class {
1212
- constructor(key, cfg, now = Date.now) {
1243
+ constructor(key, cfg, now = Date.now, onTransition) {
1213
1244
  this.key = key;
1214
1245
  this.cfg = cfg;
1215
1246
  this.now = now;
1247
+ this.onTransition = onTransition;
1216
1248
  }
1217
1249
  key;
1218
1250
  cfg;
1219
1251
  now;
1252
+ onTransition;
1220
1253
  _state = "closed";
1221
1254
  epoch = 0;
1222
1255
  openedAt = 0;
@@ -1320,22 +1353,25 @@ var CircuitBreaker = class {
1320
1353
  this.cfg.onStateChange?.(this.key, from, to);
1321
1354
  } catch {
1322
1355
  }
1356
+ this.onTransition?.(this.key, from, to);
1323
1357
  }
1324
1358
  };
1325
1359
  var BreakerRegistry = class {
1326
- constructor(getConfig, now = Date.now) {
1360
+ constructor(getConfig, now = Date.now, onTransition) {
1327
1361
  this.getConfig = getConfig;
1328
1362
  this.now = now;
1363
+ this.onTransition = onTransition;
1329
1364
  }
1330
1365
  getConfig;
1331
1366
  now;
1367
+ onTransition;
1332
1368
  breakers = /* @__PURE__ */ new Map();
1333
1369
  get(key) {
1334
1370
  const cfg = this.getConfig();
1335
1371
  if (cfg === false) return null;
1336
1372
  let b = this.breakers.get(key);
1337
1373
  if (!b) {
1338
- b = new CircuitBreaker(key, cfg, this.now);
1374
+ b = new CircuitBreaker(key, cfg, this.now, this.onTransition);
1339
1375
  this.breakers.set(key, b);
1340
1376
  }
1341
1377
  return b;
@@ -1440,6 +1476,7 @@ async function runWithRetry(attempt, cfg, config, hooks) {
1440
1476
  cancelBody(outcome.response?.data);
1441
1477
  if (hooks.signal?.aborted) throw abortError(hooks.signal);
1442
1478
  cfg.onRetry?.({ ...outcome, attempt: attempts, delayMs: delay });
1479
+ hooks.onRetry?.({ ...outcome, attempt: attempts, delayMs: delay });
1443
1480
  await sleep(delay, hooks.signal);
1444
1481
  hooks.beforeRetry?.();
1445
1482
  }
@@ -1461,7 +1498,7 @@ function defaultBreakerKey(config) {
1461
1498
  return full;
1462
1499
  }
1463
1500
  }
1464
- async function dispatchRequest(config, registry2) {
1501
+ async function dispatchRequest(config, registry2, observer) {
1465
1502
  const token = config.cancelToken;
1466
1503
  if (token) {
1467
1504
  if (token.reason) {
@@ -1478,7 +1515,8 @@ async function dispatchRequest(config, registry2) {
1478
1515
  try {
1479
1516
  const response = await dispatchRequest(
1480
1517
  { ...config, signal: joined.signal, cancelToken: void 0 },
1481
- registry2
1518
+ registry2,
1519
+ observer
1482
1520
  );
1483
1521
  if (isOneShotBody(response.data)) {
1484
1522
  response.data = whenBodyDone(response.data, release);
@@ -1497,6 +1535,7 @@ async function dispatchRequest(config, registry2) {
1497
1535
  const breaker = bcfg === false ? null : registry2.get(bcfg.key ? bcfg.key(config) : defaultBreakerKey(config));
1498
1536
  const ticket = breaker?.acquire(config);
1499
1537
  let attempts = 0;
1538
+ let responseTimeMs;
1500
1539
  try {
1501
1540
  let adapter;
1502
1541
  try {
@@ -1509,15 +1548,31 @@ async function dispatchRequest(config, registry2) {
1509
1548
  try {
1510
1549
  result = await runWithRetry(
1511
1550
  () => {
1512
- attempts++;
1513
- return adapter(config);
1551
+ const n = ++attempts;
1552
+ const t0 = Date.now();
1553
+ const failed = (e) => {
1554
+ responseTimeMs = Date.now() - t0;
1555
+ if (isExiosError(e)) observer?.onAttemptError?.(n, e);
1556
+ throw e;
1557
+ };
1558
+ let result2;
1559
+ try {
1560
+ result2 = Promise.resolve(adapter(config));
1561
+ } catch (e) {
1562
+ return failed(e);
1563
+ }
1564
+ return result2.then((r) => {
1565
+ responseTimeMs = Date.now() - t0;
1566
+ return r;
1567
+ }, failed);
1514
1568
  },
1515
1569
  ticket?.probe ? false : config.retry,
1516
1570
  // half-open probes get exactly one attempt
1517
1571
  config,
1518
1572
  {
1519
1573
  signal: config.signal,
1520
- beforeRetry: breaker && ticket ? () => breaker.check(ticket) : void 0
1574
+ beforeRetry: breaker && ticket ? () => breaker.check(ticket) : void 0,
1575
+ onRetry: observer?.onRetry
1521
1576
  }
1522
1577
  );
1523
1578
  } catch (e) {
@@ -1536,6 +1591,7 @@ async function dispatchRequest(config, registry2) {
1536
1591
  if (outcome.error) throw outcome.error;
1537
1592
  const response = outcome.response;
1538
1593
  response.meta.attempts = attempts;
1594
+ if (responseTimeMs !== void 0) response.meta.responseTimeMs = responseTimeMs;
1539
1595
  const { status } = response;
1540
1596
  if (config.validateStatus && !config.validateStatus(status)) {
1541
1597
  const err = new ExiosError(
@@ -1554,6 +1610,53 @@ async function dispatchRequest(config, registry2) {
1554
1610
  }
1555
1611
  }
1556
1612
 
1613
+ // src/core/events.ts
1614
+ var EventHub = class {
1615
+ listeners = /* @__PURE__ */ new Map();
1616
+ on(name, listener) {
1617
+ if (typeof listener !== "function")
1618
+ throw new TypeError(`exios: listener for "${name}" must be a function`);
1619
+ let set = this.listeners.get(name);
1620
+ if (!set) this.listeners.set(name, set = /* @__PURE__ */ new Set());
1621
+ set.add(listener);
1622
+ return () => this.off(name, listener);
1623
+ }
1624
+ once(name, listener) {
1625
+ const off = this.on(name, (e) => {
1626
+ off();
1627
+ listener(e);
1628
+ });
1629
+ return off;
1630
+ }
1631
+ off(name, listener) {
1632
+ const set = this.listeners.get(name);
1633
+ if (!set) return;
1634
+ if (listener === void 0) set.clear();
1635
+ else set.delete(listener);
1636
+ if (set.size === 0) this.listeners.delete(name);
1637
+ }
1638
+ has(name) {
1639
+ return this.listeners.has(name);
1640
+ }
1641
+ listenerCount(name) {
1642
+ return this.listeners.get(name)?.size ?? 0;
1643
+ }
1644
+ /** Build the payload only when someone listens: `emit('x', () => ({ ... }))`. */
1645
+ emit(name, payload) {
1646
+ const set = this.listeners.get(name);
1647
+ if (!set) return;
1648
+ const event = payload();
1649
+ for (const l of [...set]) {
1650
+ try {
1651
+ l(event);
1652
+ } catch (err) {
1653
+ if (typeof console !== "undefined")
1654
+ console.error(`[exios] "${name}" listener threw:`, err);
1655
+ }
1656
+ }
1657
+ }
1658
+ };
1659
+
1557
1660
  // src/core/InterceptorManager.ts
1558
1661
  var InterceptorManager = class {
1559
1662
  handlers = [];
@@ -1684,7 +1787,14 @@ var isPlainObject3 = (v) => {
1684
1787
  return p === Object.prototype || p === null;
1685
1788
  };
1686
1789
  var isBucket = (k) => HEADER_BUCKETS.includes(k.toLowerCase());
1687
- var SHALLOW_MERGE = /* @__PURE__ */ new Set(["auth", "transitional", "fetchOptions"]);
1790
+ var SHALLOW_MERGE = /* @__PURE__ */ new Set([
1791
+ "auth",
1792
+ "transitional",
1793
+ "fetchOptions",
1794
+ "metadata",
1795
+ "cache",
1796
+ "dedupe"
1797
+ ]);
1688
1798
  function setCI(target, k, v) {
1689
1799
  const lk = k.toLowerCase();
1690
1800
  for (const existing of Object.keys(target)) {
@@ -1790,7 +1900,231 @@ function assertRequestBreaker(b) {
1790
1900
  }
1791
1901
  }
1792
1902
 
1903
+ // src/core/dedupe.ts
1904
+ var InflightRequests = class {
1905
+ flights = /* @__PURE__ */ new Map();
1906
+ get size() {
1907
+ return this.flights.size;
1908
+ }
1909
+ /**
1910
+ * Join the flight for `key`, starting it with `start(signal)` when there is none. `start` receives a
1911
+ * signal owned by the flight, never a caller's. Resolves with `leader: true` for the caller that started it.
1912
+ */
1913
+ join(key, config, start) {
1914
+ const token = config.cancelToken;
1915
+ if (token?.reason) {
1916
+ token.reason.config ??= config;
1917
+ return Promise.reject(token.reason);
1918
+ }
1919
+ const tokenSignal = token?.toAbortSignal();
1920
+ const signals = [config.signal, tokenSignal].filter((s) => !!s);
1921
+ const aborted = signals.find((s) => s.aborted);
1922
+ if (aborted) {
1923
+ tokenSignal?.unsubscribe();
1924
+ return Promise.reject(abortError(aborted, config));
1925
+ }
1926
+ let flight = this.flights.get(key);
1927
+ const leader = !flight;
1928
+ if (!flight) {
1929
+ const controller = new AbortController();
1930
+ const f2 = { controller, subscribers: 0, promise: void 0 };
1931
+ f2.promise = start(controller.signal).finally(() => {
1932
+ if (this.flights.get(key) === f2) this.flights.delete(key);
1933
+ });
1934
+ this.flights.set(key, f2);
1935
+ flight = f2;
1936
+ }
1937
+ const f = flight;
1938
+ f.subscribers++;
1939
+ return new Promise((resolve, reject) => {
1940
+ let settled = false;
1941
+ const detach = () => {
1942
+ settled = true;
1943
+ for (const s of signals) s.removeEventListener("abort", onAbort);
1944
+ tokenSignal?.unsubscribe();
1945
+ };
1946
+ const onAbort = (ev) => {
1947
+ if (settled) return;
1948
+ detach();
1949
+ const reason = abortError(ev.target, config);
1950
+ reject(reason);
1951
+ if (--f.subscribers === 0) {
1952
+ if (this.flights.get(key) === f) this.flights.delete(key);
1953
+ f.controller.abort(reason);
1954
+ }
1955
+ };
1956
+ for (const s of signals) s.addEventListener("abort", onAbort, { once: true });
1957
+ f.promise.then(
1958
+ (response) => {
1959
+ if (settled) return;
1960
+ detach();
1961
+ f.subscribers--;
1962
+ resolve({ response, leader });
1963
+ },
1964
+ (err) => {
1965
+ if (settled) return;
1966
+ detach();
1967
+ f.subscribers--;
1968
+ reject(err);
1969
+ }
1970
+ );
1971
+ });
1972
+ }
1973
+ };
1974
+
1975
+ // src/core/requestCache.ts
1976
+ var SAFE_METHODS = Object.freeze(["get", "head"]);
1977
+ var MemoryCache = class {
1978
+ map = /* @__PURE__ */ new Map();
1979
+ maxEntries;
1980
+ constructor(options = {}) {
1981
+ const max = options.maxEntries ?? 100;
1982
+ if (!Number.isInteger(max) || max < 1) bad("maxEntries", max, "an integer >= 1");
1983
+ this.maxEntries = max;
1984
+ }
1985
+ get size() {
1986
+ return this.map.size;
1987
+ }
1988
+ get(key) {
1989
+ const entry = this.map.get(key);
1990
+ if (!entry) return void 0;
1991
+ this.map.delete(key);
1992
+ if (entry.expiresAt <= Date.now()) return void 0;
1993
+ this.map.set(key, entry);
1994
+ return entry;
1995
+ }
1996
+ set(key, entry) {
1997
+ this.map.delete(key);
1998
+ this.map.set(key, entry);
1999
+ while (this.map.size > this.maxEntries)
2000
+ this.map.delete(this.map.keys().next().value);
2001
+ }
2002
+ delete(key) {
2003
+ this.map.delete(key);
2004
+ }
2005
+ clear() {
2006
+ this.map.clear();
2007
+ }
2008
+ keys() {
2009
+ return [...this.map.keys()];
2010
+ }
2011
+ };
2012
+ function hash(str) {
2013
+ let h1 = 3735928559;
2014
+ let h2 = 1103547991;
2015
+ for (let i = 0; i < str.length; i++) {
2016
+ const ch = str.charCodeAt(i);
2017
+ h1 = Math.imul(h1 ^ ch, 2654435761);
2018
+ h2 = Math.imul(h2 ^ ch, 1597334677);
2019
+ }
2020
+ h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
2021
+ h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
2022
+ return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
2023
+ }
2024
+ var CACHE_DIRECTIVE_HEADERS = /* @__PURE__ */ new Set(["cache-control", "pragma"]);
2025
+ function requestTarget(config) {
2026
+ const url = buildURL(
2027
+ buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls),
2028
+ config.params,
2029
+ config.paramsSerializer
2030
+ );
2031
+ return `${(config.method ?? "get").toUpperCase()} ${url}`;
2032
+ }
2033
+ function defaultRequestKey(config) {
2034
+ const skip = config.correlationIdHeader?.toLowerCase();
2035
+ const parts = [];
2036
+ for (const k of Object.keys(config.headers).sort())
2037
+ if (k !== skip && !CACHE_DIRECTIVE_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
2038
+ if (config.auth) parts.push(`auth:${config.auth.username}:${config.auth.password}`);
2039
+ parts.push(`rt:${config.responseType ?? ""}`);
2040
+ return `${requestTarget(config)} #${hash(parts.join("\n"))}`;
2041
+ }
2042
+ function keyURL(key) {
2043
+ const sp = key.indexOf(" ");
2044
+ const h = key.lastIndexOf(" #");
2045
+ return sp > 0 && h > sp ? key.slice(sp + 1, h) : void 0;
2046
+ }
2047
+ function keyFor(config, opts) {
2048
+ if (!opts.methods.includes(config.method)) return void 0;
2049
+ if (config.responseType === "stream") return void 0;
2050
+ if (opts.key) return opts.key(config);
2051
+ if (config.data !== void 0) return void 0;
2052
+ return defaultRequestKey(config);
2053
+ }
2054
+ function checkMethods(name, m) {
2055
+ if (!Array.isArray(m)) bad(name, m, "an array");
2056
+ return m.map((x) => String(x).toLowerCase());
2057
+ }
2058
+ function resolveDedupe(v) {
2059
+ if (v === void 0 || v === false) return false;
2060
+ if (v === true) return { methods: [...SAFE_METHODS] };
2061
+ if (typeof v !== "object" || v === null) bad("dedupe", v, "a boolean or an object");
2062
+ if (v.key !== void 0 && typeof v.key !== "function") bad("dedupe.key", v.key, "a function");
2063
+ return { methods: checkMethods("dedupe.methods", v.methods ?? SAFE_METHODS), key: v.key };
2064
+ }
2065
+ function resolveCache(v) {
2066
+ if (v === void 0 || v === false) return false;
2067
+ const o = v === true ? {} : v;
2068
+ if (typeof o !== "object" || o === null) bad("cache", v, "a boolean or an object");
2069
+ const ttl = o.ttl ?? 6e4;
2070
+ if (typeof ttl !== "number" || !(ttl > 0) || !Number.isFinite(ttl))
2071
+ bad("cache.ttl", ttl, "a finite number > 0");
2072
+ if (o.key !== void 0 && typeof o.key !== "function") bad("cache.key", o.key, "a function");
2073
+ const p = o.provider;
2074
+ if (p !== void 0 && (typeof p !== "object" || p === null || typeof p.get !== "function" || typeof p.set !== "function"))
2075
+ bad("cache.provider", p, "an object with get/set/delete/clear");
2076
+ return {
2077
+ ttl,
2078
+ methods: checkMethods("cache.methods", o.methods ?? SAFE_METHODS),
2079
+ key: o.key,
2080
+ provider: p,
2081
+ respectCacheControl: o.respectCacheControl ?? true
2082
+ };
2083
+ }
2084
+ function parseCacheControl(value) {
2085
+ const out = /* @__PURE__ */ new Map();
2086
+ const raw = Array.isArray(value) ? value.join(",") : value;
2087
+ if (typeof raw !== "string") return out;
2088
+ for (const part of raw.split(",")) {
2089
+ const [k, v] = part.split("=", 2).map((s) => s.trim());
2090
+ if (k) out.set(k.toLowerCase(), v === void 0 ? true : v.replace(/^"|"$/g, ""));
2091
+ }
2092
+ return out;
2093
+ }
2094
+ function cloneData(data) {
2095
+ if (data === null || typeof data !== "object") return { ok: true, value: data };
2096
+ if (typeof structuredClone !== "function") return { ok: false, value: data };
2097
+ try {
2098
+ return { ok: true, value: structuredClone(data) };
2099
+ } catch {
2100
+ return { ok: false, value: data };
2101
+ }
2102
+ }
2103
+ function reportCacheError(op, err) {
2104
+ if (typeof console !== "undefined") console.error(`[exios] cache provider ${op} failed:`, err);
2105
+ }
2106
+
2107
+ // src/core/requestId.ts
2108
+ var seq = 0;
2109
+ function createRequestId() {
2110
+ const c = globalThis.crypto;
2111
+ if (typeof c?.randomUUID === "function") {
2112
+ try {
2113
+ return c.randomUUID();
2114
+ } catch {
2115
+ }
2116
+ }
2117
+ seq = (seq + 1) % Number.MAX_SAFE_INTEGER;
2118
+ return `${Date.now().toString(36)}-${seq.toString(36)}-${Math.random().toString(36).slice(2, 10)}`;
2119
+ }
2120
+
1793
2121
  // src/core/Exios.ts
2122
+ var CIRCUIT_EVENTS = {
2123
+ open: "circuitOpen",
2124
+ "half-open": "circuitHalfOpen",
2125
+ closed: "circuitClose"
2126
+ };
2127
+ var TIMEOUT_CODES = /* @__PURE__ */ new Set(["ECONNABORTED", "ETIMEDOUT"]);
1794
2128
  var isThenable = (v) => typeof v === "object" && v !== null && typeof v.then === "function";
1795
2129
  var Exios = class {
1796
2130
  defaults;
@@ -1800,15 +2134,71 @@ var Exios = class {
1800
2134
  };
1801
2135
  breaker;
1802
2136
  registry;
2137
+ events = new EventHub();
2138
+ memoryCache = new MemoryCache();
2139
+ inflight = new InflightRequests();
2140
+ /** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
2141
+ cache;
1803
2142
  constructor(defaults) {
1804
2143
  this.defaults = defaults;
1805
2144
  this.registry = new BreakerRegistry(
1806
- () => resolveBreaker(this.defaults.breaker)
2145
+ () => resolveBreaker(this.defaults.breaker),
2146
+ Date.now,
2147
+ (key, from, to) => this.events.emit(CIRCUIT_EVENTS[to], () => ({
2148
+ key,
2149
+ from,
2150
+ to,
2151
+ timestamp: Date.now()
2152
+ }))
1807
2153
  );
1808
2154
  this.breaker = {
1809
2155
  state: (key) => this.registry.state(key),
1810
2156
  reset: (key) => this.registry.reset(key)
1811
2157
  };
2158
+ const provider = () => {
2159
+ const c = this.defaults.cache;
2160
+ return typeof c === "object" && c?.provider || this.memoryCache;
2161
+ };
2162
+ this.cache = {
2163
+ clear: async () => {
2164
+ await provider().clear();
2165
+ },
2166
+ delete: async (key) => {
2167
+ await provider().delete(key);
2168
+ },
2169
+ key: (cfg = {}) => {
2170
+ const resolved = finalizeConfig(resolveConfig(mergeConfig(this.defaults, cfg)));
2171
+ const c = resolveCache(resolved.cache) || resolveCache(true);
2172
+ return c ? keyFor(resolved, c) : void 0;
2173
+ },
2174
+ invalidate: async (match) => {
2175
+ const p = provider();
2176
+ if (typeof p.keys !== "function")
2177
+ throw new ExiosError(
2178
+ "cache.invalidate needs a cache provider with keys()",
2179
+ ExiosError.ERR_NOT_SUPPORT
2180
+ );
2181
+ let test;
2182
+ if (typeof match === "function") test = match;
2183
+ else if (match instanceof RegExp) test = (k) => match.test(k);
2184
+ else {
2185
+ const target = requestTarget({ ...this.defaults, url: match, params: void 0 });
2186
+ const prefix = target.slice(target.indexOf(" ") + 1);
2187
+ test = (k) => {
2188
+ const u = keyURL(k);
2189
+ return u !== void 0 && (u === prefix || u.startsWith(prefix + "/") || u.startsWith(prefix + "?"));
2190
+ };
2191
+ }
2192
+ let n = 0;
2193
+ for (const k of [...await p.keys()]) {
2194
+ if (test(k)) {
2195
+ await p.delete(k);
2196
+ n++;
2197
+ }
2198
+ }
2199
+ return n;
2200
+ }
2201
+ };
1812
2202
  }
1813
2203
  async request(configOrUrl, config) {
1814
2204
  const cfg = typeof configOrUrl === "string" ? { ...config, url: configOrUrl } : { ...configOrUrl };
@@ -1821,7 +2211,7 @@ var Exios = class {
1821
2211
  synchronous = synchronous && h.synchronous;
1822
2212
  requestChain.unshift(h);
1823
2213
  });
1824
- const dispatch = (c) => dispatchRequest(finalizeConfig(c), this.registry);
2214
+ const dispatch = (c) => this.dispatch(finalizeConfig(c));
1825
2215
  let promise;
1826
2216
  if (synchronous) {
1827
2217
  promise = this.runSync(requestChain, resolved, dispatch);
@@ -1839,6 +2229,232 @@ var Exios = class {
1839
2229
  });
1840
2230
  return promise;
1841
2231
  }
2232
+ /** Subscribe to a lifecycle event; returns a function that unsubscribes. */
2233
+ on(name, listener) {
2234
+ return this.events.on(name, listener);
2235
+ }
2236
+ /** Like `on`, but the listener runs at most once. */
2237
+ once(name, listener) {
2238
+ return this.events.once(name, listener);
2239
+ }
2240
+ /** Remove one listener, or every listener of `name` when `listener` is omitted. */
2241
+ off(name, listener) {
2242
+ this.events.off(name, listener);
2243
+ }
2244
+ /**
2245
+ * After request interceptors: ids → cache read → dedupe → network → cache write.
2246
+ * Cache hits and deduplicated followers make no network request and emit no lifecycle events.
2247
+ */
2248
+ async dispatch(config) {
2249
+ const start = Date.now();
2250
+ config.requestId ??= createRequestId();
2251
+ const totalTimeout = config.totalTimeout ?? 0;
2252
+ if (typeof totalTimeout !== "number" || !(totalTimeout >= 0) || !Number.isFinite(totalTimeout))
2253
+ bad("totalTimeout", totalTimeout, "a non-negative finite number");
2254
+ const cacheCfg = resolveCache(config.cache);
2255
+ const dedupeCfg = resolveDedupe(config.dedupe);
2256
+ const cacheKey = cacheCfg ? keyFor(config, cacheCfg) : void 0;
2257
+ const dedupeKey = dedupeCfg ? keyFor(config, dedupeCfg) : void 0;
2258
+ const provider = cacheCfg ? cacheCfg.provider ?? this.memoryCache : void 0;
2259
+ const reqCC = cacheCfg && cacheCfg.respectCacheControl ? parseCacheControl(config.headers["cache-control"]) : void 0;
2260
+ if (cacheKey !== void 0 && provider && !reqCC?.has("no-cache") && !reqCC?.has("no-store")) {
2261
+ let entry;
2262
+ try {
2263
+ entry = await provider.get(cacheKey);
2264
+ } catch (e) {
2265
+ reportCacheError("get", e);
2266
+ }
2267
+ if (entry && entry.expiresAt > Date.now()) {
2268
+ const copy2 = cloneData(entry.data);
2269
+ return this.localResponse(config, start, {
2270
+ data: copy2.value,
2271
+ status: entry.status,
2272
+ statusText: entry.statusText,
2273
+ headers: { ...entry.headers },
2274
+ request: null,
2275
+ meta: { attempts: 0, cached: true }
2276
+ });
2277
+ }
2278
+ }
2279
+ const header = config.correlationIdHeader?.toLowerCase();
2280
+ if (header && config.headers[header] === void 0)
2281
+ config.headers = { ...config.headers, [header]: config.correlationId ?? config.requestId };
2282
+ const network = async (c) => {
2283
+ const response2 = await this.network(c, start, totalTimeout);
2284
+ if (cacheKey !== void 0 && provider && cacheCfg && !reqCC?.has("no-store"))
2285
+ this.store(provider, cacheKey, response2, cacheCfg);
2286
+ return response2;
2287
+ };
2288
+ if (dedupeKey === void 0) return network(config);
2289
+ const { response, leader } = await this.inflight.join(
2290
+ dedupeKey,
2291
+ config,
2292
+ (signal) => network({ ...config, signal, cancelToken: void 0 })
2293
+ );
2294
+ if (leader) return response;
2295
+ const copy = cloneData(response.data);
2296
+ return this.localResponse(config, start, {
2297
+ ...response,
2298
+ data: copy.value,
2299
+ headers: { ...response.headers },
2300
+ meta: { attempts: response.meta.attempts, deduped: true }
2301
+ });
2302
+ }
2303
+ /** A response made without a network request of its own (cache hit, deduplicated follower). */
2304
+ localResponse(config, start, r) {
2305
+ r.meta.requestId = config.requestId;
2306
+ if (config.correlationId !== void 0) r.meta.correlationId = config.correlationId;
2307
+ r.meta.durationMs = Date.now() - start;
2308
+ return { ...r, config };
2309
+ }
2310
+ /** Store a successful response; provider failures are reported, never thrown. */
2311
+ store(provider, key, response, cfg) {
2312
+ if (response.status < 200 || response.status >= 300) return;
2313
+ let ttl = cfg.ttl;
2314
+ if (cfg.respectCacheControl) {
2315
+ const cc = parseCacheControl(response.headers["cache-control"]);
2316
+ if (cc.has("no-store") || cc.has("no-cache")) return;
2317
+ const maxAge = Number(cc.get("max-age"));
2318
+ if (cc.has("max-age") && Number.isFinite(maxAge)) ttl = Math.min(ttl, maxAge * 1e3);
2319
+ }
2320
+ if (ttl <= 0) return;
2321
+ const copy = cloneData(response.data);
2322
+ if (!copy.ok) return;
2323
+ const now = Date.now();
2324
+ try {
2325
+ const r = provider.set(key, {
2326
+ status: response.status,
2327
+ statusText: response.statusText,
2328
+ headers: { ...response.headers },
2329
+ data: copy.value,
2330
+ storedAt: now,
2331
+ expiresAt: now + ttl
2332
+ });
2333
+ if (isThenable(r)) Promise.resolve(r).catch((e) => reportCacheError("set", e));
2334
+ } catch (e) {
2335
+ reportCacheError("set", e);
2336
+ }
2337
+ }
2338
+ /** totalTimeout, timing, error context and lifecycle events around dispatchRequest. */
2339
+ async network(config, start, totalTimeout) {
2340
+ const requestId = config.requestId;
2341
+ const { correlationId, metadata } = config;
2342
+ const hub = this.events;
2343
+ const url = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
2344
+ const base = () => ({
2345
+ requestId,
2346
+ correlationId,
2347
+ method: config.method,
2348
+ url,
2349
+ config,
2350
+ metadata,
2351
+ timestamp: Date.now()
2352
+ });
2353
+ const observer = {
2354
+ onRetry: (o) => hub.emit("retry", () => ({
2355
+ ...base(),
2356
+ attempt: o.attempt,
2357
+ delayMs: o.delayMs,
2358
+ error: o.error,
2359
+ status: o.response?.status ?? o.error?.response?.status
2360
+ })),
2361
+ onAttemptError: (attempt, error) => {
2362
+ if (TIMEOUT_CODES.has(error.code ?? ""))
2363
+ hub.emit("timeout", () => ({
2364
+ ...base(),
2365
+ kind: "attempt",
2366
+ attempt,
2367
+ timeoutMs: config.timeout ?? 0,
2368
+ error
2369
+ }));
2370
+ }
2371
+ };
2372
+ let timer;
2373
+ let totalFired = false;
2374
+ let joined;
2375
+ let dispatchConfig = config;
2376
+ if (totalTimeout > 0) {
2377
+ const ac = new AbortController();
2378
+ timer = setTimeout(() => {
2379
+ totalFired = true;
2380
+ ac.abort(new Error("totalTimeout"));
2381
+ }, totalTimeout);
2382
+ joined = combineSignals(config.signal, ac.signal);
2383
+ dispatchConfig = { ...config, signal: joined.signal };
2384
+ }
2385
+ let deferCleanup = false;
2386
+ hub.emit("request", base);
2387
+ try {
2388
+ let response;
2389
+ try {
2390
+ response = await dispatchRequest(dispatchConfig, this.registry, observer);
2391
+ } catch (e) {
2392
+ if (!totalFired || config.signal?.aborted || !isCancel(e)) throw e;
2393
+ const err = new ExiosError(
2394
+ `total timeout of ${totalTimeout}ms exceeded`,
2395
+ config.transitional?.clarifyTimeoutError ? ExiosError.ETIMEDOUT : ExiosError.ECONNABORTED,
2396
+ config,
2397
+ e.request
2398
+ );
2399
+ err.cause = e;
2400
+ err.meta.attempts = e.meta.attempts;
2401
+ hub.emit("timeout", () => ({
2402
+ ...base(),
2403
+ kind: "total",
2404
+ attempt: err.meta.attempts,
2405
+ timeoutMs: totalTimeout,
2406
+ error: err
2407
+ }));
2408
+ throw err;
2409
+ }
2410
+ if (joined && isOneShotBody(response.data)) {
2411
+ response.data = whenBodyDone(response.data, joined.cleanup);
2412
+ deferCleanup = true;
2413
+ }
2414
+ const durationMs = Date.now() - start;
2415
+ const meta = response.meta;
2416
+ meta.requestId = requestId;
2417
+ if (correlationId !== void 0) meta.correlationId = correlationId;
2418
+ meta.durationMs = durationMs;
2419
+ hub.emit("response", () => ({
2420
+ ...base(),
2421
+ response,
2422
+ status: response.status,
2423
+ attempts: meta.attempts,
2424
+ durationMs,
2425
+ responseTimeMs: meta.responseTimeMs ?? durationMs
2426
+ }));
2427
+ return response;
2428
+ } catch (e) {
2429
+ const durationMs = Date.now() - start;
2430
+ let attempts = 0;
2431
+ if (isExiosError(e)) {
2432
+ const meta = e.meta;
2433
+ meta.requestId ??= requestId;
2434
+ if (correlationId !== void 0) meta.correlationId ??= correlationId;
2435
+ meta.method ??= config.method;
2436
+ meta.url ??= url;
2437
+ meta.durationMs ??= durationMs;
2438
+ attempts = meta.attempts;
2439
+ }
2440
+ if (isCancel(e)) {
2441
+ hub.emit("canceled", () => ({ ...base(), error: e, attempts, durationMs }));
2442
+ } else {
2443
+ hub.emit("error", () => ({
2444
+ ...base(),
2445
+ error: e,
2446
+ code: isExiosError(e) ? e.code : void 0,
2447
+ status: isExiosError(e) ? e.status ?? e.response?.status : void 0,
2448
+ attempts,
2449
+ durationMs
2450
+ }));
2451
+ }
2452
+ throw e;
2453
+ } finally {
2454
+ if (timer !== void 0) clearTimeout(timer);
2455
+ if (joined && !deferCleanup) joined.cleanup();
2456
+ }
2457
+ }
1842
2458
  /** Runs every request interceptor in this tick with promise-chain semantics, then dispatches. */
1843
2459
  runSync(chain, config, dispatch) {
1844
2460
  let value = config;
@@ -1916,6 +2532,9 @@ var Exios = class {
1916
2532
  };
1917
2533
  var METHODS = [
1918
2534
  "request",
2535
+ "on",
2536
+ "once",
2537
+ "off",
1919
2538
  "getUri",
1920
2539
  "get",
1921
2540
  "delete",
@@ -1946,7 +2565,10 @@ function detachDefaults(d) {
1946
2565
  "transitional",
1947
2566
  "fetchOptions",
1948
2567
  "auth",
1949
- "breaker"
2568
+ "breaker",
2569
+ "metadata",
2570
+ "cache",
2571
+ "dedupe"
1950
2572
  ]) {
1951
2573
  if (isPlainObject4(out[k])) out[k] = { ...out[k] };
1952
2574
  }
@@ -1976,6 +2598,7 @@ function createInstance(defaults) {
1976
2598
  });
1977
2599
  instance.interceptors = context.interceptors;
1978
2600
  instance.breaker = context.breaker;
2601
+ instance.cache = context.cache;
1979
2602
  instance.create = (cfg) => createInstance(detachDefaults(mergeConfig(context.defaults, cfg)));
1980
2603
  return instance;
1981
2604
  }
@@ -1991,7 +2614,8 @@ var statics = {
1991
2614
  isExiosError,
1992
2615
  isCancel,
1993
2616
  mergeConfig,
1994
- toFormData
2617
+ toFormData,
2618
+ MemoryCache
1995
2619
  };
1996
2620
  var exios = Object.assign(
1997
2621
  createInstance(createDefaults()),