apify-client 3.0.0-beta.22 → 3.0.0-beta.24

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 (45) hide show
  1. package/README.md +6 -0
  2. package/dist/apify_api_error.d.ts +3 -3
  3. package/dist/apify_api_error.js +11 -4
  4. package/dist/apify_client.d.ts +79 -5
  5. package/dist/apify_client.js +92 -16
  6. package/dist/base/api_client.d.ts +1 -1
  7. package/dist/bundle.js +14 -14
  8. package/dist/bundle.js.map +1 -1
  9. package/dist/generated/schemas.d.ts +110 -110
  10. package/dist/http_clients/axios.d.ts +60 -0
  11. package/dist/http_clients/axios.js +117 -0
  12. package/dist/http_clients/base.d.ts +333 -0
  13. package/dist/http_clients/base.js +583 -0
  14. package/dist/http_clients/index.d.ts +4 -0
  15. package/dist/http_clients/index.js +2 -0
  16. package/dist/http_compressors/base.d.ts +40 -0
  17. package/dist/http_compressors/base.js +9 -0
  18. package/dist/http_compressors/brotli.d.ts +33 -0
  19. package/dist/http_compressors/brotli.js +39 -0
  20. package/dist/http_compressors/gzip.d.ts +33 -0
  21. package/dist/http_compressors/gzip.js +39 -0
  22. package/dist/http_compressors/index.d.ts +6 -0
  23. package/dist/http_compressors/index.js +2 -0
  24. package/dist/http_compressors/resolve.d.ts +23 -0
  25. package/dist/http_compressors/resolve.js +27 -0
  26. package/dist/index.d.ts +3 -1
  27. package/dist/index.js +3 -1
  28. package/dist/invalid_response_body_error.d.ts +13 -0
  29. package/dist/invalid_response_body_error.js +17 -0
  30. package/dist/resource_clients/actor.js +2 -4
  31. package/dist/resource_clients/dataset.js +4 -3
  32. package/dist/resource_clients/key_value_store.js +1 -1
  33. package/dist/resource_clients/run.d.ts +1 -1
  34. package/dist/resource_clients/run.js +1 -2
  35. package/dist/resource_clients/task.js +1 -2
  36. package/dist/runtime/node.js +10 -19
  37. package/dist/runtime/types.d.ts +12 -10
  38. package/dist/runtime/web.js +4 -3
  39. package/dist/utils.d.ts +14 -7
  40. package/dist/utils.js +9 -15
  41. package/package.json +1 -3
  42. package/dist/http_client.d.ts +0 -55
  43. package/dist/http_client.js +0 -260
  44. package/dist/interceptors.d.ts +0 -19
  45. package/dist/interceptors.js +0 -123
package/README.md CHANGED
@@ -59,6 +59,12 @@ By default, it will retry up to 8 times. First retry will be attempted after ~50
59
59
  and so on. You can configure those parameters using the `maxRetries` and `minDelayBetweenRetriesMillis`
60
60
  options of the `ApifyClient` constructor.
61
61
 
62
+ ### Pluggable HTTP client
63
+
64
+ The client ships with an axios-based HTTP client and accepts a custom one. Extend `HttpClient`, implement
65
+ `sendRequest()` over the HTTP library of your choice and plug it in with `ApifyClient.withCustomHttpClient()`. The
66
+ custom client inherits the retries, timeouts, compression and error handling of the built-in one.
67
+
62
68
  ### Convenience functions and options
63
69
 
64
70
  Some actions can't be performed by the API itself, such as indefinite waiting for an actor run to finish
@@ -1,5 +1,5 @@
1
- import type { AxiosResponse } from 'axios';
2
1
  import type { LiteralUnion } from 'type-fest';
2
+ import type { ApifyResponse } from './http_clients/base.js';
3
3
  import type { ApifyApiErrorType } from './models.js';
4
4
  export type { ApifyApiErrorType } from './models.js';
5
5
  /**
@@ -58,12 +58,12 @@ export declare class ApifyApiError extends Error {
58
58
  /**
59
59
  * @hidden
60
60
  */
61
- constructor(response: AxiosResponse, attempt: number);
61
+ constructor(response: ApifyResponse, attempt: number);
62
62
  /**
63
63
  * Creates the error for a failed response as an instance of the subclass matching its HTTP status code.
64
64
  * @hidden
65
65
  */
66
- static fromResponse(response: AxiosResponse, attempt: number): ApifyApiError;
66
+ static fromResponse(response: ApifyResponse, attempt: number): ApifyApiError;
67
67
  }
68
68
  /**
69
69
  * Thrown when the Apify API responds with HTTP 400 Bad Request, typically because the request
@@ -6,9 +6,16 @@ import { isBuffer } from './utils.js';
6
6
  * 2: "ActorCollectionClient"
7
7
  * 3: undefined
8
8
  * 4: "listResources"
9
+ *
10
+ * The error is created inside the HTTP client's pipeline, whose frames sit above the resource client's. The
11
+ * pipeline's own methods are private, so V8 prints them with a `#` that no method name can match. Its public
12
+ * `call()` prints under the name of the transport's class, which can be anything, so the lookaheads skip a class
13
+ * named after `HttpClient` and the method `call`. A transport named `SomethingClient` whose `call()` override
14
+ * awaits a helper of its own is reported under that helper. `ActorClient.call()` and `TaskClient.call()` reach the
15
+ * pipeline through `start()`, whose frame sits closer to the error and matches first.
9
16
  * @private
10
17
  */
11
- const CLIENT_METHOD_REGEX = /at( async)? ([A-Za-z]+(Collection)?Client)\.([A-Za-z]+) \(/;
18
+ const CLIENT_METHOD_REGEX = /at( async)? (?![A-Za-z]*HttpClient\.)([A-Za-z]+(Collection)?Client)\.(?!call \()([A-Za-z]+) \(/;
12
19
  /**
13
20
  * An `ApifyApiError` is thrown for successful HTTP requests that reach the API,
14
21
  * but the API responds with an error response. Typically, those are rate limit
@@ -69,8 +76,8 @@ export class ApifyApiError extends Error {
69
76
  let type;
70
77
  let responseData = response.data;
71
78
  let errorData;
72
- // A `forceBuffer` request (e.g. `downloadItems()`) and a failed streaming request, whose body `HttpClient`
73
- // has read into a buffer, both arrive unparsed. Parse the body here to get at the error.
79
+ // A `responseType: 'buffer'` request (e.g. `downloadItems()`) and a failed streaming request, whose body
80
+ // `HttpClient` has read into a buffer, both arrive unparsed. Parse the body here to get at the error.
74
81
  if (isBuffer(responseData)) {
75
82
  const body = new TextDecoder().decode(response.data);
76
83
  try {
@@ -146,7 +153,7 @@ export class ApifyApiError extends Error {
146
153
  * statusCode: 404
147
154
  * type: record-not-found
148
155
  * attempt: 1
149
- * httpMethod: post
156
+ * httpMethod: POST
150
157
  * path: /v2/actor-tasks/user~my-task/runs
151
158
  */
152
159
  #createApiStack() {
@@ -1,7 +1,8 @@
1
1
  import type { SetStatusMessageOptions } from '@crawlee/types';
2
2
  import type { Log } from '@apify/log';
3
- import { HttpClient } from './http_client.js';
4
- import type { RequestInterceptorFunction } from './interceptors.js';
3
+ import { HttpClient } from './http_clients/base.js';
4
+ import type { HttpCompressor } from './http_compressors/base.js';
5
+ import type { HttpCompressionAlgorithm } from './http_compressors/resolve.js';
5
6
  import { ActorClient } from './resource_clients/actor.js';
6
7
  import { ActorCollectionClient } from './resource_clients/actor_collection.js';
7
8
  import { BuildClient } from './resource_clients/build.js';
@@ -56,10 +57,59 @@ export declare class ApifyClient {
56
57
  */
57
58
  publicBaseUrl: string;
58
59
  token?: string;
60
+ /**
61
+ * Statistics of the API calls made through the client. With a custom HTTP client, this is the client's own
62
+ * `stats` object, so it only reflects what that client records.
63
+ */
59
64
  stats: Statistics;
60
65
  logger: Log;
61
- httpClient: HttpClient;
66
+ /**
67
+ * Creates a client that sends its requests through the built-in {@link AxiosHttpClient}, configured from
68
+ * `options`: the API token, retries, the timeout tiers, request compression and default headers. The HTTP
69
+ * client itself is created when {@link httpClient} is first read. To send the requests through a custom HTTP
70
+ * client, use {@link ApifyClient.withCustomHttpClient} instead.
71
+ *
72
+ * @param options - Configuration of the client and of its HTTP client.
73
+ * @throws {ArgumentValidationError} When an option is unknown or has an invalid value.
74
+ */
62
75
  constructor(options?: ApifyClientOptions);
76
+ /**
77
+ * Creates an `ApifyClient` that sends its requests through a custom HTTP client.
78
+ *
79
+ * The custom client owns its transport configuration: retries, timeouts, default headers and whatever its
80
+ * transport needs are set on the client itself. This is also how the built-in {@link AxiosHttpClient} is
81
+ * configured beyond what the constructor options offer, for example with axios request interceptors. The
82
+ * token is set as the client's `Authorization` header, unless the client already has one configured.
83
+ *
84
+ * @param options - The token, the API URLs and the HTTP client to use.
85
+ * @returns A client whose {@link httpClient} is the given one.
86
+ *
87
+ * @example
88
+ * ```javascript
89
+ * import { ApifyClient, HttpClient } from 'apify-client';
90
+ *
91
+ * class MyHttpClient extends HttpClient {
92
+ * async sendRequest({ method, url, headers, body, timeoutMillis, stream, signal }) {
93
+ * // Send the request with the HTTP library of your choice and return { status, headers, body }.
94
+ * }
95
+ * }
96
+ *
97
+ * const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new MyHttpClient() });
98
+ * ```
99
+ */
100
+ static withCustomHttpClient(options: ApifyClientCustomHttpClientOptions): ApifyClient;
101
+ /**
102
+ * The HTTP client the requests go through: the custom one when set through
103
+ * {@link ApifyClient.withCustomHttpClient}, and otherwise an {@link AxiosHttpClient} configured from the
104
+ * constructor options, created on first access. Assigning a client applies {@link token} to it through
105
+ * {@link HttpClient.setDefaultAuthorization} and points {@link stats} at its statistics, so the counters keep
106
+ * tracking the calls the client actually makes. Resource clients hold on to the HTTP client they were created
107
+ * with, so assign before reaching for them. Assigning does not close the client it replaces. A default client
108
+ * that already sent a request keeps its keep-alive agents open until {@link HttpClient.close} is called on it,
109
+ * so close it yourself, or assign before the first request.
110
+ */
111
+ get httpClient(): HttpClient;
112
+ set httpClient(httpClient: HttpClient);
63
113
  /**
64
114
  * Returns a client for managing Actors in your account.
65
115
  *
@@ -353,6 +403,18 @@ export declare class ApifyClient {
353
403
  export interface ApifyClientOptions {
354
404
  /** @default https://api.apify.com */
355
405
  baseUrl?: string;
406
+ /**
407
+ * Compression of request bodies: the name of a built-in algorithm, or an {@link HttpCompressor} for a custom
408
+ * quality or algorithm. Bodies are compressed only in Node.js, and only when they are large enough to benefit
409
+ * and their content type does not already carry its own compression.
410
+ * @default 'brotli'
411
+ */
412
+ compression?: HttpCompressionAlgorithm | HttpCompressor;
413
+ /**
414
+ * Additional headers sent with every request, such as an integration platform marker. They win over the
415
+ * built-in defaults, and a header set on a single call wins over them.
416
+ */
417
+ headers?: Record<string, string>;
356
418
  /**
357
419
  * @default https://api.apify.com
358
420
  * @since Added in 2.17.0
@@ -362,8 +424,6 @@ export interface ApifyClientOptions {
362
424
  maxRetries?: number;
363
425
  /** @default 500 */
364
426
  minDelayBetweenRetriesMillis?: number;
365
- /** @default [] */
366
- requestInterceptors?: RequestInterceptorFunction[];
367
427
  /**
368
428
  * Duration of the `short` timeout tier, in seconds: simple metadata reads and writes.
369
429
  * @default 5
@@ -391,3 +451,17 @@ export interface ApifyClientOptions {
391
451
  */
392
452
  userAgentSuffix?: string | string[];
393
453
  }
454
+ /**
455
+ * Configuration options for {@link ApifyClient.withCustomHttpClient}. Retries, timeouts and headers are configured
456
+ * on the HTTP client itself.
457
+ */
458
+ export interface ApifyClientCustomHttpClientOptions {
459
+ /** @default https://api.apify.com */
460
+ baseUrl?: string;
461
+ /** @default https://api.apify.com */
462
+ publicBaseUrl?: string;
463
+ /** Set as the HTTP client's `Authorization` header, unless it already has one. */
464
+ token?: string;
465
+ /** The HTTP client to send the requests through. */
466
+ httpClient: HttpClient;
467
+ }
@@ -1,7 +1,9 @@
1
1
  import { z } from 'zod';
2
2
  import { ACTOR_ENV_VARS, ME_USER_NAME_PLACEHOLDER } from '@apify/consts';
3
3
  import logger from '@apify/log';
4
- import { HttpClient } from './http_client.js';
4
+ import { AxiosHttpClient } from './http_clients/axios.js';
5
+ import { DEFAULT_MAX_RETRIES, DEFAULT_MIN_DELAY_BETWEEN_RETRIES_MILLIS, HttpClient, httpClientOptionsShape, } from './http_clients/base.js';
6
+ import { compressionSchema } from './http_compressors/resolve.js';
5
7
  import { ActorClient } from './resource_clients/actor.js';
6
8
  import { ActorCollectionClient } from './resource_clients/actor_collection.js';
7
9
  import { BuildClient } from './resource_clients/build.js';
@@ -28,19 +30,27 @@ import { WebhookDispatchCollectionClient } from './resource_clients/webhook_disp
28
30
  import { Statistics } from './statistics.js';
29
31
  import { DEFAULT_TIMEOUT_LONG_SECS, DEFAULT_TIMEOUT_MAX_SECS, DEFAULT_TIMEOUT_MEDIUM_SECS, DEFAULT_TIMEOUT_SHORT_SECS, } from './timeouts.js';
30
32
  import { getEnv, parseArgument } from './utils.js';
33
+ const DEFAULT_API_URL = 'https://api.apify.com';
31
34
  const clientOptionsSchema = z.strictObject({
32
- baseUrl: z.string().default('https://api.apify.com'),
33
- publicBaseUrl: z.string().default('https://api.apify.com'),
34
- maxRetries: z.number().default(8),
35
- minDelayBetweenRetriesMillis: z.number().default(500),
36
- requestInterceptors: z.array(z.unknown()).default([]),
37
- timeoutShortSecs: z.number().positive().default(DEFAULT_TIMEOUT_SHORT_SECS),
38
- timeoutMediumSecs: z.number().positive().default(DEFAULT_TIMEOUT_MEDIUM_SECS),
39
- timeoutLongSecs: z.number().positive().default(DEFAULT_TIMEOUT_LONG_SECS),
40
- timeoutMaxSecs: z.number().positive().default(DEFAULT_TIMEOUT_MAX_SECS),
35
+ baseUrl: z.string().default(DEFAULT_API_URL),
36
+ compression: compressionSchema.default('brotli'),
37
+ headers: z.record(z.string(), z.string()).optional(),
38
+ publicBaseUrl: z.string().default(DEFAULT_API_URL),
39
+ maxRetries: httpClientOptionsShape.maxRetries.default(DEFAULT_MAX_RETRIES),
40
+ minDelayBetweenRetriesMillis: httpClientOptionsShape.minDelayBetweenRetriesMillis.default(DEFAULT_MIN_DELAY_BETWEEN_RETRIES_MILLIS),
41
+ timeoutShortSecs: httpClientOptionsShape.timeoutShortSecs.default(DEFAULT_TIMEOUT_SHORT_SECS),
42
+ timeoutMediumSecs: httpClientOptionsShape.timeoutMediumSecs.default(DEFAULT_TIMEOUT_MEDIUM_SECS),
43
+ timeoutLongSecs: httpClientOptionsShape.timeoutLongSecs.default(DEFAULT_TIMEOUT_LONG_SECS),
44
+ timeoutMaxSecs: httpClientOptionsShape.timeoutMaxSecs.default(DEFAULT_TIMEOUT_MAX_SECS),
41
45
  token: z.string().optional(),
42
46
  userAgentSuffix: z.union([z.string(), z.array(z.string())]).optional(),
43
47
  });
48
+ const customHttpClientOptionsSchema = z.strictObject({
49
+ baseUrl: z.string().default(DEFAULT_API_URL),
50
+ publicBaseUrl: z.string().default(DEFAULT_API_URL),
51
+ token: z.string().optional(),
52
+ httpClient: z.instanceof(HttpClient),
53
+ });
44
54
  const resourceIdSchema = z.string().min(1);
45
55
  const requestQueueOptionsSchema = z.strictObject({
46
56
  clientKey: z.string().min(1).optional(),
@@ -74,12 +84,27 @@ export class ApifyClient {
74
84
  */
75
85
  publicBaseUrl;
76
86
  token;
87
+ /**
88
+ * Statistics of the API calls made through the client. With a custom HTTP client, this is the client's own
89
+ * `stats` object, so it only reflects what that client records.
90
+ */
77
91
  stats;
78
92
  logger;
79
- httpClient;
93
+ #httpClient;
94
+ /** Configuration of the default HTTP client, applied when no custom one is set. */
95
+ #httpClientOptions;
96
+ /**
97
+ * Creates a client that sends its requests through the built-in {@link AxiosHttpClient}, configured from
98
+ * `options`: the API token, retries, the timeout tiers, request compression and default headers. The HTTP
99
+ * client itself is created when {@link httpClient} is first read. To send the requests through a custom HTTP
100
+ * client, use {@link ApifyClient.withCustomHttpClient} instead.
101
+ *
102
+ * @param options - Configuration of the client and of its HTTP client.
103
+ * @throws {ArgumentValidationError} When an option is unknown or has an invalid value.
104
+ */
80
105
  constructor(options = {}) {
81
106
  const parsed = parseArgument(options, clientOptionsSchema, 'ApifyClientOptions');
82
- const { baseUrl, publicBaseUrl, maxRetries, minDelayBetweenRetriesMillis, requestInterceptors, timeoutShortSecs, timeoutMediumSecs, timeoutLongSecs, timeoutMaxSecs, token, } = parsed;
107
+ const { baseUrl, compression, headers, publicBaseUrl, maxRetries, minDelayBetweenRetriesMillis, timeoutShortSecs, timeoutMediumSecs, timeoutLongSecs, timeoutMaxSecs, token, } = parsed;
83
108
  const tempBaseUrl = baseUrl.endsWith('/') ? baseUrl.slice(0, baseUrl.length - 1) : baseUrl;
84
109
  this.baseUrl = `${tempBaseUrl}/v2`;
85
110
  const tempPublicBaseUrl = publicBaseUrl.endsWith('/')
@@ -89,11 +114,12 @@ export class ApifyClient {
89
114
  this.token = token;
90
115
  this.stats = new Statistics();
91
116
  this.logger = logger.child({ prefix: 'ApifyClient' });
92
- this.httpClient = new HttpClient({
93
- apifyClientStats: this.stats,
117
+ this.#httpClientOptions = {
118
+ stats: this.stats,
94
119
  maxRetries,
95
120
  minDelayBetweenRetriesMillis,
96
- requestInterceptors,
121
+ compression,
122
+ headers,
97
123
  timeoutShortSecs,
98
124
  timeoutMediumSecs,
99
125
  timeoutLongSecs,
@@ -101,7 +127,57 @@ export class ApifyClient {
101
127
  logger: this.logger,
102
128
  token: this.token,
103
129
  userAgentSuffix: parsed.userAgentSuffix,
104
- });
130
+ };
131
+ }
132
+ /**
133
+ * Creates an `ApifyClient` that sends its requests through a custom HTTP client.
134
+ *
135
+ * The custom client owns its transport configuration: retries, timeouts, default headers and whatever its
136
+ * transport needs are set on the client itself. This is also how the built-in {@link AxiosHttpClient} is
137
+ * configured beyond what the constructor options offer, for example with axios request interceptors. The
138
+ * token is set as the client's `Authorization` header, unless the client already has one configured.
139
+ *
140
+ * @param options - The token, the API URLs and the HTTP client to use.
141
+ * @returns A client whose {@link httpClient} is the given one.
142
+ *
143
+ * @example
144
+ * ```javascript
145
+ * import { ApifyClient, HttpClient } from 'apify-client';
146
+ *
147
+ * class MyHttpClient extends HttpClient {
148
+ * async sendRequest({ method, url, headers, body, timeoutMillis, stream, signal }) {
149
+ * // Send the request with the HTTP library of your choice and return { status, headers, body }.
150
+ * }
151
+ * }
152
+ *
153
+ * const client = ApifyClient.withCustomHttpClient({ token: 'my-token', httpClient: new MyHttpClient() });
154
+ * ```
155
+ */
156
+ static withCustomHttpClient(options) {
157
+ const { httpClient, ...rest } = parseArgument(options, customHttpClientOptionsSchema, 'ApifyClientCustomHttpClientOptions');
158
+ const client = new ApifyClient(rest);
159
+ client.httpClient = httpClient;
160
+ return client;
161
+ }
162
+ /**
163
+ * The HTTP client the requests go through: the custom one when set through
164
+ * {@link ApifyClient.withCustomHttpClient}, and otherwise an {@link AxiosHttpClient} configured from the
165
+ * constructor options, created on first access. Assigning a client applies {@link token} to it through
166
+ * {@link HttpClient.setDefaultAuthorization} and points {@link stats} at its statistics, so the counters keep
167
+ * tracking the calls the client actually makes. Resource clients hold on to the HTTP client they were created
168
+ * with, so assign before reaching for them. Assigning does not close the client it replaces. A default client
169
+ * that already sent a request keeps its keep-alive agents open until {@link HttpClient.close} is called on it,
170
+ * so close it yourself, or assign before the first request.
171
+ */
172
+ get httpClient() {
173
+ this.#httpClient ??= new AxiosHttpClient(this.#httpClientOptions);
174
+ return this.#httpClient;
175
+ }
176
+ set httpClient(httpClient) {
177
+ if (this.token)
178
+ httpClient.setDefaultAuthorization(this.token);
179
+ this.#httpClient = httpClient;
180
+ this.stats = httpClient.stats;
105
181
  }
106
182
  #subClientOptions() {
107
183
  return {
@@ -1,5 +1,5 @@
1
1
  import type { ApifyClient } from '../apify_client.js';
2
- import type { HttpClient } from '../http_client.js';
2
+ import type { HttpClient } from '../http_clients/index.js';
3
3
  import type { PaginatedResponse, PaginationOptions } from '../utils.js';
4
4
  /** @private */
5
5
  export interface ApiClientOptions {