@npora/request 1.10.0 → 1.10.2

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
@@ -1,11 +1,34 @@
1
1
  # @npora/request
2
2
 
3
- A TypeScript-first HTTP client built on the standard Fetch API.
4
-
5
- Npora Request adds typed configuration, a predictable request lifecycle,
6
- runtime response validation, streaming, interceptors, plugins, unified errors,
7
- retries, caching, concurrency control, circuit breaking, authentication, and
8
- upload/download progress without adding runtime dependencies.
3
+ [![npm version](https://img.shields.io/npm/v/@npora/request.svg)](https://www.npmjs.com/package/@npora/request)
4
+ [![CI](https://github.com/npora/request/actions/workflows/ci.yml/badge.svg)](https://github.com/npora/request/actions/workflows/ci.yml)
5
+ [![Security](https://github.com/npora/request/actions/workflows/security.yml/badge.svg)](https://github.com/npora/request/actions/workflows/security.yml)
6
+ [![runtime dependencies](https://img.shields.io/badge/runtime_dependencies-0-success)](package.json)
7
+ [![license](https://img.shields.io/npm/l/@npora/request.svg)](LICENSE)
8
+
9
+ A production-focused, TypeScript-first HTTP client built on the standard Fetch
10
+ API, with zero runtime dependencies.
11
+
12
+ Npora Request keeps the native Fetch model while adding the contracts and
13
+ resilience needed by real applications: inferred response types, runtime
14
+ validation, incremental streaming, stable errors, deterministic extension
15
+ ordering, retries, caching, concurrency control, circuit breaking,
16
+ authentication, and upload/download progress.
17
+
18
+ ## Why Npora Request
19
+
20
+ - **Trust responses at runtime.** Standard Schema v1 validation checks and can
21
+ transform untrusted data while preserving full response and error metadata.
22
+ - **Stream without buffering everything.** SSE and NDJSON are exposed as lazy
23
+ async iterables with cancellation, timeout, and response-size enforcement.
24
+ - **Add resilience without hiding the transport.** Retry, cache, circuit
25
+ breaker, concurrency, authentication, logging, and progress are isolated,
26
+ composable plugins over the standard Fetch API.
27
+ - **Use one predictable contract everywhere.** Browsers, Web Workers, Node.js,
28
+ ESM, and CommonJS share the same typed lifecycle and stable error codes.
29
+ - **Ship less supply-chain risk.** The package has no runtime dependencies and
30
+ verifies public exports, browser behavior, security regressions, and size
31
+ budgets before release.
9
32
 
10
33
  ## Features
11
34
 
package/dist/index.cjs CHANGED
@@ -1,8 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
2
  //#region src/errors/RequestError.ts
3
- /**
4
- * Unified public error for all request failures.
5
- */
6
3
  var RequestError = class extends Error {
7
4
  constructor(message, options) {
8
5
  super(message);
@@ -18,9 +15,6 @@ var RequestError = class extends Error {
18
15
  };
19
16
  //#endregion
20
17
  //#region src/errors/SchemaValidationError.ts
21
- /**
22
- * Response failure reported by a Standard Schema compatible validator.
23
- */
24
18
  var SchemaValidationError = class extends RequestError {
25
19
  constructor(message, response, schemaVendor, issues = [], cause) {
26
20
  super(message, {
@@ -76,15 +70,9 @@ function createTimeoutSignal(signal, timeout) {
76
70
  function noop() {}
77
71
  //#endregion
78
72
  //#region src/utils/buildRequest.ts
79
- /**
80
- * Build a Fetch-compatible request from RequestConfig.
81
- */
82
73
  function buildRequest(config) {
83
74
  return buildRequestWithHeaders(config, new Headers(config.headers));
84
75
  }
85
- /**
86
- * Internal fast path for a Headers instance already created by validation.
87
- */
88
76
  function buildRequestWithHeaders(config, headers) {
89
77
  const body = buildBody(config, headers);
90
78
  const timeoutSignal = createTimeoutSignal(config.signal, config.timeout);
@@ -164,7 +152,7 @@ function buildURLSearchParams(form) {
164
152
  function buildFormData(input, maxDepth = 32) {
165
153
  if (input instanceof FormData) return input;
166
154
  const formData = new FormData();
167
- const ancestors = /* @__PURE__ */ new WeakSet();
155
+ const ancestors = new WeakSet();
168
156
  for (const key in input) if (Object.prototype.hasOwnProperty.call(input, key)) appendFormDataValue(formData, key, input[key], 0, maxDepth, ancestors);
169
157
  return formData;
170
158
  }
@@ -196,19 +184,12 @@ function isPlainObject$1(value) {
196
184
  }
197
185
  //#endregion
198
186
  //#region src/utils/parseStreamingResponse.ts
199
- /**
200
- * Decode a server-sent event response without buffering the complete body.
201
- */
202
187
  function parseServerSentEvents(response, config) {
203
188
  return decodeServerSentEvents(response.body, {
204
189
  config,
205
190
  response
206
191
  });
207
192
  }
208
- /**
209
- * Decode a newline-delimited JSON response without buffering the complete
210
- * body.
211
- */
212
193
  function parseNdjson(response, config) {
213
194
  return decodeNdjson(response.body, {
214
195
  config,
@@ -330,9 +311,6 @@ function parserError(message, context, cause) {
330
311
  }
331
312
  //#endregion
332
313
  //#region src/utils/parseResponse.ts
333
- /**
334
- * Bound a Fetch response before it can be cloned into multiple body branches.
335
- */
336
314
  function limitResponseSize(response, config) {
337
315
  const maxSize = config.maxResponseSize;
338
316
  if (maxSize === void 0 || !Number.isFinite(maxSize) || !response.body) return response;
@@ -350,10 +328,6 @@ function limitResponseSize(response, config) {
350
328
  copyResponseMetadata(response, limited);
351
329
  return limited;
352
330
  }
353
- /**
354
- * Keep request cancellation resources alive until a streaming response body
355
- * settles instead of releasing them as soon as response headers arrive.
356
- */
357
331
  function finalizeStreamingResponse(response, signal, config, finalize) {
358
332
  if (!response.body) {
359
333
  finalize();
@@ -426,11 +400,8 @@ function finalizeStreamingResponse(response, signal, config, finalize) {
426
400
  copyResponseMetadata(response, wrapped);
427
401
  return wrapped;
428
402
  }
429
- /**
430
- * Parse a Fetch response according to the request configuration.
431
- */
432
403
  async function parseResponse(response, config) {
433
- if (config.method === "HEAD" || response.status === 204 || response.status === 205) return;
404
+ if (config.method === "HEAD" || response.status === 204 || response.status === 205 || response.status === 304) return;
434
405
  const responseType = resolveResponseType(response, config);
435
406
  const maxSize = config.maxResponseSize;
436
407
  try {
@@ -470,7 +441,7 @@ async function rejectOversizedContentLength(response, maxSize, config) {
470
441
  throw error;
471
442
  }
472
443
  async function readLimitedBody(response, maxSize, config) {
473
- if (!response.body) return /* @__PURE__ */ new Uint8Array();
444
+ if (!response.body) return new Uint8Array();
474
445
  const reader = response.body.getReader();
475
446
  const chunks = [];
476
447
  let size = 0;
@@ -630,9 +601,6 @@ const BODY_FIELDS = [
630
601
  "form",
631
602
  "formData"
632
603
  ];
633
- /**
634
- * Validate configuration before request hooks or adapters act on it.
635
- */
636
604
  function validateRequestConfig(config) {
637
605
  validateURL(config);
638
606
  validateTimeout(config);
@@ -697,6 +665,20 @@ function configError(message, config, cause) {
697
665
  });
698
666
  }
699
667
  //#endregion
668
+ //#region src/utils/validateResponseStatus.ts
669
+ function validateResponseStatus(status, config) {
670
+ try {
671
+ return config.validateStatus ? config.validateStatus(status) : status >= 200 && status < 300;
672
+ } catch (error) {
673
+ throw new RequestError("Request validateStatus callback failed", {
674
+ code: "CONFIG_ERROR",
675
+ status,
676
+ config,
677
+ cause: error
678
+ });
679
+ }
680
+ }
681
+ //#endregion
700
682
  //#region src/adapters/FetchAdapter.ts
701
683
  var FetchAdapter = class {
702
684
  async request(config) {
@@ -712,7 +694,7 @@ var FetchAdapter = class {
712
694
  try {
713
695
  request = buildRequestWithHeaders(config, headers);
714
696
  let response = limitResponseSize(await fetch(request.url, request.init), config);
715
- const validStatus = (config.validateStatus ?? defaultValidateStatus$2)(response.status);
697
+ const validStatus = validateResponseStatus(response.status, config);
716
698
  const streaming = isStreamingResponseType(resolveResponseType(response, config));
717
699
  if (streaming) {
718
700
  response = finalizeStreamingResponse(response, request.init.signal, config, request.clear);
@@ -766,14 +748,11 @@ var FetchAdapter = class {
766
748
  }
767
749
  }
768
750
  };
769
- function defaultValidateStatus$2(status) {
770
- return status >= 200 && status < 300;
771
- }
772
751
  //#endregion
773
752
  //#region src/adapters/MockAdapter.ts
774
753
  var MockAdapter = class {
775
754
  constructor(options = {}) {
776
- this.handlers = /* @__PURE__ */ new Map();
755
+ this.handlers = new Map();
777
756
  this.rules = [];
778
757
  this.requests = [];
779
758
  this.delay = normalizeDelay$1(options.delay);
@@ -784,9 +763,6 @@ var MockAdapter = class {
784
763
  get history() {
785
764
  return [...this.requests];
786
765
  }
787
- /**
788
- * Register a legacy URL-only data handler.
789
- */
790
766
  on(url, handler) {
791
767
  this.handlers.set(url, handler);
792
768
  return this;
@@ -964,15 +940,12 @@ function createMockResponse(config, reply) {
964
940
  };
965
941
  }
966
942
  function validateMockResponse(response, config) {
967
- if (!(config.validateStatus ?? defaultValidateStatus$1)(response.status)) throw new RequestError(response.statusText || "Mock request failed", {
943
+ if (!validateResponseStatus(response.status, config)) throw new RequestError(response.statusText || "Mock request failed", {
968
944
  code: "HTTP_ERROR",
969
945
  response
970
946
  });
971
947
  return response;
972
948
  }
973
- function defaultValidateStatus$1(status) {
974
- return status >= 200 && status < 300;
975
- }
976
949
  function defaultStatusText(status) {
977
950
  return STATUS_TEXT[status] ?? "";
978
951
  }
@@ -1044,22 +1017,10 @@ function createAbortError$3(reason, config) {
1044
1017
  }
1045
1018
  //#endregion
1046
1019
  //#region src/core/ConfigMerger.ts
1047
- /**
1048
- * Request configuration merger.
1049
- *
1050
- * Responsible for merging client defaults
1051
- * and request specific configuration.
1052
- */
1053
1020
  var ConfigMerger = class {
1054
- /**
1055
- * Merge request configuration.
1056
- */
1057
1021
  static merge(defaults, config) {
1058
1022
  return this.mergeConfig(defaults, config);
1059
1023
  }
1060
- /**
1061
- * Merge two sets of client defaults.
1062
- */
1063
1024
  static mergeDefaults(defaults, overrides) {
1064
1025
  return this.mergeConfig(defaults, overrides);
1065
1026
  }
@@ -1082,9 +1043,6 @@ var ConfigMerger = class {
1082
1043
  ...options
1083
1044
  };
1084
1045
  }
1085
- /**
1086
- * Merge request headers.
1087
- */
1088
1046
  static mergeHeaders(defaults, headers) {
1089
1047
  if (!defaults && !headers) return;
1090
1048
  const result = {};
@@ -1181,11 +1139,6 @@ var RequestContext = class {
1181
1139
  };
1182
1140
  //#endregion
1183
1141
  //#region src/core/Pipeline.ts
1184
- /**
1185
- * Coordinates the request lifecycle.
1186
- *
1187
- * Pipeline does not implement business features.
1188
- */
1189
1142
  var Pipeline = class {
1190
1143
  constructor(adapter, interceptors, hooks) {
1191
1144
  this.adapter = adapter;
@@ -1264,13 +1217,13 @@ var Pipeline = class {
1264
1217
  } catch (error) {
1265
1218
  throw new SchemaValidationError("Response schema validator failed", response, schemaVendor, [], error);
1266
1219
  }
1267
- if (typeof result !== "object" || result === null) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], /* @__PURE__ */ new TypeError("Expected a Standard Schema result"));
1220
+ if (typeof result !== "object" || result === null) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], new TypeError("Expected a Standard Schema result"));
1268
1221
  const issues = "issues" in result ? result.issues : void 0;
1269
1222
  if (issues !== void 0) {
1270
- if (!Array.isArray(issues)) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], /* @__PURE__ */ new TypeError("Expected Standard Schema issues to be an array"));
1223
+ if (!Array.isArray(issues)) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], new TypeError("Expected Standard Schema issues to be an array"));
1271
1224
  throw new SchemaValidationError("Response schema validation failed", response, schemaVendor, issues);
1272
1225
  }
1273
- if (!("value" in result)) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], /* @__PURE__ */ new TypeError("Expected a Standard Schema value"));
1226
+ if (!("value" in result)) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], new TypeError("Expected a Standard Schema value"));
1274
1227
  context.response = {
1275
1228
  ...response,
1276
1229
  data: result.value
@@ -1334,7 +1287,7 @@ function createAbortError$2(reason, config) {
1334
1287
  var InterceptorManager = class {
1335
1288
  constructor() {
1336
1289
  this.id = 0;
1337
- this.interceptors = /* @__PURE__ */ new Map();
1290
+ this.interceptors = new Map();
1338
1291
  this.orderedInterceptors = [];
1339
1292
  }
1340
1293
  get active() {
@@ -1373,12 +1326,6 @@ function normalizePriority$1(priority) {
1373
1326
  }
1374
1327
  //#endregion
1375
1328
  //#region src/interceptors/PluginHooks.ts
1376
- /**
1377
- * Internal plugin lifecycle manager.
1378
- *
1379
- * Hook order is calculated when registrations change so the hot request path
1380
- * can iterate a stable array without allocating and sorting per request.
1381
- */
1382
1329
  var PluginHooks = class {
1383
1330
  constructor() {
1384
1331
  this.requestHooks = new HookRegistry();
@@ -1445,7 +1392,7 @@ var PluginHooks = class {
1445
1392
  var HookRegistry = class {
1446
1393
  constructor() {
1447
1394
  this.id = 0;
1448
- this.hooks = /* @__PURE__ */ new Map();
1395
+ this.hooks = new Map();
1449
1396
  this.orderedHooks = [];
1450
1397
  }
1451
1398
  get active() {
@@ -1477,9 +1424,6 @@ function normalizePriority(priority) {
1477
1424
  }
1478
1425
  //#endregion
1479
1426
  //#region src/plugins/PluginError.ts
1480
- /**
1481
- * Stable error thrown for invalid plugin lifecycle operations.
1482
- */
1483
1427
  var PluginError = class extends Error {
1484
1428
  constructor(message, options) {
1485
1429
  super(message);
@@ -1492,9 +1436,6 @@ var PluginError = class extends Error {
1492
1436
  };
1493
1437
  //#endregion
1494
1438
  //#region src/plugins/PluginScope.ts
1495
- /**
1496
- * Create an isolated registration scope for one plugin.
1497
- */
1498
1439
  function createPluginScope(interceptors, hooks, priority = 0) {
1499
1440
  const cleanups = [];
1500
1441
  return {
@@ -1522,7 +1463,7 @@ function createPluginScope(interceptors, hooks, priority = 0) {
1522
1463
  };
1523
1464
  }
1524
1465
  function createScopedInterceptor(manager, pluginPriority, cleanups) {
1525
- const ids = /* @__PURE__ */ new Set();
1466
+ const ids = new Set();
1526
1467
  cleanups.push(() => {
1527
1468
  for (const id of ids) manager.eject(id);
1528
1469
  ids.clear();
@@ -1578,7 +1519,7 @@ function once(cleanup) {
1578
1519
  //#region src/client/Client.ts
1579
1520
  var Client = class Client {
1580
1521
  constructor(options = {}) {
1581
- this.installedPlugins = /* @__PURE__ */ new Map();
1522
+ this.installedPlugins = new Map();
1582
1523
  this.hooks = new PluginHooks();
1583
1524
  this.interceptors = {
1584
1525
  request: new InterceptorManager(),
@@ -1590,9 +1531,6 @@ var Client = class Client {
1590
1531
  this.adapter = adapter;
1591
1532
  this.pipeline = this.createPipeline(adapter);
1592
1533
  }
1593
- /**
1594
- * Create an isolated client that inherits this client's defaults.
1595
- */
1596
1534
  extend(options = {}) {
1597
1535
  const { adapter = this.adapter, ...overrides } = options;
1598
1536
  const defaults = ConfigMerger.mergeDefaults(this.defaults, overrides);
@@ -1745,36 +1683,24 @@ var Client = class Client {
1745
1683
  method: "OPTIONS"
1746
1684
  });
1747
1685
  }
1748
- /**
1749
- * Consume a server-sent event response as a lazy async iterable.
1750
- */
1751
1686
  sse(url, config = {}) {
1752
1687
  return this.get(url, {
1753
1688
  ...config,
1754
1689
  responseType: "sse"
1755
1690
  });
1756
1691
  }
1757
- /**
1758
- * Consume a server-sent event response with complete response metadata.
1759
- */
1760
1692
  sseResponse(url, config = {}) {
1761
1693
  return this.getResponse(url, {
1762
1694
  ...config,
1763
1695
  responseType: "sse"
1764
1696
  });
1765
1697
  }
1766
- /**
1767
- * Consume newline-delimited JSON records as a lazy async iterable.
1768
- */
1769
1698
  ndjson(url, config = {}) {
1770
1699
  return this.get(url, {
1771
1700
  ...config,
1772
1701
  responseType: "ndjson"
1773
1702
  });
1774
1703
  }
1775
- /**
1776
- * Consume newline-delimited JSON with complete response metadata.
1777
- */
1778
1704
  ndjsonResponse(url, config = {}) {
1779
1705
  return this.getResponse(url, {
1780
1706
  ...config,
@@ -1813,28 +1739,19 @@ var Client = class Client {
1813
1739
  };
1814
1740
  //#endregion
1815
1741
  //#region src/client/createClient.ts
1816
- /**
1817
- * Create an HTTP client instance.
1818
- */
1819
1742
  function createClient(options = {}) {
1820
1743
  return new Client(options);
1821
1744
  }
1822
1745
  //#endregion
1823
1746
  //#region src/plugins/resolveExtensionConfig.ts
1824
- /**
1825
- * Resolve namespaced plugin configuration.
1826
- */
1827
1747
  function resolveExtensionConfig(config, key) {
1828
1748
  return config.extensions?.[key];
1829
1749
  }
1830
1750
  //#endregion
1831
1751
  //#region src/plugins/authPlugin.ts
1832
- /**
1833
- * Authentication plugin.
1834
- */
1835
1752
  function authPlugin(options = {}) {
1836
1753
  let refreshPromise;
1837
- const refreshedContexts = /* @__PURE__ */ new WeakSet();
1754
+ const refreshedContexts = new WeakSet();
1838
1755
  return {
1839
1756
  name: "auth",
1840
1757
  install(context) {
@@ -1907,13 +1824,13 @@ function defaultShouldRefresh(error) {
1907
1824
  //#region src/plugins/cachePlugin.ts
1908
1825
  var MemoryCacheStore = class {
1909
1826
  constructor(options = {}) {
1910
- this.entries = /* @__PURE__ */ new Map();
1827
+ this.entries = new Map();
1911
1828
  this.maxEntries = normalizeMaxEntries(options.maxEntries);
1912
1829
  }
1913
1830
  get(key) {
1914
1831
  const entry = this.entries.get(key);
1915
1832
  if (!entry) return;
1916
- if (!Number.isFinite(entry.expiresAt) || Date.now() > entry.expiresAt) {
1833
+ if (isExpired(entry.expiresAt)) {
1917
1834
  this.entries.delete(key);
1918
1835
  return;
1919
1836
  }
@@ -1947,11 +1864,11 @@ const DEFAULT_VARY_HEADERS = [
1947
1864
  ];
1948
1865
  function cachePlugin(options = {}) {
1949
1866
  const store = options.store ?? new MemoryCacheStore({ maxEntries: options.maxEntries });
1950
- const cacheHits = /* @__PURE__ */ new WeakSet();
1951
- const leaders = /* @__PURE__ */ new WeakMap();
1952
- const completedRecords = /* @__PURE__ */ new WeakMap();
1953
- const uncacheableLeaders = /* @__PURE__ */ new WeakSet();
1954
- const inFlight = /* @__PURE__ */ new Map();
1867
+ const cacheHits = new WeakSet();
1868
+ const leaders = new WeakMap();
1869
+ const completedRecords = new WeakMap();
1870
+ const uncacheableLeaders = new WeakSet();
1871
+ const inFlight = new Map();
1955
1872
  const methods = new Set(options.methods ?? DEFAULT_CACHE_METHODS);
1956
1873
  const varyHeaders = options.varyHeaders ?? DEFAULT_VARY_HEADERS;
1957
1874
  return {
@@ -1960,15 +1877,16 @@ function cachePlugin(options = {}) {
1960
1877
  return store.clear();
1961
1878
  },
1962
1879
  install(context) {
1963
- const ownedLeaders = /* @__PURE__ */ new Set();
1880
+ const ownedLeaders = new Set();
1964
1881
  let active = true;
1965
1882
  context.hooks.onRequest(async (requestContext) => {
1966
1883
  const cache = resolveExtensionConfig(requestContext.config, "cache");
1967
1884
  if (!cache?.enabled || !isCacheableRequest(requestContext.config, methods)) return;
1885
+ normalizeCacheTtl(cache.ttl, requestContext.config);
1968
1886
  const key = createCacheKey(requestContext.config, cache, varyHeaders);
1969
1887
  const record = await readStore(store, key);
1970
1888
  if (!active) return;
1971
- if (record) if (!Number.isFinite(record.expiresAt) || Date.now() > record.expiresAt) await deleteStore(store, key);
1889
+ if (record) if (isExpired(record.expiresAt)) await deleteStore(store, key);
1972
1890
  else {
1973
1891
  const cachedResponse = restoreCacheEntry(record, requestContext.config);
1974
1892
  if (cachedResponse) {
@@ -2002,7 +1920,7 @@ function cachePlugin(options = {}) {
2002
1920
  await deleteStore(store, key);
2003
1921
  return;
2004
1922
  }
2005
- const ttl = cache.ttl ?? 3e4;
1923
+ const ttl = normalizeCacheTtl(cache.ttl, requestContext.config);
2006
1924
  const record = createCacheEntry(requestContext.response, Date.now() + Math.max(0, ttl));
2007
1925
  completedRecords.set(requestContext, record);
2008
1926
  if (ttl <= 0 || !allowsPersistentCaching(requestContext.response)) {
@@ -2179,7 +2097,7 @@ function createCacheKey(config, cache, varyHeaders) {
2179
2097
  });
2180
2098
  }
2181
2099
  function normalizeCacheHeaders(headers, varyHeaders) {
2182
- const values = /* @__PURE__ */ new Map();
2100
+ const values = new Map();
2183
2101
  headers.forEach((value, name) => {
2184
2102
  values.set(name.toLowerCase(), value);
2185
2103
  });
@@ -2236,11 +2154,33 @@ function normalizeMaxEntries(value) {
2236
2154
  if (!Number.isFinite(value)) return value > 0 ? Number.POSITIVE_INFINITY : 0;
2237
2155
  return Math.max(0, Math.floor(value));
2238
2156
  }
2157
+ function normalizeCacheTtl(value, config) {
2158
+ const ttl = value ?? 3e4;
2159
+ if (ttl !== Number.POSITIVE_INFINITY && (!Number.isFinite(ttl) || ttl < 0)) throw new RequestError("Cache ttl must be a non-negative finite number or Infinity", {
2160
+ code: "CONFIG_ERROR",
2161
+ config
2162
+ });
2163
+ return ttl;
2164
+ }
2165
+ function isExpired(expiresAt) {
2166
+ return Number.isNaN(expiresAt) || Date.now() >= expiresAt;
2167
+ }
2168
+ //#endregion
2169
+ //#region src/utils/resolveRequestOrigin.ts
2170
+ function resolveRequestOrigin(config) {
2171
+ try {
2172
+ return new URL(config.url).origin;
2173
+ } catch {}
2174
+ try {
2175
+ if (config.baseURL) return new URL(config.url, config.baseURL).origin;
2176
+ } catch {}
2177
+ return "default";
2178
+ }
2239
2179
  //#endregion
2240
2180
  //#region src/plugins/circuitBreakerPlugin.ts
2241
2181
  function circuitBreakerPlugin(options = {}) {
2242
2182
  const normalized = normalizeOptions$1(options);
2243
- const circuits = /* @__PURE__ */ new Map();
2183
+ const circuits = new Map();
2244
2184
  return {
2245
2185
  name: "circuit-breaker",
2246
2186
  getState(key) {
@@ -2254,7 +2194,7 @@ function circuitBreakerPlugin(options = {}) {
2254
2194
  circuits.delete(key);
2255
2195
  },
2256
2196
  install(context) {
2257
- const admissions = /* @__PURE__ */ new WeakMap();
2197
+ const admissions = new WeakMap();
2258
2198
  let active = true;
2259
2199
  context.hooks.onRequest((requestContext) => {
2260
2200
  const requestOptions = resolveExtensionConfig(requestContext.config, "circuitBreaker");
@@ -2323,7 +2263,7 @@ function normalizeOptions$1(options) {
2323
2263
  resetTimeout: normalizeDuration$1(options.resetTimeout, 3e4),
2324
2264
  halfOpenMaxRequests: normalizePositiveInteger$1(options.halfOpenMaxRequests, 1),
2325
2265
  maxCircuits: normalizePositiveInteger$1(options.maxCircuits, 1e3),
2326
- createKey: options.createKey ?? createDefaultKey$1,
2266
+ createKey: options.createKey ?? resolveRequestOrigin,
2327
2267
  shouldCountFailure: options.shouldCountFailure ?? defaultShouldCountFailure,
2328
2268
  onStateChange: options.onStateChange
2329
2269
  };
@@ -2341,15 +2281,6 @@ function normalizeDuration$1(value, fallback) {
2341
2281
  function normalizeKey$1(key) {
2342
2282
  return key || "default";
2343
2283
  }
2344
- function createDefaultKey$1(config) {
2345
- try {
2346
- return new URL(config.url).origin;
2347
- } catch {}
2348
- try {
2349
- if (config.baseURL) return new URL(config.url, config.baseURL).origin;
2350
- } catch {}
2351
- return "default";
2352
- }
2353
2284
  function getCircuit(circuits, key, maxCircuits) {
2354
2285
  let record = circuits.get(key);
2355
2286
  if (record) {
@@ -2431,7 +2362,7 @@ function defaultShouldCountFailure(error) {
2431
2362
  //#region src/plugins/concurrencyPlugin.ts
2432
2363
  function concurrencyPlugin(options = {}) {
2433
2364
  const normalized = normalizeOptions(options);
2434
- const records = /* @__PURE__ */ new Map();
2365
+ const records = new Map();
2435
2366
  return {
2436
2367
  name: "concurrency",
2437
2368
  getState(key) {
@@ -2442,7 +2373,7 @@ function concurrencyPlugin(options = {}) {
2442
2373
  };
2443
2374
  },
2444
2375
  install(context) {
2445
- const admissions = /* @__PURE__ */ new WeakMap();
2376
+ const admissions = new WeakMap();
2446
2377
  let active = true;
2447
2378
  context.hooks.onRequest(async (requestContext) => {
2448
2379
  const requestOptions = resolveExtensionConfig(requestContext.config, "concurrency");
@@ -2574,7 +2505,7 @@ function normalizeOptions(options) {
2574
2505
  maxQueue: normalizeNonNegativeInteger(options.maxQueue, 1e3),
2575
2506
  queueTimeout: normalizeDuration(options.queueTimeout, 3e4),
2576
2507
  maxKeys: normalizePositiveInteger(options.maxKeys, 1e3),
2577
- createKey: options.createKey ?? createDefaultKey
2508
+ createKey: options.createKey ?? resolveRequestOrigin
2578
2509
  };
2579
2510
  }
2580
2511
  function normalizePositiveInteger(value, fallback) {
@@ -2593,15 +2524,6 @@ function normalizeDuration(value, fallback) {
2593
2524
  function normalizeKey(key) {
2594
2525
  return String(key).trim() || "default";
2595
2526
  }
2596
- function createDefaultKey(config) {
2597
- try {
2598
- return new URL(config.url).origin;
2599
- } catch {}
2600
- try {
2601
- if (config.baseURL) return new URL(config.url, config.baseURL).origin;
2602
- } catch {}
2603
- return "default";
2604
- }
2605
2527
  function createLimitError(message, config) {
2606
2528
  return new RequestError(message, {
2607
2529
  code: "CONCURRENCY_LIMIT",
@@ -2725,7 +2647,7 @@ async function processResponse(xhr, config) {
2725
2647
  config,
2726
2648
  raw
2727
2649
  };
2728
- if (!(config.validateStatus ?? defaultValidateStatus)(xhr.status)) throw new RequestError(xhr.statusText || "Request failed", {
2650
+ if (!validateResponseStatus(xhr.status, config)) throw new RequestError(xhr.statusText || "Request failed", {
2729
2651
  code: "HTTP_ERROR",
2730
2652
  response
2731
2653
  });
@@ -2801,13 +2723,10 @@ function createConfigError(config, cause) {
2801
2723
  function isNullBodyStatus(status) {
2802
2724
  return status === 204 || status === 205 || status === 304;
2803
2725
  }
2804
- function defaultValidateStatus(status) {
2805
- return status >= 200 && status < 300;
2806
- }
2807
2726
  //#endregion
2808
2727
  //#region src/plugins/downloadPlugin.ts
2809
2728
  function downloadPlugin(options = {}) {
2810
- const xhrContexts = /* @__PURE__ */ new WeakSet();
2729
+ const xhrContexts = new WeakSet();
2811
2730
  return {
2812
2731
  name: "download",
2813
2732
  install(context) {
@@ -2885,10 +2804,6 @@ async function consumeDownloadStream(stream, response, onProgress) {
2885
2804
  }
2886
2805
  return new Blob(chunks, { type: response.headers.get("content-type") ?? "" });
2887
2806
  }
2888
- /**
2889
- * Reuses complete ArrayBuffer chunks and copies only sliced or
2890
- * SharedArrayBuffer-backed views before passing them to Blob.
2891
- */
2892
2807
  function toDownloadBuffer(chunk) {
2893
2808
  if (chunk.buffer instanceof ArrayBuffer) {
2894
2809
  if (chunk.byteOffset === 0 && chunk.byteLength === chunk.buffer.byteLength) return chunk.buffer;
@@ -2919,7 +2834,7 @@ function createProgress(loaded, total) {
2919
2834
  //#region src/plugins/loggerPlugin.ts
2920
2835
  function loggerPlugin(defaultOptions = {}) {
2921
2836
  let nextRequestId = 0;
2922
- const states = /* @__PURE__ */ new WeakMap();
2837
+ const states = new WeakMap();
2923
2838
  return {
2924
2839
  name: "logger",
2925
2840
  install(context) {
@@ -3000,7 +2915,7 @@ function emitError(options, entry) {
3000
2915
  } catch {}
3001
2916
  }
3002
2917
  function ignoreLoggerError() {}
3003
- const SENSITIVE_QUERY_KEYS = /* @__PURE__ */ new Set([
2918
+ const SENSITIVE_QUERY_KEYS = new Set([
3004
2919
  "access_token",
3005
2920
  "api-key",
3006
2921
  "api_key",
package/dist/index.d.cts CHANGED
@@ -134,6 +134,12 @@ interface RetryEvent {
134
134
  }
135
135
  interface CacheOptions {
136
136
  enabled?: boolean;
137
+ /**
138
+ * Time in milliseconds before a cached response expires.
139
+ * Use `0` to disable persistence or `Infinity` to retain it indefinitely.
140
+ *
141
+ * @default 30000
142
+ */
137
143
  ttl?: number;
138
144
  key?: string;
139
145
  /**
package/dist/index.d.ts CHANGED
@@ -134,6 +134,12 @@ interface RetryEvent {
134
134
  }
135
135
  interface CacheOptions {
136
136
  enabled?: boolean;
137
+ /**
138
+ * Time in milliseconds before a cached response expires.
139
+ * Use `0` to disable persistence or `Infinity` to retain it indefinitely.
140
+ *
141
+ * @default 30000
142
+ */
137
143
  ttl?: number;
138
144
  key?: string;
139
145
  /**
package/dist/index.js CHANGED
@@ -1,7 +1,4 @@
1
1
  //#region src/errors/RequestError.ts
2
- /**
3
- * Unified public error for all request failures.
4
- */
5
2
  var RequestError = class extends Error {
6
3
  constructor(message, options) {
7
4
  super(message);
@@ -17,9 +14,6 @@ var RequestError = class extends Error {
17
14
  };
18
15
  //#endregion
19
16
  //#region src/errors/SchemaValidationError.ts
20
- /**
21
- * Response failure reported by a Standard Schema compatible validator.
22
- */
23
17
  var SchemaValidationError = class extends RequestError {
24
18
  constructor(message, response, schemaVendor, issues = [], cause) {
25
19
  super(message, {
@@ -75,15 +69,9 @@ function createTimeoutSignal(signal, timeout) {
75
69
  function noop() {}
76
70
  //#endregion
77
71
  //#region src/utils/buildRequest.ts
78
- /**
79
- * Build a Fetch-compatible request from RequestConfig.
80
- */
81
72
  function buildRequest(config) {
82
73
  return buildRequestWithHeaders(config, new Headers(config.headers));
83
74
  }
84
- /**
85
- * Internal fast path for a Headers instance already created by validation.
86
- */
87
75
  function buildRequestWithHeaders(config, headers) {
88
76
  const body = buildBody(config, headers);
89
77
  const timeoutSignal = createTimeoutSignal(config.signal, config.timeout);
@@ -163,7 +151,7 @@ function buildURLSearchParams(form) {
163
151
  function buildFormData(input, maxDepth = 32) {
164
152
  if (input instanceof FormData) return input;
165
153
  const formData = new FormData();
166
- const ancestors = /* @__PURE__ */ new WeakSet();
154
+ const ancestors = new WeakSet();
167
155
  for (const key in input) if (Object.prototype.hasOwnProperty.call(input, key)) appendFormDataValue(formData, key, input[key], 0, maxDepth, ancestors);
168
156
  return formData;
169
157
  }
@@ -195,19 +183,12 @@ function isPlainObject$1(value) {
195
183
  }
196
184
  //#endregion
197
185
  //#region src/utils/parseStreamingResponse.ts
198
- /**
199
- * Decode a server-sent event response without buffering the complete body.
200
- */
201
186
  function parseServerSentEvents(response, config) {
202
187
  return decodeServerSentEvents(response.body, {
203
188
  config,
204
189
  response
205
190
  });
206
191
  }
207
- /**
208
- * Decode a newline-delimited JSON response without buffering the complete
209
- * body.
210
- */
211
192
  function parseNdjson(response, config) {
212
193
  return decodeNdjson(response.body, {
213
194
  config,
@@ -329,9 +310,6 @@ function parserError(message, context, cause) {
329
310
  }
330
311
  //#endregion
331
312
  //#region src/utils/parseResponse.ts
332
- /**
333
- * Bound a Fetch response before it can be cloned into multiple body branches.
334
- */
335
313
  function limitResponseSize(response, config) {
336
314
  const maxSize = config.maxResponseSize;
337
315
  if (maxSize === void 0 || !Number.isFinite(maxSize) || !response.body) return response;
@@ -349,10 +327,6 @@ function limitResponseSize(response, config) {
349
327
  copyResponseMetadata(response, limited);
350
328
  return limited;
351
329
  }
352
- /**
353
- * Keep request cancellation resources alive until a streaming response body
354
- * settles instead of releasing them as soon as response headers arrive.
355
- */
356
330
  function finalizeStreamingResponse(response, signal, config, finalize) {
357
331
  if (!response.body) {
358
332
  finalize();
@@ -425,11 +399,8 @@ function finalizeStreamingResponse(response, signal, config, finalize) {
425
399
  copyResponseMetadata(response, wrapped);
426
400
  return wrapped;
427
401
  }
428
- /**
429
- * Parse a Fetch response according to the request configuration.
430
- */
431
402
  async function parseResponse(response, config) {
432
- if (config.method === "HEAD" || response.status === 204 || response.status === 205) return;
403
+ if (config.method === "HEAD" || response.status === 204 || response.status === 205 || response.status === 304) return;
433
404
  const responseType = resolveResponseType(response, config);
434
405
  const maxSize = config.maxResponseSize;
435
406
  try {
@@ -469,7 +440,7 @@ async function rejectOversizedContentLength(response, maxSize, config) {
469
440
  throw error;
470
441
  }
471
442
  async function readLimitedBody(response, maxSize, config) {
472
- if (!response.body) return /* @__PURE__ */ new Uint8Array();
443
+ if (!response.body) return new Uint8Array();
473
444
  const reader = response.body.getReader();
474
445
  const chunks = [];
475
446
  let size = 0;
@@ -629,9 +600,6 @@ const BODY_FIELDS = [
629
600
  "form",
630
601
  "formData"
631
602
  ];
632
- /**
633
- * Validate configuration before request hooks or adapters act on it.
634
- */
635
603
  function validateRequestConfig(config) {
636
604
  validateURL(config);
637
605
  validateTimeout(config);
@@ -696,6 +664,20 @@ function configError(message, config, cause) {
696
664
  });
697
665
  }
698
666
  //#endregion
667
+ //#region src/utils/validateResponseStatus.ts
668
+ function validateResponseStatus(status, config) {
669
+ try {
670
+ return config.validateStatus ? config.validateStatus(status) : status >= 200 && status < 300;
671
+ } catch (error) {
672
+ throw new RequestError("Request validateStatus callback failed", {
673
+ code: "CONFIG_ERROR",
674
+ status,
675
+ config,
676
+ cause: error
677
+ });
678
+ }
679
+ }
680
+ //#endregion
699
681
  //#region src/adapters/FetchAdapter.ts
700
682
  var FetchAdapter = class {
701
683
  async request(config) {
@@ -711,7 +693,7 @@ var FetchAdapter = class {
711
693
  try {
712
694
  request = buildRequestWithHeaders(config, headers);
713
695
  let response = limitResponseSize(await fetch(request.url, request.init), config);
714
- const validStatus = (config.validateStatus ?? defaultValidateStatus$2)(response.status);
696
+ const validStatus = validateResponseStatus(response.status, config);
715
697
  const streaming = isStreamingResponseType(resolveResponseType(response, config));
716
698
  if (streaming) {
717
699
  response = finalizeStreamingResponse(response, request.init.signal, config, request.clear);
@@ -765,14 +747,11 @@ var FetchAdapter = class {
765
747
  }
766
748
  }
767
749
  };
768
- function defaultValidateStatus$2(status) {
769
- return status >= 200 && status < 300;
770
- }
771
750
  //#endregion
772
751
  //#region src/adapters/MockAdapter.ts
773
752
  var MockAdapter = class {
774
753
  constructor(options = {}) {
775
- this.handlers = /* @__PURE__ */ new Map();
754
+ this.handlers = new Map();
776
755
  this.rules = [];
777
756
  this.requests = [];
778
757
  this.delay = normalizeDelay$1(options.delay);
@@ -783,9 +762,6 @@ var MockAdapter = class {
783
762
  get history() {
784
763
  return [...this.requests];
785
764
  }
786
- /**
787
- * Register a legacy URL-only data handler.
788
- */
789
765
  on(url, handler) {
790
766
  this.handlers.set(url, handler);
791
767
  return this;
@@ -963,15 +939,12 @@ function createMockResponse(config, reply) {
963
939
  };
964
940
  }
965
941
  function validateMockResponse(response, config) {
966
- if (!(config.validateStatus ?? defaultValidateStatus$1)(response.status)) throw new RequestError(response.statusText || "Mock request failed", {
942
+ if (!validateResponseStatus(response.status, config)) throw new RequestError(response.statusText || "Mock request failed", {
967
943
  code: "HTTP_ERROR",
968
944
  response
969
945
  });
970
946
  return response;
971
947
  }
972
- function defaultValidateStatus$1(status) {
973
- return status >= 200 && status < 300;
974
- }
975
948
  function defaultStatusText(status) {
976
949
  return STATUS_TEXT[status] ?? "";
977
950
  }
@@ -1043,22 +1016,10 @@ function createAbortError$3(reason, config) {
1043
1016
  }
1044
1017
  //#endregion
1045
1018
  //#region src/core/ConfigMerger.ts
1046
- /**
1047
- * Request configuration merger.
1048
- *
1049
- * Responsible for merging client defaults
1050
- * and request specific configuration.
1051
- */
1052
1019
  var ConfigMerger = class {
1053
- /**
1054
- * Merge request configuration.
1055
- */
1056
1020
  static merge(defaults, config) {
1057
1021
  return this.mergeConfig(defaults, config);
1058
1022
  }
1059
- /**
1060
- * Merge two sets of client defaults.
1061
- */
1062
1023
  static mergeDefaults(defaults, overrides) {
1063
1024
  return this.mergeConfig(defaults, overrides);
1064
1025
  }
@@ -1081,9 +1042,6 @@ var ConfigMerger = class {
1081
1042
  ...options
1082
1043
  };
1083
1044
  }
1084
- /**
1085
- * Merge request headers.
1086
- */
1087
1045
  static mergeHeaders(defaults, headers) {
1088
1046
  if (!defaults && !headers) return;
1089
1047
  const result = {};
@@ -1180,11 +1138,6 @@ var RequestContext = class {
1180
1138
  };
1181
1139
  //#endregion
1182
1140
  //#region src/core/Pipeline.ts
1183
- /**
1184
- * Coordinates the request lifecycle.
1185
- *
1186
- * Pipeline does not implement business features.
1187
- */
1188
1141
  var Pipeline = class {
1189
1142
  constructor(adapter, interceptors, hooks) {
1190
1143
  this.adapter = adapter;
@@ -1263,13 +1216,13 @@ var Pipeline = class {
1263
1216
  } catch (error) {
1264
1217
  throw new SchemaValidationError("Response schema validator failed", response, schemaVendor, [], error);
1265
1218
  }
1266
- if (typeof result !== "object" || result === null) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], /* @__PURE__ */ new TypeError("Expected a Standard Schema result"));
1219
+ if (typeof result !== "object" || result === null) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], new TypeError("Expected a Standard Schema result"));
1267
1220
  const issues = "issues" in result ? result.issues : void 0;
1268
1221
  if (issues !== void 0) {
1269
- if (!Array.isArray(issues)) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], /* @__PURE__ */ new TypeError("Expected Standard Schema issues to be an array"));
1222
+ if (!Array.isArray(issues)) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], new TypeError("Expected Standard Schema issues to be an array"));
1270
1223
  throw new SchemaValidationError("Response schema validation failed", response, schemaVendor, issues);
1271
1224
  }
1272
- if (!("value" in result)) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], /* @__PURE__ */ new TypeError("Expected a Standard Schema value"));
1225
+ if (!("value" in result)) throw new SchemaValidationError("Response schema validator returned an invalid result", response, schemaVendor, [], new TypeError("Expected a Standard Schema value"));
1273
1226
  context.response = {
1274
1227
  ...response,
1275
1228
  data: result.value
@@ -1333,7 +1286,7 @@ function createAbortError$2(reason, config) {
1333
1286
  var InterceptorManager = class {
1334
1287
  constructor() {
1335
1288
  this.id = 0;
1336
- this.interceptors = /* @__PURE__ */ new Map();
1289
+ this.interceptors = new Map();
1337
1290
  this.orderedInterceptors = [];
1338
1291
  }
1339
1292
  get active() {
@@ -1372,12 +1325,6 @@ function normalizePriority$1(priority) {
1372
1325
  }
1373
1326
  //#endregion
1374
1327
  //#region src/interceptors/PluginHooks.ts
1375
- /**
1376
- * Internal plugin lifecycle manager.
1377
- *
1378
- * Hook order is calculated when registrations change so the hot request path
1379
- * can iterate a stable array without allocating and sorting per request.
1380
- */
1381
1328
  var PluginHooks = class {
1382
1329
  constructor() {
1383
1330
  this.requestHooks = new HookRegistry();
@@ -1444,7 +1391,7 @@ var PluginHooks = class {
1444
1391
  var HookRegistry = class {
1445
1392
  constructor() {
1446
1393
  this.id = 0;
1447
- this.hooks = /* @__PURE__ */ new Map();
1394
+ this.hooks = new Map();
1448
1395
  this.orderedHooks = [];
1449
1396
  }
1450
1397
  get active() {
@@ -1476,9 +1423,6 @@ function normalizePriority(priority) {
1476
1423
  }
1477
1424
  //#endregion
1478
1425
  //#region src/plugins/PluginError.ts
1479
- /**
1480
- * Stable error thrown for invalid plugin lifecycle operations.
1481
- */
1482
1426
  var PluginError = class extends Error {
1483
1427
  constructor(message, options) {
1484
1428
  super(message);
@@ -1491,9 +1435,6 @@ var PluginError = class extends Error {
1491
1435
  };
1492
1436
  //#endregion
1493
1437
  //#region src/plugins/PluginScope.ts
1494
- /**
1495
- * Create an isolated registration scope for one plugin.
1496
- */
1497
1438
  function createPluginScope(interceptors, hooks, priority = 0) {
1498
1439
  const cleanups = [];
1499
1440
  return {
@@ -1521,7 +1462,7 @@ function createPluginScope(interceptors, hooks, priority = 0) {
1521
1462
  };
1522
1463
  }
1523
1464
  function createScopedInterceptor(manager, pluginPriority, cleanups) {
1524
- const ids = /* @__PURE__ */ new Set();
1465
+ const ids = new Set();
1525
1466
  cleanups.push(() => {
1526
1467
  for (const id of ids) manager.eject(id);
1527
1468
  ids.clear();
@@ -1577,7 +1518,7 @@ function once(cleanup) {
1577
1518
  //#region src/client/Client.ts
1578
1519
  var Client = class Client {
1579
1520
  constructor(options = {}) {
1580
- this.installedPlugins = /* @__PURE__ */ new Map();
1521
+ this.installedPlugins = new Map();
1581
1522
  this.hooks = new PluginHooks();
1582
1523
  this.interceptors = {
1583
1524
  request: new InterceptorManager(),
@@ -1589,9 +1530,6 @@ var Client = class Client {
1589
1530
  this.adapter = adapter;
1590
1531
  this.pipeline = this.createPipeline(adapter);
1591
1532
  }
1592
- /**
1593
- * Create an isolated client that inherits this client's defaults.
1594
- */
1595
1533
  extend(options = {}) {
1596
1534
  const { adapter = this.adapter, ...overrides } = options;
1597
1535
  const defaults = ConfigMerger.mergeDefaults(this.defaults, overrides);
@@ -1744,36 +1682,24 @@ var Client = class Client {
1744
1682
  method: "OPTIONS"
1745
1683
  });
1746
1684
  }
1747
- /**
1748
- * Consume a server-sent event response as a lazy async iterable.
1749
- */
1750
1685
  sse(url, config = {}) {
1751
1686
  return this.get(url, {
1752
1687
  ...config,
1753
1688
  responseType: "sse"
1754
1689
  });
1755
1690
  }
1756
- /**
1757
- * Consume a server-sent event response with complete response metadata.
1758
- */
1759
1691
  sseResponse(url, config = {}) {
1760
1692
  return this.getResponse(url, {
1761
1693
  ...config,
1762
1694
  responseType: "sse"
1763
1695
  });
1764
1696
  }
1765
- /**
1766
- * Consume newline-delimited JSON records as a lazy async iterable.
1767
- */
1768
1697
  ndjson(url, config = {}) {
1769
1698
  return this.get(url, {
1770
1699
  ...config,
1771
1700
  responseType: "ndjson"
1772
1701
  });
1773
1702
  }
1774
- /**
1775
- * Consume newline-delimited JSON with complete response metadata.
1776
- */
1777
1703
  ndjsonResponse(url, config = {}) {
1778
1704
  return this.getResponse(url, {
1779
1705
  ...config,
@@ -1812,28 +1738,19 @@ var Client = class Client {
1812
1738
  };
1813
1739
  //#endregion
1814
1740
  //#region src/client/createClient.ts
1815
- /**
1816
- * Create an HTTP client instance.
1817
- */
1818
1741
  function createClient(options = {}) {
1819
1742
  return new Client(options);
1820
1743
  }
1821
1744
  //#endregion
1822
1745
  //#region src/plugins/resolveExtensionConfig.ts
1823
- /**
1824
- * Resolve namespaced plugin configuration.
1825
- */
1826
1746
  function resolveExtensionConfig(config, key) {
1827
1747
  return config.extensions?.[key];
1828
1748
  }
1829
1749
  //#endregion
1830
1750
  //#region src/plugins/authPlugin.ts
1831
- /**
1832
- * Authentication plugin.
1833
- */
1834
1751
  function authPlugin(options = {}) {
1835
1752
  let refreshPromise;
1836
- const refreshedContexts = /* @__PURE__ */ new WeakSet();
1753
+ const refreshedContexts = new WeakSet();
1837
1754
  return {
1838
1755
  name: "auth",
1839
1756
  install(context) {
@@ -1906,13 +1823,13 @@ function defaultShouldRefresh(error) {
1906
1823
  //#region src/plugins/cachePlugin.ts
1907
1824
  var MemoryCacheStore = class {
1908
1825
  constructor(options = {}) {
1909
- this.entries = /* @__PURE__ */ new Map();
1826
+ this.entries = new Map();
1910
1827
  this.maxEntries = normalizeMaxEntries(options.maxEntries);
1911
1828
  }
1912
1829
  get(key) {
1913
1830
  const entry = this.entries.get(key);
1914
1831
  if (!entry) return;
1915
- if (!Number.isFinite(entry.expiresAt) || Date.now() > entry.expiresAt) {
1832
+ if (isExpired(entry.expiresAt)) {
1916
1833
  this.entries.delete(key);
1917
1834
  return;
1918
1835
  }
@@ -1946,11 +1863,11 @@ const DEFAULT_VARY_HEADERS = [
1946
1863
  ];
1947
1864
  function cachePlugin(options = {}) {
1948
1865
  const store = options.store ?? new MemoryCacheStore({ maxEntries: options.maxEntries });
1949
- const cacheHits = /* @__PURE__ */ new WeakSet();
1950
- const leaders = /* @__PURE__ */ new WeakMap();
1951
- const completedRecords = /* @__PURE__ */ new WeakMap();
1952
- const uncacheableLeaders = /* @__PURE__ */ new WeakSet();
1953
- const inFlight = /* @__PURE__ */ new Map();
1866
+ const cacheHits = new WeakSet();
1867
+ const leaders = new WeakMap();
1868
+ const completedRecords = new WeakMap();
1869
+ const uncacheableLeaders = new WeakSet();
1870
+ const inFlight = new Map();
1954
1871
  const methods = new Set(options.methods ?? DEFAULT_CACHE_METHODS);
1955
1872
  const varyHeaders = options.varyHeaders ?? DEFAULT_VARY_HEADERS;
1956
1873
  return {
@@ -1959,15 +1876,16 @@ function cachePlugin(options = {}) {
1959
1876
  return store.clear();
1960
1877
  },
1961
1878
  install(context) {
1962
- const ownedLeaders = /* @__PURE__ */ new Set();
1879
+ const ownedLeaders = new Set();
1963
1880
  let active = true;
1964
1881
  context.hooks.onRequest(async (requestContext) => {
1965
1882
  const cache = resolveExtensionConfig(requestContext.config, "cache");
1966
1883
  if (!cache?.enabled || !isCacheableRequest(requestContext.config, methods)) return;
1884
+ normalizeCacheTtl(cache.ttl, requestContext.config);
1967
1885
  const key = createCacheKey(requestContext.config, cache, varyHeaders);
1968
1886
  const record = await readStore(store, key);
1969
1887
  if (!active) return;
1970
- if (record) if (!Number.isFinite(record.expiresAt) || Date.now() > record.expiresAt) await deleteStore(store, key);
1888
+ if (record) if (isExpired(record.expiresAt)) await deleteStore(store, key);
1971
1889
  else {
1972
1890
  const cachedResponse = restoreCacheEntry(record, requestContext.config);
1973
1891
  if (cachedResponse) {
@@ -2001,7 +1919,7 @@ function cachePlugin(options = {}) {
2001
1919
  await deleteStore(store, key);
2002
1920
  return;
2003
1921
  }
2004
- const ttl = cache.ttl ?? 3e4;
1922
+ const ttl = normalizeCacheTtl(cache.ttl, requestContext.config);
2005
1923
  const record = createCacheEntry(requestContext.response, Date.now() + Math.max(0, ttl));
2006
1924
  completedRecords.set(requestContext, record);
2007
1925
  if (ttl <= 0 || !allowsPersistentCaching(requestContext.response)) {
@@ -2178,7 +2096,7 @@ function createCacheKey(config, cache, varyHeaders) {
2178
2096
  });
2179
2097
  }
2180
2098
  function normalizeCacheHeaders(headers, varyHeaders) {
2181
- const values = /* @__PURE__ */ new Map();
2099
+ const values = new Map();
2182
2100
  headers.forEach((value, name) => {
2183
2101
  values.set(name.toLowerCase(), value);
2184
2102
  });
@@ -2235,11 +2153,33 @@ function normalizeMaxEntries(value) {
2235
2153
  if (!Number.isFinite(value)) return value > 0 ? Number.POSITIVE_INFINITY : 0;
2236
2154
  return Math.max(0, Math.floor(value));
2237
2155
  }
2156
+ function normalizeCacheTtl(value, config) {
2157
+ const ttl = value ?? 3e4;
2158
+ if (ttl !== Number.POSITIVE_INFINITY && (!Number.isFinite(ttl) || ttl < 0)) throw new RequestError("Cache ttl must be a non-negative finite number or Infinity", {
2159
+ code: "CONFIG_ERROR",
2160
+ config
2161
+ });
2162
+ return ttl;
2163
+ }
2164
+ function isExpired(expiresAt) {
2165
+ return Number.isNaN(expiresAt) || Date.now() >= expiresAt;
2166
+ }
2167
+ //#endregion
2168
+ //#region src/utils/resolveRequestOrigin.ts
2169
+ function resolveRequestOrigin(config) {
2170
+ try {
2171
+ return new URL(config.url).origin;
2172
+ } catch {}
2173
+ try {
2174
+ if (config.baseURL) return new URL(config.url, config.baseURL).origin;
2175
+ } catch {}
2176
+ return "default";
2177
+ }
2238
2178
  //#endregion
2239
2179
  //#region src/plugins/circuitBreakerPlugin.ts
2240
2180
  function circuitBreakerPlugin(options = {}) {
2241
2181
  const normalized = normalizeOptions$1(options);
2242
- const circuits = /* @__PURE__ */ new Map();
2182
+ const circuits = new Map();
2243
2183
  return {
2244
2184
  name: "circuit-breaker",
2245
2185
  getState(key) {
@@ -2253,7 +2193,7 @@ function circuitBreakerPlugin(options = {}) {
2253
2193
  circuits.delete(key);
2254
2194
  },
2255
2195
  install(context) {
2256
- const admissions = /* @__PURE__ */ new WeakMap();
2196
+ const admissions = new WeakMap();
2257
2197
  let active = true;
2258
2198
  context.hooks.onRequest((requestContext) => {
2259
2199
  const requestOptions = resolveExtensionConfig(requestContext.config, "circuitBreaker");
@@ -2322,7 +2262,7 @@ function normalizeOptions$1(options) {
2322
2262
  resetTimeout: normalizeDuration$1(options.resetTimeout, 3e4),
2323
2263
  halfOpenMaxRequests: normalizePositiveInteger$1(options.halfOpenMaxRequests, 1),
2324
2264
  maxCircuits: normalizePositiveInteger$1(options.maxCircuits, 1e3),
2325
- createKey: options.createKey ?? createDefaultKey$1,
2265
+ createKey: options.createKey ?? resolveRequestOrigin,
2326
2266
  shouldCountFailure: options.shouldCountFailure ?? defaultShouldCountFailure,
2327
2267
  onStateChange: options.onStateChange
2328
2268
  };
@@ -2340,15 +2280,6 @@ function normalizeDuration$1(value, fallback) {
2340
2280
  function normalizeKey$1(key) {
2341
2281
  return key || "default";
2342
2282
  }
2343
- function createDefaultKey$1(config) {
2344
- try {
2345
- return new URL(config.url).origin;
2346
- } catch {}
2347
- try {
2348
- if (config.baseURL) return new URL(config.url, config.baseURL).origin;
2349
- } catch {}
2350
- return "default";
2351
- }
2352
2283
  function getCircuit(circuits, key, maxCircuits) {
2353
2284
  let record = circuits.get(key);
2354
2285
  if (record) {
@@ -2430,7 +2361,7 @@ function defaultShouldCountFailure(error) {
2430
2361
  //#region src/plugins/concurrencyPlugin.ts
2431
2362
  function concurrencyPlugin(options = {}) {
2432
2363
  const normalized = normalizeOptions(options);
2433
- const records = /* @__PURE__ */ new Map();
2364
+ const records = new Map();
2434
2365
  return {
2435
2366
  name: "concurrency",
2436
2367
  getState(key) {
@@ -2441,7 +2372,7 @@ function concurrencyPlugin(options = {}) {
2441
2372
  };
2442
2373
  },
2443
2374
  install(context) {
2444
- const admissions = /* @__PURE__ */ new WeakMap();
2375
+ const admissions = new WeakMap();
2445
2376
  let active = true;
2446
2377
  context.hooks.onRequest(async (requestContext) => {
2447
2378
  const requestOptions = resolveExtensionConfig(requestContext.config, "concurrency");
@@ -2573,7 +2504,7 @@ function normalizeOptions(options) {
2573
2504
  maxQueue: normalizeNonNegativeInteger(options.maxQueue, 1e3),
2574
2505
  queueTimeout: normalizeDuration(options.queueTimeout, 3e4),
2575
2506
  maxKeys: normalizePositiveInteger(options.maxKeys, 1e3),
2576
- createKey: options.createKey ?? createDefaultKey
2507
+ createKey: options.createKey ?? resolveRequestOrigin
2577
2508
  };
2578
2509
  }
2579
2510
  function normalizePositiveInteger(value, fallback) {
@@ -2592,15 +2523,6 @@ function normalizeDuration(value, fallback) {
2592
2523
  function normalizeKey(key) {
2593
2524
  return String(key).trim() || "default";
2594
2525
  }
2595
- function createDefaultKey(config) {
2596
- try {
2597
- return new URL(config.url).origin;
2598
- } catch {}
2599
- try {
2600
- if (config.baseURL) return new URL(config.url, config.baseURL).origin;
2601
- } catch {}
2602
- return "default";
2603
- }
2604
2526
  function createLimitError(message, config) {
2605
2527
  return new RequestError(message, {
2606
2528
  code: "CONCURRENCY_LIMIT",
@@ -2724,7 +2646,7 @@ async function processResponse(xhr, config) {
2724
2646
  config,
2725
2647
  raw
2726
2648
  };
2727
- if (!(config.validateStatus ?? defaultValidateStatus)(xhr.status)) throw new RequestError(xhr.statusText || "Request failed", {
2649
+ if (!validateResponseStatus(xhr.status, config)) throw new RequestError(xhr.statusText || "Request failed", {
2728
2650
  code: "HTTP_ERROR",
2729
2651
  response
2730
2652
  });
@@ -2800,13 +2722,10 @@ function createConfigError(config, cause) {
2800
2722
  function isNullBodyStatus(status) {
2801
2723
  return status === 204 || status === 205 || status === 304;
2802
2724
  }
2803
- function defaultValidateStatus(status) {
2804
- return status >= 200 && status < 300;
2805
- }
2806
2725
  //#endregion
2807
2726
  //#region src/plugins/downloadPlugin.ts
2808
2727
  function downloadPlugin(options = {}) {
2809
- const xhrContexts = /* @__PURE__ */ new WeakSet();
2728
+ const xhrContexts = new WeakSet();
2810
2729
  return {
2811
2730
  name: "download",
2812
2731
  install(context) {
@@ -2884,10 +2803,6 @@ async function consumeDownloadStream(stream, response, onProgress) {
2884
2803
  }
2885
2804
  return new Blob(chunks, { type: response.headers.get("content-type") ?? "" });
2886
2805
  }
2887
- /**
2888
- * Reuses complete ArrayBuffer chunks and copies only sliced or
2889
- * SharedArrayBuffer-backed views before passing them to Blob.
2890
- */
2891
2806
  function toDownloadBuffer(chunk) {
2892
2807
  if (chunk.buffer instanceof ArrayBuffer) {
2893
2808
  if (chunk.byteOffset === 0 && chunk.byteLength === chunk.buffer.byteLength) return chunk.buffer;
@@ -2918,7 +2833,7 @@ function createProgress(loaded, total) {
2918
2833
  //#region src/plugins/loggerPlugin.ts
2919
2834
  function loggerPlugin(defaultOptions = {}) {
2920
2835
  let nextRequestId = 0;
2921
- const states = /* @__PURE__ */ new WeakMap();
2836
+ const states = new WeakMap();
2922
2837
  return {
2923
2838
  name: "logger",
2924
2839
  install(context) {
@@ -2999,7 +2914,7 @@ function emitError(options, entry) {
2999
2914
  } catch {}
3000
2915
  }
3001
2916
  function ignoreLoggerError() {}
3002
- const SENSITIVE_QUERY_KEYS = /* @__PURE__ */ new Set([
2917
+ const SENSITIVE_QUERY_KEYS = new Set([
3003
2918
  "access_token",
3004
2919
  "api-key",
3005
2920
  "api_key",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@npora/request",
3
- "version": "1.10.0",
3
+ "version": "1.10.2",
4
4
  "description": "A modern, TypeScript-first HTTP client powered by the Fetch API.",
5
5
  "keywords": [
6
6
  "npora",
@@ -8,7 +8,14 @@
8
8
  "fetch",
9
9
  "http",
10
10
  "http-client",
11
- "typescript"
11
+ "typescript",
12
+ "retry",
13
+ "cache",
14
+ "sse",
15
+ "ndjson",
16
+ "standard-schema",
17
+ "circuit-breaker",
18
+ "web-worker"
12
19
  ],
13
20
  "homepage": "https://github.com/npora/request",
14
21
  "repository": {