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.
- package/README.md +6 -0
- package/dist/apify_api_error.d.ts +2 -1
- package/dist/apify_api_error.js +2 -1
- package/dist/apify_client_error.d.ts +10 -0
- package/dist/apify_client_error.js +10 -0
- package/dist/base/api_client.js +8 -20
- package/dist/base/resource_client.js +8 -8
- package/dist/bundle.js +13 -13
- package/dist/bundle.js.map +1 -1
- package/dist/generated/api.d.ts +2300 -690
- package/dist/generated/schemas.d.ts +1720 -246
- package/dist/generated/schemas.js +416 -75
- package/dist/http_clients/axios.d.ts +2 -1
- package/dist/http_clients/axios.js +6 -4
- package/dist/http_clients/base.d.ts +80 -20
- package/dist/http_clients/base.js +127 -40
- package/dist/http_compressors/index.d.ts +2 -0
- package/dist/http_compressors/index.js +1 -0
- package/dist/http_compressors/resolve.d.ts +4 -3
- package/dist/http_compressors/resolve.js +4 -1
- package/dist/http_compressors/zstd.d.ts +34 -0
- package/dist/http_compressors/zstd.js +43 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/invalid_response_body_error.d.ts +5 -4
- package/dist/invalid_response_body_error.js +5 -4
- package/dist/models.d.ts +30 -61
- package/dist/resource_clients/actor.d.ts +30 -0
- package/dist/resource_clients/actor.js +43 -0
- package/dist/resource_clients/actor_server.d.ts +149 -0
- package/dist/resource_clients/actor_server.js +199 -0
- package/dist/resource_clients/actor_version.d.ts +5 -0
- package/dist/resource_clients/dataset.d.ts +33 -4
- package/dist/resource_clients/dataset.js +16 -54
- package/dist/resource_clients/key_value_store.d.ts +51 -11
- package/dist/resource_clients/key_value_store.js +59 -15
- package/dist/resource_clients/log.d.ts +29 -3
- package/dist/resource_clients/log.js +7 -11
- package/dist/resource_clients/request_queue.d.ts +9 -0
- package/dist/resource_clients/request_queue.js +9 -6
- package/dist/resource_clients/run.d.ts +9 -0
- package/dist/resource_clients/run.js +6 -3
- package/dist/response_validation_error.d.ts +2 -1
- package/dist/response_validation_error.js +2 -1
- package/dist/runtime/node.js +44 -6
- package/dist/runtime/types.d.ts +9 -1
- package/dist/runtime/web.js +4 -1
- package/dist/schemas.d.ts +369 -3
- package/dist/schemas.js +25 -3
- package/dist/utils.d.ts +23 -26
- package/dist/utils.js +32 -25
- package/package.json +23 -23
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { ApifyClientError } from '../apify_client_error.js';
|
|
3
|
+
import { ResourceClient } from '../base/resource_client.js';
|
|
4
|
+
import { mergeHeaders } from '../http_clients/base.js';
|
|
5
|
+
import { compressionSchema, resolveCompressor } from '../http_compressors/resolve.js';
|
|
6
|
+
import * as schemas from '../schemas.js';
|
|
7
|
+
import { timeoutOptionsSchema, timeoutOptionsShape } from '../timeouts.js';
|
|
8
|
+
import { runtime } from '#runtime';
|
|
9
|
+
import { parseArgument, parseResponse } from '../utils.js';
|
|
10
|
+
import { BuildClient } from './build.js';
|
|
11
|
+
import { BuildCollectionClient } from './build_collection.js';
|
|
12
|
+
/**
|
|
13
|
+
* Statuses a server request is retried on. The platform answers with them when it can't pass a request to a server
|
|
14
|
+
* run, so a retry usually doesn't run the Actor's code again. An Actor that returns one itself gets the request again.
|
|
15
|
+
*/
|
|
16
|
+
const SERVER_RETRY_STATUS_CODES = [429, 503];
|
|
17
|
+
const BUILD_NUMBER_PATTERN = /^(\d+)\.(\d+)\.(\d+)$/;
|
|
18
|
+
/**
|
|
19
|
+
* Splits a build number like `0.1.23` into its version and sequence number, or returns `undefined` for anything else.
|
|
20
|
+
*/
|
|
21
|
+
function parseBuildNumber(buildNumber) {
|
|
22
|
+
const match = BUILD_NUMBER_PATTERN.exec(buildNumber ?? '');
|
|
23
|
+
if (!match)
|
|
24
|
+
return undefined;
|
|
25
|
+
return [Number(match[1]), Number(match[2]), Number(match[3])];
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Returns whether `buildNumber` belongs to the same version as `target` and comes before it. Builds are listed newest
|
|
29
|
+
* first and the sequence numbers of a version grow over time, so meeting such a build means the target doesn't exist.
|
|
30
|
+
*/
|
|
31
|
+
function isOlderBuild(buildNumber, target) {
|
|
32
|
+
const parsed = parseBuildNumber(buildNumber);
|
|
33
|
+
return parsed !== undefined && parsed[0] === target[0] && parsed[1] === target[1] && parsed[2] < target[2];
|
|
34
|
+
}
|
|
35
|
+
const requestOptionsSchema = z.strictObject({
|
|
36
|
+
method: z
|
|
37
|
+
.enum(['GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH'])
|
|
38
|
+
.optional(),
|
|
39
|
+
params: z.record(z.string(), z.unknown()).optional(),
|
|
40
|
+
headers: z.record(z.string(), z.string()).optional(),
|
|
41
|
+
data: z.unknown().optional(),
|
|
42
|
+
parentRequestId: z.string().optional(),
|
|
43
|
+
compression: compressionSchema.optional(),
|
|
44
|
+
responseType: z.enum(['parsed', 'buffer', 'stream']).optional(),
|
|
45
|
+
...timeoutOptionsShape,
|
|
46
|
+
});
|
|
47
|
+
/**
|
|
48
|
+
* Client for the server interface of a specific Actor.
|
|
49
|
+
*
|
|
50
|
+
* Provides methods to work with the web server of a Server Actor, such as sending it requests or getting its OpenAPI
|
|
51
|
+
* specification. Get an instance with {@link ActorClient.server}.
|
|
52
|
+
*
|
|
53
|
+
* @example
|
|
54
|
+
* ```javascript
|
|
55
|
+
* const client = new ApifyClient({ token: 'my-token' });
|
|
56
|
+
* const actorServerClient = client.actor('username/actor-name').server();
|
|
57
|
+
*
|
|
58
|
+
* const response = await actorServerClient.request('/search', { params: { q: 'apify' } });
|
|
59
|
+
* console.log(response.data);
|
|
60
|
+
* ```
|
|
61
|
+
*
|
|
62
|
+
* @see https://docs.apify.com/platform/actors/running/standby
|
|
63
|
+
*/
|
|
64
|
+
export class ActorServerClient extends ResourceClient {
|
|
65
|
+
/**
|
|
66
|
+
* The server URL. Getting it takes an API call for the Actor, so it's cached for {@link getUrl} and
|
|
67
|
+
* {@link request}. It's pending while the first lookup runs, so concurrent first calls share one API request.
|
|
68
|
+
*/
|
|
69
|
+
#url;
|
|
70
|
+
/**
|
|
71
|
+
* @hidden
|
|
72
|
+
*/
|
|
73
|
+
constructor(options) {
|
|
74
|
+
super({
|
|
75
|
+
resourcePath: 'actors',
|
|
76
|
+
...options,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* Returns the URL of the Actor's server.
|
|
81
|
+
*
|
|
82
|
+
* The URL is the Actor's `standbyUrl`, fetched from the API by the first call of this method or
|
|
83
|
+
* {@link getOpenApiSpec} and reused by later calls on this client. Use it to call the server with another HTTP
|
|
84
|
+
* client, for example one generated from the server's OpenAPI specification.
|
|
85
|
+
*
|
|
86
|
+
* @param options - Request options
|
|
87
|
+
* @param options.timeoutSecs - Timeout for the API request. Default is `'short'`.
|
|
88
|
+
* @returns The URL of the Actor's server
|
|
89
|
+
* @throws {ApifyClientError} When the Actor is not a Server Actor.
|
|
90
|
+
* @throws {NotFoundError} When the Actor does not exist.
|
|
91
|
+
* @see https://docs.apify.com/platform/actors/running/standby
|
|
92
|
+
*/
|
|
93
|
+
async getUrl(options = {}) {
|
|
94
|
+
const { timeoutSecs = 'short', signal } = parseArgument(options, timeoutOptionsSchema, 'TimeoutOptions');
|
|
95
|
+
const url = (this.#url ??= this.#getServerActor(timeoutSecs, signal).then((actor) => actor.standbyUrl));
|
|
96
|
+
try {
|
|
97
|
+
return await url;
|
|
98
|
+
}
|
|
99
|
+
catch (err) {
|
|
100
|
+
// A failed lookup is not kept, so the next call tries again.
|
|
101
|
+
if (this.#url === url)
|
|
102
|
+
this.#url = undefined;
|
|
103
|
+
throw err;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* Returns the OpenAPI specification of the Actor's server.
|
|
108
|
+
*
|
|
109
|
+
* The specification is the web server schema from the Actor's definition, taken from the build that serves the
|
|
110
|
+
* server interface: the build set in `actorStandby.build`, or `latest` if none is set. Use it to generate an HTTP
|
|
111
|
+
* client for the server, and point that client at the URL returned by {@link getUrl}.
|
|
112
|
+
*
|
|
113
|
+
* @param options - Request options
|
|
114
|
+
* @param options.timeoutSecs - Timeout for each API request. Default is `'short'`.
|
|
115
|
+
* @returns The OpenAPI specification of the Actor's server, or `undefined` if the Actor's definition doesn't
|
|
116
|
+
* include one
|
|
117
|
+
* @throws {ApifyClientError} When the Actor is not a Server Actor, or the build that serves its server interface
|
|
118
|
+
* doesn't exist.
|
|
119
|
+
* @throws {NotFoundError} When the Actor does not exist.
|
|
120
|
+
* @see https://docs.apify.com/platform/actors/development/actor-definition/web-server-schema
|
|
121
|
+
*/
|
|
122
|
+
async getOpenApiSpec(options = {}) {
|
|
123
|
+
const { timeoutSecs = 'short', signal } = parseArgument(options, timeoutOptionsSchema, 'TimeoutOptions');
|
|
124
|
+
const actor = await this.#getServerActor(timeoutSecs, signal);
|
|
125
|
+
const buildRef = actor.actorStandby?.build || 'latest';
|
|
126
|
+
let buildId = actor.taggedBuilds?.[buildRef]?.buildId ?? undefined;
|
|
127
|
+
const targetBuildNumber = parseBuildNumber(buildRef);
|
|
128
|
+
if (buildId === undefined && targetBuildNumber !== undefined) {
|
|
129
|
+
// Not a tag, so look `buildRef` up as a build number, which the API can't resolve directly.
|
|
130
|
+
const builds = new BuildCollectionClient(this.subResourceOptions({ resourcePath: 'builds' }));
|
|
131
|
+
for await (const build of builds.list({ desc: true, timeoutSecs, signal })) {
|
|
132
|
+
if (build.buildNumber === buildRef) {
|
|
133
|
+
buildId = build.id;
|
|
134
|
+
break;
|
|
135
|
+
}
|
|
136
|
+
if (isOlderBuild(build.buildNumber, targetBuildNumber))
|
|
137
|
+
break;
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
const build = buildId === undefined
|
|
141
|
+
? undefined
|
|
142
|
+
: await new BuildClient({
|
|
143
|
+
baseUrl: this.apifyClient.baseUrl,
|
|
144
|
+
publicBaseUrl: this.apifyClient.publicBaseUrl,
|
|
145
|
+
httpClient: this.httpClient,
|
|
146
|
+
apifyClient: this.apifyClient,
|
|
147
|
+
id: buildId,
|
|
148
|
+
}).get({ timeoutSecs, signal });
|
|
149
|
+
if (build === undefined) {
|
|
150
|
+
throw new ApifyClientError(`Build ${buildRef} of Actor ${this.id} does not exist.`);
|
|
151
|
+
}
|
|
152
|
+
return build.actorDefinition?.webServerSchema;
|
|
153
|
+
}
|
|
154
|
+
async request(path = '/', options = {}) {
|
|
155
|
+
parseArgument(path, z.string());
|
|
156
|
+
const { method = 'GET', params, headers, data, parentRequestId, compression, responseType, timeoutSecs = 'long', signal, } = parseArgument(options, requestOptionsSchema, 'ActorServerRequestOptions');
|
|
157
|
+
if (responseType === 'stream' && !runtime.isNode) {
|
|
158
|
+
throw new Error("The 'stream' response type can only be used in Node.js environment.");
|
|
159
|
+
}
|
|
160
|
+
const serverUrl = await this.getUrl({ signal });
|
|
161
|
+
const serverPath = path.split('#')[0].replace(/^\/+/, '');
|
|
162
|
+
return this.httpClient.call({
|
|
163
|
+
url: `${serverUrl.replace(/\/+$/, '')}/${serverPath}`,
|
|
164
|
+
method,
|
|
165
|
+
params,
|
|
166
|
+
headers: parentRequestId === undefined
|
|
167
|
+
? headers
|
|
168
|
+
: mergeHeaders(headers ?? {}, { 'X-Actor-Request-ID': parentRequestId }),
|
|
169
|
+
data,
|
|
170
|
+
compression: compression === undefined ? false : resolveCompressor(compression),
|
|
171
|
+
authorizationHeader: 'X-Apify-Authorization',
|
|
172
|
+
throwOnErrorStatus: false,
|
|
173
|
+
retryStatusCodes: SERVER_RETRY_STATUS_CODES,
|
|
174
|
+
retryTransportErrors: false,
|
|
175
|
+
followRedirects: false,
|
|
176
|
+
responseType,
|
|
177
|
+
timeoutSecs,
|
|
178
|
+
signal,
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
/**
|
|
182
|
+
* Fetches the Actor, checks that it is a Server Actor, and caches its server URL.
|
|
183
|
+
*/
|
|
184
|
+
async #getServerActor(timeoutSecs, signal) {
|
|
185
|
+
const response = await this.httpClient.call({
|
|
186
|
+
url: this.buildUrl(),
|
|
187
|
+
method: 'GET',
|
|
188
|
+
params: this.buildParams(),
|
|
189
|
+
timeoutSecs,
|
|
190
|
+
signal,
|
|
191
|
+
});
|
|
192
|
+
const actor = parseResponse(response, schemas.ActorResource());
|
|
193
|
+
if (!actor.standbyUrl) {
|
|
194
|
+
throw new ApifyClientError(`Actor ${this.id} is not a Server Actor.`);
|
|
195
|
+
}
|
|
196
|
+
this.#url = Promise.resolve(actor.standbyUrl);
|
|
197
|
+
return actor;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
@@ -83,5 +83,10 @@ export declare class ActorVersionClient extends ResourceClient {
|
|
|
83
83
|
* All of them are optional, because the endpoint leaves untouched whatever the payload does not
|
|
84
84
|
* mention. The version union enforces the pairing: a `sourceType` can only be sent next to the
|
|
85
85
|
* source location it implies, never next to one of the other three.
|
|
86
|
+
*
|
|
87
|
+
* On a `SOURCE_FILES` or `TARBALL` version, `actorPath: null` removes the stored path. So does an
|
|
88
|
+
* update that sends `sourceType`, `sourceFiles`, or `tarballUrl` without `actorPath`, so send it
|
|
89
|
+
* again with every upload. The API rejects an `actorPath` on a version of any other source type,
|
|
90
|
+
* also when the update leaves out `sourceType`, because it then checks the stored source type.
|
|
86
91
|
*/
|
|
87
92
|
export type ActorVersionUpdateData = Partial<Version>;
|
|
@@ -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';
|
|
@@ -89,6 +90,7 @@ export declare class DatasetClient<Data extends Record<string | number, any> = R
|
|
|
89
90
|
* @param options - Options for listing items
|
|
90
91
|
* @param options.limit - Maximum number of items to return. Default is all items.
|
|
91
92
|
* @param options.chunkSize - Maximum number of items returned in one API response. Relevant in the context of asyncIterator.
|
|
93
|
+
* Without it, iteration loads the whole dataset, or all `limit` items, in one response.
|
|
92
94
|
* @param options.offset - Number of items to skip from the beginning. Default is 0.
|
|
93
95
|
* @param options.desc - If `true`, items are returned in descending order (newest first). Default is `false`.
|
|
94
96
|
* @param options.fields - Array of field names to include in the results. Omits all other fields.
|
|
@@ -132,6 +134,11 @@ export declare class DatasetClient<Data extends Record<string | number, any> = R
|
|
|
132
134
|
* dataset items, this method returns the items serialized to the provided format
|
|
133
135
|
* (JSON, CSV, Excel, etc.) as a Buffer. Useful for exporting data for further processing.
|
|
134
136
|
*
|
|
137
|
+
* In Node.js you can use the `stream` option to get a Readable stream, so a large export is processed in chunks
|
|
138
|
+
* without holding all of it in memory. The stream holds its connection open until you consume it to the end or
|
|
139
|
+
* destroy it. Iterating it with `for await` or passing it to `pipeline()` from `node:stream/promises` does either
|
|
140
|
+
* one for you.
|
|
141
|
+
*
|
|
135
142
|
* @param format - Output format: `'json'`, `'jsonl'`, `'csv'`, `'xlsx'`, `'xml'`, `'rss'`, or `'html'`
|
|
136
143
|
* @param options - Download and formatting options (extends all options from {@link listItems})
|
|
137
144
|
* @param options.attachment - If `true`, the response will have `Content-Disposition: attachment` header.
|
|
@@ -142,8 +149,12 @@ export declare class DatasetClient<Data extends Record<string | number, any> = R
|
|
|
142
149
|
* @param options.xmlRow - Name of the XML element for each item. Default is `'item'`.
|
|
143
150
|
* @param options.fields - Array of field names to include in the export.
|
|
144
151
|
* @param options.omit - Array of field names to exclude from the export.
|
|
145
|
-
* @param options.
|
|
146
|
-
* @
|
|
152
|
+
* @param options.stream - If `true`, the items are returned as a Readable stream. Node.js only.
|
|
153
|
+
* @param options.timeoutSecs - Timeout for the API request. Default is `'long'`. With `stream`, it bounds the
|
|
154
|
+
* wait for the API to start responding; once the stream is returned, it only limits inactivity: the stream errors
|
|
155
|
+
* if no data arrives for that long. To stop the download early or cap its total duration, destroy the stream or
|
|
156
|
+
* abort `signal`.
|
|
157
|
+
* @returns Buffer containing the serialized data in the specified format, or a Readable stream of it with `stream`
|
|
147
158
|
* @see https://docs.apify.com/api/v2/dataset-items-get
|
|
148
159
|
*
|
|
149
160
|
* @example
|
|
@@ -164,9 +175,21 @@ export declare class DatasetClient<Data extends Record<string | number, any> = R
|
|
|
164
175
|
* xmlRoot: 'products',
|
|
165
176
|
* xmlRow: 'product'
|
|
166
177
|
* });
|
|
178
|
+
*
|
|
179
|
+
* // Stream a CSV export straight to a file
|
|
180
|
+
* const { createWriteStream } = require('node:fs');
|
|
181
|
+
* const { pipeline } = require('node:stream/promises');
|
|
182
|
+
* const stream = await client.dataset('my-dataset').downloadItems('csv', { stream: true });
|
|
183
|
+
* await pipeline(stream, createWriteStream('output.csv'));
|
|
167
184
|
* ```
|
|
168
185
|
*/
|
|
169
|
-
downloadItems(format: `${DownloadItemsFormat}`, options?: DatasetClientDownloadItemsOptions
|
|
186
|
+
downloadItems(format: `${DownloadItemsFormat}`, options?: DatasetClientDownloadItemsOptions & {
|
|
187
|
+
stream?: false;
|
|
188
|
+
}): Promise<Buffer>;
|
|
189
|
+
downloadItems(format: `${DownloadItemsFormat}`, options: DatasetClientDownloadItemsOptions & {
|
|
190
|
+
stream: true;
|
|
191
|
+
}): Promise<Readable>;
|
|
192
|
+
downloadItems(format: `${DownloadItemsFormat}`, options?: DatasetClientDownloadItemsOptions): Promise<Buffer | Readable>;
|
|
170
193
|
/**
|
|
171
194
|
* Stores one or more items into the dataset.
|
|
172
195
|
*
|
|
@@ -221,7 +244,8 @@ export declare class DatasetClient<Data extends Record<string | number, any> = R
|
|
|
221
244
|
* This is useful for sharing dataset results with external services or users.
|
|
222
245
|
*
|
|
223
246
|
* @param options - URL generation options (extends all options from {@link listItems})
|
|
224
|
-
* @param options.expiresInSecs - Number of seconds until the signed URL expires. If omitted, the URL
|
|
247
|
+
* @param options.expiresInSecs - Number of seconds until the signed URL expires. Must be positive. If omitted, the URL
|
|
248
|
+
* never expires.
|
|
225
249
|
* @param options.fields - Array of field names to include in the response.
|
|
226
250
|
* @param options.format - Format of the items served by the URL. Defaults to `json`.
|
|
227
251
|
* @param options.limit - Maximum number of items to return.
|
|
@@ -318,4 +342,9 @@ export interface DatasetClientDownloadItemsOptions extends Omit<DatasetClientLis
|
|
|
318
342
|
skipHeaderRow?: boolean;
|
|
319
343
|
xmlRoot?: string;
|
|
320
344
|
xmlRow?: string;
|
|
345
|
+
/**
|
|
346
|
+
* If `true`, the items are returned as a Readable stream. Node.js only.
|
|
347
|
+
* @default false
|
|
348
|
+
*/
|
|
349
|
+
stream?: boolean;
|
|
321
350
|
}
|
|
@@ -3,7 +3,8 @@ 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 {
|
|
6
|
+
import { runtime } from '#runtime';
|
|
7
|
+
import { anyObjectSchema, applyQueryParamsToUrl, cast, isNonArrayObject, paginationOptionsShape, parseArgument, parseResponse, } from '../utils.js';
|
|
7
8
|
/**
|
|
8
9
|
* Supported formats for downloading dataset items.
|
|
9
10
|
*/
|
|
@@ -55,6 +56,7 @@ const downloadItemsOptionsSchema = z.strictObject({
|
|
|
55
56
|
xmlRoot: z.string().optional(),
|
|
56
57
|
xmlRow: z.string().optional(),
|
|
57
58
|
signature: z.string().optional(),
|
|
59
|
+
stream: z.boolean().optional(),
|
|
58
60
|
...timeoutOptionsShape,
|
|
59
61
|
});
|
|
60
62
|
const pushItemsSchema = z.union([itemSchema, z.string(), z.array(itemSchema)]);
|
|
@@ -74,7 +76,7 @@ const createItemsPublicUrlOptionsSchema = z.strictObject({
|
|
|
74
76
|
skipHidden: z.boolean().optional(),
|
|
75
77
|
unwind: z.array(z.string()).optional(),
|
|
76
78
|
view: z.string().optional(),
|
|
77
|
-
expiresInSecs: z.number().optional(),
|
|
79
|
+
expiresInSecs: z.number().positive().optional(),
|
|
78
80
|
...timeoutOptionsShape,
|
|
79
81
|
});
|
|
80
82
|
/**
|
|
@@ -163,6 +165,7 @@ export class DatasetClient extends ResourceClient {
|
|
|
163
165
|
* @param options - Options for listing items
|
|
164
166
|
* @param options.limit - Maximum number of items to return. Default is all items.
|
|
165
167
|
* @param options.chunkSize - Maximum number of items returned in one API response. Relevant in the context of asyncIterator.
|
|
168
|
+
* Without it, iteration loads the whole dataset, or all `limit` items, in one response.
|
|
166
169
|
* @param options.offset - Number of items to skip from the beginning. Default is 0.
|
|
167
170
|
* @param options.desc - If `true`, items are returned in descending order (newest first). Default is `false`.
|
|
168
171
|
* @param options.fields - Array of field names to include in the results. Omits all other fields.
|
|
@@ -212,50 +215,12 @@ export class DatasetClient extends ResourceClient {
|
|
|
212
215
|
};
|
|
213
216
|
return this.listPaginatedFromCallback(fetchItems, listOptions);
|
|
214
217
|
}
|
|
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
218
|
async downloadItems(format, options = {}) {
|
|
257
219
|
parseArgument(format, itemFormatSchema);
|
|
258
|
-
const { timeoutSecs = 'long', signal, ...query } = parseArgument(options, downloadItemsOptionsSchema, 'DatasetClientDownloadItemsOptions');
|
|
220
|
+
const { timeoutSecs = 'long', signal, stream, ...query } = parseArgument(options, downloadItemsOptionsSchema, 'DatasetClientDownloadItemsOptions');
|
|
221
|
+
if (stream && !runtime.isNode) {
|
|
222
|
+
throw new Error('The stream option can only be used in Node.js environment.');
|
|
223
|
+
}
|
|
259
224
|
const { data } = await this.httpClient.call({
|
|
260
225
|
url: this.buildUrl('items'),
|
|
261
226
|
method: 'GET',
|
|
@@ -263,7 +228,7 @@ export class DatasetClient extends ResourceClient {
|
|
|
263
228
|
format,
|
|
264
229
|
...query,
|
|
265
230
|
}),
|
|
266
|
-
responseType: 'buffer',
|
|
231
|
+
responseType: stream ? 'stream' : 'buffer',
|
|
267
232
|
timeoutSecs,
|
|
268
233
|
signal,
|
|
269
234
|
});
|
|
@@ -348,7 +313,8 @@ export class DatasetClient extends ResourceClient {
|
|
|
348
313
|
* This is useful for sharing dataset results with external services or users.
|
|
349
314
|
*
|
|
350
315
|
* @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
|
|
316
|
+
* @param options.expiresInSecs - Number of seconds until the signed URL expires. Must be positive. If omitted, the URL
|
|
317
|
+
* never expires.
|
|
352
318
|
* @param options.fields - Array of field names to include in the response.
|
|
353
319
|
* @param options.format - Format of the items served by the URL. Defaults to `json`.
|
|
354
320
|
* @param options.limit - Maximum number of items to return.
|
|
@@ -391,21 +357,17 @@ export class DatasetClient extends ResourceClient {
|
|
|
391
357
|
}
|
|
392
358
|
#createPaginationList(response, userProvidedDesc) {
|
|
393
359
|
const descHeader = response.headers['x-apify-pagination-desc'];
|
|
394
|
-
|
|
360
|
+
return {
|
|
395
361
|
items: response.data,
|
|
396
362
|
total: Number(response.headers['x-apify-pagination-total']),
|
|
397
363
|
offset: Number(response.headers['x-apify-pagination-offset']),
|
|
398
364
|
// `x-apify-pagination-count` reports the rows scanned, which filters and `unwind` can leave above or below
|
|
399
|
-
// the items returned.
|
|
400
|
-
|
|
365
|
+
// the items returned. It is derived from the dataset's item count, which lags a fresh push, so it can also
|
|
366
|
+
// fall below the items returned on an unfiltered page.
|
|
367
|
+
count: Math.max(Number(response.headers['x-apify-pagination-count'] ?? 0), response.data.length),
|
|
401
368
|
limit: Number(response.headers['x-apify-pagination-limit']), // API returns 999999999999 when no limit is used
|
|
402
369
|
// TODO: Replace this once https://github.com/apify/apify-core/issues/3503 is solved
|
|
403
370
|
desc: typeof descHeader === 'string' ? JSON.parse(descHeader) : userProvidedDesc,
|
|
404
371
|
};
|
|
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
372
|
}
|
|
411
373
|
}
|
|
@@ -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
|
|
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'`.
|
|
@@ -208,21 +211,33 @@ export declare class KeyValueStoreClient extends ResourceClient {
|
|
|
208
211
|
* to be valid JSON already, or {@link getRecord} fails to parse it back.
|
|
209
212
|
*
|
|
210
213
|
* **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
|
-
*
|
|
214
|
+
* the upload cannot be retried on failure or follow redirects. For reliable uploads of a file,
|
|
215
|
+
* pass a `Blob` from `fs.openAsBlob()` instead: it is read again for every attempt and never held
|
|
216
|
+
* in memory whole.
|
|
213
217
|
*
|
|
214
218
|
* @param record - The record to store
|
|
215
219
|
* @param record.key - Record key (unique identifier)
|
|
216
|
-
* @param record.value - Record value (a JSON-serializable value, Buffer, ArrayBuffer, typed array, or
|
|
220
|
+
* @param record.value - Record value (a JSON-serializable value, Buffer, ArrayBuffer, typed array, Blob, or
|
|
221
|
+
* Readable)
|
|
217
222
|
* @param record.contentType - Optional MIME type. Auto-detected if not provided:
|
|
218
223
|
* - Objects: `'application/json; charset=utf-8'`
|
|
219
224
|
* - Strings: `'text/plain; charset=utf-8'`
|
|
225
|
+
* - Blobs: their `type`, or `'application/octet-stream'` when it is empty
|
|
220
226
|
* - Binary values and streams: `'application/octet-stream'`
|
|
221
227
|
*
|
|
222
228
|
* Worth setting for media and archives: the client skips compressing a body
|
|
223
229
|
* whose content type already carries its own compression. The
|
|
224
230
|
* `'application/octet-stream'` fallback is treated as compressible, because
|
|
225
231
|
* it could hold any binary data.
|
|
232
|
+
* @param record.contentEncoding - Optional encoding already applied to `value`, sent as the `Content-Encoding`
|
|
233
|
+
* header. Set it to upload a pre-compressed value: the client then sends the
|
|
234
|
+
* bytes as they are and does not compress them again. The API accepts `gzip`,
|
|
235
|
+
* `br`, `zstd`, `deflate`, and `identity`, and stores the record exactly as
|
|
236
|
+
* uploaded, so this is also the encoding the record is served with. Only binary
|
|
237
|
+
* values and streams can carry a compression, so any encoding other than
|
|
238
|
+
* `identity` throws a `TypeError` when `value` is a string, or a plain object,
|
|
239
|
+
* array, or other value that the client serializes to JSON. Node.js only, since
|
|
240
|
+
* browsers cannot send the header to the API.
|
|
226
241
|
* @param options - Storage options
|
|
227
242
|
* @param options.timeoutSecs - Timeout for the API request. Default is `'long'`.
|
|
228
243
|
* @param options.doNotRetryTimeouts - If `true`, don't retry on timeout errors. Default is `false`.
|
|
@@ -250,9 +265,18 @@ export declare class KeyValueStoreClient extends ResourceClient {
|
|
|
250
265
|
* value: imageBuffer,
|
|
251
266
|
* contentType: 'image/png'
|
|
252
267
|
* });
|
|
268
|
+
*
|
|
269
|
+
* // Store a gzipped file without compressing it again
|
|
270
|
+
* const gzippedReport = await readFile('report.json.gz');
|
|
271
|
+
* await client.keyValueStore('my-store').setRecord({
|
|
272
|
+
* key: 'report.json',
|
|
273
|
+
* value: gzippedReport,
|
|
274
|
+
* contentType: 'application/json',
|
|
275
|
+
* contentEncoding: 'gzip'
|
|
276
|
+
* });
|
|
253
277
|
* ```
|
|
254
278
|
*/
|
|
255
|
-
setRecord(record:
|
|
279
|
+
setRecord(record: KeyValueStoreRecordInput, options?: KeyValueStoreRecordOptions): Promise<void>;
|
|
256
280
|
/**
|
|
257
281
|
* Deletes a record from the key-value store.
|
|
258
282
|
*
|
|
@@ -287,6 +311,12 @@ export interface KeyValueClientUpdateOptions {
|
|
|
287
311
|
*/
|
|
288
312
|
export interface KeyValueClientListKeysOptions extends TimeoutOptions {
|
|
289
313
|
limit?: number;
|
|
314
|
+
/**
|
|
315
|
+
* Maximum number of keys returned in one API response. When the call is iterated with `for await`, the iterator
|
|
316
|
+
* fetches keys in chunks of this size and yields them one by one, until `limit` is reached or the store has no
|
|
317
|
+
* more keys. Awaiting the call returns only the first chunk. Without it, the API's default page size applies.
|
|
318
|
+
*/
|
|
319
|
+
chunkSize?: number;
|
|
290
320
|
exclusiveStartKey?: string;
|
|
291
321
|
collection?: string;
|
|
292
322
|
/**
|
|
@@ -301,11 +331,11 @@ export interface KeyValueClientListKeysOptions extends TimeoutOptions {
|
|
|
301
331
|
/**
|
|
302
332
|
* Options for creating a public URL to list keys in a Key-Value Store.
|
|
303
333
|
*
|
|
304
|
-
* Extends {@link KeyValueClientListKeysOptions} with URL expiration control, minus `
|
|
305
|
-
* method produces one).
|
|
334
|
+
* Extends {@link KeyValueClientListKeysOptions} with URL expiration control, minus `chunkSize` (it only sizes a
|
|
335
|
+
* client-side iteration) and `signature` (this method produces one).
|
|
306
336
|
* @since Added in 2.16.0
|
|
307
337
|
*/
|
|
308
|
-
export interface KeyValueClientCreateKeysUrlOptions extends Omit<KeyValueClientListKeysOptions, 'signature'> {
|
|
338
|
+
export interface KeyValueClientCreateKeysUrlOptions extends Omit<KeyValueClientListKeysOptions, 'chunkSize' | 'signature'> {
|
|
309
339
|
expiresInSecs?: number;
|
|
310
340
|
}
|
|
311
341
|
/**
|
|
@@ -323,10 +353,10 @@ export interface KeyValueClientGetRecordOptions extends TimeoutOptions {
|
|
|
323
353
|
* A value that `setRecord` accepts.
|
|
324
354
|
*
|
|
325
355
|
* 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
|
|
327
|
-
* `TypedArray` covers it.
|
|
356
|
+
* it: a `Buffer`, an `ArrayBuffer`, a typed array, a `Blob`, or a readable stream. `Buffer` is a
|
|
357
|
+
* `Uint8Array`, so `TypedArray` covers it.
|
|
328
358
|
*/
|
|
329
|
-
export type KeyValueStoreRecordValue = JsonValue | ArrayBuffer | TypedArray | Readable;
|
|
359
|
+
export type KeyValueStoreRecordValue = JsonValue | ArrayBuffer | TypedArray | Blob | Readable;
|
|
330
360
|
/**
|
|
331
361
|
* Represents a record (key-value pair) in a Key-Value Store.
|
|
332
362
|
*
|
|
@@ -337,6 +367,16 @@ export interface KeyValueStoreRecord<T> {
|
|
|
337
367
|
value: T;
|
|
338
368
|
contentType?: string;
|
|
339
369
|
}
|
|
370
|
+
/**
|
|
371
|
+
* A record to store with {@link KeyValueStoreClient.setRecord}.
|
|
372
|
+
*/
|
|
373
|
+
export interface KeyValueStoreRecordInput extends KeyValueStoreRecord<KeyValueStoreRecordValue> {
|
|
374
|
+
/**
|
|
375
|
+
* Encoding already applied to `value`, sent as the `Content-Encoding` header. See
|
|
376
|
+
* {@link KeyValueStoreClient.setRecord}.
|
|
377
|
+
*/
|
|
378
|
+
contentEncoding?: string;
|
|
379
|
+
}
|
|
340
380
|
/**
|
|
341
381
|
* Options for storing a record in a Key-Value Store.
|
|
342
382
|
* @since Added in 2.12.4
|