apify-client 3.0.0-beta.12 → 3.0.0-beta.121

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