apify-client 3.0.0-rc.0 → 3.0.0-rc.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +10 -2
  2. package/dist/apify_api_error.d.ts +4 -3
  3. package/dist/apify_api_error.js +2 -1
  4. package/dist/apify_client.d.ts +8 -8
  5. package/dist/apify_client.js +10 -10
  6. package/dist/apify_client_error.d.ts +10 -0
  7. package/dist/apify_client_error.js +10 -0
  8. package/dist/axios.d.ts +2 -0
  9. package/dist/axios.js +1 -0
  10. package/dist/base/api_client.js +8 -20
  11. package/dist/base/resource_client.js +8 -8
  12. package/dist/body_parser.d.ts +1 -1
  13. package/dist/bundle.js +31 -30
  14. package/dist/bundle.js.map +1 -1
  15. package/dist/generated/api.d.ts +2427 -725
  16. package/dist/generated/schemas.d.ts +1868 -274
  17. package/dist/generated/schemas.js +437 -79
  18. package/dist/http_clients/axios.d.ts +35 -15
  19. package/dist/http_clients/axios.js +80 -32
  20. package/dist/http_clients/base.d.ts +105 -34
  21. package/dist/http_clients/base.js +169 -52
  22. package/dist/http_clients/fetch.d.ts +53 -0
  23. package/dist/http_clients/fetch.js +219 -0
  24. package/dist/http_clients/index.d.ts +2 -2
  25. package/dist/http_clients/index.js +1 -1
  26. package/dist/http_compressors/index.d.ts +2 -0
  27. package/dist/http_compressors/index.js +1 -0
  28. package/dist/http_compressors/resolve.d.ts +4 -3
  29. package/dist/http_compressors/resolve.js +4 -1
  30. package/dist/http_compressors/zstd.d.ts +34 -0
  31. package/dist/http_compressors/zstd.js +43 -0
  32. package/dist/index.d.ts +3 -1
  33. package/dist/index.js +2 -0
  34. package/dist/invalid_response_body_error.d.ts +5 -4
  35. package/dist/invalid_response_body_error.js +5 -4
  36. package/dist/models.d.ts +30 -61
  37. package/dist/resource_clients/actor.d.ts +33 -2
  38. package/dist/resource_clients/actor.js +46 -3
  39. package/dist/resource_clients/actor_server.d.ts +149 -0
  40. package/dist/resource_clients/actor_server.js +195 -0
  41. package/dist/resource_clients/actor_version.d.ts +7 -1
  42. package/dist/resource_clients/actor_version.js +3 -2
  43. package/dist/resource_clients/actor_version_collection.d.ts +2 -1
  44. package/dist/resource_clients/actor_version_collection.js +3 -2
  45. package/dist/resource_clients/dataset.d.ts +33 -5
  46. package/dist/resource_clients/dataset.js +12 -54
  47. package/dist/resource_clients/key_value_store.d.ts +63 -22
  48. package/dist/resource_clients/key_value_store.js +62 -19
  49. package/dist/resource_clients/log.d.ts +32 -7
  50. package/dist/resource_clients/log.js +11 -14
  51. package/dist/resource_clients/request_queue.d.ts +9 -0
  52. package/dist/resource_clients/request_queue.js +9 -6
  53. package/dist/resource_clients/run.d.ts +15 -2
  54. package/dist/resource_clients/run.js +12 -5
  55. package/dist/resource_clients/store_collection.d.ts +4 -0
  56. package/dist/resource_clients/task.js +3 -3
  57. package/dist/response_validation_error.d.ts +2 -1
  58. package/dist/response_validation_error.js +2 -1
  59. package/dist/runtime/node.js +79 -17
  60. package/dist/runtime/types.d.ts +35 -5
  61. package/dist/runtime/web.js +43 -1
  62. package/dist/schemas.d.ts +369 -3
  63. package/dist/schemas.js +25 -3
  64. package/dist/utils.d.ts +52 -27
  65. package/dist/utils.js +45 -25
  66. package/package.json +42 -30
package/README.md CHANGED
@@ -15,6 +15,7 @@ automatic retries and convenience functions that improve the experience of using
15
15
  - [Features](#features)
16
16
  - [Automatic parsing and error handling](#automatic-parsing-and-error-handling)
17
17
  - [Retries with exponential backoff](#retries-with-exponential-backoff)
18
+ - [Server Actors](#server-actors)
18
19
  - [Convenience functions and options](#convenience-functions-and-options)
19
20
  - [Usage concepts](#usage-concepts)
20
21
  - [Nested clients](#nested-clients)
@@ -61,10 +62,17 @@ options of the `ApifyClient` constructor.
61
62
 
62
63
  ### Pluggable HTTP client
63
64
 
64
- The client ships with an axios-based HTTP client and accepts a custom one. Extend `HttpClient`, implement
65
+ The client sends its requests through the `fetch` of the runtime and accepts a custom HTTP client. The axios-based
66
+ client of version 2 is available from `apify-client/axios`, with `axios` installed next to the client. For a client
67
+ of your own, extend `HttpClient`, implement
65
68
  `sendRequest()` over the HTTP library of your choice and plug it in with `ApifyClient.withCustomHttpClient()`. The
66
69
  custom client inherits the retries, timeouts, compression and error handling of the built-in one.
67
70
 
71
+ ### Server Actors
72
+
73
+ `client.actor(id).server()` returns a client for a Server Actor (formerly Actor Standby). It sends HTTP requests to
74
+ the Actor's web server with your token, and returns the server's URL and OpenAPI specification.
75
+
68
76
  ### Convenience functions and options
69
77
 
70
78
  Some actions can't be performed by the API itself, such as indefinite waiting for an actor run to finish
@@ -157,7 +165,7 @@ The package includes a pre-built browser bundle that bundlers targeting browsers
157
165
  import { ApifyClient } from 'apify-client/browser';
158
166
  ```
159
167
 
160
- Only two parts of the client need Node.js built-ins: the HTTP agents and request compression. The `node` condition selects the Node.js implementation of those, and every other target gets one built on Web APIs. Log streaming, proxy support, and request compression are only available in Node.js.
168
+ Only two parts of the client need Node.js built-ins: Node.js streams and request compression. The `node` condition selects the Node.js implementation of those, and every other target gets one built on Web APIs. Log redirection and request compression are only available in Node.js.
161
169
 
162
170
  For details, see [Bundled environments](https://docs.apify.com/api/client/js/docs/concepts/bundled-environments).
163
171
 
@@ -1,6 +1,7 @@
1
- import type { LiteralUnion } from 'type-fest';
1
+ import { ApifyClientError } from './apify_client_error.js';
2
2
  import type { ApifyResponse } from './http_clients/base.js';
3
3
  import type { ErrorType } from './models.js';
4
+ import type { AnyString } from './utils.js';
4
5
  export type { ErrorType } from './models.js';
5
6
  /**
6
7
  * An `ApifyApiError` is thrown for successful HTTP requests that reach the API,
@@ -16,7 +17,7 @@ export type { ErrorType } from './models.js';
16
17
  * subclass extends `ApifyApiError`, so `instanceof ApifyApiError` matches all of them. Errors that
17
18
  * share a status code are told apart by their `type`.
18
19
  */
19
- export declare class ApifyApiError extends Error {
20
+ export declare class ApifyApiError extends ApifyClientError {
20
21
  #private;
21
22
  name: string;
22
23
  /**
@@ -33,7 +34,7 @@ export declare class ApifyApiError extends Error {
33
34
  * The type of the error, as returned by the API. Typed as the known {@link ErrorType}
34
35
  * values for autocompletion, while still accepting any string the API may return.
35
36
  */
36
- type?: LiteralUnion<ErrorType, string>;
37
+ type?: ErrorType | AnyString;
37
38
  /**
38
39
  * Number of the API call attempt.
39
40
  */
@@ -1,3 +1,4 @@
1
+ import { ApifyClientError } from './apify_client_error.js';
1
2
  import { isBuffer } from './utils.js';
2
3
  /**
3
4
  * Examples of capturing groups for "...at ActorCollectionClient.listResources (/Users/..."
@@ -30,7 +31,7 @@ const CLIENT_METHOD_REGEX = /at( async)? (?![A-Za-z]*HttpClient\.)([A-Za-z]+(Col
30
31
  * subclass extends `ApifyApiError`, so `instanceof ApifyApiError` matches all of them. Errors that
31
32
  * share a status code are told apart by their `type`.
32
33
  */
33
- export class ApifyApiError extends Error {
34
+ export class ApifyApiError extends ApifyClientError {
34
35
  name;
35
36
  /**
36
37
  * The resource client and the method parsed from the stack trace, such as `ActorClient.getResource`. A public
@@ -63,7 +63,7 @@ export declare class ApifyClient {
63
63
  stats: Statistics;
64
64
  logger: Log;
65
65
  /**
66
- * Creates a client that sends its requests through the built-in {@link AxiosHttpClient}, configured from
66
+ * Creates a client that sends its requests through the built-in {@link FetchHttpClient}, configured from
67
67
  * `options`: the API token, retries, the timeout tiers, request compression and default headers. The HTTP
68
68
  * client itself is created when {@link httpClient} is first read. To send the requests through a custom HTTP
69
69
  * client, use {@link ApifyClient.withCustomHttpClient} instead.
@@ -76,9 +76,10 @@ export declare class ApifyClient {
76
76
  * Creates an `ApifyClient` that sends its requests through a custom HTTP client.
77
77
  *
78
78
  * The custom client owns its transport configuration: retries, timeouts, default headers and whatever its
79
- * transport needs are set on the client itself. This is also how the built-in {@link AxiosHttpClient} is
80
- * configured beyond what the constructor options offer, for example with axios request interceptors. The
81
- * token is set as the client's `Authorization` header, unless the client already has one configured.
79
+ * transport needs are set on the client itself. This is also how the built-in {@link FetchHttpClient} is
80
+ * configured beyond what the constructor options offer, for example with a `fetch` function of your own, and
81
+ * how the axios-based client from `apify-client/axios` is brought back. The token is set as the client's
82
+ * `Authorization` header, unless the client already has one configured.
82
83
  *
83
84
  * @param options - The token, the API URLs and the HTTP client to use.
84
85
  * @returns A client whose {@link httpClient} is the given one.
@@ -99,13 +100,12 @@ export declare class ApifyClient {
99
100
  static withCustomHttpClient(options: ApifyClientCustomHttpClientOptions): ApifyClient;
100
101
  /**
101
102
  * The HTTP client the requests go through: the custom one when set through
102
- * {@link ApifyClient.withCustomHttpClient}, and otherwise an {@link AxiosHttpClient} configured from the
103
+ * {@link ApifyClient.withCustomHttpClient}, and otherwise a {@link FetchHttpClient} configured from the
103
104
  * constructor options, created on first access. Assigning a client applies {@link token} to it through
104
105
  * {@link HttpClient.setDefaultAuthorization} and points {@link stats} at its statistics, so the counters keep
105
106
  * tracking the calls the client actually makes. Resource clients hold on to the HTTP client they were created
106
- * with, so assign before reaching for them. Assigning does not close the client it replaces. A default client
107
- * that already sent a request keeps its keep-alive agents open until {@link HttpClient.close} is called on it,
108
- * so close it yourself, or assign before the first request.
107
+ * with, so assign before reaching for them. Assigning does not close the client it replaces, so call
108
+ * {@link HttpClient.close} on one that owns connections yourself.
109
109
  */
110
110
  get httpClient(): HttpClient;
111
111
  set httpClient(httpClient: HttpClient);
@@ -1,7 +1,7 @@
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 { AxiosHttpClient } from './http_clients/axios.js';
4
+ import { FetchHttpClient } from './http_clients/fetch.js';
5
5
  import { DEFAULT_MAX_RETRIES, DEFAULT_MIN_DELAY_BETWEEN_RETRIES_MILLIS, HttpClient, httpClientOptionsShape, } from './http_clients/base.js';
6
6
  import { compressionSchema } from './http_compressors/resolve.js';
7
7
  import { ActorClient } from './resource_clients/actor.js';
@@ -101,7 +101,7 @@ export class ApifyClient {
101
101
  /** Configuration of the default HTTP client, applied when no custom one is set. */
102
102
  #httpClientOptions;
103
103
  /**
104
- * Creates a client that sends its requests through the built-in {@link AxiosHttpClient}, configured from
104
+ * Creates a client that sends its requests through the built-in {@link FetchHttpClient}, configured from
105
105
  * `options`: the API token, retries, the timeout tiers, request compression and default headers. The HTTP
106
106
  * client itself is created when {@link httpClient} is first read. To send the requests through a custom HTTP
107
107
  * client, use {@link ApifyClient.withCustomHttpClient} instead.
@@ -136,9 +136,10 @@ export class ApifyClient {
136
136
  * Creates an `ApifyClient` that sends its requests through a custom HTTP client.
137
137
  *
138
138
  * The custom client owns its transport configuration: retries, timeouts, default headers and whatever its
139
- * transport needs are set on the client itself. This is also how the built-in {@link AxiosHttpClient} is
140
- * configured beyond what the constructor options offer, for example with axios request interceptors. The
141
- * token is set as the client's `Authorization` header, unless the client already has one configured.
139
+ * transport needs are set on the client itself. This is also how the built-in {@link FetchHttpClient} is
140
+ * configured beyond what the constructor options offer, for example with a `fetch` function of your own, and
141
+ * how the axios-based client from `apify-client/axios` is brought back. The token is set as the client's
142
+ * `Authorization` header, unless the client already has one configured.
142
143
  *
143
144
  * @param options - The token, the API URLs and the HTTP client to use.
144
145
  * @returns A client whose {@link httpClient} is the given one.
@@ -164,16 +165,15 @@ export class ApifyClient {
164
165
  }
165
166
  /**
166
167
  * The HTTP client the requests go through: the custom one when set through
167
- * {@link ApifyClient.withCustomHttpClient}, and otherwise an {@link AxiosHttpClient} configured from the
168
+ * {@link ApifyClient.withCustomHttpClient}, and otherwise a {@link FetchHttpClient} configured from the
168
169
  * constructor options, created on first access. Assigning a client applies {@link token} to it through
169
170
  * {@link HttpClient.setDefaultAuthorization} and points {@link stats} at its statistics, so the counters keep
170
171
  * tracking the calls the client actually makes. Resource clients hold on to the HTTP client they were created
171
- * with, so assign before reaching for them. Assigning does not close the client it replaces. A default client
172
- * that already sent a request keeps its keep-alive agents open until {@link HttpClient.close} is called on it,
173
- * so close it yourself, or assign before the first request.
172
+ * with, so assign before reaching for them. Assigning does not close the client it replaces, so call
173
+ * {@link HttpClient.close} on one that owns connections yourself.
174
174
  */
175
175
  get httpClient() {
176
- this.#httpClient ??= new AxiosHttpClient(this.#httpClientOptions);
176
+ this.#httpClient ??= new FetchHttpClient(this.#httpClientOptions);
177
177
  return this.#httpClient;
178
178
  }
179
179
  set httpClient(httpClient) {
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Base class of the errors the client throws for a failed API call: {@link ApifyApiError} and its subclasses,
3
+ * {@link InvalidResponseBodyError} and {@link ResponseValidationError}. A single `instanceof ApifyClientError`
4
+ * check catches all of them.
5
+ *
6
+ * Invalid arguments throw an `ArgumentValidationError` before any request is sent, and transport errors, timeouts
7
+ * and aborts surface as the errors the transport raised. None of those extend this class.
8
+ */
9
+ export declare class ApifyClientError extends Error {
10
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Base class of the errors the client throws for a failed API call: {@link ApifyApiError} and its subclasses,
3
+ * {@link InvalidResponseBodyError} and {@link ResponseValidationError}. A single `instanceof ApifyClientError`
4
+ * check catches all of them.
5
+ *
6
+ * Invalid arguments throw an `ArgumentValidationError` before any request is sent, and transport errors, timeouts
7
+ * and aborts surface as the errors the transport raised. None of those extend this class.
8
+ */
9
+ export class ApifyClientError extends Error {
10
+ }
@@ -0,0 +1,2 @@
1
+ export type { AxiosHttpClientOptions, RequestInterceptorFunction } from './http_clients/axios.js';
2
+ export { AxiosHttpClient } from './http_clients/axios.js';
package/dist/axios.js ADDED
@@ -0,0 +1 @@
1
+ export { AxiosHttpClient } from './http_clients/axios.js';
@@ -1,4 +1,4 @@
1
- import { SCANNED_COUNT, toPath, toPathSegment } from '../utils.js';
1
+ import { minForLimitParam, toPath, toPathSegment } from '../utils.js';
2
2
  /** @private */
3
3
  export class ApiClient {
4
4
  id;
@@ -54,32 +54,20 @@ export class ApiClient {
54
54
  * Returns async iterator to iterate through all items and Promise that can be awaited to get first page of results.
55
55
  */
56
56
  listPaginatedFromCallback(getPaginatedList, options = {}) {
57
- const minForLimitParam = (a, b) => {
58
- // API treats 0 as undefined for limit parameter
59
- if (a === 0)
60
- a = undefined;
61
- if (b === 0)
62
- b = undefined;
63
- if (a === undefined)
64
- return b;
65
- if (b === undefined)
66
- return a;
67
- return Math.min(a, b);
68
- };
69
57
  // `chunkSize` only sizes this loop's requests; it is not an API parameter, so it must not reach
70
58
  // `buildParams()` and the query string. The same goes for `timeoutSecs` and `signal`, which callers take out
71
59
  // before calling this, since they also apply to every page request.
72
60
  const { chunkSize, ...listOptions } = options;
73
61
  const firstPageLimit = minForLimitParam(options.limit, chunkSize);
74
62
  const paginatedListPromise = getPaginatedList({ ...listOptions, limit: firstPageLimit });
75
- // A page can return more or fewer items than the rows it scanned (see `SCANNED_COUNT`). The next offset and
76
- // the stop condition follow the scanned rows: advancing by `items.length` would re-scan rows after a filter
77
- // dropped some and skip rows after `unwind` multiplied them, and stopping at an empty page would end the
78
- // iteration in front of rows a filter hid. The scanned number is derived from a dataset's item count, which
79
- // lags a fresh push, so the larger of it and `items.length` is taken, capped at the rows the request asked for
80
- // so that an unwound page does not advance past rows the next request would then never read.
63
+ // A page of dataset items can return more or fewer items than the rows it scanned (see `PaginatedList.count`).
64
+ // The next offset and the stop condition follow the scanned rows: advancing by `items.length` would re-scan
65
+ // rows after a filter dropped some and skip rows after `unwind` multiplied them, and stopping at an empty page
66
+ // would end the iteration in front of rows a filter hid. The step is the larger of `count` and `items.length`,
67
+ // capped at the rows the request asked for, which keeps an unwound page from advancing past rows the next
68
+ // request would then never read.
81
69
  const scannedRows = (page, requestedLimit) => {
82
- const scanned = Math.max(page[SCANNED_COUNT] ?? 0, page.items.length);
70
+ const scanned = Math.max(page.count ?? 0, page.items.length);
83
71
  return requestedLimit ? Math.min(scanned, requestedLimit) : scanned;
84
72
  };
85
73
  // `total` is not consulted, as it changes when the listed resource grows during the iteration.
@@ -102,7 +102,7 @@ export class ResourceClient extends ApiClient {
102
102
  const hasJobEnded = job && ACT_JOB_TERMINAL_STATUSES.includes(job.status);
103
103
  return !hasJobEnded;
104
104
  };
105
- do {
105
+ while (true) {
106
106
  const millisSinceStart = Date.now() - startedAt;
107
107
  const remainingWaitSeconds = Math.round((waitMillis - millisSinceStart) / 1000);
108
108
  const waitForFinish = Math.max(0, remainingWaitSeconds);
@@ -124,13 +124,13 @@ export class ResourceClient extends ApiClient {
124
124
  notFoundSince ??= Date.now();
125
125
  notFoundError = err;
126
126
  }
127
- // It might take some time for database replicas to get up-to-date,
128
- // so getRun() might return null. Wait a little bit and try it again.
129
- if (!job) {
130
- await sleep(250, signal);
131
- signal?.throwIfAborted();
132
- }
133
- } while (shouldRepeat());
127
+ if (!shouldRepeat())
128
+ break;
129
+ // The API answers right away when the remaining wait rounds to 0 seconds, and database replicas may not see
130
+ // a new job for a short while, so pause before the next poll.
131
+ await sleep(250, signal);
132
+ signal?.throwIfAborted();
133
+ }
134
134
  if (!job)
135
135
  throw notFoundError;
136
136
  return job;
@@ -1,4 +1,4 @@
1
- import type { JsonArray, JsonObject } from 'type-fest';
1
+ import type { JsonArray, JsonObject } from './utils.js';
2
2
  /**
3
3
  * Parses a binary response body using the provided content type header.
4
4
  *