@npora/request 1.13.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
@@ -2826,6 +2826,13 @@ function downloadPlugin(options = {}) {
2826
2826
  context.interceptors.request.use((config) => {
2827
2827
  const download = resolveExtensionConfig(config, "download");
2828
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
+ }
2829
2836
  const responseType = download.onProgress && !shouldUseXHR(options.transport) ? "stream" : config.responseType ?? "blob";
2830
2837
  return {
2831
2838
  ...config,
@@ -2834,8 +2841,9 @@ function downloadPlugin(options = {}) {
2834
2841
  });
2835
2842
  context.hooks.onTransport(async (requestContext) => {
2836
2843
  if (requestContext.response) return;
2837
- const onProgress = resolveExtensionConfig(requestContext.config, "download")?.onProgress;
2838
- 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;
2839
2847
  if (typeof XMLHttpRequest === "undefined") throw new RequestError("XMLHttpRequest is unavailable for download progress", {
2840
2848
  code: "CONFIG_ERROR",
2841
2849
  config: requestContext.config
@@ -2849,13 +2857,19 @@ function downloadPlugin(options = {}) {
2849
2857
  if (!response) return;
2850
2858
  const download = resolveExtensionConfig(response.config, "download");
2851
2859
  const onProgress = download?.onProgress;
2852
- if (!download || !onProgress) return;
2853
- const stream = response.data;
2854
- if (typeof ReadableStream === "undefined" || !(stream instanceof ReadableStream)) throw new RequestError("Download response stream is unavailable", {
2855
- code: "PARSER_ERROR",
2856
- status: response.status,
2857
- config: response.config
2858
- });
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);
2859
2873
  const blob = await consumeDownloadStream(stream, response, onProgress);
2860
2874
  requestContext.response = {
2861
2875
  ...response,
@@ -2865,6 +2879,42 @@ function downloadPlugin(options = {}) {
2865
2879
  }
2866
2880
  };
2867
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
+ }
2868
2918
  function shouldUseXHR(transport = "auto") {
2869
2919
  if (transport === "xhr") return true;
2870
2920
  if (transport === "fetch") return false;
@@ -2901,6 +2951,50 @@ async function consumeDownloadStream(stream, response, onProgress) {
2901
2951
  }
2902
2952
  return new Blob(chunks, { type: response.headers.get("content-type") ?? "" });
2903
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
+ }
2904
2998
  function toDownloadBuffer(chunk) {
2905
2999
  if (chunk.buffer instanceof ArrayBuffer) {
2906
3000
  if (chunk.byteOffset === 0 && chunk.byteLength === chunk.buffer.byteLength) return chunk.buffer;
package/dist/index.d.cts CHANGED
@@ -263,7 +263,17 @@ interface UploadOptions {
263
263
  * Download progress information.
264
264
  */
265
265
  interface DownloadProgress extends TransferProgress {}
266
+ type DownloadOutput = 'blob' | 'stream';
266
267
  interface DownloadOptions {
268
+ /**
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'
275
+ */
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, TransferProgress, 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
@@ -263,7 +263,17 @@ interface UploadOptions {
263
263
  * Download progress information.
264
264
  */
265
265
  interface DownloadProgress extends TransferProgress {}
266
+ type DownloadOutput = 'blob' | 'stream';
266
267
  interface DownloadOptions {
268
+ /**
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'
275
+ */
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, TransferProgress, 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
@@ -2825,6 +2825,13 @@ function downloadPlugin(options = {}) {
2825
2825
  context.interceptors.request.use((config) => {
2826
2826
  const download = resolveExtensionConfig(config, "download");
2827
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
+ }
2828
2835
  const responseType = download.onProgress && !shouldUseXHR(options.transport) ? "stream" : config.responseType ?? "blob";
2829
2836
  return {
2830
2837
  ...config,
@@ -2833,8 +2840,9 @@ function downloadPlugin(options = {}) {
2833
2840
  });
2834
2841
  context.hooks.onTransport(async (requestContext) => {
2835
2842
  if (requestContext.response) return;
2836
- const onProgress = resolveExtensionConfig(requestContext.config, "download")?.onProgress;
2837
- 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;
2838
2846
  if (typeof XMLHttpRequest === "undefined") throw new RequestError("XMLHttpRequest is unavailable for download progress", {
2839
2847
  code: "CONFIG_ERROR",
2840
2848
  config: requestContext.config
@@ -2848,13 +2856,19 @@ function downloadPlugin(options = {}) {
2848
2856
  if (!response) return;
2849
2857
  const download = resolveExtensionConfig(response.config, "download");
2850
2858
  const onProgress = download?.onProgress;
2851
- if (!download || !onProgress) return;
2852
- const stream = response.data;
2853
- if (typeof ReadableStream === "undefined" || !(stream instanceof ReadableStream)) throw new RequestError("Download response stream is unavailable", {
2854
- code: "PARSER_ERROR",
2855
- status: response.status,
2856
- config: response.config
2857
- });
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);
2858
2872
  const blob = await consumeDownloadStream(stream, response, onProgress);
2859
2873
  requestContext.response = {
2860
2874
  ...response,
@@ -2864,6 +2878,42 @@ function downloadPlugin(options = {}) {
2864
2878
  }
2865
2879
  };
2866
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
+ }
2867
2917
  function shouldUseXHR(transport = "auto") {
2868
2918
  if (transport === "xhr") return true;
2869
2919
  if (transport === "fetch") return false;
@@ -2900,6 +2950,50 @@ async function consumeDownloadStream(stream, response, onProgress) {
2900
2950
  }
2901
2951
  return new Blob(chunks, { type: response.headers.get("content-type") ?? "" });
2902
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
+ }
2903
2997
  function toDownloadBuffer(chunk) {
2904
2998
  if (chunk.buffer instanceof ArrayBuffer) {
2905
2999
  if (chunk.byteOffset === 0 && chunk.byteLength === chunk.buffer.byteLength) return chunk.buffer;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@npora/request",
3
- "version": "1.13.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",