apify-client 3.0.0-rc.1 → 3.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/README.md +4 -2
  2. package/dist/apify_api_error.d.ts +2 -2
  3. package/dist/apify_client.d.ts +8 -8
  4. package/dist/apify_client.js +10 -10
  5. package/dist/axios.d.ts +2 -0
  6. package/dist/axios.js +1 -0
  7. package/dist/body_parser.d.ts +1 -1
  8. package/dist/bundle.js +31 -30
  9. package/dist/bundle.js.map +1 -1
  10. package/dist/generated/api.d.ts +124 -32
  11. package/dist/generated/schemas.d.ts +178 -58
  12. package/dist/generated/schemas.js +23 -6
  13. package/dist/http_clients/axios.d.ts +34 -15
  14. package/dist/http_clients/axios.js +79 -33
  15. package/dist/http_clients/base.d.ts +34 -23
  16. package/dist/http_clients/base.js +50 -20
  17. package/dist/http_clients/fetch.d.ts +53 -0
  18. package/dist/http_clients/fetch.js +219 -0
  19. package/dist/http_clients/index.d.ts +2 -2
  20. package/dist/http_clients/index.js +1 -1
  21. package/dist/index.d.ts +1 -1
  22. package/dist/resource_clients/actor.d.ts +3 -2
  23. package/dist/resource_clients/actor.js +3 -3
  24. package/dist/resource_clients/actor_server.d.ts +11 -11
  25. package/dist/resource_clients/actor_server.js +0 -4
  26. package/dist/resource_clients/actor_version.d.ts +2 -1
  27. package/dist/resource_clients/actor_version.js +3 -2
  28. package/dist/resource_clients/actor_version_collection.d.ts +2 -1
  29. package/dist/resource_clients/actor_version_collection.js +3 -2
  30. package/dist/resource_clients/dataset.d.ts +14 -15
  31. package/dist/resource_clients/dataset.js +0 -4
  32. package/dist/resource_clients/key_value_store.d.ts +20 -19
  33. package/dist/resource_clients/key_value_store.js +10 -11
  34. package/dist/resource_clients/log.d.ts +10 -11
  35. package/dist/resource_clients/log.js +4 -3
  36. package/dist/resource_clients/run.d.ts +6 -2
  37. package/dist/resource_clients/run.js +6 -2
  38. package/dist/resource_clients/store_collection.d.ts +4 -0
  39. package/dist/resource_clients/task.js +3 -3
  40. package/dist/runtime/node.js +35 -11
  41. package/dist/runtime/types.d.ts +26 -4
  42. package/dist/runtime/web.js +39 -0
  43. package/dist/schemas.d.ts +4 -4
  44. package/dist/utils.d.ts +29 -1
  45. package/dist/utils.js +13 -0
  46. package/package.json +33 -21
@@ -15,25 +15,41 @@ export type RequestInterceptorFunction = Parameters<AxiosInterceptorManager<Inte
15
15
  export interface AxiosHttpClientOptions extends HttpClientOptions {
16
16
  /** @default [] */
17
17
  requestInterceptors?: RequestInterceptorFunction[];
18
+ /**
19
+ * Agent for plain HTTP requests in Node.js, in place of the built-in keep-alive one. A proxy agent goes here
20
+ * and in {@link httpsAgent}. The client does not destroy an agent it was given.
21
+ */
22
+ httpAgent?: http.Agent;
23
+ /** Agent for HTTPS requests in Node.js, in place of the built-in keep-alive one. Requests to the Apify API use it. */
24
+ httpsAgent?: https.Agent;
18
25
  }
19
26
  /**
20
- * The default HTTP client of {@link ApifyClient}, built on [axios](https://axios-http.com).
27
+ * An HTTP client for {@link ApifyClient} built on [axios](https://axios-http.com), which was the transport of the
28
+ * client before version 3. It is exported from `apify-client/axios` and needs the `axios` package installed
29
+ * next to the client.
21
30
  *
22
- * It inherits the request pipeline from {@link HttpClient} and adds the transport: in Node.js, keep-alive agents
23
- * that honor the `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` environment variables; in the browser, the XHR
24
- * adapter of axios. Network errors are retried, timeouts included, and a stream body is sent without following
25
- * redirects, since the part of it already sent could not be replayed.
31
+ * It inherits the request pipeline from {@link HttpClient} and adds the transport: in Node.js, keep-alive agents;
32
+ * in the browser, the XHR adapter of axios, or its fetch adapter for a request that must not follow redirects or
33
+ * that asks for a streamed response.
34
+ * Network errors are retried, timeouts included, and a stream body is sent without following redirects, since the
35
+ * part of it already sent could not be replayed. The proxy environment variables are not read: pass a proxy agent
36
+ * in {@link AxiosHttpClientOptions.httpAgent} and {@link AxiosHttpClientOptions.httpsAgent} instead.
37
+ *
38
+ * @example
39
+ * ```javascript
40
+ * import { ApifyClient } from 'apify-client';
41
+ * import { AxiosHttpClient } from 'apify-client/axios';
42
+ *
43
+ * const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new AxiosHttpClient() });
44
+ * ```
26
45
  */
27
46
  export declare class AxiosHttpClient extends HttpClient {
28
47
  #private;
29
48
  /** The axios instance the requests go through. */
30
49
  axios: AxiosInstance;
31
- /**
32
- * Keep-alive agent for plain HTTP, created with the first request in Node.js. It is the same `ProxyAgent` as
33
- * {@link httpsAgent}, so the socket pool is shared across both schemes.
34
- */
50
+ /** Agent for plain HTTP: the one from the options, or a keep-alive one created with the first request in Node.js. */
35
51
  httpAgent?: http.Agent;
36
- /** Keep-alive agent for HTTPS. The same instance as {@link httpAgent}. */
52
+ /** Agent for HTTPS: the one from the options, or a keep-alive one created with the first request in Node.js. */
37
53
  httpsAgent?: https.Agent;
38
54
  constructor(options?: AxiosHttpClientOptions);
39
55
  /**
@@ -43,19 +59,22 @@ export declare class AxiosHttpClient extends HttpClient {
43
59
  isTimeoutError(error: unknown): boolean;
44
60
  /**
45
61
  * A network failure is an axios error that carries the request it was sending: a connection that could not be
46
- * made, dropped mid-way or timed out. Errors raised before a request exists, such as an invalid URL, are not
47
- * retried.
62
+ * made, dropped mid-way or timed out, or the `TimeoutError` this client ends a late streamed response outside
63
+ * Node.js with. Errors raised before a request exists, such as an invalid URL, are not retried.
48
64
  */
49
65
  isRetryableTransportError(error: unknown): boolean;
50
66
  /**
51
- * Destroys the keep-alive agents, closing every pooled socket. A client that never sent a request in Node.js
52
- * has nothing to close.
67
+ * Destroys the built-in keep-alive agents, closing every pooled socket. A client that never sent a request in
68
+ * Node.js has nothing to close, and agents passed in the options are left to their owner.
53
69
  */
54
70
  close(): Promise<void>;
55
71
  /**
56
72
  * Sends the request through axios and hands the raw response back. A stream body is sent without following
57
73
  * redirects, since the part of it already sent could not be replayed, and so is a request with
58
- * `followRedirects: false`. In the browser, the browser follows redirects itself.
74
+ * `followRedirects: false`. Outside Node.js, such a request goes through `fetch`, since the browser follows the
75
+ * redirects of an XHR itself, and a redirect response fails the request: `fetch` hides it from the page. A
76
+ * request for a streamed response goes through `fetch` there too, since an XHR cannot stream one, and its
77
+ * timeout covers the wait for the headers only.
59
78
  */
60
79
  sendRequest(request: HttpRequest): Promise<HttpResponse>;
61
80
  }
@@ -1,30 +1,42 @@
1
1
  import axios, { AxiosError, AxiosHeaders } from 'axios';
2
2
  import { runtime } from '#runtime';
3
- import { isStream } from '../utils.js';
3
+ import { ApifyClientError } from '../apify_client_error.js';
4
+ import { isAnyStream, isWebStream } from '../utils.js';
4
5
  import { HttpClient } from './base.js';
5
6
  /**
6
- * The default HTTP client of {@link ApifyClient}, built on [axios](https://axios-http.com).
7
+ * An HTTP client for {@link ApifyClient} built on [axios](https://axios-http.com), which was the transport of the
8
+ * client before version 3. It is exported from `apify-client/axios` and needs the `axios` package installed
9
+ * next to the client.
7
10
  *
8
- * It inherits the request pipeline from {@link HttpClient} and adds the transport: in Node.js, keep-alive agents
9
- * that honor the `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` environment variables; in the browser, the XHR
10
- * adapter of axios. Network errors are retried, timeouts included, and a stream body is sent without following
11
- * redirects, since the part of it already sent could not be replayed.
11
+ * It inherits the request pipeline from {@link HttpClient} and adds the transport: in Node.js, keep-alive agents;
12
+ * in the browser, the XHR adapter of axios, or its fetch adapter for a request that must not follow redirects or
13
+ * that asks for a streamed response.
14
+ * Network errors are retried, timeouts included, and a stream body is sent without following redirects, since the
15
+ * part of it already sent could not be replayed. The proxy environment variables are not read: pass a proxy agent
16
+ * in {@link AxiosHttpClientOptions.httpAgent} and {@link AxiosHttpClientOptions.httpsAgent} instead.
17
+ *
18
+ * @example
19
+ * ```javascript
20
+ * import { ApifyClient } from 'apify-client';
21
+ * import { AxiosHttpClient } from 'apify-client/axios';
22
+ *
23
+ * const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new AxiosHttpClient() });
24
+ * ```
12
25
  */
13
26
  export class AxiosHttpClient extends HttpClient {
14
27
  /** The axios instance the requests go through. */
15
28
  axios;
16
- /**
17
- * Keep-alive agent for plain HTTP, created with the first request in Node.js. It is the same `ProxyAgent` as
18
- * {@link httpsAgent}, so the socket pool is shared across both schemes.
19
- */
29
+ /** Agent for plain HTTP: the one from the options, or a keep-alive one created with the first request in Node.js. */
20
30
  httpAgent;
21
- /** Keep-alive agent for HTTPS. The same instance as {@link httpAgent}. */
31
+ /** Agent for HTTPS: the one from the options, or a keep-alive one created with the first request in Node.js. */
22
32
  httpsAgent;
33
+ /** The built-in agents, which are the ones `close()` destroys. */
34
+ #ownAgents = [];
23
35
  #httpAgentsPromise;
24
36
  constructor(options = {}) {
25
37
  super(options);
26
38
  this.axios = axios.create({
27
- // The agents handle the proxy environment variables.
39
+ // Axios cannot tunnel HTTPS through a proxy on its own, so a proxy is left to the agents.
28
40
  proxy: false,
29
41
  validateStatus: null,
30
42
  // The shared pipeline serializes and parses the bodies, so axios only moves bytes.
@@ -40,6 +52,8 @@ export class AxiosHttpClient extends HttpClient {
40
52
  });
41
53
  // The pipeline merges every header the client sends, so the axios defaults would only get in the way.
42
54
  this.axios.defaults.headers = new AxiosHeaders();
55
+ this.httpAgent = options.httpAgent;
56
+ this.httpsAgent = options.httpsAgent;
43
57
  for (const interceptor of options.requestInterceptors ?? []) {
44
58
  this.axios.interceptors.request.use(interceptor);
45
59
  }
@@ -58,49 +72,77 @@ export class AxiosHttpClient extends HttpClient {
58
72
  }
59
73
  /**
60
74
  * A network failure is an axios error that carries the request it was sending: a connection that could not be
61
- * made, dropped mid-way or timed out. Errors raised before a request exists, such as an invalid URL, are not
62
- * retried.
75
+ * made, dropped mid-way or timed out, or the `TimeoutError` this client ends a late streamed response outside
76
+ * Node.js with. Errors raised before a request exists, such as an invalid URL, are not retried.
63
77
  */
64
78
  isRetryableTransportError(error) {
79
+ if (super.isTimeoutError(error))
80
+ return true;
65
81
  if (!axios.isAxiosError(error))
66
82
  return false;
67
83
  return typeof error.request === 'object' && error.request !== null && error.config != null;
68
84
  }
69
85
  /**
70
- * Destroys the keep-alive agents, closing every pooled socket. A client that never sent a request in Node.js
71
- * has nothing to close.
86
+ * Destroys the built-in keep-alive agents, closing every pooled socket. A client that never sent a request in
87
+ * Node.js has nothing to close, and agents passed in the options are left to their owner.
72
88
  */
73
89
  async close() {
74
90
  // A failed initialization left nothing to release, and its error belongs to the request that hit it.
75
91
  await this.#httpAgentsPromise?.catch(() => { });
76
- this.httpAgent?.destroy();
77
- this.httpsAgent?.destroy();
92
+ for (const agent of this.#ownAgents.splice(0))
93
+ agent.destroy();
78
94
  }
79
95
  /**
80
96
  * Sends the request through axios and hands the raw response back. A stream body is sent without following
81
97
  * redirects, since the part of it already sent could not be replayed, and so is a request with
82
- * `followRedirects: false`. In the browser, the browser follows redirects itself.
98
+ * `followRedirects: false`. Outside Node.js, such a request goes through `fetch`, since the browser follows the
99
+ * redirects of an XHR itself, and a redirect response fails the request: `fetch` hides it from the page. A
100
+ * request for a streamed response goes through `fetch` there too, since an XHR cannot stream one, and its
101
+ * timeout covers the wait for the headers only.
83
102
  */
84
103
  async sendRequest(request) {
85
104
  await this.#ensureHttpAgents();
86
- const { method, url, headers, body, timeoutMillis, stream, followRedirects, signal } = request;
87
- const response = await this.axios.request({
105
+ const { method, url, headers, timeoutMillis, stream, followRedirects, signal } = request;
106
+ // The Node.js adapter of axios refuses a web stream, and an XHR cannot send one either.
107
+ const body = runtime.isNode && isWebStream(request.body) ? runtime.openStreamBody(request.body) : request.body;
108
+ const useFetch = (!followRedirects || stream || isWebStream(body)) && !runtime.isNode;
109
+ // The fetch adapter keeps the axios timeout running until a streamed response is read to its end.
110
+ const headersTimeout = useFetch && stream && timeoutMillis !== undefined ? new AbortController() : undefined;
111
+ const headersTimer = headersTimeout &&
112
+ setTimeout(() => {
113
+ headersTimeout.abort(new DOMException(`timeout of ${timeoutMillis}ms exceeded`, 'TimeoutError'));
114
+ }, timeoutMillis);
115
+ const signals = [signal, headersTimeout?.signal].filter((item) => item !== undefined);
116
+ const response = await this.axios
117
+ .request({
88
118
  method,
89
119
  url,
90
- headers,
120
+ // The fetch adapter adds a `User-Agent` of its own otherwise, which a browser lists in the CORS preflight.
121
+ headers: useFetch ? { 'User-Agent': null, ...headers } : headers,
91
122
  data: body,
92
123
  // Axios reads 0 as no timeout.
93
- timeout: timeoutMillis ?? 0,
94
- signal,
124
+ timeout: headersTimeout ? 0 : (timeoutMillis ?? 0),
125
+ signal: signals.length > 1 ? AbortSignal.any(signals) : signals[0],
95
126
  responseType: stream ? 'stream' : 'arraybuffer',
96
- // See axios/axios#1045 for why axios must not buffer a stream body to follow redirects. The XHR adapter
97
- // ignores `maxRedirects`, since the browser follows redirects itself.
98
- ...(isStream(body) || !followRedirects ? { maxRedirects: 0 } : {}),
99
- });
127
+ // See axios/axios#1045 for why axios must not buffer a stream body to follow redirects. The fetch
128
+ // adapter turns this into `redirect: 'manual'`.
129
+ ...(isAnyStream(body) || !followRedirects ? { maxRedirects: 0 } : {}),
130
+ ...(useFetch ? { adapter: 'fetch' } : {}),
131
+ })
132
+ .catch((error) => {
133
+ // Axios reports any abort as a cancellation.
134
+ throw headersTimeout?.signal.aborted ? headersTimeout.signal.reason : error;
135
+ })
136
+ .finally(() => clearTimeout(headersTimer));
137
+ // `redirect: 'manual'` resolves to an opaque response with status 0 instead of the redirect.
138
+ if (useFetch && response.status === 0) {
139
+ throw new ApifyClientError(`${method} ${url} responded with a redirect, which the client does not follow.`);
140
+ }
100
141
  return {
101
142
  status: response.status,
102
143
  headers: AxiosHeaders.from(response.headers).toJSON(),
103
- body: response.data,
144
+ // `fetch` has no body stream for a response without a body, such as a 204.
145
+ body: (response.data ?? (stream ? new Blob([]).stream() : undefined)),
104
146
  };
105
147
  }
106
148
  async #ensureHttpAgents() {
@@ -109,11 +151,15 @@ export class AxiosHttpClient extends HttpClient {
109
151
  }
110
152
  async #initHttpAgents() {
111
153
  const agents = await runtime.createHttpAgents({ timeoutMillis: this.timeoutMaxMillis });
112
- if (!agents)
113
- return;
114
- this.httpAgent = agents.httpAgent;
115
- this.httpsAgent = agents.httpsAgent;
154
+ if (agents) {
155
+ this.httpAgent ??= this.#own(agents.httpAgent);
156
+ this.httpsAgent ??= this.#own(agents.httpsAgent);
157
+ }
116
158
  this.axios.defaults.httpAgent = this.httpAgent;
117
159
  this.axios.defaults.httpsAgent = this.httpsAgent;
118
160
  }
161
+ #own(agent) {
162
+ this.#ownAgents.push(agent);
163
+ return agent;
164
+ }
119
165
  }
@@ -29,20 +29,24 @@ export type HttpResponseHeaders = Record<string, string | string[] | undefined>;
29
29
  * A request body as the transport receives it: already serialized, and compressed when that paid off. A `Readable`
30
30
  * is passed through untouched and is only available in Node.js. A `Blob` body reaches a Node.js transport as a
31
31
  * fresh `Readable` over its bytes for every attempt, and a transport in any other runtime as the `Blob` itself.
32
+ * A web `ReadableStream` body reaches a Node.js transport as a `Readable` too, and a transport in any other
33
+ * runtime as the stream itself.
32
34
  */
33
- export type HttpRequestBody = string | Buffer | ArrayBuffer | ArrayBufferView | Readable | Blob;
35
+ export type HttpRequestBody = string | Buffer | ArrayBuffer | ArrayBufferView | Readable | ReadableStream<Uint8Array> | Blob;
34
36
  /**
35
- * A response body as the transport hands it back: the raw bytes, a `Readable` when the request asked for a streamed
36
- * response, or `undefined` when the response carried no body.
37
+ * A response body as the transport hands it back: the raw bytes, a web `ReadableStream` or a `Readable` when the
38
+ * request asked for a streamed response, or `undefined` when the response carried no body. The pipeline hands the bytes
39
+ * on as a `Uint8Array` (a `Buffer` in Node.js) and the stream as a web `ReadableStream`, whichever of the
40
+ * types they arrive in.
37
41
  */
38
- export type HttpResponseBody = Buffer | ArrayBuffer | Readable | undefined;
42
+ export type HttpResponseBody = Uint8Array | ArrayBuffer | Readable | ReadableStream<Uint8Array> | undefined;
39
43
  /**
40
44
  * How {@link HttpClient.call} hands back the response body.
41
45
  *
42
46
  * - `parsed` (the default) decodes it by content type: JSON becomes an object, text and XML become a string, anything
43
- * else stays a `Buffer` (an `ArrayBuffer` in the browser).
44
- * - `buffer` skips the decoding and hands back the raw bytes.
45
- * - `stream` hands back a `Readable` with the body unread. Node.js only.
47
+ * else stays a `Uint8Array`.
48
+ * - `buffer` skips the decoding and hands back the raw bytes as a `Uint8Array`.
49
+ * - `stream` hands back the body unread, as a web `ReadableStream` of `Uint8Array` chunks.
46
50
  */
47
51
  export type ApifyResponseType = 'parsed' | 'buffer' | 'stream';
48
52
  /**
@@ -63,10 +67,11 @@ export interface ApifyRequestConfig {
63
67
  /**
64
68
  * Request body. A plain object or array is serialized to JSON and sent as `application/json`, or form-encoded
65
69
  * when a `Content-Type: application/x-www-form-urlencoded` header asks for it. A string, binary value
66
- * (`Buffer`, `ArrayBuffer`, typed array) or `Readable` is sent as it is, and `URLSearchParams` is sent
67
- * form-encoded. A `Blob` or `File`, such as one from `fs.openAsBlob()`, is streamed without being held in
68
- * memory, under its own `type` when no `Content-Type` header is set. A `FormData` or web `ReadableStream` is
69
- * rejected with a `TypeError`, since serializing one would send an empty body.
70
+ * (`Buffer`, `ArrayBuffer`, typed array) or stream (`Readable`, web `ReadableStream`) is sent as it is, and
71
+ * `URLSearchParams` is sent form-encoded. A `Blob` or `File`, such as one from `fs.openAsBlob()`, is streamed
72
+ * without being held in memory, under its own `type` when no `Content-Type` header is set. A `FormData` is
73
+ * rejected with a `TypeError`, since serializing one would send an empty body, and so is a web `ReadableStream`
74
+ * in a browser that cannot send one.
70
75
  */
71
76
  data?: unknown;
72
77
  /**
@@ -157,7 +162,7 @@ export interface HttpRequest {
157
162
  * `timeoutSecs: 'noTimeout'` asks for.
158
163
  */
159
164
  timeoutMillis?: number;
160
- /** Whether to hand the body back unread as a `Readable`, so the caller can stream it. */
165
+ /** Whether to hand the body back unread as a stream. The caller always gets a web `ReadableStream`. */
161
166
  stream: boolean;
162
167
  /**
163
168
  * Whether to follow redirects. With `false`, return a redirect response as it is: the request carries a token
@@ -178,7 +183,7 @@ export interface HttpResponse {
178
183
  status: number;
179
184
  /** Response headers keyed by lowercase header name. */
180
185
  headers: HttpResponseHeaders;
181
- /** The body as raw bytes, or unread as a `Readable` when the request asked for a stream. */
186
+ /** The body as raw bytes, or unread as a stream: a web `ReadableStream`, or a `Readable` the pipeline converts. */
182
187
  body: HttpResponseBody;
183
188
  }
184
189
  /**
@@ -243,15 +248,21 @@ export interface HttpClientOptions {
243
248
  * ```javascript
244
249
  * import { ApifyClient, HttpClient } from 'apify-client';
245
250
  *
246
- * class FetchHttpClient extends HttpClient {
247
- * async sendRequest({ method, url, headers, body, timeoutMillis, signal }) {
251
+ * class MyFetchHttpClient extends HttpClient {
252
+ * async sendRequest({ method, url, headers, body, timeoutMillis, followRedirects, signal }) {
248
253
  * const signals = signal ? [signal] : [];
249
254
  * if (timeoutMillis !== undefined) signals.push(AbortSignal.timeout(timeoutMillis));
250
- * const response = await fetch(url, { method, headers, body, signal: AbortSignal.any(signals) });
255
+ * const response = await fetch(url, {
256
+ * method,
257
+ * headers,
258
+ * body,
259
+ * redirect: followRedirects ? 'follow' : 'manual',
260
+ * signal: AbortSignal.any(signals),
261
+ * });
251
262
  * return {
252
263
  * status: response.status,
253
264
  * headers: Object.fromEntries(response.headers),
254
- * body: Buffer.from(await response.arrayBuffer()),
265
+ * body: await response.arrayBuffer(),
255
266
  * };
256
267
  * }
257
268
  *
@@ -261,7 +272,7 @@ export interface HttpClientOptions {
261
272
  * }
262
273
  * }
263
274
  *
264
- * const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new FetchHttpClient() });
275
+ * const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new MyFetchHttpClient() });
265
276
  * ```
266
277
  */
267
278
  export declare abstract class HttpClient {
@@ -339,11 +350,11 @@ export declare abstract class HttpClient {
339
350
  * Network errors the transport classifies as retryable, rate limits (HTTP 429) and server errors (HTTP 5xx)
340
351
  * are retried up to {@link maxRetries} times, and `config.retryStatusCodes` picks other statuses to retry. Any
341
352
  * other error status is thrown as {@link ApifyApiError} right away, or returned when `config.throwOnErrorStatus`
342
- * is `false`. A request whose body is a `Readable` is never retried, since part of the stream has already been
343
- * consumed by the time the failure shows. A `Blob` body is read again for every attempt, so it is retried like
344
- * any other, unless reading the blob itself fails: that error is thrown right away, with the transport error
345
- * as its `cause` when that error does not already wrap it. Aborting `config.signal` ends the attempt in flight,
346
- * skips the remaining retries and rejects the call with the signal's `reason`.
353
+ * is `false`. A request whose body is a `Readable` or a web `ReadableStream` is never retried, since part of the
354
+ * stream has already been consumed by the time the failure shows. A `Blob` body is read again for every attempt,
355
+ * so it is retried like any other, unless reading the blob itself fails: that error is thrown right away, with
356
+ * the transport error as its `cause` when that error does not already wrap it. Aborting `config.signal` ends the
357
+ * attempt in flight, skips the remaining retries and rejects the call with the signal's `reason`.
347
358
  *
348
359
  * @template T - Type of the parsed response body.
349
360
  * @param config - The request to make.
@@ -1,7 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { APIFY_ENV_VARS } from '@apify/consts';
3
3
  import log from '@apify/log';
4
- import { concatStreamToBuffer } from '@apify/utilities';
5
4
  import { ApifyApiError } from '../apify_api_error.js';
6
5
  import { maybeParseBody } from '../body_parser.js';
7
6
  import { resolveCompressor } from '../http_compressors/resolve.js';
@@ -9,7 +8,7 @@ import { InvalidResponseBodyError } from '../invalid_response_body_error.js';
9
8
  import { Statistics } from '../statistics.js';
10
9
  import { DEFAULT_TIMEOUT_LONG_SECS, DEFAULT_TIMEOUT_MAX_SECS, DEFAULT_TIMEOUT_MEDIUM_SECS, DEFAULT_TIMEOUT_SHORT_SECS, } from '../timeouts.js';
11
10
  import { runtime } from '#runtime';
12
- import { asArray, getEnv, isBlob, isBuffer, isCompressibleContentType, isStream, MIN_COMPRESS_BYTES, parseArgument, sleep, toBytes, version, } from '../utils.js';
11
+ import { asArray, getEnv, isAnyStream, isBlob, isBuffer, isCompressibleContentType, isStream, isWebStream, MIN_COMPRESS_BYTES, parseArgument, sleep, toBytes, version, } from '../utils.js';
13
12
  export const DEFAULT_MAX_RETRIES = 8;
14
13
  export const DEFAULT_MIN_DELAY_BETWEEN_RETRIES_MILLIS = 500;
15
14
  const RATE_LIMIT_EXCEEDED_STATUS_CODE = 429;
@@ -29,7 +28,7 @@ export const httpClientOptionsShape = {
29
28
  };
30
29
  const httpClientOptionsSchema = z.looseObject(httpClientOptionsShape).partial();
31
30
  /** Objects whose payload does not live in their own enumerable keys, so JSON serialization loses it. */
32
- const UNSERIALIZABLE_OBJECT_TAGS = new Set(['FormData', 'ReadableStream']);
31
+ const UNSERIALIZABLE_OBJECT_TAGS = new Set(['FormData']);
33
32
  /**
34
33
  * Base class for the HTTP clients used by {@link ApifyClient}.
35
34
  *
@@ -54,15 +53,21 @@ const UNSERIALIZABLE_OBJECT_TAGS = new Set(['FormData', 'ReadableStream']);
54
53
  * ```javascript
55
54
  * import { ApifyClient, HttpClient } from 'apify-client';
56
55
  *
57
- * class FetchHttpClient extends HttpClient {
58
- * async sendRequest({ method, url, headers, body, timeoutMillis, signal }) {
56
+ * class MyFetchHttpClient extends HttpClient {
57
+ * async sendRequest({ method, url, headers, body, timeoutMillis, followRedirects, signal }) {
59
58
  * const signals = signal ? [signal] : [];
60
59
  * if (timeoutMillis !== undefined) signals.push(AbortSignal.timeout(timeoutMillis));
61
- * const response = await fetch(url, { method, headers, body, signal: AbortSignal.any(signals) });
60
+ * const response = await fetch(url, {
61
+ * method,
62
+ * headers,
63
+ * body,
64
+ * redirect: followRedirects ? 'follow' : 'manual',
65
+ * signal: AbortSignal.any(signals),
66
+ * });
62
67
  * return {
63
68
  * status: response.status,
64
69
  * headers: Object.fromEntries(response.headers),
65
- * body: Buffer.from(await response.arrayBuffer()),
70
+ * body: await response.arrayBuffer(),
66
71
  * };
67
72
  * }
68
73
  *
@@ -72,7 +77,7 @@ const UNSERIALIZABLE_OBJECT_TAGS = new Set(['FormData', 'ReadableStream']);
72
77
  * }
73
78
  * }
74
79
  *
75
- * const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new FetchHttpClient() });
80
+ * const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new MyFetchHttpClient() });
76
81
  * ```
77
82
  */
78
83
  export class HttpClient {
@@ -190,11 +195,11 @@ export class HttpClient {
190
195
  * Network errors the transport classifies as retryable, rate limits (HTTP 429) and server errors (HTTP 5xx)
191
196
  * are retried up to {@link maxRetries} times, and `config.retryStatusCodes` picks other statuses to retry. Any
192
197
  * other error status is thrown as {@link ApifyApiError} right away, or returned when `config.throwOnErrorStatus`
193
- * is `false`. A request whose body is a `Readable` is never retried, since part of the stream has already been
194
- * consumed by the time the failure shows. A `Blob` body is read again for every attempt, so it is retried like
195
- * any other, unless reading the blob itself fails: that error is thrown right away, with the transport error
196
- * as its `cause` when that error does not already wrap it. Aborting `config.signal` ends the attempt in flight,
197
- * skips the remaining retries and rejects the call with the signal's `reason`.
198
+ * is `false`. A request whose body is a `Readable` or a web `ReadableStream` is never retried, since part of the
199
+ * stream has already been consumed by the time the failure shows. A `Blob` body is read again for every attempt,
200
+ * so it is retried like any other, unless reading the blob itself fails: that error is thrown right away, with
201
+ * the transport error as its `cause` when that error does not already wrap it. Aborting `config.signal` ends the
202
+ * attempt in flight, skips the remaining retries and rejects the call with the signal's `reason`.
198
203
  *
199
204
  * @template T - Type of the parsed response body.
200
205
  * @param config - The request to make.
@@ -207,7 +212,15 @@ export class HttpClient {
207
212
  this.stats.calls++;
208
213
  const { headers, body } = await this.prepareRequest(config);
209
214
  const url = this.buildUrl(config.url, config.params);
210
- return this.#retryWithExpBackoff(async (stopRetrying, attempt) => this.#makeRequest({ config, url, headers, body, attempt, stopRetrying }), config.signal);
215
+ try {
216
+ return await this.#retryWithExpBackoff(async (stopRetrying, attempt) => this.#makeRequest({ config, url, headers, body, attempt, stopRetrying }), config.signal);
217
+ }
218
+ catch (error) {
219
+ // A transport may leave the `Readable` opened over a web stream unread, and the stream locked for good.
220
+ if (isWebStream(config.data) && isStream(body))
221
+ body.destroy();
222
+ throw error;
223
+ }
211
224
  }
212
225
  /**
213
226
  * Prepares the headers and the body of a request.
@@ -321,7 +334,7 @@ export class HttpClient {
321
334
  async #makeRequest(options) {
322
335
  const { config, url, headers, body, attempt, stopRetrying } = options;
323
336
  this.stats.requests++;
324
- const requestIsStream = isStream(config.data);
337
+ const requestIsStream = isAnyStream(config.data);
325
338
  // The transport reports a failure of the blob as an error of its own, which may pass as transient.
326
339
  let sourceFailure;
327
340
  const attemptBody = isBlob(body)
@@ -365,12 +378,17 @@ export class HttpClient {
365
378
  const shouldReturnError = isError &&
366
379
  config.throwOnErrorStatus === false &&
367
380
  (!isRetryable || requestIsStream || attempt > this.maxRetries);
381
+ // Transports return whichever stream and binary type their HTTP library has, and callers get the web ones.
382
+ if (isStream(response.body))
383
+ response.body = runtime.streamToWeb(response.body);
368
384
  // A failed streaming request carries the API error body in the stream, so read it and let
369
385
  // `ApifyApiError` parse it like any other error body. A body that cannot be read leaves the error
370
386
  // without a message, which beats losing the status code to a stream error.
371
- if (isError && !shouldReturnError && isStream(response.body)) {
372
- response.body = await concatStreamToBuffer(response.body).catch(() => undefined);
387
+ if (isError && !shouldReturnError && isWebStream(response.body)) {
388
+ response.body = await new Response(response.body).arrayBuffer().catch(() => undefined);
373
389
  }
390
+ if (isBuffer(response.body))
391
+ response.body = toResponseBytes(response.body);
374
392
  let data;
375
393
  try {
376
394
  data = this.#parseResponseBody(response, config);
@@ -419,7 +437,7 @@ export class HttpClient {
419
437
  const { body } = response;
420
438
  if (config.responseType === 'stream' || config.responseType === 'buffer')
421
439
  return body;
422
- if (body === undefined || isStream(body))
440
+ if (body === undefined || !isBuffer(body))
423
441
  return body;
424
442
  if (body.byteLength === 0)
425
443
  return undefined;
@@ -444,7 +462,7 @@ export class HttpClient {
444
462
  stopRetrying();
445
463
  return;
446
464
  }
447
- if (isStream(config.data)) {
465
+ if (isAnyStream(config.data)) {
448
466
  this.#informAboutStreamNoRetry();
449
467
  stopRetrying();
450
468
  }
@@ -465,7 +483,10 @@ export class HttpClient {
465
483
  }
466
484
  #onRequestRetry(error, attempt) {
467
485
  if (attempt === Math.round(this.maxRetries / 2)) {
468
- this.logger.warning(`API request failed ${attempt} times. Max attempts: ${this.maxRetries + 1}.\nCause:${error.stack}`);
486
+ // A failed `fetch` names the network error only in its `cause`, and Bun gives its errors no stack.
487
+ const { stack, cause } = error;
488
+ const causedBy = cause instanceof Error ? `\nCaused by: ${cause.stack ?? cause}` : '';
489
+ this.logger.warning(`API request failed ${attempt} times. Max attempts: ${this.maxRetries + 1}.\nCause:${stack ?? error}${causedBy}`);
469
490
  }
470
491
  }
471
492
  }
@@ -545,6 +566,13 @@ function withCause(error, cause) {
545
566
  error.cause = cause;
546
567
  return error;
547
568
  }
569
+ /** Views response bytes as a `Uint8Array` without copying them: a `Buffer` in Node.js, which v2 callers rely on. */
570
+ function toResponseBytes(body) {
571
+ if (runtime.isNode && Buffer.isBuffer(body))
572
+ return body;
573
+ const bytes = toBytes(body);
574
+ return runtime.isNode ? Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength) : bytes;
575
+ }
548
576
  function headerValue(value) {
549
577
  return Array.isArray(value) ? value[0] : value;
550
578
  }
@@ -563,6 +591,8 @@ function serializeBody(data, headers, stringifyFunctions) {
563
591
  return undefined;
564
592
  if (isStream(data))
565
593
  return data;
594
+ if (isWebStream(data))
595
+ return runtime.openStreamBody(data);
566
596
  if (isBlob(data)) {
567
597
  if (getHeader(headers, 'content-type') === undefined && data.type)
568
598
  headers['Content-Type'] = data.type;
@@ -0,0 +1,53 @@
1
+ import type { HttpClientOptions, HttpRequest, HttpResponse } from './base.js';
2
+ import { HttpClient } from './base.js';
3
+ /**
4
+ * A function with the signature of the global [`fetch`](https://developer.mozilla.org/docs/Web/API/Window/fetch).
5
+ */
6
+ export type FetchFunction = typeof globalThis.fetch;
7
+ /**
8
+ * Configuration of {@link FetchHttpClient}.
9
+ */
10
+ export interface FetchHttpClientOptions extends HttpClientOptions {
11
+ /**
12
+ * The `fetch` implementation the requests go through. Pass a wrapper around the global `fetch` to adjust every
13
+ * request, or the `fetch` of another library, such as `undici` with a dispatcher of your own, to control the
14
+ * connections. A stream body reaches it as an async iterable of byte chunks, or as the stream itself in Bun. In a
15
+ * browser or an edge runtime, a web `ReadableStream` body reaches it as a web stream.
16
+ * @default globalThis.fetch
17
+ */
18
+ fetch?: FetchFunction;
19
+ }
20
+ /**
21
+ * The default HTTP client of {@link ApifyClient}, built on the `fetch` of the runtime, so it works the same way in
22
+ * Node.js, browsers and edge runtimes and brings no dependency of its own.
23
+ *
24
+ * It inherits the request pipeline from {@link HttpClient} and adds the transport. Network errors are retried,
25
+ * timeouts included, and a stream body is sent without following redirects, since the part of it already sent could
26
+ * not be replayed. The timeout of a request runs until the response headers arrive and starts over with every chunk
27
+ * of the response body and of a stream body, so a large download or upload does not time out while it makes progress.
28
+ *
29
+ * In Node.js, `fetch` keeps connections alive on its own, and goes through a proxy only when Node.js is told to
30
+ * read the `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` environment variables: start it with `NODE_USE_ENV_PROXY=1`
31
+ * (Node.js 22.21 and 24.0) or `--use-env-proxy` (Node.js 22.21 and 24.5).
32
+ */
33
+ export declare class FetchHttpClient extends HttpClient {
34
+ #private;
35
+ constructor(options?: FetchHttpClientOptions);
36
+ /**
37
+ * A timeout is the `TimeoutError` this client aborts a late request with, or a `fetch` failure caused by one of
38
+ * the connection, headers and body timeouts of Node.js.
39
+ */
40
+ isTimeoutError(error: unknown): boolean;
41
+ /**
42
+ * A network failure is the `TypeError` that `fetch` rejects with: a connection that could not be made, dropped
43
+ * mid-way or timed out. In Node.js it carries the failure as its `cause`, which tells it apart from a request
44
+ * that was never sent, such as one with an invalid URL. Bun rejects with an `Error` that has a `code` instead.
45
+ */
46
+ isRetryableTransportError(error: unknown): boolean;
47
+ /**
48
+ * Sends the request through `fetch` and hands the raw response back. A stream body is sent without following
49
+ * redirects, and so is a request with `followRedirects: false`. A browser hides such a redirect response from
50
+ * the page, so there it fails the request.
51
+ */
52
+ sendRequest(request: HttpRequest): Promise<HttpResponse>;
53
+ }