apify-client 3.0.0-rc.0 → 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 (66) hide show
  1. package/README.md +10 -2
  2. package/dist/apify_api_error.d.ts +4 -3
  3. package/dist/apify_api_error.js +2 -1
  4. package/dist/apify_client.d.ts +8 -8
  5. package/dist/apify_client.js +10 -10
  6. package/dist/apify_client_error.d.ts +10 -0
  7. package/dist/apify_client_error.js +10 -0
  8. package/dist/axios.d.ts +2 -0
  9. package/dist/axios.js +1 -0
  10. package/dist/base/api_client.js +8 -20
  11. package/dist/base/resource_client.js +8 -8
  12. package/dist/body_parser.d.ts +1 -1
  13. package/dist/bundle.js +31 -30
  14. package/dist/bundle.js.map +1 -1
  15. package/dist/generated/api.d.ts +2427 -725
  16. package/dist/generated/schemas.d.ts +1868 -274
  17. package/dist/generated/schemas.js +437 -79
  18. package/dist/http_clients/axios.d.ts +35 -15
  19. package/dist/http_clients/axios.js +80 -32
  20. package/dist/http_clients/base.d.ts +105 -34
  21. package/dist/http_clients/base.js +169 -52
  22. package/dist/http_clients/fetch.d.ts +53 -0
  23. package/dist/http_clients/fetch.js +219 -0
  24. package/dist/http_clients/index.d.ts +2 -2
  25. package/dist/http_clients/index.js +1 -1
  26. package/dist/http_compressors/index.d.ts +2 -0
  27. package/dist/http_compressors/index.js +1 -0
  28. package/dist/http_compressors/resolve.d.ts +4 -3
  29. package/dist/http_compressors/resolve.js +4 -1
  30. package/dist/http_compressors/zstd.d.ts +34 -0
  31. package/dist/http_compressors/zstd.js +43 -0
  32. package/dist/index.d.ts +3 -1
  33. package/dist/index.js +2 -0
  34. package/dist/invalid_response_body_error.d.ts +5 -4
  35. package/dist/invalid_response_body_error.js +5 -4
  36. package/dist/models.d.ts +30 -61
  37. package/dist/resource_clients/actor.d.ts +33 -2
  38. package/dist/resource_clients/actor.js +46 -3
  39. package/dist/resource_clients/actor_server.d.ts +149 -0
  40. package/dist/resource_clients/actor_server.js +195 -0
  41. package/dist/resource_clients/actor_version.d.ts +7 -1
  42. package/dist/resource_clients/actor_version.js +3 -2
  43. package/dist/resource_clients/actor_version_collection.d.ts +2 -1
  44. package/dist/resource_clients/actor_version_collection.js +3 -2
  45. package/dist/resource_clients/dataset.d.ts +33 -5
  46. package/dist/resource_clients/dataset.js +12 -54
  47. package/dist/resource_clients/key_value_store.d.ts +63 -22
  48. package/dist/resource_clients/key_value_store.js +62 -19
  49. package/dist/resource_clients/log.d.ts +32 -7
  50. package/dist/resource_clients/log.js +11 -14
  51. package/dist/resource_clients/request_queue.d.ts +9 -0
  52. package/dist/resource_clients/request_queue.js +9 -6
  53. package/dist/resource_clients/run.d.ts +15 -2
  54. package/dist/resource_clients/run.js +12 -5
  55. package/dist/resource_clients/store_collection.d.ts +4 -0
  56. package/dist/resource_clients/task.js +3 -3
  57. package/dist/response_validation_error.d.ts +2 -1
  58. package/dist/response_validation_error.js +2 -1
  59. package/dist/runtime/node.js +79 -17
  60. package/dist/runtime/types.d.ts +35 -5
  61. package/dist/runtime/web.js +43 -1
  62. package/dist/schemas.d.ts +369 -3
  63. package/dist/schemas.js +25 -3
  64. package/dist/utils.d.ts +52 -27
  65. package/dist/utils.js +45 -25
  66. package/package.json +42 -30
@@ -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,18 +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
- * redirects, since the part of it already sent could not be replayed.
73
+ * redirects, since the part of it already sent could not be replayed, and so is a request with
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.
58
78
  */
59
79
  sendRequest(request: HttpRequest): Promise<HttpResponse>;
60
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,47 +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
- * redirects, since the part of it already sent could not be replayed.
97
+ * redirects, since the part of it already sent could not be replayed, and so is a request with
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.
82
102
  */
83
103
  async sendRequest(request) {
84
104
  await this.#ensureHttpAgents();
85
- const { method, url, headers, body, timeoutMillis, stream, signal } = request;
86
- 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({
87
118
  method,
88
119
  url,
89
- 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,
90
122
  data: body,
91
123
  // Axios reads 0 as no timeout.
92
- timeout: timeoutMillis ?? 0,
93
- signal,
124
+ timeout: headersTimeout ? 0 : (timeoutMillis ?? 0),
125
+ signal: signals.length > 1 ? AbortSignal.any(signals) : signals[0],
94
126
  responseType: stream ? 'stream' : 'arraybuffer',
95
- // See axios/axios#1045 for why axios must not buffer a stream body to follow redirects.
96
- ...(isStream(body) ? { maxRedirects: 0 } : {}),
97
- });
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
+ }
98
141
  return {
99
142
  status: response.status,
100
143
  headers: AxiosHeaders.from(response.headers).toJSON(),
101
- 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)),
102
146
  };
103
147
  }
104
148
  async #ensureHttpAgents() {
@@ -107,11 +151,15 @@ export class AxiosHttpClient extends HttpClient {
107
151
  }
108
152
  async #initHttpAgents() {
109
153
  const agents = await runtime.createHttpAgents({ timeoutMillis: this.timeoutMaxMillis });
110
- if (!agents)
111
- return;
112
- this.httpAgent = agents.httpAgent;
113
- this.httpsAgent = agents.httpsAgent;
154
+ if (agents) {
155
+ this.httpAgent ??= this.#own(agents.httpAgent);
156
+ this.httpsAgent ??= this.#own(agents.httpsAgent);
157
+ }
114
158
  this.axios.defaults.httpAgent = this.httpAgent;
115
159
  this.axios.defaults.httpsAgent = this.httpsAgent;
116
160
  }
161
+ #own(agent) {
162
+ this.#ownAgents.push(agent);
163
+ return agent;
164
+ }
117
165
  }
@@ -27,21 +27,26 @@ export declare const httpClientOptionsShape: {
27
27
  export type HttpResponseHeaders = Record<string, string | string[] | undefined>;
28
28
  /**
29
29
  * A request body as the transport receives it: already serialized, and compressed when that paid off. A `Readable`
30
- * is passed through untouched and is only available in Node.js.
30
+ * is passed through untouched and is only available in Node.js. A `Blob` body reaches a Node.js transport as a
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.
31
34
  */
32
- export type HttpRequestBody = string | Buffer | ArrayBuffer | ArrayBufferView | Readable;
35
+ export type HttpRequestBody = string | Buffer | ArrayBuffer | ArrayBufferView | Readable | ReadableStream<Uint8Array> | Blob;
33
36
  /**
34
- * A response body as the transport hands it back: the raw bytes, a `Readable` when the request asked for a streamed
35
- * 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.
36
41
  */
37
- export type HttpResponseBody = Buffer | ArrayBuffer | Readable | undefined;
42
+ export type HttpResponseBody = Uint8Array | ArrayBuffer | Readable | ReadableStream<Uint8Array> | undefined;
38
43
  /**
39
44
  * How {@link HttpClient.call} hands back the response body.
40
45
  *
41
46
  * - `parsed` (the default) decodes it by content type: JSON becomes an object, text and XML become a string, anything
42
- * else stays a `Buffer` (an `ArrayBuffer` in the browser).
43
- * - `buffer` skips the decoding and hands back the raw bytes.
44
- * - `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.
45
50
  */
46
51
  export type ApifyResponseType = 'parsed' | 'buffer' | 'stream';
47
52
  /**
@@ -62,9 +67,11 @@ export interface ApifyRequestConfig {
62
67
  /**
63
68
  * Request body. A plain object or array is serialized to JSON and sent as `application/json`, or form-encoded
64
69
  * when a `Content-Type: application/x-www-form-urlencoded` header asks for it. A string, binary value
65
- * (`Buffer`, `ArrayBuffer`, typed array) or `Readable` is sent as it is, and `URLSearchParams` is sent
66
- * form-encoded. A `Blob`, `File`, `FormData` or web `ReadableStream` is rejected with a `TypeError`, since
67
- * 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.
68
75
  */
69
76
  data?: unknown;
70
77
  /**
@@ -82,6 +89,40 @@ export interface ApifyRequestConfig {
82
89
  stringifyFunctions?: boolean;
83
90
  /** Give up on the first transport timeout instead of retrying it. */
84
91
  doNotRetryTimeouts?: boolean;
92
+ /**
93
+ * How to compress the request body: an {@link HttpCompressor} for this request only, or `false` to send the body
94
+ * uncompressed. Defaults to the client's {@link HttpClient.httpCompressor}.
95
+ */
96
+ compression?: HttpCompressor | false;
97
+ /**
98
+ * Header that carries the client's API token for this request. The Apify API reads `Authorization`. Actor
99
+ * servers also accept `X-Apify-Authorization`, which the platform removes before the request reaches the Actor,
100
+ * so the `Authorization` header stays free for the Actor's own authentication. A per-request header of either
101
+ * name still wins.
102
+ * @default 'Authorization'
103
+ */
104
+ authorizationHeader?: 'Authorization' | 'X-Apify-Authorization';
105
+ /**
106
+ * Whether an error status throws {@link ApifyApiError}. With `false`, the call resolves to the error response
107
+ * once no retry follows, and a rate limit (429) doesn't count toward the client's statistics, which track the
108
+ * API's rate limits.
109
+ * @default true
110
+ */
111
+ throwOnErrorStatus?: boolean;
112
+ /** Status codes to retry. Defaults to rate limits (429) and server errors (5xx). */
113
+ retryStatusCodes?: readonly number[];
114
+ /**
115
+ * Whether transport errors, timeouts included, are retried. With `false`, the first one fails the call, since the
116
+ * request may have reached the server before it failed.
117
+ * @default true
118
+ */
119
+ retryTransportErrors?: boolean;
120
+ /**
121
+ * Whether the transport follows redirects. With `false`, a redirect response is handled like an error status, so
122
+ * headers that carry the token never go to a host the server picked.
123
+ * @default true
124
+ */
125
+ followRedirects?: boolean;
85
126
  /**
86
127
  * Aborts the call. Once the signal aborts, the attempt in flight is ended, no retry follows, and the call
87
128
  * rejects with the signal's `reason`.
@@ -89,7 +130,8 @@ export interface ApifyRequestConfig {
89
130
  signal?: AbortSignal;
90
131
  }
91
132
  /**
92
- * A successful response as {@link HttpClient.call} resolves to it.
133
+ * A response as {@link HttpClient.call} resolves to it: a success, or an error response when the request sets
134
+ * {@link ApifyRequestConfig.throwOnErrorStatus} to `false`.
93
135
  *
94
136
  * @template T - Type of the parsed body.
95
137
  */
@@ -120,8 +162,13 @@ export interface HttpRequest {
120
162
  * `timeoutSecs: 'noTimeout'` asks for.
121
163
  */
122
164
  timeoutMillis?: number;
123
- /** 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`. */
124
166
  stream: boolean;
167
+ /**
168
+ * Whether to follow redirects. With `false`, return a redirect response as it is: the request carries a token
169
+ * that must not follow a redirect to another host.
170
+ */
171
+ followRedirects: boolean;
125
172
  /**
126
173
  * The caller's abort signal, to hand to the HTTP library alongside the timeout. The pipeline stops retrying
127
174
  * once it aborts, so the transport only has to end the request in flight.
@@ -136,7 +183,7 @@ export interface HttpResponse {
136
183
  status: number;
137
184
  /** Response headers keyed by lowercase header name. */
138
185
  headers: HttpResponseHeaders;
139
- /** 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. */
140
187
  body: HttpResponseBody;
141
188
  }
142
189
  /**
@@ -189,22 +236,33 @@ export interface HttpClientOptions {
189
236
  *
190
237
  * Overriding {@link call} itself is also supported and bypasses the transport hooks entirely. Such a client has
191
238
  * to send the default headers from `defaultHeaders` with every request, otherwise the `Authorization` header never
192
- * reaches the API. The protected helpers `prepareRequest()`, `buildUrl()` and `computeTimeoutMillis()` stay
193
- * available to it.
239
+ * reaches the API. It also has to honor the per-request options {@link ApifyRequestConfig.compression},
240
+ * {@link ApifyRequestConfig.authorizationHeader}, {@link ApifyRequestConfig.throwOnErrorStatus},
241
+ * {@link ApifyRequestConfig.retryStatusCodes}, {@link ApifyRequestConfig.retryTransportErrors} and
242
+ * {@link ApifyRequestConfig.followRedirects}.
243
+ * {@link ActorServerClient.request} relies on them to keep the token away from the Actor's code, to return the
244
+ * server's error responses and to avoid sending a request to the Actor twice. The protected helpers
245
+ * `prepareRequest()`, `buildUrl()` and `computeTimeoutMillis()` stay available to it.
194
246
  *
195
247
  * @example
196
248
  * ```javascript
197
249
  * import { ApifyClient, HttpClient } from 'apify-client';
198
250
  *
199
- * class FetchHttpClient extends HttpClient {
200
- * async sendRequest({ method, url, headers, body, timeoutMillis, signal }) {
251
+ * class MyFetchHttpClient extends HttpClient {
252
+ * async sendRequest({ method, url, headers, body, timeoutMillis, followRedirects, signal }) {
201
253
  * const signals = signal ? [signal] : [];
202
254
  * if (timeoutMillis !== undefined) signals.push(AbortSignal.timeout(timeoutMillis));
203
- * 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
+ * });
204
262
  * return {
205
263
  * status: response.status,
206
264
  * headers: Object.fromEntries(response.headers),
207
- * body: Buffer.from(await response.arrayBuffer()),
265
+ * body: await response.arrayBuffer(),
208
266
  * };
209
267
  * }
210
268
  *
@@ -214,7 +272,7 @@ export interface HttpClientOptions {
214
272
  * }
215
273
  * }
216
274
  *
217
- * const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new FetchHttpClient() });
275
+ * const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new MyFetchHttpClient() });
218
276
  * ```
219
277
  */
220
278
  export declare abstract class HttpClient {
@@ -278,7 +336,9 @@ export declare abstract class HttpClient {
278
336
  * The inherited {@link call} needs it, so every transport has to implement it. Let the library's errors
279
337
  * propagate unwrapped: {@link call} classifies them through {@link isRetryableTransportError} and
280
338
  * {@link isTimeoutError}. Return error responses as they are too, the pipeline turns them into
281
- * {@link ApifyApiError} and decides whether to retry.
339
+ * {@link ApifyApiError} and decides whether to retry. Reject when the connection drops before the body is
340
+ * complete: the pipeline takes a returned body as whole and does not retry one that fails to parse. When
341
+ * `request.followRedirects` is `false`, return a redirect response as it is, since the request carries a token.
282
342
  *
283
343
  * @param request - The request to send, with the headers merged, the body serialized and the query encoded.
284
344
  * @returns The response, with the body unread when `request.stream` is set and as raw bytes otherwise.
@@ -288,26 +348,32 @@ export declare abstract class HttpClient {
288
348
  * Makes an API request with automatic retries and exponential backoff.
289
349
  *
290
350
  * Network errors the transport classifies as retryable, rate limits (HTTP 429) and server errors (HTTP 5xx)
291
- * are retried up to {@link maxRetries} times. Any other error status is thrown as {@link ApifyApiError} right
292
- * away. A request whose body is a `Readable` is never retried, since part of the stream has already been
293
- * consumed by the time the failure shows. Aborting `config.signal` ends the attempt in flight, skips the
294
- * remaining retries and rejects the call with the signal's `reason`.
351
+ * are retried up to {@link maxRetries} times, and `config.retryStatusCodes` picks other statuses to retry. Any
352
+ * other error status is thrown as {@link ApifyApiError} right away, or returned when `config.throwOnErrorStatus`
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`.
295
358
  *
296
359
  * @template T - Type of the parsed response body.
297
360
  * @param config - The request to make.
298
- * @returns The successful response.
299
- * @throws {ApifyApiError} When the API responds with an error status the retries could not fix.
361
+ * @returns The successful response, or the error response when `config.throwOnErrorStatus` is `false`.
362
+ * @throws {ApifyApiError} When the API responds with an error status the retries could not fix, unless
363
+ * `config.throwOnErrorStatus` is `false`.
300
364
  */
301
365
  call<T = any>(config: ApifyRequestConfig): Promise<ApifyResponse<T>>;
302
366
  /**
303
367
  * Prepares the headers and the body of a request.
304
368
  *
305
- * Merges the client's default headers with the per-request ones, header names compared case-insensitively and
306
- * the per-request values winning. Serializes an object body to JSON, setting `Content-Type: application/json`
307
- * unless the caller supplied a content type. Runs the body through {@link httpCompressor} unless a
308
- * `Content-Encoding` header is already set, the body is too small, or its content type says the payload is
309
- * already compressed. A caller-supplied `Content-Encoding` is forwarded as it is, which is how a pre-encoded
310
- * body is uploaded, and `Content-Encoding: identity` opts a single request out of compression.
369
+ * Merges the client's default headers with the per-request ones, header names compared case-insensitively and the
370
+ * per-request values winning, after moving the default `Authorization` header to `X-Apify-Authorization` when
371
+ * `config.authorizationHeader` asks for it. Serializes an object body to JSON, setting
372
+ * `Content-Type: application/json` unless the caller supplied a content type. Runs the body through
373
+ * {@link httpCompressor}, or the compressor in `config.compression`, unless `config.compression` is `false`, a
374
+ * `Content-Encoding` header is already set, the body is too small, or its content type says the payload is already
375
+ * compressed. A caller-supplied `Content-Encoding` is forwarded as it is, which is how a pre-encoded body is
376
+ * uploaded, and `Content-Encoding: identity` opts a single request out of compression.
311
377
  */
312
378
  protected prepareRequest(config: ApifyRequestConfig): Promise<{
313
379
  headers: Record<string, string>;
@@ -329,3 +395,8 @@ export declare abstract class HttpClient {
329
395
  */
330
396
  protected computeTimeoutMillis(attempt: number, timeoutSecs?: Timeout): number | undefined;
331
397
  }
398
+ /**
399
+ * Merges two header records, header names compared case-insensitively. A header from `override` replaces a
400
+ * same-named header in `base` whatever the casing of either, and keeps the casing it was passed with.
401
+ */
402
+ export declare function mergeHeaders(base: Record<string, string>, override?: Record<string, string>): Record<string, string>;