apify 4.0.0-beta.15 → 4.0.0-beta.151

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 (49) hide show
  1. package/README.md +28 -2
  2. package/dist/actor.d.ts +416 -281
  3. package/dist/actor.js +743 -417
  4. package/dist/apify_dataset_backend.d.ts +22 -0
  5. package/dist/apify_dataset_backend.js +77 -0
  6. package/dist/apify_file_system_storage_backend.d.ts +34 -0
  7. package/dist/apify_file_system_storage_backend.js +41 -0
  8. package/dist/apify_key_value_store_backend.d.ts +26 -0
  9. package/dist/apify_key_value_store_backend.js +57 -0
  10. package/dist/apify_request_queue_backend.d.ts +88 -0
  11. package/dist/apify_request_queue_backend.js +123 -0
  12. package/dist/apify_request_queue_shared_backend.d.ts +31 -0
  13. package/dist/apify_request_queue_shared_backend.js +201 -0
  14. package/dist/apify_request_queue_single_backend.d.ts +43 -0
  15. package/dist/apify_request_queue_single_backend.js +265 -0
  16. package/dist/apify_storage_backend.d.ts +95 -0
  17. package/dist/apify_storage_backend.js +219 -0
  18. package/dist/charging.d.ts +77 -47
  19. package/dist/charging.js +348 -226
  20. package/dist/charging_storage_backend.d.ts +53 -0
  21. package/dist/charging_storage_backend.js +109 -0
  22. package/dist/child_run_tracker.d.ts +110 -0
  23. package/dist/child_run_tracker.js +333 -0
  24. package/dist/configuration.d.ts +48 -28
  25. package/dist/configuration.js +66 -12
  26. package/dist/enqueue_links_filters.d.ts +29 -0
  27. package/dist/enqueue_links_filters.js +52 -0
  28. package/dist/errors.d.ts +31 -0
  29. package/dist/errors.js +22 -0
  30. package/dist/google_sheets.d.ts +12 -0
  31. package/dist/google_sheets.js +26 -0
  32. package/dist/index.d.ts +13 -4
  33. package/dist/index.js +8 -3
  34. package/dist/input-schemas.d.ts +1 -1
  35. package/dist/platform_event_manager.d.ts +24 -9
  36. package/dist/platform_event_manager.js +213 -43
  37. package/dist/proxy_configuration.d.ts +32 -21
  38. package/dist/proxy_configuration.js +137 -79
  39. package/dist/smart_apify_storage_backend.d.ts +52 -0
  40. package/dist/smart_apify_storage_backend.js +73 -0
  41. package/dist/storage.d.ts +6 -26
  42. package/dist/storage.js +1 -79
  43. package/dist/utils.d.ts +28 -3
  44. package/dist/utils.js +59 -17
  45. package/package.json +38 -44
  46. package/dist/apify_storage_client.d.ts +0 -54
  47. package/dist/apify_storage_client.js +0 -152
  48. package/dist/key_value_store.d.ts +0 -21
  49. package/dist/key_value_store.js +0 -41
@@ -1,8 +1,12 @@
1
+ import { once } from 'node:events';
2
+ import { request as httpRequest } from 'node:http';
3
+ import { json } from 'node:stream/consumers';
1
4
  import { ProxyConfiguration as CoreProxyConfiguration } from '@crawlee/core';
2
- import { gotScraping } from 'got-scraping';
3
- import ow from 'ow';
5
+ import { z } from 'zod';
4
6
  import { APIFY_ENV_VARS, APIFY_PROXY_VALUE_REGEX } from '@apify/consts';
7
+ import defaultLog from '@apify/log';
5
8
  import { cryptoRandomObjectId } from '@apify/utilities';
9
+ import { parseArgument } from '@apify/validations';
6
10
  import { Actor } from './actor.js';
7
11
  import { Configuration } from './configuration.js';
8
12
  const CHECK_ACCESS_REQUEST_TIMEOUT_MILLIS = 4_000;
@@ -14,6 +18,7 @@ const SUBDIVISION_CODE_REGEX = /^[A-Z0-9]{1,3}$/;
14
18
  // users; a fresh one is minted for every URL the SDK hands out so that the
15
19
  // returned proxy URLs are independent.
16
20
  const SESSION_ID_LENGTH = 12;
21
+ const SESSION_USERNAME_REGEX = /(?:^|,)session-[^,]+/;
17
22
  /**
18
23
  * Configures connection to a proxy server with the provided options. Proxy servers are used to prevent target websites from blocking
19
24
  * your crawlers based on IP address rate limits or blacklists. Setting proxy configuration in your crawlers automatically configures
@@ -48,40 +53,45 @@ const SESSION_ID_LENGTH = 12;
48
53
  * @category Scaling
49
54
  */
50
55
  export class ProxyConfiguration extends CoreProxyConfiguration {
51
- config;
52
- groups;
53
- countryCode;
54
- subdivisionCode;
55
- password;
56
- hostname;
57
- port;
58
- usesApifyProxy;
56
+ configuration;
57
+ #groups;
58
+ #countryCode;
59
+ #subdivisionCode;
60
+ #password;
61
+ #hostname;
62
+ #port;
63
+ #usesApifyProxy;
64
+ #checkAccess;
65
+ log = defaultLog.child({ prefix: 'ProxyConfiguration' });
59
66
  /**
60
67
  * @internal
61
68
  */
62
- constructor(options = {}, config = Configuration.getGlobalConfig()) {
69
+ constructor(options = {}, configuration = Configuration.getGlobalConfiguration()) {
63
70
  const { proxyUrls, newUrlFunction, ...rest } = options;
64
71
  super({
65
72
  proxyUrls,
66
73
  newUrlFunction,
67
74
  ['validateRequired']: false,
68
75
  });
69
- this.config = config;
70
- ow(rest, ow.object.exactShape({
71
- groups: ow.optional.array.ofType(ow.string.matches(APIFY_PROXY_VALUE_REGEX)),
72
- apifyProxyGroups: ow.optional.array.ofType(ow.string.matches(APIFY_PROXY_VALUE_REGEX)),
73
- countryCode: ow.optional.string.matches(COUNTRY_CODE_REGEX),
74
- apifyProxyCountry: ow.optional.string.matches(COUNTRY_CODE_REGEX),
75
- subdivisionCode: ow.optional.string.matches(SUBDIVISION_CODE_REGEX),
76
- apifyProxySubdivision: ow.optional.string.matches(SUBDIVISION_CODE_REGEX),
77
- password: ow.optional.string,
78
- }));
79
- const { groups = [], apifyProxyGroups = [], countryCode, apifyProxyCountry, subdivisionCode, apifyProxySubdivision, password = config.proxyPassword, } = options;
76
+ this.configuration = configuration;
77
+ parseArgument(rest, z
78
+ .object({
79
+ groups: z.array(z.string().regex(APIFY_PROXY_VALUE_REGEX)).optional(),
80
+ apifyProxyGroups: z.array(z.string().regex(APIFY_PROXY_VALUE_REGEX)).optional(),
81
+ countryCode: z.string().regex(COUNTRY_CODE_REGEX).optional(),
82
+ apifyProxyCountry: z.string().regex(COUNTRY_CODE_REGEX).optional(),
83
+ subdivisionCode: z.string().regex(SUBDIVISION_CODE_REGEX).optional(),
84
+ apifyProxySubdivision: z.string().regex(SUBDIVISION_CODE_REGEX).optional(),
85
+ password: z.string().optional(),
86
+ checkAccess: z.boolean().optional(),
87
+ })
88
+ .strict());
89
+ const { groups = [], apifyProxyGroups = [], countryCode, apifyProxyCountry, subdivisionCode, apifyProxySubdivision, password = configuration.proxyPassword, } = options;
80
90
  const groupsToUse = groups.length ? groups : apifyProxyGroups;
81
91
  const countryCodeToUse = countryCode || apifyProxyCountry;
82
92
  const subdivisionCodeToUse = subdivisionCode || apifyProxySubdivision;
83
- const hostname = config.proxyHostname;
84
- const port = config.proxyPort;
93
+ const hostname = configuration.proxyHostname;
94
+ const port = configuration.proxyPort;
85
95
  // The Apify Proxy subdivision is expressed as part of the country
86
96
  // username parameter (`country-US_CA`), so a country is required.
87
97
  if (subdivisionCodeToUse && !countryCodeToUse) {
@@ -89,17 +99,16 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
89
99
  }
90
100
  // Validation
91
101
  if ((proxyUrls || newUrlFunction) && (groupsToUse.length || countryCodeToUse || subdivisionCodeToUse)) {
92
- this._throwCannotCombineCustomWithApify();
102
+ this.throwCannotCombineCustomWithApify();
93
103
  }
94
- if (proxyUrls && newUrlFunction)
95
- this._throwCannotCombineCustomMethods();
96
- this.groups = groupsToUse;
97
- this.countryCode = countryCodeToUse;
98
- this.subdivisionCode = subdivisionCodeToUse;
99
- this.password = password;
100
- this.hostname = hostname;
101
- this.port = port;
102
- this.usesApifyProxy = !this.proxyUrls && !this.newUrlFunction;
104
+ this.#groups = groupsToUse;
105
+ this.#countryCode = countryCodeToUse;
106
+ this.#subdivisionCode = subdivisionCodeToUse;
107
+ this.#password = password;
108
+ this.#hostname = hostname;
109
+ this.#port = port;
110
+ this.#usesApifyProxy = !proxyUrls && !newUrlFunction;
111
+ this.#checkAccess = options.checkAccess;
103
112
  if (proxyUrls && proxyUrls.some((url) => url?.includes('apify.com'))) {
104
113
  this.log.warning('Some Apify proxy features may work incorrectly. Please consider setting up Apify properties instead of `proxyUrls`.\n' +
105
114
  'See https://docs.apify.com/sdk/js/docs/concepts/proxy-management#apify-proxy-configuration');
@@ -114,11 +123,11 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
114
123
  * `ProxyConfiguration` instance instead of calling this manually.
115
124
  */
116
125
  async initialize(options) {
117
- if (this.usesApifyProxy) {
118
- if (!this.password) {
119
- await this._setPasswordIfToken();
126
+ if (this.#usesApifyProxy) {
127
+ if (!this.#password) {
128
+ await this.setPasswordIfToken();
120
129
  }
121
- if (!this.password) {
130
+ if (!this.#password) {
122
131
  if (Actor.isAtHome()) {
123
132
  throw new Error(`Apify Proxy password must be provided using options.password or the "${APIFY_ENV_VARS.PROXY_PASSWORD}" environment variable. ` +
124
133
  `You can also provide your Apify token via the "${APIFY_ENV_VARS.TOKEN}" environment variable, ` +
@@ -129,10 +138,11 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
129
138
  `provide options.password or "${APIFY_ENV_VARS.PROXY_PASSWORD}" environment variable. ` +
130
139
  `You can also provide your Apify token via the "${APIFY_ENV_VARS.TOKEN}" environment variable, ` +
131
140
  `so that the SDK can fetch the proxy password from Apify API, when ${APIFY_ENV_VARS.PROXY_PASSWORD} is not defined`);
141
+ return false;
132
142
  }
133
143
  }
134
- if (options?.checkAccess !== false) {
135
- return this._checkAccess();
144
+ if ((options?.checkAccess ?? this.#checkAccess) !== false) {
145
+ return this.checkAccess();
136
146
  }
137
147
  }
138
148
  return true;
@@ -141,9 +151,19 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
141
151
  * Returns a new {@link ProxyInfo} object with a fresh proxy URL. Each call mints an
142
152
  * independent URL; for Apify Proxy a random session id is embedded so consecutive
143
153
  * calls resolve to different IPs.
154
+ *
155
+ * A passed `proxyInfo` (e.g. one restored with a persisted session) is returned unchanged, unless it is an
156
+ * Apify Proxy one. Its endpoint is specific to the host, so it is moved to the current endpoint, keeping the
157
+ * username and with it the proxy session. A custom one persisted without its password is handed to the base
158
+ * class, which looks the password up in `proxyUrls`.
144
159
  */
145
- async newProxyInfo(options) {
146
- const url = await this.newUrl(options);
160
+ async newProxyInfo(proxyInfo) {
161
+ // Only Apify Proxy infos carry `groups` and a proxy session in the username.
162
+ if (proxyInfo &&
163
+ !(this.#usesApifyProxy && 'groups' in proxyInfo && SESSION_USERNAME_REGEX.test(proxyInfo.username ?? ''))) {
164
+ return super.newProxyInfo(proxyInfo);
165
+ }
166
+ const url = proxyInfo?.username ? this.composeUrl(proxyInfo.username) : await this.newUrl();
147
167
  if (!url)
148
168
  return undefined;
149
169
  const parsed = new URL(url);
@@ -154,12 +174,15 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
154
174
  hostname: parsed.hostname,
155
175
  port: parsed.port,
156
176
  };
157
- if (this.usesApifyProxy) {
158
- result.groups = this.groups;
159
- if (this.countryCode !== undefined)
160
- result.countryCode = this.countryCode;
161
- if (this.subdivisionCode !== undefined)
162
- result.subdivisionCode = this.subdivisionCode;
177
+ // A refreshed info keeps its own groups/country, which match its username rather than this config.
178
+ if (proxyInfo)
179
+ return { ...proxyInfo, ...result };
180
+ if (this.#usesApifyProxy) {
181
+ result.groups = this.#groups;
182
+ if (this.#countryCode !== undefined)
183
+ result.countryCode = this.#countryCode;
184
+ if (this.#subdivisionCode !== undefined)
185
+ result.subdivisionCode = this.#subdivisionCode;
163
186
  }
164
187
  return result;
165
188
  }
@@ -168,49 +191,49 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
168
191
  * random session id, so consecutive calls return independent URLs. For custom
169
192
  * `proxyUrls`, the URLs are rotated round-robin.
170
193
  */
171
- async newUrl(options) {
172
- if (this.newUrlFunction || this.proxyUrls) {
173
- return super.newUrl(options);
194
+ async newUrl() {
195
+ if (!this.#usesApifyProxy) {
196
+ return super.newUrl();
174
197
  }
175
198
  return this.composeDefaultUrl(cryptoRandomObjectId(SESSION_ID_LENGTH));
176
199
  }
177
200
  /**
178
201
  * Returns proxy username.
179
202
  */
180
- _getUsername(sessionId) {
181
- const { groups, countryCode, subdivisionCode } = this;
203
+ getUsername(sessionId) {
182
204
  const parts = [];
183
- if (groups && groups.length) {
184
- parts.push(`groups-${groups.join('+')}`);
205
+ if (this.#groups && this.#groups.length) {
206
+ parts.push(`groups-${this.#groups.join('+')}`);
185
207
  }
186
208
  parts.push(`session-${sessionId}`);
187
- if (subdivisionCode) {
188
- parts.push(`country-${countryCode}_${subdivisionCode}`);
209
+ if (this.#subdivisionCode) {
210
+ parts.push(`country-${this.#countryCode}_${this.#subdivisionCode}`);
189
211
  }
190
- else if (countryCode) {
191
- parts.push(`country-${countryCode}`);
212
+ else if (this.#countryCode) {
213
+ parts.push(`country-${this.#countryCode}`);
192
214
  }
193
215
  return parts.join(',');
194
216
  }
195
217
  composeDefaultUrl(sessionId) {
196
- const username = this._getUsername(sessionId);
197
- const url = new URL(`http://${this.hostname}:${this.port}`);
218
+ return this.composeUrl(this.getUsername(sessionId));
219
+ }
220
+ composeUrl(username) {
221
+ const url = new URL(`http://${this.#hostname}:${this.#port}`);
198
222
  url.username = `${username}`;
199
- url.password = `${this.password}`;
223
+ url.password = `${this.#password}`;
200
224
  const urlString = url.toString();
201
225
  return urlString.substring(0, urlString.length - 1);
202
226
  }
203
227
  /**
204
228
  * Fetch & set the proxy password from Apify API if an Apify token is provided.
205
229
  */
206
- // TODO: Make this private
207
- async _setPasswordIfToken() {
208
- const { token } = this.config;
230
+ async setPasswordIfToken() {
231
+ const { token } = this.configuration;
209
232
  if (!token)
210
233
  return;
211
234
  try {
212
235
  const user = await Actor.apifyClient.user().get();
213
- this.password = user.proxy?.password;
236
+ this.#password = user?.proxy?.password ?? undefined;
214
237
  }
215
238
  catch (error) {
216
239
  if (Actor.isAtHome()) {
@@ -228,14 +251,16 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
228
251
  * If the check can not be made, it only prints a warning and allows the program to continue. This is to
229
252
  * prevent program crashes caused by short downtimes of Proxy.
230
253
  */
231
- async _checkAccess() {
232
- const status = await this._fetchStatus();
254
+ async checkAccess() {
255
+ const status = await this.fetchStatus();
233
256
  if (!status) {
234
257
  this.log.warning('Apify Proxy access check timed out. Watch out for errors with status code 407. ' +
235
258
  "If you see some, it most likely means you don't have access to either all or some of the proxies you're trying to use.");
236
259
  return true;
237
260
  }
238
261
  const { connected, connectionError, isManInTheMiddle } = status;
262
+ // Declared `readonly false` on the base class; the status check is the one place that
263
+ // learns the actual value, so bypass the readonly marker.
239
264
  this.isManInTheMiddle = isManInTheMiddle;
240
265
  if (connected) {
241
266
  return true;
@@ -252,18 +277,16 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
252
277
  /**
253
278
  * Apify Proxy can be down for a second or a minute, but this should not crash processes.
254
279
  */
255
- async _fetchStatus() {
256
- const { proxyStatusUrl } = this.config;
257
- const requestOpts = {
258
- url: `${proxyStatusUrl}/?format=json`,
259
- proxyUrl: await this.newUrl(),
260
- timeout: { request: CHECK_ACCESS_REQUEST_TIMEOUT_MILLIS },
261
- responseType: 'json',
262
- };
280
+ async fetchStatus() {
281
+ const { proxyStatusUrl } = this.configuration;
282
+ const statusUrl = `${proxyStatusUrl}/?format=json`;
283
+ const proxyUrl = await this.newUrl();
284
+ // Without a proxy URL we can't perform the (proxied) status check.
285
+ if (!proxyUrl)
286
+ return undefined;
263
287
  for (let attempt = 1; attempt <= CHECK_ACCESS_MAX_ATTEMPTS; attempt++) {
264
288
  try {
265
- const response = await gotScraping(requestOpts);
266
- return response.body;
289
+ return await this.requestStatus(statusUrl, proxyUrl);
267
290
  }
268
291
  catch {
269
292
  // retry connection errors
@@ -271,11 +294,46 @@ export class ProxyConfiguration extends CoreProxyConfiguration {
271
294
  }
272
295
  return undefined;
273
296
  }
297
+ /**
298
+ * Fetches the Apify Proxy status endpoint once, *through* the proxy, so the
299
+ * response reports on this exact connection (auth + man-in-the-middle).
300
+ *
301
+ * Uses a native `node:http` forward-proxy request — an absolute request URL
302
+ * plus a `Proxy-Authorization` header — so no proxy-agent dependency is
303
+ * needed. The status endpoint (`http://proxy.apify.com`) is plain HTTP.
304
+ */
305
+ async requestStatus(statusUrl, proxyUrl) {
306
+ const target = new URL(statusUrl);
307
+ const proxy = new URL(proxyUrl);
308
+ const headers = { host: target.host };
309
+ if (proxy.username) {
310
+ const credentials = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
311
+ headers['proxy-authorization'] = `Basic ${Buffer.from(credentials).toString('base64')}`;
312
+ }
313
+ const request = httpRequest({
314
+ host: proxy.hostname,
315
+ port: proxy.port,
316
+ // Absolute-form request URI tells the proxy to forward the request.
317
+ path: target.href,
318
+ headers,
319
+ signal: AbortSignal.timeout(CHECK_ACCESS_REQUEST_TIMEOUT_MILLIS),
320
+ });
321
+ request.end();
322
+ // `once` rejects if the request emits `error` first (connection refused,
323
+ // timeout/abort), so failures propagate to the retry loop in `fetchStatus`.
324
+ const [response] = (await once(request, 'response'));
325
+ const statusCode = response.statusCode ?? 0;
326
+ if (statusCode < 200 || statusCode >= 300) {
327
+ response.resume(); // drain so the socket can be freed
328
+ throw new Error(`Apify Proxy status check responded with status code ${statusCode}.`);
329
+ }
330
+ return (await json(response));
331
+ }
274
332
  /**
275
333
  * Throws cannot combine custom proxies with Apify Proxy
276
334
  * @internal
277
335
  */
278
- _throwCannotCombineCustomWithApify() {
336
+ throwCannotCombineCustomWithApify() {
279
337
  throw new Error('Cannot combine custom proxies with Apify Proxy! ' +
280
338
  'It is not allowed to set "options.proxyUrls" or "options.newUrlFunction" combined with ' +
281
339
  '"options.groups", "options.apifyProxyGroups", "options.countryCode", "options.apifyProxyCountry", ' +
@@ -0,0 +1,52 @@
1
+ import type { DatasetBackend, KeyValueStoreBackend, RequestQueueBackend, StorageBackend, StorageIdentifier } from '@crawlee/types';
2
+ import type { StorageType } from './apify_storage_backend.js';
3
+ import type { Configuration } from './configuration.js';
4
+ import type { OpenStorageOptions } from './storage.js';
5
+ export interface SmartApifyStorageBackendOptions {
6
+ /** Used on the Apify platform, and locally for `forceCloud` storages. */
7
+ cloudStorageBackend: StorageBackend;
8
+ /** Used outside of the Apify platform, except for `forceCloud` storages. */
9
+ localStorageBackend: StorageBackend;
10
+ /** Supplies `isAtHome` and the token that cloud storage needs. */
11
+ configuration: Configuration;
12
+ }
13
+ /**
14
+ * Routes storages to Apify cloud storage or to a local one, depending on where the Actor runs.
15
+ *
16
+ * On the Apify platform (detected through the `APIFY_IS_AT_HOME` environment variable) storages are
17
+ * opened in the cloud; locally they are opened through `localStorageBackend`, unless `forceCloud`
18
+ * asks for the cloud one. `Actor` installs it; callers who want storages of their own pass a
19
+ * backend to `Actor.init({ storage })` instead.
20
+ *
21
+ * @internal
22
+ */
23
+ export declare class SmartApifyStorageBackend implements StorageBackend {
24
+ #private;
25
+ constructor(options: SmartApifyStorageBackendOptions);
26
+ /**
27
+ * The backend a storage is opened through: the cloud one on the platform or with `forceCloud`,
28
+ * the local one otherwise.
29
+ *
30
+ * Exposed so that `forceCloud` storages can be opened through the very same cloud backend
31
+ * instance this one delegates to — two instances would resolve run-scoped aliases to two
32
+ * separate storages.
33
+ */
34
+ getSuitableStorageBackend(options?: OpenStorageOptions): StorageBackend;
35
+ get stats(): {
36
+ rateLimitErrors: number[];
37
+ } | undefined;
38
+ /** Repeats crawlee's own fallback, so that routing a backend does not change how storages are cached. */
39
+ getStorageBackendCacheKey(): string;
40
+ createDatasetBackend(options?: StorageIdentifier): Promise<DatasetBackend>;
41
+ createKeyValueStoreBackend(options?: StorageIdentifier): Promise<KeyValueStoreBackend>;
42
+ createRequestQueueBackend(options?: StorageIdentifier): Promise<RequestQueueBackend>;
43
+ /**
44
+ * Declared unconditionally, unlike on the backends this one delegates to: crawlee branches on
45
+ * the presence of the three methods below, and delegating to a backend that lacks one is
46
+ * indistinguishable from not having it — a `false` from `storageExists` means the same as its
47
+ * absence (crawlee falls through to a name lookup), and the other two have no return value.
48
+ */
49
+ storageExists(id: string, type: StorageType): Promise<boolean>;
50
+ purge(): Promise<void>;
51
+ teardown(): Promise<void>;
52
+ }
@@ -0,0 +1,73 @@
1
+ /**
2
+ * Routes storages to Apify cloud storage or to a local one, depending on where the Actor runs.
3
+ *
4
+ * On the Apify platform (detected through the `APIFY_IS_AT_HOME` environment variable) storages are
5
+ * opened in the cloud; locally they are opened through `localStorageBackend`, unless `forceCloud`
6
+ * asks for the cloud one. `Actor` installs it; callers who want storages of their own pass a
7
+ * backend to `Actor.init({ storage })` instead.
8
+ *
9
+ * @internal
10
+ */
11
+ export class SmartApifyStorageBackend {
12
+ #cloudStorageBackend;
13
+ #localStorageBackend;
14
+ #configuration;
15
+ constructor(options) {
16
+ this.#cloudStorageBackend = options.cloudStorageBackend;
17
+ this.#localStorageBackend = options.localStorageBackend;
18
+ this.#configuration = options.configuration;
19
+ }
20
+ /**
21
+ * The backend a storage is opened through: the cloud one on the platform or with `forceCloud`,
22
+ * the local one otherwise.
23
+ *
24
+ * Exposed so that `forceCloud` storages can be opened through the very same cloud backend
25
+ * instance this one delegates to — two instances would resolve run-scoped aliases to two
26
+ * separate storages.
27
+ */
28
+ getSuitableStorageBackend(options = {}) {
29
+ if (this.#configuration.isAtHome) {
30
+ return this.#cloudStorageBackend;
31
+ }
32
+ if (!options.forceCloud) {
33
+ return this.#localStorageBackend;
34
+ }
35
+ if (!this.#configuration.token) {
36
+ throw new Error('In order to use the Apify cloud storage from your computer, you need to provide an Apify token ' +
37
+ 'using the APIFY_TOKEN environment variable.');
38
+ }
39
+ return this.#cloudStorageBackend;
40
+ }
41
+ get stats() {
42
+ return this.getSuitableStorageBackend().stats;
43
+ }
44
+ /** Repeats crawlee's own fallback, so that routing a backend does not change how storages are cached. */
45
+ getStorageBackendCacheKey() {
46
+ const backend = this.getSuitableStorageBackend();
47
+ return backend.getStorageBackendCacheKey?.() ?? backend.constructor.name;
48
+ }
49
+ async createDatasetBackend(options) {
50
+ return await this.getSuitableStorageBackend().createDatasetBackend(options);
51
+ }
52
+ async createKeyValueStoreBackend(options) {
53
+ return await this.getSuitableStorageBackend().createKeyValueStoreBackend(options);
54
+ }
55
+ async createRequestQueueBackend(options) {
56
+ return await this.getSuitableStorageBackend().createRequestQueueBackend(options);
57
+ }
58
+ /**
59
+ * Declared unconditionally, unlike on the backends this one delegates to: crawlee branches on
60
+ * the presence of the three methods below, and delegating to a backend that lacks one is
61
+ * indistinguishable from not having it — a `false` from `storageExists` means the same as its
62
+ * absence (crawlee falls through to a name lookup), and the other two have no return value.
63
+ */
64
+ async storageExists(id, type) {
65
+ return (await this.getSuitableStorageBackend().storageExists?.(id, type)) ?? false;
66
+ }
67
+ async purge() {
68
+ await this.getSuitableStorageBackend().purge?.();
69
+ }
70
+ async teardown() {
71
+ await this.getSuitableStorageBackend().teardown?.();
72
+ }
73
+ }
package/dist/storage.d.ts CHANGED
@@ -1,6 +1,3 @@
1
- import type { Constructor, IStorage, StorageOpenOptions } from '@crawlee/core';
2
- import type { StorageClient } from '@crawlee/types';
3
- import type { Configuration } from './configuration.js';
4
1
  export interface OpenStorageOptions {
5
2
  /**
6
3
  * If set to `true` then the cloud storage is used even if the `CRAWLEE_STORAGE_DIR`
@@ -10,8 +7,11 @@ export interface OpenStorageOptions {
10
7
  forceCloud?: boolean;
11
8
  }
12
9
  /**
13
- * Identifies a storage by its alias from the Actor's schema storages
14
- * (resolved via the `ACTOR_STORAGES_JSON` environment variable).
10
+ * Identifies a run-scoped storage by its alias.
11
+ *
12
+ * An alias declared in the Actor's schema storages (the `ACTOR_STORAGES_JSON` environment variable)
13
+ * resolves to the storage the platform created for it; any other alias gets an unnamed storage of
14
+ * its own, for this run only.
15
15
  */
16
16
  export interface StorageAlias {
17
17
  alias: string;
@@ -31,28 +31,8 @@ export interface StorageName {
31
31
  /**
32
32
  * Identifies a storage to open. Can be:
33
33
  * - A plain `string` for backward compatibility (treated as ID or name)
34
- * - `{ alias: string }` to resolve from the Actor's schema storages (`ACTOR_STORAGES_JSON`)
34
+ * - `{ alias: string }` to open a run-scoped storage — see {@link StorageAlias}
35
35
  * - `{ id: string }` to open by explicit platform ID
36
36
  * - `{ name: string }` to open by explicit name
37
37
  */
38
38
  export type StorageIdentifier = string | StorageAlias | StorageId | StorageName;
39
- /**
40
- * Identifies a storage to open, without alias support.
41
- * Used for key-value stores and request queues, which do not support aliases.
42
- * Can be:
43
- * - A plain `string` for backward compatibility (treated as ID or name)
44
- * - `{ id: string }` to open by explicit platform ID
45
- * - `{ name: string }` to open by explicit name
46
- */
47
- export type StorageIdentifierWithoutAlias = string | StorageId | StorageName;
48
- export interface OpenStorageContext {
49
- config: Configuration;
50
- client?: StorageClient;
51
- purgedStorageAliases: Set<string>;
52
- }
53
- /**
54
- * Opens a storage by its identifier, handling Apify alias resolution and local purging.
55
- */
56
- export declare function openStorage<T extends IStorage>(storageClass: Constructor<T> & {
57
- open(id?: string | null, options?: StorageOpenOptions): Promise<T>;
58
- }, identifier: StorageIdentifier | null | undefined, context: OpenStorageContext): Promise<T>;
package/dist/storage.js CHANGED
@@ -1,79 +1 @@
1
- import { ApifyStorageClient } from './apify_storage_client.js';
2
- const STORAGE_TYPE_KEYS = {
3
- Dataset: 'datasets',
4
- KeyValueStore: 'keyValueStores',
5
- RequestQueue: 'requestQueues',
6
- };
7
- const parsedStoragesJson = new Map();
8
- /**
9
- * Resolves a {@link StorageIdentifier} to a plain string ID or name
10
- * that can be passed to crawlee v4's `<Storage>.open()`.
11
- */
12
- function resolveStorageIdentifier(storageType, identifier, config) {
13
- if (identifier === null || identifier === undefined) {
14
- return undefined;
15
- }
16
- if (typeof identifier === 'string') {
17
- return identifier;
18
- }
19
- if ('id' in identifier) {
20
- return identifier.id;
21
- }
22
- if ('name' in identifier) {
23
- return identifier.name;
24
- }
25
- // { alias: string }
26
- const storagesJson = config.actorStoragesJson;
27
- if (config.isAtHome && storagesJson) {
28
- let storages;
29
- try {
30
- if (!parsedStoragesJson.has(storagesJson)) {
31
- parsedStoragesJson.set(storagesJson, JSON.parse(storagesJson));
32
- }
33
- storages = parsedStoragesJson.get(storagesJson);
34
- }
35
- catch {
36
- throw new Error(`Failed to parse ACTOR_STORAGES_JSON environment variable: ${storagesJson}`);
37
- }
38
- const typeKey = STORAGE_TYPE_KEYS[storageType];
39
- const resolvedId = storages[typeKey]?.[identifier.alias];
40
- if (resolvedId) {
41
- return resolvedId;
42
- }
43
- throw new Error(`Storage alias "${identifier.alias}" not found in ACTOR_STORAGES_JSON for storage type "${storageType}". ` +
44
- `Available aliases: ${Object.keys(storages[typeKey] ?? {}).join(', ') || '(none)'}`);
45
- }
46
- // When using local storage, just use the alias as a name.
47
- // When using platform storage, we can't just make up a name — the alias must be
48
- // in ACTOR_STORAGES_JSON.
49
- if (config.isAtHome) {
50
- throw new Error(`Storage alias "${identifier.alias}" cannot be resolved because ACTOR_STORAGES_JSON is not set. ` +
51
- `Aliases are only available for storages declared in the Actor's schema.`);
52
- }
53
- return identifier.alias;
54
- }
55
- /**
56
- * Opens a storage by its identifier, handling Apify alias resolution and local purging.
57
- */
58
- export async function openStorage(storageClass, identifier, context) {
59
- const isAlias = identifier !== null && identifier !== undefined && typeof identifier === 'object' && 'alias' in identifier;
60
- if (isAlias && !context.config.isAtHome && context.client instanceof ApifyStorageClient) {
61
- throw new Error('The `alias` option is not allowed for Apify-based storages running outside of Apify');
62
- }
63
- const resolvedIdOrName = resolveStorageIdentifier(storageClass.name, identifier, context.config);
64
- // When running locally, purge aliased storages on first open
65
- // (similar to how crawlee purges default storages on start).
66
- if (isAlias &&
67
- !context.config.isAtHome &&
68
- context.config.purgeOnStart &&
69
- !context.purgedStorageAliases.has(identifier.alias)) {
70
- context.purgedStorageAliases.add(identifier.alias);
71
- const existingStorage = await storageClass.open(resolvedIdOrName ?? null, {
72
- storageClient: context.client,
73
- });
74
- await existingStorage.drop();
75
- }
76
- return storageClass.open(resolvedIdOrName ?? null, {
77
- storageClient: context.client,
78
- });
79
- }
1
+ export {};
package/dist/utils.d.ts CHANGED
@@ -1,3 +1,26 @@
1
+ export { ArgumentValidationError } from '@apify/validations';
2
+ /**
3
+ * Returns `true` for a plain, non-empty object (not `null`, not an array).
4
+ * Mirrors the `ow.object.nonEmpty` predicate the SDK used previously.
5
+ * @internal
6
+ */
7
+ export declare function isNonEmptyObject(value: unknown): value is Record<string, unknown>;
8
+ /** Content type of a JSON record, as `KeyValueStore` and the file-system adoption write it. */
9
+ export declare const JSON_CONTENT_TYPE = "application/json; charset=utf-8";
10
+ /** Content type of raw bytes, which is what a local input file without an extension is adopted as. */
11
+ export declare const BINARY_CONTENT_TYPE = "application/octet-stream";
12
+ /**
13
+ * Parses a raw input record the way `KeyValueStore.getValue` would, with one exception:
14
+ * `application/octet-stream` — the type a local input file without an extension is adopted as — is
15
+ * tried as JSON5 first, so such a file still yields an object. Bytes that do not parse come back as they are.
16
+ * @internal
17
+ */
18
+ export declare function parseInputValue(value: Buffer | ArrayBuffer, contentType: string | null): unknown;
19
+ /**
20
+ * Converts a `SNAKE_CASE` string to `camelCase` (previously provided by `@crawlee/utils`).
21
+ * @internal
22
+ */
23
+ export declare function snakeCaseToCamelCase(snakeCaseStr: string): string;
1
24
  /**
2
25
  * Gets info about system, node version and apify package version.
3
26
  * @internal
@@ -14,7 +37,9 @@ export declare function getSystemInfo(): {
14
37
  */
15
38
  export declare function checkCrawleeVersion(): void;
16
39
  /**
17
- * Prints a warning if this version of Apify SDK is outdated.
18
- * @ignore
40
+ * A FIFO mutex that a critical section may re-enter from a nested call without deadlocking.
19
41
  */
20
- export declare function printOutdatedSdkWarning(): void;
42
+ export declare class ReentrantAsyncLock {
43
+ #private;
44
+ runExclusive<T>(fn: () => Promise<T>): Promise<T>;
45
+ }