@npora/request 1.6.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/README.md CHANGED
@@ -116,6 +116,7 @@ import {
116
116
  authPlugin,
117
117
  cachePlugin,
118
118
  circuitBreakerPlugin,
119
+ concurrencyPlugin,
119
120
  createClient,
120
121
  retryPlugin
121
122
  } from '@npora/request'
@@ -129,6 +130,7 @@ const request = createClient()
129
130
  maxElapsedTime: 10000
130
131
  }))
131
132
  .use(circuitBreakerPlugin())
133
+ .use(concurrencyPlugin({ maxConcurrent: 20 }))
132
134
  .use(cache)
133
135
  .use(authPlugin({
134
136
  token: () => accessToken,
@@ -167,6 +169,7 @@ Built-in plugins:
167
169
  - `retryPlugin()`
168
170
  - `cachePlugin()`
169
171
  - `circuitBreakerPlugin()`
172
+ - `concurrencyPlugin()`
170
173
  - `authPlugin()`
171
174
  - `loggerPlugin()`
172
175
  - `uploadPlugin()`
@@ -194,6 +197,22 @@ the stable `CIRCUIT_OPEN` error code and permit a bounded half-open probe after
194
197
  the recovery window. Inactive circuit state is retained with LRU eviction;
195
198
  active requests are never evicted and can temporarily exceed `maxCircuits`.
196
199
 
200
+ Bound concurrent logical requests and queue short bursts before adapter I/O:
201
+
202
+ ```ts
203
+ const concurrency = concurrencyPlugin({
204
+ maxConcurrent: 20,
205
+ maxQueue: 200,
206
+ queueTimeout: 5000
207
+ })
208
+
209
+ const request = createClient().use(concurrency)
210
+ ```
211
+
212
+ Limits are isolated by resolved request origin. Queued requests are admitted
213
+ in FIFO order and remain abortable through their request signal. Full queues
214
+ and expired queue waits reject with the stable `CONCURRENCY_LIMIT` error code.
215
+
197
216
  Inject a structured logger when request correlation and timing are needed:
198
217
 
199
218
  ```ts
@@ -269,6 +288,7 @@ Stable request error codes:
269
288
  - `ABORT_ERROR`
270
289
  - `PARSER_ERROR`
271
290
  - `CIRCUIT_OPEN`
291
+ - `CONCURRENCY_LIMIT`
272
292
 
273
293
  ## Documentation
274
294
 
package/dist/index.cjs CHANGED
@@ -30,6 +30,7 @@ __export(index_exports, {
30
30
  authPlugin: () => authPlugin,
31
31
  cachePlugin: () => cachePlugin,
32
32
  circuitBreakerPlugin: () => circuitBreakerPlugin,
33
+ concurrencyPlugin: () => concurrencyPlugin,
33
34
  createClient: () => createClient,
34
35
  downloadPlugin: () => downloadPlugin,
35
36
  loggerPlugin: () => loggerPlugin,
@@ -2530,6 +2531,274 @@ function defaultShouldCountFailure(error) {
2530
2531
  return error.code === "HTTP_ERROR" && (error.status === 429 || error.status !== void 0 && error.status >= 500);
2531
2532
  }
2532
2533
 
2534
+ // src/plugins/concurrencyPlugin.ts
2535
+ function concurrencyPlugin(options = {}) {
2536
+ const normalized = normalizeOptions2(options);
2537
+ const records = /* @__PURE__ */ new Map();
2538
+ return {
2539
+ name: "concurrency",
2540
+ getState(key) {
2541
+ const record = records.get(normalizeKey2(key));
2542
+ return {
2543
+ active: record?.active ?? 0,
2544
+ queued: record?.queue.length ?? 0
2545
+ };
2546
+ },
2547
+ install(context) {
2548
+ const admissions = /* @__PURE__ */ new WeakMap();
2549
+ let active = true;
2550
+ context.hooks.onRequest(async (requestContext) => {
2551
+ const requestOptions = resolveExtensionConfig(
2552
+ requestContext.config,
2553
+ "concurrency"
2554
+ );
2555
+ if (requestOptions?.enabled === false) {
2556
+ return;
2557
+ }
2558
+ const key = normalizeKey2(
2559
+ requestOptions?.key ?? normalized.createKey(requestContext.config)
2560
+ );
2561
+ const record = getRecord(records, key, normalized.maxKeys);
2562
+ if (record.active < normalized.maxConcurrent) {
2563
+ record.active += 1;
2564
+ admissions.set(requestContext, {
2565
+ key,
2566
+ record
2567
+ });
2568
+ return;
2569
+ }
2570
+ if (requestContext.config.signal?.aborted) {
2571
+ throw createAbortError3(
2572
+ requestContext.config.signal.reason,
2573
+ requestContext.config
2574
+ );
2575
+ }
2576
+ if (record.queue.length >= normalized.maxQueue) {
2577
+ throw createLimitError(
2578
+ "Concurrency queue is full",
2579
+ requestContext.config
2580
+ );
2581
+ }
2582
+ const timeout = normalizeDuration2(
2583
+ requestOptions?.queueTimeout,
2584
+ normalized.queueTimeout
2585
+ );
2586
+ await enqueue(record, requestContext, timeout);
2587
+ if (!active) {
2588
+ throw createRemovedError(requestContext.config);
2589
+ }
2590
+ });
2591
+ context.hooks.onSettled((requestContext) => {
2592
+ const admission = admissions.get(requestContext);
2593
+ if (!admission) {
2594
+ return;
2595
+ }
2596
+ admissions.delete(requestContext);
2597
+ if (!active || records.get(admission.key) !== admission.record) {
2598
+ return;
2599
+ }
2600
+ releaseNext(admission.record, (entry) => {
2601
+ admissions.set(entry.context, admission);
2602
+ entry.resolve();
2603
+ });
2604
+ if (admission.record.active === 0 && admission.record.queue.length === 0) {
2605
+ touchRecord(records, admission.key, admission.record);
2606
+ trimRecords(records, normalized.maxKeys);
2607
+ }
2608
+ });
2609
+ return () => {
2610
+ active = false;
2611
+ for (const record of records.values()) {
2612
+ for (const entry of record.queue.splice(0)) {
2613
+ entry.cleanup();
2614
+ entry.reject(createRemovedError(entry.config));
2615
+ }
2616
+ }
2617
+ records.clear();
2618
+ };
2619
+ }
2620
+ };
2621
+ }
2622
+ function enqueue(record, context, timeout) {
2623
+ const { config } = context;
2624
+ const signal = config.signal;
2625
+ if (signal?.aborted) {
2626
+ return Promise.reject(createAbortError3(signal.reason, config));
2627
+ }
2628
+ if (timeout <= 0) {
2629
+ return Promise.reject(
2630
+ createLimitError("Concurrency queue wait timed out", config)
2631
+ );
2632
+ }
2633
+ return new Promise((resolve, reject) => {
2634
+ let timer;
2635
+ let settled = false;
2636
+ const remove = () => {
2637
+ const index = record.queue.indexOf(entry);
2638
+ if (index !== -1) {
2639
+ record.queue.splice(index, 1);
2640
+ }
2641
+ };
2642
+ const cleanup = () => {
2643
+ if (timer !== void 0) {
2644
+ clearTimeout(timer);
2645
+ }
2646
+ signal?.removeEventListener("abort", onAbort);
2647
+ };
2648
+ const rejectOnce = (error) => {
2649
+ if (settled) {
2650
+ return;
2651
+ }
2652
+ settled = true;
2653
+ cleanup();
2654
+ reject(error);
2655
+ };
2656
+ const resolveOnce = () => {
2657
+ if (settled) {
2658
+ return;
2659
+ }
2660
+ settled = true;
2661
+ cleanup();
2662
+ resolve();
2663
+ };
2664
+ const onAbort = () => {
2665
+ remove();
2666
+ rejectOnce(createAbortError3(signal?.reason, config));
2667
+ };
2668
+ const entry = {
2669
+ context,
2670
+ config,
2671
+ resolve: resolveOnce,
2672
+ reject: rejectOnce,
2673
+ cleanup
2674
+ };
2675
+ record.queue.push(entry);
2676
+ signal?.addEventListener("abort", onAbort, {
2677
+ once: true
2678
+ });
2679
+ if (Number.isFinite(timeout)) {
2680
+ timer = setTimeout(() => {
2681
+ remove();
2682
+ rejectOnce(
2683
+ createLimitError("Concurrency queue wait timed out", config)
2684
+ );
2685
+ }, timeout);
2686
+ }
2687
+ });
2688
+ }
2689
+ function releaseNext(record, grant) {
2690
+ const next = record.queue.shift();
2691
+ if (next) {
2692
+ next.cleanup();
2693
+ grant(next);
2694
+ return;
2695
+ }
2696
+ record.active = Math.max(0, record.active - 1);
2697
+ }
2698
+ function getRecord(records, key, maxKeys) {
2699
+ const existing = records.get(key);
2700
+ if (existing) {
2701
+ touchRecord(records, key, existing);
2702
+ return existing;
2703
+ }
2704
+ trimRecords(records, Math.max(0, maxKeys - 1));
2705
+ const record = {
2706
+ active: 0,
2707
+ queue: []
2708
+ };
2709
+ records.set(key, record);
2710
+ return record;
2711
+ }
2712
+ function touchRecord(records, key, record) {
2713
+ records.delete(key);
2714
+ records.set(key, record);
2715
+ }
2716
+ function trimRecords(records, maxKeys) {
2717
+ if (records.size <= maxKeys) {
2718
+ return;
2719
+ }
2720
+ for (const [key, record] of records) {
2721
+ if (records.size <= maxKeys) {
2722
+ return;
2723
+ }
2724
+ if (record.active === 0 && record.queue.length === 0) {
2725
+ records.delete(key);
2726
+ }
2727
+ }
2728
+ }
2729
+ function normalizeOptions2(options) {
2730
+ return {
2731
+ maxConcurrent: normalizePositiveInteger2(options.maxConcurrent, 10),
2732
+ maxQueue: normalizeNonNegativeInteger(options.maxQueue, 1e3),
2733
+ queueTimeout: normalizeDuration2(options.queueTimeout, 3e4),
2734
+ maxKeys: normalizePositiveInteger2(options.maxKeys, 1e3),
2735
+ createKey: options.createKey ?? createDefaultKey2
2736
+ };
2737
+ }
2738
+ function normalizePositiveInteger2(value, fallback) {
2739
+ if (value === void 0 || !Number.isFinite(value)) {
2740
+ return fallback;
2741
+ }
2742
+ return Math.max(1, Math.floor(value));
2743
+ }
2744
+ function normalizeNonNegativeInteger(value, fallback) {
2745
+ if (value === void 0 || !Number.isFinite(value)) {
2746
+ return fallback;
2747
+ }
2748
+ return Math.max(0, Math.floor(value));
2749
+ }
2750
+ function normalizeDuration2(value, fallback) {
2751
+ if (value === void 0) {
2752
+ return fallback;
2753
+ }
2754
+ if (!Number.isFinite(value)) {
2755
+ return value > 0 ? Number.POSITIVE_INFINITY : 0;
2756
+ }
2757
+ return Math.max(0, value);
2758
+ }
2759
+ function normalizeKey2(key) {
2760
+ const normalized = String(key).trim();
2761
+ return normalized || "default";
2762
+ }
2763
+ function createDefaultKey2(config) {
2764
+ try {
2765
+ return new URL(config.url).origin;
2766
+ } catch {
2767
+ }
2768
+ try {
2769
+ if (config.baseURL) {
2770
+ return new URL(config.url, config.baseURL).origin;
2771
+ }
2772
+ } catch {
2773
+ }
2774
+ return "default";
2775
+ }
2776
+ function createLimitError(message, config) {
2777
+ return new RequestError(message, {
2778
+ code: "CONCURRENCY_LIMIT",
2779
+ config
2780
+ });
2781
+ }
2782
+ function createAbortError3(reason, config) {
2783
+ return new RequestError(
2784
+ "Request aborted while waiting for concurrency permit",
2785
+ {
2786
+ code: "ABORT_ERROR",
2787
+ config,
2788
+ cause: reason
2789
+ }
2790
+ );
2791
+ }
2792
+ function createRemovedError(config) {
2793
+ return new RequestError(
2794
+ "Concurrency plugin removed while request was queued",
2795
+ {
2796
+ code: "ABORT_ERROR",
2797
+ config
2798
+ }
2799
+ );
2800
+ }
2801
+
2533
2802
  // src/plugins/xhrTransport.ts
2534
2803
  function xhrRequest(config, options = {}) {
2535
2804
  let request;
@@ -2579,7 +2848,7 @@ function xhrRequest(config, options = {}) {
2579
2848
  };
2580
2849
  const onSignalAbort = () => {
2581
2850
  abortWith(
2582
- createAbortError3(signal?.reason, config)
2851
+ createAbortError4(signal?.reason, config)
2583
2852
  );
2584
2853
  };
2585
2854
  xhr.onload = () => {
@@ -2598,7 +2867,7 @@ function xhrRequest(config, options = {}) {
2598
2867
  };
2599
2868
  xhr.onabort = () => {
2600
2869
  rejectOnce(
2601
- createAbortError3(signal?.reason, config)
2870
+ createAbortError4(signal?.reason, config)
2602
2871
  );
2603
2872
  };
2604
2873
  xhr.onprogress = createProgressHandler(
@@ -2756,7 +3025,7 @@ function parseHeaders(value) {
2756
3025
  }
2757
3026
  return headers;
2758
3027
  }
2759
- function createAbortError3(reason, config) {
3028
+ function createAbortError4(reason, config) {
2760
3029
  if (reason instanceof RequestError) {
2761
3030
  return new RequestError(reason.message, {
2762
3031
  code: reason.code,
@@ -3460,6 +3729,7 @@ function uploadPlugin() {
3460
3729
  authPlugin,
3461
3730
  cachePlugin,
3462
3731
  circuitBreakerPlugin,
3732
+ concurrencyPlugin,
3463
3733
  createClient,
3464
3734
  downloadPlugin,
3465
3735
  loggerPlugin,
package/dist/index.d.cts CHANGED
@@ -98,6 +98,24 @@ interface CacheOptions {
98
98
  */
99
99
  dedupe?: boolean;
100
100
  }
101
+ interface ConcurrencyOptions {
102
+ /**
103
+ * Enable concurrency limiting for this request.
104
+ *
105
+ * @default true
106
+ */
107
+ enabled?: boolean;
108
+ /**
109
+ * Override the isolation key for this request.
110
+ */
111
+ key?: string;
112
+ /**
113
+ * Maximum time in milliseconds this request may wait for a permit.
114
+ *
115
+ * @default the plugin-level queueTimeout
116
+ */
117
+ queueTimeout?: number;
118
+ }
101
119
  interface AuthOptions {
102
120
  token?: string | (() => string | Promise<string>);
103
121
  scheme?: string;
@@ -221,6 +239,7 @@ interface RequestExtensions {
221
239
  auth?: AuthOptions;
222
240
  cache?: CacheOptions;
223
241
  circuitBreaker?: CircuitBreakerOptions;
242
+ concurrency?: ConcurrencyOptions;
224
243
  download?: DownloadOptions;
225
244
  logger?: LoggerOptions;
226
245
  retry?: number | RetryOptions;
@@ -516,7 +535,7 @@ declare function createClient(options?: ClientOptions): Client;
516
535
  /**
517
536
  * Public request error codes.
518
537
  */
519
- type RequestErrorCode = 'CONFIG_ERROR' | 'HTTP_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT_ERROR' | 'ABORT_ERROR' | 'PARSER_ERROR' | 'CIRCUIT_OPEN';
538
+ type RequestErrorCode = 'CONFIG_ERROR' | 'HTTP_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT_ERROR' | 'ABORT_ERROR' | 'PARSER_ERROR' | 'CIRCUIT_OPEN' | 'CONCURRENCY_LIMIT';
520
539
  interface RequestErrorOptions<T = unknown> {
521
540
  /**
522
541
  * Stable machine-readable error code.
@@ -748,6 +767,50 @@ interface CircuitBreakerPlugin extends Plugin {
748
767
  }
749
768
  declare function circuitBreakerPlugin(options?: CircuitBreakerPluginOptions): CircuitBreakerPlugin;
750
769
 
770
+ interface ConcurrencyPluginOptions {
771
+ /**
772
+ * Maximum active logical requests for each isolation key.
773
+ *
774
+ * @default 10
775
+ */
776
+ maxConcurrent?: number;
777
+ /**
778
+ * Maximum queued requests for each isolation key.
779
+ * Set to zero to reject instead of waiting.
780
+ *
781
+ * @default 1000
782
+ */
783
+ maxQueue?: number;
784
+ /**
785
+ * Maximum time in milliseconds a request may wait for a permit.
786
+ *
787
+ * @default 30000
788
+ */
789
+ queueTimeout?: number;
790
+ /**
791
+ * Maximum inactive isolation states retained by this plugin instance.
792
+ * Active and queued states are never evicted and may temporarily exceed
793
+ * the limit.
794
+ *
795
+ * @default 1000
796
+ */
797
+ maxKeys?: number;
798
+ /**
799
+ * Create the default isolation key for a request.
800
+ *
801
+ * @default the resolved request origin or "default"
802
+ */
803
+ createKey?: (config: RequestConfig) => string;
804
+ }
805
+ interface ConcurrencyState {
806
+ active: number;
807
+ queued: number;
808
+ }
809
+ interface ConcurrencyPlugin extends Plugin {
810
+ getState(key: string): Readonly<ConcurrencyState>;
811
+ }
812
+ declare function concurrencyPlugin(options?: ConcurrencyPluginOptions): ConcurrencyPlugin;
813
+
751
814
  type DownloadTransport = 'auto' | 'fetch' | 'xhr';
752
815
  interface DownloadPluginOptions {
753
816
  /**
@@ -768,4 +831,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
768
831
 
769
832
  declare function uploadPlugin(): Plugin;
770
833
 
771
- export { type Adapter, type AuthOptions, type AuthPluginOptions, type AuthTokenStorage, type CacheEntry, type CacheOptions, type CachePlugin, type CachePluginOptions, type CacheStore, type CircuitBreakerOptions, type CircuitBreakerPlugin, type CircuitBreakerPluginOptions, type CircuitBreakerStateChange, type CircuitState, 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, type MemoryCacheStoreOptions, MockAdapter, type MockAdapterOptions, type MockHandler, type MockReply, type MockReplyHandler, type MockRequestMatcher, type MockResponseOptions, type MockRoute, type MockURLMatcher, 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, circuitBreakerPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
834
+ export { type Adapter, type AuthOptions, type AuthPluginOptions, type AuthTokenStorage, type CacheEntry, type CacheOptions, type CachePlugin, type CachePluginOptions, type CacheStore, type CircuitBreakerOptions, type CircuitBreakerPlugin, type CircuitBreakerPluginOptions, type CircuitBreakerStateChange, type CircuitState, Client, type ClientOptions, type ConcurrencyOptions, type ConcurrencyPlugin, type ConcurrencyPluginOptions, type ConcurrencyState, 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, type MemoryCacheStoreOptions, MockAdapter, type MockAdapterOptions, type MockHandler, type MockReply, type MockReplyHandler, type MockRequestMatcher, type MockResponseOptions, type MockRoute, type MockURLMatcher, 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, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
package/dist/index.d.ts CHANGED
@@ -98,6 +98,24 @@ interface CacheOptions {
98
98
  */
99
99
  dedupe?: boolean;
100
100
  }
101
+ interface ConcurrencyOptions {
102
+ /**
103
+ * Enable concurrency limiting for this request.
104
+ *
105
+ * @default true
106
+ */
107
+ enabled?: boolean;
108
+ /**
109
+ * Override the isolation key for this request.
110
+ */
111
+ key?: string;
112
+ /**
113
+ * Maximum time in milliseconds this request may wait for a permit.
114
+ *
115
+ * @default the plugin-level queueTimeout
116
+ */
117
+ queueTimeout?: number;
118
+ }
101
119
  interface AuthOptions {
102
120
  token?: string | (() => string | Promise<string>);
103
121
  scheme?: string;
@@ -221,6 +239,7 @@ interface RequestExtensions {
221
239
  auth?: AuthOptions;
222
240
  cache?: CacheOptions;
223
241
  circuitBreaker?: CircuitBreakerOptions;
242
+ concurrency?: ConcurrencyOptions;
224
243
  download?: DownloadOptions;
225
244
  logger?: LoggerOptions;
226
245
  retry?: number | RetryOptions;
@@ -516,7 +535,7 @@ declare function createClient(options?: ClientOptions): Client;
516
535
  /**
517
536
  * Public request error codes.
518
537
  */
519
- type RequestErrorCode = 'CONFIG_ERROR' | 'HTTP_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT_ERROR' | 'ABORT_ERROR' | 'PARSER_ERROR' | 'CIRCUIT_OPEN';
538
+ type RequestErrorCode = 'CONFIG_ERROR' | 'HTTP_ERROR' | 'NETWORK_ERROR' | 'TIMEOUT_ERROR' | 'ABORT_ERROR' | 'PARSER_ERROR' | 'CIRCUIT_OPEN' | 'CONCURRENCY_LIMIT';
520
539
  interface RequestErrorOptions<T = unknown> {
521
540
  /**
522
541
  * Stable machine-readable error code.
@@ -748,6 +767,50 @@ interface CircuitBreakerPlugin extends Plugin {
748
767
  }
749
768
  declare function circuitBreakerPlugin(options?: CircuitBreakerPluginOptions): CircuitBreakerPlugin;
750
769
 
770
+ interface ConcurrencyPluginOptions {
771
+ /**
772
+ * Maximum active logical requests for each isolation key.
773
+ *
774
+ * @default 10
775
+ */
776
+ maxConcurrent?: number;
777
+ /**
778
+ * Maximum queued requests for each isolation key.
779
+ * Set to zero to reject instead of waiting.
780
+ *
781
+ * @default 1000
782
+ */
783
+ maxQueue?: number;
784
+ /**
785
+ * Maximum time in milliseconds a request may wait for a permit.
786
+ *
787
+ * @default 30000
788
+ */
789
+ queueTimeout?: number;
790
+ /**
791
+ * Maximum inactive isolation states retained by this plugin instance.
792
+ * Active and queued states are never evicted and may temporarily exceed
793
+ * the limit.
794
+ *
795
+ * @default 1000
796
+ */
797
+ maxKeys?: number;
798
+ /**
799
+ * Create the default isolation key for a request.
800
+ *
801
+ * @default the resolved request origin or "default"
802
+ */
803
+ createKey?: (config: RequestConfig) => string;
804
+ }
805
+ interface ConcurrencyState {
806
+ active: number;
807
+ queued: number;
808
+ }
809
+ interface ConcurrencyPlugin extends Plugin {
810
+ getState(key: string): Readonly<ConcurrencyState>;
811
+ }
812
+ declare function concurrencyPlugin(options?: ConcurrencyPluginOptions): ConcurrencyPlugin;
813
+
751
814
  type DownloadTransport = 'auto' | 'fetch' | 'xhr';
752
815
  interface DownloadPluginOptions {
753
816
  /**
@@ -768,4 +831,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
768
831
 
769
832
  declare function uploadPlugin(): Plugin;
770
833
 
771
- export { type Adapter, type AuthOptions, type AuthPluginOptions, type AuthTokenStorage, type CacheEntry, type CacheOptions, type CachePlugin, type CachePluginOptions, type CacheStore, type CircuitBreakerOptions, type CircuitBreakerPlugin, type CircuitBreakerPluginOptions, type CircuitBreakerStateChange, type CircuitState, 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, type MemoryCacheStoreOptions, MockAdapter, type MockAdapterOptions, type MockHandler, type MockReply, type MockReplyHandler, type MockRequestMatcher, type MockResponseOptions, type MockRoute, type MockURLMatcher, 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, circuitBreakerPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
834
+ export { type Adapter, type AuthOptions, type AuthPluginOptions, type AuthTokenStorage, type CacheEntry, type CacheOptions, type CachePlugin, type CachePluginOptions, type CacheStore, type CircuitBreakerOptions, type CircuitBreakerPlugin, type CircuitBreakerPluginOptions, type CircuitBreakerStateChange, type CircuitState, Client, type ClientOptions, type ConcurrencyOptions, type ConcurrencyPlugin, type ConcurrencyPluginOptions, type ConcurrencyState, 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, type MemoryCacheStoreOptions, MockAdapter, type MockAdapterOptions, type MockHandler, type MockReply, type MockReplyHandler, type MockRequestMatcher, type MockResponseOptions, type MockRoute, type MockURLMatcher, 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, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
package/dist/index.js CHANGED
@@ -2490,6 +2490,274 @@ function defaultShouldCountFailure(error) {
2490
2490
  return error.code === "HTTP_ERROR" && (error.status === 429 || error.status !== void 0 && error.status >= 500);
2491
2491
  }
2492
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
+
2493
2761
  // src/plugins/xhrTransport.ts
2494
2762
  function xhrRequest(config, options = {}) {
2495
2763
  let request;
@@ -2539,7 +2807,7 @@ function xhrRequest(config, options = {}) {
2539
2807
  };
2540
2808
  const onSignalAbort = () => {
2541
2809
  abortWith(
2542
- createAbortError3(signal?.reason, config)
2810
+ createAbortError4(signal?.reason, config)
2543
2811
  );
2544
2812
  };
2545
2813
  xhr.onload = () => {
@@ -2558,7 +2826,7 @@ function xhrRequest(config, options = {}) {
2558
2826
  };
2559
2827
  xhr.onabort = () => {
2560
2828
  rejectOnce(
2561
- createAbortError3(signal?.reason, config)
2829
+ createAbortError4(signal?.reason, config)
2562
2830
  );
2563
2831
  };
2564
2832
  xhr.onprogress = createProgressHandler(
@@ -2716,7 +2984,7 @@ function parseHeaders(value) {
2716
2984
  }
2717
2985
  return headers;
2718
2986
  }
2719
- function createAbortError3(reason, config) {
2987
+ function createAbortError4(reason, config) {
2720
2988
  if (reason instanceof RequestError) {
2721
2989
  return new RequestError(reason.message, {
2722
2990
  code: reason.code,
@@ -3419,6 +3687,7 @@ export {
3419
3687
  authPlugin,
3420
3688
  cachePlugin,
3421
3689
  circuitBreakerPlugin,
3690
+ concurrencyPlugin,
3422
3691
  createClient,
3423
3692
  downloadPlugin,
3424
3693
  loggerPlugin,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@npora/request",
3
- "version": "1.6.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",