apify-client 3.0.0-beta.5 → 3.0.0-beta.51

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 (115) hide show
  1. package/README.md +13 -3
  2. package/dist/apify_api_error.d.ts +62 -21
  3. package/dist/apify_api_error.js +96 -23
  4. package/dist/apify_client.d.ts +125 -10
  5. package/dist/apify_client.js +133 -48
  6. package/dist/base/api_client.d.ts +7 -7
  7. package/dist/base/api_client.js +36 -24
  8. package/dist/base/resource_client.d.ts +21 -8
  9. package/dist/base/resource_client.js +54 -26
  10. package/dist/base/resource_collection_client.d.ts +12 -4
  11. package/dist/base/resource_collection_client.js +34 -11
  12. package/dist/body_parser.d.ts +3 -4
  13. package/dist/body_parser.js +19 -26
  14. package/dist/bundle.js +27 -22
  15. package/dist/bundle.js.map +1 -1
  16. package/dist/generated/api.d.ts +610 -112
  17. package/dist/generated/schemas.d.ts +726 -703
  18. package/dist/generated/schemas.js +92 -85
  19. package/dist/http_clients/axios.d.ts +60 -0
  20. package/dist/http_clients/axios.js +117 -0
  21. package/dist/http_clients/base.d.ts +333 -0
  22. package/dist/http_clients/base.js +563 -0
  23. package/dist/http_clients/index.d.ts +4 -0
  24. package/dist/http_clients/index.js +2 -0
  25. package/dist/http_compressors/base.d.ts +40 -0
  26. package/dist/http_compressors/base.js +9 -0
  27. package/dist/http_compressors/brotli.d.ts +33 -0
  28. package/dist/http_compressors/brotli.js +39 -0
  29. package/dist/http_compressors/gzip.d.ts +33 -0
  30. package/dist/http_compressors/gzip.js +39 -0
  31. package/dist/http_compressors/index.d.ts +6 -0
  32. package/dist/http_compressors/index.js +2 -0
  33. package/dist/http_compressors/resolve.d.ts +23 -0
  34. package/dist/http_compressors/resolve.js +27 -0
  35. package/dist/index.d.ts +4 -1
  36. package/dist/index.js +3 -1
  37. package/dist/invalid_response_body_error.d.ts +13 -0
  38. package/dist/invalid_response_body_error.js +17 -0
  39. package/dist/models.d.ts +19 -22
  40. package/dist/resource_clients/actor.d.ts +72 -32
  41. package/dist/resource_clients/actor.js +87 -56
  42. package/dist/resource_clients/actor_collection.d.ts +9 -5
  43. package/dist/resource_clients/actor_collection.js +11 -3
  44. package/dist/resource_clients/actor_env_var.d.ts +10 -3
  45. package/dist/resource_clients/actor_env_var.js +16 -6
  46. package/dist/resource_clients/actor_env_var_collection.d.ts +14 -18
  47. package/dist/resource_clients/actor_env_var_collection.js +17 -11
  48. package/dist/resource_clients/actor_version.d.ts +18 -3
  49. package/dist/resource_clients/actor_version.js +19 -9
  50. package/dist/resource_clients/actor_version_collection.d.ts +16 -17
  51. package/dist/resource_clients/actor_version_collection.js +19 -11
  52. package/dist/resource_clients/build.d.ts +18 -6
  53. package/dist/resource_clients/build.js +34 -15
  54. package/dist/resource_clients/build_collection.d.ts +3 -1
  55. package/dist/resource_clients/build_collection.js +4 -1
  56. package/dist/resource_clients/dataset.d.ts +51 -33
  57. package/dist/resource_clients/dataset.js +105 -80
  58. package/dist/resource_clients/dataset_collection.d.ts +6 -2
  59. package/dist/resource_clients/dataset_collection.js +13 -2
  60. package/dist/resource_clients/key_value_store.d.ts +58 -16
  61. package/dist/resource_clients/key_value_store.js +78 -40
  62. package/dist/resource_clients/key_value_store_collection.d.ts +6 -2
  63. package/dist/resource_clients/key_value_store_collection.js +13 -2
  64. package/dist/resource_clients/log.d.ts +12 -20
  65. package/dist/resource_clients/log.js +93 -58
  66. package/dist/resource_clients/request_queue.d.ts +56 -26
  67. package/dist/resource_clients/request_queue.js +176 -103
  68. package/dist/resource_clients/request_queue_collection.d.ts +6 -2
  69. package/dist/resource_clients/request_queue_collection.js +9 -3
  70. package/dist/resource_clients/run.d.ts +108 -18
  71. package/dist/resource_clients/run.js +183 -43
  72. package/dist/resource_clients/run_collection.d.ts +3 -1
  73. package/dist/resource_clients/run_collection.js +4 -1
  74. package/dist/resource_clients/schedule.d.ts +14 -5
  75. package/dist/resource_clients/schedule.js +29 -21
  76. package/dist/resource_clients/schedule_collection.d.ts +6 -2
  77. package/dist/resource_clients/schedule_collection.js +9 -3
  78. package/dist/resource_clients/store_collection.d.ts +3 -1
  79. package/dist/resource_clients/store_collection.js +4 -1
  80. package/dist/resource_clients/task.d.ts +33 -10
  81. package/dist/resource_clients/task.js +79 -46
  82. package/dist/resource_clients/task_collection.d.ts +6 -2
  83. package/dist/resource_clients/task_collection.js +9 -3
  84. package/dist/resource_clients/user.d.ts +17 -8
  85. package/dist/resource_clients/user.js +42 -38
  86. package/dist/resource_clients/webhook.d.ts +14 -5
  87. package/dist/resource_clients/webhook.js +30 -22
  88. package/dist/resource_clients/webhook_collection.d.ts +6 -2
  89. package/dist/resource_clients/webhook_collection.js +9 -3
  90. package/dist/resource_clients/webhook_dispatch.d.ts +4 -1
  91. package/dist/resource_clients/webhook_dispatch.js +7 -2
  92. package/dist/resource_clients/webhook_dispatch_collection.d.ts +3 -1
  93. package/dist/resource_clients/webhook_dispatch_collection.js +4 -1
  94. package/dist/runtime/node.d.ts +6 -0
  95. package/dist/runtime/node.js +49 -0
  96. package/dist/runtime/types.d.ts +52 -0
  97. package/dist/runtime/types.js +1 -0
  98. package/dist/runtime/web.d.ts +5 -0
  99. package/dist/runtime/web.js +18 -0
  100. package/dist/schemas.d.ts +1 -1
  101. package/dist/schemas.js +1 -1
  102. package/dist/statistics.d.ts +1 -6
  103. package/dist/statistics.js +2 -2
  104. package/dist/timeouts.d.ts +84 -0
  105. package/dist/timeouts.js +37 -0
  106. package/dist/timezones.d.ts +1 -1
  107. package/dist/utils.d.ts +81 -52
  108. package/dist/utils.js +201 -170
  109. package/dist/wait_for_resources.d.ts +8 -0
  110. package/dist/wait_for_resources.js +39 -0
  111. package/package.json +32 -29
  112. package/dist/http_client.d.ts +0 -88
  113. package/dist/http_client.js +0 -255
  114. package/dist/interceptors.d.ts +0 -19
  115. package/dist/interceptors.js +0 -105
@@ -0,0 +1,117 @@
1
+ import axios, { AxiosError, AxiosHeaders } from 'axios';
2
+ import { runtime } from '#runtime';
3
+ import { isStream } from '../utils.js';
4
+ import { HttpClient } from './base.js';
5
+ /**
6
+ * The default HTTP client of {@link ApifyClient}, built on [axios](https://axios-http.com).
7
+ *
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.
12
+ */
13
+ export class AxiosHttpClient extends HttpClient {
14
+ /** The axios instance the requests go through. */
15
+ 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
+ */
20
+ httpAgent;
21
+ /** Keep-alive agent for HTTPS. The same instance as {@link httpAgent}. */
22
+ httpsAgent;
23
+ #httpAgentsPromise;
24
+ constructor(options = {}) {
25
+ super(options);
26
+ this.axios = axios.create({
27
+ // The agents handle the proxy environment variables.
28
+ proxy: false,
29
+ validateStatus: null,
30
+ // The shared pipeline serializes and parses the bodies, so axios only moves bytes.
31
+ transformRequest: [],
32
+ transformResponse: [],
33
+ responseType: 'arraybuffer',
34
+ // maxBodyLength needs to be Infinity, because -1 falls back to a 10 MB default
35
+ // from an axios subdependency - 'follow-redirects'
36
+ maxBodyLength: Infinity,
37
+ // maxContentLength must be -1, because Infinity will cause axios to run super slow
38
+ // thanks to a bug that's now fixed, but not released yet https://github.com/axios/axios/pull/3738
39
+ maxContentLength: -1,
40
+ });
41
+ // The pipeline merges every header the client sends, so the axios defaults would only get in the way.
42
+ this.axios.defaults.headers = new AxiosHeaders();
43
+ for (const interceptor of options.requestInterceptors ?? []) {
44
+ this.axios.interceptors.request.use(interceptor);
45
+ }
46
+ }
47
+ /**
48
+ * A timeout is an axios error coded `ECONNABORTED` or `ETIMEDOUT`, besides the `TimeoutError` the base class
49
+ * recognizes.
50
+ */
51
+ isTimeoutError(error) {
52
+ if (super.isTimeoutError(error))
53
+ return true;
54
+ // Axios aborts the request when its own timeout fires, which gives ECONNABORTED, or ETIMEDOUT under
55
+ // `clarifyTimeoutError`. ETIMEDOUT also arrives straight from the socket, when the connection itself
56
+ // times out.
57
+ return (axios.isAxiosError(error) && (error.code === AxiosError.ECONNABORTED || error.code === AxiosError.ETIMEDOUT));
58
+ }
59
+ /**
60
+ * 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.
63
+ */
64
+ isRetryableTransportError(error) {
65
+ if (!axios.isAxiosError(error))
66
+ return false;
67
+ return typeof error.request === 'object' && error.request !== null && error.config != null;
68
+ }
69
+ /**
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.
72
+ */
73
+ async close() {
74
+ // A failed initialization left nothing to release, and its error belongs to the request that hit it.
75
+ await this.#httpAgentsPromise?.catch(() => { });
76
+ this.httpAgent?.destroy();
77
+ this.httpsAgent?.destroy();
78
+ }
79
+ /**
80
+ * 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.
82
+ */
83
+ async sendRequest(request) {
84
+ await this.#ensureHttpAgents();
85
+ const { method, url, headers, body, timeoutMillis, stream, signal } = request;
86
+ const response = await this.axios.request({
87
+ method,
88
+ url,
89
+ headers,
90
+ data: body,
91
+ // Axios reads 0 as no timeout.
92
+ timeout: timeoutMillis ?? 0,
93
+ signal,
94
+ 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
+ });
98
+ return {
99
+ status: response.status,
100
+ headers: AxiosHeaders.from(response.headers).toJSON(),
101
+ body: response.data,
102
+ };
103
+ }
104
+ async #ensureHttpAgents() {
105
+ this.#httpAgentsPromise ??= this.#initHttpAgents();
106
+ return this.#httpAgentsPromise;
107
+ }
108
+ async #initHttpAgents() {
109
+ const agents = await runtime.createHttpAgents({ timeoutMillis: this.timeoutMaxMillis });
110
+ if (!agents)
111
+ return;
112
+ this.httpAgent = agents.httpAgent;
113
+ this.httpsAgent = agents.httpsAgent;
114
+ this.axios.defaults.httpAgent = this.httpAgent;
115
+ this.axios.defaults.httpsAgent = this.httpsAgent;
116
+ }
117
+ }
@@ -0,0 +1,333 @@
1
+ import type { Readable } from 'node:stream';
2
+ import { z } from 'zod';
3
+ import type { Log } from '@apify/log';
4
+ import type { HttpCompressor } from '../http_compressors/base.js';
5
+ import type { HttpCompressionAlgorithm } from '../http_compressors/resolve.js';
6
+ import { Statistics } from '../statistics.js';
7
+ import type { Timeout, TimeoutTier } from '../timeouts.js';
8
+ export declare const DEFAULT_MAX_RETRIES = 8;
9
+ export declare const DEFAULT_MIN_DELAY_BETWEEN_RETRIES_MILLIS = 500;
10
+ /**
11
+ * Bounds of the numeric {@link HttpClientOptions}. `ApifyClientOptions` checks the same bounds and adds the defaults.
12
+ * @internal
13
+ */
14
+ export declare const httpClientOptionsShape: {
15
+ maxRetries: z.ZodNumber;
16
+ minDelayBetweenRetriesMillis: z.ZodNumber;
17
+ timeoutShortSecs: z.ZodNumber;
18
+ timeoutMediumSecs: z.ZodNumber;
19
+ timeoutLongSecs: z.ZodNumber;
20
+ timeoutMaxSecs: z.ZodNumber;
21
+ };
22
+ /**
23
+ * HTTP methods the Apify API accepts.
24
+ */
25
+ export type HttpMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD' | 'OPTIONS';
26
+ /**
27
+ * Response headers keyed by lowercase header name. A header the server sent more than once may arrive as an array.
28
+ */
29
+ export type HttpResponseHeaders = Record<string, string | string[] | undefined>;
30
+ /**
31
+ * A request body as the transport receives it: already serialized, and compressed when that paid off. A `Readable`
32
+ * is passed through untouched and is only available in Node.js.
33
+ */
34
+ export type HttpRequestBody = string | Buffer | ArrayBuffer | ArrayBufferView | Readable;
35
+ /**
36
+ * A response body as the transport hands it back: the raw bytes, a `Readable` when the request asked for a streamed
37
+ * response, or `undefined` when the response carried no body.
38
+ */
39
+ export type HttpResponseBody = Buffer | ArrayBuffer | Readable | undefined;
40
+ /**
41
+ * How {@link HttpClient.call} hands back the response body.
42
+ *
43
+ * - `parsed` (the default) decodes it by content type: JSON becomes an object, text and XML become a string, anything
44
+ * else stays a `Buffer` (an `ArrayBuffer` in the browser).
45
+ * - `buffer` skips the decoding and hands back the raw bytes.
46
+ * - `stream` hands back a `Readable` with the body unread. Node.js only.
47
+ */
48
+ export type ApifyResponseType = 'parsed' | 'buffer' | 'stream';
49
+ /**
50
+ * A request as the resource clients hand it to {@link HttpClient.call}.
51
+ */
52
+ export interface ApifyRequestConfig {
53
+ /** Full URL of the endpoint, without the query string. */
54
+ url: string;
55
+ /** HTTP method. */
56
+ method: HttpMethod;
57
+ /**
58
+ * Query parameters. `undefined` values are dropped, booleans are sent as `1` and `0`, `Date` values as ISO 8601
59
+ * strings and arrays comma-separated.
60
+ */
61
+ params?: Record<string, unknown>;
62
+ /** Per-request headers. They win over the client's default headers, header names compared case-insensitively. */
63
+ headers?: Record<string, string>;
64
+ /**
65
+ * Request body. A plain object or array is serialized to JSON and sent as `application/json`, or form-encoded
66
+ * when a `Content-Type: application/x-www-form-urlencoded` header asks for it. A string, binary value
67
+ * (`Buffer`, `ArrayBuffer`, typed array) or `Readable` is sent as it is, and `URLSearchParams` is sent
68
+ * form-encoded. A `Blob`, `File`, `FormData` or web `ReadableStream` is rejected with a `TypeError`, since
69
+ * serializing one would send an empty body.
70
+ */
71
+ data?: unknown;
72
+ /**
73
+ * Timeout of the request: a tier name, a number of seconds, or `'noTimeout'`. The client resolves it to the
74
+ * timeout of each attempt in milliseconds, doubling it with every retry up to `timeoutMaxSecs`.
75
+ * @default 'medium'
76
+ */
77
+ timeoutSecs?: Timeout;
78
+ /** @default 'parsed' */
79
+ responseType?: ApifyResponseType;
80
+ /**
81
+ * Serialize function-valued fields of a JSON body to their source instead of dropping them, which is how
82
+ * Actor input carrying page functions reaches the API.
83
+ */
84
+ stringifyFunctions?: boolean;
85
+ /** Give up on the first transport timeout instead of retrying it. */
86
+ doNotRetryTimeouts?: boolean;
87
+ /**
88
+ * Aborts the call. Once the signal aborts, the attempt in flight is ended, no retry follows, and the call
89
+ * rejects with the signal's `reason`.
90
+ */
91
+ signal?: AbortSignal;
92
+ }
93
+ /**
94
+ * A successful response as {@link HttpClient.call} resolves to it.
95
+ *
96
+ * @template T - Type of the parsed body.
97
+ */
98
+ export interface ApifyResponse<T = any> {
99
+ /** HTTP status code. */
100
+ status: number;
101
+ /** Response headers keyed by lowercase header name. */
102
+ headers: HttpResponseHeaders;
103
+ /** The response body, decoded according to the request's {@link ApifyRequestConfig.responseType}. */
104
+ data: T;
105
+ /** The request this response answers, as it was passed to {@link HttpClient.call}. */
106
+ config: ApifyRequestConfig;
107
+ }
108
+ /**
109
+ * One prepared request attempt, as {@link HttpClient.sendRequest} receives it from the shared pipeline.
110
+ */
111
+ export interface HttpRequest {
112
+ /** HTTP method. */
113
+ method: HttpMethod;
114
+ /** Full request URL with the query string already encoded into it. */
115
+ url: string;
116
+ /** Final request headers, with the client's default headers already merged in. */
117
+ headers: Record<string, string>;
118
+ /** Request body, already serialized and compressed, or `undefined` for a request without one. */
119
+ body?: HttpRequestBody;
120
+ /**
121
+ * Timeout for this attempt in milliseconds, or `undefined` for a request that runs without one, which is what
122
+ * `timeoutSecs: 'noTimeout'` asks for.
123
+ */
124
+ timeoutMillis?: number;
125
+ /** Whether to hand the body back unread as a `Readable`, so the caller can stream it. */
126
+ stream: boolean;
127
+ /**
128
+ * The caller's abort signal, to hand to the HTTP library alongside the timeout. The pipeline stops retrying
129
+ * once it aborts, so the transport only has to end the request in flight.
130
+ */
131
+ signal?: AbortSignal;
132
+ }
133
+ /**
134
+ * A response as the transport returns it from {@link HttpClient.sendRequest}, error statuses included.
135
+ */
136
+ export interface HttpResponse {
137
+ /** HTTP status code. */
138
+ status: number;
139
+ /** Response headers keyed by lowercase header name. */
140
+ headers: HttpResponseHeaders;
141
+ /** The body as raw bytes, or unread as a `Readable` when the request asked for a stream. */
142
+ body: HttpResponseBody;
143
+ }
144
+ /**
145
+ * Configuration shared by every {@link HttpClient}.
146
+ */
147
+ export interface HttpClientOptions {
148
+ /** Apify API token, sent as a `Bearer` token in the `Authorization` header. */
149
+ token?: string;
150
+ /** How many times a failed request is retried at most. @default 8 */
151
+ maxRetries?: number;
152
+ /**
153
+ * Lower bound for the delay before the first retry in milliseconds. It doubles with every further retry.
154
+ * @default 500
155
+ */
156
+ minDelayBetweenRetriesMillis?: number;
157
+ /** Duration of the `short` timeout tier, in seconds. @default 5 */
158
+ timeoutShortSecs?: number;
159
+ /** Duration of the `medium` timeout tier, in seconds. @default 30 */
160
+ timeoutMediumSecs?: number;
161
+ /** Duration of the `long` timeout tier, in seconds. @default 360 */
162
+ timeoutLongSecs?: number;
163
+ /** Upper bound for the timeout of a single attempt, in seconds. @default 360 */
164
+ timeoutMaxSecs?: number;
165
+ /**
166
+ * Compression of request bodies: the name of a built-in algorithm, or an {@link HttpCompressor} for a custom
167
+ * quality or algorithm.
168
+ * @default 'brotli'
169
+ */
170
+ compression?: HttpCompressionAlgorithm | HttpCompressor;
171
+ /** Additional headers sent with every request. They win over the built-in defaults. */
172
+ headers?: Record<string, string>;
173
+ /** Statistics the client records its calls into. Created when omitted. */
174
+ stats?: Statistics;
175
+ /** Logger for the retry warnings. Defaults to a child of the `@apify/log` default with an `ApifyClient` prefix. */
176
+ logger?: Log;
177
+ /** Value of the `X-Apify-Workflow-Key` header. Defaults to the `APIFY_WORKFLOW_KEY` environment variable. */
178
+ workflowKey?: string;
179
+ /** @internal */
180
+ userAgentSuffix?: string | string[];
181
+ }
182
+ /**
183
+ * Base class for the HTTP clients used by {@link ApifyClient}.
184
+ *
185
+ * It holds the shared request pipeline: {@link call} merges the default headers in, serializes and compresses the
186
+ * body, encodes the query parameters, retries transient failures with exponential backoff, grows the timeout with
187
+ * every attempt, decodes the response body by content type, records statistics and converts error statuses to
188
+ * {@link ApifyApiError}. A concrete client only has to implement {@link sendRequest}, the transport that moves one
189
+ * prepared request over the wire, and can override the classification and lifecycle hooks {@link isTimeoutError},
190
+ * {@link isRetryableTransportError} and {@link close}.
191
+ *
192
+ * Overriding {@link call} itself is also supported and bypasses the transport hooks entirely. Such a client has
193
+ * to send the default headers from `defaultHeaders` with every request, otherwise the `Authorization` header never
194
+ * reaches the API. The protected helpers `prepareRequest()`, `buildUrl()` and `computeTimeoutMillis()` stay
195
+ * available to it.
196
+ *
197
+ * @example
198
+ * ```javascript
199
+ * import { ApifyClient, HttpClient } from 'apify-client';
200
+ *
201
+ * class FetchHttpClient extends HttpClient {
202
+ * async sendRequest({ method, url, headers, body, timeoutMillis, signal }) {
203
+ * const signals = signal ? [signal] : [];
204
+ * if (timeoutMillis !== undefined) signals.push(AbortSignal.timeout(timeoutMillis));
205
+ * const response = await fetch(url, { method, headers, body, signal: AbortSignal.any(signals) });
206
+ * return {
207
+ * status: response.status,
208
+ * headers: Object.fromEntries(response.headers),
209
+ * body: Buffer.from(await response.arrayBuffer()),
210
+ * };
211
+ * }
212
+ *
213
+ * isRetryableTransportError(error) {
214
+ * // Without this the client gives up on the first connection failure.
215
+ * return this.isTimeoutError(error) || error instanceof TypeError;
216
+ * }
217
+ * }
218
+ *
219
+ * const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new FetchHttpClient() });
220
+ * ```
221
+ */
222
+ export declare abstract class HttpClient {
223
+ #private;
224
+ /** Statistics of the API calls made through this client. */
225
+ stats: Statistics;
226
+ /** Logger for the retry warnings. */
227
+ logger: Log;
228
+ /** How many times a failed request is retried at most. */
229
+ maxRetries: number;
230
+ /** Lower bound for the delay before the first retry in milliseconds. It doubles with every further retry. */
231
+ minDelayBetweenRetriesMillis: number;
232
+ /** Duration of each timeout tier, in milliseconds. */
233
+ timeoutMillis: Record<TimeoutTier, number>;
234
+ /** Upper bound for the timeout of a single attempt, in milliseconds. */
235
+ timeoutMaxMillis: number;
236
+ /** Compressor the request pipeline runs the bodies worth compressing through. */
237
+ readonly httpCompressor: HttpCompressor;
238
+ /**
239
+ * Headers sent with every request: the `Authorization` header built from the token, the `User-Agent` where the
240
+ * runtime lets a client set one, the `X-Apify-Workflow-Key` when a workflow key is configured, and whatever
241
+ * {@link HttpClientOptions.headers} added.
242
+ */
243
+ protected readonly defaultHeaders: Record<string, string>;
244
+ /**
245
+ * @param options - Configuration of the pipeline. The retry and timeout options are validated the same way the
246
+ * `ApifyClient` constructor validates them.
247
+ * @throws {ArgumentValidationError} When a retry or timeout option is out of bounds.
248
+ */
249
+ constructor(options?: HttpClientOptions);
250
+ /**
251
+ * Sets the `Authorization` header from the token, unless an authorization header is already configured.
252
+ *
253
+ * @param token - The Apify API token to send as the `Bearer` token.
254
+ */
255
+ setDefaultAuthorization(token: string): void;
256
+ /**
257
+ * Whether an error thrown by the transport is a timeout.
258
+ *
259
+ * Recognizes errors named `TimeoutError`, which is what `AbortSignal.timeout()` produces. Transports extend it
260
+ * with the timeout errors their HTTP library throws. The classification is independent of retryability: a
261
+ * timeout the retry loop should retry has to be covered by {@link isRetryableTransportError} too.
262
+ */
263
+ isTimeoutError(error: unknown): boolean;
264
+ /**
265
+ * Whether an error thrown by the transport is worth retrying.
266
+ *
267
+ * The default classifies nothing as retryable, so a transport that does not override it gives up on the first
268
+ * connection failure. Every transport should map its own transient errors here: connection resets, refused
269
+ * connections, timeouts and the like. Error responses are not the transport's concern, the pipeline decides on
270
+ * them from the status code.
271
+ */
272
+ isRetryableTransportError(_error: unknown): boolean;
273
+ /**
274
+ * Releases resources owned by the transport, such as a connection pool. The default does nothing.
275
+ */
276
+ close(): Promise<void>;
277
+ /**
278
+ * Sends one prepared request through the underlying HTTP library.
279
+ *
280
+ * The inherited {@link call} needs it, so every transport has to implement it. Let the library's errors
281
+ * propagate unwrapped: {@link call} classifies them through {@link isRetryableTransportError} and
282
+ * {@link isTimeoutError}. Return error responses as they are too, the pipeline turns them into
283
+ * {@link ApifyApiError} and decides whether to retry.
284
+ *
285
+ * @param request - The request to send, with the headers merged, the body serialized and the query encoded.
286
+ * @returns The response, with the body unread when `request.stream` is set and as raw bytes otherwise.
287
+ */
288
+ sendRequest(request: HttpRequest): Promise<HttpResponse>;
289
+ /**
290
+ * Makes an API request with automatic retries and exponential backoff.
291
+ *
292
+ * Network errors the transport classifies as retryable, rate limits (HTTP 429) and server errors (HTTP 5xx)
293
+ * are retried up to {@link maxRetries} times. Any other error status is thrown as {@link ApifyApiError} right
294
+ * away. A request whose body is a `Readable` is never retried, since part of the stream has already been
295
+ * consumed by the time the failure shows. Aborting `config.signal` ends the attempt in flight, skips the
296
+ * remaining retries and rejects the call with the signal's `reason`.
297
+ *
298
+ * @template T - Type of the parsed response body.
299
+ * @param config - The request to make.
300
+ * @returns The successful response.
301
+ * @throws {ApifyApiError} When the API responds with an error status the retries could not fix.
302
+ */
303
+ call<T = any>(config: ApifyRequestConfig): Promise<ApifyResponse<T>>;
304
+ /**
305
+ * Prepares the headers and the body of a request.
306
+ *
307
+ * Merges the client's default headers with the per-request ones, header names compared case-insensitively and
308
+ * the per-request values winning. Serializes an object body to JSON, setting `Content-Type: application/json`
309
+ * unless the caller supplied a content type. Runs the body through {@link httpCompressor} unless a
310
+ * `Content-Encoding` header is already set, the body is too small, or its content type says the payload is
311
+ * already compressed. A caller-supplied `Content-Encoding` is forwarded as it is, which is how a pre-encoded
312
+ * body is uploaded, and `Content-Encoding: identity` opts a single request out of compression.
313
+ */
314
+ protected prepareRequest(config: ApifyRequestConfig): Promise<{
315
+ headers: Record<string, string>;
316
+ body: HttpRequestBody | undefined;
317
+ }>;
318
+ /**
319
+ * Appends the query parameters to the URL. `undefined` values are dropped, booleans are sent as `1` and `0`,
320
+ * `Date` values as ISO 8601 strings and arrays comma-separated.
321
+ */
322
+ protected buildUrl(url: string, params?: Record<string, unknown>): string;
323
+ /**
324
+ * Resolves `timeoutSecs` to the number of milliseconds the given attempt gets. A tier name resolves to its
325
+ * configured duration, a number is taken as seconds, and `'noTimeout'` becomes `undefined`. The result doubles
326
+ * with each attempt and is capped at `timeoutMaxMillis`. A requested value above the cap is capped too, which
327
+ * warns once, since it does not take effect in full.
328
+ *
329
+ * @param attempt - Current attempt number, starting at 1.
330
+ * @param timeoutSecs - The request's timeout. Defaults to the `medium` tier.
331
+ */
332
+ protected computeTimeoutMillis(attempt: number, timeoutSecs?: Timeout): number | undefined;
333
+ }