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

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 (52) hide show
  1. package/README.md +6 -0
  2. package/dist/apify_api_error.d.ts +2 -1
  3. package/dist/apify_api_error.js +2 -1
  4. package/dist/apify_client_error.d.ts +10 -0
  5. package/dist/apify_client_error.js +10 -0
  6. package/dist/base/api_client.js +8 -20
  7. package/dist/base/resource_client.js +8 -8
  8. package/dist/bundle.js +13 -13
  9. package/dist/bundle.js.map +1 -1
  10. package/dist/generated/api.d.ts +2300 -690
  11. package/dist/generated/schemas.d.ts +1720 -246
  12. package/dist/generated/schemas.js +416 -75
  13. package/dist/http_clients/axios.d.ts +2 -1
  14. package/dist/http_clients/axios.js +6 -4
  15. package/dist/http_clients/base.d.ts +80 -20
  16. package/dist/http_clients/base.js +127 -40
  17. package/dist/http_compressors/index.d.ts +2 -0
  18. package/dist/http_compressors/index.js +1 -0
  19. package/dist/http_compressors/resolve.d.ts +4 -3
  20. package/dist/http_compressors/resolve.js +4 -1
  21. package/dist/http_compressors/zstd.d.ts +34 -0
  22. package/dist/http_compressors/zstd.js +43 -0
  23. package/dist/index.d.ts +2 -0
  24. package/dist/index.js +2 -0
  25. package/dist/invalid_response_body_error.d.ts +5 -4
  26. package/dist/invalid_response_body_error.js +5 -4
  27. package/dist/models.d.ts +30 -61
  28. package/dist/resource_clients/actor.d.ts +30 -0
  29. package/dist/resource_clients/actor.js +43 -0
  30. package/dist/resource_clients/actor_server.d.ts +149 -0
  31. package/dist/resource_clients/actor_server.js +199 -0
  32. package/dist/resource_clients/actor_version.d.ts +5 -0
  33. package/dist/resource_clients/dataset.d.ts +33 -4
  34. package/dist/resource_clients/dataset.js +16 -54
  35. package/dist/resource_clients/key_value_store.d.ts +51 -11
  36. package/dist/resource_clients/key_value_store.js +59 -15
  37. package/dist/resource_clients/log.d.ts +29 -3
  38. package/dist/resource_clients/log.js +7 -11
  39. package/dist/resource_clients/request_queue.d.ts +9 -0
  40. package/dist/resource_clients/request_queue.js +9 -6
  41. package/dist/resource_clients/run.d.ts +9 -0
  42. package/dist/resource_clients/run.js +6 -3
  43. package/dist/response_validation_error.d.ts +2 -1
  44. package/dist/response_validation_error.js +2 -1
  45. package/dist/runtime/node.js +44 -6
  46. package/dist/runtime/types.d.ts +9 -1
  47. package/dist/runtime/web.js +4 -1
  48. package/dist/schemas.d.ts +369 -3
  49. package/dist/schemas.js +25 -3
  50. package/dist/utils.d.ts +23 -26
  51. package/dist/utils.js +32 -25
  52. package/package.json +23 -23
@@ -5,9 +5,10 @@ import { ResourceClient } from '../base/resource_client.js';
5
5
  import * as schemas from '../schemas.js';
6
6
  import { timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
7
7
  import { runtime } from '#runtime';
8
- import { anyObjectSchema, applyQueryParamsToUrl, catchNotFoundOrThrow, isBuffer, isStream, parseArgument, parseResponse, } from '../utils.js';
8
+ import { anyObjectSchema, applyQueryParamsToUrl, catchNotFoundOrThrow, isBlob, isBuffer, isStream, minForLimitParam, parseArgument, parseResponse, } from '../utils.js';
9
9
  const listKeysOptionsSchema = z.strictObject({
10
10
  limit: z.number().min(0).optional(),
11
+ chunkSize: z.number().positive().optional(),
11
12
  exclusiveStartKey: z.string().optional(),
12
13
  collection: z.string().optional(),
13
14
  prefix: z.string().optional(),
@@ -15,13 +16,14 @@ const listKeysOptionsSchema = z.strictObject({
15
16
  ...timeoutOptionsShape,
16
17
  });
17
18
  const nonEmptyKeySchema = z.string().min(1);
18
- // `signature` is left out - this method produces one. The options type omits it to match.
19
+ // `chunkSize` (client-side only) and `signature` (which this method produces) are left out. The options type omits
20
+ // both to match.
19
21
  const createKeysPublicUrlOptionsSchema = z.strictObject({
20
22
  limit: z.number().min(0).optional(),
21
23
  exclusiveStartKey: z.string().optional(),
22
24
  collection: z.string().optional(),
23
25
  prefix: z.string().optional(),
24
- expiresInSecs: z.number().optional(),
26
+ expiresInSecs: z.number().positive().optional(),
25
27
  ...timeoutOptionsShape,
26
28
  });
27
29
  const keySchema = z.string();
@@ -44,6 +46,7 @@ const recordSchema = z.strictObject({
44
46
  typeof value !== 'function' &&
45
47
  (typeof value !== 'number' || Number.isFinite(value)), 'Expected a JSON-serializable value, binary data, or a stream'),
46
48
  contentType: z.string().min(1).optional(),
49
+ contentEncoding: z.string().trim().min(1).optional(),
47
50
  });
48
51
  const recordOptionsSchema = z.strictObject({
49
52
  ...timeoutOptionsShape,
@@ -135,6 +138,8 @@ export class KeyValueStoreClient extends ResourceClient {
135
138
  *
136
139
  * @param options - Listing options
137
140
  * @param options.limit - Maximum number of keys to return. Default is 1000.
141
+ * @param options.chunkSize - Maximum number of keys requested per API call when iterating across pages. `limit`
142
+ * then caps the total across all pages.
138
143
  * @param options.exclusiveStartKey - Key to start listing from (for pagination). The listing starts with the next key after this one.
139
144
  * @param options.collection - Filter keys by collection name.
140
145
  * @param options.prefix - Filter keys that start with this prefix.
@@ -164,7 +169,8 @@ export class KeyValueStoreClient extends ResourceClient {
164
169
  * ```
165
170
  */
166
171
  listKeys(options = {}) {
167
- const { timeoutSecs = 'medium', signal, ...parsed } = parseArgument(options, listKeysOptionsSchema, 'KeyValueClientListKeysOptions');
172
+ // `chunkSize` only sizes the page requests; it is not an API parameter, so it must not reach the query string.
173
+ const { chunkSize, timeoutSecs = 'medium', signal, ...parsed } = parseArgument(options, listKeysOptionsSchema, 'KeyValueClientListKeysOptions');
168
174
  const getPaginatedList = async (kvsListOptions = {}) => {
169
175
  const response = await this.httpClient.call({
170
176
  url: this.buildUrl('keys'),
@@ -175,7 +181,7 @@ export class KeyValueStoreClient extends ResourceClient {
175
181
  });
176
182
  return parseResponse(response, schemas.ListOfKeys());
177
183
  };
178
- const paginatedListPromise = getPaginatedList(parsed);
184
+ const paginatedListPromise = getPaginatedList({ ...parsed, limit: minForLimitParam(parsed.limit, chunkSize) });
179
185
  async function* asyncGenerator() {
180
186
  let currentPage = await paginatedListPromise;
181
187
  yield* currentPage.items;
@@ -188,7 +194,7 @@ export class KeyValueStoreClient extends ResourceClient {
188
194
  ) {
189
195
  const newOptions = {
190
196
  ...parsed,
191
- limit: remainingItems,
197
+ limit: minForLimitParam(remainingItems, chunkSize),
192
198
  exclusiveStartKey: currentPage.nextExclusiveStartKey,
193
199
  };
194
200
  currentPage = await getPaginatedList(newOptions);
@@ -240,7 +246,8 @@ export class KeyValueStoreClient extends ResourceClient {
240
246
  * the URL will include a cryptographic signature which allows access without authentication.
241
247
  *
242
248
  * @param options - URL generation options (extends all options from {@link listKeys})
243
- * @param options.expiresInSecs - Number of seconds until the signed URL expires. If omitted, the URL never expires.
249
+ * @param options.expiresInSecs - Number of seconds until the signed URL expires. Must be positive. If omitted, the URL
250
+ * never expires.
244
251
  * @param options.limit - Maximum number of keys to return.
245
252
  * @param options.prefix - Filter keys by prefix.
246
253
  * @param options.timeoutSecs - Timeout for the API request that fetches the store. Default is `'long'`.
@@ -358,21 +365,33 @@ export class KeyValueStoreClient extends ResourceClient {
358
365
  * to be valid JSON already, or {@link getRecord} fails to parse it back.
359
366
  *
360
367
  * **Note about streams:** If the value is a stream object (has `.pipe` and `.on` methods),
361
- * the upload cannot be retried on failure or follow redirects. For reliable uploads,
362
- * buffer the entire stream into memory first.
368
+ * the upload cannot be retried on failure or follow redirects. For reliable uploads of a file,
369
+ * pass a `Blob` from `fs.openAsBlob()` instead: it is read again for every attempt and never held
370
+ * in memory whole.
363
371
  *
364
372
  * @param record - The record to store
365
373
  * @param record.key - Record key (unique identifier)
366
- * @param record.value - Record value (a JSON-serializable value, Buffer, ArrayBuffer, typed array, or Readable)
374
+ * @param record.value - Record value (a JSON-serializable value, Buffer, ArrayBuffer, typed array, Blob, or
375
+ * Readable)
367
376
  * @param record.contentType - Optional MIME type. Auto-detected if not provided:
368
377
  * - Objects: `'application/json; charset=utf-8'`
369
378
  * - Strings: `'text/plain; charset=utf-8'`
379
+ * - Blobs: their `type`, or `'application/octet-stream'` when it is empty
370
380
  * - Binary values and streams: `'application/octet-stream'`
371
381
  *
372
382
  * Worth setting for media and archives: the client skips compressing a body
373
383
  * whose content type already carries its own compression. The
374
384
  * `'application/octet-stream'` fallback is treated as compressible, because
375
385
  * it could hold any binary data.
386
+ * @param record.contentEncoding - Optional encoding already applied to `value`, sent as the `Content-Encoding`
387
+ * header. Set it to upload a pre-compressed value: the client then sends the
388
+ * bytes as they are and does not compress them again. The API accepts `gzip`,
389
+ * `br`, `zstd`, `deflate`, and `identity`, and stores the record exactly as
390
+ * uploaded, so this is also the encoding the record is served with. Only binary
391
+ * values and streams can carry a compression, so any encoding other than
392
+ * `identity` throws a `TypeError` when `value` is a string, or a plain object,
393
+ * array, or other value that the client serializes to JSON. Node.js only, since
394
+ * browsers cannot send the header to the API.
376
395
  * @param options - Storage options
377
396
  * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
378
397
  * @param options.doNotRetryTimeouts - If `true`, don't retry on timeout errors. Default is `false`.
@@ -400,18 +419,40 @@ export class KeyValueStoreClient extends ResourceClient {
400
419
  * value: imageBuffer,
401
420
  * contentType: 'image/png'
402
421
  * });
422
+ *
423
+ * // Store a gzipped file without compressing it again
424
+ * const gzippedReport = await readFile('report.json.gz');
425
+ * await client.keyValueStore('my-store').setRecord({
426
+ * key: 'report.json',
427
+ * value: gzippedReport,
428
+ * contentType: 'application/json',
429
+ * contentEncoding: 'gzip'
430
+ * });
403
431
  * ```
404
432
  */
405
433
  async setRecord(record, options = {}) {
406
434
  parseArgument(record, recordSchema);
407
435
  const parsed = parseArgument(options, recordOptionsSchema, 'KeyValueStoreRecordOptions');
408
- const { key } = record;
436
+ const { key, contentEncoding } = record;
409
437
  let { value, contentType } = record;
410
438
  const { timeoutSecs = 'long', signal, doNotRetryTimeouts } = parsed;
411
- const isValueStreamOrBuffer = isStream(value) || isBuffer(value);
439
+ if (contentEncoding !== undefined && !runtime.isNode) {
440
+ throw new Error('The contentEncoding option can only be used in Node.js environment.');
441
+ }
442
+ const isBinaryValue = isStream(value) || isBuffer(value) || isBlob(value);
443
+ // The client forwards the header without inspecting the body, so a string or a value serialized to JSON, which
444
+ // cannot hold compressed bytes, would be stored under an encoding that misdescribes it.
445
+ const declaresCompression = contentEncoding !== undefined && contentEncoding.trim().toLowerCase() !== 'identity';
446
+ if (declaresCompression && !isBinaryValue) {
447
+ throw new TypeError(`Cannot upload a value of type ${typeof value} with Content-Encoding: ${contentEncoding}. ` +
448
+ 'An encoding other than identity declares the value is already compressed, so pass the ' +
449
+ 'compressed bytes as a Buffer, an ArrayBuffer, a typed array, a Blob, or a readable stream.');
450
+ }
412
451
  // To allow saving Objects to JSON without providing content type
413
452
  if (!contentType) {
414
- if (isValueStreamOrBuffer)
453
+ if (isBlob(value))
454
+ contentType = value.type || 'application/octet-stream';
455
+ else if (isBinaryValue)
415
456
  contentType = 'application/octet-stream';
416
457
  else if (typeof value === 'string')
417
458
  contentType = 'text/plain; charset=utf-8';
@@ -419,7 +460,7 @@ export class KeyValueStoreClient extends ResourceClient {
419
460
  contentType = 'application/json; charset=utf-8';
420
461
  }
421
462
  const isContentTypeJson = contentType.startsWith('application/json');
422
- if (isContentTypeJson && !isValueStreamOrBuffer && typeof value !== 'string') {
463
+ if (isContentTypeJson && !isBinaryValue && typeof value !== 'string') {
423
464
  try {
424
465
  value = JSON.stringify(value, null, 2);
425
466
  }
@@ -433,7 +474,10 @@ export class KeyValueStoreClient extends ResourceClient {
433
474
  method: 'PUT',
434
475
  params: this.buildParams(),
435
476
  data: value,
436
- headers: contentType ? { 'content-type': contentType } : undefined,
477
+ headers: {
478
+ 'content-type': contentType,
479
+ ...(contentEncoding !== undefined && { 'content-encoding': contentEncoding }),
480
+ },
437
481
  doNotRetryTimeouts,
438
482
  timeoutSecs,
439
483
  signal,
@@ -19,6 +19,9 @@ import type { TimeoutOptions } from '../timeouts.js';
19
19
  * const log = await runClient.log().get();
20
20
  * console.log(log);
21
21
  *
22
+ * // Get the log content as raw bytes
23
+ * const logBuffer = await runClient.log().get({ buffer: true });
24
+ *
22
25
  * // Stream the log in real-time
23
26
  * const stream = await runClient.log().stream();
24
27
  * stream.on('line', (line) => console.log(line));
@@ -34,14 +37,26 @@ export declare class LogClient extends ResourceClient {
34
37
  /**
35
38
  * Retrieves the log as a string.
36
39
  *
40
+ * The `buffer` option only selects the return type: the bytes come back as a Buffer (Node.js) or ArrayBuffer
41
+ * (browser), not decoded to a string. Either way the whole log is downloaded in one response; to read it
42
+ * incrementally, use {@link LogClient.stream}.
43
+ *
37
44
  * @param options - Log retrieval options.
38
45
  * @param options.raw - If `true`, returns raw log content without any processing. Default is `false`.
46
+ * @param options.buffer - If `true`, the log is returned as a Buffer (Node.js) or ArrayBuffer (browser) instead of a
47
+ * string. It does not change how the log is fetched.
39
48
  * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
40
- * @returns The log content as a string, or `undefined` if it does not exist. A chained client such as
41
- * `run.log()` throws an `ApifyApiError` on a 404, since the run itself may be what is missing.
49
+ * @returns The log content, or `undefined` if it does not exist. A chained client such as `run.log()` throws an
50
+ * `ApifyApiError` on a 404, since the run itself may be what is missing.
42
51
  * @see https://docs.apify.com/api/v2/log-get
43
52
  */
44
- get(options?: LogOptions): Promise<string | undefined>;
53
+ get(options?: LogGetOptions & {
54
+ buffer?: false;
55
+ }): Promise<string | undefined>;
56
+ get(options: LogGetOptions & {
57
+ buffer: true;
58
+ }): Promise<Buffer | undefined>;
59
+ get(options?: LogGetOptions): Promise<string | Buffer | undefined>;
45
60
  /**
46
61
  * Retrieves the log as a Readable stream. Only works in Node.js.
47
62
  *
@@ -61,6 +76,17 @@ export interface LogOptions extends TimeoutOptions {
61
76
  /** @default false */
62
77
  raw?: boolean;
63
78
  }
79
+ /**
80
+ * Options for {@link LogClient.get}.
81
+ */
82
+ export interface LogGetOptions extends LogOptions {
83
+ /**
84
+ * If `true`, the log is returned as a Buffer (Node.js) or ArrayBuffer (browser) instead of a string. It only selects
85
+ * the return type; to read the log incrementally, use {@link LogClient.stream}.
86
+ * @default false
87
+ */
88
+ buffer?: boolean;
89
+ }
64
90
  /**
65
91
  * Logger for redirected actor logs.
66
92
  * @since Added in 2.20.0
@@ -13,6 +13,7 @@ const EMPTY_LOG_STREAM_RETRY_MILLIS = 500;
13
13
  /** Upper bound on the pause between reopens of an empty log stream. */
14
14
  const EMPTY_LOG_STREAM_MAX_RETRY_MILLIS = 5_000;
15
15
  const logOptionsSchema = z.strictObject({ raw: z.boolean().optional(), ...timeoutOptionsShape });
16
+ const logGetOptionsSchema = logOptionsSchema.extend({ buffer: z.boolean().optional() });
16
17
  /** How long `StreamedLog.stop()` waits for lines already in flight before aborting the log stream request. */
17
18
  const STOP_GRACE_MILLIS = 1000;
18
19
  /**
@@ -30,6 +31,9 @@ const STOP_GRACE_MILLIS = 1000;
30
31
  * const log = await runClient.log().get();
31
32
  * console.log(log);
32
33
  *
34
+ * // Get the log content as raw bytes
35
+ * const logBuffer = await runClient.log().get({ buffer: true });
36
+ *
33
37
  * // Stream the log in real-time
34
38
  * const stream = await runClient.log().stream();
35
39
  * stream.on('line', (line) => console.log(line));
@@ -47,18 +51,8 @@ export class LogClient extends ResourceClient {
47
51
  ...options,
48
52
  });
49
53
  }
50
- /**
51
- * Retrieves the log as a string.
52
- *
53
- * @param options - Log retrieval options.
54
- * @param options.raw - If `true`, returns raw log content without any processing. Default is `false`.
55
- * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
56
- * @returns The log content as a string, or `undefined` if it does not exist. A chained client such as
57
- * `run.log()` throws an `ApifyApiError` on a 404, since the run itself may be what is missing.
58
- * @see https://docs.apify.com/api/v2/log-get
59
- */
60
54
  async get(options = {}) {
61
- const { timeoutSecs = 'long', signal, ...params } = parseArgument(options, logOptionsSchema, 'LogOptions');
55
+ const { timeoutSecs = 'long', signal, buffer, ...params } = parseArgument(options, logGetOptionsSchema, 'LogGetOptions');
62
56
  const requestOpts = {
63
57
  url: this.buildUrl(),
64
58
  method: 'GET',
@@ -66,6 +60,8 @@ export class LogClient extends ResourceClient {
66
60
  timeoutSecs,
67
61
  signal,
68
62
  };
63
+ if (buffer)
64
+ requestOpts.responseType = 'buffer';
69
65
  try {
70
66
  const response = await this.httpClient.call(requestOpts);
71
67
  return cast(response.data);
@@ -301,6 +301,8 @@ export declare class RequestQueueClient extends ResourceClient {
301
301
  * queue contents.
302
302
  *
303
303
  * @param options - Pagination options
304
+ * @param options.chunkSize - Maximum number of requests fetched per API call when iterating across pages. `limit`
305
+ * then caps the total across all pages.
304
306
  * @param options.timeoutSecs - Timeout for each API request. Default is `'medium'`.
305
307
  * @returns List of requests with pagination information
306
308
  * @see https://docs.apify.com/api/v2/request-queue-requests-get
@@ -383,6 +385,13 @@ export type RequestQueueListRequestsFilter = 'locked' | 'pending';
383
385
  */
384
386
  export interface RequestQueueClientListRequestsOptions extends TimeoutOptions {
385
387
  limit?: number;
388
+ /**
389
+ * Maximum number of requests returned in one API response. When the call is iterated with `for await`, the iterator
390
+ * fetches requests in chunks of this size and yields them one by one, until `limit` is reached or the RQ is
391
+ * exhausted. Awaiting the call returns only the first chunk. Without it, the API's default page size
392
+ * applies.
393
+ */
394
+ chunkSize?: number;
386
395
  /**
387
396
  * @since Added in 2.23.2
388
397
  */
@@ -5,7 +5,7 @@ import { ResourceClient } from '../base/resource_client.js';
5
5
  import { ResponseValidationError } from '../response_validation_error.js';
6
6
  import * as schemas from '../schemas.js';
7
7
  import { optionalSignalSchema, optionalTimeoutSchema, timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
8
- import { anyObjectSchema, catchNotFoundOrThrow, isNonArrayObject, parseArgument, parseResponse, RequestQueuePaginationIterator, sleep, splitIntoJsonArrayBatches, utf8ByteLength, } from '../utils.js';
8
+ import { anyObjectSchema, catchNotFoundOrThrow, isNonArrayObject, minForLimitParam, parseArgument, parseResponse, RequestQueuePaginationIterator, sleep, splitIntoJsonArrayBatches, utf8ByteLength, } from '../utils.js';
9
9
  const DEFAULT_PARALLEL_BATCH_ADD_REQUESTS = 5;
10
10
  const DEFAULT_UNPROCESSED_RETRIES_BATCH_ADD_REQUESTS = 3;
11
11
  const DEFAULT_MIN_DELAY_BETWEEN_UNPROCESSED_REQUESTS_RETRIES_MILLIS = 500;
@@ -39,6 +39,7 @@ const prolongRequestLockOptionsSchema = z.strictObject({
39
39
  const requestFilterSchema = z.array(z.enum(['locked', 'pending'])).min(1);
40
40
  const listRequestsOptionsSchema = z.strictObject({
41
41
  limit: z.number().min(0).optional(),
42
+ chunkSize: z.number().positive().optional(),
42
43
  cursor: z.string().optional(),
43
44
  filter: requestFilterSchema.optional(),
44
45
  ...timeoutOptionsShape,
@@ -622,15 +623,17 @@ export class RequestQueueClient extends ResourceClient {
622
623
  * queue contents.
623
624
  *
624
625
  * @param options - Pagination options
626
+ * @param options.chunkSize - Maximum number of requests fetched per API call when iterating across pages. `limit`
627
+ * then caps the total across all pages.
625
628
  * @param options.timeoutSecs - Timeout for each API request. Default is `'medium'`.
626
629
  * @returns List of requests with pagination information
627
630
  * @see https://docs.apify.com/api/v2/request-queue-requests-get
628
631
  * @since Added in 2.5.1
629
632
  */
630
633
  listRequests(options = {}) {
631
- // `timeoutSecs` and `signal` apply to every page request; they are not API parameters, so they must not reach
632
- // the query string.
633
- const { timeoutSecs, signal, ...parsed } = parseArgument(options, listRequestsOptionsSchema, 'RequestQueueClientListRequestsOptions');
634
+ // `chunkSize` only sizes the page requests, and `timeoutSecs` and `signal` apply to every one of them; none of
635
+ // them is an API parameter, so they must not reach the query string.
636
+ const { chunkSize, timeoutSecs, signal, ...parsed } = parseArgument(options, listRequestsOptionsSchema, 'RequestQueueClientListRequestsOptions');
634
637
  const pageTimeout = this.#resolveTimeout(timeoutSecs, 'medium');
635
638
  const getPaginatedList = async (rqListOptions = {}) => {
636
639
  const response = await this.httpClient.call({
@@ -646,7 +649,7 @@ export class RequestQueueClient extends ResourceClient {
646
649
  });
647
650
  return parseResponse(response, schemas.ListOfRequests());
648
651
  };
649
- const paginatedListPromise = getPaginatedList(parsed);
652
+ const paginatedListPromise = getPaginatedList({ ...parsed, limit: minForLimitParam(parsed.limit, chunkSize) });
650
653
  async function* asyncGenerator() {
651
654
  let currentPage = await paginatedListPromise;
652
655
  yield* currentPage.items;
@@ -659,7 +662,7 @@ export class RequestQueueClient extends ResourceClient {
659
662
  ) {
660
663
  const newOptions = {
661
664
  ...parsed,
662
- limit: remainingItems,
665
+ limit: minForLimitParam(remainingItems, chunkSize),
663
666
  cursor: currentPage.nextCursor,
664
667
  };
665
668
  currentPage = await getPaginatedList(newOptions);
@@ -186,6 +186,7 @@ export declare class RunClient extends ResourceClient {
186
186
  * @param options.eventName - **Required.** Name of the event to charge for.
187
187
  * @param options.count - Number of times to charge the event. Default is 1.
188
188
  * @param options.idempotencyKey - Optional key to ensure the charge is not duplicated. If not provided, one is auto-generated.
189
+ * @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.
189
190
  * @param options.timeoutSecs - Timeout for the API request. Default is `'short'`.
190
191
  * @returns Empty response object.
191
192
  * @see https://docs.apify.com/api/v2/post-charge-run
@@ -411,6 +412,12 @@ export interface RunChargeOptions extends TimeoutOptions {
411
412
  count?: number;
412
413
  /** Defaults to runId-eventName-timestamp */
413
414
  idempotencyKey?: string;
415
+ /**
416
+ * ID of the Server Actor request being charged, taken from the `X-Actor-Request-ID` header of the incoming request.
417
+ * 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.
418
+ * Ignored elsewhere.
419
+ */
420
+ requestId?: string;
414
421
  }
415
422
  /**
416
423
  * Options for waiting for a Run to finish.
@@ -427,6 +434,8 @@ export interface RunWaitForFinishOptions extends TimeoutOptions {
427
434
  * Options for iterating over the items of a run's default dataset while the run is still producing them.
428
435
  */
429
436
  export interface RunIterateDatasetItemsOptions extends PaginationOptions, TimeoutOptions {
437
+ /** Maximum number of dataset rows requested per API call. Default is 1000. */
438
+ chunkSize?: number;
430
439
  /** If `true`, returns only non-empty items and skips hidden fields. */
431
440
  clean?: boolean;
432
441
  /** Field names to include in the items. Omits all other fields. */
@@ -5,7 +5,7 @@ import { ResourceClient } from '../base/resource_client.js';
5
5
  import * as schemas from '../schemas.js';
6
6
  import { optionalSignalSchema, optionalTimeoutSchema, timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
7
7
  import { runtime } from '#runtime';
8
- import { anyObjectSchema, paginationOptionsShape, parseArgument, parseResponse, SCANNED_COUNT } from '../utils.js';
8
+ import { anyObjectSchema, paginationOptionsShape, parseArgument, parseResponse } from '../utils.js';
9
9
  import { DatasetClient } from './dataset.js';
10
10
  import { KeyValueStoreClient } from './key_value_store.js';
11
11
  import { LogClient, LoggerActorRedirect, StreamedLog } from './log.js';
@@ -32,6 +32,7 @@ const chargeOptionsSchema = z.strictObject({
32
32
  eventName: z.string(),
33
33
  count: z.number().default(1),
34
34
  idempotencyKey: z.string().optional(),
35
+ requestId: z.string().optional(),
35
36
  ...timeoutOptionsShape,
36
37
  });
37
38
  const waitForFinishOptionsSchema = z.strictObject({ waitSecs: z.number().optional(), ...timeoutOptionsShape });
@@ -294,13 +295,14 @@ export class RunClient extends ResourceClient {
294
295
  * @param options.eventName - **Required.** Name of the event to charge for.
295
296
  * @param options.count - Number of times to charge the event. Default is 1.
296
297
  * @param options.idempotencyKey - Optional key to ensure the charge is not duplicated. If not provided, one is auto-generated.
298
+ * @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.
297
299
  * @param options.timeoutSecs - Timeout for the API request. Default is `'short'`.
298
300
  * @returns Empty response object.
299
301
  * @see https://docs.apify.com/api/v2/post-charge-run
300
302
  * @since Added in 2.11.0
301
303
  */
302
304
  async charge(options) {
303
- const { eventName, count, idempotencyKey: providedIdempotencyKey, timeoutSecs = 'short', signal, } = parseArgument(options, chargeOptionsSchema, 'RunChargeOptions');
305
+ const { eventName, count, idempotencyKey: providedIdempotencyKey, timeoutSecs = 'short', requestId, signal, } = parseArgument(options, chargeOptionsSchema, 'RunChargeOptions');
304
306
  /** To avoid duplicates during the same milisecond, doesn't need to by crypto-secure. */
305
307
  const randomSuffix = (Math.random() + 1).toString(36).slice(3, 8);
306
308
  const idempotencyKey = providedIdempotencyKey ?? `${this.id}-${eventName}-${Date.now()}-${randomSuffix}`;
@@ -310,6 +312,7 @@ export class RunClient extends ResourceClient {
310
312
  data: {
311
313
  eventName,
312
314
  count,
315
+ requestId,
313
316
  },
314
317
  headers: {
315
318
  [RUN_CHARGE_IDEMPOTENCY_HEADER]: idempotencyKey,
@@ -534,7 +537,7 @@ export class RunClient extends ResourceClient {
534
537
  yield* page.items;
535
538
  // Only an empty page marks the end, as filters can shorten a full one. A page that `clean`, `skipEmpty` or
536
539
  // `unwind` emptied past a lagging `itemCount` reports no scanned rows either, so a plain read checks.
537
- const isEmpty = page.items.length === 0 && !page[SCANNED_COUNT];
540
+ const isEmpty = page.count === 0;
538
541
  if (isEmpty &&
539
542
  (!(clean || skipEmpty || unwind?.length) ||
540
543
  (await datasetClient.listItems({ offset: position, limit: 1, timeoutSecs, signal })).items
@@ -1,4 +1,5 @@
1
1
  import type { z } from 'zod';
2
+ import { ApifyClientError } from './apify_client_error.js';
2
3
  /**
3
4
  * Thrown when an API response does not match the schema the client expects for it.
4
5
  *
@@ -12,7 +13,7 @@ import type { z } from 'zod';
12
13
  * {@link https://zod.dev | zod} issues are available on `issues`, and the original `ZodError` on `cause`,
13
14
  * for programmatic inspection.
14
15
  */
15
- export declare class ResponseValidationError extends Error {
16
+ export declare class ResponseValidationError extends ApifyClientError {
16
17
  /** Structured issues from the underlying schema check. */
17
18
  readonly issues: z.ZodError['issues'];
18
19
  /** HTTP method of the request whose response failed validation, upper-cased. */
@@ -1,4 +1,5 @@
1
1
  import { ArgumentValidationError } from '@apify/validations';
2
+ import { ApifyClientError } from './apify_client_error.js';
2
3
  const REPORT_HINT = 'The API returned something its OpenAPI specification does not describe. ' +
3
4
  'Please report this at https://github.com/apify/apify-client-js/issues.';
4
5
  /**
@@ -14,7 +15,7 @@ const REPORT_HINT = 'The API returned something its OpenAPI specification does n
14
15
  * {@link https://zod.dev | zod} issues are available on `issues`, and the original `ZodError` on `cause`,
15
16
  * for programmatic inspection.
16
17
  */
17
- export class ResponseValidationError extends Error {
18
+ export class ResponseValidationError extends ApifyClientError {
18
19
  /** Structured issues from the underlying schema check. */
19
20
  issues;
20
21
  /** HTTP method of the request whose response failed validation, upper-cased. */
@@ -1,5 +1,6 @@
1
1
  import os from 'node:os';
2
- import { brotliCompress, constants, gzip } from 'node:zlib';
2
+ import { Readable } from 'node:stream';
3
+ import { brotliCompress, constants, gzip, zstdCompress } from 'node:zlib';
3
4
  /**
4
5
  * The Node.js implementation of {@link Runtime}. Deno and Bun resolve the `node` condition too and
5
6
  * provide the built-ins it uses.
@@ -10,11 +11,18 @@ export const runtime = {
10
11
  async compress(data, { algorithm, quality }) {
11
12
  return new Promise((resolve, reject) => {
12
13
  const done = (error, result) => (error ? reject(error) : resolve(result));
13
- if (algorithm === 'br') {
14
- brotliCompress(data, { params: { [constants.BROTLI_PARAM_QUALITY]: quality } }, done);
15
- }
16
- else {
17
- gzip(data, { level: quality }, done);
14
+ switch (algorithm) {
15
+ case 'br':
16
+ brotliCompress(data, { params: { [constants.BROTLI_PARAM_QUALITY]: quality } }, done);
17
+ break;
18
+ case 'gzip':
19
+ gzip(data, { level: quality }, done);
20
+ break;
21
+ case 'zstd':
22
+ zstdCompress(data, { params: { [constants.ZSTD_c_compressionLevel]: quality } }, done);
23
+ break;
24
+ default:
25
+ reject(new Error(`Unrecognized compression algorithm: ${String(algorithm)}`));
18
26
  }
19
27
  });
20
28
  },
@@ -46,4 +54,34 @@ export const runtime = {
46
54
  });
47
55
  return { httpAgent: agent, httpsAgent: agent };
48
56
  },
57
+ openBlobBody(blob, onSourceError) {
58
+ return Readable.from(readBlob(blob, onSourceError), { objectMode: false });
59
+ },
49
60
  };
61
+ /**
62
+ * Yields the bytes of a blob. Ending the iteration early, which destroying the `Readable` around it does, cancels
63
+ * the read and releases a file the blob reads from. Only a failing read is reported: an error the `Readable` is
64
+ * destroyed with is thrown in at the `yield` and belongs to the transport. A `for await` loop would surface both at
65
+ * the same place, so the loop calls `next()` itself to catch only the read.
66
+ */
67
+ async function* readBlob(blob, onSourceError) {
68
+ const chunks = blob.stream()[Symbol.asyncIterator]();
69
+ try {
70
+ while (true) {
71
+ let chunk;
72
+ try {
73
+ chunk = await chunks.next();
74
+ }
75
+ catch (error) {
76
+ onSourceError(error);
77
+ throw error;
78
+ }
79
+ if (chunk.done)
80
+ return;
81
+ yield chunk.value;
82
+ }
83
+ }
84
+ finally {
85
+ await chunks.return?.();
86
+ }
87
+ }
@@ -1,12 +1,13 @@
1
1
  import type http from 'node:http';
2
2
  import type https from 'node:https';
3
+ import type { Readable } from 'node:stream';
3
4
  /**
4
5
  * What to compress a request body with, as the built-in `HttpCompressor` implementations ask for it.
5
6
  * @internal
6
7
  */
7
8
  export interface CompressionOptions {
8
9
  /** Algorithm to compress with, named by the `Content-Encoding` value it produces. */
9
- algorithm: 'br' | 'gzip';
10
+ algorithm: 'br' | 'gzip' | 'zstd';
10
11
  /** Compression level, in the range the algorithm defines. */
11
12
  quality: number;
12
13
  }
@@ -49,4 +50,11 @@ export interface Runtime {
49
50
  createHttpAgents(options: {
50
51
  timeoutMillis: number;
51
52
  }): Promise<HttpAgents | undefined>;
53
+ /**
54
+ * Opens a `Blob` request body for one attempt. The Node.js implementation reads the blob into a `Readable` and
55
+ * reports an error the blob raises while it is read to `onSourceError` before the stream fails with it, so the
56
+ * pipeline can tell a failing source apart from a failing connection. The Web API one returns the blob itself,
57
+ * which `fetch` and `XMLHttpRequest` read on their own, and never calls `onSourceError`.
58
+ */
59
+ openBlobBody(blob: Blob, onSourceError: (error: unknown) => void): Readable | Blob;
52
60
  }
@@ -5,7 +5,7 @@ export const runtime = {
5
5
  isNode: false,
6
6
  // Browsers do not let a page set the `User-Agent` header.
7
7
  platform: undefined,
8
- // No request compression: brotli and gzip have no Web API, and a `content-encoding` request header is not
8
+ // No request compression: brotli, gzip and zstd have no Web API, and a `content-encoding` request header is not
9
9
  // on the list of headers the Apify API allows in a cross-origin request, so a browser would fail the
10
10
  // preflight. The client compresses in Node.js alone, so nothing reaches this.
11
11
  async compress() {
@@ -15,4 +15,7 @@ export const runtime = {
15
15
  async createHttpAgents() {
16
16
  return undefined;
17
17
  },
18
+ openBlobBody(blob) {
19
+ return blob;
20
+ },
18
21
  };