apify-client 2.25.1-beta.9 → 2.26.1-beta.0

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.
@@ -0,0 +1,193 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ActorServerClient = void 0;
4
+ const tslib_1 = require("tslib");
5
+ const ow_1 = tslib_1.__importDefault(require("ow"));
6
+ const resource_client_1 = require("../base/resource_client");
7
+ const utils_1 = require("../utils");
8
+ const build_collection_1 = require("./build_collection");
9
+ /**
10
+ * Statuses a server request is retried on. The platform answers with them when it can't pass a request to a server
11
+ * run, so a retry usually doesn't run the Actor's code again. An Actor that returns one itself gets the request again.
12
+ */
13
+ const SERVER_RETRY_STATUS_CODES = [429, 503];
14
+ const HTTP_METHODS = ['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH'];
15
+ const BUILD_NUMBER_PATTERN = /^(\d+)\.(\d+)\.(\d+)$/;
16
+ /**
17
+ * Splits a build number like `0.1.23` into its version and sequence number, or returns `undefined` for anything else.
18
+ */
19
+ function parseBuildNumber(buildNumber) {
20
+ const match = BUILD_NUMBER_PATTERN.exec(buildNumber ?? '');
21
+ if (!match)
22
+ return undefined;
23
+ return [Number(match[1]), Number(match[2]), Number(match[3])];
24
+ }
25
+ /**
26
+ * Returns whether `buildNumber` belongs to the same version as `target` and comes before it. Builds are listed newest
27
+ * first and the sequence numbers of a version grow over time, so meeting such a build means the target doesn't exist.
28
+ */
29
+ function isOlderBuild(buildNumber, target) {
30
+ const parsed = parseBuildNumber(buildNumber);
31
+ return parsed !== undefined && parsed[0] === target[0] && parsed[1] === target[1] && parsed[2] < target[2];
32
+ }
33
+ /**
34
+ * Merges two header records, header names compared case-insensitively. A header from `override` replaces a
35
+ * same-named header in `base` whatever the casing of either.
36
+ */
37
+ function mergeHeaders(base, override = {}) {
38
+ const overridden = new Set(Object.keys(override).map((name) => name.toLowerCase()));
39
+ const kept = Object.entries(base).filter(([name]) => !overridden.has(name.toLowerCase()));
40
+ return { ...Object.fromEntries(kept), ...override };
41
+ }
42
+ /**
43
+ * Client for the server interface of a specific Actor.
44
+ *
45
+ * Provides methods to work with the web server of a Server Actor, such as sending it requests or getting its OpenAPI
46
+ * specification. Get an instance with {@link ActorClient.server}.
47
+ *
48
+ * @example
49
+ * ```javascript
50
+ * const client = new ApifyClient({ token: 'my-token' });
51
+ * const actorServerClient = client.actor('username/actor-name').server();
52
+ *
53
+ * const response = await actorServerClient.request('/search', { params: { q: 'apify' } });
54
+ * console.log(response.data);
55
+ * ```
56
+ *
57
+ * @see https://docs.apify.com/platform/actors/running/standby
58
+ * @since Added in 2.26.0
59
+ */
60
+ class ActorServerClient extends resource_client_1.ResourceClient {
61
+ /**
62
+ * The server URL. Getting it takes an API call for the Actor, so it's cached for {@link getUrl} and
63
+ * {@link request}. It's pending while the first lookup runs, so concurrent first calls share one API request.
64
+ */
65
+ _serverUrl;
66
+ /**
67
+ * @hidden
68
+ */
69
+ constructor(options) {
70
+ super({
71
+ resourcePath: 'actors',
72
+ ...options,
73
+ });
74
+ }
75
+ /**
76
+ * Returns the URL of the Actor's server.
77
+ *
78
+ * The URL is the Actor's `standbyUrl`, fetched from the API by the first call of this method or
79
+ * {@link getOpenApiSpec} and reused by later calls on this client. Use it to call the server with another HTTP
80
+ * client, for example one generated from the server's OpenAPI specification.
81
+ *
82
+ * @returns The URL of the Actor's server
83
+ * @throws When the Actor does not exist or is not a Server Actor.
84
+ * @see https://docs.apify.com/platform/actors/running/standby
85
+ */
86
+ async getUrl() {
87
+ const url = (this._serverUrl ??= this._getServerActor().then((actor) => actor.standbyUrl));
88
+ try {
89
+ return await url;
90
+ }
91
+ catch (err) {
92
+ // A failed lookup is not kept, so the next call tries again.
93
+ if (this._serverUrl === url)
94
+ this._serverUrl = undefined;
95
+ throw err;
96
+ }
97
+ }
98
+ /**
99
+ * Returns the OpenAPI specification of the Actor's server.
100
+ *
101
+ * The specification is the web server schema from the Actor's definition, taken from the build that serves the
102
+ * server interface: the build set in `actorStandby.build`, or `latest` if none is set. Use it to generate an HTTP
103
+ * client for the server, and point that client at the URL returned by {@link getUrl}.
104
+ *
105
+ * @returns The OpenAPI specification of the Actor's server, or `undefined` if the Actor's definition doesn't
106
+ * include one
107
+ * @throws When the Actor does not exist or is not a Server Actor, or the build that serves its server interface
108
+ * doesn't exist.
109
+ * @see https://docs.apify.com/platform/actors/development/actor-definition/web-server-schema
110
+ */
111
+ async getOpenApiSpec() {
112
+ const actor = await this._getServerActor();
113
+ const buildRef = actor.actorStandby?.build || 'latest';
114
+ let buildId = actor.taggedBuilds?.[buildRef]?.buildId;
115
+ const targetBuildNumber = parseBuildNumber(buildRef);
116
+ if (buildId === undefined && targetBuildNumber !== undefined) {
117
+ // Not a tag, so look `buildRef` up as a build number, which the API can't resolve directly.
118
+ const builds = new build_collection_1.BuildCollectionClient(this._subResourceOptions({ resourcePath: 'builds' }));
119
+ for await (const build of builds.list({ desc: true })) {
120
+ // The API lists builds with their build number, though the list item type omits it.
121
+ const { buildNumber } = build;
122
+ if (buildNumber === buildRef) {
123
+ buildId = build.id;
124
+ break;
125
+ }
126
+ if (isOlderBuild(buildNumber, targetBuildNumber))
127
+ break;
128
+ }
129
+ }
130
+ const build = buildId === undefined ? undefined : await this.apifyClient.build(buildId).get();
131
+ if (build === undefined) {
132
+ throw new Error(`Build ${buildRef} of Actor ${this.id} does not exist.`);
133
+ }
134
+ return build.actorDefinition?.webServerSchema;
135
+ }
136
+ async request(path = '/', options = {}) {
137
+ (0, ow_1.default)(path, ow_1.default.string);
138
+ const { data, ...rest } = options;
139
+ (0, ow_1.default)(rest, ow_1.default.object.exactShape({
140
+ method: ow_1.default.optional.string.oneOf(HTTP_METHODS),
141
+ params: ow_1.default.optional.object,
142
+ headers: ow_1.default.optional.object.valuesOfType(ow_1.default.string),
143
+ parentRequestId: ow_1.default.optional.string,
144
+ responseType: ow_1.default.optional.string.oneOf(['parsed', 'buffer', 'stream']),
145
+ timeoutSecs: ow_1.default.optional.number.positive,
146
+ }));
147
+ const { method = 'GET', params, headers, parentRequestId, responseType, timeoutSecs } = rest;
148
+ if (responseType === 'stream' && !(0, utils_1.isNode)()) {
149
+ throw new Error("The 'stream' response type can only be used in Node.js environment.");
150
+ }
151
+ const serverUrl = await this.getUrl();
152
+ const serverPath = path.split('#')[0].replace(/^\/+/, '');
153
+ // The token goes in `X-Apify-Authorization`, which the platform strips, and the client's default
154
+ // `Authorization` header is dropped (`null`) so the caller's own one, if any, reaches the Actor.
155
+ const authHeaders = { Authorization: null };
156
+ if (this.apifyClient.token)
157
+ authHeaders['X-Apify-Authorization'] = `Bearer ${this.apifyClient.token}`;
158
+ const requestHeaders = mergeHeaders(mergeHeaders(authHeaders, headers), parentRequestId === undefined ? undefined : { 'X-Actor-Request-ID': parentRequestId });
159
+ const config = {
160
+ url: `${serverUrl.replace(/\/+$/, '')}/${serverPath}`,
161
+ method,
162
+ params,
163
+ headers: requestHeaders,
164
+ data,
165
+ doNotCompress: true,
166
+ throwOnErrorStatus: false,
167
+ retryStatusCodes: SERVER_RETRY_STATUS_CODES,
168
+ retryTransportErrors: false,
169
+ maxRedirects: 0,
170
+ timeout: timeoutSecs !== undefined ? timeoutSecs * 1000 : resource_client_1.DEFAULT_TIMEOUT_MILLIS,
171
+ };
172
+ if (responseType === 'buffer')
173
+ config.forceBuffer = true;
174
+ if (responseType === 'stream')
175
+ config.responseType = 'stream';
176
+ return this.httpClient.call(config);
177
+ }
178
+ /**
179
+ * Fetches the Actor, checks that it is a Server Actor, and caches its server URL.
180
+ */
181
+ async _getServerActor() {
182
+ const actor = await this._get({}, resource_client_1.SMALL_TIMEOUT_MILLIS);
183
+ if (!actor) {
184
+ throw new Error(`Actor ${this.id} does not exist.`);
185
+ }
186
+ if (!actor.standbyUrl) {
187
+ throw new Error(`Actor ${this.id} is not a Server Actor.`);
188
+ }
189
+ this._serverUrl = Promise.resolve(actor.standbyUrl);
190
+ return actor;
191
+ }
192
+ }
193
+ exports.ActorServerClient = ActorServerClient;
@@ -79,6 +79,15 @@ export interface BaseActorVersion<SourceType extends ActorSourceType> {
79
79
  */
80
80
  export interface ActorVersionSourceFiles extends BaseActorVersion<ActorSourceType.SourceFiles> {
81
81
  sourceFiles: ActorVersionSourceFile[];
82
+ /**
83
+ * The Actor's folder inside the uploaded source, as a POSIX path relative to the upload root, such as
84
+ * `actors/typescript-actor`. When absent or `null`, the upload root is the Actor's folder. It has 1 to 255
85
+ * characters, with no leading, trailing, or repeated `/` and no `.` or `..` segment.
86
+ *
87
+ * An update that sends `sourceType` or `sourceFiles` without `actorPath` removes the stored path.
88
+ * @since Added in 2.26.0
89
+ */
90
+ actorPath?: string | null;
82
91
  }
83
92
  export interface ActorVersionSourceFile {
84
93
  name: string;
@@ -90,6 +99,15 @@ export interface ActorVersionGitRepo extends BaseActorVersion<ActorSourceType.Gi
90
99
  }
91
100
  export interface ActorVersionTarball extends BaseActorVersion<ActorSourceType.Tarball> {
92
101
  tarballUrl: string;
102
+ /**
103
+ * The Actor's folder inside the archive, as a POSIX path relative to the archive root, such as
104
+ * `actors/typescript-actor`. When absent or `null`, the archive root is the Actor's folder. It has 1 to 255
105
+ * characters, with no leading, trailing, or repeated `/` and no `.` or `..` segment.
106
+ *
107
+ * An update that sends `sourceType` or `tarballUrl` without `actorPath` removes the stored path.
108
+ * @since Added in 2.26.0
109
+ */
110
+ actorPath?: string | null;
93
111
  }
94
112
  export interface ActorVersionGitHubGist extends BaseActorVersion<ActorSourceType.GitHubGist> {
95
113
  gitHubGistUrl: string;
@@ -89,6 +89,7 @@ export declare class BuildClient extends ResourceClient {
89
89
  * Unlike the `waitForFinish` parameter in {@link get}, this method can wait indefinitely
90
90
  * by polling the build status. It uses the `waitForFinish` parameter internally (max 60s per call)
91
91
  * and continuously polls until the build finishes or the timeout is reached.
92
+ * Rejects if the build keeps returning 404 for 3 seconds.
92
93
  *
93
94
  * This is useful when you need to immediately start a run after a build finishes.
94
95
  *
@@ -192,6 +193,12 @@ export interface Build {
192
193
  * @since Added in 2.11.0
193
194
  */
194
195
  actorDefinition?: ActorDefinition;
196
+ /**
197
+ * Digest of the built Docker image manifest, without the `sha256:` prefix. Compare digests of two builds
198
+ * to find out whether their image contents differ. `null` if the digest is not available.
199
+ * @since Added in 2.26.0
200
+ */
201
+ imageDigest?: string | null;
195
202
  }
196
203
  /**
197
204
  * Resource usage for an Actor build.
@@ -118,6 +118,7 @@ class BuildClient extends resource_client_1.ResourceClient {
118
118
  * Unlike the `waitForFinish` parameter in {@link get}, this method can wait indefinitely
119
119
  * by polling the build status. It uses the `waitForFinish` parameter internally (max 60s per call)
120
120
  * and continuously polls until the build finishes or the timeout is reached.
121
+ * Rejects if the build keeps returning 404 for 3 seconds.
121
122
  *
122
123
  * This is useful when you need to immediately start a run after a build finishes.
123
124
  *
@@ -195,8 +195,10 @@ export declare class DatasetClient<Data extends Record<string | number, any> = R
195
195
  * This is useful for sharing dataset results with external services or users.
196
196
  *
197
197
  * @param options - URL generation options (extends all options from {@link listItems})
198
- * @param options.expiresInSecs - Number of seconds until the signed URL expires. If omitted, the URL never expires.
198
+ * @param options.expiresInSecs - Number of seconds until the signed URL expires. Must be positive. If omitted, the URL
199
+ * never expires.
199
200
  * @param options.fields - Array of field names to include in the response.
201
+ * @param options.format - Format of the items served by the URL. Defaults to `json`.
200
202
  * @param options.limit - Maximum number of items to return.
201
203
  * @param options.offset - Number of items to skip.
202
204
  * @returns A public URL string for accessing the dataset items
@@ -315,10 +317,15 @@ export interface DatasetClientListItemOptions extends PaginationOptions {
315
317
  /**
316
318
  * Options for creating a public URL to access dataset items.
317
319
  *
318
- * Extends {@link DatasetClientListItemOptions} with URL expiration control.
320
+ * Extends {@link DatasetClientListItemOptions} with output format and URL expiration control.
319
321
  * @since Added in 2.16.0
320
322
  */
321
323
  export interface DatasetClientCreateItemsUrlOptions extends DatasetClientListItemOptions {
324
+ /**
325
+ * Format of the items served by the URL. Defaults to `json`.
326
+ * @since Added in 2.26.0
327
+ */
328
+ format?: `${DownloadItemsFormat}`;
322
329
  expiresInSecs?: number;
323
330
  }
324
331
  /**
@@ -298,8 +298,10 @@ class DatasetClient extends resource_client_1.ResourceClient {
298
298
  * This is useful for sharing dataset results with external services or users.
299
299
  *
300
300
  * @param options - URL generation options (extends all options from {@link listItems})
301
- * @param options.expiresInSecs - Number of seconds until the signed URL expires. If omitted, the URL never expires.
301
+ * @param options.expiresInSecs - Number of seconds until the signed URL expires. Must be positive. If omitted, the URL
302
+ * never expires.
302
303
  * @param options.fields - Array of field names to include in the response.
304
+ * @param options.format - Format of the items served by the URL. Defaults to `json`.
303
305
  * @param options.limit - Maximum number of items to return.
304
306
  * @param options.offset - Number of items to skip.
305
307
  * @returns A public URL string for accessing the dataset items
@@ -328,6 +330,7 @@ class DatasetClient extends resource_client_1.ResourceClient {
328
330
  desc: ow_1.default.optional.boolean,
329
331
  flatten: ow_1.default.optional.array.ofType(ow_1.default.string),
330
332
  fields: ow_1.default.optional.array.ofType(ow_1.default.string),
333
+ format: ow_1.default.optional.string.oneOf(validItemFormats),
331
334
  omit: ow_1.default.optional.array.ofType(ow_1.default.string),
332
335
  limit: ow_1.default.optional.number.not.negative,
333
336
  offset: ow_1.default.optional.number.not.negative,
@@ -335,7 +338,7 @@ class DatasetClient extends resource_client_1.ResourceClient {
335
338
  skipHidden: ow_1.default.optional.boolean,
336
339
  unwind: ow_1.default.optional.any(ow_1.default.string, ow_1.default.array.ofType(ow_1.default.string)),
337
340
  view: ow_1.default.optional.string,
338
- expiresInSecs: ow_1.default.optional.number,
341
+ expiresInSecs: ow_1.default.optional.number.positive,
339
342
  }));
340
343
  const dataset = await this.get();
341
344
  const { expiresInSecs, ...queryOptions } = options;
@@ -122,7 +122,8 @@ export declare class KeyValueStoreClient extends ResourceClient {
122
122
  * the URL will include a cryptographic signature which allows access without authentication.
123
123
  *
124
124
  * @param options - URL generation options (extends all options from {@link listKeys})
125
- * @param options.expiresInSecs - Number of seconds until the signed URL expires. If omitted, the URL never expires.
125
+ * @param options.expiresInSecs - Number of seconds until the signed URL expires. Must be positive. If omitted, the URL
126
+ * never expires.
126
127
  * @param options.limit - Maximum number of keys to return.
127
128
  * @param options.prefix - Filter keys by prefix.
128
129
  * @returns A public URL string for accessing the keys list
@@ -174,7 +174,7 @@ class KeyValueStoreClient extends resource_client_1.ResourceClient {
174
174
  async getRecordPublicUrl(key) {
175
175
  (0, ow_1.default)(key, ow_1.default.string.nonEmpty);
176
176
  const store = await this.get();
177
- const recordPublicUrl = new URL(this._publicUrl(`records/${key}`));
177
+ const recordPublicUrl = new URL(this._publicUrl(['records', key]));
178
178
  if (store?.urlSigningSecretKey) {
179
179
  const signature = await (0, utilities_1.createHmacSignatureAsync)(store.urlSigningSecretKey, key);
180
180
  recordPublicUrl.searchParams.append('signature', signature);
@@ -188,7 +188,8 @@ class KeyValueStoreClient extends resource_client_1.ResourceClient {
188
188
  * the URL will include a cryptographic signature which allows access without authentication.
189
189
  *
190
190
  * @param options - URL generation options (extends all options from {@link listKeys})
191
- * @param options.expiresInSecs - Number of seconds until the signed URL expires. If omitted, the URL never expires.
191
+ * @param options.expiresInSecs - Number of seconds until the signed URL expires. Must be positive. If omitted, the URL
192
+ * never expires.
192
193
  * @param options.limit - Maximum number of keys to return.
193
194
  * @param options.prefix - Filter keys by prefix.
194
195
  * @returns A public URL string for accessing the keys list
@@ -210,7 +211,7 @@ class KeyValueStoreClient extends resource_client_1.ResourceClient {
210
211
  exclusiveStartKey: ow_1.default.optional.string,
211
212
  collection: ow_1.default.optional.string,
212
213
  prefix: ow_1.default.optional.string,
213
- expiresInSecs: ow_1.default.optional.number,
214
+ expiresInSecs: ow_1.default.optional.number.positive,
214
215
  }));
215
216
  const store = await this.get();
216
217
  const { expiresInSecs, ...queryOptions } = options;
@@ -246,7 +247,7 @@ class KeyValueStoreClient extends resource_client_1.ResourceClient {
246
247
  */
247
248
  async recordExists(key) {
248
249
  const requestOpts = {
249
- url: this._url(`records/${key}`),
250
+ url: this._url(['records', key]),
250
251
  method: 'HEAD',
251
252
  params: this._params(),
252
253
  };
@@ -278,7 +279,7 @@ class KeyValueStoreClient extends resource_client_1.ResourceClient {
278
279
  if (options.signature)
279
280
  queryParams.signature = options.signature;
280
281
  const requestOpts = {
281
- url: this._url(`records/${key}`),
282
+ url: this._url(['records', key]),
282
283
  method: 'GET',
283
284
  params: this._params(queryParams),
284
285
  timeout: resource_client_1.DEFAULT_TIMEOUT_MILLIS,
@@ -381,7 +382,7 @@ class KeyValueStoreClient extends resource_client_1.ResourceClient {
381
382
  }
382
383
  }
383
384
  const uploadOpts = {
384
- url: this._url(`records/${key}`),
385
+ url: this._url(['records', key]),
385
386
  method: 'PUT',
386
387
  params: this._params(),
387
388
  data: value,
@@ -405,7 +406,7 @@ class KeyValueStoreClient extends resource_client_1.ResourceClient {
405
406
  async deleteRecord(key) {
406
407
  (0, ow_1.default)(key, ow_1.default.string);
407
408
  await this.httpClient.call({
408
- url: this._url(`records/${key}`),
409
+ url: this._url(['records', key]),
409
410
  method: 'DELETE',
410
411
  params: this._params(),
411
412
  timeout: resource_client_1.SMALL_TIMEOUT_MILLIS,
@@ -409,7 +409,7 @@ class RequestQueueClient extends resource_client_1.ResourceClient {
409
409
  async getRequest(id) {
410
410
  (0, ow_1.default)(id, ow_1.default.string);
411
411
  const requestOpts = {
412
- url: this._url(`requests/${id}`),
412
+ url: this._url(['requests', id]),
413
413
  method: 'GET',
414
414
  timeout: Math.min(resource_client_1.SMALL_TIMEOUT_MILLIS, this.timeoutMillis ?? Infinity),
415
415
  params: this._params(),
@@ -439,7 +439,7 @@ class RequestQueueClient extends resource_client_1.ResourceClient {
439
439
  forefront: ow_1.default.optional.boolean,
440
440
  }));
441
441
  const response = await this.httpClient.call({
442
- url: this._url(`requests/${request.id}`),
442
+ url: this._url(['requests', request.id]),
443
443
  method: 'PUT',
444
444
  timeout: Math.min(resource_client_1.MEDIUM_TIMEOUT_MILLIS, this.timeoutMillis ?? Infinity),
445
445
  data: request,
@@ -458,7 +458,7 @@ class RequestQueueClient extends resource_client_1.ResourceClient {
458
458
  async deleteRequest(id) {
459
459
  (0, ow_1.default)(id, ow_1.default.string);
460
460
  await this.httpClient.call({
461
- url: this._url(`requests/${id}`),
461
+ url: this._url(['requests', id]),
462
462
  method: 'DELETE',
463
463
  timeout: Math.min(resource_client_1.SMALL_TIMEOUT_MILLIS, this.timeoutMillis ?? Infinity),
464
464
  params: this._params({
@@ -498,7 +498,7 @@ class RequestQueueClient extends resource_client_1.ResourceClient {
498
498
  forefront: ow_1.default.optional.boolean,
499
499
  }));
500
500
  const response = await this.httpClient.call({
501
- url: this._url(`requests/${id}/lock`),
501
+ url: this._url(['requests', id, 'lock']),
502
502
  method: 'PUT',
503
503
  timeout: Math.min(resource_client_1.MEDIUM_TIMEOUT_MILLIS, this.timeoutMillis ?? Infinity),
504
504
  params: this._params({
@@ -526,7 +526,7 @@ class RequestQueueClient extends resource_client_1.ResourceClient {
526
526
  forefront: ow_1.default.optional.boolean,
527
527
  }));
528
528
  await this.httpClient.call({
529
- url: this._url(`requests/${id}/lock`),
529
+ url: this._url(['requests', id, 'lock']),
530
530
  method: 'DELETE',
531
531
  timeout: Math.min(resource_client_1.SMALL_TIMEOUT_MILLIS, this.timeoutMillis ?? Infinity),
532
532
  params: this._params({
@@ -173,6 +173,7 @@ export declare class RunClient extends ResourceClient {
173
173
  * @param options.eventName - **Required.** Name of the event to charge for.
174
174
  * @param options.count - Number of times to charge the event. Default is 1.
175
175
  * @param options.idempotencyKey - Optional key to ensure the charge is not duplicated. If not provided, one is auto-generated.
176
+ * @param options.requestId - ID of the Server Actor request being charged, from the `X-Actor-Request-ID` header of the incoming request. Required for multi-tenant Server Actor runs.
176
177
  * @returns Empty response object.
177
178
  * @see https://docs.apify.com/api/v2/post-charge-run
178
179
  * @since Added in 2.11.0
@@ -188,6 +189,7 @@ export declare class RunClient extends ResourceClient {
188
189
  * Unlike the `waitForFinish` parameter in {@link get}, this method can wait indefinitely
189
190
  * by polling the run status. It uses the `waitForFinish` parameter internally (max 60s per call)
190
191
  * and continuously polls until the run finishes or the timeout is reached.
192
+ * Rejects if the run keeps returning 404 for 3 seconds.
191
193
  *
192
194
  * @param options - Wait options
193
195
  * @param options.waitSecs - Maximum time to wait for the run to finish, in seconds. If the limit is reached, the returned promise resolves to a run object that will have status `READY` or `RUNNING`. If omitted, waits indefinitely.
@@ -339,6 +341,13 @@ export interface RunChargeOptions {
339
341
  count?: number;
340
342
  /** Defaults to runId-eventName-timestamp */
341
343
  idempotencyKey?: string;
344
+ /**
345
+ * ID of the Server Actor request being charged, taken from the `X-Actor-Request-ID` header of the incoming request.
346
+ * Required for multi-tenant Server Actor runs, where it maps the charge to the caller's account instead of the account that started the run.
347
+ * Ignored elsewhere.
348
+ * @since Added in 2.26.0
349
+ */
350
+ requestId?: string;
342
351
  }
343
352
  /**
344
353
  * Options for waiting for a Run to finish.
@@ -253,6 +253,7 @@ class RunClient extends resource_client_1.ResourceClient {
253
253
  * @param options.eventName - **Required.** Name of the event to charge for.
254
254
  * @param options.count - Number of times to charge the event. Default is 1.
255
255
  * @param options.idempotencyKey - Optional key to ensure the charge is not duplicated. If not provided, one is auto-generated.
256
+ * @param options.requestId - ID of the Server Actor request being charged, from the `X-Actor-Request-ID` header of the incoming request. Required for multi-tenant Server Actor runs.
256
257
  * @returns Empty response object.
257
258
  * @see https://docs.apify.com/api/v2/post-charge-run
258
259
  * @since Added in 2.11.0
@@ -262,6 +263,7 @@ class RunClient extends resource_client_1.ResourceClient {
262
263
  eventName: ow_1.default.string,
263
264
  count: ow_1.default.optional.number,
264
265
  idempotencyKey: ow_1.default.optional.string,
266
+ requestId: ow_1.default.optional.string,
265
267
  }));
266
268
  const count = options.count ?? 1;
267
269
  /** To avoid duplicates during the same milisecond, doesn't need to by crypto-secure. */
@@ -273,6 +275,7 @@ class RunClient extends resource_client_1.ResourceClient {
273
275
  data: {
274
276
  eventName: options.eventName,
275
277
  count,
278
+ requestId: options.requestId,
276
279
  },
277
280
  headers: {
278
281
  [RUN_CHARGE_IDEMPOTENCY_HEADER]: idempotencyKey,
@@ -291,6 +294,7 @@ class RunClient extends resource_client_1.ResourceClient {
291
294
  * Unlike the `waitForFinish` parameter in {@link get}, this method can wait indefinitely
292
295
  * by polling the run status. It uses the `waitForFinish` parameter internally (max 60s per call)
293
296
  * and continuously polls until the run finishes or the timeout is reached.
297
+ * Rejects if the run keeps returning 404 for 3 seconds.
294
298
  *
295
299
  * @param options - Wait options
296
300
  * @param options.waitSecs - Maximum time to wait for the run to finish, in seconds. If the limit is reached, the returned promise resolves to a run object that will have status `READY` or `RUNNING`. If omitted, waits indefinitely.
@@ -73,6 +73,11 @@ export interface User {
73
73
  githubUsername?: string;
74
74
  websiteUrl?: string;
75
75
  twitterUsername?: string;
76
+ /**
77
+ * Markdown README shown on the user's public profile page.
78
+ * @since Added in 2.26.0
79
+ */
80
+ readme?: string | null;
76
81
  };
77
82
  id?: string;
78
83
  email?: string;
package/dist/utils.d.ts CHANGED
@@ -45,6 +45,16 @@ export interface CompressedValue {
45
45
  data: Buffer;
46
46
  encoding: 'br' | 'gzip';
47
47
  }
48
+ /**
49
+ * Decides whether a request body with the given content type is worth compressing.
50
+ *
51
+ * Images, audio, video and archives already carry their own compression. Running them through brotli or gzip
52
+ * burns CPU, holds a second full copy of the body in memory, and usually produces output slightly larger than
53
+ * the input. Formats that are raw despite such a media type, for example `image/bmp` or `audio/wav`, are still
54
+ * compressed. A body with no content type is assumed to be compressible.
55
+ * @internal
56
+ */
57
+ export declare function isCompressibleContentType(contentType?: string): boolean;
48
58
  /**
49
59
  * Compress the passed value using brotli, falling back to gzip. Returns undefined if the data is
50
60
  * too small / wrong type, or if neither algorithm is available.
package/dist/utils.js CHANGED
@@ -5,6 +5,7 @@ exports.pluckData = pluckData;
5
5
  exports.catchNotFoundOrThrow = catchNotFoundOrThrow;
6
6
  exports.parseDateFields = parseDateFields;
7
7
  exports.stringifyWebhooksToBase64 = stringifyWebhooksToBase64;
8
+ exports.isCompressibleContentType = isCompressibleContentType;
8
9
  exports.maybeCompressValue = maybeCompressValue;
9
10
  exports.sliceArrayByByteLength = sliceArrayByByteLength;
10
11
  exports.isNode = isNode;
@@ -20,6 +21,51 @@ const NOT_FOUND_STATUS_CODE = 404;
20
21
  const RECORD_NOT_FOUND_TYPE = 'record-not-found';
21
22
  const RECORD_OR_TOKEN_NOT_FOUND_TYPE = 'record-or-token-not-found';
22
23
  const MIN_COMPRESS_BYTES = 1024;
24
+ /** Media type prefixes whose payloads carry their own compression, so compressing the request body is wasted work. */
25
+ const ALREADY_COMPRESSED_MEDIA_TYPE_PREFIXES = ['audio/', 'image/', 'video/'];
26
+ /** Exact media types whose payloads carry their own compression. */
27
+ const ALREADY_COMPRESSED_MEDIA_TYPES = new Set([
28
+ 'application/epub+zip',
29
+ 'application/gzip',
30
+ 'application/java-archive',
31
+ 'application/vnd.android.package-archive',
32
+ 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
33
+ 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
34
+ 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
35
+ 'application/vnd.rar',
36
+ 'application/x-7z-compressed',
37
+ 'application/x-bzip',
38
+ 'application/x-bzip2',
39
+ 'application/x-gzip',
40
+ 'application/x-rar-compressed',
41
+ 'application/x-xz',
42
+ 'application/x-zip-compressed',
43
+ 'application/zip',
44
+ 'application/zstd',
45
+ 'font/woff',
46
+ 'font/woff2',
47
+ ]);
48
+ /** Uncompressed media types that sit under an already-compressed prefix, so compressing them still pays off. */
49
+ const COMPRESSIBLE_MEDIA_TYPES = new Set([
50
+ 'audio/aiff',
51
+ 'audio/basic',
52
+ 'audio/l16',
53
+ 'audio/l24',
54
+ 'audio/midi',
55
+ 'audio/vnd.wave',
56
+ 'audio/wav',
57
+ 'audio/wave',
58
+ 'audio/x-aiff',
59
+ 'audio/x-wav',
60
+ 'image/bmp',
61
+ 'image/tiff',
62
+ 'image/vnd.adobe.photoshop',
63
+ 'image/vnd.microsoft.icon',
64
+ 'image/x-icon',
65
+ 'image/x-ms-bmp',
66
+ ]);
67
+ /** Structured syntax suffixes marking a media type as text even under an already-compressed prefix (`image/svg+xml`). */
68
+ const COMPRESSIBLE_MEDIA_TYPE_SUFFIXES = ['+json', '+xml'];
23
69
  /**
24
70
  * Returns object's 'data' property or throws if parameter is not an object,
25
71
  * or an object without a 'data' property.
@@ -123,6 +169,28 @@ async function gzipValue(value) {
123
169
  }
124
170
  return gzipPromisified(value);
125
171
  }
172
+ /**
173
+ * Decides whether a request body with the given content type is worth compressing.
174
+ *
175
+ * Images, audio, video and archives already carry their own compression. Running them through brotli or gzip
176
+ * burns CPU, holds a second full copy of the body in memory, and usually produces output slightly larger than
177
+ * the input. Formats that are raw despite such a media type, for example `image/bmp` or `audio/wav`, are still
178
+ * compressed. A body with no content type is assumed to be compressible.
179
+ * @internal
180
+ */
181
+ function isCompressibleContentType(contentType) {
182
+ if (!contentType)
183
+ return true;
184
+ // `Content-Type` is case-insensitive and may carry parameters, for example `text/plain; charset=utf-8`.
185
+ const mediaType = contentType.split(';', 1)[0].trim().toLowerCase();
186
+ if (COMPRESSIBLE_MEDIA_TYPES.has(mediaType))
187
+ return true;
188
+ if (COMPRESSIBLE_MEDIA_TYPE_SUFFIXES.some((suffix) => mediaType.endsWith(suffix)))
189
+ return true;
190
+ if (ALREADY_COMPRESSED_MEDIA_TYPES.has(mediaType))
191
+ return false;
192
+ return !ALREADY_COMPRESSED_MEDIA_TYPE_PREFIXES.some((prefix) => mediaType.startsWith(prefix));
193
+ }
126
194
  /**
127
195
  * Compress the passed value using brotli, falling back to gzip. Returns undefined if the data is
128
196
  * too small / wrong type, or if neither algorithm is available.