apify-client 3.0.0-beta.61 → 3.0.0-beta.63

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.
package/dist/index.d.ts CHANGED
@@ -26,6 +26,7 @@ export * from './resource_clients/webhook.js';
26
26
  export * from './resource_clients/webhook_collection.js';
27
27
  export * from './resource_clients/webhook_dispatch.js';
28
28
  export * from './resource_clients/webhook_dispatch_collection.js';
29
+ export * from './apify_client_error.js';
29
30
  export * from './apify_api_error.js';
30
31
  export { ArgumentValidationError } from '@apify/validations';
31
32
  export * from './response_validation_error.js';
package/dist/index.js CHANGED
@@ -26,6 +26,7 @@ export * from './resource_clients/webhook.js';
26
26
  export * from './resource_clients/webhook_collection.js';
27
27
  export * from './resource_clients/webhook_dispatch.js';
28
28
  export * from './resource_clients/webhook_dispatch_collection.js';
29
+ export * from './apify_client_error.js';
29
30
  export * from './apify_api_error.js';
30
31
  export { ArgumentValidationError } from '@apify/validations';
31
32
  export * from './response_validation_error.js';
@@ -1,10 +1,11 @@
1
+ import { ApifyClientError } from './apify_client_error.js';
1
2
  import type { HttpResponse } from './http_clients/base.js';
2
3
  /**
3
4
  * Thrown when a response body does not parse as its content type claims, typically a JSON document cut short by a
4
5
  * connection dropped mid-response. The client retries such requests, so the error surfaces once the retries are
5
6
  * exhausted.
6
7
  */
7
- export declare class InvalidResponseBodyError extends Error {
8
+ export declare class InvalidResponseBodyError extends ApifyClientError {
8
9
  code: string;
9
10
  /** The response whose body did not parse, with the body as the transport returned it. */
10
11
  response: HttpResponse;
@@ -1,9 +1,10 @@
1
+ import { ApifyClientError } from './apify_client_error.js';
1
2
  /**
2
3
  * Thrown when a response body does not parse as its content type claims, typically a JSON document cut short by a
3
4
  * connection dropped mid-response. The client retries such requests, so the error surfaces once the retries are
4
5
  * exhausted.
5
6
  */
6
- export class InvalidResponseBodyError extends Error {
7
+ export class InvalidResponseBodyError extends ApifyClientError {
7
8
  code;
8
9
  /** The response whose body did not parse, with the body as the transport returned it. */
9
10
  response;
@@ -1,3 +1,4 @@
1
+ import type { Readable } from 'node:stream';
1
2
  import type { STORAGE_GENERAL_ACCESS } from '@apify/consts';
2
3
  import type { ApiClientSubResourceOptions } from '../base/api_client.js';
3
4
  import { ResourceClient } from '../base/resource_client.js';
@@ -167,6 +168,34 @@ export declare class DatasetClient<Data extends Record<string | number, any> = R
167
168
  * ```
168
169
  */
169
170
  downloadItems(format: `${DownloadItemsFormat}`, options?: DatasetClientDownloadItemsOptions): Promise<Buffer>;
171
+ /**
172
+ * Downloads dataset items in a specific format as a Readable stream. Only works in Node.js.
173
+ *
174
+ * Takes the same arguments as {@link downloadItems}, but resolves to the response body as a stream, so a large
175
+ * export is processed in chunks without holding all of it in memory.
176
+ *
177
+ * The stream holds its connection open until you consume it to the end or destroy it. Iterating it with
178
+ * `for await` or passing it to `pipeline()` from `node:stream/promises` does either one for you.
179
+ *
180
+ * @param format - Output format: `'json'`, `'jsonl'`, `'csv'`, `'xlsx'`, `'xml'`, `'rss'`, or `'html'`
181
+ * @param options - Download and formatting options, the same as for {@link downloadItems}
182
+ * @param options.timeoutSecs - Timeout for the API to start responding. Default is `'long'`. Once the stream is
183
+ * returned, it only limits inactivity: the stream errors if no data arrives for that long. To stop the download
184
+ * early or cap its total duration, destroy the stream or abort `signal`.
185
+ * @returns Readable stream of the items serialized to the specified format
186
+ * @see https://docs.apify.com/api/v2/dataset-items-get
187
+ *
188
+ * @example
189
+ * ```javascript
190
+ * const { createWriteStream } = require('node:fs');
191
+ * const { pipeline } = require('node:stream/promises');
192
+ *
193
+ * // Write a CSV export straight to a file
194
+ * const stream = await client.dataset('my-dataset').streamItems('csv', { bom: true });
195
+ * await pipeline(stream, createWriteStream('output.csv'));
196
+ * ```
197
+ */
198
+ streamItems(format: `${DownloadItemsFormat}`, options?: DatasetClientDownloadItemsOptions): Promise<Readable>;
170
199
  /**
171
200
  * Stores one or more items into the dataset.
172
201
  *
@@ -3,6 +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 { runtime } from '#runtime';
6
7
  import { anyObjectSchema, applyQueryParamsToUrl, cast, isNonArrayObject, paginationOptionsShape, parseArgument, parseResponse, SCANNED_COUNT, } from '../utils.js';
7
8
  /**
8
9
  * Supported formats for downloading dataset items.
@@ -269,6 +270,52 @@ export class DatasetClient extends ResourceClient {
269
270
  });
270
271
  return cast(data);
271
272
  }
273
+ /**
274
+ * Downloads dataset items in a specific format as a Readable stream. Only works in Node.js.
275
+ *
276
+ * Takes the same arguments as {@link downloadItems}, but resolves to the response body as a stream, so a large
277
+ * export is processed in chunks without holding all of it in memory.
278
+ *
279
+ * The stream holds its connection open until you consume it to the end or destroy it. Iterating it with
280
+ * `for await` or passing it to `pipeline()` from `node:stream/promises` does either one for you.
281
+ *
282
+ * @param format - Output format: `'json'`, `'jsonl'`, `'csv'`, `'xlsx'`, `'xml'`, `'rss'`, or `'html'`
283
+ * @param options - Download and formatting options, the same as for {@link downloadItems}
284
+ * @param options.timeoutSecs - Timeout for the API to start responding. Default is `'long'`. Once the stream is
285
+ * returned, it only limits inactivity: the stream errors if no data arrives for that long. To stop the download
286
+ * early or cap its total duration, destroy the stream or abort `signal`.
287
+ * @returns Readable stream of the items serialized to the specified format
288
+ * @see https://docs.apify.com/api/v2/dataset-items-get
289
+ *
290
+ * @example
291
+ * ```javascript
292
+ * const { createWriteStream } = require('node:fs');
293
+ * const { pipeline } = require('node:stream/promises');
294
+ *
295
+ * // Write a CSV export straight to a file
296
+ * const stream = await client.dataset('my-dataset').streamItems('csv', { bom: true });
297
+ * await pipeline(stream, createWriteStream('output.csv'));
298
+ * ```
299
+ */
300
+ async streamItems(format, options = {}) {
301
+ parseArgument(format, itemFormatSchema);
302
+ const { timeoutSecs = 'long', signal, ...query } = parseArgument(options, downloadItemsOptionsSchema, 'DatasetClientDownloadItemsOptions');
303
+ if (!runtime.isNode) {
304
+ throw new Error('The streamItems() method can only be used in Node.js environment.');
305
+ }
306
+ const { data } = await this.httpClient.call({
307
+ url: this.buildUrl('items'),
308
+ method: 'GET',
309
+ params: this.buildParams({
310
+ format,
311
+ ...query,
312
+ }),
313
+ responseType: 'stream',
314
+ timeoutSecs,
315
+ signal,
316
+ });
317
+ return cast(data);
318
+ }
272
319
  /**
273
320
  * Stores one or more items into the dataset.
274
321
  *
@@ -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. */
package/dist/utils.d.ts CHANGED
@@ -27,14 +27,6 @@ export declare function isNonArrayObject(value: unknown): value is Record<string
27
27
  * @internal
28
28
  */
29
29
  export declare const anyObjectSchema: z.ZodCustom<Record<string, unknown>, Record<string, unknown>>;
30
- /**
31
- * Generic interface for objects that may contain a data property.
32
- *
33
- * @template R - The type of the data property
34
- */
35
- export interface MaybeData<R> {
36
- data?: R;
37
- }
38
30
  /**
39
31
  * Turns a JSON API response into the value a resource method returns: unwraps the `data` envelope and validates the
40
32
  * result against `schema`, one of the schemas generated from the OpenAPI specification. The validated copy is what
@@ -46,11 +38,6 @@ export interface MaybeData<R> {
46
38
  * @internal
47
39
  */
48
40
  export declare function parseResponse<R>(response: ApifyResponse, schema: z.ZodType): R;
49
- /**
50
- * Returns object's 'data' property or throws if parameter is not an object,
51
- * or an object without a 'data' property.
52
- */
53
- export declare function pluckData<R>(obj: MaybeData<R>): R;
54
41
  /**
55
42
  * Swallows a 404 Not Found API error and rethrows anything else.
56
43
  */
package/dist/utils.js CHANGED
@@ -80,6 +80,7 @@ export const anyObjectSchema = z.custom(isNonArrayObject, {
80
80
  // any tree-shaking bundler drops it and every message degrades to a bare "Invalid input". Passing it
81
81
  // in per parse keeps them intact without reaching into the zod config the whole process shares.
82
82
  const { localeError } = z.locales.en();
83
+ const RESPONSE_ENVELOPE_SCHEMA = z.object({ data: z.unknown() });
83
84
  /**
84
85
  * Turns a JSON API response into the value a resource method returns: unwraps the `data` envelope and validates the
85
86
  * result against `schema`, one of the schemas generated from the OpenAPI specification. The validated copy is what
@@ -91,25 +92,18 @@ const { localeError } = z.locales.en();
91
92
  * @internal
92
93
  */
93
94
  export function parseResponse(response, schema) {
94
- const data = pluckData(response.data);
95
+ const { method = 'GET', url = '' } = response.config;
96
+ const envelope = RESPONSE_ENVELOPE_SCHEMA.safeParse(response.data, { error: localeError });
97
+ if (!envelope.success) {
98
+ throw new ResponseValidationError(envelope.error, response.data, { method, url });
99
+ }
100
+ const { data } = envelope.data;
95
101
  const result = schema.safeParse(data, { error: localeError });
96
102
  if (!result.success) {
97
- const { method = 'GET', url = '' } = response.config;
98
103
  throw new ResponseValidationError(result.error, data, { method, url });
99
104
  }
100
105
  return result.data;
101
106
  }
102
- /**
103
- * Returns object's 'data' property or throws if parameter is not an object,
104
- * or an object without a 'data' property.
105
- */
106
- export function pluckData(obj) {
107
- if (typeof obj === 'object' && obj) {
108
- if (typeof obj.data !== 'undefined')
109
- return obj.data;
110
- }
111
- throw new Error(`Expected response object with a "data" property, but received: ${obj}`);
112
- }
113
107
  /**
114
108
  * Swallows a 404 Not Found API error and rethrows anything else.
115
109
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "apify-client",
3
- "version": "3.0.0-beta.61",
3
+ "version": "3.0.0-beta.63",
4
4
  "description": "Apify API client for JavaScript",
5
5
  "engines": {
6
6
  "node": ">=22.13.0"