@npora/request 1.5.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1829,13 +1829,35 @@ function defaultShouldRefresh(error) {
1829
1829
 
1830
1830
  // src/plugins/cachePlugin.ts
1831
1831
  var MemoryCacheStore = class {
1832
- constructor() {
1832
+ constructor(options = {}) {
1833
1833
  this.entries = /* @__PURE__ */ new Map();
1834
+ this.maxEntries = normalizeMaxEntries(options.maxEntries);
1834
1835
  }
1835
1836
  get(key) {
1836
- return this.entries.get(key);
1837
+ const entry = this.entries.get(key);
1838
+ if (!entry) {
1839
+ return void 0;
1840
+ }
1841
+ if (!Number.isFinite(entry.expiresAt) || Date.now() > entry.expiresAt) {
1842
+ this.entries.delete(key);
1843
+ return void 0;
1844
+ }
1845
+ this.entries.delete(key);
1846
+ this.entries.set(key, entry);
1847
+ return entry;
1837
1848
  }
1838
1849
  set(key, entry) {
1850
+ if (this.maxEntries === 0) {
1851
+ return;
1852
+ }
1853
+ this.entries.delete(key);
1854
+ while (this.entries.size >= this.maxEntries) {
1855
+ const oldestKey = this.entries.keys().next().value;
1856
+ if (oldestKey === void 0) {
1857
+ break;
1858
+ }
1859
+ this.entries.delete(oldestKey);
1860
+ }
1839
1861
  this.entries.set(key, entry);
1840
1862
  }
1841
1863
  delete(key) {
@@ -1856,7 +1878,9 @@ var DEFAULT_VARY_HEADERS = [
1856
1878
  "accept-language"
1857
1879
  ];
1858
1880
  function cachePlugin(options = {}) {
1859
- const store = options.store ?? new MemoryCacheStore();
1881
+ const store = options.store ?? new MemoryCacheStore({
1882
+ maxEntries: options.maxEntries
1883
+ });
1860
1884
  const cacheHits = /* @__PURE__ */ new WeakSet();
1861
1885
  const leaders = /* @__PURE__ */ new WeakMap();
1862
1886
  const completedRecords = /* @__PURE__ */ new WeakMap();
@@ -2196,6 +2220,15 @@ function cloneCacheValue(value) {
2196
2220
  return value;
2197
2221
  }
2198
2222
  }
2223
+ function normalizeMaxEntries(value) {
2224
+ if (value === void 0) {
2225
+ return 1e3;
2226
+ }
2227
+ if (!Number.isFinite(value)) {
2228
+ return value > 0 ? Number.POSITIVE_INFINITY : 0;
2229
+ }
2230
+ return Math.max(0, Math.floor(value));
2231
+ }
2199
2232
 
2200
2233
  // src/plugins/circuitBreakerPlugin.ts
2201
2234
  function circuitBreakerPlugin(options = {}) {
@@ -2227,7 +2260,11 @@ function circuitBreakerPlugin(options = {}) {
2227
2260
  const key = normalizeKey(
2228
2261
  requestOptions?.key ?? normalized.createKey(requestContext.config)
2229
2262
  );
2230
- const record = getCircuit(circuits, key);
2263
+ const record = getCircuit(
2264
+ circuits,
2265
+ key,
2266
+ normalized.maxCircuits
2267
+ );
2231
2268
  if (record.state === "open" && Date.now() - record.openedAt >= normalized.resetTimeout) {
2232
2269
  transition(record, key, "half-open", normalized);
2233
2270
  }
@@ -2241,10 +2278,12 @@ function circuitBreakerPlugin(options = {}) {
2241
2278
  if (probe) {
2242
2279
  record.probes += 1;
2243
2280
  }
2281
+ record.activeRequests += 1;
2244
2282
  admissions.set(requestContext, {
2245
2283
  key,
2246
2284
  generation: record.generation,
2247
- probe
2285
+ probe,
2286
+ record
2248
2287
  });
2249
2288
  });
2250
2289
  context.hooks.onSettled(async (requestContext) => {
@@ -2253,42 +2292,48 @@ function circuitBreakerPlugin(options = {}) {
2253
2292
  return;
2254
2293
  }
2255
2294
  admissions.delete(requestContext);
2295
+ const record = admission.record;
2256
2296
  if (!active) {
2297
+ record.activeRequests = Math.max(0, record.activeRequests - 1);
2257
2298
  return;
2258
2299
  }
2259
- const record = circuits.get(admission.key);
2260
- if (!record || record.generation !== admission.generation) {
2261
- return;
2262
- }
2263
- if (admission.probe) {
2264
- record.probes = Math.max(0, record.probes - 1);
2265
- }
2266
- if (!requestContext.error && requestContext.response) {
2267
- record.failures = 0;
2268
- if (admission.probe && record.state === "half-open") {
2269
- record.successes += 1;
2270
- if (record.successes >= normalized.successThreshold) {
2271
- transition(record, admission.key, "closed", normalized);
2300
+ try {
2301
+ if (circuits.get(admission.key) !== record || record.generation !== admission.generation) {
2302
+ return;
2303
+ }
2304
+ if (admission.probe) {
2305
+ record.probes = Math.max(0, record.probes - 1);
2306
+ }
2307
+ if (!requestContext.error && requestContext.response) {
2308
+ record.failures = 0;
2309
+ if (admission.probe && record.state === "half-open") {
2310
+ record.successes += 1;
2311
+ if (record.successes >= normalized.successThreshold) {
2312
+ transition(record, admission.key, "closed", normalized);
2313
+ }
2272
2314
  }
2315
+ return;
2273
2316
  }
2274
- return;
2275
- }
2276
- const counted = await normalized.shouldCountFailure(
2277
- requestContext.error,
2278
- requestContext.config
2279
- );
2280
- if (!active || circuits.get(admission.key) !== record || record.generation !== admission.generation || !counted) {
2281
- return;
2282
- }
2283
- if (admission.probe && record.state === "half-open") {
2284
- transition(record, admission.key, "open", normalized);
2285
- return;
2286
- }
2287
- if (record.state === "closed") {
2288
- record.failures += 1;
2289
- if (record.failures >= normalized.failureThreshold) {
2317
+ const counted = await normalized.shouldCountFailure(
2318
+ requestContext.error,
2319
+ requestContext.config
2320
+ );
2321
+ if (!active || circuits.get(admission.key) !== record || record.generation !== admission.generation || !counted) {
2322
+ return;
2323
+ }
2324
+ if (admission.probe && record.state === "half-open") {
2290
2325
  transition(record, admission.key, "open", normalized);
2326
+ return;
2291
2327
  }
2328
+ if (record.state === "closed") {
2329
+ record.failures += 1;
2330
+ if (record.failures >= normalized.failureThreshold) {
2331
+ transition(record, admission.key, "open", normalized);
2332
+ }
2333
+ }
2334
+ } finally {
2335
+ record.activeRequests = Math.max(0, record.activeRequests - 1);
2336
+ trimCircuits(circuits, normalized.maxCircuits);
2292
2337
  }
2293
2338
  });
2294
2339
  return () => {
@@ -2314,6 +2359,7 @@ function normalizeOptions(options) {
2314
2359
  options.halfOpenMaxRequests,
2315
2360
  1
2316
2361
  ),
2362
+ maxCircuits: normalizePositiveInteger(options.maxCircuits, 1e3),
2317
2363
  createKey: options.createKey ?? createDefaultKey,
2318
2364
  shouldCountFailure: options.shouldCountFailure ?? defaultShouldCountFailure,
2319
2365
  onStateChange: options.onStateChange
@@ -2353,21 +2399,41 @@ function createDefaultKey(config) {
2353
2399
  }
2354
2400
  return "default";
2355
2401
  }
2356
- function getCircuit(circuits, key) {
2402
+ function getCircuit(circuits, key, maxCircuits) {
2357
2403
  let record = circuits.get(key);
2358
- if (!record) {
2359
- record = {
2360
- state: "closed",
2361
- failures: 0,
2362
- successes: 0,
2363
- openedAt: 0,
2364
- probes: 0,
2365
- generation: 0
2366
- };
2404
+ if (record) {
2405
+ circuits.delete(key);
2367
2406
  circuits.set(key, record);
2368
- }
2407
+ return record;
2408
+ }
2409
+ trimCircuits(circuits, maxCircuits - 1);
2410
+ record = {
2411
+ state: "closed",
2412
+ failures: 0,
2413
+ successes: 0,
2414
+ openedAt: 0,
2415
+ probes: 0,
2416
+ generation: 0,
2417
+ activeRequests: 0
2418
+ };
2419
+ circuits.set(key, record);
2369
2420
  return record;
2370
2421
  }
2422
+ function trimCircuits(circuits, maxCircuits) {
2423
+ while (circuits.size > maxCircuits) {
2424
+ let removableKey;
2425
+ for (const [key, record] of circuits) {
2426
+ if (record.activeRequests === 0) {
2427
+ removableKey = key;
2428
+ break;
2429
+ }
2430
+ }
2431
+ if (removableKey === void 0) {
2432
+ return;
2433
+ }
2434
+ circuits.delete(removableKey);
2435
+ }
2436
+ }
2371
2437
  function transition(record, key, state, options) {
2372
2438
  if (record.state === state) {
2373
2439
  if (state === "open") {
@@ -2424,6 +2490,274 @@ function defaultShouldCountFailure(error) {
2424
2490
  return error.code === "HTTP_ERROR" && (error.status === 429 || error.status !== void 0 && error.status >= 500);
2425
2491
  }
2426
2492
 
2493
+ // src/plugins/concurrencyPlugin.ts
2494
+ function concurrencyPlugin(options = {}) {
2495
+ const normalized = normalizeOptions2(options);
2496
+ const records = /* @__PURE__ */ new Map();
2497
+ return {
2498
+ name: "concurrency",
2499
+ getState(key) {
2500
+ const record = records.get(normalizeKey2(key));
2501
+ return {
2502
+ active: record?.active ?? 0,
2503
+ queued: record?.queue.length ?? 0
2504
+ };
2505
+ },
2506
+ install(context) {
2507
+ const admissions = /* @__PURE__ */ new WeakMap();
2508
+ let active = true;
2509
+ context.hooks.onRequest(async (requestContext) => {
2510
+ const requestOptions = resolveExtensionConfig(
2511
+ requestContext.config,
2512
+ "concurrency"
2513
+ );
2514
+ if (requestOptions?.enabled === false) {
2515
+ return;
2516
+ }
2517
+ const key = normalizeKey2(
2518
+ requestOptions?.key ?? normalized.createKey(requestContext.config)
2519
+ );
2520
+ const record = getRecord(records, key, normalized.maxKeys);
2521
+ if (record.active < normalized.maxConcurrent) {
2522
+ record.active += 1;
2523
+ admissions.set(requestContext, {
2524
+ key,
2525
+ record
2526
+ });
2527
+ return;
2528
+ }
2529
+ if (requestContext.config.signal?.aborted) {
2530
+ throw createAbortError3(
2531
+ requestContext.config.signal.reason,
2532
+ requestContext.config
2533
+ );
2534
+ }
2535
+ if (record.queue.length >= normalized.maxQueue) {
2536
+ throw createLimitError(
2537
+ "Concurrency queue is full",
2538
+ requestContext.config
2539
+ );
2540
+ }
2541
+ const timeout = normalizeDuration2(
2542
+ requestOptions?.queueTimeout,
2543
+ normalized.queueTimeout
2544
+ );
2545
+ await enqueue(record, requestContext, timeout);
2546
+ if (!active) {
2547
+ throw createRemovedError(requestContext.config);
2548
+ }
2549
+ });
2550
+ context.hooks.onSettled((requestContext) => {
2551
+ const admission = admissions.get(requestContext);
2552
+ if (!admission) {
2553
+ return;
2554
+ }
2555
+ admissions.delete(requestContext);
2556
+ if (!active || records.get(admission.key) !== admission.record) {
2557
+ return;
2558
+ }
2559
+ releaseNext(admission.record, (entry) => {
2560
+ admissions.set(entry.context, admission);
2561
+ entry.resolve();
2562
+ });
2563
+ if (admission.record.active === 0 && admission.record.queue.length === 0) {
2564
+ touchRecord(records, admission.key, admission.record);
2565
+ trimRecords(records, normalized.maxKeys);
2566
+ }
2567
+ });
2568
+ return () => {
2569
+ active = false;
2570
+ for (const record of records.values()) {
2571
+ for (const entry of record.queue.splice(0)) {
2572
+ entry.cleanup();
2573
+ entry.reject(createRemovedError(entry.config));
2574
+ }
2575
+ }
2576
+ records.clear();
2577
+ };
2578
+ }
2579
+ };
2580
+ }
2581
+ function enqueue(record, context, timeout) {
2582
+ const { config } = context;
2583
+ const signal = config.signal;
2584
+ if (signal?.aborted) {
2585
+ return Promise.reject(createAbortError3(signal.reason, config));
2586
+ }
2587
+ if (timeout <= 0) {
2588
+ return Promise.reject(
2589
+ createLimitError("Concurrency queue wait timed out", config)
2590
+ );
2591
+ }
2592
+ return new Promise((resolve, reject) => {
2593
+ let timer;
2594
+ let settled = false;
2595
+ const remove = () => {
2596
+ const index = record.queue.indexOf(entry);
2597
+ if (index !== -1) {
2598
+ record.queue.splice(index, 1);
2599
+ }
2600
+ };
2601
+ const cleanup = () => {
2602
+ if (timer !== void 0) {
2603
+ clearTimeout(timer);
2604
+ }
2605
+ signal?.removeEventListener("abort", onAbort);
2606
+ };
2607
+ const rejectOnce = (error) => {
2608
+ if (settled) {
2609
+ return;
2610
+ }
2611
+ settled = true;
2612
+ cleanup();
2613
+ reject(error);
2614
+ };
2615
+ const resolveOnce = () => {
2616
+ if (settled) {
2617
+ return;
2618
+ }
2619
+ settled = true;
2620
+ cleanup();
2621
+ resolve();
2622
+ };
2623
+ const onAbort = () => {
2624
+ remove();
2625
+ rejectOnce(createAbortError3(signal?.reason, config));
2626
+ };
2627
+ const entry = {
2628
+ context,
2629
+ config,
2630
+ resolve: resolveOnce,
2631
+ reject: rejectOnce,
2632
+ cleanup
2633
+ };
2634
+ record.queue.push(entry);
2635
+ signal?.addEventListener("abort", onAbort, {
2636
+ once: true
2637
+ });
2638
+ if (Number.isFinite(timeout)) {
2639
+ timer = setTimeout(() => {
2640
+ remove();
2641
+ rejectOnce(
2642
+ createLimitError("Concurrency queue wait timed out", config)
2643
+ );
2644
+ }, timeout);
2645
+ }
2646
+ });
2647
+ }
2648
+ function releaseNext(record, grant) {
2649
+ const next = record.queue.shift();
2650
+ if (next) {
2651
+ next.cleanup();
2652
+ grant(next);
2653
+ return;
2654
+ }
2655
+ record.active = Math.max(0, record.active - 1);
2656
+ }
2657
+ function getRecord(records, key, maxKeys) {
2658
+ const existing = records.get(key);
2659
+ if (existing) {
2660
+ touchRecord(records, key, existing);
2661
+ return existing;
2662
+ }
2663
+ trimRecords(records, Math.max(0, maxKeys - 1));
2664
+ const record = {
2665
+ active: 0,
2666
+ queue: []
2667
+ };
2668
+ records.set(key, record);
2669
+ return record;
2670
+ }
2671
+ function touchRecord(records, key, record) {
2672
+ records.delete(key);
2673
+ records.set(key, record);
2674
+ }
2675
+ function trimRecords(records, maxKeys) {
2676
+ if (records.size <= maxKeys) {
2677
+ return;
2678
+ }
2679
+ for (const [key, record] of records) {
2680
+ if (records.size <= maxKeys) {
2681
+ return;
2682
+ }
2683
+ if (record.active === 0 && record.queue.length === 0) {
2684
+ records.delete(key);
2685
+ }
2686
+ }
2687
+ }
2688
+ function normalizeOptions2(options) {
2689
+ return {
2690
+ maxConcurrent: normalizePositiveInteger2(options.maxConcurrent, 10),
2691
+ maxQueue: normalizeNonNegativeInteger(options.maxQueue, 1e3),
2692
+ queueTimeout: normalizeDuration2(options.queueTimeout, 3e4),
2693
+ maxKeys: normalizePositiveInteger2(options.maxKeys, 1e3),
2694
+ createKey: options.createKey ?? createDefaultKey2
2695
+ };
2696
+ }
2697
+ function normalizePositiveInteger2(value, fallback) {
2698
+ if (value === void 0 || !Number.isFinite(value)) {
2699
+ return fallback;
2700
+ }
2701
+ return Math.max(1, Math.floor(value));
2702
+ }
2703
+ function normalizeNonNegativeInteger(value, fallback) {
2704
+ if (value === void 0 || !Number.isFinite(value)) {
2705
+ return fallback;
2706
+ }
2707
+ return Math.max(0, Math.floor(value));
2708
+ }
2709
+ function normalizeDuration2(value, fallback) {
2710
+ if (value === void 0) {
2711
+ return fallback;
2712
+ }
2713
+ if (!Number.isFinite(value)) {
2714
+ return value > 0 ? Number.POSITIVE_INFINITY : 0;
2715
+ }
2716
+ return Math.max(0, value);
2717
+ }
2718
+ function normalizeKey2(key) {
2719
+ const normalized = String(key).trim();
2720
+ return normalized || "default";
2721
+ }
2722
+ function createDefaultKey2(config) {
2723
+ try {
2724
+ return new URL(config.url).origin;
2725
+ } catch {
2726
+ }
2727
+ try {
2728
+ if (config.baseURL) {
2729
+ return new URL(config.url, config.baseURL).origin;
2730
+ }
2731
+ } catch {
2732
+ }
2733
+ return "default";
2734
+ }
2735
+ function createLimitError(message, config) {
2736
+ return new RequestError(message, {
2737
+ code: "CONCURRENCY_LIMIT",
2738
+ config
2739
+ });
2740
+ }
2741
+ function createAbortError3(reason, config) {
2742
+ return new RequestError(
2743
+ "Request aborted while waiting for concurrency permit",
2744
+ {
2745
+ code: "ABORT_ERROR",
2746
+ config,
2747
+ cause: reason
2748
+ }
2749
+ );
2750
+ }
2751
+ function createRemovedError(config) {
2752
+ return new RequestError(
2753
+ "Concurrency plugin removed while request was queued",
2754
+ {
2755
+ code: "ABORT_ERROR",
2756
+ config
2757
+ }
2758
+ );
2759
+ }
2760
+
2427
2761
  // src/plugins/xhrTransport.ts
2428
2762
  function xhrRequest(config, options = {}) {
2429
2763
  let request;
@@ -2473,7 +2807,7 @@ function xhrRequest(config, options = {}) {
2473
2807
  };
2474
2808
  const onSignalAbort = () => {
2475
2809
  abortWith(
2476
- createAbortError3(signal?.reason, config)
2810
+ createAbortError4(signal?.reason, config)
2477
2811
  );
2478
2812
  };
2479
2813
  xhr.onload = () => {
@@ -2492,7 +2826,7 @@ function xhrRequest(config, options = {}) {
2492
2826
  };
2493
2827
  xhr.onabort = () => {
2494
2828
  rejectOnce(
2495
- createAbortError3(signal?.reason, config)
2829
+ createAbortError4(signal?.reason, config)
2496
2830
  );
2497
2831
  };
2498
2832
  xhr.onprogress = createProgressHandler(
@@ -2650,7 +2984,7 @@ function parseHeaders(value) {
2650
2984
  }
2651
2985
  return headers;
2652
2986
  }
2653
- function createAbortError3(reason, config) {
2987
+ function createAbortError4(reason, config) {
2654
2988
  if (reason instanceof RequestError) {
2655
2989
  return new RequestError(reason.message, {
2656
2990
  code: reason.code,
@@ -3353,6 +3687,7 @@ export {
3353
3687
  authPlugin,
3354
3688
  cachePlugin,
3355
3689
  circuitBreakerPlugin,
3690
+ concurrencyPlugin,
3356
3691
  createClient,
3357
3692
  downloadPlugin,
3358
3693
  loggerPlugin,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@npora/request",
3
- "version": "1.5.0",
3
+ "version": "1.7.0",
4
4
  "description": "A modern, TypeScript-first HTTP client powered by the Fetch API.",
5
5
  "keywords": [
6
6
  "npora",