apify-client 3.0.0-beta.112 → 3.0.0-beta.113
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -2
- package/dist/apify_client.d.ts +8 -8
- package/dist/apify_client.js +10 -10
- package/dist/axios.d.ts +2 -0
- package/dist/axios.js +1 -0
- package/dist/bundle.js +31 -30
- package/dist/bundle.js.map +1 -1
- package/dist/http_clients/axios.d.ts +27 -13
- package/dist/http_clients/axios.js +35 -20
- package/dist/http_clients/base.d.ts +2 -2
- package/dist/http_clients/base.js +6 -3
- package/dist/http_clients/fetch.d.ts +52 -0
- package/dist/http_clients/fetch.js +183 -0
- package/dist/http_clients/index.d.ts +2 -2
- package/dist/http_clients/index.js +1 -1
- package/dist/runtime/node.js +34 -11
- package/dist/runtime/types.d.ts +18 -3
- package/dist/runtime/web.js +8 -0
- package/package.json +15 -3
|
@@ -15,26 +15,40 @@ 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
|
-
*
|
|
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
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
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.
|
|
33
|
+
* Network errors are retried, timeouts included, and a stream body is sent without following redirects, since the
|
|
34
|
+
* part of it already sent could not be replayed. The proxy environment variables are not read: pass a proxy agent
|
|
35
|
+
* in {@link AxiosHttpClientOptions.httpAgent} and {@link AxiosHttpClientOptions.httpsAgent} instead.
|
|
36
|
+
*
|
|
37
|
+
* @example
|
|
38
|
+
* ```javascript
|
|
39
|
+
* import { ApifyClient } from 'apify-client';
|
|
40
|
+
* import { AxiosHttpClient } from 'apify-client/axios';
|
|
41
|
+
*
|
|
42
|
+
* const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new AxiosHttpClient() });
|
|
43
|
+
* ```
|
|
27
44
|
*/
|
|
28
45
|
export declare class AxiosHttpClient extends HttpClient {
|
|
29
46
|
#private;
|
|
30
47
|
/** The axios instance the requests go through. */
|
|
31
48
|
axios: AxiosInstance;
|
|
32
|
-
/**
|
|
33
|
-
* Keep-alive agent for plain HTTP, created with the first request in Node.js. It is the same `ProxyAgent` as
|
|
34
|
-
* {@link httpsAgent}, so the socket pool is shared across both schemes.
|
|
35
|
-
*/
|
|
49
|
+
/** Agent for plain HTTP: the one from the options, or a keep-alive one created with the first request in Node.js. */
|
|
36
50
|
httpAgent?: http.Agent;
|
|
37
|
-
/**
|
|
51
|
+
/** Agent for HTTPS: the one from the options, or a keep-alive one created with the first request in Node.js. */
|
|
38
52
|
httpsAgent?: https.Agent;
|
|
39
53
|
constructor(options?: AxiosHttpClientOptions);
|
|
40
54
|
/**
|
|
@@ -49,8 +63,8 @@ export declare class AxiosHttpClient extends HttpClient {
|
|
|
49
63
|
*/
|
|
50
64
|
isRetryableTransportError(error: unknown): boolean;
|
|
51
65
|
/**
|
|
52
|
-
* Destroys the keep-alive agents, closing every pooled socket. A client that never sent a request in
|
|
53
|
-
* has nothing to close.
|
|
66
|
+
* Destroys the built-in keep-alive agents, closing every pooled socket. A client that never sent a request in
|
|
67
|
+
* Node.js has nothing to close, and agents passed in the options are left to their owner.
|
|
54
68
|
*/
|
|
55
69
|
close(): Promise<void>;
|
|
56
70
|
/**
|
|
@@ -4,29 +4,38 @@ import { ApifyClientError } from '../apify_client_error.js';
|
|
|
4
4
|
import { isStream } from '../utils.js';
|
|
5
5
|
import { HttpClient } from './base.js';
|
|
6
6
|
/**
|
|
7
|
-
*
|
|
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.
|
|
8
10
|
*
|
|
9
|
-
* It inherits the request pipeline from {@link HttpClient} and adds the transport: in Node.js, keep-alive agents
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
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.
|
|
13
|
+
* Network errors are retried, timeouts included, and a stream body is sent without following redirects, since the
|
|
14
|
+
* part of it already sent could not be replayed. The proxy environment variables are not read: pass a proxy agent
|
|
15
|
+
* in {@link AxiosHttpClientOptions.httpAgent} and {@link AxiosHttpClientOptions.httpsAgent} instead.
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* ```javascript
|
|
19
|
+
* import { ApifyClient } from 'apify-client';
|
|
20
|
+
* import { AxiosHttpClient } from 'apify-client/axios';
|
|
21
|
+
*
|
|
22
|
+
* const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new AxiosHttpClient() });
|
|
23
|
+
* ```
|
|
14
24
|
*/
|
|
15
25
|
export class AxiosHttpClient extends HttpClient {
|
|
16
26
|
/** The axios instance the requests go through. */
|
|
17
27
|
axios;
|
|
18
|
-
/**
|
|
19
|
-
* Keep-alive agent for plain HTTP, created with the first request in Node.js. It is the same `ProxyAgent` as
|
|
20
|
-
* {@link httpsAgent}, so the socket pool is shared across both schemes.
|
|
21
|
-
*/
|
|
28
|
+
/** Agent for plain HTTP: the one from the options, or a keep-alive one created with the first request in Node.js. */
|
|
22
29
|
httpAgent;
|
|
23
|
-
/**
|
|
30
|
+
/** Agent for HTTPS: the one from the options, or a keep-alive one created with the first request in Node.js. */
|
|
24
31
|
httpsAgent;
|
|
32
|
+
/** The built-in agents, which are the ones `close()` destroys. */
|
|
33
|
+
#ownAgents = [];
|
|
25
34
|
#httpAgentsPromise;
|
|
26
35
|
constructor(options = {}) {
|
|
27
36
|
super(options);
|
|
28
37
|
this.axios = axios.create({
|
|
29
|
-
//
|
|
38
|
+
// Axios cannot tunnel HTTPS through a proxy on its own, so a proxy is left to the agents.
|
|
30
39
|
proxy: false,
|
|
31
40
|
validateStatus: null,
|
|
32
41
|
// The shared pipeline serializes and parses the bodies, so axios only moves bytes.
|
|
@@ -42,6 +51,8 @@ export class AxiosHttpClient extends HttpClient {
|
|
|
42
51
|
});
|
|
43
52
|
// The pipeline merges every header the client sends, so the axios defaults would only get in the way.
|
|
44
53
|
this.axios.defaults.headers = new AxiosHeaders();
|
|
54
|
+
this.httpAgent = options.httpAgent;
|
|
55
|
+
this.httpsAgent = options.httpsAgent;
|
|
45
56
|
for (const interceptor of options.requestInterceptors ?? []) {
|
|
46
57
|
this.axios.interceptors.request.use(interceptor);
|
|
47
58
|
}
|
|
@@ -69,14 +80,14 @@ export class AxiosHttpClient extends HttpClient {
|
|
|
69
80
|
return typeof error.request === 'object' && error.request !== null && error.config != null;
|
|
70
81
|
}
|
|
71
82
|
/**
|
|
72
|
-
* Destroys the keep-alive agents, closing every pooled socket. A client that never sent a request in
|
|
73
|
-
* has nothing to close.
|
|
83
|
+
* Destroys the built-in keep-alive agents, closing every pooled socket. A client that never sent a request in
|
|
84
|
+
* Node.js has nothing to close, and agents passed in the options are left to their owner.
|
|
74
85
|
*/
|
|
75
86
|
async close() {
|
|
76
87
|
// A failed initialization left nothing to release, and its error belongs to the request that hit it.
|
|
77
88
|
await this.#httpAgentsPromise?.catch(() => { });
|
|
78
|
-
this.
|
|
79
|
-
|
|
89
|
+
for (const agent of this.#ownAgents.splice(0))
|
|
90
|
+
agent.destroy();
|
|
80
91
|
}
|
|
81
92
|
/**
|
|
82
93
|
* Sends the request through axios and hands the raw response back. A stream body is sent without following
|
|
@@ -119,11 +130,15 @@ export class AxiosHttpClient extends HttpClient {
|
|
|
119
130
|
}
|
|
120
131
|
async #initHttpAgents() {
|
|
121
132
|
const agents = await runtime.createHttpAgents({ timeoutMillis: this.timeoutMaxMillis });
|
|
122
|
-
if (
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
133
|
+
if (agents) {
|
|
134
|
+
this.httpAgent ??= this.#own(agents.httpAgent);
|
|
135
|
+
this.httpsAgent ??= this.#own(agents.httpsAgent);
|
|
136
|
+
}
|
|
126
137
|
this.axios.defaults.httpAgent = this.httpAgent;
|
|
127
138
|
this.axios.defaults.httpsAgent = this.httpsAgent;
|
|
128
139
|
}
|
|
140
|
+
#own(agent) {
|
|
141
|
+
this.#ownAgents.push(agent);
|
|
142
|
+
return agent;
|
|
143
|
+
}
|
|
129
144
|
}
|
|
@@ -243,7 +243,7 @@ export interface HttpClientOptions {
|
|
|
243
243
|
* ```javascript
|
|
244
244
|
* import { ApifyClient, HttpClient } from 'apify-client';
|
|
245
245
|
*
|
|
246
|
-
* class
|
|
246
|
+
* class MyFetchHttpClient extends HttpClient {
|
|
247
247
|
* async sendRequest({ method, url, headers, body, timeoutMillis, followRedirects, signal }) {
|
|
248
248
|
* const signals = signal ? [signal] : [];
|
|
249
249
|
* if (timeoutMillis !== undefined) signals.push(AbortSignal.timeout(timeoutMillis));
|
|
@@ -267,7 +267,7 @@ export interface HttpClientOptions {
|
|
|
267
267
|
* }
|
|
268
268
|
* }
|
|
269
269
|
*
|
|
270
|
-
* const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new
|
|
270
|
+
* const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new MyFetchHttpClient() });
|
|
271
271
|
* ```
|
|
272
272
|
*/
|
|
273
273
|
export declare abstract class HttpClient {
|
|
@@ -54,7 +54,7 @@ const UNSERIALIZABLE_OBJECT_TAGS = new Set(['FormData', 'ReadableStream']);
|
|
|
54
54
|
* ```javascript
|
|
55
55
|
* import { ApifyClient, HttpClient } from 'apify-client';
|
|
56
56
|
*
|
|
57
|
-
* class
|
|
57
|
+
* class MyFetchHttpClient extends HttpClient {
|
|
58
58
|
* async sendRequest({ method, url, headers, body, timeoutMillis, followRedirects, signal }) {
|
|
59
59
|
* const signals = signal ? [signal] : [];
|
|
60
60
|
* if (timeoutMillis !== undefined) signals.push(AbortSignal.timeout(timeoutMillis));
|
|
@@ -78,7 +78,7 @@ const UNSERIALIZABLE_OBJECT_TAGS = new Set(['FormData', 'ReadableStream']);
|
|
|
78
78
|
* }
|
|
79
79
|
* }
|
|
80
80
|
*
|
|
81
|
-
* const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new
|
|
81
|
+
* const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new MyFetchHttpClient() });
|
|
82
82
|
* ```
|
|
83
83
|
*/
|
|
84
84
|
export class HttpClient {
|
|
@@ -471,7 +471,10 @@ export class HttpClient {
|
|
|
471
471
|
}
|
|
472
472
|
#onRequestRetry(error, attempt) {
|
|
473
473
|
if (attempt === Math.round(this.maxRetries / 2)) {
|
|
474
|
-
|
|
474
|
+
// A failed `fetch` names the network error only in its `cause`, and Bun gives its errors no stack.
|
|
475
|
+
const { stack, cause } = error;
|
|
476
|
+
const causedBy = cause instanceof Error ? `\nCaused by: ${cause.stack ?? cause}` : '';
|
|
477
|
+
this.logger.warning(`API request failed ${attempt} times. Max attempts: ${this.maxRetries + 1}.\nCause:${stack ?? error}${causedBy}`);
|
|
475
478
|
}
|
|
476
479
|
}
|
|
477
480
|
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import type { HttpClientOptions, HttpRequest, HttpResponse } from './base.js';
|
|
2
|
+
import { HttpClient } from './base.js';
|
|
3
|
+
/**
|
|
4
|
+
* A function with the signature of the global [`fetch`](https://developer.mozilla.org/docs/Web/API/Window/fetch).
|
|
5
|
+
*/
|
|
6
|
+
export type FetchFunction = typeof globalThis.fetch;
|
|
7
|
+
/**
|
|
8
|
+
* Configuration of {@link FetchHttpClient}.
|
|
9
|
+
*/
|
|
10
|
+
export interface FetchHttpClientOptions extends HttpClientOptions {
|
|
11
|
+
/**
|
|
12
|
+
* The `fetch` implementation the requests go through. Pass a wrapper around the global `fetch` to adjust every
|
|
13
|
+
* request, or the `fetch` of another library, such as `undici` with a dispatcher of your own, to control the
|
|
14
|
+
* connections. A stream body reaches it as an async iterable of byte chunks, or as the stream itself in Bun.
|
|
15
|
+
* @default globalThis.fetch
|
|
16
|
+
*/
|
|
17
|
+
fetch?: FetchFunction;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The default HTTP client of {@link ApifyClient}, built on the `fetch` of the runtime, so it works the same way in
|
|
21
|
+
* Node.js, browsers and edge runtimes and brings no dependency of its own.
|
|
22
|
+
*
|
|
23
|
+
* It inherits the request pipeline from {@link HttpClient} and adds the transport. Network errors are retried,
|
|
24
|
+
* timeouts included, and a stream body is sent without following redirects, since the part of it already sent could
|
|
25
|
+
* not be replayed. The timeout of a request runs until the response headers arrive and starts over with every chunk
|
|
26
|
+
* of the response body and of a stream body, so a large download or upload does not time out while it makes progress.
|
|
27
|
+
*
|
|
28
|
+
* In Node.js, `fetch` keeps connections alive on its own, and goes through a proxy only when Node.js is told to
|
|
29
|
+
* read the `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` environment variables: start it with `NODE_USE_ENV_PROXY=1`
|
|
30
|
+
* (Node.js 22.21 and 24.0) or `--use-env-proxy` (Node.js 22.21 and 24.5).
|
|
31
|
+
*/
|
|
32
|
+
export declare class FetchHttpClient extends HttpClient {
|
|
33
|
+
#private;
|
|
34
|
+
constructor(options?: FetchHttpClientOptions);
|
|
35
|
+
/**
|
|
36
|
+
* A timeout is the `TimeoutError` this client aborts a late request with, or a `fetch` failure caused by one of
|
|
37
|
+
* the connection, headers and body timeouts of Node.js.
|
|
38
|
+
*/
|
|
39
|
+
isTimeoutError(error: unknown): boolean;
|
|
40
|
+
/**
|
|
41
|
+
* A network failure is the `TypeError` that `fetch` rejects with: a connection that could not be made, dropped
|
|
42
|
+
* mid-way or timed out. In Node.js it carries the failure as its `cause`, which tells it apart from a request
|
|
43
|
+
* that was never sent, such as one with an invalid URL. Bun rejects with an `Error` that has a `code` instead.
|
|
44
|
+
*/
|
|
45
|
+
isRetryableTransportError(error: unknown): boolean;
|
|
46
|
+
/**
|
|
47
|
+
* Sends the request through `fetch` and hands the raw response back. A stream body is sent without following
|
|
48
|
+
* redirects, and so is a request with `followRedirects: false`. A browser hides such a redirect response from
|
|
49
|
+
* the page, so there it fails the request.
|
|
50
|
+
*/
|
|
51
|
+
sendRequest(request: HttpRequest): Promise<HttpResponse>;
|
|
52
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
import { runtime } from '#runtime';
|
|
2
|
+
import { ApifyClientError } from '../apify_client_error.js';
|
|
3
|
+
import { isStream } from '../utils.js';
|
|
4
|
+
import { HttpClient } from './base.js';
|
|
5
|
+
/** Error codes of the timeouts that Node.js reports as the `cause` of a failed `fetch`. */
|
|
6
|
+
const TIMEOUT_ERROR_CODES = new Set([
|
|
7
|
+
'ETIMEDOUT',
|
|
8
|
+
'UND_ERR_CONNECT_TIMEOUT',
|
|
9
|
+
'UND_ERR_HEADERS_TIMEOUT',
|
|
10
|
+
'UND_ERR_BODY_TIMEOUT',
|
|
11
|
+
]);
|
|
12
|
+
/** Error codes of a request that Node.js or Bun refused to send, so sending it again fails the same way. */
|
|
13
|
+
const INVALID_REQUEST_ERROR_CODES = new Set([
|
|
14
|
+
'ERR_INVALID_URL',
|
|
15
|
+
'ERR_INVALID_ARG_TYPE',
|
|
16
|
+
'ERR_INVALID_ARG_VALUE',
|
|
17
|
+
'UND_ERR_INVALID_ARG',
|
|
18
|
+
'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH',
|
|
19
|
+
]);
|
|
20
|
+
/**
|
|
21
|
+
* The default HTTP client of {@link ApifyClient}, built on the `fetch` of the runtime, so it works the same way in
|
|
22
|
+
* Node.js, browsers and edge runtimes and brings no dependency of its own.
|
|
23
|
+
*
|
|
24
|
+
* It inherits the request pipeline from {@link HttpClient} and adds the transport. Network errors are retried,
|
|
25
|
+
* timeouts included, and a stream body is sent without following redirects, since the part of it already sent could
|
|
26
|
+
* not be replayed. The timeout of a request runs until the response headers arrive and starts over with every chunk
|
|
27
|
+
* of the response body and of a stream body, so a large download or upload does not time out while it makes progress.
|
|
28
|
+
*
|
|
29
|
+
* In Node.js, `fetch` keeps connections alive on its own, and goes through a proxy only when Node.js is told to
|
|
30
|
+
* read the `HTTP_PROXY`, `HTTPS_PROXY` and `NO_PROXY` environment variables: start it with `NODE_USE_ENV_PROXY=1`
|
|
31
|
+
* (Node.js 22.21 and 24.0) or `--use-env-proxy` (Node.js 22.21 and 24.5).
|
|
32
|
+
*/
|
|
33
|
+
export class FetchHttpClient extends HttpClient {
|
|
34
|
+
#fetch;
|
|
35
|
+
constructor(options = {}) {
|
|
36
|
+
super(options);
|
|
37
|
+
this.#fetch = options.fetch;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* A timeout is the `TimeoutError` this client aborts a late request with, or a `fetch` failure caused by one of
|
|
41
|
+
* the connection, headers and body timeouts of Node.js.
|
|
42
|
+
*/
|
|
43
|
+
isTimeoutError(error) {
|
|
44
|
+
if (super.isTimeoutError(error))
|
|
45
|
+
return true;
|
|
46
|
+
const code = causeCode(error);
|
|
47
|
+
return code !== undefined && TIMEOUT_ERROR_CODES.has(code);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* A network failure is the `TypeError` that `fetch` rejects with: a connection that could not be made, dropped
|
|
51
|
+
* mid-way or timed out. In Node.js it carries the failure as its `cause`, which tells it apart from a request
|
|
52
|
+
* that was never sent, such as one with an invalid URL. Bun rejects with an `Error` that has a `code` instead.
|
|
53
|
+
*/
|
|
54
|
+
isRetryableTransportError(error) {
|
|
55
|
+
if (this.isTimeoutError(error))
|
|
56
|
+
return true;
|
|
57
|
+
const code = causeCode(error) ?? errorCode(error);
|
|
58
|
+
if (code !== undefined && INVALID_REQUEST_ERROR_CODES.has(code))
|
|
59
|
+
return false;
|
|
60
|
+
if (runtime.fetchFailsWithCause)
|
|
61
|
+
return error instanceof TypeError && error.cause !== undefined;
|
|
62
|
+
// Browsers and Deno fail with a bare `TypeError` whatever the reason, and Bun with an error that has a `code`.
|
|
63
|
+
return error instanceof TypeError || code !== undefined;
|
|
64
|
+
}
|
|
65
|
+
/**
|
|
66
|
+
* Sends the request through `fetch` and hands the raw response back. A stream body is sent without following
|
|
67
|
+
* redirects, and so is a request with `followRedirects: false`. A browser hides such a redirect response from
|
|
68
|
+
* the page, so there it fails the request.
|
|
69
|
+
*/
|
|
70
|
+
async sendRequest(request) {
|
|
71
|
+
const { method, url, headers, body, timeoutMillis, stream, followRedirects, signal } = request;
|
|
72
|
+
// `AbortSignal.timeout()` could neither be restarted nor called off.
|
|
73
|
+
const timeout = new AbortController();
|
|
74
|
+
let timer;
|
|
75
|
+
let settled = false;
|
|
76
|
+
const restartTimeout = () => {
|
|
77
|
+
clearTimeout(timer);
|
|
78
|
+
// The transport may still read a stream body after the response arrived.
|
|
79
|
+
if (timeoutMillis === undefined || settled)
|
|
80
|
+
return;
|
|
81
|
+
timer = setTimeout(() => timeout.abort(new DOMException(`timeout of ${timeoutMillis}ms exceeded`, 'TimeoutError')), timeoutMillis);
|
|
82
|
+
};
|
|
83
|
+
restartTimeout();
|
|
84
|
+
try {
|
|
85
|
+
// Browsers and Deno reject an invalid URL with the same bare `TypeError` as a network failure.
|
|
86
|
+
const baseUrl = globalThis.location?.href;
|
|
87
|
+
if (!runtime.fetchFailsWithCause && !URL.canParse(url, baseUrl)) {
|
|
88
|
+
throw Object.assign(new TypeError(`Invalid URL: ${url}`), { code: 'ERR_INVALID_URL' });
|
|
89
|
+
}
|
|
90
|
+
const response = await (this.#fetch ?? globalThis.fetch)(url, {
|
|
91
|
+
method,
|
|
92
|
+
headers,
|
|
93
|
+
// Node.js reads an async iterable, which the DOM types do not know about.
|
|
94
|
+
body: (isStream(body) && !isBun ? withProgress(body, restartTimeout) : body),
|
|
95
|
+
redirect: followRedirects && !isStream(body) ? 'follow' : 'manual',
|
|
96
|
+
signal: signal ? AbortSignal.any([signal, timeout.signal]) : timeout.signal,
|
|
97
|
+
// Required for a stream body, and ignored for any other.
|
|
98
|
+
...(isStream(body) ? { duplex: 'half' } : {}),
|
|
99
|
+
});
|
|
100
|
+
// `redirect: 'manual'` resolves to an opaque response with status 0 in a browser.
|
|
101
|
+
if (response.type === 'opaqueredirect') {
|
|
102
|
+
throw new ApifyClientError(`${method} ${url} responded with a redirect, which the client does not follow.`);
|
|
103
|
+
}
|
|
104
|
+
return {
|
|
105
|
+
status: response.status,
|
|
106
|
+
headers: toResponseHeaders(response.headers),
|
|
107
|
+
// The timeout covers a streamed response only until its headers, and the caller's signal throughout.
|
|
108
|
+
body: stream ? runtime.readableFromWeb(response.body) : await readBody(response, restartTimeout),
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
catch (error) {
|
|
112
|
+
if (!this.#fetch && this.isRetryableTransportError(error))
|
|
113
|
+
this.#warnAboutUnusedProxy();
|
|
114
|
+
throw error;
|
|
115
|
+
}
|
|
116
|
+
finally {
|
|
117
|
+
settled = true;
|
|
118
|
+
clearTimeout(timer);
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
/** A proxy the environment names and Node.js ignores is the likeliest reason for a connection to fail. */
|
|
122
|
+
#warnAboutUnusedProxy() {
|
|
123
|
+
const hint = runtime.unusedProxyHint();
|
|
124
|
+
if (hint)
|
|
125
|
+
this.logger.warningOnce(hint);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
/** Bun reads a stream body ahead of sending it, so reading it there says nothing about the progress. */
|
|
129
|
+
const isBun = 'Bun' in globalThis;
|
|
130
|
+
/** A larger chunk of a stream body is passed on in pieces, since a `Blob` held in memory arrives as a single one. */
|
|
131
|
+
const MAX_BODY_CHUNK_BYTES = 64 * 1024;
|
|
132
|
+
/** Passes a stream body on piece by piece, so that a large upload counts as alive for as long as it is being read. */
|
|
133
|
+
async function* withProgress(body, onChunk) {
|
|
134
|
+
for await (const chunk of body) {
|
|
135
|
+
// Deno refuses the string chunks of a stream with an encoding.
|
|
136
|
+
const bytes = typeof chunk === 'string' ? new TextEncoder().encode(chunk) : chunk;
|
|
137
|
+
if (!(bytes instanceof Uint8Array) || bytes.byteLength <= MAX_BODY_CHUNK_BYTES) {
|
|
138
|
+
onChunk();
|
|
139
|
+
yield bytes;
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
for (let offset = 0; offset < bytes.byteLength; offset += MAX_BODY_CHUNK_BYTES) {
|
|
143
|
+
onChunk();
|
|
144
|
+
yield bytes.subarray(offset, offset + MAX_BODY_CHUNK_BYTES);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
/**
|
|
149
|
+
* Reads the response body chunk by chunk, so that a large download counts as alive for as long as bytes arrive.
|
|
150
|
+
*/
|
|
151
|
+
async function readBody(response, onChunk) {
|
|
152
|
+
const chunks = [];
|
|
153
|
+
let length = 0;
|
|
154
|
+
const reader = response.body?.getReader();
|
|
155
|
+
for (let chunk = await reader?.read(); chunk && !chunk.done; chunk = await reader?.read()) {
|
|
156
|
+
onChunk();
|
|
157
|
+
chunks.push(chunk.value);
|
|
158
|
+
length += chunk.value.byteLength;
|
|
159
|
+
}
|
|
160
|
+
const bytes = new Uint8Array(length);
|
|
161
|
+
let offset = 0;
|
|
162
|
+
for (const chunk of chunks) {
|
|
163
|
+
bytes.set(chunk, offset);
|
|
164
|
+
offset += chunk.byteLength;
|
|
165
|
+
}
|
|
166
|
+
return runtime.isNode ? Buffer.from(bytes.buffer) : bytes.buffer;
|
|
167
|
+
}
|
|
168
|
+
function toResponseHeaders(headers) {
|
|
169
|
+
const result = Object.fromEntries(headers);
|
|
170
|
+
// `fetch` joins repeated headers with a comma, which a cookie's `Expires` date makes ambiguous.
|
|
171
|
+
const cookies = headers.getSetCookie?.() ?? [];
|
|
172
|
+
if (cookies.length > 0)
|
|
173
|
+
result['set-cookie'] = cookies;
|
|
174
|
+
return result;
|
|
175
|
+
}
|
|
176
|
+
/** Reads the `code` of the error that caused a `fetch` failure, which is where Node.js puts the network error. */
|
|
177
|
+
function causeCode(error) {
|
|
178
|
+
return errorCode(error instanceof Error ? error.cause : undefined);
|
|
179
|
+
}
|
|
180
|
+
function errorCode(error) {
|
|
181
|
+
const code = error?.code;
|
|
182
|
+
return typeof code === 'string' ? code : undefined;
|
|
183
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type { AxiosHttpClientOptions, RequestInterceptorFunction } from './axios.js';
|
|
2
|
-
export { AxiosHttpClient } from './axios.js';
|
|
3
1
|
export type { ApifyRequestConfig, ApifyResponse, ApifyResponseType, HttpClientOptions, HttpMethod, HttpRequest, HttpRequestBody, HttpResponse, HttpResponseBody, HttpResponseHeaders, } from './base.js';
|
|
4
2
|
export { HttpClient } from './base.js';
|
|
3
|
+
export type { FetchFunction, FetchHttpClientOptions } from './fetch.js';
|
|
4
|
+
export { FetchHttpClient } from './fetch.js';
|
package/dist/runtime/node.js
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import https from 'node:https';
|
|
1
3
|
import os from 'node:os';
|
|
2
4
|
import { Readable } from 'node:stream';
|
|
3
5
|
import { brotliCompress, constants, gzip, zstdCompress } from 'node:zlib';
|
|
6
|
+
const isBunOrDeno = Boolean(process.versions.bun || process.versions.deno);
|
|
4
7
|
/**
|
|
5
8
|
* The Node.js implementation of {@link Runtime}. Deno and Bun resolve the `node` condition too and
|
|
6
9
|
* provide the built-ins it uses.
|
|
7
10
|
*/
|
|
8
11
|
export const runtime = {
|
|
9
12
|
isNode: true,
|
|
13
|
+
fetchFailsWithCause: !isBunOrDeno,
|
|
10
14
|
platform: `${os.platform()}; Node/${process.version}`,
|
|
11
15
|
async compress(data, { algorithm, quality }) {
|
|
12
16
|
return new Promise((resolve, reject) => {
|
|
@@ -27,9 +31,6 @@ export const runtime = {
|
|
|
27
31
|
});
|
|
28
32
|
},
|
|
29
33
|
async createHttpAgents({ timeoutMillis }) {
|
|
30
|
-
// Loaded on the first request rather than with the client: the proxy support pulls in a sizeable
|
|
31
|
-
// dependency tree that a client which never sends a request should not pay for.
|
|
32
|
-
const { ProxyAgent } = await import('proxy-agent');
|
|
33
34
|
// We want to keep sockets alive for better performance.
|
|
34
35
|
const agentOptions = {
|
|
35
36
|
keepAlive: true,
|
|
@@ -44,15 +45,37 @@ export const runtime = {
|
|
|
44
45
|
maxFreeSockets: 256,
|
|
45
46
|
// LIFO scheduling - reuse most recently used sockets for better performance
|
|
46
47
|
scheduling: 'lifo',
|
|
48
|
+
// Disable Nagle's algorithm for lower latency. The agent hands the option to `net.createConnection()`.
|
|
49
|
+
noDelay: true,
|
|
47
50
|
};
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
51
|
+
return { httpAgent: new http.Agent(agentOptions), httpsAgent: new https.Agent(agentOptions) };
|
|
52
|
+
},
|
|
53
|
+
readableFromWeb(body) {
|
|
54
|
+
if (!body)
|
|
55
|
+
return Readable.from([]);
|
|
56
|
+
return Readable.fromWeb(body);
|
|
57
|
+
},
|
|
58
|
+
unusedProxyHint() {
|
|
59
|
+
const names = ['HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy'].filter((name) => process.env[name]);
|
|
60
|
+
if (names.length === 0)
|
|
61
|
+
return undefined;
|
|
62
|
+
// The `fetch` of Bun and Deno reads these variables on its own.
|
|
63
|
+
if (isBunOrDeno)
|
|
64
|
+
return undefined;
|
|
65
|
+
const [major, minor] = process.versions.node.split('.').map(Number);
|
|
66
|
+
const supported = major >= 24 || (major === 22 && minor >= 21);
|
|
67
|
+
const flags = [...process.execArgv, ...(process.env.NODE_OPTIONS ?? '').split(/\s+/)];
|
|
68
|
+
const enabled = process.env.NODE_USE_ENV_PROXY === '1' || flags.includes('--use-env-proxy');
|
|
69
|
+
// An older Node.js ignores the switch, so the proxy stays unused there even with it set.
|
|
70
|
+
if (supported && enabled)
|
|
71
|
+
return undefined;
|
|
72
|
+
const fix = supported
|
|
73
|
+
? 'Start Node.js with NODE_USE_ENV_PROXY=1 to send the requests through it.'
|
|
74
|
+
: `Node.js ${process.versions.node} cannot route fetch() through it: upgrade to Node.js 22.21 or 24, ` +
|
|
75
|
+
'then start it with NODE_USE_ENV_PROXY=1.';
|
|
76
|
+
return (`The request failed, and the proxy set in ${names[0]} was not used, since fetch() in Node.js ignores the ` +
|
|
77
|
+
`proxy environment variables by default. ${fix} ` +
|
|
78
|
+
'See https://docs.apify.com/api/client/js/docs/concepts/custom-http-clients#proxies for the other options.');
|
|
56
79
|
},
|
|
57
80
|
openBlobBody(blob, onSourceError) {
|
|
58
81
|
return Readable.from(readBlob(blob, onSourceError), { objectMode: false });
|
package/dist/runtime/types.d.ts
CHANGED
|
@@ -12,7 +12,7 @@ export interface CompressionOptions {
|
|
|
12
12
|
quality: number;
|
|
13
13
|
}
|
|
14
14
|
/**
|
|
15
|
-
* The agents
|
|
15
|
+
* The agents the Node.js adapter of axios sends requests through.
|
|
16
16
|
* @internal
|
|
17
17
|
*/
|
|
18
18
|
export interface HttpAgents {
|
|
@@ -32,6 +32,11 @@ export interface Runtime {
|
|
|
32
32
|
* streaming, the `stream` record option and request body compression are gated on it.
|
|
33
33
|
*/
|
|
34
34
|
isNode: boolean;
|
|
35
|
+
/**
|
|
36
|
+
* Whether a failed `fetch` rejects with a `TypeError` that names the network error as its `cause`, which is
|
|
37
|
+
* what Node.js does. Bun and Deno resolve the `node` condition too, and their `fetch` does not.
|
|
38
|
+
*/
|
|
39
|
+
fetchFailsWithCause: boolean;
|
|
35
40
|
/**
|
|
36
41
|
* The platform part of the `User-Agent` header, or `undefined` where the runtime does not let a client
|
|
37
42
|
* set that header (browsers).
|
|
@@ -44,12 +49,22 @@ export interface Runtime {
|
|
|
44
49
|
*/
|
|
45
50
|
compress(data: Uint8Array, options: CompressionOptions): Promise<Buffer>;
|
|
46
51
|
/**
|
|
47
|
-
* Creates the agents
|
|
48
|
-
* axios does not use agents.
|
|
52
|
+
* Creates the keep-alive agents the Node.js adapter of axios sends requests through, or resolves to `undefined`
|
|
53
|
+
* where axios does not use agents.
|
|
49
54
|
*/
|
|
50
55
|
createHttpAgents(options: {
|
|
51
56
|
timeoutMillis: number;
|
|
52
57
|
}): Promise<HttpAgents | undefined>;
|
|
58
|
+
/**
|
|
59
|
+
* Wraps the body of a `fetch` response in a `Readable`, an empty one for a response without a body. Throws
|
|
60
|
+
* where the runtime has no `Readable`, since streamed responses are a Node.js feature.
|
|
61
|
+
*/
|
|
62
|
+
readableFromWeb(body: ReadableStream<Uint8Array> | null): Readable;
|
|
63
|
+
/**
|
|
64
|
+
* Explains how to make `fetch` use the proxy named in the environment variables, or returns `undefined` when
|
|
65
|
+
* none is set, the runtime already honors them, or it has no environment to read.
|
|
66
|
+
*/
|
|
67
|
+
unusedProxyHint(): string | undefined;
|
|
53
68
|
/**
|
|
54
69
|
* Opens a `Blob` request body for one attempt. The Node.js implementation reads the blob into a `Readable` and
|
|
55
70
|
* reports an error the blob raises while it is read to `onSourceError` before the stream fails with it, so the
|
package/dist/runtime/web.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
export const runtime = {
|
|
5
5
|
isNode: false,
|
|
6
|
+
fetchFailsWithCause: false,
|
|
6
7
|
// Browsers do not let a page set the `User-Agent` header.
|
|
7
8
|
platform: undefined,
|
|
8
9
|
// No request compression: brotli, gzip and zstd have no Web API, and a `content-encoding` request header is not
|
|
@@ -15,6 +16,13 @@ export const runtime = {
|
|
|
15
16
|
async createHttpAgents() {
|
|
16
17
|
return undefined;
|
|
17
18
|
},
|
|
19
|
+
readableFromWeb() {
|
|
20
|
+
throw new Error('Streamed responses are only available in Node.js.');
|
|
21
|
+
},
|
|
22
|
+
// A browser applies the proxy settings of the system on its own.
|
|
23
|
+
unusedProxyHint() {
|
|
24
|
+
return undefined;
|
|
25
|
+
},
|
|
18
26
|
openBlobBody(blob) {
|
|
19
27
|
return blob;
|
|
20
28
|
},
|