@indra211/exios 3.0.0 → 3.1.1
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 +100 -2
- package/dist/index.cjs +478 -15
- package/dist/index.d.cts +7 -0
- package/dist/index.d.ts +162 -53
- package/dist/index.js +479 -15
- package/dist/index.node.cjs +478 -15
- package/dist/index.node.js +479 -15
- package/package.json +1 -1
package/dist/index.node.cjs
CHANGED
|
@@ -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
|
|
177
|
-
return
|
|
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 "";
|
|
@@ -200,8 +200,8 @@ function serializeParams(params, opts2 = {}) {
|
|
|
200
200
|
return parts.join("&");
|
|
201
201
|
}
|
|
202
202
|
function buildURL(url, params, serializer) {
|
|
203
|
-
const
|
|
204
|
-
if (
|
|
203
|
+
const hash2 = url.indexOf("#");
|
|
204
|
+
if (hash2 !== -1) url = url.slice(0, hash2);
|
|
205
205
|
if (params === void 0 || params === null) return url;
|
|
206
206
|
let serialized;
|
|
207
207
|
if (typeof serializer === "function") serialized = serializer(params);
|
|
@@ -242,8 +242,8 @@ function toFormData(obj, fd = new FormData()) {
|
|
|
242
242
|
// src/core/transforms.ts
|
|
243
243
|
function isPlainObject2(v) {
|
|
244
244
|
if (v === null || typeof v !== "object") return false;
|
|
245
|
-
const
|
|
246
|
-
return
|
|
245
|
+
const proto2 = Object.getPrototypeOf(v);
|
|
246
|
+
return proto2 === Object.prototype || proto2 === null;
|
|
247
247
|
}
|
|
248
248
|
function isPassThrough(data) {
|
|
249
249
|
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);
|
|
@@ -2321,7 +2321,14 @@ var isPlainObject3 = (v) => {
|
|
|
2321
2321
|
return p === Object.prototype || p === null;
|
|
2322
2322
|
};
|
|
2323
2323
|
var isBucket = (k) => HEADER_BUCKETS.includes(k.toLowerCase());
|
|
2324
|
-
var SHALLOW_MERGE = /* @__PURE__ */ new Set([
|
|
2324
|
+
var SHALLOW_MERGE = /* @__PURE__ */ new Set([
|
|
2325
|
+
"auth",
|
|
2326
|
+
"transitional",
|
|
2327
|
+
"fetchOptions",
|
|
2328
|
+
"metadata",
|
|
2329
|
+
"cache",
|
|
2330
|
+
"dedupe"
|
|
2331
|
+
]);
|
|
2325
2332
|
function setCI(target, k, v) {
|
|
2326
2333
|
const lk = k.toLowerCase();
|
|
2327
2334
|
for (const existing of Object.keys(target)) {
|
|
@@ -2427,6 +2434,275 @@ function assertRequestBreaker(b) {
|
|
|
2427
2434
|
}
|
|
2428
2435
|
}
|
|
2429
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, scope = "cache") {
|
|
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
|
+
parts.push(
|
|
2575
|
+
`shape:${fingerprint([config.transformResponse, config.responseEncoding, config.decompress])}`
|
|
2576
|
+
);
|
|
2577
|
+
if (scope === "dedupe") {
|
|
2578
|
+
parts.push(
|
|
2579
|
+
`policy:${fingerprint([
|
|
2580
|
+
config.timeout,
|
|
2581
|
+
config.totalTimeout,
|
|
2582
|
+
config.validateStatus,
|
|
2583
|
+
config.retry,
|
|
2584
|
+
config.breaker,
|
|
2585
|
+
config.adapter,
|
|
2586
|
+
config.maxContentLength,
|
|
2587
|
+
config.maxRedirects,
|
|
2588
|
+
config.transitional
|
|
2589
|
+
])}`
|
|
2590
|
+
);
|
|
2591
|
+
}
|
|
2592
|
+
return `${requestTarget(config)} #${hash(parts.join("\n"))}`;
|
|
2593
|
+
}
|
|
2594
|
+
var fnIds = /* @__PURE__ */ new WeakMap();
|
|
2595
|
+
var nextFnId = 0;
|
|
2596
|
+
function fingerprint(v) {
|
|
2597
|
+
if (typeof v === "function") {
|
|
2598
|
+
let id = fnIds.get(v);
|
|
2599
|
+
if (id === void 0) fnIds.set(v, id = ++nextFnId);
|
|
2600
|
+
return `f${id}`;
|
|
2601
|
+
}
|
|
2602
|
+
if (v === null || typeof v !== "object") return v === void 0 ? "u" : JSON.stringify(v);
|
|
2603
|
+
if (Array.isArray(v)) return `[${v.map(fingerprint).join(",")}]`;
|
|
2604
|
+
const o = v;
|
|
2605
|
+
return `{${Object.keys(o).filter((k) => o[k] !== void 0).sort().map((k) => `${k}:${fingerprint(o[k])}`).join(",")}}`;
|
|
2606
|
+
}
|
|
2607
|
+
function keyURL(key) {
|
|
2608
|
+
const sp = key.indexOf(" ");
|
|
2609
|
+
const h = key.lastIndexOf(" #");
|
|
2610
|
+
return sp > 0 && h > sp ? key.slice(sp + 1, h) : void 0;
|
|
2611
|
+
}
|
|
2612
|
+
function keyFor(config, opts2, scope = "cache") {
|
|
2613
|
+
if (!opts2.methods.includes(config.method)) return void 0;
|
|
2614
|
+
if (config.responseType === "stream") return void 0;
|
|
2615
|
+
if (opts2.key) return opts2.key(config);
|
|
2616
|
+
if (config.data !== void 0) return void 0;
|
|
2617
|
+
return defaultRequestKey(config, scope);
|
|
2618
|
+
}
|
|
2619
|
+
function checkMethods(name, m) {
|
|
2620
|
+
if (!Array.isArray(m)) bad(name, m, "an array");
|
|
2621
|
+
return m.map((x) => String(x).toLowerCase());
|
|
2622
|
+
}
|
|
2623
|
+
function resolveDedupe(v) {
|
|
2624
|
+
if (v === void 0 || v === false) return false;
|
|
2625
|
+
if (v === true) return { methods: [...SAFE_METHODS] };
|
|
2626
|
+
if (typeof v !== "object" || v === null) bad("dedupe", v, "a boolean or an object");
|
|
2627
|
+
if (v.key !== void 0 && typeof v.key !== "function") bad("dedupe.key", v.key, "a function");
|
|
2628
|
+
return { methods: checkMethods("dedupe.methods", v.methods ?? SAFE_METHODS), key: v.key };
|
|
2629
|
+
}
|
|
2630
|
+
function resolveCache(v) {
|
|
2631
|
+
if (v === void 0 || v === false) return false;
|
|
2632
|
+
const o = v === true ? {} : v;
|
|
2633
|
+
if (typeof o !== "object" || o === null) bad("cache", v, "a boolean or an object");
|
|
2634
|
+
const ttl = o.ttl ?? 6e4;
|
|
2635
|
+
if (typeof ttl !== "number" || !(ttl > 0) || !Number.isFinite(ttl))
|
|
2636
|
+
bad("cache.ttl", ttl, "a finite number > 0");
|
|
2637
|
+
if (o.key !== void 0 && typeof o.key !== "function") bad("cache.key", o.key, "a function");
|
|
2638
|
+
const p = o.provider;
|
|
2639
|
+
if (p !== void 0 && (typeof p !== "object" || p === null || typeof p.get !== "function" || typeof p.set !== "function"))
|
|
2640
|
+
bad("cache.provider", p, "an object with get/set/delete/clear");
|
|
2641
|
+
return {
|
|
2642
|
+
ttl,
|
|
2643
|
+
methods: checkMethods("cache.methods", o.methods ?? SAFE_METHODS),
|
|
2644
|
+
key: o.key,
|
|
2645
|
+
provider: p,
|
|
2646
|
+
respectCacheControl: o.respectCacheControl ?? true
|
|
2647
|
+
};
|
|
2648
|
+
}
|
|
2649
|
+
function parseCacheControl(value) {
|
|
2650
|
+
const out = /* @__PURE__ */ new Map();
|
|
2651
|
+
const raw = Array.isArray(value) ? value.join(",") : value;
|
|
2652
|
+
if (typeof raw !== "string") return out;
|
|
2653
|
+
for (const part of raw.split(",")) {
|
|
2654
|
+
const [k, v] = part.split("=", 2).map((s) => s.trim());
|
|
2655
|
+
if (k) out.set(k.toLowerCase(), v === void 0 ? true : v.replace(/^"|"$/g, ""));
|
|
2656
|
+
}
|
|
2657
|
+
return out;
|
|
2658
|
+
}
|
|
2659
|
+
function cloneData(data) {
|
|
2660
|
+
if (data === null || typeof data !== "object") return { ok: true, value: data };
|
|
2661
|
+
if (typeof structuredClone !== "function") return { ok: false, value: data };
|
|
2662
|
+
if (!clonesFaithfully(data, /* @__PURE__ */ new Set())) return { ok: false, value: data };
|
|
2663
|
+
try {
|
|
2664
|
+
return { ok: true, value: structuredClone(data) };
|
|
2665
|
+
} catch {
|
|
2666
|
+
return { ok: false, value: data };
|
|
2667
|
+
}
|
|
2668
|
+
}
|
|
2669
|
+
var proto = (v) => Object.getPrototypeOf(v);
|
|
2670
|
+
var VIEW_TYPES = [
|
|
2671
|
+
"Int8Array",
|
|
2672
|
+
"Uint8Array",
|
|
2673
|
+
"Uint8ClampedArray",
|
|
2674
|
+
"Int16Array",
|
|
2675
|
+
"Uint16Array",
|
|
2676
|
+
"Int32Array",
|
|
2677
|
+
"Uint32Array",
|
|
2678
|
+
"Float32Array",
|
|
2679
|
+
"Float64Array",
|
|
2680
|
+
"BigInt64Array",
|
|
2681
|
+
"BigUint64Array",
|
|
2682
|
+
"DataView"
|
|
2683
|
+
];
|
|
2684
|
+
var isType = (v, name) => {
|
|
2685
|
+
const C = globalThis[name];
|
|
2686
|
+
return typeof C === "function" && v instanceof C;
|
|
2687
|
+
};
|
|
2688
|
+
function clonesFaithfully(v, seen) {
|
|
2689
|
+
if (typeof v === "function" || typeof v === "symbol") return false;
|
|
2690
|
+
if (v === null || typeof v !== "object") return true;
|
|
2691
|
+
if (seen.has(v)) return true;
|
|
2692
|
+
seen.add(v);
|
|
2693
|
+
if (Array.isArray(v)) return proto(v) === Array.prototype && v.every((x) => clonesFaithfully(x, seen));
|
|
2694
|
+
if (v instanceof Map) return proto(v) === Map.prototype && [...v].every(([k, x]) => clonesFaithfully(k, seen) && clonesFaithfully(x, seen));
|
|
2695
|
+
if (v instanceof Set) return proto(v) === Set.prototype && [...v].every((x) => clonesFaithfully(x, seen));
|
|
2696
|
+
const p = proto(v);
|
|
2697
|
+
if (p === Object.prototype || p === null)
|
|
2698
|
+
return Object.values(v).every((x) => clonesFaithfully(x, seen));
|
|
2699
|
+
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
|
|
2700
|
+
isType(v, "Blob") || isType(v, "FormData");
|
|
2701
|
+
}
|
|
2702
|
+
function reportCacheError(op, err) {
|
|
2703
|
+
if (typeof console !== "undefined") console.error(`[exios] cache provider ${op} failed:`, err);
|
|
2704
|
+
}
|
|
2705
|
+
|
|
2430
2706
|
// src/core/requestId.ts
|
|
2431
2707
|
var seq = 0;
|
|
2432
2708
|
function createRequestId() {
|
|
@@ -2458,6 +2734,10 @@ var Exios = class {
|
|
|
2458
2734
|
breaker;
|
|
2459
2735
|
registry;
|
|
2460
2736
|
events = new EventHub();
|
|
2737
|
+
memoryCache = new MemoryCache();
|
|
2738
|
+
inflight = new InflightRequests();
|
|
2739
|
+
/** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
|
|
2740
|
+
cache;
|
|
2461
2741
|
constructor(defaults) {
|
|
2462
2742
|
this.defaults = defaults;
|
|
2463
2743
|
this.registry = new BreakerRegistry(
|
|
@@ -2474,6 +2754,50 @@ var Exios = class {
|
|
|
2474
2754
|
state: (key) => this.registry.state(key),
|
|
2475
2755
|
reset: (key) => this.registry.reset(key)
|
|
2476
2756
|
};
|
|
2757
|
+
const provider = () => {
|
|
2758
|
+
const c = this.defaults.cache;
|
|
2759
|
+
return typeof c === "object" && c?.provider || this.memoryCache;
|
|
2760
|
+
};
|
|
2761
|
+
this.cache = {
|
|
2762
|
+
clear: async () => {
|
|
2763
|
+
await provider().clear();
|
|
2764
|
+
},
|
|
2765
|
+
delete: async (key) => {
|
|
2766
|
+
await provider().delete(key);
|
|
2767
|
+
},
|
|
2768
|
+
key: (cfg = {}) => {
|
|
2769
|
+
const resolved = finalizeConfig(resolveConfig(mergeConfig(this.defaults, cfg)));
|
|
2770
|
+
const c = resolveCache(resolved.cache) || resolveCache(true);
|
|
2771
|
+
return c ? keyFor(resolved, c) : void 0;
|
|
2772
|
+
},
|
|
2773
|
+
invalidate: async (match) => {
|
|
2774
|
+
const p = provider();
|
|
2775
|
+
if (typeof p.keys !== "function")
|
|
2776
|
+
throw new ExiosError(
|
|
2777
|
+
"cache.invalidate needs a cache provider with keys()",
|
|
2778
|
+
ExiosError.ERR_NOT_SUPPORT
|
|
2779
|
+
);
|
|
2780
|
+
let test;
|
|
2781
|
+
if (typeof match === "function") test = match;
|
|
2782
|
+
else if (match instanceof RegExp) test = (k) => match.test(k);
|
|
2783
|
+
else {
|
|
2784
|
+
const target = requestTarget({ ...this.defaults, url: match, params: void 0 });
|
|
2785
|
+
const prefix = target.slice(target.indexOf(" ") + 1);
|
|
2786
|
+
test = (k) => {
|
|
2787
|
+
const u = keyURL(k);
|
|
2788
|
+
return u !== void 0 && (u === prefix || u.startsWith(prefix + "/") || u.startsWith(prefix + "?"));
|
|
2789
|
+
};
|
|
2790
|
+
}
|
|
2791
|
+
let n = 0;
|
|
2792
|
+
for (const k of [...await p.keys()]) {
|
|
2793
|
+
if (test(k)) {
|
|
2794
|
+
await p.delete(k);
|
|
2795
|
+
n++;
|
|
2796
|
+
}
|
|
2797
|
+
}
|
|
2798
|
+
return n;
|
|
2799
|
+
}
|
|
2800
|
+
};
|
|
2477
2801
|
}
|
|
2478
2802
|
async request(configOrUrl, config) {
|
|
2479
2803
|
const cfg = typeof configOrUrl === "string" ? { ...config, url: configOrUrl } : { ...configOrUrl };
|
|
@@ -2516,13 +2840,104 @@ var Exios = class {
|
|
|
2516
2840
|
off(name, listener) {
|
|
2517
2841
|
this.events.off(name, listener);
|
|
2518
2842
|
}
|
|
2519
|
-
/**
|
|
2843
|
+
/**
|
|
2844
|
+
* After request interceptors: ids → cache read → dedupe → network → cache write.
|
|
2845
|
+
* Cache hits and deduplicated followers make no network request and emit no lifecycle events.
|
|
2846
|
+
*/
|
|
2520
2847
|
async dispatch(config) {
|
|
2521
|
-
const
|
|
2522
|
-
|
|
2848
|
+
const start = Date.now();
|
|
2849
|
+
config.requestId ??= createRequestId();
|
|
2850
|
+
const totalTimeout = config.totalTimeout ?? 0;
|
|
2851
|
+
if (typeof totalTimeout !== "number" || !(totalTimeout >= 0) || !Number.isFinite(totalTimeout))
|
|
2852
|
+
bad("totalTimeout", totalTimeout, "a non-negative finite number");
|
|
2853
|
+
const cacheCfg = resolveCache(config.cache);
|
|
2854
|
+
const dedupeCfg = resolveDedupe(config.dedupe);
|
|
2855
|
+
const cacheKey = cacheCfg ? keyFor(config, cacheCfg) : void 0;
|
|
2856
|
+
const dedupeKey = dedupeCfg ? keyFor(config, dedupeCfg, "dedupe") : void 0;
|
|
2857
|
+
const provider = cacheCfg ? cacheCfg.provider ?? this.memoryCache : void 0;
|
|
2858
|
+
const reqCC = cacheCfg && cacheCfg.respectCacheControl ? parseCacheControl(config.headers["cache-control"]) : void 0;
|
|
2859
|
+
if (cacheKey !== void 0 && provider && !reqCC?.has("no-cache") && !reqCC?.has("no-store")) {
|
|
2860
|
+
let entry;
|
|
2861
|
+
try {
|
|
2862
|
+
entry = await provider.get(cacheKey);
|
|
2863
|
+
} catch (e) {
|
|
2864
|
+
reportCacheError("get", e);
|
|
2865
|
+
}
|
|
2866
|
+
if (entry && entry.expiresAt > Date.now()) {
|
|
2867
|
+
const copy2 = cloneData(entry.data);
|
|
2868
|
+
return this.localResponse(config, start, {
|
|
2869
|
+
data: copy2.value,
|
|
2870
|
+
status: entry.status,
|
|
2871
|
+
statusText: entry.statusText,
|
|
2872
|
+
headers: { ...entry.headers },
|
|
2873
|
+
request: null,
|
|
2874
|
+
meta: { attempts: 0, cached: true }
|
|
2875
|
+
});
|
|
2876
|
+
}
|
|
2877
|
+
}
|
|
2523
2878
|
const header = config.correlationIdHeader?.toLowerCase();
|
|
2524
2879
|
if (header && config.headers[header] === void 0)
|
|
2525
|
-
config.headers = { ...config.headers, [header]: correlationId ?? requestId };
|
|
2880
|
+
config.headers = { ...config.headers, [header]: config.correlationId ?? config.requestId };
|
|
2881
|
+
const network = async (c) => {
|
|
2882
|
+
const response2 = await this.network(c, start, totalTimeout);
|
|
2883
|
+
if (cacheKey !== void 0 && provider && cacheCfg && !reqCC?.has("no-store"))
|
|
2884
|
+
this.store(provider, cacheKey, response2, cacheCfg);
|
|
2885
|
+
return response2;
|
|
2886
|
+
};
|
|
2887
|
+
if (dedupeKey === void 0) return network(config);
|
|
2888
|
+
const { response, leader } = await this.inflight.join(
|
|
2889
|
+
dedupeKey,
|
|
2890
|
+
config,
|
|
2891
|
+
(signal) => network({ ...config, signal, cancelToken: void 0 })
|
|
2892
|
+
);
|
|
2893
|
+
if (leader) return response;
|
|
2894
|
+
const copy = cloneData(response.data);
|
|
2895
|
+
return this.localResponse(config, start, {
|
|
2896
|
+
...response,
|
|
2897
|
+
data: copy.value,
|
|
2898
|
+
headers: { ...response.headers },
|
|
2899
|
+
meta: { attempts: response.meta.attempts, deduped: true }
|
|
2900
|
+
});
|
|
2901
|
+
}
|
|
2902
|
+
/** A response made without a network request of its own (cache hit, deduplicated follower). */
|
|
2903
|
+
localResponse(config, start, r) {
|
|
2904
|
+
r.meta.requestId = config.requestId;
|
|
2905
|
+
if (config.correlationId !== void 0) r.meta.correlationId = config.correlationId;
|
|
2906
|
+
r.meta.durationMs = Date.now() - start;
|
|
2907
|
+
return { ...r, config };
|
|
2908
|
+
}
|
|
2909
|
+
/** Store a successful response; provider failures are reported, never thrown. */
|
|
2910
|
+
store(provider, key, response, cfg) {
|
|
2911
|
+
if (response.status < 200 || response.status >= 300) return;
|
|
2912
|
+
let ttl = cfg.ttl;
|
|
2913
|
+
if (cfg.respectCacheControl) {
|
|
2914
|
+
const cc = parseCacheControl(response.headers["cache-control"]);
|
|
2915
|
+
if (cc.has("no-store") || cc.has("no-cache")) return;
|
|
2916
|
+
const maxAge = Number(cc.get("max-age"));
|
|
2917
|
+
if (cc.has("max-age") && Number.isFinite(maxAge)) ttl = Math.min(ttl, maxAge * 1e3);
|
|
2918
|
+
}
|
|
2919
|
+
if (ttl <= 0) return;
|
|
2920
|
+
const copy = cloneData(response.data);
|
|
2921
|
+
if (!copy.ok) return;
|
|
2922
|
+
const now = Date.now();
|
|
2923
|
+
try {
|
|
2924
|
+
const r = provider.set(key, {
|
|
2925
|
+
status: response.status,
|
|
2926
|
+
statusText: response.statusText,
|
|
2927
|
+
headers: { ...response.headers },
|
|
2928
|
+
data: copy.value,
|
|
2929
|
+
storedAt: now,
|
|
2930
|
+
expiresAt: now + ttl
|
|
2931
|
+
});
|
|
2932
|
+
if (isThenable(r)) Promise.resolve(r).catch((e) => reportCacheError("set", e));
|
|
2933
|
+
} catch (e) {
|
|
2934
|
+
reportCacheError("set", e);
|
|
2935
|
+
}
|
|
2936
|
+
}
|
|
2937
|
+
/** totalTimeout, timing, error context and lifecycle events around dispatchRequest. */
|
|
2938
|
+
async network(config, start, totalTimeout) {
|
|
2939
|
+
const requestId = config.requestId;
|
|
2940
|
+
const { correlationId, metadata } = config;
|
|
2526
2941
|
const hub = this.events;
|
|
2527
2942
|
const url = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
|
|
2528
2943
|
const base = () => ({
|
|
@@ -2531,9 +2946,9 @@ var Exios = class {
|
|
|
2531
2946
|
method: config.method,
|
|
2532
2947
|
url,
|
|
2533
2948
|
config,
|
|
2949
|
+
metadata,
|
|
2534
2950
|
timestamp: Date.now()
|
|
2535
2951
|
});
|
|
2536
|
-
const start = Date.now();
|
|
2537
2952
|
const observer = {
|
|
2538
2953
|
onRetry: (o) => hub.emit("retry", () => ({
|
|
2539
2954
|
...base(),
|
|
@@ -2546,15 +2961,55 @@ var Exios = class {
|
|
|
2546
2961
|
if (TIMEOUT_CODES.has(error.code ?? ""))
|
|
2547
2962
|
hub.emit("timeout", () => ({
|
|
2548
2963
|
...base(),
|
|
2964
|
+
kind: "attempt",
|
|
2549
2965
|
attempt,
|
|
2550
2966
|
timeoutMs: config.timeout ?? 0,
|
|
2551
2967
|
error
|
|
2552
2968
|
}));
|
|
2553
2969
|
}
|
|
2554
2970
|
};
|
|
2971
|
+
let timer;
|
|
2972
|
+
let totalFired = false;
|
|
2973
|
+
let joined;
|
|
2974
|
+
let dispatchConfig = config;
|
|
2975
|
+
if (totalTimeout > 0) {
|
|
2976
|
+
const ac = new AbortController();
|
|
2977
|
+
timer = setTimeout(() => {
|
|
2978
|
+
totalFired = true;
|
|
2979
|
+
ac.abort(new Error("totalTimeout"));
|
|
2980
|
+
}, totalTimeout);
|
|
2981
|
+
joined = combineSignals(config.signal, ac.signal);
|
|
2982
|
+
dispatchConfig = { ...config, signal: joined.signal };
|
|
2983
|
+
}
|
|
2984
|
+
let deferCleanup = false;
|
|
2555
2985
|
hub.emit("request", base);
|
|
2556
2986
|
try {
|
|
2557
|
-
|
|
2987
|
+
let response;
|
|
2988
|
+
try {
|
|
2989
|
+
response = await dispatchRequest(dispatchConfig, this.registry, observer);
|
|
2990
|
+
} catch (e) {
|
|
2991
|
+
if (!totalFired || config.signal?.aborted || !isCancel(e)) throw e;
|
|
2992
|
+
const err = new ExiosError(
|
|
2993
|
+
`total timeout of ${totalTimeout}ms exceeded`,
|
|
2994
|
+
config.transitional?.clarifyTimeoutError ? ExiosError.ETIMEDOUT : ExiosError.ECONNABORTED,
|
|
2995
|
+
config,
|
|
2996
|
+
e.request
|
|
2997
|
+
);
|
|
2998
|
+
err.cause = e;
|
|
2999
|
+
err.meta.attempts = e.meta.attempts;
|
|
3000
|
+
hub.emit("timeout", () => ({
|
|
3001
|
+
...base(),
|
|
3002
|
+
kind: "total",
|
|
3003
|
+
attempt: err.meta.attempts,
|
|
3004
|
+
timeoutMs: totalTimeout,
|
|
3005
|
+
error: err
|
|
3006
|
+
}));
|
|
3007
|
+
throw err;
|
|
3008
|
+
}
|
|
3009
|
+
if (joined && isOneShotBody(response.data)) {
|
|
3010
|
+
response.data = whenBodyDone(response.data, joined.cleanup);
|
|
3011
|
+
deferCleanup = true;
|
|
3012
|
+
}
|
|
2558
3013
|
const durationMs = Date.now() - start;
|
|
2559
3014
|
const meta = response.meta;
|
|
2560
3015
|
meta.requestId = requestId;
|
|
@@ -2594,6 +3049,9 @@ var Exios = class {
|
|
|
2594
3049
|
}));
|
|
2595
3050
|
}
|
|
2596
3051
|
throw e;
|
|
3052
|
+
} finally {
|
|
3053
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
3054
|
+
if (joined && !deferCleanup) joined.cleanup();
|
|
2597
3055
|
}
|
|
2598
3056
|
}
|
|
2599
3057
|
/** Runs every request interceptor in this tick with promise-chain semantics, then dispatches. */
|
|
@@ -2706,7 +3164,10 @@ function detachDefaults(d) {
|
|
|
2706
3164
|
"transitional",
|
|
2707
3165
|
"fetchOptions",
|
|
2708
3166
|
"auth",
|
|
2709
|
-
"breaker"
|
|
3167
|
+
"breaker",
|
|
3168
|
+
"metadata",
|
|
3169
|
+
"cache",
|
|
3170
|
+
"dedupe"
|
|
2710
3171
|
]) {
|
|
2711
3172
|
if (isPlainObject4(out[k])) out[k] = { ...out[k] };
|
|
2712
3173
|
}
|
|
@@ -2736,6 +3197,7 @@ function createInstance(defaults) {
|
|
|
2736
3197
|
});
|
|
2737
3198
|
instance.interceptors = context.interceptors;
|
|
2738
3199
|
instance.breaker = context.breaker;
|
|
3200
|
+
instance.cache = context.cache;
|
|
2739
3201
|
instance.create = (cfg) => createInstance(detachDefaults(mergeConfig(context.defaults, cfg)));
|
|
2740
3202
|
return instance;
|
|
2741
3203
|
}
|
|
@@ -2751,7 +3213,8 @@ var statics = {
|
|
|
2751
3213
|
isExiosError,
|
|
2752
3214
|
isCancel,
|
|
2753
3215
|
mergeConfig,
|
|
2754
|
-
toFormData
|
|
3216
|
+
toFormData,
|
|
3217
|
+
MemoryCache
|
|
2755
3218
|
};
|
|
2756
3219
|
var exios = Object.assign(
|
|
2757
3220
|
createInstance(createDefaults()),
|