@npora/request 1.12.0 → 1.14.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
@@ -19,8 +19,9 @@ authentication, and upload/download progress.
19
19
 
20
20
  - **Trust responses at runtime.** Standard Schema v1 validation checks and can
21
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.
22
+ - **Stream without buffering everything.** File downloads, SSE, and NDJSON can
23
+ be consumed lazily with backpressure, cancellation, timeout, progress, and
24
+ response-size enforcement.
24
25
  - **Add resilience without hiding the transport.** Retry, cache, circuit
25
26
  breaker, concurrency, authentication, logging, and progress are isolated,
26
27
  composable plugins over the standard Fetch API.
@@ -37,6 +38,8 @@ authentication, and upload/download progress.
37
38
  `searchParams`.
38
39
  - Standard Schema v1 validation and transformation for untrusted responses.
39
40
  - Incremental SSE and NDJSON async iterables with cancellation and size limits.
41
+ - Progress-aware file download streams that preserve backpressure and avoid
42
+ buffering the complete response in memory.
40
43
  - Unified errors across Fetch, XHR, parsing, validation, timeouts, and aborts.
41
44
  - Request/response/error interceptors with deterministic priority ordering.
42
45
  - Official retry, cache, circuit-breaker, concurrency, authentication, logger,
package/dist/index.cjs CHANGED
@@ -2623,6 +2623,30 @@ function createRemovedError(config) {
2623
2623
  });
2624
2624
  }
2625
2625
  //#endregion
2626
+ //#region src/plugins/transferProgress.ts
2627
+ const MIN_RATE_SAMPLE_MILLISECONDS = 250;
2628
+ function createTransferProgressTracker(now = Date.now) {
2629
+ const startedAt = now();
2630
+ let previousLoaded = 0;
2631
+ return (loaded, total) => {
2632
+ const bytes = Math.max(loaded - previousLoaded, 0);
2633
+ const elapsed = Math.max(now() - startedAt, 0) / 1e3;
2634
+ const rate = elapsed >= MIN_RATE_SAMPLE_MILLISECONDS / 1e3 && loaded > 0 ? loaded / elapsed : void 0;
2635
+ const progress = total === void 0 || total === 0 ? void 0 : Math.min(loaded / total, 1);
2636
+ const estimated = rate && total !== void 0 ? Math.max(total - loaded, 0) / rate : void 0;
2637
+ previousLoaded = loaded;
2638
+ const snapshot = {
2639
+ loaded,
2640
+ total,
2641
+ bytes
2642
+ };
2643
+ if (progress !== void 0) snapshot.progress = progress;
2644
+ if (rate !== void 0) snapshot.rate = rate;
2645
+ if (estimated !== void 0) snapshot.estimated = estimated;
2646
+ return snapshot;
2647
+ };
2648
+ }
2649
+ //#endregion
2626
2650
  //#region src/plugins/xhrTransport.ts
2627
2651
  function xhrRequest(config, options = {}) {
2628
2652
  let request;
@@ -2742,6 +2766,7 @@ async function processResponse(xhr, config) {
2742
2766
  }
2743
2767
  function createProgressHandler(callback, abortWith, maxResponseSize, config) {
2744
2768
  if (!callback && !Number.isFinite(maxResponseSize)) return null;
2769
+ const trackProgress = callback ? createTransferProgressTracker() : void 0;
2745
2770
  return (event) => {
2746
2771
  if (Number.isFinite(maxResponseSize) && event.loaded > (maxResponseSize ?? Number.POSITIVE_INFINITY)) {
2747
2772
  abortWith(new RequestError(`Response body exceeds maxResponseSize ${maxResponseSize}`, {
@@ -2750,25 +2775,14 @@ function createProgressHandler(callback, abortWith, maxResponseSize, config) {
2750
2775
  }));
2751
2776
  return;
2752
2777
  }
2753
- if (!callback) return;
2778
+ if (!callback || !trackProgress) return;
2754
2779
  try {
2755
- callback(createProgress$1(event.loaded, event.lengthComputable ? event.total : void 0));
2780
+ callback(trackProgress(event.loaded, event.lengthComputable ? event.total : void 0));
2756
2781
  } catch (error) {
2757
2782
  abortWith(error);
2758
2783
  }
2759
2784
  };
2760
2785
  }
2761
- function createProgress$1(loaded, total) {
2762
- if (total === void 0 || total === 0) return {
2763
- loaded,
2764
- total
2765
- };
2766
- return {
2767
- loaded,
2768
- total,
2769
- progress: Math.min(loaded / total, 1)
2770
- };
2771
- }
2772
2786
  function parseHeaders(value) {
2773
2787
  const headers = new Headers();
2774
2788
  for (const line of value.split(/\r?\n/)) {
@@ -2812,6 +2826,13 @@ function downloadPlugin(options = {}) {
2812
2826
  context.interceptors.request.use((config) => {
2813
2827
  const download = resolveExtensionConfig(config, "download");
2814
2828
  if (!download) return config;
2829
+ if (resolveDownloadOutput(download.output, config) === "stream") {
2830
+ validateStreamOutput(options.transport, config);
2831
+ return {
2832
+ ...config,
2833
+ responseType: "stream"
2834
+ };
2835
+ }
2815
2836
  const responseType = download.onProgress && !shouldUseXHR(options.transport) ? "stream" : config.responseType ?? "blob";
2816
2837
  return {
2817
2838
  ...config,
@@ -2820,8 +2841,9 @@ function downloadPlugin(options = {}) {
2820
2841
  });
2821
2842
  context.hooks.onTransport(async (requestContext) => {
2822
2843
  if (requestContext.response) return;
2823
- const onProgress = resolveExtensionConfig(requestContext.config, "download")?.onProgress;
2824
- if (!onProgress || !shouldUseXHR(options.transport)) return;
2844
+ const download = resolveExtensionConfig(requestContext.config, "download");
2845
+ const onProgress = download?.onProgress;
2846
+ if (download?.output === "stream" || !onProgress || !shouldUseXHR(options.transport)) return;
2825
2847
  if (typeof XMLHttpRequest === "undefined") throw new RequestError("XMLHttpRequest is unavailable for download progress", {
2826
2848
  code: "CONFIG_ERROR",
2827
2849
  config: requestContext.config
@@ -2835,13 +2857,19 @@ function downloadPlugin(options = {}) {
2835
2857
  if (!response) return;
2836
2858
  const download = resolveExtensionConfig(response.config, "download");
2837
2859
  const onProgress = download?.onProgress;
2838
- if (!download || !onProgress) return;
2839
- const stream = response.data;
2840
- if (typeof ReadableStream === "undefined" || !(stream instanceof ReadableStream)) throw new RequestError("Download response stream is unavailable", {
2841
- code: "PARSER_ERROR",
2842
- status: response.status,
2843
- config: response.config
2844
- });
2860
+ if (!download) return;
2861
+ let stream = response.data;
2862
+ if (download.output === "stream") {
2863
+ if (stream === void 0 && isBodylessResponse(response)) stream = createEmptyDownloadStream();
2864
+ if (!isReadableStream$1(stream)) throw unavailableDownloadStream(response);
2865
+ if (onProgress) requestContext.response = {
2866
+ ...response,
2867
+ data: monitorDownloadStream(stream, response, onProgress)
2868
+ };
2869
+ return;
2870
+ }
2871
+ if (!onProgress) return;
2872
+ if (!isReadableStream$1(stream)) throw unavailableDownloadStream(response);
2845
2873
  const blob = await consumeDownloadStream(stream, response, onProgress);
2846
2874
  requestContext.response = {
2847
2875
  ...response,
@@ -2851,6 +2879,42 @@ function downloadPlugin(options = {}) {
2851
2879
  }
2852
2880
  };
2853
2881
  }
2882
+ function isBodylessResponse(response) {
2883
+ return response.config.method === "HEAD" || response.status === 204 || response.status === 205 || response.status === 304;
2884
+ }
2885
+ function createEmptyDownloadStream() {
2886
+ return new ReadableStream({ start(controller) {
2887
+ controller.close();
2888
+ } });
2889
+ }
2890
+ function resolveDownloadOutput(output, config) {
2891
+ if (output === void 0 || output === "blob") return "blob";
2892
+ if (output === "stream") return output;
2893
+ throw new RequestError("Download output must be \"blob\" or \"stream\"", {
2894
+ code: "CONFIG_ERROR",
2895
+ config
2896
+ });
2897
+ }
2898
+ function validateStreamOutput(transport, config) {
2899
+ if (transport === "xhr") throw new RequestError("Stream downloads require the Fetch transport", {
2900
+ code: "CONFIG_ERROR",
2901
+ config
2902
+ });
2903
+ if (!supportsFetchResponseStream()) throw new RequestError("Fetch response streams are unavailable", {
2904
+ code: "CONFIG_ERROR",
2905
+ config
2906
+ });
2907
+ }
2908
+ function unavailableDownloadStream(response) {
2909
+ return new RequestError("Download response stream is unavailable", {
2910
+ code: "PARSER_ERROR",
2911
+ status: response.status,
2912
+ config: response.config
2913
+ });
2914
+ }
2915
+ function isReadableStream$1(value) {
2916
+ return typeof value === "object" && value !== null && typeof value.getReader === "function";
2917
+ }
2854
2918
  function shouldUseXHR(transport = "auto") {
2855
2919
  if (transport === "xhr") return true;
2856
2920
  if (transport === "fetch") return false;
@@ -2863,7 +2927,9 @@ async function consumeDownloadStream(stream, response, onProgress) {
2863
2927
  const reader = stream.getReader();
2864
2928
  const chunks = [];
2865
2929
  const total = parseContentLength(response.headers.get("content-length"));
2930
+ const trackProgress = createTransferProgressTracker();
2866
2931
  let loaded = 0;
2932
+ let reported = false;
2867
2933
  try {
2868
2934
  while (true) {
2869
2935
  const result = await reader.read();
@@ -2871,8 +2937,10 @@ async function consumeDownloadStream(stream, response, onProgress) {
2871
2937
  const chunk = result.value;
2872
2938
  chunks.push(toDownloadBuffer(chunk));
2873
2939
  loaded += chunk.byteLength;
2874
- onProgress(createProgress(loaded, total));
2940
+ reported = true;
2941
+ onProgress(trackProgress(loaded, total));
2875
2942
  }
2943
+ if (!reported) onProgress(trackProgress(0, total));
2876
2944
  } catch (error) {
2877
2945
  try {
2878
2946
  await reader.cancel(error);
@@ -2883,6 +2951,50 @@ async function consumeDownloadStream(stream, response, onProgress) {
2883
2951
  }
2884
2952
  return new Blob(chunks, { type: response.headers.get("content-type") ?? "" });
2885
2953
  }
2954
+ function monitorDownloadStream(stream, response, onProgress) {
2955
+ const reader = stream.getReader();
2956
+ const total = parseContentLength(response.headers.get("content-length"));
2957
+ const trackProgress = createTransferProgressTracker();
2958
+ let loaded = 0;
2959
+ let reported = false;
2960
+ let released = false;
2961
+ const release = () => {
2962
+ if (!released) {
2963
+ released = true;
2964
+ reader.releaseLock();
2965
+ }
2966
+ };
2967
+ return new ReadableStream({
2968
+ async pull(controller) {
2969
+ try {
2970
+ const result = await reader.read();
2971
+ if (result.done) {
2972
+ if (!reported) onProgress(trackProgress(0, total));
2973
+ release();
2974
+ controller.close();
2975
+ return;
2976
+ }
2977
+ loaded += result.value.byteLength;
2978
+ reported = true;
2979
+ onProgress(trackProgress(loaded, total));
2980
+ controller.enqueue(result.value);
2981
+ } catch (error) {
2982
+ try {
2983
+ await reader.cancel(error);
2984
+ } catch {}
2985
+ release();
2986
+ controller.error(error);
2987
+ }
2988
+ },
2989
+ async cancel(reason) {
2990
+ try {
2991
+ await reader.cancel(reason);
2992
+ } finally {
2993
+ release();
2994
+ }
2995
+ }
2996
+ }, { highWaterMark: 0 });
2997
+ }
2886
2998
  function toDownloadBuffer(chunk) {
2887
2999
  if (chunk.buffer instanceof ArrayBuffer) {
2888
3000
  if (chunk.byteOffset === 0 && chunk.byteLength === chunk.buffer.byteLength) return chunk.buffer;
@@ -2898,17 +3010,6 @@ function parseContentLength(value) {
2898
3010
  if (!Number.isFinite(total) || total < 0) return;
2899
3011
  return total;
2900
3012
  }
2901
- function createProgress(loaded, total) {
2902
- if (total === void 0 || total === 0) return {
2903
- loaded,
2904
- total
2905
- };
2906
- return {
2907
- loaded,
2908
- total,
2909
- progress: Math.min(loaded / total, 1)
2910
- };
2911
- }
2912
3013
  //#endregion
2913
3014
  //#region src/plugins/loggerPlugin.ts
2914
3015
  function loggerPlugin(defaultOptions = {}) {
package/dist/index.d.cts CHANGED
@@ -222,23 +222,36 @@ interface RequestLogger {
222
222
  error(message: string, entry: ErrorLogEntry): void | Promise<void>;
223
223
  }
224
224
  type UploadData = FormData | Record<string, unknown>;
225
- /**
226
- * Upload progress information.
227
- */
228
- interface UploadProgress {
225
+ interface TransferProgress {
229
226
  /**
230
- * Number of bytes sent.
227
+ * Cumulative number of bytes transferred.
231
228
  */
232
229
  loaded: number;
233
230
  /**
234
- * Total request size when the browser provides it.
231
+ * Total transfer size when the runtime provides it.
235
232
  */
236
233
  total?: number;
237
234
  /**
238
235
  * Progress ratio between 0 and 1 when total is available.
239
236
  */
240
237
  progress?: number;
238
+ /**
239
+ * Bytes transferred since the previous progress event.
240
+ */
241
+ bytes?: number;
242
+ /**
243
+ * Average transfer rate in bytes per second when measurable.
244
+ */
245
+ rate?: number;
246
+ /**
247
+ * Estimated remaining seconds when total and rate are available.
248
+ */
249
+ estimated?: number;
241
250
  }
251
+ /**
252
+ * Upload progress information.
253
+ */
254
+ interface UploadProgress extends TransferProgress {}
242
255
  interface UploadOptions {
243
256
  data: UploadData;
244
257
  /**
@@ -249,21 +262,18 @@ interface UploadOptions {
249
262
  /**
250
263
  * Download progress information.
251
264
  */
252
- interface DownloadProgress {
253
- /**
254
- * Number of bytes received.
255
- */
256
- loaded: number;
257
- /**
258
- * Total response size when Content-Length is available.
259
- */
260
- total?: number;
265
+ interface DownloadProgress extends TransferProgress {}
266
+ type DownloadOutput = 'blob' | 'stream';
267
+ interface DownloadOptions {
261
268
  /**
262
- * Progress ratio between 0 and 1 when total is available.
269
+ * Returned download representation.
270
+ *
271
+ * `stream` requires Fetch response-stream support and preserves backpressure
272
+ * without buffering the complete response in memory.
273
+ *
274
+ * @default 'blob'
263
275
  */
264
- progress?: number;
265
- }
266
- interface DownloadOptions {
276
+ output?: DownloadOutput;
267
277
  /**
268
278
  * Reserved legacy field. It does not save or rename the returned Blob.
269
279
  *
@@ -1007,4 +1017,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
1007
1017
  //#region src/plugins/uploadPlugin.d.ts
1008
1018
  declare function uploadPlugin(): Plugin;
1009
1019
  //#endregion
1010
- export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, CacheEntry, CacheOptions, CachePlugin, CachePluginOptions, CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, MemoryCacheStore, MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, SchemaValidationError, ServerSentEvent, StandardSchemaV1, UploadData, UploadOptions, UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
1020
+ export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, CacheEntry, CacheOptions, CachePlugin, CachePluginOptions, CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadOutput, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, MemoryCacheStore, MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, SchemaValidationError, ServerSentEvent, StandardSchemaV1, TransferProgress, UploadData, UploadOptions, UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
package/dist/index.d.ts CHANGED
@@ -222,23 +222,36 @@ interface RequestLogger {
222
222
  error(message: string, entry: ErrorLogEntry): void | Promise<void>;
223
223
  }
224
224
  type UploadData = FormData | Record<string, unknown>;
225
- /**
226
- * Upload progress information.
227
- */
228
- interface UploadProgress {
225
+ interface TransferProgress {
229
226
  /**
230
- * Number of bytes sent.
227
+ * Cumulative number of bytes transferred.
231
228
  */
232
229
  loaded: number;
233
230
  /**
234
- * Total request size when the browser provides it.
231
+ * Total transfer size when the runtime provides it.
235
232
  */
236
233
  total?: number;
237
234
  /**
238
235
  * Progress ratio between 0 and 1 when total is available.
239
236
  */
240
237
  progress?: number;
238
+ /**
239
+ * Bytes transferred since the previous progress event.
240
+ */
241
+ bytes?: number;
242
+ /**
243
+ * Average transfer rate in bytes per second when measurable.
244
+ */
245
+ rate?: number;
246
+ /**
247
+ * Estimated remaining seconds when total and rate are available.
248
+ */
249
+ estimated?: number;
241
250
  }
251
+ /**
252
+ * Upload progress information.
253
+ */
254
+ interface UploadProgress extends TransferProgress {}
242
255
  interface UploadOptions {
243
256
  data: UploadData;
244
257
  /**
@@ -249,21 +262,18 @@ interface UploadOptions {
249
262
  /**
250
263
  * Download progress information.
251
264
  */
252
- interface DownloadProgress {
253
- /**
254
- * Number of bytes received.
255
- */
256
- loaded: number;
257
- /**
258
- * Total response size when Content-Length is available.
259
- */
260
- total?: number;
265
+ interface DownloadProgress extends TransferProgress {}
266
+ type DownloadOutput = 'blob' | 'stream';
267
+ interface DownloadOptions {
261
268
  /**
262
- * Progress ratio between 0 and 1 when total is available.
269
+ * Returned download representation.
270
+ *
271
+ * `stream` requires Fetch response-stream support and preserves backpressure
272
+ * without buffering the complete response in memory.
273
+ *
274
+ * @default 'blob'
263
275
  */
264
- progress?: number;
265
- }
266
- interface DownloadOptions {
276
+ output?: DownloadOutput;
267
277
  /**
268
278
  * Reserved legacy field. It does not save or rename the returned Blob.
269
279
  *
@@ -1007,4 +1017,4 @@ declare function retryPlugin(defaultOptions?: RetryOptions): Plugin;
1007
1017
  //#region src/plugins/uploadPlugin.d.ts
1008
1018
  declare function uploadPlugin(): Plugin;
1009
1019
  //#endregion
1010
- export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, CacheEntry, CacheOptions, CachePlugin, CachePluginOptions, CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, MemoryCacheStore, MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, SchemaValidationError, ServerSentEvent, StandardSchemaV1, UploadData, UploadOptions, UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
1020
+ export { Adapter, AuthOptions, AuthPluginOptions, AuthTokenStorage, CacheEntry, CacheOptions, CachePlugin, CachePluginOptions, CacheStore, CircuitBreakerOptions, CircuitBreakerPlugin, CircuitBreakerPluginOptions, CircuitBreakerStateChange, CircuitState, Client, ClientOptions, ConcurrencyOptions, ConcurrencyPlugin, ConcurrencyPluginOptions, ConcurrencyState, DownloadOptions, DownloadOutput, DownloadPluginOptions, DownloadProgress, DownloadTransport, ErrorLogEntry, FetchAdapter, FetchOptions, HttpMethod, Interceptor, InterceptorManager, InterceptorOptions, LoggerEntry, LoggerOptions, MemoryCacheStore, MemoryCacheStoreOptions, MockAdapter, MockAdapterOptions, MockHandler, MockReply, MockReplyHandler, MockRequestMatcher, MockResponseOptions, MockRoute, MockURLMatcher, NporaResponse, Plugin, PluginCleanup, PluginContext, PluginError, PluginErrorCode, PluginErrorOptions, PluginHookManager, PluginInterceptorManager, QueryParams, QueryValue, RequestConfig, RequestError, RequestErrorCode, RequestErrorOptions, RequestExtensions, RequestLogEntry, RequestLogger, ResponseLogEntry, ResponseType, RetryEvent, RetryOptions, SchemaValidationError, ServerSentEvent, StandardSchemaV1, TransferProgress, UploadData, UploadOptions, UploadProgress, authPlugin, cachePlugin, circuitBreakerPlugin, concurrencyPlugin, createClient, downloadPlugin, loggerPlugin, retryPlugin, uploadPlugin };
package/dist/index.js CHANGED
@@ -2622,6 +2622,30 @@ function createRemovedError(config) {
2622
2622
  });
2623
2623
  }
2624
2624
  //#endregion
2625
+ //#region src/plugins/transferProgress.ts
2626
+ const MIN_RATE_SAMPLE_MILLISECONDS = 250;
2627
+ function createTransferProgressTracker(now = Date.now) {
2628
+ const startedAt = now();
2629
+ let previousLoaded = 0;
2630
+ return (loaded, total) => {
2631
+ const bytes = Math.max(loaded - previousLoaded, 0);
2632
+ const elapsed = Math.max(now() - startedAt, 0) / 1e3;
2633
+ const rate = elapsed >= MIN_RATE_SAMPLE_MILLISECONDS / 1e3 && loaded > 0 ? loaded / elapsed : void 0;
2634
+ const progress = total === void 0 || total === 0 ? void 0 : Math.min(loaded / total, 1);
2635
+ const estimated = rate && total !== void 0 ? Math.max(total - loaded, 0) / rate : void 0;
2636
+ previousLoaded = loaded;
2637
+ const snapshot = {
2638
+ loaded,
2639
+ total,
2640
+ bytes
2641
+ };
2642
+ if (progress !== void 0) snapshot.progress = progress;
2643
+ if (rate !== void 0) snapshot.rate = rate;
2644
+ if (estimated !== void 0) snapshot.estimated = estimated;
2645
+ return snapshot;
2646
+ };
2647
+ }
2648
+ //#endregion
2625
2649
  //#region src/plugins/xhrTransport.ts
2626
2650
  function xhrRequest(config, options = {}) {
2627
2651
  let request;
@@ -2741,6 +2765,7 @@ async function processResponse(xhr, config) {
2741
2765
  }
2742
2766
  function createProgressHandler(callback, abortWith, maxResponseSize, config) {
2743
2767
  if (!callback && !Number.isFinite(maxResponseSize)) return null;
2768
+ const trackProgress = callback ? createTransferProgressTracker() : void 0;
2744
2769
  return (event) => {
2745
2770
  if (Number.isFinite(maxResponseSize) && event.loaded > (maxResponseSize ?? Number.POSITIVE_INFINITY)) {
2746
2771
  abortWith(new RequestError(`Response body exceeds maxResponseSize ${maxResponseSize}`, {
@@ -2749,25 +2774,14 @@ function createProgressHandler(callback, abortWith, maxResponseSize, config) {
2749
2774
  }));
2750
2775
  return;
2751
2776
  }
2752
- if (!callback) return;
2777
+ if (!callback || !trackProgress) return;
2753
2778
  try {
2754
- callback(createProgress$1(event.loaded, event.lengthComputable ? event.total : void 0));
2779
+ callback(trackProgress(event.loaded, event.lengthComputable ? event.total : void 0));
2755
2780
  } catch (error) {
2756
2781
  abortWith(error);
2757
2782
  }
2758
2783
  };
2759
2784
  }
2760
- function createProgress$1(loaded, total) {
2761
- if (total === void 0 || total === 0) return {
2762
- loaded,
2763
- total
2764
- };
2765
- return {
2766
- loaded,
2767
- total,
2768
- progress: Math.min(loaded / total, 1)
2769
- };
2770
- }
2771
2785
  function parseHeaders(value) {
2772
2786
  const headers = new Headers();
2773
2787
  for (const line of value.split(/\r?\n/)) {
@@ -2811,6 +2825,13 @@ function downloadPlugin(options = {}) {
2811
2825
  context.interceptors.request.use((config) => {
2812
2826
  const download = resolveExtensionConfig(config, "download");
2813
2827
  if (!download) return config;
2828
+ if (resolveDownloadOutput(download.output, config) === "stream") {
2829
+ validateStreamOutput(options.transport, config);
2830
+ return {
2831
+ ...config,
2832
+ responseType: "stream"
2833
+ };
2834
+ }
2814
2835
  const responseType = download.onProgress && !shouldUseXHR(options.transport) ? "stream" : config.responseType ?? "blob";
2815
2836
  return {
2816
2837
  ...config,
@@ -2819,8 +2840,9 @@ function downloadPlugin(options = {}) {
2819
2840
  });
2820
2841
  context.hooks.onTransport(async (requestContext) => {
2821
2842
  if (requestContext.response) return;
2822
- const onProgress = resolveExtensionConfig(requestContext.config, "download")?.onProgress;
2823
- if (!onProgress || !shouldUseXHR(options.transport)) return;
2843
+ const download = resolveExtensionConfig(requestContext.config, "download");
2844
+ const onProgress = download?.onProgress;
2845
+ if (download?.output === "stream" || !onProgress || !shouldUseXHR(options.transport)) return;
2824
2846
  if (typeof XMLHttpRequest === "undefined") throw new RequestError("XMLHttpRequest is unavailable for download progress", {
2825
2847
  code: "CONFIG_ERROR",
2826
2848
  config: requestContext.config
@@ -2834,13 +2856,19 @@ function downloadPlugin(options = {}) {
2834
2856
  if (!response) return;
2835
2857
  const download = resolveExtensionConfig(response.config, "download");
2836
2858
  const onProgress = download?.onProgress;
2837
- if (!download || !onProgress) return;
2838
- const stream = response.data;
2839
- if (typeof ReadableStream === "undefined" || !(stream instanceof ReadableStream)) throw new RequestError("Download response stream is unavailable", {
2840
- code: "PARSER_ERROR",
2841
- status: response.status,
2842
- config: response.config
2843
- });
2859
+ if (!download) return;
2860
+ let stream = response.data;
2861
+ if (download.output === "stream") {
2862
+ if (stream === void 0 && isBodylessResponse(response)) stream = createEmptyDownloadStream();
2863
+ if (!isReadableStream$1(stream)) throw unavailableDownloadStream(response);
2864
+ if (onProgress) requestContext.response = {
2865
+ ...response,
2866
+ data: monitorDownloadStream(stream, response, onProgress)
2867
+ };
2868
+ return;
2869
+ }
2870
+ if (!onProgress) return;
2871
+ if (!isReadableStream$1(stream)) throw unavailableDownloadStream(response);
2844
2872
  const blob = await consumeDownloadStream(stream, response, onProgress);
2845
2873
  requestContext.response = {
2846
2874
  ...response,
@@ -2850,6 +2878,42 @@ function downloadPlugin(options = {}) {
2850
2878
  }
2851
2879
  };
2852
2880
  }
2881
+ function isBodylessResponse(response) {
2882
+ return response.config.method === "HEAD" || response.status === 204 || response.status === 205 || response.status === 304;
2883
+ }
2884
+ function createEmptyDownloadStream() {
2885
+ return new ReadableStream({ start(controller) {
2886
+ controller.close();
2887
+ } });
2888
+ }
2889
+ function resolveDownloadOutput(output, config) {
2890
+ if (output === void 0 || output === "blob") return "blob";
2891
+ if (output === "stream") return output;
2892
+ throw new RequestError("Download output must be \"blob\" or \"stream\"", {
2893
+ code: "CONFIG_ERROR",
2894
+ config
2895
+ });
2896
+ }
2897
+ function validateStreamOutput(transport, config) {
2898
+ if (transport === "xhr") throw new RequestError("Stream downloads require the Fetch transport", {
2899
+ code: "CONFIG_ERROR",
2900
+ config
2901
+ });
2902
+ if (!supportsFetchResponseStream()) throw new RequestError("Fetch response streams are unavailable", {
2903
+ code: "CONFIG_ERROR",
2904
+ config
2905
+ });
2906
+ }
2907
+ function unavailableDownloadStream(response) {
2908
+ return new RequestError("Download response stream is unavailable", {
2909
+ code: "PARSER_ERROR",
2910
+ status: response.status,
2911
+ config: response.config
2912
+ });
2913
+ }
2914
+ function isReadableStream$1(value) {
2915
+ return typeof value === "object" && value !== null && typeof value.getReader === "function";
2916
+ }
2853
2917
  function shouldUseXHR(transport = "auto") {
2854
2918
  if (transport === "xhr") return true;
2855
2919
  if (transport === "fetch") return false;
@@ -2862,7 +2926,9 @@ async function consumeDownloadStream(stream, response, onProgress) {
2862
2926
  const reader = stream.getReader();
2863
2927
  const chunks = [];
2864
2928
  const total = parseContentLength(response.headers.get("content-length"));
2929
+ const trackProgress = createTransferProgressTracker();
2865
2930
  let loaded = 0;
2931
+ let reported = false;
2866
2932
  try {
2867
2933
  while (true) {
2868
2934
  const result = await reader.read();
@@ -2870,8 +2936,10 @@ async function consumeDownloadStream(stream, response, onProgress) {
2870
2936
  const chunk = result.value;
2871
2937
  chunks.push(toDownloadBuffer(chunk));
2872
2938
  loaded += chunk.byteLength;
2873
- onProgress(createProgress(loaded, total));
2939
+ reported = true;
2940
+ onProgress(trackProgress(loaded, total));
2874
2941
  }
2942
+ if (!reported) onProgress(trackProgress(0, total));
2875
2943
  } catch (error) {
2876
2944
  try {
2877
2945
  await reader.cancel(error);
@@ -2882,6 +2950,50 @@ async function consumeDownloadStream(stream, response, onProgress) {
2882
2950
  }
2883
2951
  return new Blob(chunks, { type: response.headers.get("content-type") ?? "" });
2884
2952
  }
2953
+ function monitorDownloadStream(stream, response, onProgress) {
2954
+ const reader = stream.getReader();
2955
+ const total = parseContentLength(response.headers.get("content-length"));
2956
+ const trackProgress = createTransferProgressTracker();
2957
+ let loaded = 0;
2958
+ let reported = false;
2959
+ let released = false;
2960
+ const release = () => {
2961
+ if (!released) {
2962
+ released = true;
2963
+ reader.releaseLock();
2964
+ }
2965
+ };
2966
+ return new ReadableStream({
2967
+ async pull(controller) {
2968
+ try {
2969
+ const result = await reader.read();
2970
+ if (result.done) {
2971
+ if (!reported) onProgress(trackProgress(0, total));
2972
+ release();
2973
+ controller.close();
2974
+ return;
2975
+ }
2976
+ loaded += result.value.byteLength;
2977
+ reported = true;
2978
+ onProgress(trackProgress(loaded, total));
2979
+ controller.enqueue(result.value);
2980
+ } catch (error) {
2981
+ try {
2982
+ await reader.cancel(error);
2983
+ } catch {}
2984
+ release();
2985
+ controller.error(error);
2986
+ }
2987
+ },
2988
+ async cancel(reason) {
2989
+ try {
2990
+ await reader.cancel(reason);
2991
+ } finally {
2992
+ release();
2993
+ }
2994
+ }
2995
+ }, { highWaterMark: 0 });
2996
+ }
2885
2997
  function toDownloadBuffer(chunk) {
2886
2998
  if (chunk.buffer instanceof ArrayBuffer) {
2887
2999
  if (chunk.byteOffset === 0 && chunk.byteLength === chunk.buffer.byteLength) return chunk.buffer;
@@ -2897,17 +3009,6 @@ function parseContentLength(value) {
2897
3009
  if (!Number.isFinite(total) || total < 0) return;
2898
3010
  return total;
2899
3011
  }
2900
- function createProgress(loaded, total) {
2901
- if (total === void 0 || total === 0) return {
2902
- loaded,
2903
- total
2904
- };
2905
- return {
2906
- loaded,
2907
- total,
2908
- progress: Math.min(loaded / total, 1)
2909
- };
2910
- }
2911
3012
  //#endregion
2912
3013
  //#region src/plugins/loggerPlugin.ts
2913
3014
  function loggerPlugin(defaultOptions = {}) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@npora/request",
3
- "version": "1.12.0",
3
+ "version": "1.14.0",
4
4
  "description": "A modern, TypeScript-first HTTP client powered by the Fetch API.",
5
5
  "keywords": [
6
6
  "npora",