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
@@ -3,7 +3,7 @@ import { createStorageContentSignatureAsync } from '@apify/utilities';
3
3
  import { ResourceClient } from '../base/resource_client.js';
4
4
  import * as schemas from '../schemas.js';
5
5
  import { timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
6
- import { anyObjectSchema, applyQueryParamsToUrl, cast, isNonArrayObject, paginationOptionsShape, parseArgument, parseResponse, SCANNED_COUNT, } from '../utils.js';
6
+ import { anyObjectSchema, applyQueryParamsToUrl, cast, isNonArrayObject, paginationOptionsShape, parseArgument, parseResponse, } from '../utils.js';
7
7
  /**
8
8
  * Supported formats for downloading dataset items.
9
9
  */
@@ -55,6 +55,7 @@ const downloadItemsOptionsSchema = z.strictObject({
55
55
  xmlRoot: z.string().optional(),
56
56
  xmlRow: z.string().optional(),
57
57
  signature: z.string().optional(),
58
+ stream: z.boolean().optional(),
58
59
  ...timeoutOptionsShape,
59
60
  });
60
61
  const pushItemsSchema = z.union([itemSchema, z.string(), z.array(itemSchema)]);
@@ -74,7 +75,7 @@ const createItemsPublicUrlOptionsSchema = z.strictObject({
74
75
  skipHidden: z.boolean().optional(),
75
76
  unwind: z.array(z.string()).optional(),
76
77
  view: z.string().optional(),
77
- expiresInSecs: z.number().optional(),
78
+ expiresInSecs: z.number().positive().optional(),
78
79
  ...timeoutOptionsShape,
79
80
  });
80
81
  /**
@@ -163,6 +164,7 @@ export class DatasetClient extends ResourceClient {
163
164
  * @param options - Options for listing items
164
165
  * @param options.limit - Maximum number of items to return. Default is all items.
165
166
  * @param options.chunkSize - Maximum number of items returned in one API response. Relevant in the context of asyncIterator.
167
+ * Without it, iteration loads the whole dataset, or all `limit` items, in one response.
166
168
  * @param options.offset - Number of items to skip from the beginning. Default is 0.
167
169
  * @param options.desc - If `true`, items are returned in descending order (newest first). Default is `false`.
168
170
  * @param options.fields - Array of field names to include in the results. Omits all other fields.
@@ -212,50 +214,9 @@ export class DatasetClient extends ResourceClient {
212
214
  };
213
215
  return this.listPaginatedFromCallback(fetchItems, listOptions);
214
216
  }
215
- /**
216
- * Downloads dataset items in a specific format.
217
- *
218
- * Unlike {@link listItems} which returns a {@link PaginatedList} with an array of individual
219
- * dataset items, this method returns the items serialized to the provided format
220
- * (JSON, CSV, Excel, etc.) as a Buffer. Useful for exporting data for further processing.
221
- *
222
- * @param format - Output format: `'json'`, `'jsonl'`, `'csv'`, `'xlsx'`, `'xml'`, `'rss'`, or `'html'`
223
- * @param options - Download and formatting options (extends all options from {@link listItems})
224
- * @param options.attachment - If `true`, the response will have `Content-Disposition: attachment` header.
225
- * @param options.bom - If `true`, adds UTF-8 BOM to the beginning of the file (useful for Excel compatibility).
226
- * @param options.delimiter - CSV delimiter character. Default is `,` (comma).
227
- * @param options.skipHeaderRow - If `true`, CSV export will not include the header row with field names.
228
- * @param options.xmlRoot - Name of the root XML element. Default is `'items'`.
229
- * @param options.xmlRow - Name of the XML element for each item. Default is `'item'`.
230
- * @param options.fields - Array of field names to include in the export.
231
- * @param options.omit - Array of field names to exclude from the export.
232
- * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
233
- * @returns Buffer containing the serialized data in the specified format
234
- * @see https://docs.apify.com/api/v2/dataset-items-get
235
- *
236
- * @example
237
- * ```javascript
238
- * // Download as CSV with BOM for Excel compatibility
239
- * const csvBuffer = await client.dataset('my-dataset').downloadItems('csv', { bom: true });
240
- * require('fs').writeFileSync('output.csv', csvBuffer);
241
- *
242
- * // Download as Excel with custom options
243
- * const xlsxBuffer = await client.dataset('my-dataset').downloadItems('xlsx', {
244
- * fields: ['url', 'title', 'price'],
245
- * skipEmpty: true,
246
- * limit: 1000
247
- * });
248
- *
249
- * // Download as XML with custom element names
250
- * const xmlBuffer = await client.dataset('my-dataset').downloadItems('xml', {
251
- * xmlRoot: 'products',
252
- * xmlRow: 'product'
253
- * });
254
- * ```
255
- */
256
217
  async downloadItems(format, options = {}) {
257
218
  parseArgument(format, itemFormatSchema);
258
- const { timeoutSecs = 'long', signal, ...query } = parseArgument(options, downloadItemsOptionsSchema, 'DatasetClientDownloadItemsOptions');
219
+ const { timeoutSecs = 'long', signal, stream, ...query } = parseArgument(options, downloadItemsOptionsSchema, 'DatasetClientDownloadItemsOptions');
259
220
  const { data } = await this.httpClient.call({
260
221
  url: this.buildUrl('items'),
261
222
  method: 'GET',
@@ -263,7 +224,7 @@ export class DatasetClient extends ResourceClient {
263
224
  format,
264
225
  ...query,
265
226
  }),
266
- responseType: 'buffer',
227
+ responseType: stream ? 'stream' : 'buffer',
267
228
  timeoutSecs,
268
229
  signal,
269
230
  });
@@ -348,7 +309,8 @@ export class DatasetClient extends ResourceClient {
348
309
  * This is useful for sharing dataset results with external services or users.
349
310
  *
350
311
  * @param options - URL generation options (extends all options from {@link listItems})
351
- * @param options.expiresInSecs - Number of seconds until the signed URL expires. If omitted, the URL never expires.
312
+ * @param options.expiresInSecs - Number of seconds until the signed URL expires. Must be positive. If omitted, the URL
313
+ * never expires.
352
314
  * @param options.fields - Array of field names to include in the response.
353
315
  * @param options.format - Format of the items served by the URL. Defaults to `json`.
354
316
  * @param options.limit - Maximum number of items to return.
@@ -391,21 +353,17 @@ export class DatasetClient extends ResourceClient {
391
353
  }
392
354
  #createPaginationList(response, userProvidedDesc) {
393
355
  const descHeader = response.headers['x-apify-pagination-desc'];
394
- const page = {
356
+ return {
395
357
  items: response.data,
396
358
  total: Number(response.headers['x-apify-pagination-total']),
397
359
  offset: Number(response.headers['x-apify-pagination-offset']),
398
360
  // `x-apify-pagination-count` reports the rows scanned, which filters and `unwind` can leave above or below
399
- // the items returned.
400
- count: response.data.length,
361
+ // the items returned. It is derived from the dataset's item count, which lags a fresh push, so it can also
362
+ // fall below the items returned on an unfiltered page.
363
+ count: Math.max(Number(response.headers['x-apify-pagination-count'] ?? 0), response.data.length),
401
364
  limit: Number(response.headers['x-apify-pagination-limit']), // API returns 999999999999 when no limit is used
402
365
  // TODO: Replace this once https://github.com/apify/apify-core/issues/3503 is solved
403
366
  desc: typeof descHeader === 'string' ? JSON.parse(descHeader) : userProvidedDesc,
404
367
  };
405
- const scannedCount = response.headers['x-apify-pagination-count'];
406
- if (scannedCount === undefined)
407
- return page;
408
- // The offset iterator paginates by the scanned number, so it travels with the page outside its public shape.
409
- return Object.defineProperty(page, SCANNED_COUNT, { value: Number(scannedCount) });
410
368
  }
411
369
  }
@@ -1,10 +1,10 @@
1
1
  import type { Readable } from 'node:stream';
2
- import type { JsonValue, TypedArray } from 'type-fest';
3
2
  import type { STORAGE_GENERAL_ACCESS } from '@apify/consts';
4
3
  import type { ApiClientSubResourceOptions } from '../base/api_client.js';
5
4
  import { ResourceClient } from '../base/resource_client.js';
6
5
  import type { KeyValueStoreResource, KeyValueStoreKey, ListOfKeys } from '../models.js';
7
6
  import type { TimeoutOptions } from '../timeouts.js';
7
+ import type { JsonValue, TypedArray } from '../utils.js';
8
8
  export type { KeyValueStoreResource, KeyValueStoreKey, KeyValueStoreStats, ListOfKeys } from '../models.js';
9
9
  /**
10
10
  * Client for managing a specific key-value store.
@@ -77,6 +77,8 @@ export declare class KeyValueStoreClient extends ResourceClient {
77
77
  *
78
78
  * @param options - Listing options
79
79
  * @param options.limit - Maximum number of keys to return. Default is 1000.
80
+ * @param options.chunkSize - Maximum number of keys requested per API call when iterating across pages. `limit`
81
+ * then caps the total across all pages.
80
82
  * @param options.exclusiveStartKey - Key to start listing from (for pagination). The listing starts with the next key after this one.
81
83
  * @param options.collection - Filter keys by collection name.
82
84
  * @param options.prefix - Filter keys that start with this prefix.
@@ -134,7 +136,8 @@ export declare class KeyValueStoreClient extends ResourceClient {
134
136
  * the URL will include a cryptographic signature which allows access without authentication.
135
137
  *
136
138
  * @param options - URL generation options (extends all options from {@link listKeys})
137
- * @param options.expiresInSecs - Number of seconds until the signed URL expires. If omitted, the URL never expires.
139
+ * @param options.expiresInSecs - Number of seconds until the signed URL expires. Must be positive. If omitted, the URL
140
+ * never expires.
138
141
  * @param options.limit - Maximum number of keys to return.
139
142
  * @param options.prefix - Filter keys by prefix.
140
143
  * @param options.timeoutSecs - Timeout for the API request that fetches the store. Default is `'long'`.
@@ -175,22 +178,21 @@ export declare class KeyValueStoreClient extends ResourceClient {
175
178
  recordExists(key: string, options?: TimeoutOptions): Promise<boolean>;
176
179
  /**
177
180
  * By default, the value is parsed by the record's content type: `application/json` is parsed into a value,
178
- * `text/*` and `application/*xml` are decoded to a string, and anything else is returned as a Buffer (Node.js)
179
- * or ArrayBuffer (browser). A record whose body does not parse as its content type claims, such as a non-JSON
181
+ * `text/*` and `application/*xml` are decoded to a string, and anything else is returned as a Uint8Array.
182
+ * A record whose body does not parse as its content type claims, such as a non-JSON
180
183
  * string stored under `application/json`, makes the call throw an {@link InvalidResponseBodyError}, which
181
184
  * carries the raw body in `error.response`.
182
185
  *
183
- * You can use the `buffer` option to get the value in a Buffer (Node.js)
184
- * or ArrayBuffer (browser) format, which skips the parsing. In Node.js (not in browser) you can also
185
- * use the `stream` option to get a Readable stream.
186
+ * You can use the `buffer` option to get the value as a Uint8Array, which skips the parsing. You can also
187
+ * use the `stream` option to get the value unread, as a web ReadableStream.
186
188
  *
187
189
  * When the record does not exist, the function resolves to `undefined`. It does
188
190
  * NOT resolve to a `KeyValueStoreRecord` with an `undefined` value.
189
191
  *
190
192
  * @param key - The record key
191
193
  * @param options - Retrieval options
192
- * @param options.buffer - If `true`, the value is returned as a Buffer (Node.js) or ArrayBuffer (browser).
193
- * @param options.stream - If `true`, the value is returned as a Readable stream. Node.js only.
194
+ * @param options.buffer - If `true`, the value is returned as a Uint8Array.
195
+ * @param options.stream - If `true`, the value is returned as a web ReadableStream.
194
196
  * @param options.signature - Signature of a public URL, for reading a record without a token.
195
197
  * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
196
198
  * @see https://docs.apify.com/api/v2/key-value-store-record-get
@@ -207,22 +209,36 @@ export declare class KeyValueStoreClient extends ResourceClient {
207
209
  * A string is sent as it is, even under `application/json`, so a string stored under a JSON content type has
208
210
  * to be valid JSON already, or {@link getRecord} fails to parse it back.
209
211
  *
210
- * **Note about streams:** If the value is a stream object (has `.pipe` and `.on` methods),
211
- * the upload cannot be retried on failure or follow redirects. For reliable uploads,
212
- * buffer the entire stream into memory first.
212
+ * **Note about streams:** If the value is a stream, either a Node.js `Readable` or a web `ReadableStream`
213
+ * such as the `value` that {@link getRecord} returns with the `stream` option, the upload cannot be retried
214
+ * on failure or follow redirects. For reliable uploads of a file, pass a `Blob` from `fs.openAsBlob()`
215
+ * instead: it is read again for every attempt and never held in memory whole. A browser sends a web
216
+ * `ReadableStream` only over HTTP/2 or later, and only if it supports streaming request bodies at all:
217
+ * where it doesn't, the call throws a `TypeError`.
213
218
  *
214
219
  * @param record - The record to store
215
220
  * @param record.key - Record key (unique identifier)
216
- * @param record.value - Record value (a JSON-serializable value, Buffer, ArrayBuffer, typed array, or Readable)
221
+ * @param record.value - Record value (a JSON-serializable value, Buffer, ArrayBuffer, typed array, Blob,
222
+ * Readable, or web ReadableStream)
217
223
  * @param record.contentType - Optional MIME type. Auto-detected if not provided:
218
224
  * - Objects: `'application/json; charset=utf-8'`
219
225
  * - Strings: `'text/plain; charset=utf-8'`
226
+ * - Blobs: their `type`, or `'application/octet-stream'` when it is empty
220
227
  * - Binary values and streams: `'application/octet-stream'`
221
228
  *
222
229
  * Worth setting for media and archives: the client skips compressing a body
223
230
  * whose content type already carries its own compression. The
224
231
  * `'application/octet-stream'` fallback is treated as compressible, because
225
232
  * it could hold any binary data.
233
+ * @param record.contentEncoding - Optional encoding already applied to `value`, sent as the `Content-Encoding`
234
+ * header. Set it to upload a pre-compressed value: the client then sends the
235
+ * bytes as they are and does not compress them again. The API accepts `gzip`,
236
+ * `br`, `zstd`, `deflate`, and `identity`, and stores the record exactly as
237
+ * uploaded, so this is also the encoding the record is served with. Only binary
238
+ * values and streams can carry a compression, so any encoding other than
239
+ * `identity` throws a `TypeError` when `value` is a string, or a plain object,
240
+ * array, or other value that the client serializes to JSON. Node.js only, since
241
+ * browsers cannot send the header to the API.
226
242
  * @param options - Storage options
227
243
  * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
228
244
  * @param options.doNotRetryTimeouts - If `true`, don't retry on timeout errors. Default is `false`.
@@ -250,9 +266,18 @@ export declare class KeyValueStoreClient extends ResourceClient {
250
266
  * value: imageBuffer,
251
267
  * contentType: 'image/png'
252
268
  * });
269
+ *
270
+ * // Store a gzipped file without compressing it again
271
+ * const gzippedReport = await readFile('report.json.gz');
272
+ * await client.keyValueStore('my-store').setRecord({
273
+ * key: 'report.json',
274
+ * value: gzippedReport,
275
+ * contentType: 'application/json',
276
+ * contentEncoding: 'gzip'
277
+ * });
253
278
  * ```
254
279
  */
255
- setRecord(record: KeyValueStoreRecord<KeyValueStoreRecordValue>, options?: KeyValueStoreRecordOptions): Promise<void>;
280
+ setRecord(record: KeyValueStoreRecordInput, options?: KeyValueStoreRecordOptions): Promise<void>;
256
281
  /**
257
282
  * Deletes a record from the key-value store.
258
283
  *
@@ -287,6 +312,12 @@ export interface KeyValueClientUpdateOptions {
287
312
  */
288
313
  export interface KeyValueClientListKeysOptions extends TimeoutOptions {
289
314
  limit?: number;
315
+ /**
316
+ * Maximum number of keys returned in one API response. When the call is iterated with `for await`, the iterator
317
+ * fetches keys in chunks of this size and yields them one by one, until `limit` is reached or the store has no
318
+ * more keys. Awaiting the call returns only the first chunk. Without it, the API's default page size applies.
319
+ */
320
+ chunkSize?: number;
290
321
  exclusiveStartKey?: string;
291
322
  collection?: string;
292
323
  /**
@@ -301,11 +332,11 @@ export interface KeyValueClientListKeysOptions extends TimeoutOptions {
301
332
  /**
302
333
  * Options for creating a public URL to list keys in a Key-Value Store.
303
334
  *
304
- * Extends {@link KeyValueClientListKeysOptions} with URL expiration control, minus `signature` (this
305
- * method produces one).
335
+ * Extends {@link KeyValueClientListKeysOptions} with URL expiration control, minus `chunkSize` (it only sizes a
336
+ * client-side iteration) and `signature` (this method produces one).
306
337
  * @since Added in 2.16.0
307
338
  */
308
- export interface KeyValueClientCreateKeysUrlOptions extends Omit<KeyValueClientListKeysOptions, 'signature'> {
339
+ export interface KeyValueClientCreateKeysUrlOptions extends Omit<KeyValueClientListKeysOptions, 'chunkSize' | 'signature'> {
309
340
  expiresInSecs?: number;
310
341
  }
311
342
  /**
@@ -323,10 +354,10 @@ export interface KeyValueClientGetRecordOptions extends TimeoutOptions {
323
354
  * A value that `setRecord` accepts.
324
355
  *
325
356
  * Anything JSON-serializable, or binary content the client uploads as bytes instead of JSON-encoding
326
- * it: a `Buffer`, an `ArrayBuffer`, a typed array, or a readable stream. `Buffer` is a `Uint8Array`, so
327
- * `TypedArray` covers it.
357
+ * it: a `Buffer`, an `ArrayBuffer`, a typed array, a `Blob`, a Node.js `Readable`, or a web `ReadableStream`.
358
+ * `Buffer` is a `Uint8Array`, so `TypedArray` covers it.
328
359
  */
329
- export type KeyValueStoreRecordValue = JsonValue | ArrayBuffer | TypedArray | Readable;
360
+ export type KeyValueStoreRecordValue = JsonValue | ArrayBuffer | TypedArray | Blob | Readable | ReadableStream<Uint8Array>;
330
361
  /**
331
362
  * Represents a record (key-value pair) in a Key-Value Store.
332
363
  *
@@ -337,6 +368,16 @@ export interface KeyValueStoreRecord<T> {
337
368
  value: T;
338
369
  contentType?: string;
339
370
  }
371
+ /**
372
+ * A record to store with {@link KeyValueStoreClient.setRecord}.
373
+ */
374
+ export interface KeyValueStoreRecordInput extends KeyValueStoreRecord<KeyValueStoreRecordValue> {
375
+ /**
376
+ * Encoding already applied to `value`, sent as the `Content-Encoding` header. See
377
+ * {@link KeyValueStoreClient.setRecord}.
378
+ */
379
+ contentEncoding?: string;
380
+ }
340
381
  /**
341
382
  * Options for storing a record in a Key-Value Store.
342
383
  * @since Added in 2.12.4
@@ -347,8 +388,8 @@ export interface KeyValueStoreRecordOptions extends TimeoutOptions {
347
388
  /**
348
389
  * Helper type to determine the return type based on getRecord options.
349
390
  *
350
- * Returns Readable if stream option is true, Buffer if buffer option is true,
391
+ * Returns a web ReadableStream if stream option is true, Uint8Array if buffer option is true,
351
392
  * otherwise returns JsonValue.
352
393
  * @since Added in 2.0.6
353
394
  */
354
- export type ReturnTypeFromOptions<Options extends KeyValueClientGetRecordOptions> = Options['stream'] extends true ? Readable : Options['buffer'] extends true ? Buffer : JsonValue;
395
+ export type ReturnTypeFromOptions<Options extends KeyValueClientGetRecordOptions> = Options['stream'] extends true ? ReadableStream<Uint8Array> : Options['buffer'] extends true ? Uint8Array : JsonValue;
@@ -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, isAnyStream, isBlob, isBuffer, 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'`.
@@ -313,9 +320,6 @@ export class KeyValueStoreClient extends ResourceClient {
313
320
  async getRecord(key, options = {}) {
314
321
  parseArgument(key, keySchema);
315
322
  const parsed = parseArgument(options, getRecordOptionsSchema, 'KeyValueClientGetRecordOptions');
316
- if (parsed.stream && !runtime.isNode) {
317
- throw new Error('The stream option can only be used in Node.js environment.');
318
- }
319
323
  if ('disableRedirect' in parsed) {
320
324
  log.deprecated('The disableRedirect option for getRecord() is deprecated. ' +
321
325
  'It has no effect and will be removed in the following major release.');
@@ -357,22 +361,36 @@ export class KeyValueStoreClient extends ResourceClient {
357
361
  * A string is sent as it is, even under `application/json`, so a string stored under a JSON content type has
358
362
  * to be valid JSON already, or {@link getRecord} fails to parse it back.
359
363
  *
360
- * **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.
364
+ * **Note about streams:** If the value is a stream, either a Node.js `Readable` or a web `ReadableStream`
365
+ * such as the `value` that {@link getRecord} returns with the `stream` option, the upload cannot be retried
366
+ * on failure or follow redirects. For reliable uploads of a file, pass a `Blob` from `fs.openAsBlob()`
367
+ * instead: it is read again for every attempt and never held in memory whole. A browser sends a web
368
+ * `ReadableStream` only over HTTP/2 or later, and only if it supports streaming request bodies at all:
369
+ * where it doesn't, the call throws a `TypeError`.
363
370
  *
364
371
  * @param record - The record to store
365
372
  * @param record.key - Record key (unique identifier)
366
- * @param record.value - Record value (a JSON-serializable value, Buffer, ArrayBuffer, typed array, or Readable)
373
+ * @param record.value - Record value (a JSON-serializable value, Buffer, ArrayBuffer, typed array, Blob,
374
+ * Readable, or web ReadableStream)
367
375
  * @param record.contentType - Optional MIME type. Auto-detected if not provided:
368
376
  * - Objects: `'application/json; charset=utf-8'`
369
377
  * - Strings: `'text/plain; charset=utf-8'`
378
+ * - Blobs: their `type`, or `'application/octet-stream'` when it is empty
370
379
  * - Binary values and streams: `'application/octet-stream'`
371
380
  *
372
381
  * Worth setting for media and archives: the client skips compressing a body
373
382
  * whose content type already carries its own compression. The
374
383
  * `'application/octet-stream'` fallback is treated as compressible, because
375
384
  * it could hold any binary data.
385
+ * @param record.contentEncoding - Optional encoding already applied to `value`, sent as the `Content-Encoding`
386
+ * header. Set it to upload a pre-compressed value: the client then sends the
387
+ * bytes as they are and does not compress them again. The API accepts `gzip`,
388
+ * `br`, `zstd`, `deflate`, and `identity`, and stores the record exactly as
389
+ * uploaded, so this is also the encoding the record is served with. Only binary
390
+ * values and streams can carry a compression, so any encoding other than
391
+ * `identity` throws a `TypeError` when `value` is a string, or a plain object,
392
+ * array, or other value that the client serializes to JSON. Node.js only, since
393
+ * browsers cannot send the header to the API.
376
394
  * @param options - Storage options
377
395
  * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
378
396
  * @param options.doNotRetryTimeouts - If `true`, don't retry on timeout errors. Default is `false`.
@@ -400,18 +418,40 @@ export class KeyValueStoreClient extends ResourceClient {
400
418
  * value: imageBuffer,
401
419
  * contentType: 'image/png'
402
420
  * });
421
+ *
422
+ * // Store a gzipped file without compressing it again
423
+ * const gzippedReport = await readFile('report.json.gz');
424
+ * await client.keyValueStore('my-store').setRecord({
425
+ * key: 'report.json',
426
+ * value: gzippedReport,
427
+ * contentType: 'application/json',
428
+ * contentEncoding: 'gzip'
429
+ * });
403
430
  * ```
404
431
  */
405
432
  async setRecord(record, options = {}) {
406
433
  parseArgument(record, recordSchema);
407
434
  const parsed = parseArgument(options, recordOptionsSchema, 'KeyValueStoreRecordOptions');
408
- const { key } = record;
435
+ const { key, contentEncoding } = record;
409
436
  let { value, contentType } = record;
410
437
  const { timeoutSecs = 'long', signal, doNotRetryTimeouts } = parsed;
411
- const isValueStreamOrBuffer = isStream(value) || isBuffer(value);
438
+ if (contentEncoding !== undefined && !runtime.isNode) {
439
+ throw new Error('The contentEncoding option can only be used in Node.js environment.');
440
+ }
441
+ const isBinaryValue = isAnyStream(value) || isBuffer(value) || isBlob(value);
442
+ // The client forwards the header without inspecting the body, so a string or a value serialized to JSON, which
443
+ // cannot hold compressed bytes, would be stored under an encoding that misdescribes it.
444
+ const declaresCompression = contentEncoding !== undefined && contentEncoding.trim().toLowerCase() !== 'identity';
445
+ if (declaresCompression && !isBinaryValue) {
446
+ throw new TypeError(`Cannot upload a value of type ${typeof value} with Content-Encoding: ${contentEncoding}. ` +
447
+ 'An encoding other than identity declares the value is already compressed, so pass the ' +
448
+ 'compressed bytes as a Buffer, an ArrayBuffer, a typed array, a Blob, or a readable stream.');
449
+ }
412
450
  // To allow saving Objects to JSON without providing content type
413
451
  if (!contentType) {
414
- if (isValueStreamOrBuffer)
452
+ if (isBlob(value))
453
+ contentType = value.type || 'application/octet-stream';
454
+ else if (isBinaryValue)
415
455
  contentType = 'application/octet-stream';
416
456
  else if (typeof value === 'string')
417
457
  contentType = 'text/plain; charset=utf-8';
@@ -419,7 +459,7 @@ export class KeyValueStoreClient extends ResourceClient {
419
459
  contentType = 'application/json; charset=utf-8';
420
460
  }
421
461
  const isContentTypeJson = contentType.startsWith('application/json');
422
- if (isContentTypeJson && !isValueStreamOrBuffer && typeof value !== 'string') {
462
+ if (isContentTypeJson && !isBinaryValue && typeof value !== 'string') {
423
463
  try {
424
464
  value = JSON.stringify(value, null, 2);
425
465
  }
@@ -433,7 +473,10 @@ export class KeyValueStoreClient extends ResourceClient {
433
473
  method: 'PUT',
434
474
  params: this.buildParams(),
435
475
  data: value,
436
- headers: contentType ? { 'content-type': contentType } : undefined,
476
+ headers: {
477
+ 'content-type': contentType,
478
+ ...(contentEncoding !== undefined && { 'content-encoding': contentEncoding }),
479
+ },
437
480
  doNotRetryTimeouts,
438
481
  timeoutSecs,
439
482
  signal,
@@ -1,4 +1,3 @@
1
- import type { Readable } from 'node:stream';
2
1
  import type { Log } from '@apify/log';
3
2
  import { Logger, LogLevel } from '@apify/log';
4
3
  import type { ApiClientSubResourceOptions } from '../base/api_client.js';
@@ -19,6 +18,9 @@ import type { TimeoutOptions } from '../timeouts.js';
19
18
  * const log = await runClient.log().get();
20
19
  * console.log(log);
21
20
  *
21
+ * // Get the log content as raw bytes
22
+ * const logBuffer = await runClient.log().get({ buffer: true });
23
+ *
22
24
  * // Stream the log in real-time
23
25
  * const stream = await runClient.log().stream();
24
26
  * stream.on('line', (line) => console.log(line));
@@ -34,25 +36,37 @@ export declare class LogClient extends ResourceClient {
34
36
  /**
35
37
  * Retrieves the log as a string.
36
38
  *
39
+ * The `buffer` option only selects the return type: the bytes come back as a Uint8Array, not decoded to a
40
+ * string. Either way the whole log is downloaded in one response; to read it incrementally, use
41
+ * {@link LogClient.stream}.
42
+ *
37
43
  * @param options - Log retrieval options.
38
44
  * @param options.raw - If `true`, returns raw log content without any processing. Default is `false`.
45
+ * @param options.buffer - If `true`, the log is returned as a Uint8Array instead of a
46
+ * string. It does not change how the log is fetched.
39
47
  * @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.
48
+ * @returns The log content, or `undefined` if it does not exist. A chained client such as `run.log()` throws an
49
+ * `ApifyApiError` on a 404, since the run itself may be what is missing.
42
50
  * @see https://docs.apify.com/api/v2/log-get
43
51
  */
44
- get(options?: LogOptions): Promise<string | undefined>;
52
+ get(options?: LogGetOptions & {
53
+ buffer?: false;
54
+ }): Promise<string | undefined>;
55
+ get(options: LogGetOptions & {
56
+ buffer: true;
57
+ }): Promise<Uint8Array | undefined>;
58
+ get(options?: LogGetOptions): Promise<string | Uint8Array | undefined>;
45
59
  /**
46
- * Retrieves the log as a Readable stream. Only works in Node.js.
60
+ * Retrieves the log as a web ReadableStream of Uint8Array chunks.
47
61
  *
48
62
  * @param options - Log retrieval options.
49
63
  * @param options.raw - If `true`, returns raw log content without any processing. Default is `false`.
50
64
  * @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
51
- * @returns The log content as a Readable stream, or `undefined` if it does not exist. A chained client such as
65
+ * @returns The log content as a web ReadableStream, or `undefined` if it does not exist. A chained client such as
52
66
  * `run.log()` throws an `ApifyApiError` on a 404, since the run itself may be what is missing.
53
67
  * @see https://docs.apify.com/api/v2/log-get
54
68
  */
55
- stream(options?: LogOptions): Promise<Readable | undefined>;
69
+ stream(options?: LogOptions): Promise<ReadableStream<Uint8Array> | undefined>;
56
70
  }
57
71
  /**
58
72
  * @since Added in 2.20.0
@@ -61,6 +75,17 @@ export interface LogOptions extends TimeoutOptions {
61
75
  /** @default false */
62
76
  raw?: boolean;
63
77
  }
78
+ /**
79
+ * Options for {@link LogClient.get}.
80
+ */
81
+ export interface LogGetOptions extends LogOptions {
82
+ /**
83
+ * If `true`, the log is returned as a Uint8Array instead of a string. It only selects
84
+ * the return type; to read the log incrementally, use {@link LogClient.stream}.
85
+ * @default false
86
+ */
87
+ buffer?: boolean;
88
+ }
64
89
  /**
65
90
  * Logger for redirected actor logs.
66
91
  * @since Added in 2.20.0