@indra211/exios 3.0.0 → 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/README.md +95 -2
- package/dist/index.cjs +409 -11
- package/dist/index.d.cts +6 -0
- package/dist/index.d.ts +105 -4
- package/dist/index.js +410 -11
- package/dist/index.node.cjs +409 -11
- package/dist/index.node.js +410 -11
- package/package.json +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -199,6 +199,56 @@ interface ExiosRequestConfig<D = any> {
|
|
|
199
199
|
* Off by default: an extra header can trigger a CORS preflight. A header the caller already set wins.
|
|
200
200
|
*/
|
|
201
201
|
correlationIdHeader?: string;
|
|
202
|
+
/** Free-form data that travels with the request: readable in interceptors, events and adapters. Never sent. */
|
|
203
|
+
metadata?: Record<string, unknown>;
|
|
204
|
+
/**
|
|
205
|
+
* Time limit (ms) for the whole logical request: every attempt, retry and backoff sleep.
|
|
206
|
+
* `timeout` still limits each attempt. 0 / undefined = no limit. For `responseType: 'stream'` it ends
|
|
207
|
+
* when the headers arrive.
|
|
208
|
+
*/
|
|
209
|
+
totalTimeout?: number;
|
|
210
|
+
/** Share one in-flight request between identical concurrent requests (GET/HEAD by default). Off by default. */
|
|
211
|
+
dedupe?: boolean | DedupeConfig;
|
|
212
|
+
/** Cache successful responses (GET/HEAD by default). Off by default. */
|
|
213
|
+
cache?: boolean | Partial<CacheConfig>;
|
|
214
|
+
}
|
|
215
|
+
interface DedupeConfig {
|
|
216
|
+
/** Methods that may be deduplicated. Default: ["get", "head"]. */
|
|
217
|
+
methods?: Lowercase<Method>[];
|
|
218
|
+
/** Custom key; return undefined to not deduplicate this request. Default: method + URL + params + headers. */
|
|
219
|
+
key?: (config: InternalConfig) => string | undefined;
|
|
220
|
+
}
|
|
221
|
+
/** What a cache provider stores for one response. */
|
|
222
|
+
interface CacheEntry {
|
|
223
|
+
status: number;
|
|
224
|
+
statusText: string;
|
|
225
|
+
headers: Record<string, string | string[]>;
|
|
226
|
+
data: unknown;
|
|
227
|
+
/** `Date.now()` when stored. */
|
|
228
|
+
storedAt: number;
|
|
229
|
+
/** `Date.now()` after which the entry is stale and is not used. */
|
|
230
|
+
expiresAt: number;
|
|
231
|
+
}
|
|
232
|
+
/** Storage for cached responses. Methods may be sync or async. */
|
|
233
|
+
interface CacheProvider {
|
|
234
|
+
get(key: string): CacheEntry | undefined | Promise<CacheEntry | undefined>;
|
|
235
|
+
set(key: string, entry: CacheEntry): void | Promise<void>;
|
|
236
|
+
delete(key: string): void | Promise<void>;
|
|
237
|
+
clear(): void | Promise<void>;
|
|
238
|
+
/** Needed only for `instance.cache.invalidate()`. */
|
|
239
|
+
keys?(): Iterable<string> | Promise<Iterable<string>>;
|
|
240
|
+
}
|
|
241
|
+
interface CacheConfig {
|
|
242
|
+
/** Time to live in ms. Default 60000. */
|
|
243
|
+
ttl: number;
|
|
244
|
+
/** Methods whose responses may be cached. Default: ["get", "head"]. */
|
|
245
|
+
methods: Lowercase<Method>[];
|
|
246
|
+
/** Custom key; return undefined to not cache this request. Default: method + URL + params + headers. */
|
|
247
|
+
key?: (config: InternalConfig) => string | undefined;
|
|
248
|
+
/** Where entries live. Default: the instance's in-memory LRU cache (100 entries). */
|
|
249
|
+
provider?: CacheProvider;
|
|
250
|
+
/** Honour Cache-Control (`no-store`, `no-cache`, `max-age`) on the request and the response. Default true. */
|
|
251
|
+
respectCacheControl: boolean;
|
|
202
252
|
}
|
|
203
253
|
/**
|
|
204
254
|
* Type of `instance.defaults`: like a request config, but every header bucket, `retry` and `breaker`
|
|
@@ -237,6 +287,10 @@ interface ResponseMeta {
|
|
|
237
287
|
durationMs?: number;
|
|
238
288
|
/** The final attempt only (ms). */
|
|
239
289
|
responseTimeMs?: number;
|
|
290
|
+
/** Served from the cache (no network request was made). */
|
|
291
|
+
cached?: boolean;
|
|
292
|
+
/** Shared with an identical request already in flight. */
|
|
293
|
+
deduped?: boolean;
|
|
240
294
|
}
|
|
241
295
|
/** Diagnostics attached to an ExiosError. Fields other than `attempts` are set by exios ≥ 3. */
|
|
242
296
|
interface ErrorMeta {
|
|
@@ -257,6 +311,8 @@ interface RequestEventBase {
|
|
|
257
311
|
/** baseURL + url, without the serialized `params`. */
|
|
258
312
|
url: string;
|
|
259
313
|
config: InternalConfig;
|
|
314
|
+
/** `config.metadata`, for convenience. */
|
|
315
|
+
metadata?: Record<string, unknown>;
|
|
260
316
|
/** `Date.now()` when the event was emitted. */
|
|
261
317
|
timestamp: number;
|
|
262
318
|
}
|
|
@@ -286,6 +342,8 @@ interface RetryEvent extends RequestEventBase {
|
|
|
286
342
|
status?: number;
|
|
287
343
|
}
|
|
288
344
|
interface TimeoutEvent extends RequestEventBase {
|
|
345
|
+
/** "attempt": one attempt hit `timeout` (it may be retried). "total": `totalTimeout` ended the request. */
|
|
346
|
+
kind: "attempt" | "total";
|
|
289
347
|
attempt: number;
|
|
290
348
|
timeoutMs: number;
|
|
291
349
|
error: ExiosError;
|
|
@@ -348,6 +406,10 @@ declare class Exios {
|
|
|
348
406
|
};
|
|
349
407
|
private readonly registry;
|
|
350
408
|
private readonly events;
|
|
409
|
+
private readonly memoryCache;
|
|
410
|
+
private readonly inflight;
|
|
411
|
+
/** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
|
|
412
|
+
cache: ExiosCache;
|
|
351
413
|
constructor(defaults: ExiosDefaults);
|
|
352
414
|
request<T = any, R = ExiosResponse<T>, D = any>(configOrUrl: string | Cfg<D>, config?: Cfg<D>): Promise<R>;
|
|
353
415
|
/** Subscribe to a lifecycle event; returns a function that unsubscribes. */
|
|
@@ -356,8 +418,17 @@ declare class Exios {
|
|
|
356
418
|
once<K extends ExiosEventName>(name: K, listener: ExiosEventListener<K>): () => void;
|
|
357
419
|
/** Remove one listener, or every listener of `name` when `listener` is omitted. */
|
|
358
420
|
off<K extends ExiosEventName>(name: K, listener?: ExiosEventListener<K>): void;
|
|
359
|
-
/**
|
|
421
|
+
/**
|
|
422
|
+
* After request interceptors: ids → cache read → dedupe → network → cache write.
|
|
423
|
+
* Cache hits and deduplicated followers make no network request and emit no lifecycle events.
|
|
424
|
+
*/
|
|
360
425
|
private dispatch;
|
|
426
|
+
/** A response made without a network request of its own (cache hit, deduplicated follower). */
|
|
427
|
+
private localResponse;
|
|
428
|
+
/** Store a successful response; provider failures are reported, never thrown. */
|
|
429
|
+
private store;
|
|
430
|
+
/** totalTimeout, timing, error context and lifecycle events around dispatchRequest. */
|
|
431
|
+
private network;
|
|
361
432
|
/** Runs every request interceptor in this tick with promise-chain semantics, then dispatches. */
|
|
362
433
|
private runSync;
|
|
363
434
|
getUri(config?: ExiosRequestConfig): string;
|
|
@@ -375,7 +446,21 @@ declare class Exios {
|
|
|
375
446
|
patchForm<T = any, R = ExiosResponse<T>, D = any>(url: string, data?: D, config?: Cfg<D>): Promise<R>;
|
|
376
447
|
}
|
|
377
448
|
declare const METHODS: readonly ["request", "on", "once", "off", "getUri", "get", "delete", "head", "options", "post", "put", "patch", "postForm", "putForm", "patchForm"];
|
|
378
|
-
|
|
449
|
+
/** `instance.cache`: manage the instance's cache provider. */
|
|
450
|
+
interface ExiosCache {
|
|
451
|
+
/** Remove every entry. */
|
|
452
|
+
clear(): Promise<void>;
|
|
453
|
+
/** Remove one entry by key. */
|
|
454
|
+
delete(key: string): Promise<void>;
|
|
455
|
+
/** The default cache key a request config would get (undefined if it is not cacheable). */
|
|
456
|
+
key(config?: ExiosRequestConfig): string | undefined;
|
|
457
|
+
/**
|
|
458
|
+
* Remove entries: a URL (resolved against baseURL; the URL itself, its query variants and sub-paths),
|
|
459
|
+
* a RegExp tested against keys, or a predicate. Resolves with the number removed.
|
|
460
|
+
*/
|
|
461
|
+
invalidate(match: string | RegExp | ((key: string) => boolean)): Promise<number>;
|
|
462
|
+
}
|
|
463
|
+
interface ExiosStatic extends Pick<Exios, (typeof METHODS)[number] | "defaults" | "interceptors" | "breaker" | "cache"> {
|
|
379
464
|
<T = any, R = ExiosResponse<T>, D = any>(config: ExiosRequestConfig<D>): Promise<R>;
|
|
380
465
|
<T = any, R = ExiosResponse<T>, D = any>(url: string, config?: ExiosRequestConfig<D>): Promise<R>;
|
|
381
466
|
create(config?: ExiosRequestConfig): ExiosStatic;
|
|
@@ -384,6 +469,21 @@ type ExiosInstance = ExiosStatic;
|
|
|
384
469
|
|
|
385
470
|
declare function mergeConfig(a: ExiosRequestConfig, b?: ExiosRequestConfig): ExiosRequestConfig;
|
|
386
471
|
|
|
472
|
+
/** In-memory LRU cache: the default provider. Expired entries are dropped when read. */
|
|
473
|
+
declare class MemoryCache implements CacheProvider {
|
|
474
|
+
private readonly map;
|
|
475
|
+
readonly maxEntries: number;
|
|
476
|
+
constructor(options?: {
|
|
477
|
+
maxEntries?: number;
|
|
478
|
+
});
|
|
479
|
+
get size(): number;
|
|
480
|
+
get(key: string): CacheEntry | undefined;
|
|
481
|
+
set(key: string, entry: CacheEntry): void;
|
|
482
|
+
delete(key: string): void;
|
|
483
|
+
clear(): void;
|
|
484
|
+
keys(): Iterable<string>;
|
|
485
|
+
}
|
|
486
|
+
|
|
387
487
|
declare function toFormData(obj: object, fd?: FormData): FormData;
|
|
388
488
|
|
|
389
489
|
declare const statics: {
|
|
@@ -395,10 +495,11 @@ declare const statics: {
|
|
|
395
495
|
isCancel: typeof isCancel;
|
|
396
496
|
mergeConfig: typeof mergeConfig;
|
|
397
497
|
toFormData: typeof toFormData;
|
|
498
|
+
MemoryCache: typeof MemoryCache;
|
|
398
499
|
};
|
|
399
500
|
type ExiosDefault = ExiosStatic & typeof statics;
|
|
400
501
|
declare const exios: ExiosDefault;
|
|
401
502
|
declare const create: (config?: ExiosRequestConfig) => ExiosStatic;
|
|
402
503
|
|
|
403
|
-
export { CancelToken, CanceledError, CircuitOpenError, ExiosError, InterceptorManager, create, exios as default, isCancel, isExiosError, mergeConfig, toFormData };
|
|
404
|
-
export type { AdapterConfig, AdapterFn, AdapterName, BreakerConfig, BreakerState, CancelTokenSource, CanceledEvent, Canceler, CircuitEvent, ErrorEvent, ErrorMeta, 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 };
|
|
504
|
+
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 };
|
package/dist/index.js
CHANGED
|
@@ -240,8 +240,8 @@ function serializeParams(params, opts = {}) {
|
|
|
240
240
|
return parts.join("&");
|
|
241
241
|
}
|
|
242
242
|
function buildURL(url, params, serializer) {
|
|
243
|
-
const
|
|
244
|
-
if (
|
|
243
|
+
const hash2 = url.indexOf("#");
|
|
244
|
+
if (hash2 !== -1) url = url.slice(0, hash2);
|
|
245
245
|
if (params === void 0 || params === null) return url;
|
|
246
246
|
let serialized;
|
|
247
247
|
if (typeof serializer === "function") serialized = serializer(params);
|
|
@@ -1761,7 +1761,14 @@ var isPlainObject3 = (v) => {
|
|
|
1761
1761
|
return p === Object.prototype || p === null;
|
|
1762
1762
|
};
|
|
1763
1763
|
var isBucket = (k) => HEADER_BUCKETS.includes(k.toLowerCase());
|
|
1764
|
-
var SHALLOW_MERGE = /* @__PURE__ */ new Set([
|
|
1764
|
+
var SHALLOW_MERGE = /* @__PURE__ */ new Set([
|
|
1765
|
+
"auth",
|
|
1766
|
+
"transitional",
|
|
1767
|
+
"fetchOptions",
|
|
1768
|
+
"metadata",
|
|
1769
|
+
"cache",
|
|
1770
|
+
"dedupe"
|
|
1771
|
+
]);
|
|
1765
1772
|
function setCI(target, k, v) {
|
|
1766
1773
|
const lk = k.toLowerCase();
|
|
1767
1774
|
for (const existing of Object.keys(target)) {
|
|
@@ -1867,6 +1874,210 @@ function assertRequestBreaker(b) {
|
|
|
1867
1874
|
}
|
|
1868
1875
|
}
|
|
1869
1876
|
|
|
1877
|
+
// src/core/dedupe.ts
|
|
1878
|
+
var InflightRequests = class {
|
|
1879
|
+
flights = /* @__PURE__ */ new Map();
|
|
1880
|
+
get size() {
|
|
1881
|
+
return this.flights.size;
|
|
1882
|
+
}
|
|
1883
|
+
/**
|
|
1884
|
+
* Join the flight for `key`, starting it with `start(signal)` when there is none. `start` receives a
|
|
1885
|
+
* signal owned by the flight, never a caller's. Resolves with `leader: true` for the caller that started it.
|
|
1886
|
+
*/
|
|
1887
|
+
join(key, config, start) {
|
|
1888
|
+
const token = config.cancelToken;
|
|
1889
|
+
if (token?.reason) {
|
|
1890
|
+
token.reason.config ??= config;
|
|
1891
|
+
return Promise.reject(token.reason);
|
|
1892
|
+
}
|
|
1893
|
+
const tokenSignal = token?.toAbortSignal();
|
|
1894
|
+
const signals = [config.signal, tokenSignal].filter((s) => !!s);
|
|
1895
|
+
const aborted = signals.find((s) => s.aborted);
|
|
1896
|
+
if (aborted) {
|
|
1897
|
+
tokenSignal?.unsubscribe();
|
|
1898
|
+
return Promise.reject(abortError(aborted, config));
|
|
1899
|
+
}
|
|
1900
|
+
let flight = this.flights.get(key);
|
|
1901
|
+
const leader = !flight;
|
|
1902
|
+
if (!flight) {
|
|
1903
|
+
const controller = new AbortController();
|
|
1904
|
+
const f2 = { controller, subscribers: 0, promise: void 0 };
|
|
1905
|
+
f2.promise = start(controller.signal).finally(() => {
|
|
1906
|
+
if (this.flights.get(key) === f2) this.flights.delete(key);
|
|
1907
|
+
});
|
|
1908
|
+
this.flights.set(key, f2);
|
|
1909
|
+
flight = f2;
|
|
1910
|
+
}
|
|
1911
|
+
const f = flight;
|
|
1912
|
+
f.subscribers++;
|
|
1913
|
+
return new Promise((resolve, reject) => {
|
|
1914
|
+
let settled = false;
|
|
1915
|
+
const detach = () => {
|
|
1916
|
+
settled = true;
|
|
1917
|
+
for (const s of signals) s.removeEventListener("abort", onAbort);
|
|
1918
|
+
tokenSignal?.unsubscribe();
|
|
1919
|
+
};
|
|
1920
|
+
const onAbort = (ev) => {
|
|
1921
|
+
if (settled) return;
|
|
1922
|
+
detach();
|
|
1923
|
+
const reason = abortError(ev.target, config);
|
|
1924
|
+
reject(reason);
|
|
1925
|
+
if (--f.subscribers === 0) {
|
|
1926
|
+
if (this.flights.get(key) === f) this.flights.delete(key);
|
|
1927
|
+
f.controller.abort(reason);
|
|
1928
|
+
}
|
|
1929
|
+
};
|
|
1930
|
+
for (const s of signals) s.addEventListener("abort", onAbort, { once: true });
|
|
1931
|
+
f.promise.then(
|
|
1932
|
+
(response) => {
|
|
1933
|
+
if (settled) return;
|
|
1934
|
+
detach();
|
|
1935
|
+
f.subscribers--;
|
|
1936
|
+
resolve({ response, leader });
|
|
1937
|
+
},
|
|
1938
|
+
(err) => {
|
|
1939
|
+
if (settled) return;
|
|
1940
|
+
detach();
|
|
1941
|
+
f.subscribers--;
|
|
1942
|
+
reject(err);
|
|
1943
|
+
}
|
|
1944
|
+
);
|
|
1945
|
+
});
|
|
1946
|
+
}
|
|
1947
|
+
};
|
|
1948
|
+
|
|
1949
|
+
// src/core/requestCache.ts
|
|
1950
|
+
var SAFE_METHODS = Object.freeze(["get", "head"]);
|
|
1951
|
+
var MemoryCache = class {
|
|
1952
|
+
map = /* @__PURE__ */ new Map();
|
|
1953
|
+
maxEntries;
|
|
1954
|
+
constructor(options = {}) {
|
|
1955
|
+
const max = options.maxEntries ?? 100;
|
|
1956
|
+
if (!Number.isInteger(max) || max < 1) bad("maxEntries", max, "an integer >= 1");
|
|
1957
|
+
this.maxEntries = max;
|
|
1958
|
+
}
|
|
1959
|
+
get size() {
|
|
1960
|
+
return this.map.size;
|
|
1961
|
+
}
|
|
1962
|
+
get(key) {
|
|
1963
|
+
const entry = this.map.get(key);
|
|
1964
|
+
if (!entry) return void 0;
|
|
1965
|
+
this.map.delete(key);
|
|
1966
|
+
if (entry.expiresAt <= Date.now()) return void 0;
|
|
1967
|
+
this.map.set(key, entry);
|
|
1968
|
+
return entry;
|
|
1969
|
+
}
|
|
1970
|
+
set(key, entry) {
|
|
1971
|
+
this.map.delete(key);
|
|
1972
|
+
this.map.set(key, entry);
|
|
1973
|
+
while (this.map.size > this.maxEntries)
|
|
1974
|
+
this.map.delete(this.map.keys().next().value);
|
|
1975
|
+
}
|
|
1976
|
+
delete(key) {
|
|
1977
|
+
this.map.delete(key);
|
|
1978
|
+
}
|
|
1979
|
+
clear() {
|
|
1980
|
+
this.map.clear();
|
|
1981
|
+
}
|
|
1982
|
+
keys() {
|
|
1983
|
+
return [...this.map.keys()];
|
|
1984
|
+
}
|
|
1985
|
+
};
|
|
1986
|
+
function hash(str) {
|
|
1987
|
+
let h1 = 3735928559;
|
|
1988
|
+
let h2 = 1103547991;
|
|
1989
|
+
for (let i = 0; i < str.length; i++) {
|
|
1990
|
+
const ch = str.charCodeAt(i);
|
|
1991
|
+
h1 = Math.imul(h1 ^ ch, 2654435761);
|
|
1992
|
+
h2 = Math.imul(h2 ^ ch, 1597334677);
|
|
1993
|
+
}
|
|
1994
|
+
h1 = Math.imul(h1 ^ h1 >>> 16, 2246822507) ^ Math.imul(h2 ^ h2 >>> 13, 3266489909);
|
|
1995
|
+
h2 = Math.imul(h2 ^ h2 >>> 16, 2246822507) ^ Math.imul(h1 ^ h1 >>> 13, 3266489909);
|
|
1996
|
+
return (4294967296 * (2097151 & h2) + (h1 >>> 0)).toString(36);
|
|
1997
|
+
}
|
|
1998
|
+
var CACHE_DIRECTIVE_HEADERS = /* @__PURE__ */ new Set(["cache-control", "pragma"]);
|
|
1999
|
+
function requestTarget(config) {
|
|
2000
|
+
const url = buildURL(
|
|
2001
|
+
buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls),
|
|
2002
|
+
config.params,
|
|
2003
|
+
config.paramsSerializer
|
|
2004
|
+
);
|
|
2005
|
+
return `${(config.method ?? "get").toUpperCase()} ${url}`;
|
|
2006
|
+
}
|
|
2007
|
+
function defaultRequestKey(config) {
|
|
2008
|
+
const skip = config.correlationIdHeader?.toLowerCase();
|
|
2009
|
+
const parts = [];
|
|
2010
|
+
for (const k of Object.keys(config.headers).sort())
|
|
2011
|
+
if (k !== skip && !CACHE_DIRECTIVE_HEADERS.has(k)) parts.push(`${k}:${config.headers[k]}`);
|
|
2012
|
+
if (config.auth) parts.push(`auth:${config.auth.username}:${config.auth.password}`);
|
|
2013
|
+
parts.push(`rt:${config.responseType ?? ""}`);
|
|
2014
|
+
return `${requestTarget(config)} #${hash(parts.join("\n"))}`;
|
|
2015
|
+
}
|
|
2016
|
+
function keyURL(key) {
|
|
2017
|
+
const sp = key.indexOf(" ");
|
|
2018
|
+
const h = key.lastIndexOf(" #");
|
|
2019
|
+
return sp > 0 && h > sp ? key.slice(sp + 1, h) : void 0;
|
|
2020
|
+
}
|
|
2021
|
+
function keyFor(config, opts) {
|
|
2022
|
+
if (!opts.methods.includes(config.method)) return void 0;
|
|
2023
|
+
if (config.responseType === "stream") return void 0;
|
|
2024
|
+
if (opts.key) return opts.key(config);
|
|
2025
|
+
if (config.data !== void 0) return void 0;
|
|
2026
|
+
return defaultRequestKey(config);
|
|
2027
|
+
}
|
|
2028
|
+
function checkMethods(name, m) {
|
|
2029
|
+
if (!Array.isArray(m)) bad(name, m, "an array");
|
|
2030
|
+
return m.map((x) => String(x).toLowerCase());
|
|
2031
|
+
}
|
|
2032
|
+
function resolveDedupe(v) {
|
|
2033
|
+
if (v === void 0 || v === false) return false;
|
|
2034
|
+
if (v === true) return { methods: [...SAFE_METHODS] };
|
|
2035
|
+
if (typeof v !== "object" || v === null) bad("dedupe", v, "a boolean or an object");
|
|
2036
|
+
if (v.key !== void 0 && typeof v.key !== "function") bad("dedupe.key", v.key, "a function");
|
|
2037
|
+
return { methods: checkMethods("dedupe.methods", v.methods ?? SAFE_METHODS), key: v.key };
|
|
2038
|
+
}
|
|
2039
|
+
function resolveCache(v) {
|
|
2040
|
+
if (v === void 0 || v === false) return false;
|
|
2041
|
+
const o = v === true ? {} : v;
|
|
2042
|
+
if (typeof o !== "object" || o === null) bad("cache", v, "a boolean or an object");
|
|
2043
|
+
const ttl = o.ttl ?? 6e4;
|
|
2044
|
+
if (typeof ttl !== "number" || !(ttl > 0) || !Number.isFinite(ttl))
|
|
2045
|
+
bad("cache.ttl", ttl, "a finite number > 0");
|
|
2046
|
+
if (o.key !== void 0 && typeof o.key !== "function") bad("cache.key", o.key, "a function");
|
|
2047
|
+
const p = o.provider;
|
|
2048
|
+
if (p !== void 0 && (typeof p !== "object" || p === null || typeof p.get !== "function" || typeof p.set !== "function"))
|
|
2049
|
+
bad("cache.provider", p, "an object with get/set/delete/clear");
|
|
2050
|
+
return {
|
|
2051
|
+
ttl,
|
|
2052
|
+
methods: checkMethods("cache.methods", o.methods ?? SAFE_METHODS),
|
|
2053
|
+
key: o.key,
|
|
2054
|
+
provider: p,
|
|
2055
|
+
respectCacheControl: o.respectCacheControl ?? true
|
|
2056
|
+
};
|
|
2057
|
+
}
|
|
2058
|
+
function parseCacheControl(value) {
|
|
2059
|
+
const out = /* @__PURE__ */ new Map();
|
|
2060
|
+
const raw = Array.isArray(value) ? value.join(",") : value;
|
|
2061
|
+
if (typeof raw !== "string") return out;
|
|
2062
|
+
for (const part of raw.split(",")) {
|
|
2063
|
+
const [k, v] = part.split("=", 2).map((s) => s.trim());
|
|
2064
|
+
if (k) out.set(k.toLowerCase(), v === void 0 ? true : v.replace(/^"|"$/g, ""));
|
|
2065
|
+
}
|
|
2066
|
+
return out;
|
|
2067
|
+
}
|
|
2068
|
+
function cloneData(data) {
|
|
2069
|
+
if (data === null || typeof data !== "object") return { ok: true, value: data };
|
|
2070
|
+
if (typeof structuredClone !== "function") return { ok: false, value: data };
|
|
2071
|
+
try {
|
|
2072
|
+
return { ok: true, value: structuredClone(data) };
|
|
2073
|
+
} catch {
|
|
2074
|
+
return { ok: false, value: data };
|
|
2075
|
+
}
|
|
2076
|
+
}
|
|
2077
|
+
function reportCacheError(op, err) {
|
|
2078
|
+
if (typeof console !== "undefined") console.error(`[exios] cache provider ${op} failed:`, err);
|
|
2079
|
+
}
|
|
2080
|
+
|
|
1870
2081
|
// src/core/requestId.ts
|
|
1871
2082
|
var seq = 0;
|
|
1872
2083
|
function createRequestId() {
|
|
@@ -1898,6 +2109,10 @@ var Exios = class {
|
|
|
1898
2109
|
breaker;
|
|
1899
2110
|
registry;
|
|
1900
2111
|
events = new EventHub();
|
|
2112
|
+
memoryCache = new MemoryCache();
|
|
2113
|
+
inflight = new InflightRequests();
|
|
2114
|
+
/** The instance cache: `defaults.cache.provider`, or the built-in in-memory cache. */
|
|
2115
|
+
cache;
|
|
1901
2116
|
constructor(defaults) {
|
|
1902
2117
|
this.defaults = defaults;
|
|
1903
2118
|
this.registry = new BreakerRegistry(
|
|
@@ -1914,6 +2129,50 @@ var Exios = class {
|
|
|
1914
2129
|
state: (key) => this.registry.state(key),
|
|
1915
2130
|
reset: (key) => this.registry.reset(key)
|
|
1916
2131
|
};
|
|
2132
|
+
const provider = () => {
|
|
2133
|
+
const c = this.defaults.cache;
|
|
2134
|
+
return typeof c === "object" && c?.provider || this.memoryCache;
|
|
2135
|
+
};
|
|
2136
|
+
this.cache = {
|
|
2137
|
+
clear: async () => {
|
|
2138
|
+
await provider().clear();
|
|
2139
|
+
},
|
|
2140
|
+
delete: async (key) => {
|
|
2141
|
+
await provider().delete(key);
|
|
2142
|
+
},
|
|
2143
|
+
key: (cfg = {}) => {
|
|
2144
|
+
const resolved = finalizeConfig(resolveConfig(mergeConfig(this.defaults, cfg)));
|
|
2145
|
+
const c = resolveCache(resolved.cache) || resolveCache(true);
|
|
2146
|
+
return c ? keyFor(resolved, c) : void 0;
|
|
2147
|
+
},
|
|
2148
|
+
invalidate: async (match) => {
|
|
2149
|
+
const p = provider();
|
|
2150
|
+
if (typeof p.keys !== "function")
|
|
2151
|
+
throw new ExiosError(
|
|
2152
|
+
"cache.invalidate needs a cache provider with keys()",
|
|
2153
|
+
ExiosError.ERR_NOT_SUPPORT
|
|
2154
|
+
);
|
|
2155
|
+
let test;
|
|
2156
|
+
if (typeof match === "function") test = match;
|
|
2157
|
+
else if (match instanceof RegExp) test = (k) => match.test(k);
|
|
2158
|
+
else {
|
|
2159
|
+
const target = requestTarget({ ...this.defaults, url: match, params: void 0 });
|
|
2160
|
+
const prefix = target.slice(target.indexOf(" ") + 1);
|
|
2161
|
+
test = (k) => {
|
|
2162
|
+
const u = keyURL(k);
|
|
2163
|
+
return u !== void 0 && (u === prefix || u.startsWith(prefix + "/") || u.startsWith(prefix + "?"));
|
|
2164
|
+
};
|
|
2165
|
+
}
|
|
2166
|
+
let n = 0;
|
|
2167
|
+
for (const k of [...await p.keys()]) {
|
|
2168
|
+
if (test(k)) {
|
|
2169
|
+
await p.delete(k);
|
|
2170
|
+
n++;
|
|
2171
|
+
}
|
|
2172
|
+
}
|
|
2173
|
+
return n;
|
|
2174
|
+
}
|
|
2175
|
+
};
|
|
1917
2176
|
}
|
|
1918
2177
|
async request(configOrUrl, config) {
|
|
1919
2178
|
const cfg = typeof configOrUrl === "string" ? { ...config, url: configOrUrl } : { ...configOrUrl };
|
|
@@ -1956,13 +2215,104 @@ var Exios = class {
|
|
|
1956
2215
|
off(name, listener) {
|
|
1957
2216
|
this.events.off(name, listener);
|
|
1958
2217
|
}
|
|
1959
|
-
/**
|
|
2218
|
+
/**
|
|
2219
|
+
* After request interceptors: ids → cache read → dedupe → network → cache write.
|
|
2220
|
+
* Cache hits and deduplicated followers make no network request and emit no lifecycle events.
|
|
2221
|
+
*/
|
|
1960
2222
|
async dispatch(config) {
|
|
1961
|
-
const
|
|
1962
|
-
|
|
2223
|
+
const start = Date.now();
|
|
2224
|
+
config.requestId ??= createRequestId();
|
|
2225
|
+
const totalTimeout = config.totalTimeout ?? 0;
|
|
2226
|
+
if (typeof totalTimeout !== "number" || !(totalTimeout >= 0) || !Number.isFinite(totalTimeout))
|
|
2227
|
+
bad("totalTimeout", totalTimeout, "a non-negative finite number");
|
|
2228
|
+
const cacheCfg = resolveCache(config.cache);
|
|
2229
|
+
const dedupeCfg = resolveDedupe(config.dedupe);
|
|
2230
|
+
const cacheKey = cacheCfg ? keyFor(config, cacheCfg) : void 0;
|
|
2231
|
+
const dedupeKey = dedupeCfg ? keyFor(config, dedupeCfg) : void 0;
|
|
2232
|
+
const provider = cacheCfg ? cacheCfg.provider ?? this.memoryCache : void 0;
|
|
2233
|
+
const reqCC = cacheCfg && cacheCfg.respectCacheControl ? parseCacheControl(config.headers["cache-control"]) : void 0;
|
|
2234
|
+
if (cacheKey !== void 0 && provider && !reqCC?.has("no-cache") && !reqCC?.has("no-store")) {
|
|
2235
|
+
let entry;
|
|
2236
|
+
try {
|
|
2237
|
+
entry = await provider.get(cacheKey);
|
|
2238
|
+
} catch (e) {
|
|
2239
|
+
reportCacheError("get", e);
|
|
2240
|
+
}
|
|
2241
|
+
if (entry && entry.expiresAt > Date.now()) {
|
|
2242
|
+
const copy2 = cloneData(entry.data);
|
|
2243
|
+
return this.localResponse(config, start, {
|
|
2244
|
+
data: copy2.value,
|
|
2245
|
+
status: entry.status,
|
|
2246
|
+
statusText: entry.statusText,
|
|
2247
|
+
headers: { ...entry.headers },
|
|
2248
|
+
request: null,
|
|
2249
|
+
meta: { attempts: 0, cached: true }
|
|
2250
|
+
});
|
|
2251
|
+
}
|
|
2252
|
+
}
|
|
1963
2253
|
const header = config.correlationIdHeader?.toLowerCase();
|
|
1964
2254
|
if (header && config.headers[header] === void 0)
|
|
1965
|
-
config.headers = { ...config.headers, [header]: correlationId ?? requestId };
|
|
2255
|
+
config.headers = { ...config.headers, [header]: config.correlationId ?? config.requestId };
|
|
2256
|
+
const network = async (c) => {
|
|
2257
|
+
const response2 = await this.network(c, start, totalTimeout);
|
|
2258
|
+
if (cacheKey !== void 0 && provider && cacheCfg && !reqCC?.has("no-store"))
|
|
2259
|
+
this.store(provider, cacheKey, response2, cacheCfg);
|
|
2260
|
+
return response2;
|
|
2261
|
+
};
|
|
2262
|
+
if (dedupeKey === void 0) return network(config);
|
|
2263
|
+
const { response, leader } = await this.inflight.join(
|
|
2264
|
+
dedupeKey,
|
|
2265
|
+
config,
|
|
2266
|
+
(signal) => network({ ...config, signal, cancelToken: void 0 })
|
|
2267
|
+
);
|
|
2268
|
+
if (leader) return response;
|
|
2269
|
+
const copy = cloneData(response.data);
|
|
2270
|
+
return this.localResponse(config, start, {
|
|
2271
|
+
...response,
|
|
2272
|
+
data: copy.value,
|
|
2273
|
+
headers: { ...response.headers },
|
|
2274
|
+
meta: { attempts: response.meta.attempts, deduped: true }
|
|
2275
|
+
});
|
|
2276
|
+
}
|
|
2277
|
+
/** A response made without a network request of its own (cache hit, deduplicated follower). */
|
|
2278
|
+
localResponse(config, start, r) {
|
|
2279
|
+
r.meta.requestId = config.requestId;
|
|
2280
|
+
if (config.correlationId !== void 0) r.meta.correlationId = config.correlationId;
|
|
2281
|
+
r.meta.durationMs = Date.now() - start;
|
|
2282
|
+
return { ...r, config };
|
|
2283
|
+
}
|
|
2284
|
+
/** Store a successful response; provider failures are reported, never thrown. */
|
|
2285
|
+
store(provider, key, response, cfg) {
|
|
2286
|
+
if (response.status < 200 || response.status >= 300) return;
|
|
2287
|
+
let ttl = cfg.ttl;
|
|
2288
|
+
if (cfg.respectCacheControl) {
|
|
2289
|
+
const cc = parseCacheControl(response.headers["cache-control"]);
|
|
2290
|
+
if (cc.has("no-store") || cc.has("no-cache")) return;
|
|
2291
|
+
const maxAge = Number(cc.get("max-age"));
|
|
2292
|
+
if (cc.has("max-age") && Number.isFinite(maxAge)) ttl = Math.min(ttl, maxAge * 1e3);
|
|
2293
|
+
}
|
|
2294
|
+
if (ttl <= 0) return;
|
|
2295
|
+
const copy = cloneData(response.data);
|
|
2296
|
+
if (!copy.ok) return;
|
|
2297
|
+
const now = Date.now();
|
|
2298
|
+
try {
|
|
2299
|
+
const r = provider.set(key, {
|
|
2300
|
+
status: response.status,
|
|
2301
|
+
statusText: response.statusText,
|
|
2302
|
+
headers: { ...response.headers },
|
|
2303
|
+
data: copy.value,
|
|
2304
|
+
storedAt: now,
|
|
2305
|
+
expiresAt: now + ttl
|
|
2306
|
+
});
|
|
2307
|
+
if (isThenable(r)) Promise.resolve(r).catch((e) => reportCacheError("set", e));
|
|
2308
|
+
} catch (e) {
|
|
2309
|
+
reportCacheError("set", e);
|
|
2310
|
+
}
|
|
2311
|
+
}
|
|
2312
|
+
/** totalTimeout, timing, error context and lifecycle events around dispatchRequest. */
|
|
2313
|
+
async network(config, start, totalTimeout) {
|
|
2314
|
+
const requestId = config.requestId;
|
|
2315
|
+
const { correlationId, metadata } = config;
|
|
1966
2316
|
const hub = this.events;
|
|
1967
2317
|
const url = buildFullPath(config.baseURL, config.url, config.allowAbsoluteUrls);
|
|
1968
2318
|
const base = () => ({
|
|
@@ -1971,9 +2321,9 @@ var Exios = class {
|
|
|
1971
2321
|
method: config.method,
|
|
1972
2322
|
url,
|
|
1973
2323
|
config,
|
|
2324
|
+
metadata,
|
|
1974
2325
|
timestamp: Date.now()
|
|
1975
2326
|
});
|
|
1976
|
-
const start = Date.now();
|
|
1977
2327
|
const observer = {
|
|
1978
2328
|
onRetry: (o) => hub.emit("retry", () => ({
|
|
1979
2329
|
...base(),
|
|
@@ -1986,15 +2336,55 @@ var Exios = class {
|
|
|
1986
2336
|
if (TIMEOUT_CODES.has(error.code ?? ""))
|
|
1987
2337
|
hub.emit("timeout", () => ({
|
|
1988
2338
|
...base(),
|
|
2339
|
+
kind: "attempt",
|
|
1989
2340
|
attempt,
|
|
1990
2341
|
timeoutMs: config.timeout ?? 0,
|
|
1991
2342
|
error
|
|
1992
2343
|
}));
|
|
1993
2344
|
}
|
|
1994
2345
|
};
|
|
2346
|
+
let timer;
|
|
2347
|
+
let totalFired = false;
|
|
2348
|
+
let joined;
|
|
2349
|
+
let dispatchConfig = config;
|
|
2350
|
+
if (totalTimeout > 0) {
|
|
2351
|
+
const ac = new AbortController();
|
|
2352
|
+
timer = setTimeout(() => {
|
|
2353
|
+
totalFired = true;
|
|
2354
|
+
ac.abort(new Error("totalTimeout"));
|
|
2355
|
+
}, totalTimeout);
|
|
2356
|
+
joined = combineSignals(config.signal, ac.signal);
|
|
2357
|
+
dispatchConfig = { ...config, signal: joined.signal };
|
|
2358
|
+
}
|
|
2359
|
+
let deferCleanup = false;
|
|
1995
2360
|
hub.emit("request", base);
|
|
1996
2361
|
try {
|
|
1997
|
-
|
|
2362
|
+
let response;
|
|
2363
|
+
try {
|
|
2364
|
+
response = await dispatchRequest(dispatchConfig, this.registry, observer);
|
|
2365
|
+
} catch (e) {
|
|
2366
|
+
if (!totalFired || config.signal?.aborted || !isCancel(e)) throw e;
|
|
2367
|
+
const err = new ExiosError(
|
|
2368
|
+
`total timeout of ${totalTimeout}ms exceeded`,
|
|
2369
|
+
config.transitional?.clarifyTimeoutError ? ExiosError.ETIMEDOUT : ExiosError.ECONNABORTED,
|
|
2370
|
+
config,
|
|
2371
|
+
e.request
|
|
2372
|
+
);
|
|
2373
|
+
err.cause = e;
|
|
2374
|
+
err.meta.attempts = e.meta.attempts;
|
|
2375
|
+
hub.emit("timeout", () => ({
|
|
2376
|
+
...base(),
|
|
2377
|
+
kind: "total",
|
|
2378
|
+
attempt: err.meta.attempts,
|
|
2379
|
+
timeoutMs: totalTimeout,
|
|
2380
|
+
error: err
|
|
2381
|
+
}));
|
|
2382
|
+
throw err;
|
|
2383
|
+
}
|
|
2384
|
+
if (joined && isOneShotBody(response.data)) {
|
|
2385
|
+
response.data = whenBodyDone(response.data, joined.cleanup);
|
|
2386
|
+
deferCleanup = true;
|
|
2387
|
+
}
|
|
1998
2388
|
const durationMs = Date.now() - start;
|
|
1999
2389
|
const meta = response.meta;
|
|
2000
2390
|
meta.requestId = requestId;
|
|
@@ -2034,6 +2424,9 @@ var Exios = class {
|
|
|
2034
2424
|
}));
|
|
2035
2425
|
}
|
|
2036
2426
|
throw e;
|
|
2427
|
+
} finally {
|
|
2428
|
+
if (timer !== void 0) clearTimeout(timer);
|
|
2429
|
+
if (joined && !deferCleanup) joined.cleanup();
|
|
2037
2430
|
}
|
|
2038
2431
|
}
|
|
2039
2432
|
/** Runs every request interceptor in this tick with promise-chain semantics, then dispatches. */
|
|
@@ -2146,7 +2539,10 @@ function detachDefaults(d) {
|
|
|
2146
2539
|
"transitional",
|
|
2147
2540
|
"fetchOptions",
|
|
2148
2541
|
"auth",
|
|
2149
|
-
"breaker"
|
|
2542
|
+
"breaker",
|
|
2543
|
+
"metadata",
|
|
2544
|
+
"cache",
|
|
2545
|
+
"dedupe"
|
|
2150
2546
|
]) {
|
|
2151
2547
|
if (isPlainObject4(out[k])) out[k] = { ...out[k] };
|
|
2152
2548
|
}
|
|
@@ -2176,6 +2572,7 @@ function createInstance(defaults) {
|
|
|
2176
2572
|
});
|
|
2177
2573
|
instance.interceptors = context.interceptors;
|
|
2178
2574
|
instance.breaker = context.breaker;
|
|
2575
|
+
instance.cache = context.cache;
|
|
2179
2576
|
instance.create = (cfg) => createInstance(detachDefaults(mergeConfig(context.defaults, cfg)));
|
|
2180
2577
|
return instance;
|
|
2181
2578
|
}
|
|
@@ -2191,7 +2588,8 @@ var statics = {
|
|
|
2191
2588
|
isExiosError,
|
|
2192
2589
|
isCancel,
|
|
2193
2590
|
mergeConfig,
|
|
2194
|
-
toFormData
|
|
2591
|
+
toFormData,
|
|
2592
|
+
MemoryCache
|
|
2195
2593
|
};
|
|
2196
2594
|
var exios = Object.assign(
|
|
2197
2595
|
createInstance(createDefaults()),
|
|
@@ -2204,6 +2602,7 @@ export {
|
|
|
2204
2602
|
CanceledError,
|
|
2205
2603
|
CircuitOpenError,
|
|
2206
2604
|
ExiosError,
|
|
2605
|
+
MemoryCache,
|
|
2207
2606
|
create,
|
|
2208
2607
|
index_default as default,
|
|
2209
2608
|
isCancel,
|