@npora/request 1.2.0 → 1.3.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 CHANGED
@@ -145,6 +145,17 @@ const user = await request.get<User>('/users/1', {
145
145
  cache.clear()
146
146
  ```
147
147
 
148
+ Equivalent concurrent cache-enabled requests share one network operation by
149
+ default. Pass a custom `CacheStore` to share cached entries across clients or
150
+ connect an external storage system:
151
+
152
+ ```ts
153
+ const cache = cachePlugin({
154
+ store: sharedStore,
155
+ dedupe: true
156
+ })
157
+ ```
158
+
148
159
  Built-in plugins:
149
160
 
150
161
  - `retryPlugin()`
package/dist/index.cjs CHANGED
@@ -23,6 +23,7 @@ __export(index_exports, {
23
23
  Client: () => Client,
24
24
  FetchAdapter: () => FetchAdapter,
25
25
  InterceptorManager: () => InterceptorManager,
26
+ MemoryCacheStore: () => MemoryCacheStore,
26
27
  MockAdapter: () => MockAdapter,
27
28
  PluginError: () => PluginError,
28
29
  RequestError: () => RequestError,
@@ -771,6 +772,12 @@ var Pipeline = class {
771
772
  }
772
773
  } finally {
773
774
  context.endTime = Date.now();
775
+ if (this.hooks.hasSettledHooks) {
776
+ try {
777
+ await this.hooks.runSettled(context);
778
+ } catch {
779
+ }
780
+ }
774
781
  }
775
782
  }
776
783
  async processResponse(context) {
@@ -911,6 +918,7 @@ var PluginHooks = class {
911
918
  this.requestHooks = new HookRegistry();
912
919
  this.responseHooks = new HookRegistry();
913
920
  this.errorHooks = new HookRegistry();
921
+ this.settledHooks = new HookRegistry();
914
922
  this.retryHooks = new HookRegistry();
915
923
  }
916
924
  get hasRequestHooks() {
@@ -925,6 +933,9 @@ var PluginHooks = class {
925
933
  get hasRetryHooks() {
926
934
  return this.retryHooks.active;
927
935
  }
936
+ get hasSettledHooks() {
937
+ return this.settledHooks.active;
938
+ }
928
939
  onRequest(hook, options = {}) {
929
940
  return this.requestHooks.register(hook, options);
930
941
  }
@@ -937,6 +948,9 @@ var PluginHooks = class {
937
948
  onRetry(hook, options = {}) {
938
949
  return this.retryHooks.register(hook, options);
939
950
  }
951
+ onSettled(hook, options = {}) {
952
+ return this.settledHooks.register(hook, options);
953
+ }
940
954
  async runRequest(context) {
941
955
  for (const hook of this.requestHooks.values()) {
942
956
  await hook(context);
@@ -952,6 +966,14 @@ var PluginHooks = class {
952
966
  await hook(context);
953
967
  }
954
968
  }
969
+ async runSettled(context) {
970
+ for (const hook of this.settledHooks.values()) {
971
+ try {
972
+ await hook(context);
973
+ } catch {
974
+ }
975
+ }
976
+ }
955
977
  async resolveRetry(context, attempt) {
956
978
  for (const hook of this.retryHooks.values()) {
957
979
  const decision = await hook(context, attempt);
@@ -1101,6 +1123,12 @@ function createScopedHooks(hooks, pluginPriority, cleanups) {
1101
1123
  cleanups
1102
1124
  );
1103
1125
  },
1126
+ onSettled(hook, options) {
1127
+ return trackHook(
1128
+ hooks.onSettled(hook, withPriority(options, pluginPriority)),
1129
+ cleanups
1130
+ );
1131
+ },
1104
1132
  onRetry(hook, options) {
1105
1133
  return trackHook(
1106
1134
  hooks.onRetry(hook, withPriority(options, pluginPriority)),
@@ -1504,6 +1532,23 @@ function defaultShouldRefresh(error) {
1504
1532
  }
1505
1533
 
1506
1534
  // src/plugins/cachePlugin.ts
1535
+ var MemoryCacheStore = class {
1536
+ constructor() {
1537
+ this.entries = /* @__PURE__ */ new Map();
1538
+ }
1539
+ get(key) {
1540
+ return this.entries.get(key);
1541
+ }
1542
+ set(key, entry) {
1543
+ this.entries.set(key, entry);
1544
+ }
1545
+ delete(key) {
1546
+ this.entries.delete(key);
1547
+ }
1548
+ clear() {
1549
+ this.entries.clear();
1550
+ }
1551
+ };
1507
1552
  var DEFAULT_CACHE_METHODS = [
1508
1553
  "GET",
1509
1554
  "HEAD"
@@ -1515,8 +1560,11 @@ var DEFAULT_VARY_HEADERS = [
1515
1560
  "accept-language"
1516
1561
  ];
1517
1562
  function cachePlugin(options = {}) {
1518
- const cacheStore = /* @__PURE__ */ new Map();
1563
+ const store = options.store ?? new MemoryCacheStore();
1519
1564
  const cacheHits = /* @__PURE__ */ new WeakSet();
1565
+ const leaders = /* @__PURE__ */ new WeakMap();
1566
+ const completedRecords = /* @__PURE__ */ new WeakMap();
1567
+ const inFlight = /* @__PURE__ */ new Map();
1520
1568
  const methods = new Set(
1521
1569
  options.methods ?? DEFAULT_CACHE_METHODS
1522
1570
  );
@@ -1524,10 +1572,12 @@ function cachePlugin(options = {}) {
1524
1572
  const plugin = {
1525
1573
  name: "cache",
1526
1574
  clear() {
1527
- cacheStore.clear();
1575
+ return store.clear();
1528
1576
  },
1529
1577
  install(context) {
1530
- context.hooks.onRequest((requestContext) => {
1578
+ const ownedLeaders = /* @__PURE__ */ new Set();
1579
+ let active = true;
1580
+ context.hooks.onRequest(async (requestContext) => {
1531
1581
  const cache = resolveExtensionConfig(
1532
1582
  requestContext.config,
1533
1583
  "cache"
@@ -1540,25 +1590,48 @@ function cachePlugin(options = {}) {
1540
1590
  cache,
1541
1591
  varyHeaders
1542
1592
  );
1543
- const record = cacheStore.get(key);
1544
- if (!record) {
1593
+ const record = await readStore(store, key);
1594
+ if (!active) {
1545
1595
  return;
1546
1596
  }
1547
- if (Date.now() > record.expiresAt) {
1548
- cacheStore.delete(key);
1597
+ if (record) {
1598
+ if (!Number.isFinite(record.expiresAt) || Date.now() > record.expiresAt) {
1599
+ await deleteStore(store, key);
1600
+ } else {
1601
+ const cachedResponse = restoreCacheEntry(
1602
+ record,
1603
+ requestContext.config
1604
+ );
1605
+ if (cachedResponse) {
1606
+ requestContext.response = cachedResponse;
1607
+ cacheHits.add(requestContext);
1608
+ return;
1609
+ }
1610
+ await deleteStore(store, key);
1611
+ }
1612
+ }
1613
+ if (!(cache.dedupe ?? options.dedupe ?? true)) {
1549
1614
  return;
1550
1615
  }
1551
- requestContext.response = {
1552
- data: cloneCacheValue(record.data),
1553
- status: record.status,
1554
- statusText: record.statusText,
1555
- headers: new Headers(record.headers),
1556
- config: requestContext.config,
1557
- raw: cloneRawResponse(record)
1558
- };
1559
- cacheHits.add(requestContext);
1616
+ const pending = inFlight.get(key);
1617
+ if (pending) {
1618
+ const sharedRecord = await waitForSharedRecord(
1619
+ pending.promise,
1620
+ requestContext.config
1621
+ );
1622
+ requestContext.response = createCachedResponse(
1623
+ sharedRecord,
1624
+ requestContext.config
1625
+ );
1626
+ cacheHits.add(requestContext);
1627
+ return;
1628
+ }
1629
+ const created = createInFlightRequest(requestContext);
1630
+ inFlight.set(key, created);
1631
+ leaders.set(requestContext, key);
1632
+ ownedLeaders.add(requestContext);
1560
1633
  });
1561
- context.hooks.onResponse((requestContext) => {
1634
+ context.hooks.onResponse(async (requestContext) => {
1562
1635
  if (cacheHits.has(requestContext)) {
1563
1636
  return;
1564
1637
  }
@@ -1575,23 +1648,184 @@ function cachePlugin(options = {}) {
1575
1648
  varyHeaders
1576
1649
  );
1577
1650
  const ttl = cache.ttl ?? 3e4;
1651
+ const record = createCacheEntry(
1652
+ requestContext.response,
1653
+ Date.now() + Math.max(0, ttl)
1654
+ );
1655
+ completedRecords.set(requestContext, record);
1578
1656
  if (ttl <= 0) {
1579
- cacheStore.delete(key);
1657
+ await deleteStore(store, key);
1580
1658
  return;
1581
1659
  }
1582
- cacheStore.set(key, {
1583
- data: cloneCacheValue(requestContext.response.data),
1584
- expiresAt: Date.now() + ttl,
1585
- status: requestContext.response.status,
1586
- statusText: requestContext.response.statusText,
1587
- headers: new Headers(requestContext.response.headers),
1588
- raw: cloneResponse(requestContext.response.raw)
1589
- });
1660
+ await writeStore(store, key, record);
1661
+ });
1662
+ context.hooks.onSettled((requestContext) => {
1663
+ const key = leaders.get(requestContext);
1664
+ if (!key) {
1665
+ return;
1666
+ }
1667
+ leaders.delete(requestContext);
1668
+ ownedLeaders.delete(requestContext);
1669
+ const pending = inFlight.get(key);
1670
+ if (!pending || pending.owner !== requestContext) {
1671
+ return;
1672
+ }
1673
+ inFlight.delete(key);
1674
+ const record = completedRecords.get(requestContext);
1675
+ completedRecords.delete(requestContext);
1676
+ if (record && requestContext.response && !requestContext.error) {
1677
+ pending.resolve(record);
1678
+ return;
1679
+ }
1680
+ pending.reject(
1681
+ requestContext.error ?? new RequestError("Shared request failed", {
1682
+ code: "NETWORK_ERROR",
1683
+ config: requestContext.config
1684
+ })
1685
+ );
1590
1686
  });
1687
+ return () => {
1688
+ active = false;
1689
+ for (const owner of ownedLeaders) {
1690
+ const key = leaders.get(owner);
1691
+ leaders.delete(owner);
1692
+ if (!key) {
1693
+ continue;
1694
+ }
1695
+ const pending = inFlight.get(key);
1696
+ if (!pending || pending.owner !== owner) {
1697
+ continue;
1698
+ }
1699
+ inFlight.delete(key);
1700
+ pending.reject(
1701
+ new RequestError("Cache plugin removed during shared request", {
1702
+ code: "ABORT_ERROR"
1703
+ })
1704
+ );
1705
+ }
1706
+ ownedLeaders.clear();
1707
+ };
1591
1708
  }
1592
1709
  };
1593
1710
  return plugin;
1594
1711
  }
1712
+ function createInFlightRequest(owner) {
1713
+ let resolve;
1714
+ let reject;
1715
+ const promise = new Promise((resolvePromise, rejectPromise) => {
1716
+ resolve = resolvePromise;
1717
+ reject = rejectPromise;
1718
+ });
1719
+ void promise.catch(() => {
1720
+ });
1721
+ return {
1722
+ owner,
1723
+ promise,
1724
+ resolve,
1725
+ reject
1726
+ };
1727
+ }
1728
+ async function readStore(store, key) {
1729
+ try {
1730
+ return await store.get(key);
1731
+ } catch {
1732
+ return void 0;
1733
+ }
1734
+ }
1735
+ async function writeStore(store, key, entry) {
1736
+ try {
1737
+ await store.set(key, entry);
1738
+ } catch {
1739
+ }
1740
+ }
1741
+ async function deleteStore(store, key) {
1742
+ try {
1743
+ await store.delete(key);
1744
+ } catch {
1745
+ }
1746
+ }
1747
+ async function waitForSharedRecord(promise, config) {
1748
+ const signal = config.signal;
1749
+ if (!signal) {
1750
+ try {
1751
+ return await promise;
1752
+ } catch (error) {
1753
+ throw cloneSharedError(error, config);
1754
+ }
1755
+ }
1756
+ if (signal.aborted) {
1757
+ throw createSharedAbortError(signal.reason, config);
1758
+ }
1759
+ return new Promise((resolve, reject) => {
1760
+ const cleanup = () => {
1761
+ signal.removeEventListener("abort", onAbort);
1762
+ };
1763
+ const onAbort = () => {
1764
+ cleanup();
1765
+ reject(createSharedAbortError(signal.reason, config));
1766
+ };
1767
+ signal.addEventListener("abort", onAbort, {
1768
+ once: true
1769
+ });
1770
+ promise.then(
1771
+ (entry) => {
1772
+ cleanup();
1773
+ resolve(entry);
1774
+ },
1775
+ (error) => {
1776
+ cleanup();
1777
+ reject(cloneSharedError(error, config));
1778
+ }
1779
+ );
1780
+ });
1781
+ }
1782
+ function createSharedAbortError(reason, config) {
1783
+ return new RequestError("Request aborted while waiting for shared response", {
1784
+ code: "ABORT_ERROR",
1785
+ config,
1786
+ cause: reason
1787
+ });
1788
+ }
1789
+ function cloneSharedError(error, config) {
1790
+ if (!(error instanceof RequestError)) {
1791
+ return error;
1792
+ }
1793
+ return new RequestError(error.message, {
1794
+ code: error.code,
1795
+ status: error.status,
1796
+ data: error.data,
1797
+ response: error.response,
1798
+ config,
1799
+ cause: error
1800
+ });
1801
+ }
1802
+ function createCacheEntry(response, expiresAt) {
1803
+ return {
1804
+ data: cloneCacheValue(response.data),
1805
+ expiresAt,
1806
+ status: response.status,
1807
+ statusText: response.statusText,
1808
+ headers: [...response.headers.entries()],
1809
+ raw: cloneResponse(response.raw)
1810
+ };
1811
+ }
1812
+ function createCachedResponse(record, config) {
1813
+ return {
1814
+ data: cloneCacheValue(record.data),
1815
+ status: record.status,
1816
+ statusText: record.statusText,
1817
+ headers: new Headers(record.headers),
1818
+ config,
1819
+ raw: cloneRawResponse(record)
1820
+ };
1821
+ }
1822
+ function restoreCacheEntry(record, config) {
1823
+ try {
1824
+ return createCachedResponse(record, config);
1825
+ } catch {
1826
+ return void 0;
1827
+ }
1828
+ }
1595
1829
  function isCacheableRequest(config, methods) {
1596
1830
  return methods.has(config.method ?? "GET") && config.responseType !== "stream";
1597
1831
  }
@@ -2590,6 +2824,7 @@ function uploadPlugin() {
2590
2824
  Client,
2591
2825
  FetchAdapter,
2592
2826
  InterceptorManager,
2827
+ MemoryCacheStore,
2593
2828
  MockAdapter,
2594
2829
  PluginError,
2595
2830
  RequestError,
package/dist/index.d.cts CHANGED
@@ -71,6 +71,12 @@ interface CacheOptions {
71
71
  enabled?: boolean;
72
72
  ttl?: number;
73
73
  key?: string;
74
+ /**
75
+ * Share one network operation between concurrent equivalent requests.
76
+ *
77
+ * @default true
78
+ */
79
+ dedupe?: boolean;
74
80
  }
75
81
  interface AuthOptions {
76
82
  token?: string | (() => string | Promise<string>);
@@ -349,6 +355,12 @@ interface PluginHookManager {
349
355
  onRequest(hook: RequestHook, options?: HookOptions): HookDisposer;
350
356
  onResponse(hook: RequestHook, options?: HookOptions): HookDisposer;
351
357
  onError(hook: RequestHook, options?: HookOptions): HookDisposer;
358
+ /**
359
+ * Observe the final request outcome after retries and interceptors finish.
360
+ *
361
+ * Settled hook failures are isolated from the request result.
362
+ */
363
+ onSettled(hook: RequestHook, options?: HookOptions): HookDisposer;
352
364
  onRetry(hook: RetryHook, options?: HookOptions): HookDisposer;
353
365
  }
354
366
  interface PluginContext {
@@ -484,7 +496,7 @@ declare class PluginError extends Error {
484
496
  constructor(message: string, options: PluginErrorOptions);
485
497
  }
486
498
 
487
- type MaybePromise<T> = T | Promise<T>;
499
+ type MaybePromise$1<T> = T | Promise<T>;
488
500
  /**
489
501
  * Token storage used by the authentication extension.
490
502
  *
@@ -492,9 +504,9 @@ type MaybePromise<T> = T | Promise<T>;
492
504
  * The request library does not access localStorage or sessionStorage directly.
493
505
  */
494
506
  interface AuthTokenStorage {
495
- get(): MaybePromise<string | null | undefined>;
496
- set(token: string): MaybePromise<void>;
497
- remove(): MaybePromise<void>;
507
+ get(): MaybePromise$1<string | null | undefined>;
508
+ set(token: string): MaybePromise$1<void>;
509
+ remove(): MaybePromise$1<void>;
498
510
  }
499
511
  interface AuthPluginOptions {
500
512
  /**
@@ -504,7 +516,7 @@ interface AuthPluginOptions {
504
516
  * the request-level token has the highest priority,
505
517
  * followed by this token option, then storage.
506
518
  */
507
- token?: string | (() => MaybePromise<string>);
519
+ token?: string | (() => MaybePromise$1<string>);
508
520
  /**
509
521
  * Authorization scheme.
510
522
  *
@@ -521,19 +533,41 @@ interface AuthPluginOptions {
521
533
  * Returning a token stores it through storage when configured.
522
534
  * Returning void allows the callback to update external state itself.
523
535
  */
524
- refreshToken?: () => MaybePromise<string | void>;
536
+ refreshToken?: () => MaybePromise$1<string | void>;
525
537
  /**
526
538
  * Determine whether an error should trigger token refresh.
527
539
  *
528
540
  * @default HTTP status 401
529
541
  */
530
- shouldRefresh?: (error: unknown) => MaybePromise<boolean>;
542
+ shouldRefresh?: (error: unknown) => MaybePromise$1<boolean>;
531
543
  }
532
544
  /**
533
545
  * Authentication plugin.
534
546
  */
535
547
  declare function authPlugin(options?: AuthPluginOptions): Plugin;
536
548
 
549
+ type MaybePromise<T> = T | Promise<T>;
550
+ interface CacheEntry {
551
+ data: unknown;
552
+ expiresAt: number;
553
+ status: number;
554
+ statusText: string;
555
+ headers: Array<[string, string]>;
556
+ raw?: Response;
557
+ }
558
+ interface CacheStore {
559
+ get(key: string): MaybePromise<CacheEntry | undefined>;
560
+ set(key: string, entry: CacheEntry): MaybePromise<void>;
561
+ delete(key: string): MaybePromise<void>;
562
+ clear(): MaybePromise<void>;
563
+ }
564
+ declare class MemoryCacheStore implements CacheStore {
565
+ private readonly entries;
566
+ get(key: string): CacheEntry | undefined;
567
+ set(key: string, entry: CacheEntry): void;
568
+ delete(key: string): void;
569
+ clear(): void;
570
+ }
537
571
  interface CachePluginOptions {
538
572
  /**
539
573
  * HTTP methods that may be cached.
@@ -547,9 +581,21 @@ interface CachePluginOptions {
547
581
  * @default authorization, cookie, accept and accept-language
548
582
  */
549
583
  varyHeaders?: readonly string[];
584
+ /**
585
+ * Cache storage shared by this plugin instance.
586
+ *
587
+ * @default an isolated MemoryCacheStore
588
+ */
589
+ store?: CacheStore;
590
+ /**
591
+ * Share one network operation between concurrent equivalent requests.
592
+ *
593
+ * @default true
594
+ */
595
+ dedupe?: boolean;
550
596
  }
551
597
  interface CachePlugin extends Plugin {
552
- clear(): void;
598
+ clear(): MaybePromise<void>;
553
599
  }
554
600
  declare function cachePlugin(options?: CachePluginOptions): CachePlugin;
555
601
 
@@ -573,4 +619,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
573
619
 
574
620
  declare function uploadPlugin(): Plugin;
575
621
 
576
- export { type Adapter, type AuthOptions, type AuthPluginOptions, type AuthTokenStorage, type CacheOptions, type CachePlugin, type CachePluginOptions, Client, type ClientOptions, type DownloadOptions, type DownloadPluginOptions, type DownloadProgress, type DownloadTransport, type ErrorLogEntry, FetchAdapter, type FetchOptions, type HttpMethod, type Interceptor, InterceptorManager, type InterceptorOptions, type LoggerEntry, type LoggerOptions, MockAdapter, type MockAdapterOptions, type MockHandler, type NporaResponse, type Plugin, type PluginCleanup, type PluginContext, PluginError, type PluginErrorCode, type PluginErrorOptions, type PluginHookManager, type PluginInterceptorManager, type QueryParams, type QueryValue, type RequestConfig, RequestError, type RequestErrorCode, type RequestErrorOptions, type RequestExtensions, type RequestLogEntry, type RequestLogger, type ResponseLogEntry, type ResponseType, type RetryEvent, type RetryOptions, type UploadData, type UploadOptions, type UploadProgress, authPlugin, cachePlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
622
+ export { type Adapter, type AuthOptions, type AuthPluginOptions, type AuthTokenStorage, type CacheEntry, type CacheOptions, type CachePlugin, type CachePluginOptions, type CacheStore, Client, type ClientOptions, type DownloadOptions, type DownloadPluginOptions, type DownloadProgress, type DownloadTransport, type ErrorLogEntry, FetchAdapter, type FetchOptions, type HttpMethod, type Interceptor, InterceptorManager, type InterceptorOptions, type LoggerEntry, type LoggerOptions, MemoryCacheStore, MockAdapter, type MockAdapterOptions, type MockHandler, type NporaResponse, type Plugin, type PluginCleanup, type PluginContext, PluginError, type PluginErrorCode, type PluginErrorOptions, type PluginHookManager, type PluginInterceptorManager, type QueryParams, type QueryValue, type RequestConfig, RequestError, type RequestErrorCode, type RequestErrorOptions, type RequestExtensions, type RequestLogEntry, type RequestLogger, type ResponseLogEntry, type ResponseType, type RetryEvent, type RetryOptions, type UploadData, type UploadOptions, type UploadProgress, authPlugin, cachePlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
package/dist/index.d.ts CHANGED
@@ -71,6 +71,12 @@ interface CacheOptions {
71
71
  enabled?: boolean;
72
72
  ttl?: number;
73
73
  key?: string;
74
+ /**
75
+ * Share one network operation between concurrent equivalent requests.
76
+ *
77
+ * @default true
78
+ */
79
+ dedupe?: boolean;
74
80
  }
75
81
  interface AuthOptions {
76
82
  token?: string | (() => string | Promise<string>);
@@ -349,6 +355,12 @@ interface PluginHookManager {
349
355
  onRequest(hook: RequestHook, options?: HookOptions): HookDisposer;
350
356
  onResponse(hook: RequestHook, options?: HookOptions): HookDisposer;
351
357
  onError(hook: RequestHook, options?: HookOptions): HookDisposer;
358
+ /**
359
+ * Observe the final request outcome after retries and interceptors finish.
360
+ *
361
+ * Settled hook failures are isolated from the request result.
362
+ */
363
+ onSettled(hook: RequestHook, options?: HookOptions): HookDisposer;
352
364
  onRetry(hook: RetryHook, options?: HookOptions): HookDisposer;
353
365
  }
354
366
  interface PluginContext {
@@ -484,7 +496,7 @@ declare class PluginError extends Error {
484
496
  constructor(message: string, options: PluginErrorOptions);
485
497
  }
486
498
 
487
- type MaybePromise<T> = T | Promise<T>;
499
+ type MaybePromise$1<T> = T | Promise<T>;
488
500
  /**
489
501
  * Token storage used by the authentication extension.
490
502
  *
@@ -492,9 +504,9 @@ type MaybePromise<T> = T | Promise<T>;
492
504
  * The request library does not access localStorage or sessionStorage directly.
493
505
  */
494
506
  interface AuthTokenStorage {
495
- get(): MaybePromise<string | null | undefined>;
496
- set(token: string): MaybePromise<void>;
497
- remove(): MaybePromise<void>;
507
+ get(): MaybePromise$1<string | null | undefined>;
508
+ set(token: string): MaybePromise$1<void>;
509
+ remove(): MaybePromise$1<void>;
498
510
  }
499
511
  interface AuthPluginOptions {
500
512
  /**
@@ -504,7 +516,7 @@ interface AuthPluginOptions {
504
516
  * the request-level token has the highest priority,
505
517
  * followed by this token option, then storage.
506
518
  */
507
- token?: string | (() => MaybePromise<string>);
519
+ token?: string | (() => MaybePromise$1<string>);
508
520
  /**
509
521
  * Authorization scheme.
510
522
  *
@@ -521,19 +533,41 @@ interface AuthPluginOptions {
521
533
  * Returning a token stores it through storage when configured.
522
534
  * Returning void allows the callback to update external state itself.
523
535
  */
524
- refreshToken?: () => MaybePromise<string | void>;
536
+ refreshToken?: () => MaybePromise$1<string | void>;
525
537
  /**
526
538
  * Determine whether an error should trigger token refresh.
527
539
  *
528
540
  * @default HTTP status 401
529
541
  */
530
- shouldRefresh?: (error: unknown) => MaybePromise<boolean>;
542
+ shouldRefresh?: (error: unknown) => MaybePromise$1<boolean>;
531
543
  }
532
544
  /**
533
545
  * Authentication plugin.
534
546
  */
535
547
  declare function authPlugin(options?: AuthPluginOptions): Plugin;
536
548
 
549
+ type MaybePromise<T> = T | Promise<T>;
550
+ interface CacheEntry {
551
+ data: unknown;
552
+ expiresAt: number;
553
+ status: number;
554
+ statusText: string;
555
+ headers: Array<[string, string]>;
556
+ raw?: Response;
557
+ }
558
+ interface CacheStore {
559
+ get(key: string): MaybePromise<CacheEntry | undefined>;
560
+ set(key: string, entry: CacheEntry): MaybePromise<void>;
561
+ delete(key: string): MaybePromise<void>;
562
+ clear(): MaybePromise<void>;
563
+ }
564
+ declare class MemoryCacheStore implements CacheStore {
565
+ private readonly entries;
566
+ get(key: string): CacheEntry | undefined;
567
+ set(key: string, entry: CacheEntry): void;
568
+ delete(key: string): void;
569
+ clear(): void;
570
+ }
537
571
  interface CachePluginOptions {
538
572
  /**
539
573
  * HTTP methods that may be cached.
@@ -547,9 +581,21 @@ interface CachePluginOptions {
547
581
  * @default authorization, cookie, accept and accept-language
548
582
  */
549
583
  varyHeaders?: readonly string[];
584
+ /**
585
+ * Cache storage shared by this plugin instance.
586
+ *
587
+ * @default an isolated MemoryCacheStore
588
+ */
589
+ store?: CacheStore;
590
+ /**
591
+ * Share one network operation between concurrent equivalent requests.
592
+ *
593
+ * @default true
594
+ */
595
+ dedupe?: boolean;
550
596
  }
551
597
  interface CachePlugin extends Plugin {
552
- clear(): void;
598
+ clear(): MaybePromise<void>;
553
599
  }
554
600
  declare function cachePlugin(options?: CachePluginOptions): CachePlugin;
555
601
 
@@ -573,4 +619,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
573
619
 
574
620
  declare function uploadPlugin(): Plugin;
575
621
 
576
- export { type Adapter, type AuthOptions, type AuthPluginOptions, type AuthTokenStorage, type CacheOptions, type CachePlugin, type CachePluginOptions, Client, type ClientOptions, type DownloadOptions, type DownloadPluginOptions, type DownloadProgress, type DownloadTransport, type ErrorLogEntry, FetchAdapter, type FetchOptions, type HttpMethod, type Interceptor, InterceptorManager, type InterceptorOptions, type LoggerEntry, type LoggerOptions, MockAdapter, type MockAdapterOptions, type MockHandler, type NporaResponse, type Plugin, type PluginCleanup, type PluginContext, PluginError, type PluginErrorCode, type PluginErrorOptions, type PluginHookManager, type PluginInterceptorManager, type QueryParams, type QueryValue, type RequestConfig, RequestError, type RequestErrorCode, type RequestErrorOptions, type RequestExtensions, type RequestLogEntry, type RequestLogger, type ResponseLogEntry, type ResponseType, type RetryEvent, type RetryOptions, type UploadData, type UploadOptions, type UploadProgress, authPlugin, cachePlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
622
+ export { type Adapter, type AuthOptions, type AuthPluginOptions, type AuthTokenStorage, type CacheEntry, type CacheOptions, type CachePlugin, type CachePluginOptions, type CacheStore, Client, type ClientOptions, type DownloadOptions, type DownloadPluginOptions, type DownloadProgress, type DownloadTransport, type ErrorLogEntry, FetchAdapter, type FetchOptions, type HttpMethod, type Interceptor, InterceptorManager, type InterceptorOptions, type LoggerEntry, type LoggerOptions, MemoryCacheStore, MockAdapter, type MockAdapterOptions, type MockHandler, type NporaResponse, type Plugin, type PluginCleanup, type PluginContext, PluginError, type PluginErrorCode, type PluginErrorOptions, type PluginHookManager, type PluginInterceptorManager, type QueryParams, type QueryValue, type RequestConfig, RequestError, type RequestErrorCode, type RequestErrorOptions, type RequestExtensions, type RequestLogEntry, type RequestLogger, type ResponseLogEntry, type ResponseType, type RetryEvent, type RetryOptions, type UploadData, type UploadOptions, type UploadProgress, authPlugin, cachePlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
package/dist/index.js CHANGED
@@ -733,6 +733,12 @@ var Pipeline = class {
733
733
  }
734
734
  } finally {
735
735
  context.endTime = Date.now();
736
+ if (this.hooks.hasSettledHooks) {
737
+ try {
738
+ await this.hooks.runSettled(context);
739
+ } catch {
740
+ }
741
+ }
736
742
  }
737
743
  }
738
744
  async processResponse(context) {
@@ -873,6 +879,7 @@ var PluginHooks = class {
873
879
  this.requestHooks = new HookRegistry();
874
880
  this.responseHooks = new HookRegistry();
875
881
  this.errorHooks = new HookRegistry();
882
+ this.settledHooks = new HookRegistry();
876
883
  this.retryHooks = new HookRegistry();
877
884
  }
878
885
  get hasRequestHooks() {
@@ -887,6 +894,9 @@ var PluginHooks = class {
887
894
  get hasRetryHooks() {
888
895
  return this.retryHooks.active;
889
896
  }
897
+ get hasSettledHooks() {
898
+ return this.settledHooks.active;
899
+ }
890
900
  onRequest(hook, options = {}) {
891
901
  return this.requestHooks.register(hook, options);
892
902
  }
@@ -899,6 +909,9 @@ var PluginHooks = class {
899
909
  onRetry(hook, options = {}) {
900
910
  return this.retryHooks.register(hook, options);
901
911
  }
912
+ onSettled(hook, options = {}) {
913
+ return this.settledHooks.register(hook, options);
914
+ }
902
915
  async runRequest(context) {
903
916
  for (const hook of this.requestHooks.values()) {
904
917
  await hook(context);
@@ -914,6 +927,14 @@ var PluginHooks = class {
914
927
  await hook(context);
915
928
  }
916
929
  }
930
+ async runSettled(context) {
931
+ for (const hook of this.settledHooks.values()) {
932
+ try {
933
+ await hook(context);
934
+ } catch {
935
+ }
936
+ }
937
+ }
917
938
  async resolveRetry(context, attempt) {
918
939
  for (const hook of this.retryHooks.values()) {
919
940
  const decision = await hook(context, attempt);
@@ -1063,6 +1084,12 @@ function createScopedHooks(hooks, pluginPriority, cleanups) {
1063
1084
  cleanups
1064
1085
  );
1065
1086
  },
1087
+ onSettled(hook, options) {
1088
+ return trackHook(
1089
+ hooks.onSettled(hook, withPriority(options, pluginPriority)),
1090
+ cleanups
1091
+ );
1092
+ },
1066
1093
  onRetry(hook, options) {
1067
1094
  return trackHook(
1068
1095
  hooks.onRetry(hook, withPriority(options, pluginPriority)),
@@ -1466,6 +1493,23 @@ function defaultShouldRefresh(error) {
1466
1493
  }
1467
1494
 
1468
1495
  // src/plugins/cachePlugin.ts
1496
+ var MemoryCacheStore = class {
1497
+ constructor() {
1498
+ this.entries = /* @__PURE__ */ new Map();
1499
+ }
1500
+ get(key) {
1501
+ return this.entries.get(key);
1502
+ }
1503
+ set(key, entry) {
1504
+ this.entries.set(key, entry);
1505
+ }
1506
+ delete(key) {
1507
+ this.entries.delete(key);
1508
+ }
1509
+ clear() {
1510
+ this.entries.clear();
1511
+ }
1512
+ };
1469
1513
  var DEFAULT_CACHE_METHODS = [
1470
1514
  "GET",
1471
1515
  "HEAD"
@@ -1477,8 +1521,11 @@ var DEFAULT_VARY_HEADERS = [
1477
1521
  "accept-language"
1478
1522
  ];
1479
1523
  function cachePlugin(options = {}) {
1480
- const cacheStore = /* @__PURE__ */ new Map();
1524
+ const store = options.store ?? new MemoryCacheStore();
1481
1525
  const cacheHits = /* @__PURE__ */ new WeakSet();
1526
+ const leaders = /* @__PURE__ */ new WeakMap();
1527
+ const completedRecords = /* @__PURE__ */ new WeakMap();
1528
+ const inFlight = /* @__PURE__ */ new Map();
1482
1529
  const methods = new Set(
1483
1530
  options.methods ?? DEFAULT_CACHE_METHODS
1484
1531
  );
@@ -1486,10 +1533,12 @@ function cachePlugin(options = {}) {
1486
1533
  const plugin = {
1487
1534
  name: "cache",
1488
1535
  clear() {
1489
- cacheStore.clear();
1536
+ return store.clear();
1490
1537
  },
1491
1538
  install(context) {
1492
- context.hooks.onRequest((requestContext) => {
1539
+ const ownedLeaders = /* @__PURE__ */ new Set();
1540
+ let active = true;
1541
+ context.hooks.onRequest(async (requestContext) => {
1493
1542
  const cache = resolveExtensionConfig(
1494
1543
  requestContext.config,
1495
1544
  "cache"
@@ -1502,25 +1551,48 @@ function cachePlugin(options = {}) {
1502
1551
  cache,
1503
1552
  varyHeaders
1504
1553
  );
1505
- const record = cacheStore.get(key);
1506
- if (!record) {
1554
+ const record = await readStore(store, key);
1555
+ if (!active) {
1507
1556
  return;
1508
1557
  }
1509
- if (Date.now() > record.expiresAt) {
1510
- cacheStore.delete(key);
1558
+ if (record) {
1559
+ if (!Number.isFinite(record.expiresAt) || Date.now() > record.expiresAt) {
1560
+ await deleteStore(store, key);
1561
+ } else {
1562
+ const cachedResponse = restoreCacheEntry(
1563
+ record,
1564
+ requestContext.config
1565
+ );
1566
+ if (cachedResponse) {
1567
+ requestContext.response = cachedResponse;
1568
+ cacheHits.add(requestContext);
1569
+ return;
1570
+ }
1571
+ await deleteStore(store, key);
1572
+ }
1573
+ }
1574
+ if (!(cache.dedupe ?? options.dedupe ?? true)) {
1511
1575
  return;
1512
1576
  }
1513
- requestContext.response = {
1514
- data: cloneCacheValue(record.data),
1515
- status: record.status,
1516
- statusText: record.statusText,
1517
- headers: new Headers(record.headers),
1518
- config: requestContext.config,
1519
- raw: cloneRawResponse(record)
1520
- };
1521
- cacheHits.add(requestContext);
1577
+ const pending = inFlight.get(key);
1578
+ if (pending) {
1579
+ const sharedRecord = await waitForSharedRecord(
1580
+ pending.promise,
1581
+ requestContext.config
1582
+ );
1583
+ requestContext.response = createCachedResponse(
1584
+ sharedRecord,
1585
+ requestContext.config
1586
+ );
1587
+ cacheHits.add(requestContext);
1588
+ return;
1589
+ }
1590
+ const created = createInFlightRequest(requestContext);
1591
+ inFlight.set(key, created);
1592
+ leaders.set(requestContext, key);
1593
+ ownedLeaders.add(requestContext);
1522
1594
  });
1523
- context.hooks.onResponse((requestContext) => {
1595
+ context.hooks.onResponse(async (requestContext) => {
1524
1596
  if (cacheHits.has(requestContext)) {
1525
1597
  return;
1526
1598
  }
@@ -1537,23 +1609,184 @@ function cachePlugin(options = {}) {
1537
1609
  varyHeaders
1538
1610
  );
1539
1611
  const ttl = cache.ttl ?? 3e4;
1612
+ const record = createCacheEntry(
1613
+ requestContext.response,
1614
+ Date.now() + Math.max(0, ttl)
1615
+ );
1616
+ completedRecords.set(requestContext, record);
1540
1617
  if (ttl <= 0) {
1541
- cacheStore.delete(key);
1618
+ await deleteStore(store, key);
1542
1619
  return;
1543
1620
  }
1544
- cacheStore.set(key, {
1545
- data: cloneCacheValue(requestContext.response.data),
1546
- expiresAt: Date.now() + ttl,
1547
- status: requestContext.response.status,
1548
- statusText: requestContext.response.statusText,
1549
- headers: new Headers(requestContext.response.headers),
1550
- raw: cloneResponse(requestContext.response.raw)
1551
- });
1621
+ await writeStore(store, key, record);
1622
+ });
1623
+ context.hooks.onSettled((requestContext) => {
1624
+ const key = leaders.get(requestContext);
1625
+ if (!key) {
1626
+ return;
1627
+ }
1628
+ leaders.delete(requestContext);
1629
+ ownedLeaders.delete(requestContext);
1630
+ const pending = inFlight.get(key);
1631
+ if (!pending || pending.owner !== requestContext) {
1632
+ return;
1633
+ }
1634
+ inFlight.delete(key);
1635
+ const record = completedRecords.get(requestContext);
1636
+ completedRecords.delete(requestContext);
1637
+ if (record && requestContext.response && !requestContext.error) {
1638
+ pending.resolve(record);
1639
+ return;
1640
+ }
1641
+ pending.reject(
1642
+ requestContext.error ?? new RequestError("Shared request failed", {
1643
+ code: "NETWORK_ERROR",
1644
+ config: requestContext.config
1645
+ })
1646
+ );
1552
1647
  });
1648
+ return () => {
1649
+ active = false;
1650
+ for (const owner of ownedLeaders) {
1651
+ const key = leaders.get(owner);
1652
+ leaders.delete(owner);
1653
+ if (!key) {
1654
+ continue;
1655
+ }
1656
+ const pending = inFlight.get(key);
1657
+ if (!pending || pending.owner !== owner) {
1658
+ continue;
1659
+ }
1660
+ inFlight.delete(key);
1661
+ pending.reject(
1662
+ new RequestError("Cache plugin removed during shared request", {
1663
+ code: "ABORT_ERROR"
1664
+ })
1665
+ );
1666
+ }
1667
+ ownedLeaders.clear();
1668
+ };
1553
1669
  }
1554
1670
  };
1555
1671
  return plugin;
1556
1672
  }
1673
+ function createInFlightRequest(owner) {
1674
+ let resolve;
1675
+ let reject;
1676
+ const promise = new Promise((resolvePromise, rejectPromise) => {
1677
+ resolve = resolvePromise;
1678
+ reject = rejectPromise;
1679
+ });
1680
+ void promise.catch(() => {
1681
+ });
1682
+ return {
1683
+ owner,
1684
+ promise,
1685
+ resolve,
1686
+ reject
1687
+ };
1688
+ }
1689
+ async function readStore(store, key) {
1690
+ try {
1691
+ return await store.get(key);
1692
+ } catch {
1693
+ return void 0;
1694
+ }
1695
+ }
1696
+ async function writeStore(store, key, entry) {
1697
+ try {
1698
+ await store.set(key, entry);
1699
+ } catch {
1700
+ }
1701
+ }
1702
+ async function deleteStore(store, key) {
1703
+ try {
1704
+ await store.delete(key);
1705
+ } catch {
1706
+ }
1707
+ }
1708
+ async function waitForSharedRecord(promise, config) {
1709
+ const signal = config.signal;
1710
+ if (!signal) {
1711
+ try {
1712
+ return await promise;
1713
+ } catch (error) {
1714
+ throw cloneSharedError(error, config);
1715
+ }
1716
+ }
1717
+ if (signal.aborted) {
1718
+ throw createSharedAbortError(signal.reason, config);
1719
+ }
1720
+ return new Promise((resolve, reject) => {
1721
+ const cleanup = () => {
1722
+ signal.removeEventListener("abort", onAbort);
1723
+ };
1724
+ const onAbort = () => {
1725
+ cleanup();
1726
+ reject(createSharedAbortError(signal.reason, config));
1727
+ };
1728
+ signal.addEventListener("abort", onAbort, {
1729
+ once: true
1730
+ });
1731
+ promise.then(
1732
+ (entry) => {
1733
+ cleanup();
1734
+ resolve(entry);
1735
+ },
1736
+ (error) => {
1737
+ cleanup();
1738
+ reject(cloneSharedError(error, config));
1739
+ }
1740
+ );
1741
+ });
1742
+ }
1743
+ function createSharedAbortError(reason, config) {
1744
+ return new RequestError("Request aborted while waiting for shared response", {
1745
+ code: "ABORT_ERROR",
1746
+ config,
1747
+ cause: reason
1748
+ });
1749
+ }
1750
+ function cloneSharedError(error, config) {
1751
+ if (!(error instanceof RequestError)) {
1752
+ return error;
1753
+ }
1754
+ return new RequestError(error.message, {
1755
+ code: error.code,
1756
+ status: error.status,
1757
+ data: error.data,
1758
+ response: error.response,
1759
+ config,
1760
+ cause: error
1761
+ });
1762
+ }
1763
+ function createCacheEntry(response, expiresAt) {
1764
+ return {
1765
+ data: cloneCacheValue(response.data),
1766
+ expiresAt,
1767
+ status: response.status,
1768
+ statusText: response.statusText,
1769
+ headers: [...response.headers.entries()],
1770
+ raw: cloneResponse(response.raw)
1771
+ };
1772
+ }
1773
+ function createCachedResponse(record, config) {
1774
+ return {
1775
+ data: cloneCacheValue(record.data),
1776
+ status: record.status,
1777
+ statusText: record.statusText,
1778
+ headers: new Headers(record.headers),
1779
+ config,
1780
+ raw: cloneRawResponse(record)
1781
+ };
1782
+ }
1783
+ function restoreCacheEntry(record, config) {
1784
+ try {
1785
+ return createCachedResponse(record, config);
1786
+ } catch {
1787
+ return void 0;
1788
+ }
1789
+ }
1557
1790
  function isCacheableRequest(config, methods) {
1558
1791
  return methods.has(config.method ?? "GET") && config.responseType !== "stream";
1559
1792
  }
@@ -2551,6 +2784,7 @@ export {
2551
2784
  Client,
2552
2785
  FetchAdapter,
2553
2786
  InterceptorManager,
2787
+ MemoryCacheStore,
2554
2788
  MockAdapter,
2555
2789
  PluginError,
2556
2790
  RequestError,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@npora/request",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "description": "A modern, TypeScript-first HTTP client powered by the Fetch API.",
5
5
  "keywords": [
6
6
  "npora",