Crawlee—A web scraping and browser automation library for Node.js to build reliable crawlers. In JavaScript and TypeScript. Extract data for AI, LLMs, RAG, or GPTs. Download HTML, PDF, JPG, PNG, and other files from websites. Works with Puppeteer, Playwright, Cheerio, JSDOM, and raw HTTP. Both headful and headless mode. With proxy rotation.
TypeScript apifyautomationcrawlercrawlingheadlessheadless-chromejavascriptnodejsnpmplaywrightpuppeteerscraperscrapingtypescriptweb-crawlerweb-crawlingweb-scraping
feat: introduce new `Apify` and `Configuration` classes (#993)
Martin Adámekd44f3b506822
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0bebcb6e5..6949fe264 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,3 +1,46 @@+1.3.0 / BETA+====================+Adds two new named exports:++- `Configuration` class that serves as the main configuration holder, replacing explicit usage of+environment variables.+- `Apify` class that allows configuring the SDK. Env vars still have precedence over the SDK configuration.++When using the Apify class, there should be no side effects.+Also adds new configuration for WAL mode in `ApifyStorageLocal`.++As opposed to using the global helper functions like `main`, there is an alternative approach using `Apify` class.+It has mostly the same API, but the methods on `Apify` instance will use the configuration provided in the constructor.+Environment variables will have precedence over this configuration.++```js+const { Apify } = require('apify'); // use named export to get the class++const sdk = new Apify({ token: '123' });+console.log(sdk.config.get('token')); // '123'++// the token will be passed to the `call` method automatically+const run = await sdk.call('apify/hello-world', { myInput: 123 });+console.log(`Received message: ${run.output.body.message}`);+```++Another example shows how the default dataset name can be changed:++```js+const { Apify } = require('apify'); // use named export to get the class++const sdk = new Apify({ defaultDatasetId: 'custom-name' });+await sdk.pushData({ myValue: 123 });+```++is equivalent to:+```js+const Apify = require('apify'); // use default export to get the helper functions++const dataset = await Apify.openDataset('custom-name');+await dataset.pushData({ myValue: 123 });+```+1.2.1 / 2021/05/14====================- Fix `requestAsBrowser` behavior with various combinations of `json`, `payload` legacy options.diff --git a/package.json b/package.jsonindex b3ad06a2d..b4e2e6100 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "apify",- "version": "1.2.1",+ "version": "1.3.0","description": "The scalable web crawling and scraping library for JavaScript/Node.js. Enables development of data extraction and web automation jobs (not only) with headless Chrome and Puppeteer.","engines": {"node": ">=10.17.0"diff --git a/src/apify.js b/src/apify.jsnew file mode 100644index 000000000..c18bd288d--- /dev/null+++ b/src/apify.js@@ -0,0 +1,961 @@+import ow from 'ow';+import { ACT_JOB_STATUSES, ENV_VARS } from 'apify-shared/consts';+import { getEnv } from './actor';+import { initializeEvents, stopEvents } from './events';+import { StorageManager } from './storages/storage_manager';+import { Dataset } from './storages/dataset';+import { KeyValueStore, maybeStringify } from './storages/key_value_store';+import { RequestList, REQUESTS_PERSISTENCE_KEY, STATE_PERSISTENCE_KEY } from './request_list';+import { RequestQueue } from './storages/request_queue';+import { SessionPool } from './session_pool/session_pool';+import { ProxyConfiguration } from './proxy_configuration';+import { addCharsetToContentType, logSystemInfo, printOutdatedSdkWarning, publicUtils, sleep } from './utils';+import log from './utils_log';+import { EXIT_CODES } from './constants';+import { Configuration } from './configuration';+import { puppeteerUtils } from './puppeteer_utils';+import { playwrightUtils } from './playwright_utils';+import { socialUtils } from './utils_social';+import { enqueueLinks } from './enqueue_links/enqueue_links';+import { requestAsBrowser } from './utils_request';+import { ApifyCallError } from './errors';++/**+ * @typedef AdhocWebhook+ * @property {EventTypes} eventTypes+ * @property {string} requestUrl+ * @property {string} [idempotencyKey]+ * @property {string} [payloadTemplate]+ */++/**+ * `Apify` class serves as an alternative approach to the static helpers exported from the package. It allows to pass configuration+ * that will be used on the instance methods. Environment variables will have precedence over this configuration.+ * See {@link Configuration} for details about what can be configured and what are the default values.+ *+ * @property {Configuration} config Configuration of this SDK instance (provided to its constructor). See {@link Configuration} for details.+ * @ignore+ */+export class Apify {+ constructor(options = {}) {+ this.config = new Configuration(options);+ this._storageManagers = new Map();+ }++ /**+ * Runs the main user function that performs the job of the actor+ * and terminates the process when the user function finishes.+ *+ * **The `Apify.main()` function is optional** and is provided merely for your convenience.+ * It is mainly useful when you're running your code as an actor on the [Apify platform](https://apify.com/actors).+ * However, if you want to use Apify SDK tools directly inside your existing projects, e.g.+ * running in an [Express](https://expressjs.com/) server, on+ * [Google Cloud functions](https://cloud.google.com/functions)+ * or [AWS Lambda](https://aws.amazon.com/lambda/), it's better to avoid+ * it since the function terminates the main process when it finishes!+ *+ * The `Apify.main()` function performs the following actions:+ *+ * - When running on the Apify platform (i.e. <code>APIFY_IS_AT_HOME</code> environment variable is set),+ * it sets up a connection to listen for platform events.+ * For example, to get a notification about an imminent migration to another server.+ * See {@link Apify.events} for details.+ * - It checks that either <code>APIFY_TOKEN</code> or <code>APIFY_LOCAL_STORAGE_DIR</code> environment variable+ * is defined. If not, the functions sets <code>APIFY_LOCAL_STORAGE_DIR</code> to <code>./apify_storage</code>+ * inside the current working directory. This is to simplify running code examples.+ * - It invokes the user function passed as the <code>userFunc</code> parameter.+ * - If the user function returned a promise, waits for it to resolve.+ * - If the user function throws an exception or some other error is encountered,+ * prints error details to console so that they are stored to the log.+ * - Exits the Node.js process, with zero exit code on success and non-zero on errors.+ *+ * The user function can be synchronous:+ *+ * ```javascript+ * Apify.main(() => {+ * // My synchronous function that returns immediately+ * console.log('Hello world from actor!');+ * });+ * ```+ *+ * If the user function returns a promise, it is considered asynchronous:+ * ```javascript+ * const { requestAsBrowser } = require('some-request-library');+ *+ * Apify.main(() => {+ * // My asynchronous function that returns a promise+ * return request('http://www.example.com').then((html) => {+ * console.log(html);+ * });+ * });+ * ```+ *+ * To simplify your code, you can take advantage of the `async`/`await` keywords:+ *+ * ```javascript+ * const request = require('some-request-library');+ *+ * Apify.main(async () => {+ * // My asynchronous function+ * const html = await request('http://www.example.com');+ * console.log(html);+ * });+ * ```+ *+ * @param {UserFunc} userFunc User function to be executed. If it returns a promise,+ * the promise will be awaited. The user function is called with no arguments.+ * @return {Promise<unknown>}+ */+ main(userFunc) {+ if (!userFunc || typeof (userFunc) !== 'function') {+ // eslint-disable-next-line max-len+ throw new Error(`Apify.main() accepts a single parameter that must be a function (was '${userFunc === null ? 'null' : typeof userFunc}').`);+ }++ // Logging some basic system info (apify and apify-client version, NodeJS version, ...).+ logSystemInfo();++ // Log warning if SDK is outdated.+ printOutdatedSdkWarning();++ // This is to enable unit tests where process.exit() is mocked and doesn't really exit the process+ // Note that mocked process.exit() might throw, so set exited flag before calling it to avoid confusion.+ let exited = false;+ const exitWithError = (err, exitCode) => {+ log.exception(err);+ exited = true;+ process.exit(exitCode);+ };++ // Set dummy interval to ensure the process will not be killed while awaiting empty promise:+ // await new Promise(() => {})+ // Such a construct is used for testing of actor timeouts and aborts.+ const intervalId = setInterval((i) => i, 9999999);++ // Using async here to have nice stack traces for errors+ try {+ initializeEvents(this.config);+ return (async () => {+ try {+ await userFunc();+ process.exit(EXIT_CODES.SUCCESS);+ } catch (err) {+ if (!exited) {+ exitWithError(err, EXIT_CODES.ERROR_USER_FUNCTION_THREW);+ }+ }+ })();+ } catch (err) {+ exitWithError(err, EXIT_CODES.ERROR_UNKNOWN);+ } finally {+ stopEvents();+ clearInterval(intervalId);+ }+ }++ /**+ * Runs an actor on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),+ * waits for the actor to finish and fetches its output.+ *+ * By passing the `waitSecs` option you can reduce the maximum amount of time to wait for the run to finish.+ * If the value is less than or equal to zero, the function returns immediately after the run is started.+ *+ * The result of the function is an {@link ActorRun} object+ * that contains details about the actor run and its output (if any).+ * If the actor run fails, the function throws the {@link ApifyCallError} exception.+ *+ * If you want to run an actor task rather than an actor, please use the+ * {@link Apify#callTask} function instead.+ *+ * For more information about actors, read the+ * [documentation](https://docs.apify.com/actor).+ *+ * **Example usage:**+ *+ * ```javascript+ * const run = await Apify.call('apify/hello-world', { myInput: 123 });+ * console.log(`Received message: ${run.output.body.message}`);+ * ```+ *+ * Internally, the `call()` function invokes the+ * [Run actor](https://apify.com/docs/api/v2#/reference/actors/run-collection/run-actor)+ * and several other API endpoints to obtain the output.+ *+ * @param {string} actId+ * Allowed formats are `username/actor-name`, `userId/actor-name` or actor ID.+ * @param {Object<string, *>} [input]+ * Input for the actor. If it is an object, it will be stringified to+ * JSON and its content type set to `application/json; charset=utf-8`.+ * Otherwise the `options.contentType` parameter must be provided.+ * @param {object} [options]+ * Object with the settings below:+ * @param {string} [options.contentType]+ * Content type for the `input`. If not specified,+ * `input` is expected to be an object that will be stringified to JSON and content type set to+ * `application/json; charset=utf-8`. If `options.contentType` is specified, then `input` must be a+ * `String` or `Buffer`.+ * @param {string} [options.token]+ * User API token that is used to run the actor. By default, it is taken from the `APIFY_TOKEN` environment variable.+ * @param {number} [options.memoryMbytes]+ * Memory in megabytes which will be allocated for the new actor run.+ * If not provided, the run uses memory of the default actor run configuration.+ * @param {number} [options.timeoutSecs]+ * Timeout for the actor run in seconds. Zero value means there is no timeout.+ * If not provided, the run uses timeout of the default actor run configuration.+ * @param {string} [options.build]+ * Tag or number of the actor build to run (e.g. `beta` or `1.2.345`).+ * If not provided, the run uses build tag or number from the default actor run configuration (typically `latest`).+ * @param {number} [options.waitSecs]+ * Maximum time to wait for the actor run to finish, in seconds.+ * If the limit is reached, the returned promise is resolved to a run object that will have+ * status `READY` or `RUNNING` and it will not contain the actor run output.+ * If `waitSecs` is null or undefined, the function waits for the actor to finish (default behavior).+ * @param {boolean} [options.fetchOutput=true]+ * If `false` then the function does not fetch output of the actor.+ * @param {boolean} [options.disableBodyParser=false]+ * If `true` then the function will not attempt to parse the+ * actor's output and will return it in a raw `Buffer`.+ * @param {Array<AdhocWebhook>} [options.webhooks] Specifies optional webhooks associated with the actor run, which can be used+ * to receive a notification e.g. when the actor finished or failed, see+ * [ad hook webhooks documentation](https://docs.apify.com/webhooks/ad-hoc-webhooks) for detailed description.+ * @returns {Promise<ActorRun>}+ * @throws {ApifyCallError} If the run did not succeed, e.g. if it failed or timed out.+ */+ async call(actId, input, options = {}) {+ ow(actId, ow.string);+ // input can be anything, no reason to validate+ ow(options, ow.object.exactShape({+ contentType: ow.optional.string.nonEmpty,+ token: ow.optional.string,+ memoryMbytes: ow.optional.number.not.negative,+ timeoutSecs: ow.optional.number.not.negative,+ build: ow.optional.string,+ waitSecs: ow.optional.number.not.negative,+ fetchOutput: ow.optional.boolean,+ disableBodyParser: ow.optional.boolean,+ webhooks: ow.optional.array.ofType(ow.object),+ }));++ const {+ token = this.config.get('token'),+ fetchOutput = true,+ disableBodyParser = false,+ memoryMbytes,+ timeoutSecs,+ ...callActorOpts+ } = options;++ callActorOpts.memory = memoryMbytes;+ callActorOpts.timeout = timeoutSecs;+ callActorOpts.token = token;++ if (input) {+ callActorOpts.contentType = addCharsetToContentType(callActorOpts.contentType);+ input = maybeStringify(input, callActorOpts);+ }++ const client = this.newClient({ token });++ let run;+ try {+ run = await client.actor(actId).call(input, callActorOpts);+ } catch (err) {+ if (err.message.startsWith('Waiting for run to finish')) {+ throw new ApifyCallError({ id: run.id, actId: run.actId }, 'Apify.call() failed, cannot fetch actor run details from the server');+ }+ throw err;+ }++ if (this._isRunUnsuccessful(run.status)) {+ const message = `The actor ${actId} invoked by Apify.call() did not succeed. For details, see https://my.apify.com/view/runs/${run.id}`;+ throw new ApifyCallError(run, message);+ }++ // Finish if output is not requested or run haven't finished.+ if (!fetchOutput || run.status !== ACT_JOB_STATUSES.SUCCEEDED) return run;++ // Fetch output.+ let getRecordOptions = {};+ if (disableBodyParser) getRecordOptions = { buffer: true };++ const { value: body, contentType } = await client.keyValueStore(run.defaultKeyValueStoreId).getRecord('OUTPUT', getRecordOptions);++ return { ...run, output: { contentType, body } };+ }++ /**+ * Runs an actor task on the Apify platform using the current user account (determined by the `APIFY_TOKEN` environment variable),+ * waits for the task to finish and fetches its output.+ *+ * By passing the `waitSecs` option you can reduce the maximum amount of time to wait for the run to finish.+ * If the value is less than or equal to zero, the function returns immediately after the run is started.+ *+ * The result of the function is an {@link ActorRun} object+ * that contains details about the actor run and its output (if any).+ * If the actor run failed, the function fails with {@link ApifyCallError} exception.+ *+ * Note that an actor task is a saved input configuration and options for an actor.+ * If you want to run an actor directly rather than an actor task, please use the+ * {@link Apify#call} function instead.+ *+ * For more information about actor tasks, read the [documentation](https://docs.apify.com/tasks).+ *+ * **Example usage:**+ *+ * ```javascript+ * const run = await Apify.callTask('bob/some-task');+ * console.log(`Received message: ${run.output.body.message}`);+ * ```+ *+ * Internally, the `callTask()` function calls the+ * [Run task](https://apify.com/docs/api/v2#/reference/actor-tasks/run-collection/run-task)+ * and several other API endpoints to obtain the output.+ *+ * @param {string} taskId+ * Allowed formats are `username/task-name`, `userId/task-name` or task ID.+ * @param {Object<string, *>} [input]+ * Input overrides for the actor task. If it is an object, it will be stringified to+ * JSON and its content type set to `application/json; charset=utf-8`.+ * Provided input will be merged with actor task input.+ * @param {object} [options]+ * Object with the settings below:+ * @param {string} [options.token]+ * User API token that is used to run the actor. By default, it is taken from the `APIFY_TOKEN` environment variable.+ * @param {number} [options.memoryMbytes]+ * Memory in megabytes which will be allocated for the new actor task run.+ * If not provided, the run uses memory of the default actor run configuration.+ * @param {number} [options.timeoutSecs]+ * Timeout for the actor task run in seconds. Zero value means there is no timeout.+ * If not provided, the run uses timeout of the default actor run configuration.+ * @param {string} [options.build]+ * Tag or number of the actor build to run (e.g. `beta` or `1.2.345`).+ * If not provided, the run uses build tag or number from the default actor run configuration (typically `latest`).+ * @param {number} [options.waitSecs]+ * Maximum time to wait for the actor task run to finish, in seconds.+ * If the limit is reached, the returned promise is resolved to a run object that will have+ * status `READY` or `RUNNING` and it will not contain the actor run output.+ * If `waitSecs` is null or undefined, the function waits for the actor task to finish (default behavior).+ * @param {Array<AdhocWebhook>} [options.webhooks] Specifies optional webhooks associated with the actor run, which can be used+ * to receive a notification e.g. when the actor finished or failed, see+ * [ad hook webhooks documentation](https://docs.apify.com/webhooks/ad-hoc-webhooks) for detailed description.+ * @returns {Promise<ActorRun>}+ * @throws {ApifyCallError} If the run did not succeed, e.g. if it failed or timed out.+ */+ async callTask(taskId, input, options = {}) {+ ow(taskId, ow.string);+ ow(input, ow.optional.any(ow.string, ow.object));+ ow(options, ow.object.exactShape({+ token: ow.optional.string,+ memoryMbytes: ow.optional.number.not.negative,+ timeoutSecs: ow.optional.number.not.negative,+ build: ow.optional.string,+ waitSecs: ow.optional.number.not.negative,+ fetchOutput: ow.optional.boolean,+ disableBodyParser: ow.optional.boolean,+ webhooks: ow.optional.array.ofType(ow.object),+ }));++ const {+ token = this.config.get('token'),+ fetchOutput = true,+ disableBodyParser = false,+ memoryMbytes,+ timeoutSecs,+ ...callTaskOpts+ } = options;++ callTaskOpts.memory = memoryMbytes;+ callTaskOpts.timeout = timeoutSecs;+ callTaskOpts.token = token;++ const client = this.newClient({ token });+ // Start task and wait for run to finish if waitSecs is provided+ let run;+ try {+ run = await client.task(taskId).call(input, callTaskOpts);+ } catch (err) {+ if (err.message.startsWith('Waiting for run to finish')) {+ throw new ApifyCallError({ id: run.id, actId: run.actId }, 'Apify.call() failed, cannot fetch actor run details from the server');+ }+ throw err;+ }++ if (this._isRunUnsuccessful(run.status)) {+ // eslint-disable-next-line max-len+ const message = `The actor task ${taskId} invoked by Apify.callTask() did not succeed. For details, see https://my.apify.com/view/runs/${run.id}`;+ throw new ApifyCallError(run, message);+ }++ // Finish if output is not requested or run haven't finished.+ if (!fetchOutput || run.status !== ACT_JOB_STATUSES.SUCCEEDED) return run;++ // Fetch output.+ let getRecordOptions = {};+ if (disableBodyParser) getRecordOptions = { buffer: true };++ const { value: body, contentType } = await client.keyValueStore(run.defaultKeyValueStoreId).getRecord('OUTPUT', getRecordOptions);++ return { ...run, output: { contentType, body } };+ }++ /**+ * Transforms this actor run to an actor run of a given actor. The system stops the current container and starts+ * the new container instead. All the default storages are preserved and the new input is stored under the `INPUT-METAMORPH-1` key+ * in the same default key-value store.+ *+ * @param {string} targetActorId+ * Either `username/actor-name` or actor ID of an actor to which we want to metamorph.+ * @param {Object<string, *>} [input]+ * Input for the actor. If it is an object, it will be stringified to+ * JSON and its content type set to `application/json; charset=utf-8`.+ * Otherwise the `options.contentType` parameter must be provided.+ * @param {object} [options]+ * Object with the settings below:+ * @param {string} [options.contentType]+ * Content type for the `input`. If not specified,+ * `input` is expected to be an object that will be stringified to JSON and content type set to+ * `application/json; charset=utf-8`. If `options.contentType` is specified, then `input` must be a+ * `String` or `Buffer`.+ * @param {string} [options.build]+ * Tag or number of the target actor build to metamorph into (e.g. `beta` or `1.2.345`).+ * If not provided, the run uses build tag or number from the default actor run configuration (typically `latest`).+ * @returns {Promise<void>}+ */+ async metamorph(targetActorId, input, options = {}) {+ ow(targetActorId, ow.string);+ // input can be anything, no reason to validate+ ow(options, ow.object.exactShape({+ contentType: ow.optional.string.nonEmpty,+ build: ow.optional.string,+ customAfterSleepMillis: ow.optional.number.not.negative,+ }));++ const {+ customAfterSleepMillis,+ ...metamorphOpts+ } = options;++ const actorId = this.config.get('actorId');+ const runId = this.config.get('actorRunId');+ if (!actorId) throw new Error(`Environment variable ${ENV_VARS.ACTOR_ID} must be provided!`);+ if (!runId) throw new Error(`Environment variable ${ENV_VARS.ACTOR_RUN_ID} must be provided!`);++ if (input) {+ metamorphOpts.contentType = addCharsetToContentType(metamorphOpts.contentType);+ input = maybeStringify(input, metamorphOpts);+ }++ await this.newClient().run(runId).metamorph(targetActorId, input, metamorphOpts);++ // Wait some time for container to be stopped.+ // NOTE: option.customAfterSleepMillis is used in tests+ await sleep(customAfterSleepMillis || this.config.get('metamorphAfterSleepMillis'));+ }++ /**+ * @typedef WebhookRun+ * @property {string} id+ * @property {string} createdAt+ * @property {string} modifiedAt+ * @property {string} userId+ * @property {boolean} isAdHoc+ * @property {EventTypes} eventTypes+ * @property {*} condition+ * @property {boolean} ignoreSslErrors+ * @property {boolean} doNotRetry+ * @property {string} requestUrl+ * @property {string} payloadTemplate+ * @property {*} lastDispatch+ * @property {*} stats+ */+ /**+ *+ * Creates an ad-hoc webhook for the current actor run, which lets you receive a notification when the actor run finished or failed.+ * For more information about Apify actor webhooks, please see the [documentation](https://docs.apify.com/webhooks).+ *+ * Note that webhooks are only supported for actors running on the Apify platform.+ * In local environment, the function will print a warning and have no effect.+ *+ * @param {object} options+ * @param {EventTypes} options.eventTypes+ * Array of event types, which you can set for actor run, see+ * the [actor run events](https://docs.apify.com/webhooks/events#actor-run) in the Apify doc.+ * @param {string} options.requestUrl+ * URL which will be requested using HTTP POST request, when actor run will reach the set event type.+ * @param {string} [options.payloadTemplate]+ * Payload template is a JSON-like string that describes the structure of the webhook POST request payload.+ * It uses JSON syntax, extended with a double curly braces syntax for injecting variables `{{variable}}`.+ * Those variables are resolved at the time of the webhook's dispatch, and a list of available variables with their descriptions+ * is available in the [Apify webhook documentation](https://docs.apify.com/webhooks).+ * If `payloadTemplate` is omitted, the default payload template is used+ * ([view docs](https://docs.apify.com/webhooks/actions#payload-template)).+ * @param {string} [options.idempotencyKey]+ * Idempotency key enables you to ensure that a webhook will not be added multiple times in case of+ * an actor restart or other situation that would cause the `addWebhook()` function to be called again.+ * We suggest using the actor run ID as the idempotency key. You can get the run ID by calling+ * {@link Apify#getEnv} function.+ * @return {Promise<WebhookRun|undefined>} The return value is the Webhook object.+ * For more information, see the [Get webhook](https://apify.com/docs/api/v2#/reference/webhooks/webhook-object/get-webhook) API endpoint.+ */+ async addWebhook(options) {+ ow(options, ow.object.exactShape({+ eventTypes: ow.array.ofType(ow.string),+ requestUrl: ow.string,+ payloadTemplate: ow.optional.string,+ idempotencyKey: ow.optional.string,+ }));++ const { eventTypes, requestUrl, payloadTemplate, idempotencyKey } = options;++ if (!this.isAtHome()) {+ log.warning('Apify.addWebhook() is only supported when running on the Apify platform. The webhook will not be invoked.');+ return;+ }++ const runId = this.config.get('actorRunId');+ if (!runId) {+ throw new Error(`Environment variable ${ENV_VARS.ACTOR_RUN_ID} is not set!`);+ }++ return this.newClient().webhooks().create({+ isAdHoc: true,+ eventTypes,+ condition: {+ actorRunId: runId,+ },+ requestUrl,+ payloadTemplate,+ idempotencyKey,+ });+ }++ /**+ * Stores an object or an array of objects to the default {@link Dataset} of the current actor run.+ *+ * This is just a convenient shortcut for {@link Dataset#pushData}.+ * For example, calling the following code:+ * ```javascript+ * await Apify.pushData({ myValue: 123 });+ * ```+ *+ * is equivalent to:+ * ```javascript+ * const dataset = await Apify.openDataset();+ * await dataset.pushData({ myValue: 123 });+ * ```+ *+ * For more information, see {@link Apify#openDataset} and {@link Dataset#pushData}+ *+ * **IMPORTANT**: Make sure to use the `await` keyword when calling `pushData()`,+ * otherwise the actor process might finish before the data are stored!+ *+ * @param {object} item Object or array of objects containing data to be stored in the default dataset.+ * The objects must be serializable to JSON and the JSON representation of each object must be smaller than 9MB.+ * @returns {Promise<void>}+ */+ async pushData(item) {+ const dataset = await this.openDataset();+ return dataset.pushData(item);+ }++ /**+ * Opens a dataset and returns a promise resolving to an instance of the {@link Dataset} class.+ *+ * Datasets are used to store structured data where each object stored has the same attributes,+ * such as online store products or real estate offers.+ * The actual data is stored either on the local filesystem or in the cloud.+ *+ * For more details and code examples, see the {@link Dataset} class.+ *+ * @param {string} [datasetIdOrName]+ * ID or name of the dataset to be opened. If `null` or `undefined`,+ * the function returns the default dataset associated with the actor run.+ * @param {Object} [options]+ * @param {boolean} [options.forceCloud=false]+ * If set to `true` then the function uses cloud storage usage even if the `APIFY_LOCAL_STORAGE_DIR`+ * environment variable is set. This way it is possible to combine local and cloud storage.+ * @returns {Promise<Dataset>}+ */+ async openDataset(datasetIdOrName, options = {}) {+ ow(datasetIdOrName, ow.optional.string);+ ow(options, ow.object.exactShape({+ forceCloud: ow.optional.boolean,+ }));++ return this._getStorageManager(Dataset).openStorage(datasetIdOrName, options);+ }++ /**+ * Gets a value from the default {@link KeyValueStore} associated with the current actor run.+ *+ * This is just a convenient shortcut for {@link KeyValueStore#getValue}.+ * For example, calling the following code:+ * ```javascript+ * const value = await Apify.getValue('my-key');+ * ```+ *+ * is equivalent to:+ * ```javascript+ * const store = await Apify.openKeyValueStore();+ * const value = await store.getValue('my-key');+ * ```+ *+ * To store the value to the default key-value store, you can use the {@link Apify#setValue} function.+ *+ * For more information, see {@link Apify#openKeyValueStore}+ * and {@link KeyValueStore#getValue}.+ *+ * @param {string} key+ * Unique record key.+ * @returns {Promise<Object<string, *>|string|Buffer|null>}+ * Returns a promise that resolves to an object, string+ * or [`Buffer`](https://nodejs.org/api/buffer.html), depending+ * on the MIME content type of the record, or `null`+ * if the record is missing.+ */+ async getValue(key) {+ const store = await this.openKeyValueStore();+ return store.getValue(key);+ }++ /**+ * Stores or deletes a value in the default {@link KeyValueStore} associated with the current actor run.+ *+ * This is just a convenient shortcut for {@link KeyValueStore#setValue}.+ * For example, calling the following code:+ * ```javascript+ * await Apify.setValue('OUTPUT', { foo: "bar" });+ * ```+ *+ * is equivalent to:+ * ```javascript+ * const store = await Apify.openKeyValueStore();+ * await store.setValue('OUTPUT', { foo: "bar" });+ * ```+ *+ * To get a value from the default key-value store, you can use the {@link Apify#getValue} function.+ *+ * For more information, see {@link Apify#openKeyValueStore}+ * and {@link KeyValueStore#getValue}.+ *+ * @param {string} key+ * Unique record key.+ * @param {*} value+ * Record data, which can be one of the following values:+ * - If `null`, the record in the key-value store is deleted.+ * - If no `options.contentType` is specified, `value` can be any JavaScript object and it will be stringified to JSON.+ * - If `options.contentType` is set, `value` is taken as is and it must be a `String` or [`Buffer`](https://nodejs.org/api/buffer.html).+ * For any other value an error will be thrown.+ * @param {object} [options]+ * @param {string} [options.contentType]+ * Specifies a custom MIME content type of the record.+ * @return {Promise<void>}+ */+ async setValue(key, value, options) {+ const store = await this.openKeyValueStore();+ return store.setValue(key, value, options);+ }++ /**+ * Gets the actor input value from the default {@link KeyValueStore} associated with the current actor run.+ *+ * This is just a convenient shortcut for [`keyValueStore.getValue('INPUT')`](key-value-store#getvalue).+ * For example, calling the following code:+ * ```javascript+ * const input = await Apify.getInput();+ * ```+ *+ * is equivalent to:+ * ```javascript+ * const store = await Apify.openKeyValueStore();+ * await store.getValue('INPUT');+ * ```+ *+ * Note that the `getInput()` function does not cache the value read from the key-value store.+ * If you need to use the input multiple times in your actor,+ * it is far more efficient to read it once and store it locally.+ *+ * For more information, see {@link Apify#openKeyValueStore}+ * and {@link KeyValueStore#getValue}.+ *+ * @returns {Promise<Object<string, *>|string|Buffer|null>}+ * Returns a promise that resolves to an object, string+ * or [`Buffer`](https://nodejs.org/api/buffer.html), depending+ * on the MIME content type of the record, or `null`+ * if the record is missing.+ */+ async getInput() {+ return this.getValue(this.config.get('inputKey'));+ }++ /**+ * Opens a key-value store and returns a promise resolving to an instance of the {@link KeyValueStore} class.+ *+ * Key-value stores are used to store records or files, along with their MIME content type.+ * The records are stored and retrieved using a unique key.+ * The actual data is stored either on a local filesystem or in the Apify cloud.+ *+ * For more details and code examples, see the {@link KeyValueStore} class.+ *+ * @param {string} [storeIdOrName]+ * ID or name of the key-value store to be opened. If `null` or `undefined`,+ * the function returns the default key-value store associated with the actor run.+ * @param {object} [options]+ * @param {boolean} [options.forceCloud=false]+ * If set to `true` then the function uses cloud storage usage even if the `APIFY_LOCAL_STORAGE_DIR`+ * environment variable is set. This way it is possible to combine local and cloud storage.+ * @returns {Promise<KeyValueStore>}+ */+ async openKeyValueStore(storeIdOrName, options = {}) {+ ow(storeIdOrName, ow.optional.string);+ ow(options, ow.object.exactShape({+ forceCloud: ow.optional.boolean,+ }));++ return this._getStorageManager(KeyValueStore).openStorage(storeIdOrName, options);+ }++ /**+ * Opens a request list and returns a promise resolving to an instance+ * of the {@link RequestList} class that is already initialized.+ *+ * {@link RequestList} represents a list of URLs to crawl, which is always stored in memory.+ * To enable picking up where left off after a process restart, the request list sources+ * are persisted to the key-value store at initialization of the list. Then, while crawling,+ * a small state object is regularly persisted to keep track of the crawling status.+ *+ * For more details and code examples, see the {@link RequestList} class.+ *+ * **Example usage:**+ *+ * ```javascript+ * const sources = [+ * 'https://www.example.com',+ * 'https://www.google.com',+ * 'https://www.bing.com'+ * ];+ *+ * const requestList = await Apify.openRequestList('my-name', sources);+ * ```+ *+ * @param {string|null} listName+ * Name of the request list to be opened. Setting a name enables the `RequestList`'s state to be persisted+ * in the key-value store. This is useful in case of a restart or migration. Since `RequestList` is only+ * stored in memory, a restart or migration wipes it clean. Setting a name will enable the `RequestList`'s+ * state to survive those situations and continue where it left off.+ *+ * The name will be used as a prefix in key-value store, producing keys such as `NAME-REQUEST_LIST_STATE`+ * and `NAME-REQUEST_LIST_SOURCES`.+ *+ * If `null`, the list will not be persisted and will only be stored in memory. Process restart+ * will then cause the list to be crawled again from the beginning. We suggest always using a name.+ * @param {Array<RequestOptions|Request|string>} sources+ * An array of sources of URLs for the {@link RequestList}. It can be either an array of strings,+ * plain objects that define at least the `url` property, or an array of {@link Request} instances.+ *+ * **IMPORTANT:** The `sources` array will be consumed (left empty) after {@link RequestList} initializes.+ * This is a measure to prevent memory leaks in situations when millions of sources are+ * added.+ *+ * Additionally, the `requestsFromUrl` property may be used instead of `url`,+ * which will instruct {@link RequestList} to download the source URLs from a given remote location.+ * The URLs will be parsed from the received response. In this case you can limit the URLs+ * using `regex` parameter containing regular expression pattern for URLs to be included.+ *+ * For details, see the {@link RequestListOptions.sources}+ * @param {RequestListOptions} [options]+ * The {@link RequestList} options. Note that the `listName` parameter supersedes+ * the {@link RequestListOptions.persistStateKey} and {@link RequestListOptions.persistRequestsKey}+ * options and the `sources` parameter supersedes the {@link RequestListOptions.sources} option.+ * @returns {Promise<RequestList>}+ */+ async openRequestList(listName, sources, options = {}) {+ ow(listName, ow.any(ow.string, ow.null));+ ow(sources, ow.array);+ ow(options, ow.object.is((v) => !Array.isArray(v)));++ const rl = new RequestList({+ ...options,+ persistStateKey: listName ? `${listName}-${STATE_PERSISTENCE_KEY}` : undefined,+ persistRequestsKey: listName ? `${listName}-${REQUESTS_PERSISTENCE_KEY}` : undefined,+ sources,+ });+ await rl.initialize();++ return rl;+ }++ /**+ * Opens a request queue and returns a promise resolving to an instance+ * of the {@link RequestQueue} class.+ *+ * {@link RequestQueue} represents a queue of URLs to crawl, which is stored either on local filesystem or in the cloud.+ * The queue is used for deep crawling of websites, where you start with several URLs and then+ * recursively follow links to other pages. The data structure supports both breadth-first+ * and depth-first crawling orders.+ *+ * For more details and code examples, see the {@link RequestQueue} class.+ *+ * @param {string} [queueIdOrName]+ * ID or name of the request queue to be opened. If `null` or `undefined`,+ * the function returns the default request queue associated with the actor run.+ * @param {object} [options]+ * @param {boolean} [options.forceCloud=false]+ * If set to `true` then the function uses cloud storage usage even if the `APIFY_LOCAL_STORAGE_DIR`+ * environment variable is set. This way it is possible to combine local and cloud storage.+ * @returns {Promise<RequestQueue>}+ */+ async openRequestQueue(queueIdOrName, options = {}) {+ ow(queueIdOrName, ow.optional.string);+ ow(options, ow.object.exactShape({+ forceCloud: ow.optional.boolean,+ }));++ return this._getStorageManager(RequestQueue).openStorage(queueIdOrName, options);+ }++ /**+ * Opens a SessionPool and returns a promise resolving to an instance+ * of the {@link SessionPool} class that is already initialized.+ *+ * For more details and code examples, see the {@link SessionPool} class.+ *+ * @param {SessionPoolOptions} sessionPoolOptions+ * @return {Promise<SessionPool>}+ */+ async openSessionPool(sessionPoolOptions) {+ const sessionPool = new SessionPool(sessionPoolOptions);+ await sessionPool.initialize();++ return sessionPool;+ }++ /**+ * Creates a proxy configuration and returns a promise resolving to an instance+ * of the {@link ProxyConfiguration} class that is already initialized.+ *+ * Configures connection to a proxy server with the provided options. Proxy servers are used to prevent target websites from blocking+ * your crawlers based on IP address rate limits or blacklists. Setting proxy configuration in your crawlers automatically configures+ * them to use the selected proxies for all connections.+ *+ * For more details and code examples, see the {@link ProxyConfiguration} class.+ *+ * ```javascript+ *+ * // Returns initialized proxy configuration class+ * const proxyConfiguration = await Apify.createProxyConfiguration({+ * groups: ['GROUP1', 'GROUP2'] // List of Apify proxy groups+ * countryCode: 'US'+ * });+ *+ * const crawler = new Apify.CheerioCrawler({+ * // ...+ * proxyConfiguration,+ * handlePageFunction: ({ proxyInfo }) => {+ * const usedProxyUrl = proxyInfo.url; // Getting the proxy URL+ * }+ * })+ *+ * ```+ *+ * For compatibility with existing Actor Input UI (Input Schema), this function+ * returns `undefined` when the following object is passed as `proxyConfigurationOptions`.+ *+ * ```+ * { useApifyProxy: false }+ * ```+ *+ * @param {ProxyConfigurationOptions} [proxyConfigurationOptions]+ * @returns {Promise<ProxyConfiguration|undefined>}+ */+ async createProxyConfiguration(proxyConfigurationOptions = {}) {+ // Compatibility fix for Input UI where proxy: None returns { useApifyProxy: false }+ // Without this, it would cause proxy to use the zero config / auto mode.+ const dontUseApifyProxy = proxyConfigurationOptions.useApifyProxy === false;+ const dontUseCustomProxies = !proxyConfigurationOptions.proxyUrls;++ if (dontUseApifyProxy && dontUseCustomProxies) {+ return;+ }++ const proxyConfiguration = new ProxyConfiguration(proxyConfigurationOptions, this.config);+ await proxyConfiguration.initialize();++ return proxyConfiguration;+ }++ /**+ * Returns a new {@link ApifyEnv} object which contains information parsed from all the `APIFY_XXX` environment variables.+ *+ * For the list of the `APIFY_XXX` environment variables, see+ * [Actor documentation](https://docs.apify.com/actor/run#environment-variables).+ * If some of the variables are not defined or are invalid, the corresponding value in the resulting object will be null.+ * @returns {ApifyEnv}+ */+ getEnv() {+ return getEnv();+ }++ /**+ * Returns a new instance of the Apify API client. The `ApifyClient` class is provided+ * by the <a href="https://www.npmjs.com/package/apify-client" target="_blank">apify-client</a>+ * NPM package, and it is automatically configured using the `APIFY_API_BASE_URL`, and `APIFY_TOKEN`+ * environment variables. You can override the token via the available options. That's useful+ * if you want to use the client as a different Apify user than the SDK internals are using.+ *+ * @param {object} [options]+ * @param {string} [options.token]+ * @param {string} [options.maxRetries]+ * @param {string} [options.minDelayBetweenRetriesMillis]+ * @return {ApifyClient}+ */+ newClient(options = {}) {+ return this.config.createClient(options);+ }++ /**+ * Returns `true` when code is running on Apify platform and `false` otherwise (for example locally).+ *+ * @returns {boolean}+ */+ isAtHome() {+ return !!this.config.get('isAtHome');+ }++ get utils() {+ return {+ ...publicUtils,+ puppeteer: puppeteerUtils,+ playwright: playwrightUtils,+ social: socialUtils,+ log,+ enqueueLinks,+ requestAsBrowser,+ };+ }++ /**+ * @param {Function} storageClass+ * @return {StorageManager}+ * @private+ */+ _getStorageManager(storageClass) {+ if (!this._storageManagers.has(storageClass)) {+ const manager = new StorageManager(storageClass, this.config);+ this._storageManagers.set(storageClass, manager);+ }++ return this._storageManagers.get(storageClass);+ }++ /**+ * @param {ACT_JOB_STATUSES} status+ * @return {boolean}+ * @private+ */+ _isRunUnsuccessful(status) {+ return status !== ACT_JOB_STATUSES.SUCCEEDED+ && status !== ACT_JOB_STATUSES.RUNNING+ && status !== ACT_JOB_STATUSES.READY;+ }+}diff --git a/src/configuration.js b/src/configuration.jsnew file mode 100644index 000000000..1933fb12e--- /dev/null+++ b/src/configuration.js@@ -0,0 +1,311 @@+import { ENV_VARS, LOCAL_ENV_VARS } from 'apify-shared/consts';+import { join } from 'path';+import { ApifyStorageLocal } from '@apify/storage-local';+import * as ApifyClient from 'apify-client';+import log from './utils_log';++/**+ * `Configuration` is a value object holding the SDK configuration. We can use it in two ways:+ *+ * 1. When using `Apify` class, we can get the instance configuration via `sdk.config`+ * ```js+ * const { Apify } = require('apify');+ *+ * const sdk = new Apify({ token: '123' });+ * console.log(sdk.config.get('token')); // '123'+ * ```+ * 2. To get the global configuration (singleton instance). It will respect the environment variables.+ * ```js+ * console.log(Configuration.getGlobalConfig().get('token')); // returns the token from APIFY_TOKEN env var+ * ```+ *+ * ## Supported Configuration Options+ *+ * Key | Environment Variable | Default Value+ * ---|---|---+ * `defaultDatasetId` | `APIFY_DEFAULT_DATASET_ID` | `'default'`+ * `defaultKeyValueStoreId` | `APIFY_DEFAULT_KEY_VALUE_STORE_ID` | `'default'`+ * `defaultRequestQueueId` | `APIFY_DEFAULT_REQUEST_QUEUE_ID` | `'default'`+ * `localStorageDir` | `APIFY_LOCAL_STORAGE_DIR` | `'./apify_storage'`+ * `localStorageEnableWalMode` | `APIFY_LOCAL_STORAGE_ENABLE_WAL_MODE` | `true`+ * `persistStateIntervalMillis` | `APIFY_PERSIST_STATE_INTERVAL_MILLIS` | `60e3`+ * `token` | `APIFY_TOKEN` | -+ *+ * ## Advanced Configuration Options+ *+ * Key | Environment Variable | Default Value+ * ---|---|---+ * `actorEventsWsUrl` | `APIFY_ACTOR_EVENTS_WS_URL` | -+ * `actorId` | `APIFY_ACTOR_ID` | -+ * `actorRunId` | `APIFY_ACTOR_RUN_ID` | -+ * `actorTaskId` | `APIFY_ACTOR_TASK_ID` | -+ * `apiBaseUrl` | `APIFY_API_BASE_URL` | `'https://api.apify.com/v2'`+ * `containerPort` | `APIFY_CONTAINER_PORT` | `4321`+ * `containerUrl` | `APIFY_CONTAINER_URL` | `'http://localhost:4321'`+ * `inputKey` | `APIFY_INPUT_KEY` | `'INPUT'`+ * `isAtHome` | `APIFY_IS_AT_HOME` | -+ * `metamorphAfterSleepMillis` | `APIFY_METAMORPH_AFTER_SLEEP_MILLIS` | `300e3`+ * `proxyHostname` | `APIFY_PROXY_HOSTNAME` | `'proxy.apify.com'`+ * `proxyPassword` | `APIFY_PROXY_PASSWORD` | -+ * `proxyPort` | `APIFY_PROXY_PORT` | `8000`+ * `proxyStatusUrl` | `APIFY_PROXY_STATUS_URL` | `'http://proxy.apify.com'`+ * `userId` | `APIFY_USER_ID` | -+ *+ * ## Not Supported environment variables+ *+ * - `MEMORY_MBYTES`+ * - `HEADLESS`+ * - `XVFB`+ * - `CHROME_EXECUTABLE_PATH`+ */+export class Configuration {+ // maps environment variables to config keys (e.g. `APIFY_PROXY_PORT` to `proxyPort`)+ static ENV_MAP = {+ APIFY_TOKEN: 'token',+ APIFY_LOCAL_STORAGE_DIR: 'localStorageDir',+ APIFY_LOCAL_STORAGE_ENABLE_WAL_MODE: 'localStorageEnableWalMode',+ APIFY_DEFAULT_DATASET_ID: 'defaultDatasetId',+ APIFY_DEFAULT_KEY_VALUE_STORE_ID: 'defaultKeyValueStoreId',+ APIFY_DEFAULT_REQUEST_QUEUE_ID: 'defaultRequestQueueId',+ APIFY_METAMORPH_AFTER_SLEEP_MILLIS: 'metamorphAfterSleepMillis',+ APIFY_PERSIST_STATE_INTERVAL_MILLIS: 'persistStateIntervalMillis',+ APIFY_TEST_PERSIST_INTERVAL_MILLIS: 'persistStateIntervalMillis', // for BC, seems to be unused+ APIFY_ACTOR_EVENTS_WS_URL: 'actorEventsWsUrl',+ APIFY_INPUT_KEY: 'inputKey',+ APIFY_ACTOR_ID: 'actorId',+ APIFY_API_BASE_URL: 'apiBaseUrl',+ APIFY_IS_AT_HOME: 'isAtHome',+ APIFY_ACTOR_RUN_ID: 'actorRunId',+ APIFY_ACTOR_TASK_ID: 'actorTaskId',+ APIFY_CONTAINER_PORT: 'containerPort',+ APIFY_CONTAINER_URL: 'containerUrl',+ APIFY_USER_ID: 'userId',+ APIFY_PROXY_HOSTNAME: 'proxyHostname',+ APIFY_PROXY_PASSWORD: 'proxyPassword',+ APIFY_PROXY_STATUS_URL: 'proxyStatusUrl',+ APIFY_PROXY_PORT: 'proxyPort',++ // not supported, use env vars directly:+ // APIFY_MEMORY_MBYTES: 'memoryMbytes',+ // APIFY_HEADLESS: 'headless',+ // APIFY_XVFB: 'xvfb',+ // APIFY_CHROME_EXECUTABLE_PATH: 'chromeExecutablePath',+ };++ // maps config keys to environment variables (e.g. `proxyPort` to `APIFY_PROXY_PORT`)+ static ENV_MAP_REVERSED = Object.entries(Configuration.ENV_MAP).reduce((obj, [key, value]) => {+ obj[value] = key;+ return obj;+ }, {});++ static BOOLEAN_VARS = ['localStorageEnableWalMode'];++ static INTEGER_VARS = ['proxyPort', 'memoryMbytes', 'containerPort'];++ static DEFAULTS = {+ defaultKeyValueStoreId: LOCAL_ENV_VARS[ENV_VARS.DEFAULT_KEY_VALUE_STORE_ID],+ defaultDatasetId: LOCAL_ENV_VARS[ENV_VARS.DEFAULT_DATASET_ID],+ defaultRequestQueueId: LOCAL_ENV_VARS[ENV_VARS.DEFAULT_REQUEST_QUEUE_ID],+ inputKey: 'INPUT',+ apiBaseUrl: 'https://api.apify.com/v2',+ proxyStatusUrl: 'http://proxy.apify.com',+ proxyHostname: LOCAL_ENV_VARS[ENV_VARS.PROXY_HOSTNAME],+ proxyPort: +LOCAL_ENV_VARS[ENV_VARS.PROXY_PORT],+ containerPort: +LOCAL_ENV_VARS[ENV_VARS.CONTAINER_PORT],+ containerUrl: LOCAL_ENV_VARS[ENV_VARS.CONTAINER_URL],+ metamorphAfterSleepMillis: 300e3,+ persistStateIntervalMillis: 60e3, // This value is mentioned in jsdoc in `events.js`, if you update it here, update it there too.+ localStorageEnableWalMode: true,+ };++ /**+ * Creates new `Configuration` instance with provided options. Env vars will have precedence over those.+ *+ * @param {Record<string, number | string | boolean>} options+ */+ constructor(options = {}) {+ this.options = new Map(Object.entries(options));+ this.services = new Map();++ if (!this.get('localStorageDir') && !this.get('token')) {+ const dir = join(process.cwd(), './apify_storage');+ this.set('localStorageDir', dir);+ // eslint-disable-next-line max-len+ log.warning(`Neither ${ENV_VARS.LOCAL_STORAGE_DIR} nor ${ENV_VARS.TOKEN} environment variable is set, defaulting to ${ENV_VARS.LOCAL_STORAGE_DIR}="${dir}"`);+ }+ }++ /**+ * Returns configured value. First checks the environment variables, then provided configuration,+ * fallbacks to the `defaultValue` argument if provided, otherwise uses the default value as described+ * in the above section.+ *+ * @param {string} key+ * @param {string | number | boolean} [defaultValue]+ * @return {string | number | boolean}+ */+ get(key, defaultValue) {+ // prefer env vars+ const envKey = Configuration.ENV_MAP_REVERSED[key] ?? key;+ const envValue = process.env[envKey];++ if (envValue != null) {+ return this._castEnvValue(key, envValue);+ }++ // check instance level options+ if (this.options.has(key)) {+ return this.options.get(key);+ }++ // fallback to defaults+ return defaultValue ?? Configuration.DEFAULTS[key] ?? envValue;+ }++ /**+ * @param {string} key+ * @param {number | string | boolean} value+ * @return {boolean}+ * @private+ */+ _castEnvValue(key, value) {+ if (key in Configuration.INTEGER_VARS) {+ return +value;+ }++ if (key in Configuration.BOOLEAN_VARS) {+ // 0, false and empty string are considered falsy values+ return !['0', 'false', ''].includes(value.toLowerCase());+ }++ return value;+ }++ /**+ * Sets value for given option. Only affects this `Configuration` instance, the value will not be propagated down to the env var.+ * To reset a value, we can omit the `value` argument or pass `undefined` there.+ *+ * @param {string} key+ * @param {string | number | boolean} [value]+ */+ set(key, value) {+ this.options.set(key, value);+ }++ /**+ * Returns cached instance of {@link ApifyClient} using options as defined in the environment variables or in+ * this {@link Configuration} instance. Only first call of this method will create the client, following calls will+ * return the same client instance.+ *+ * Caching works based on the API URL and token, so calling this method with different options will return+ * multiple instances, one for each variant of the options.+ *+ * @param {object} [options]+ * @param {string} [options.token]+ * @param {string} [options.maxRetries]+ * @param {string} [options.minDelayBetweenRetriesMillis]+ * @return {ApifyClient}+ * @internal+ */+ getClient(options = {}) {+ const baseUrl = options.baseUrl ?? this.get('apiBaseUrl');+ const token = options.token ?? this.get('token');+ const cacheKey = `${baseUrl}~${token}`;++ return this._getService('ApifyClient', () => this.createClient(options), cacheKey);+ }++ /**+ * Returns cached instance of {@link ApifyStorageLocal} using options as defined in the environment variables or in+ * this {@link Configuration} instance. Only first call of this method will create the client, following calls will return+ * the same client instance.+ *+ * Caching works based on the `storageDir` option, so calling this method with different `storageDir` will return+ * multiple instances, one for each directory.+ *+ * @param {object} [options]+ * @param {string} [options.storageDir]+ * @param {boolean} [options.enableWalMode=true]+ * @return {ApifyStorageLocal}+ * @internal+ */+ getStorageLocal(options = {}) {+ const cacheKey = options.storageDir ?? this.get('localStorageDir');+ return this._getService('ApifyStorageLocal', () => this.createStorageLocal(options), cacheKey);+ }++ /**+ * Returns cached (singleton) instance of a service by its name. If the service does not exist yet, it will be created+ * via the `createCallback`. To have multiple instances of one service, we can use unique values in the `cacheKey`.+ *+ * @param {string} name+ * @param {Function} createCallback+ * @param {string} [cacheKey]+ * @return {unknown}+ * @private+ */+ _getService(name, createCallback, cacheKey = name) {+ cacheKey = `${name}~${cacheKey}`;++ if (!this.services.has(cacheKey)) {+ this.services.set(cacheKey, createCallback());+ }++ return this.services.get(cacheKey);+ }++ /**+ * Creates an instance of ApifyClient using options as defined in the environment variables or in this `Configuration` instance.+ *+ * @param {object} [options]+ * @param {string} [options.token]+ * @param {string} [options.maxRetries]+ * @param {string} [options.minDelayBetweenRetriesMillis]+ * @return {ApifyClient}+ * @internal+ */+ createClient(options = {}) {+ return new ApifyClient({+ baseUrl: this.get('apiBaseUrl'),+ token: this.get('token'),+ ...options, // allow overriding the instance configuration+ });+ }++ /**+ * Creates an instance of ApifyStorageLocal using options as defined in the environment variables or in this `Configuration` instance.+ *+ * @param {object} [options]+ * @param {string} [options.storageDir]+ * @param {boolean} [options.enableWalMode=true]+ * @return {ApifyStorageLocal}+ * @internal+ */+ createStorageLocal(options = {}) {+ const storageDir = options.storageDir ?? this.get('localStorageDir');+ const enableWalMode = options.enableWalMode ?? this.get('localStorageEnableWalMode');+ const storage = new ApifyStorageLocal({ ...options, storageDir, enableWalMode });++ process.on('exit', () => {+ // TODO this is not public API, need to update+ // storage local with some teardown+ storage.dbConnections.closeAllConnections();+ });++ return storage;+ }++ /**+ * Returns the global configuration instance. It will respect the environment variables.+ * As opposed to this method, we can also get the SDK instance configuration via `sdk.config` property.+ *+ * @return {Configuration}+ */+ static getGlobalConfig() {+ if (!Configuration.globalConfig) {+ Configuration.globalConfig = new Configuration();+ }++ return Configuration.globalConfig;+ }+}diff --git a/src/constants.js b/src/constants.jsindex 3cbb89191..a20f3e3d4 100644--- a/src/constants.js+++ b/src/constants.js@@ -25,12 +25,6 @@ export const EXIT_CODES = {*/export const ACTOR_EVENT_NAMES_EX = { ...ACTOR_EVENT_NAMES, PERSIST_STATE: 'persistState' };-/**- * Base URL of Apify's API endpoints.- * @type {string}- */-export const APIFY_API_BASE_URL = 'https://api.apify.com/v2';-/*** Additional number of seconds used in CheerioCrawler and BrowserCrawler to set a reasonable* handleRequestTimeoutSecs for BasicCrawler that would not impare functionality (not timeout before crawlers).diff --git a/src/crawlers/basic_crawler.js b/src/crawlers/basic_crawler.jsindex 79b7cf215..ada947d5d 100644--- a/src/crawlers/basic_crawler.js+++ b/src/crawlers/basic_crawler.js@@ -193,7 +193,7 @@ const SAFE_MIGRATION_WAIT_MILLIS = 20000;* to pause the crawler by calling {@link AutoscaledPool#pause}* or to abort it by calling {@link AutoscaledPool#abort}.*/-class BasicCrawler {+export class BasicCrawler {static optionsShape = {requestList: ow.optional.object.validate(validators.requestList),requestQueue: ow.optional.object.validate(validators.requestQueue),@@ -644,8 +644,6 @@ class BasicCrawler {}}-export default BasicCrawler;-/*** @callback HandleRequest* @param {HandleRequestInputs} inputs Arguments passed to this callback.diff --git a/src/crawlers/browser_crawler.js b/src/crawlers/browser_crawler.jsindex 70e39dfc7..d6f496f6f 100644--- a/src/crawlers/browser_crawler.js+++ b/src/crawlers/browser_crawler.js@@ -10,7 +10,7 @@ import {} from './crawler_utils';/* eslint-disable no-unused-vars,import/named,import/no-duplicates,import/order */-import BasicCrawler, { CrawlingContext } from './basic_crawler';+import { BasicCrawler, CrawlingContext } from './basic_crawler';import { HandleFailedRequest } from './basic_crawler';import { ProxyConfiguration, ProxyInfo } from '../proxy_configuration';import { Session } from '../session_pool/session';@@ -106,7 +106,7 @@ import { AutoscaledPoolOptions } from '../autoscaling/autoscaled_pool';* ```* Where the {@link Request} instance corresponds to the failed request, and the `Error` instance* represents the last error thrown during processing of the request.-* @property {BrowserPoolOptions} [browserPoolOptions]+ * @property {BrowserPoolOptions} [browserPoolOptions]* Custom options passed to the underlying [`BrowserPool`](https://github.com/apify/browser-pool#BrowserPool) constructor.* You can tweak those to fine-tune browser management.* @property {boolean} [persistCookiesPerSession=true]@@ -253,7 +253,7 @@ import { AutoscaledPoolOptions } from '../autoscaling/autoscaled_pool';* or to abort it by calling {@link AutoscaledPool#abort}.* @ignore*/-class BrowserCrawler extends BasicCrawler {+export default class BrowserCrawler extends BasicCrawler {static optionsShape = {...BasicCrawler.optionsShape,// TODO temporary until the API is unified in V2@@ -276,9 +276,9 @@ class BrowserCrawler extends BasicCrawler {};/**- * @param {BrowserCrawlerOptions} options- * All `BrowserCrawler` parameters are passed via an options object.- */+ * @param {BrowserCrawlerOptions} options+ * All `BrowserCrawler` parameters are passed via an options object.+ */constructor(options) {ow(options, 'BrowserCrawlerOptions', ow.object.exactShape(BrowserCrawler.optionsShape));const {@@ -551,13 +551,11 @@ class BrowserCrawler extends BasicCrawler {}/**- * Function for cleaning up after all request are processed.- * @ignore- */+ * Function for cleaning up after all request are processed.+ * @ignore+ */async teardown() {await this.browserPool.destroy();- super.teardown();+ await super.teardown();}}--export default BrowserCrawler;diff --git a/src/crawlers/cheerio_crawler.js b/src/crawlers/cheerio_crawler.jsindex f5f85351e..d0ade5057 100644--- a/src/crawlers/cheerio_crawler.js+++ b/src/crawlers/cheerio_crawler.js@@ -11,7 +11,7 @@ import { TimeoutError } from 'got-scraping';import { BASIC_CRAWLER_TIMEOUT_BUFFER_SECS } from '../constants';import { addTimeoutToPromise, parseContentTypeFromResponse } from '../utils';import * as utilsRequest from '../utils_request'; // eslint-disable-line import/no-duplicates-import BasicCrawler from './basic_crawler'; // eslint-disable-line import/no-duplicates+import { BasicCrawler } from './basic_crawler'; // eslint-disable-line import/no-duplicatesimport CrawlerExtension from './crawler_extension';// TYPE IMPORTSdiff --git a/src/events.js b/src/events.jsindex 25c70377d..759b22f55 100644--- a/src/events.js+++ b/src/events.js@@ -3,9 +3,7 @@ import * as WebSocket from 'ws';import { ENV_VARS, ACTOR_EVENT_NAMES } from 'apify-shared/consts';import { ACTOR_EVENT_NAMES_EX } from './constants';import defaultLog from './utils_log';--// NOTE: This value is mentioned below in docs, if you update it here, update it there too.-const PERSIST_STATE_INTERVAL_MILLIS = 60 * 1000;+import { Configuration } from './configuration';/*** Event emitter providing events from underlying Actor infrastructure and Apify package.@@ -81,21 +79,21 @@ const emitPersistStateEvent = (isMigrating = false) => {** @memberof module:Apify* @name initializeEvents+ * @param {Configuration} [config]* @function* @ignore*/-export const initializeEvents = () => {+export const initializeEvents = (config = Configuration.getGlobalConfig()) => {if (eventsWs) return;const log = defaultLog.child({ prefix: 'Events' });if (!persistStateInterval) {- // This is overridable only to enable unit testing.- const intervalMillis = process.env.APIFY_TEST_PERSIST_INTERVAL_MILLIS || PERSIST_STATE_INTERVAL_MILLIS;+ const intervalMillis = config.get('persistStateIntervalMillis');persistStateInterval = setInterval(() => emitPersistStateEvent(), intervalMillis);}- const eventsWsUrl = process.env[ENV_VARS.ACTOR_EVENTS_WS_URL];+ const eventsWsUrl = config.get('actorEventsWsUrl');// Locally there is no web socket to connect, so just print a log message.if (!eventsWsUrl) {diff --git a/src/live_view/live_view_server.js b/src/live_view/live_view_server.jsindex ea3ca13a5..a41a340b9 100644--- a/src/live_view/live_view_server.js+++ b/src/live_view/live_view_server.js@@ -49,6 +49,7 @@ const DEFAULT_SCREENSHOT_DIR_PATH = path.resolve(LOCAL_STORAGE_DIR, 'live_view')** When running locally, it is often best to use a headful browser for debugging, since it provides* a better view into the browser, including DevTools, but `LiveViewServer` works too.+ * @deprecated no longer supported, will be removed in 2.0* @ignore*/class LiveViewServer {diff --git a/src/main.js b/src/main.jsindex bfdc806d7..c9a489177 100644--- a/src/main.js+++ b/src/main.js@@ -1,8 +1,10 @@import { EventEmitter } from 'events';import log from './utils_log';import { main, getEnv, call, callTask, metamorph, addWebhook } from './actor';+import { Apify } from './apify';+import { Configuration } from './configuration';import AutoscaledPool from './autoscaling/autoscaled_pool';-import BasicCrawler from './crawlers/basic_crawler';+import { BasicCrawler } from './crawlers/basic_crawler';import CheerioCrawler from './crawlers/cheerio_crawler';import { pushData, openDataset } from './storages/dataset';import events, { initializeEvents, stopEvents } from './events';@@ -50,9 +52,48 @@ const exportedUtils = Object.assign(publicUtils, {* > [Apify platform](../guides/apify-platform) and require your scripts to be authenticated.* > See the [authentication guide](../guides/apify-platform#logging-into-apify-platform-from-apify-sdk) for instructions.*+ * ## `Apify` Class+ *+ * As opposed to those helper functions, there is an alternative approach using `Apify` class (a named export).+ * It has mostly the same API, but the methods on `Apify` instance will use the configuration provided in the constructor.+ * Environment variables will have precedence over this configuration.+ *+ * ```js+ * const { Apify } = require('apify'); // use named export to get the class+ *+ * const sdk = new Apify({ token: '123' });+ * console.log(sdk.config.get('token')); // '123'+ *+ * // the token will be passed to the `call` method automatically+ * const run = await sdk.call('apify/hello-world', { myInput: 123 });+ * console.log(`Received message: ${run.output.body.message}`);+ * ```+ *+ * Another example shows how the default dataset name can be changed:+ *+ * ```js+ * const { Apify } = require('apify'); // use named export to get the class+ *+ * const sdk = new Apify({ defaultDatasetId: 'custom-name' });+ * await sdk.pushData({ myValue: 123 });+ * ```+ *+ * is equivalent to:+ * ```js+ * const Apify = require('apify'); // use default export to get the helper functions+ *+ * const dataset = await Apify.openDataset('custom-name');+ * await dataset.pushData({ myValue: 123 });+ * ```+ *+ *+ * See {@link Configuration} for details about what can be configured and what are the default values.+ ** @module Apify*/export {+ Apify,+ Configuration,main,getEnv,call,diff --git a/src/proxy_configuration.js b/src/proxy_configuration.jsindex a9db0e42c..48ad1b0ee 100644--- a/src/proxy_configuration.js+++ b/src/proxy_configuration.js@@ -1,10 +1,11 @@-import { ENV_VARS, LOCAL_ENV_VARS } from 'apify-shared/consts';+import { ENV_VARS } from 'apify-shared/consts';import { APIFY_PROXY_VALUE_REGEX } from 'apify-shared/regexs';import ow from 'ow';import { COUNTRY_CODE_REGEX } from './constants';import { apifyClient } from './utils';import { requestAsBrowser } from './utils_request';import defaultLog from './utils_log';+import { Configuration } from './configuration';// CONSTANTSconst PROTOCOL = 'http';@@ -149,8 +150,9 @@ export class ProxyConfiguration {* Configuration of proxy.** @param {ProxyConfigurationOptions} [options] All `ProxyConfiguration` options.+ * @param {Configuration} [config]*/- constructor(options = {}) {+ constructor(options = {}, config = Configuration.getGlobalConfig()) {ow(options, ow.object.exactShape({groups: ow.optional.array.ofType(ow.string.matches(APIFY_PROXY_VALUE_REGEX)),apifyProxyGroups: ow.optional.array.ofType(ow.string.matches(APIFY_PROXY_VALUE_REGEX)),@@ -159,8 +161,6 @@ export class ProxyConfiguration {proxyUrls: ow.optional.array.nonEmpty.ofType(ow.string.url),password: ow.optional.string,newUrlFunction: ow.optional.function,- // This is not an actual param, but it's here for legacy purposes.- useApifyProxy: ow.optional.boolean,}));const {@@ -169,14 +169,14 @@ export class ProxyConfiguration {countryCode,apifyProxyCountry,proxyUrls,- password = process.env[ENV_VARS.PROXY_PASSWORD],+ password = config.get('proxyPassword'),newUrlFunction,} = options;const groupsToUse = groups.length ? groups : apifyProxyGroups;const countryCodeToUse = countryCode || apifyProxyCountry;- const hostname = process.env[ENV_VARS.PROXY_HOSTNAME] || LOCAL_ENV_VARS[ENV_VARS.PROXY_HOSTNAME];- const port = Number(process.env[ENV_VARS.PROXY_PORT] || LOCAL_ENV_VARS[ENV_VARS.PROXY_PORT]);+ const hostname = config.get('proxyHostname');+ const port = config.get('proxyPort');// Validationif (((proxyUrls || newUrlFunction) && ((groupsToUse.length) || countryCodeToUse))) {@@ -195,6 +195,7 @@ export class ProxyConfiguration {this.newUrlFunction = newUrlFunction;this.usesApifyProxy = !this.proxyUrls && !this.newUrlFunction;this.log = defaultLog.child({ prefix: 'ProxyConfiguration' });+ this.config = config;}/**@@ -308,15 +309,6 @@ export class ProxyConfiguration {return username;}- /**- * Returns Apify proxy status url.- * @return {string} the Apify proxy status url- * @ignore- */- _getApifyProxyStatusUrl() {- return process.env[ENV_VARS.PROXY_STATUS_URL] || `${PROTOCOL}://${LOCAL_ENV_VARS[ENV_VARS.PROXY_HOSTNAME]}`;- }-/*** Checks if Apify Token is provided in env* and gets the password via API and sets it to env@@ -326,7 +318,7 @@ export class ProxyConfiguration {* @internal*/async _setPasswordIfToken() {- const token = process.env[ENV_VARS.TOKEN] || LOCAL_ENV_VARS[ENV_VARS.TOKEN];+ const token = this.config.get('token');if (token) {const { proxy: { password } } = await apifyClient.user().get();if (this.password) {@@ -368,14 +360,14 @@ export class ProxyConfiguration {/*** Apify Proxy can be down for a second or a minute, but this should not crash processes.*- * @return {Promise<{ connected: boolean, connectionError: string }|undefined>}+ * @return {Promise<{ connected: boolean, connectionError: string } | undefined>}* @protected* @ignore* @internal*/async _fetchStatus() {const requestOpts = {- url: `${this._getApifyProxyStatusUrl()}/?format=json`,+ url: `${this.config.get('proxyStatusUrl')}/?format=json`,proxyUrl: this.newUrl(),json: true,timeoutSecs: CHECK_ACCESS_REQUEST_TIMEOUT_SECS,@@ -531,11 +523,12 @@ export class ProxyConfiguration {export const createProxyConfiguration = async (proxyConfigurationOptions = {}) => {// Compatibility fix for Input UI where proxy: None returns { useApifyProxy: false }// Without this, it would cause proxy to use the zero config / auto mode.- const dontUseApifyProxy = proxyConfigurationOptions.useApifyProxy === false;+ const { useApifyProxy, ...options } = proxyConfigurationOptions;+ const dontUseApifyProxy = useApifyProxy === false;const dontUseCustomProxies = !proxyConfigurationOptions.proxyUrls;if (dontUseApifyProxy && dontUseCustomProxies) return undefined;- const proxyConfiguration = new ProxyConfiguration(proxyConfigurationOptions);+ const proxyConfiguration = new ProxyConfiguration(options);await proxyConfiguration.initialize();return proxyConfiguration;diff --git a/src/request_list.js b/src/request_list.jsindex f7af09c37..9e7b0c1e6 100644--- a/src/request_list.js+++ b/src/request_list.js@@ -262,8 +262,7 @@ export class RequestList {this.reclaimed = {};this.persistStateKey = persistStateKey ? `SDK_${persistStateKey}` : persistStateKey;- this.persistRequestsKey = persistRequestsKey;- this.persistRequestsKey = this.persistRequestsKey ? `SDK_${persistRequestsKey}` : this.persistRequestsKey;+ this.persistRequestsKey = persistRequestsKey ? `SDK_${persistRequestsKey}` : persistRequestsKey;this.initialState = state;diff --git a/src/stealth/hiding_tricks.js b/src/stealth/hiding_tricks.jsindex 45e4c8578..ef9f81c69 100644--- a/src/stealth/hiding_tricks.js+++ b/src/stealth/hiding_tricks.js@@ -56,6 +56,7 @@ const emulateWebGL = () => {return getParameterOld(parameter);};} catch (err) {+ // eslint-disable-next-line no-consoleconsole.error('hiding_tricks: Could not emulate WebGL');}};diff --git a/src/stealth/stealth.js b/src/stealth/stealth.jsindex 6f0c67224..8a2f5d15a 100644--- a/src/stealth/stealth.js+++ b/src/stealth/stealth.js@@ -123,12 +123,14 @@ function applyStealthTricks(page, evaluationDebugMessage, options) {/* istanbul ignore next */const addFunctions = (functionsArr, errorMessagePrefix, debugMessage) => {+ // eslint-disable-next-line no-consoleconsole.log(debugMessage);// add functionsfor (const func of functionsArr) {try {eval(func)(); // eslint-disable-line} catch (e) {+ // eslint-disable-next-line no-consoleconsole.error(`${errorMessagePrefix}: Failed to apply stealth trick reason: ${e.message}`);}}diff --git a/src/storages/dataset.js b/src/storages/dataset.jsindex f5d1f2a00..3fd4fc39a 100644--- a/src/storages/dataset.js+++ b/src/storages/dataset.js@@ -1,7 +1,7 @@import ow from 'ow';import * as _ from 'underscore';import { MAX_PAYLOAD_SIZE_BYTES } from 'apify-shared/consts';-import StorageManager from './storage_manager';+import { StorageManager } from './storage_manager';import log from '../utils_log';/* eslint-disable no-unused-vars,import/named,import/no-duplicates,import/order */diff --git a/src/storages/key_value_store.js b/src/storages/key_value_store.jsindex b51c68d02..075e5ecea 100644--- a/src/storages/key_value_store.js+++ b/src/storages/key_value_store.js@@ -2,8 +2,7 @@ import { KEY_VALUE_STORE_KEY_REGEX } from 'apify-shared/regexs';import { ENV_VARS, KEY_VALUE_STORE_KEYS } from 'apify-shared/consts';import { jsonStringifyExtended } from 'apify-shared/utilities';import ow, { ArgumentError } from 'ow';-import { APIFY_API_BASE_URL } from '../constants';-import StorageManager from './storage_manager';+import { StorageManager } from './storage_manager';import log from '../utils_log';/* eslint-disable no-unused-vars,import/named,import/no-duplicates,import/order */@@ -11,6 +10,7 @@ import log from '../utils_log';import * as ApifyClient from 'apify-client';// @ts-ignoreimport { ApifyStorageLocal } from '@apify/storage-local';+import { Configuration } from '../configuration';/* eslint-enable no-unused-vars,import/named,import/no-duplicates,import/order *//**@@ -119,13 +119,15 @@ export class KeyValueStore {* @param {string} [options.name]* @param {ApifyClient|ApifyStorageLocal} options.client* @param {boolean} options.isLocal+ * @param {Configuration} [config]*/- constructor(options) {+ constructor(options, config = Configuration.getGlobalConfig()) {this.id = options.id;this.name = options.name;this.isLocal = options.isLocal;this.client = options.client.keyValueStore(this.id);this.log = log.child({ prefix: 'KeyValueStore' });+ this.config = config;}/**@@ -162,7 +164,7 @@ export class KeyValueStore {ow(key, ow.string.nonEmpty);// TODO: Perhaps we should add options.contentType or options.asBuffer/asString- // to enforce the representation of value+ // to enforce the representation of valueconst record = await this.client.getRecord(key);return record ? record.value : null;@@ -253,7 +255,7 @@ export class KeyValueStore {*/async drop() {await this.client.delete();- const manager = new StorageManager(KeyValueStore);+ const manager = new StorageManager(KeyValueStore, this.config);manager.closeStorage(this);}@@ -265,7 +267,7 @@ export class KeyValueStore {* @return {string}*/getPublicUrl(key) {- return `${APIFY_API_BASE_URL}/key-value-stores/${this.id}/records/${key}`;+ return `${this.config.get('apiBaseUrl')}/key-value-stores/${this.id}/records/${key}`;}/**@@ -292,7 +294,18 @@ export class KeyValueStore {* @param {string} [options.exclusiveStartKey] All keys up to this one (including) are skipped from the result.* @return {Promise<void>}*/- async forEachKey(iteratee, options = {}, index = 0) {+ async forEachKey(iteratee, options = {}) {+ return this._forEachKey(iteratee, options);+ }++ /**+ * @param {KeyConsumer} iteratee+ * @param {Record<string, any>} [options]+ * @param {number} [index=0]+ * @return {Promise<Promise<void> | undefined>}+ * @private+ */+ async _forEachKey(iteratee, options = {}, index = 0) {const { exclusiveStartKey } = options;ow(iteratee, ow.function);ow(options, ow.object.exactShape({@@ -305,7 +318,7 @@ export class KeyValueStore {await iteratee(item.key, index++, { size: item.size });}return isTruncated- ? this.forEachKey(iteratee, { exclusiveStartKey: nextExclusiveStartKey }, index)+ ? this._forEachKey(iteratee, { exclusiveStartKey: nextExclusiveStartKey }, index): undefined; // [].forEach() returns undefined.}}diff --git a/src/storages/request_queue.js b/src/storages/request_queue.jsindex ce7b34671..11fb62613 100644--- a/src/storages/request_queue.js+++ b/src/storages/request_queue.js@@ -4,7 +4,7 @@ import * as ListDictionary from 'apify-shared/list_dictionary';import { REQUEST_QUEUE_HEAD_MAX_LIMIT } from 'apify-shared/consts';import { cryptoRandomObjectId } from 'apify-shared/utilities';import ow from 'ow';-import StorageManager from './storage_manager';+import { StorageManager } from './storage_manager';import { sleep } from '../utils';import log from '../utils_log';diff --git a/src/storages/storage_manager.js b/src/storages/storage_manager.jsindex 6a7d5fcfa..08253dcb1 100644--- a/src/storages/storage_manager.js+++ b/src/storages/storage_manager.js@@ -1,66 +1,69 @@-import { ENV_VARS, LOCAL_ENV_VARS } from 'apify-shared/consts';-import cacheContainer from '../cache_container';-import * as utils from '../utils';+import { ENV_VARS } from 'apify-shared/consts';/* eslint-disable no-unused-vars,import/named,import/no-duplicates,import/order */// @ts-ignoreimport * as ApifyClient from 'apify-client';// @ts-ignoreimport { ApifyStorageLocal } from '@apify/storage-local';+import cacheContainer from '../cache_container';+import { Configuration } from '../configuration';/* eslint-enable no-unused-vars,import/named,import/no-duplicates,import/order */+const MAX_OPENED_STORAGES = 1000;+const DEFAULT_ID_ENV_VAR_NAMES = {Dataset: ENV_VARS.DEFAULT_DATASET_ID,KeyValueStore: ENV_VARS.DEFAULT_KEY_VALUE_STORE_ID,RequestQueue: ENV_VARS.DEFAULT_REQUEST_QUEUE_ID,};-const MAX_OPENED_STORAGES = 1000;+const DEFAULT_ID_CONFIG_KEYS = {+ Dataset: 'defaultDatasetId',+ KeyValueStore: 'defaultKeyValueStoreId',+ RequestQueue: 'defaultRequestQueueId',+};/**- * @template T* StorageManager takes care of opening remote or local storages.+ * @template T* @property {Function} StorageConstructor* @property {string} name* @property {LruCache} cache* @ignore*/-class StorageManager {+export class StorageManager {/*** @param {T} StorageConstructor+ * @param {Configuration} [config]*/- constructor(StorageConstructor) {+ constructor(StorageConstructor, config = Configuration.getGlobalConfig()) {this.StorageConstructor = StorageConstructor;this.name = StorageConstructor.name;this.cache = cacheContainer.openCache(this.name, MAX_OPENED_STORAGES);+ this.config = config;}/**- * @param {string} idOrName+ * @param {string} [idOrName]* @param {object} [options]* @param {boolean} [options.forceCloud]* @return {Promise<T>}*/async openStorage(idOrName, options = {}) {- if (!process.env[ENV_VARS.LOCAL_STORAGE_DIR] && !process.env[ENV_VARS.TOKEN]) {- throw new Error(`Cannot use ${this.name} as neither ${ENV_VARS.LOCAL_STORAGE_DIR} nor ${ENV_VARS.TOKEN}`- + ' environment variable is set. You need to set one these variables in order to enable data storage.');- }-- const isLocal = !!(process.env[ENV_VARS.LOCAL_STORAGE_DIR] && !options.forceCloud);+ const isLocal = !!(this.config.get('localStorageDir') && !options.forceCloud);if (!idOrName) {const defaultIdEnvVarName = DEFAULT_ID_ENV_VAR_NAMES[this.name];- idOrName = process.env[defaultIdEnvVarName];- if (!idOrName && isLocal) idOrName = LOCAL_ENV_VARS[defaultIdEnvVarName];+ const defaultIdConfigKey = DEFAULT_ID_CONFIG_KEYS[this.name];+ idOrName = this.config.get(defaultIdConfigKey);if (!idOrName) throw new Error(`The '${defaultIdEnvVarName}' environment variable is not defined.`);}const cacheKey = this._createCacheKey(idOrName, isLocal);-let storage = this.cache.get(cacheKey);+if (!storage) {- const client = isLocal ? utils.apifyStorageLocal : utils.apifyClient;+ const client = isLocal ? this.config.getStorageLocal() : this.config.getClient();const storageObject = await this._getOrCreateStorage(idOrName, this.name, client);storage = new this.StorageConstructor({id: storageObject.id,@@ -162,5 +165,3 @@ class StorageManager {}}}--export default StorageManager;diff --git a/src/utils.js b/src/utils.jsindex ca2781020..97fc7e7b3 100644--- a/src/utils.js+++ b/src/utils.js@@ -1,10 +1,9 @@import * as psTree from '@apify/ps-tree';// eslint-disable-next-line import/no-extraneous-dependencies-import { ApifyStorageLocal } from '@apify/storage-local';import { execSync } from 'child_process';import * as ApifyClient from 'apify-client';import { version as apifyClientVersion } from 'apify-client/package.json';-import { ACT_JOB_TERMINAL_STATUSES, ENV_VARS, LOCAL_ENV_VARS } from 'apify-shared/consts';+import { ACT_JOB_TERMINAL_STATUSES, ENV_VARS } from 'apify-shared/consts';import * as cheerio from 'cheerio';import * as contentTypeParser from 'content-type';import * as fs from 'fs';@@ -86,30 +85,6 @@ export const newClient = (options = {}) => {});};-/**- * Creates an instance of ApifyStorageLocal using options as defined in the environment variables.- * @param {object} [options]- * @return {ApifyStorageLocal}- */-export const newStorageLocal = (options = {}) => {- const {- storageDir = process.env[ENV_VARS.LOCAL_STORAGE_DIR] || LOCAL_ENV_VARS[ENV_VARS.LOCAL_STORAGE_DIR],- } = options;-- const storage = new ApifyStorageLocal({- ...options,- storageDir,- });-- process.on('exit', () => {- // TODO this is not public API, need to update- // storage local with some teardown- storage.dbConnections.closeAllConnections();- });-- return storage;-};-/*** Logs info about system, node version and apify package version.*/@@ -131,19 +106,6 @@ export const logSystemInfo = () => {*/export const apifyClient = newClient();-/**- * The default instance of the `ApifyStorageLocal` class.- * The instance is created automatically by the Apify SDK and it is configured using the- * `APIFY_LOCAL_STORAGE_DIR` environment variable.- *- * The instance is lazy loaded and used for local emulation of calls to the Apify API- * in Apify Storages such as {@link RequestQueue}.- *- * @type {*}- * @ignore- */-export const apifyStorageLocal = newStorageLocal();-/*** Adds charset=utf-8 to given content type if this parameter is missing.*diff --git a/test/apify.test.js b/test/apify.test.jsnew file mode 100644index 000000000..837a347e9--- /dev/null+++ b/test/apify.test.js@@ -0,0 +1,670 @@+import path from 'path';+import _ from 'underscore';+import { ACT_JOB_STATUSES, ENV_VARS, KEY_VALUE_STORE_KEYS } from 'apify-shared/consts';+import ApifyClient from 'apify-client';+import { ApifyCallError } from '../build/errors';+import * as utils from '../build/utils';+import { Dataset } from '../build/storages/dataset';+import { KeyValueStore } from '../build/storages/key_value_store';+import LocalStorageDirEmulator from './local_storage_dir_emulator';+import { StorageManager } from '../build/storages/storage_manager';+import { ProxyConfiguration } from '../build/proxy_configuration';+import { SessionPool } from '../build/session_pool/session_pool';++// NOTE: test use of require() here because this is how its done in acts+const { Apify, RequestList, utils: { log, sleep } } = require('../build/index');++/**+ * Helper function that enables testing of Apify.main()+ */+const testMain = async ({ userFunc, exitCode }) => {+ const exitSpy = jest.spyOn(process, 'exit');+ exitSpy.mockImplementationOnce((i) => i); // prevent `process.exit()`++ let error = null;+ const sdk = new Apify();++ try {+ await sdk.main(() => {+ sdk.config.get('');+ if (userFunc) {+ return userFunc(sdk);+ }+ }).catch((err) => { error = err; });++ // Waits max 1000 millis for process.exit() mock to be called+ await new Promise((resolve) => {+ const waitUntil = Date.now() + 1000;+ const intervalId = setInterval(() => {+ if (exitSpy.mock.calls.length === 0 && Date.now() < waitUntil) {+ return;+ }+ clearInterval(intervalId);+ resolve();+ }, 10);+ });++ if (error) {+ throw error;+ }+ } finally {+ expect(exitSpy).toBeCalledWith(exitCode);+ }+};++const getEmptyEnv = () => {+ return {+ // internalPort: null,+ actId: null,+ actRunId: null,+ userId: null,+ token: null,+ startedAt: null,+ timeoutAt: null,+ defaultKeyValueStoreId: null,+ defaultDatasetId: null,+ memoryMbytes: null,+ };+};++const setEnv = (env) => {+ delete process.env.APIFY_ACT_ID;+ delete process.env.APIFY_ACT_RUN_ID;+ delete process.env.APIFY_USER_ID;+ delete process.env.APIFY_TOKEN;+ delete process.env.APIFY_STARTED_AT;+ delete process.env.APIFY_TIMEOUT_AT;+ delete process.env.APIFY_DEFAULT_KEY_VALUE_STORE_ID;+ delete process.env.APIFY_DEFAULT_DATASET_ID;++ if (env.actId) process.env.APIFY_ACT_ID = env.actId;+ if (env.actRunId) process.env.APIFY_ACT_RUN_ID = env.actRunId;+ if (env.userId) process.env.APIFY_USER_ID = env.userId;+ if (env.token) process.env.APIFY_TOKEN = env.token;+ if (env.startedAt) process.env.APIFY_STARTED_AT = env.startedAt.toISOString();+ if (env.timeoutAt) process.env.APIFY_TIMEOUT_AT = env.timeoutAt.toISOString();+ if (env.defaultKeyValueStoreId) process.env.APIFY_DEFAULT_KEY_VALUE_STORE_ID = env.defaultKeyValueStoreId;+ if (env.defaultDatasetId) process.env.APIFY_DEFAULT_DATASET_ID = env.defaultDatasetId;+ if (env.memoryMbytes) process.env.APIFY_MEMORY_MBYTES = env.memoryMbytes.toString();+};++describe('new Apify({ ... })', () => {+ afterEach(() => jest.restoreAllMocks());++ describe('getEnv()', () => {+ let prevEnv;++ beforeAll(() => { prevEnv = new Apify().getEnv(); });+ afterAll(() => { setEnv(prevEnv); });++ test('works with null values', () => {+ const expectedEnv = getEmptyEnv();+ setEnv(expectedEnv);++ const env = new Apify().getEnv();+ expect(env).toMatchObject(expectedEnv);+ });++ test('works with with non-null values', () => {+ const expectedEnv = _.extend(getEmptyEnv(), {+ // internalPort: 12345,+ actId: 'test actId',+ actRunId: 'test actId',+ userId: 'some user',+ token: 'auth token',+ startedAt: new Date('2017-01-01'),+ timeoutAt: new Date(),+ defaultKeyValueStoreId: 'some store',+ defaultDatasetId: 'some dataset',+ memoryMbytes: 1234,+ });+ setEnv(expectedEnv);++ const env = new Apify().getEnv();+ expect(env).toMatchObject(expectedEnv);+ });+ });++ describe('main()', () => {+ test('throws on invalid args', () => {+ expect(() => {+ new Apify().main();+ }).toThrowError(Error);+ });++ test('works with simple user function', () => {+ return testMain({+ userFunc: () => {},+ exitCode: 0,+ });+ });++ test('sets default APIFY_LOCAL_STORAGE_DIR', async () => {+ delete process.env[ENV_VARS.LOCAL_STORAGE_DIR];+ delete process.env[ENV_VARS.TOKEN];++ await testMain({+ userFunc: (sdk) => {+ expect(sdk.config.get('localStorageDir')).toEqual(path.join(process.cwd(), './apify_storage'));+ },+ exitCode: 0,+ });++ delete process.env[ENV_VARS.LOCAL_STORAGE_DIR];+ });++ test('works with promised user function', async () => {+ let called = false;+ await testMain({+ userFunc: async () => {+ await sleep(20);+ called = true;+ },+ exitCode: 0,+ });+ expect(called).toBe(true);+ });++ test('on exception in simple user function the process exits with code 91', async () => {+ await testMain({+ userFunc: () => {+ throw new Error('Test exception I');+ },+ exitCode: 91,+ });+ });++ test('on exception in promised user function the process exits with code 91', async () => {+ await testMain({+ userFunc: async () => {+ await utils.sleep(20);+ throw new Error('Test exception II');+ },+ exitCode: 91,+ });+ });+ });++ describe('call()', () => {+ const token = 'some-token';+ const actId = 'some-act-id';+ const defaultKeyValueStoreId = 'some-store-id';+ const input = 'something';+ const contentType = 'text/plain';+ const outputKey = 'OUTPUT';+ const outputValue = 'some-output';+ const build = 'xxx';++ const run = { id: 'some-run-id', actId, defaultKeyValueStoreId };+ const finishedRun = { ...run, status: ACT_JOB_STATUSES.SUCCEEDED };+ const failedRun = { ...run, status: ACT_JOB_STATUSES.ABORTED };+ const runningRun = { ...run, status: ACT_JOB_STATUSES.RUNNING };+ const readyRun = { ...run, status: ACT_JOB_STATUSES.READY };++ const output = { contentType, key: outputKey, value: outputValue };+ const expected = { ...finishedRun, output: { contentType, body: outputValue } };++ test('works as expected', async () => {+ const memoryMbytes = 1024;+ const timeoutSecs = 60;+ const webhooks = [{ a: 'a' }, { b: 'b' }];++ const getRecordMock = jest.fn();+ getRecordMock.mockResolvedValueOnce(output);+ const callMock = jest.fn();+ callMock.mockResolvedValueOnce(finishedRun);+ const actorSpy = jest.spyOn(ApifyClient.prototype, 'actor');+ actorSpy.mockReturnValueOnce({ call: callMock });+ const keyValueStoreSpy = jest.spyOn(ApifyClient.prototype, 'keyValueStore');+ keyValueStoreSpy.mockReturnValueOnce({ getRecord: getRecordMock });++ const callOutput = await new Apify().call(actId, input, {+ contentType,+ disableBodyParser: true,+ build,+ memoryMbytes,+ timeoutSecs,+ webhooks,+ });++ expect(callOutput).toEqual(expected);+ expect(keyValueStoreSpy).toBeCalledTimes(1);+ expect(keyValueStoreSpy).toBeCalledWith('some-store-id');+ });++ test('works as expected with fetchOutput = false', async () => {+ const callMock = jest.fn();+ callMock.mockResolvedValueOnce(finishedRun);+ const actorSpy = jest.spyOn(ApifyClient.prototype, 'actor');+ const keyValueStoreSpy = jest.spyOn(ApifyClient.prototype, 'keyValueStore');+ actorSpy.mockReturnValueOnce({ call: callMock });++ const callOutput = await new Apify().call(actId, undefined, { disableBodyParser: true, fetchOutput: false });++ expect(keyValueStoreSpy).not.toBeCalled();+ expect(callOutput).toEqual(finishedRun);+ });++ test('works with token', async () => {+ const memoryMbytes = 1024;+ const timeoutSecs = 60;+ const webhooks = [{ a: 'a' }, { b: 'b' }];++ const newClientSpy = jest.spyOn(Apify.prototype, 'newClient');+ const callMock = jest.fn();+ callMock.mockResolvedValueOnce(finishedRun);+ const getRecordMock = jest.fn();+ getRecordMock.mockResolvedValueOnce(output);+ const actorSpy = jest.spyOn(ApifyClient.prototype, 'actor');+ actorSpy.mockReturnValueOnce({ call: callMock });+ const keyValueStoreSpy = jest.spyOn(ApifyClient.prototype, 'keyValueStore');+ keyValueStoreSpy.mockReturnValueOnce({ getRecord: getRecordMock });++ const callOutput = await new Apify({ token }).call(actId, input, {+ contentType,+ disableBodyParser: true,+ build,+ memoryMbytes,+ timeoutSecs,+ webhooks,+ });++ expect(callOutput).toEqual(expected);+ expect(newClientSpy).toBeCalledWith({ token });+ expect(actorSpy).toBeCalledWith(actId);+ expect(callMock).toBeCalledWith(input, {+ token,+ build,+ contentType: `${contentType}; charset=utf-8`,+ memory: memoryMbytes,+ timeout: timeoutSecs,+ webhooks,+ });+ expect(keyValueStoreSpy).toBeCalledWith(run.defaultKeyValueStoreId);+ expect(getRecordMock).toBeCalledWith('OUTPUT', { buffer: true });+ });++ test('works as expected with unfinished run', async () => {+ const waitSecs = 1;++ const callMock = jest.fn();+ callMock.mockResolvedValueOnce(runningRun);+ const actorSpy = jest.spyOn(ApifyClient.prototype, 'actor');+ actorSpy.mockReturnValueOnce({ call: callMock });+ const keyValueStoreSpy = jest.spyOn(ApifyClient.prototype, 'keyValueStore');++ const callOutput = await new Apify().call(actId, undefined, { disableBodyParser: true, fetchOutput: false, waitSecs });++ expect(callOutput).toEqual(runningRun);+ expect(actorSpy).toBeCalledWith('some-act-id');+ expect(keyValueStoreSpy).not.toBeCalled();+ });++ test('returns immediately with zero ', async () => {+ const waitSecs = 0;++ const callMock = jest.fn();+ callMock.mockResolvedValueOnce(readyRun);+ const actorSpy = jest.spyOn(ApifyClient.prototype, 'actor');+ actorSpy.mockReturnValueOnce({ call: callMock });+ const keyValueStoreSpy = jest.spyOn(ApifyClient.prototype, 'keyValueStore');++ const callOutput = await new Apify().call(actId, undefined, { waitSecs });++ expect(callOutput).toEqual(readyRun);+ expect(actorSpy).toBeCalledWith('some-act-id');+ expect(keyValueStoreSpy).not.toBeCalled();+ });++ test("throws if run doesn't succeed", async () => {+ const callMock = jest.fn();+ callMock.mockResolvedValueOnce(failedRun);+ const actorSpy = jest.spyOn(ApifyClient.prototype, 'actor');+ actorSpy.mockReturnValueOnce({ call: callMock });++ const err = 'The actor some-act-id invoked by Apify.call() did not succeed. For details, see https://my.apify.com/view/runs/some-run-id';+ await expect(new Apify().call(actId, null)).rejects.toThrowError(new ApifyCallError(failedRun, err));++ expect(actorSpy).toBeCalledWith('some-act-id');+ });+ });++ describe('callTask()', () => {+ const taskId = 'some-task-id';+ const actId = 'xxx';+ const token = 'some-token';+ const defaultKeyValueStoreId = 'some-store-id';+ const run = { id: 'some-run-id', actId, defaultKeyValueStoreId };+ const readyRun = { ...run, status: ACT_JOB_STATUSES.READY };+ const runningRun = { ...run, status: ACT_JOB_STATUSES.RUNNING };+ const finishedRun = { ...run, status: ACT_JOB_STATUSES.SUCCEEDED };+ const failedRun = { ...run, status: ACT_JOB_STATUSES.ABORTED };+ const contentType = 'application/json';+ const outputKey = 'OUTPUT';+ const outputValue = 'some-output';+ const output = { contentType, key: outputKey, value: outputValue };+ const expected = { ...finishedRun, output: { contentType, body: outputValue } };+ const input = { foo: 'bar' };+ const memoryMbytes = 256;+ const timeoutSecs = 60;+ const build = 'beta';+ const webhooks = [{ a: 'a' }, { b: 'b' }];++ test('works as expected', async () => {+ const getRecordMock = jest.fn();+ getRecordMock.mockResolvedValueOnce(output);+ const callMock = jest.fn();+ callMock.mockResolvedValueOnce(finishedRun);+ const taskSpy = jest.spyOn(ApifyClient.prototype, 'task');+ taskSpy.mockReturnValueOnce({ call: callMock });+ const keyValueStoreSpy = jest.spyOn(ApifyClient.prototype, 'keyValueStore');+ keyValueStoreSpy.mockReturnValueOnce({ getRecord: getRecordMock });++ const callOutput = await new Apify().callTask(taskId, input, { disableBodyParser: true, memoryMbytes, timeoutSecs, build, webhooks });++ expect(callOutput).toEqual(expected);+ expect(taskSpy).toBeCalledWith('some-task-id');+ });++ test('works with token', async () => {+ const newClientSpy = jest.spyOn(Apify.prototype, 'newClient');+ const callMock = jest.fn();+ callMock.mockResolvedValueOnce(finishedRun);+ const getRecordMock = jest.fn();+ getRecordMock.mockResolvedValueOnce(output);+ const taskSpy = jest.spyOn(ApifyClient.prototype, 'task');+ taskSpy.mockReturnValueOnce({ call: callMock });+ const keyValueStoreSpy = jest.spyOn(ApifyClient.prototype, 'keyValueStore');+ keyValueStoreSpy.mockReturnValueOnce({ getRecord: getRecordMock });++ const callOutput = await new Apify({ token }).callTask(taskId, input, {+ disableBodyParser: true,+ build,+ memoryMbytes,+ timeoutSecs,+ webhooks,+ });++ expect(callOutput).toEqual(expected);+ expect(newClientSpy).toBeCalledWith({ token });+ expect(taskSpy).toBeCalledWith(taskId);+ expect(callMock).toBeCalledWith(input, {+ token,+ build,+ memory: memoryMbytes,+ timeout: timeoutSecs,+ webhooks,+ });+ expect(keyValueStoreSpy).toBeCalledWith(run.defaultKeyValueStoreId);+ expect(getRecordMock).toBeCalledWith('OUTPUT', { buffer: true });+ });++ test('works as expected with fetchOutput = false', async () => {+ const callMock = jest.fn();+ callMock.mockResolvedValueOnce(finishedRun);+ const taskSpy = jest.spyOn(ApifyClient.prototype, 'task');+ const keyValueStoreSpy = jest.spyOn(ApifyClient.prototype, 'keyValueStore');+ taskSpy.mockReturnValueOnce({ call: callMock });++ const callOutput = await new Apify().callTask(taskId, undefined, { disableBodyParser: true, fetchOutput: false });++ expect(keyValueStoreSpy).not.toBeCalled();+ expect(callOutput).toEqual(finishedRun);+ expect(taskSpy).toBeCalledWith('some-task-id');+ });++ test('works as expected with unfinished run', async () => {+ const waitSecs = 1;++ const callMock = jest.fn();+ callMock.mockResolvedValueOnce(runningRun);+ const taskSpy = jest.spyOn(ApifyClient.prototype, 'task');+ taskSpy.mockReturnValueOnce({ call: callMock });+ const keyValueStoreSpy = jest.spyOn(ApifyClient.prototype, 'keyValueStore');++ const callOutput = await new Apify().callTask(taskId, undefined, { disableBodyParser: true, fetchOutput: false, waitSecs });++ expect(callOutput).toEqual(runningRun);+ expect(keyValueStoreSpy).not.toBeCalled();+ expect(taskSpy).toBeCalledWith('some-task-id');+ });++ test('returns immediately with zero ', async () => {+ const waitSecs = 0;++ const callMock = jest.fn();+ callMock.mockResolvedValueOnce(readyRun);+ const taskSpy = jest.spyOn(ApifyClient.prototype, 'task');+ taskSpy.mockReturnValueOnce({ call: callMock });+ const keyValueStoreSpy = jest.spyOn(ApifyClient.prototype, 'keyValueStore');++ const callOutput = await new Apify().callTask(taskId, undefined, { waitSecs });++ expect(callOutput).toEqual(readyRun);+ expect(keyValueStoreSpy).not.toBeCalled();+ expect(taskSpy).toBeCalledWith('some-task-id');+ });++ test("throws if run doesn't succeed", async () => {+ const callMock = jest.fn();+ callMock.mockResolvedValueOnce(failedRun);+ const taskSpy = jest.spyOn(ApifyClient.prototype, 'task');+ taskSpy.mockReturnValueOnce({ call: callMock });++ // eslint-disable-next-line max-len+ const err = 'The actor task some-task-id invoked by Apify.callTask() did not succeed. For details, see https://my.apify.com/view/runs/some-run-id';+ await expect(new Apify().callTask(taskId)).rejects.toThrowError(new ApifyCallError(failedRun, err));++ expect(taskSpy).toBeCalledWith('some-task-id');+ });+ });++ describe('metamorph()', () => {+ const runId = 'some-run-id';+ const actorId = 'some-actor-id';+ const targetActorId = 'some-target-actor-id';+ const contentType = 'application/json';+ const input = '{ "foo": "bar" }';+ const build = 'beta';+ const run = { id: runId, actId: actorId };++ beforeEach(() => {+ process.env[ENV_VARS.ACTOR_ID] = actorId;+ process.env[ENV_VARS.ACTOR_RUN_ID] = runId;+ });++ afterEach(() => {+ delete process.env[ENV_VARS.ACTOR_ID];+ delete process.env[ENV_VARS.ACTOR_RUN_ID];+ });++ test('works as expected', async () => {+ const metamorphMock = jest.fn();+ metamorphMock.mockResolvedValueOnce(run);+ const runSpy = jest.spyOn(ApifyClient.prototype, 'run');+ runSpy.mockReturnValueOnce({ metamorph: metamorphMock });++ await new Apify().metamorph(targetActorId, input, { contentType, build, customAfterSleepMillis: 1 });++ expect(metamorphMock).toBeCalledWith(targetActorId, input, {+ build,+ contentType: `${contentType}; charset=utf-8`,+ });+ });++ test('works without opts and input', async () => {+ const metamorphMock = jest.fn();+ metamorphMock.mockResolvedValueOnce(run);+ const runSpy = jest.spyOn(ApifyClient.prototype, 'run');+ runSpy.mockReturnValueOnce({ metamorph: metamorphMock });++ await new Apify().metamorph(targetActorId, undefined, { customAfterSleepMillis: 1 });++ expect(metamorphMock).toBeCalledWith(targetActorId, undefined, {});+ });+ });++ describe('addWebhook()', () => {+ const runId = 'my-run-id';+ const expectedEventTypes = ['ACTOR.RUN.SUCCEEDED'];+ const expectedRequestUrl = 'http://example.com/api';+ const expectedPayloadTemplate = '{"hello":{{world}}';+ const expectedIdempotencyKey = 'some-key';+ const webhook = {+ isAdHoc: true,+ eventTypes: expectedEventTypes,+ condition: {+ actorRunId: runId,+ },+ requestUrl: expectedRequestUrl,+ payloadTemplate: expectedPayloadTemplate,+ idempotencyKey: expectedIdempotencyKey,+ };++ test('works', async () => {+ process.env[ENV_VARS.ACTOR_RUN_ID] = runId;+ process.env[ENV_VARS.IS_AT_HOME] = '1';++ const createMock = jest.fn();+ createMock.mockResolvedValueOnce(webhook);+ const webhooksSpy = jest.spyOn(ApifyClient.prototype, 'webhooks');+ webhooksSpy.mockReturnValueOnce({ create: createMock });++ await new Apify().addWebhook({+ eventTypes: expectedEventTypes,+ requestUrl: expectedRequestUrl,+ payloadTemplate: expectedPayloadTemplate,+ idempotencyKey: expectedIdempotencyKey,+ });++ delete process.env[ENV_VARS.ACTOR_RUN_ID];+ delete process.env[ENV_VARS.IS_AT_HOME];++ expect(webhooksSpy).toBeCalledTimes(1);+ });++ test('on local logs warning and does nothing', async () => {+ const metamorphMock = jest.fn();+ const warningMock = jest.spyOn(log, 'warning');+ const runSpy = jest.spyOn(ApifyClient.prototype, 'run');+ runSpy.mockReturnValueOnce({ metamorph: metamorphMock });++ const sdk = new Apify();+ await sdk.addWebhook({ eventTypes: expectedEventTypes, requestUrl: expectedRequestUrl });++ expect(metamorphMock).not.toBeCalled();+ expect(warningMock).toBeCalledTimes(2);+ // eslint-disable-next-line max-len+ expect(warningMock).toBeCalledWith(`Neither APIFY_LOCAL_STORAGE_DIR nor APIFY_TOKEN environment variable is set, defaulting to APIFY_LOCAL_STORAGE_DIR="${sdk.config.get('localStorageDir')}"`);+ // eslint-disable-next-line max-len+ expect(warningMock).toBeCalledWith('Apify.addWebhook() is only supported when running on the Apify platform. The webhook will not be invoked.');+ });++ test('should fail without actor run ID', async () => {+ process.env[ENV_VARS.IS_AT_HOME] = '1';++ let isThrow;+ try {+ await new Apify().addWebhook({ eventTypes: expectedEventTypes, requestUrl: expectedRequestUrl });+ } catch (err) {+ isThrow = true;+ }+ expect(isThrow).toBe(true);++ delete process.env[ENV_VARS.IS_AT_HOME];+ });++ test('openSessionPool should create SessionPool', async () => {+ const sdk = new Apify();+ const initializeSpy = jest.spyOn(SessionPool.prototype, 'initialize');+ initializeSpy.mockImplementationOnce((i) => i);+ await sdk.openSessionPool();+ expect(initializeSpy).toBeCalledTimes(1);+ });++ test('createProxyConfiguration should create ProxyConfiguration', async () => {+ const sdk = new Apify();+ const initializeSpy = jest.spyOn(ProxyConfiguration.prototype, 'initialize');+ initializeSpy.mockImplementationOnce((i) => i);+ await sdk.createProxyConfiguration();+ expect(initializeSpy).toBeCalledTimes(1);+ });+ });++ describe('Storage API', () => {+ let localStorageEmulator;+ let sdk;++ beforeAll(() => { localStorageEmulator = new LocalStorageDirEmulator(); });+ beforeEach(async () => { sdk = new Apify({ localStorageDir: await localStorageEmulator.init() }); });+ afterAll(() => localStorageEmulator.destroy());++ test('getInput()', async () => {+ const getValueSpy = jest.spyOn(KeyValueStore.prototype, 'getValue');+ getValueSpy.mockImplementation(() => 123);++ // Uses default value.+ const val1 = await sdk.getInput();+ expect(getValueSpy).toBeCalledTimes(1);+ expect(getValueSpy).toBeCalledWith(KEY_VALUE_STORE_KEYS.INPUT);+ expect(val1).toBe(123);++ // Uses value from config+ sdk.config.set('inputKey', 'some-value');+ const val2 = await sdk.getInput();+ expect(getValueSpy).toBeCalledTimes(2);+ expect(getValueSpy).toBeCalledWith('some-value');+ expect(val2).toBe(123);+ sdk.config.set('inputKey', undefined); // restore defaults+ });++ test('setValue()', async () => {+ const record = { foo: 'bar' };+ const setValueSpy = jest.spyOn(KeyValueStore.prototype, 'setValue');+ setValueSpy.mockImplementationOnce((i) => i);++ await sdk.setValue('key-1', record);+ expect(setValueSpy).toBeCalledTimes(1);+ expect(setValueSpy).toBeCalledWith('key-1', record, undefined);+ });++ test('getValue()', async () => {+ const getValueSpy = jest.spyOn(KeyValueStore.prototype, 'getValue');+ getValueSpy.mockImplementationOnce(() => 123);++ const val = await sdk.getValue('key-1');+ expect(getValueSpy).toBeCalledTimes(1);+ expect(getValueSpy).toBeCalledWith('key-1');+ expect(val).toBe(123);+ });++ test('pushData()', async () => {+ const pushDataSpy = jest.spyOn(Dataset.prototype, 'pushData');+ pushDataSpy.mockImplementationOnce((i) => i);++ await sdk.pushData({ foo: 'bar' });+ expect(pushDataSpy).toBeCalledTimes(1);+ expect(pushDataSpy).toBeCalledWith({ foo: 'bar' });+ });++ test('openRequestList should create RequestList', async () => {+ const initializeSpy = jest.spyOn(RequestList.prototype, 'initialize');+ initializeSpy.mockImplementationOnce((i) => i);+ const list = await sdk.openRequestList('my-list', ['url-1', 'url-2', 'url-3']);+ expect(initializeSpy).toBeCalledTimes(1);+ expect(list.sources).toEqual(['url-1', 'url-2', 'url-3']);+ expect(list.persistStateKey).toBe('SDK_my-list-REQUEST_LIST_STATE');+ expect(list.persistRequestsKey).toBe('SDK_my-list-REQUEST_LIST_REQUESTS');+ });++ test('openRequestQueue should open storage', async () => {+ const queueId = 'abc';+ const options = { forceCloud: true };+ const openStorageSpy = jest.spyOn(StorageManager.prototype, 'openStorage');+ openStorageSpy.mockImplementationOnce((i) => i);+ await sdk.openRequestQueue(queueId, options);+ expect(openStorageSpy).toBeCalledWith(queueId, options);+ expect(openStorageSpy).toBeCalledTimes(1);+ });+ });+});diff --git a/test/browser_launchers/playwright_launcher.test.js b/test/browser_launchers/playwright_launcher.test.jsindex d0802d1e9..2f526ef67 100644--- a/test/browser_launchers/playwright_launcher.test.js+++ b/test/browser_launchers/playwright_launcher.test.js@@ -23,7 +23,7 @@ beforeAll(() => {process.env[ENV_VARS.HEADLESS] = '1';// Find free port for the proxy- return portastic.find({ min: 50000, max: 50100 }).then((ports) => {+ return portastic.find({ min: 50000, max: 50099 }).then((ports) => {return new Promise((resolve, reject) => {const httpServer = http.createServer();diff --git a/test/browser_launchers/puppeteer_launcher.test.js b/test/browser_launchers/puppeteer_launcher.test.jsindex 5037ffeeb..98f693958 100644--- a/test/browser_launchers/puppeteer_launcher.test.js+++ b/test/browser_launchers/puppeteer_launcher.test.js@@ -21,7 +21,7 @@ beforeAll(() => {process.env[ENV_VARS.HEADLESS] = '1';// Find free port for the proxy- return portastic.find({ min: 50000, max: 50100 }).then((ports) => {+ return portastic.find({ min: 50100, max: 50199 }).then((ports) => {return new Promise((resolve, reject) => {const httpServer = http.createServer();diff --git a/test/crawlers/basic_crawler.test.js b/test/crawlers/basic_crawler.test.jsindex 76ce41cf0..f5532d88d 100644--- a/test/crawlers/basic_crawler.test.js+++ b/test/crawlers/basic_crawler.test.js@@ -21,7 +21,7 @@ describe('BasicCrawler', () => {beforeEach(async () => {const storageDir = await localStorageEmulator.init();- utils.apifyStorageLocal = utils.newStorageLocal({ storageDir });+ Apify.Configuration.getGlobalConfig().set('localStorageDir', storageDir);});afterAll(async () => {diff --git a/test/crawlers/browser_crawler.test.js b/test/crawlers/browser_crawler.test.jsindex 3c30450a4..ae209fbca 100644--- a/test/crawlers/browser_crawler.test.js+++ b/test/crawlers/browser_crawler.test.js@@ -1,3 +1,5 @@+/* eslint-disable no-prototype-builtins */+import { URL } from 'url';import { ENV_VARS } from 'apify-shared/consts';import sinon from 'sinon';@@ -8,7 +10,6 @@ import * as Apify from '../../build';import { STATUS_CODES_BLOCKED } from '../../build/constants';import LocalStorageDirEmulator from '../local_storage_dir_emulator';import * as utilsRequest from '../../build/utils_request';-import * as utils from '../../build/utils';import Request from '../../build/request';import AutoscaledPool from '../../build/autoscaling/autoscaled_pool';import { Session } from '../../build/session_pool/session';@@ -29,7 +30,7 @@ describe('BrowserCrawler', () => {});beforeEach(async () => {const storageDir = await localStorageEmulator.init();- utils.apifyStorageLocal = utils.newStorageLocal({ storageDir });+ Apify.Configuration.getGlobalConfig().set('localStorageDir', storageDir);puppeteerPlugin = new PuppeteerPlugin(puppeteer);});afterEach(() => {diff --git a/test/crawlers/cheerio_crawler.test.js b/test/crawlers/cheerio_crawler.test.jsindex 0dbaabd06..b8b5a4f1f 100644--- a/test/crawlers/cheerio_crawler.test.js+++ b/test/crawlers/cheerio_crawler.test.js@@ -1,3 +1,5 @@+/* eslint-disable no-prototype-builtins */+import fs from 'fs';import path from 'path';import { ENV_VARS } from 'apify-shared/consts';@@ -15,7 +17,6 @@ import LocalStorageDirEmulator from '../local_storage_dir_emulator';import * as utilsRequest from '../../build/utils_request';import CrawlerExtension from '../../build/crawlers/crawler_extension';import Request from '../../build/request';-import * as utils from '../../build/utils';import AutoscaledPool from '../../build/autoscaling/autoscaled_pool';const HOST = '127.0.0.1';@@ -100,7 +101,7 @@ describe('CheerioCrawler', () => {beforeEach(async () => {const storageDir = await localStorageEmulator.init();- utils.apifyStorageLocal = utils.newStorageLocal({ storageDir });+ Apify.Configuration.getGlobalConfig().set('localStorageDir', storageDir);});afterAll(async () => {diff --git a/test/crawlers/playwright_crawler.test.js b/test/crawlers/playwright_crawler.test.jsindex eb7adb560..0770a8652 100644--- a/test/crawlers/playwright_crawler.test.js+++ b/test/crawlers/playwright_crawler.test.js@@ -3,7 +3,6 @@ import playwright from 'playwright';import log from '../../build/utils_log';import * as Apify from '../../build';import LocalStorageDirEmulator from '../local_storage_dir_emulator';-import * as utils from '../../build/utils';describe('PlaywrightCrawler', () => {let prevEnvHeadless;@@ -20,7 +19,7 @@ describe('PlaywrightCrawler', () => {});beforeEach(async () => {const storageDir = await localStorageEmulator.init();- utils.apifyStorageLocal = utils.newStorageLocal({ storageDir });+ Apify.Configuration.getGlobalConfig().set('localStorageDir', storageDir);const sources = ['http://example.com/'];requestList = await Apify.openRequestList(`sources-${Math.random * 10000}`, sources);});diff --git a/test/crawlers/puppeteer_crawler.test.js b/test/crawlers/puppeteer_crawler.test.jsindex 938597201..a11107eeb 100644--- a/test/crawlers/puppeteer_crawler.test.js+++ b/test/crawlers/puppeteer_crawler.test.js@@ -20,7 +20,7 @@ describe('PuppeteerCrawler', () => {});beforeEach(async () => {const storageDir = await localStorageEmulator.init();- utils.apifyStorageLocal = utils.newStorageLocal({ storageDir });+ Apify.Configuration.getGlobalConfig().set('localStorageDir', storageDir);const sources = ['http://example.com/'];requestList = await Apify.openRequestList(`sources-${Math.random * 10000}`, sources);});@@ -79,8 +79,7 @@ describe('PuppeteerCrawler', () => {requestList,maxRequestRetries: 0,maxConcurrency: 1,- handlePageFunction: async () => {- },+ handlePageFunction: async () => {},preNavigationHooks: [(context, gotoOptions) => {options = gotoOptions;}],@@ -95,7 +94,7 @@ describe('PuppeteerCrawler', () => {test('should support custom gotoFunction', async () => {const functions = {- handlePageFunction: () => {},+ handlePageFunction: async () => {},gotoFunction: ({ page, request }, options) => {return page.goto(request.url, options);},@@ -124,8 +123,7 @@ describe('PuppeteerCrawler', () => {requestList,maxRequestRetries: 0,maxConcurrency: 1,- handlePageFunction: async () => {- },+ handlePageFunction: async () => {},preNavigationHooks: [(context, gotoOptions) => {options = gotoOptions;}],@@ -155,10 +153,10 @@ describe('PuppeteerCrawler', () => {expect.hasAssertions();});+test('supports useChrome option', async () => {const spy = sinon.spy(utils, 'getTypicalChromeExecutablePath');-- const puppeteerCrawler = new Apify.PuppeteerCrawler({ //eslint-disable-line+ const puppeteerCrawler = new Apify.PuppeteerCrawler({ //eslint-disable-linerequestList,maxRequestRetries: 0,maxConcurrency: 1,@@ -168,8 +166,7 @@ describe('PuppeteerCrawler', () => {headless: true,},},- handlePageFunction: async () => {- },+ handlePageFunction: async () => {},});expect(spy.calledOnce).toBe(true);diff --git a/test/crawlers/statistics.test.js b/test/crawlers/statistics.test.jsindex 3ced5e73f..80378bb8e 100644--- a/test/crawlers/statistics.test.js+++ b/test/crawlers/statistics.test.js@@ -1,9 +1,9 @@import sinon from 'sinon';import Statistics from '../../build/crawlers/statistics';import LocalStorageDirEmulator from '../local_storage_dir_emulator';+import Apify from '../../build';import events from '../../build/events';import { ACTOR_EVENT_NAMES_EX } from '../../build/constants';-import * as utils from '../../build/utils';describe('Statistics', () => {const getPerMinute = (jobCount, totalTickMillis) => {@@ -23,7 +23,7 @@ describe('Statistics', () => {beforeEach(async () => {const storageDir = await localStorageEmulator.init();- utils.apifyStorageLocal = utils.newStorageLocal({ storageDir });+ Apify.Configuration.getGlobalConfig().set('localStorageDir', storageDir);clock = sinon.useFakeTimers();stats = new Statistics();});@@ -61,7 +61,7 @@ describe('Statistics', () => {await stats.startCapturing();await stats.persistState();- console.dir(stats);+ // console.dir(stats);// eslint-disable-next-line no-unused-varsconst state = await stats.keyValueStore.getValue(stats.persistStateKey);diff --git a/test/events.test.js b/test/events.test.jsindex 3292bcae0..4c4004fb4 100644--- a/test/events.test.js+++ b/test/events.test.js@@ -16,11 +16,13 @@ describe('Apify.events', () => {process.env[ENV_VARS.TOKEN] = 'dummy';});afterEach((done) => {- wss.close(done);clock.restore();delete process.env[ENV_VARS.ACTOR_EVENTS_WS_URL];delete process.env[ENV_VARS.TOKEN];+ Apify.events.removeAllListeners();+ wss.close(done);});+test('is there and works as EventEmitter', () => {return new Promise((resolve, reject) => {try {@@ -124,6 +126,11 @@ describe('Apify.events', () => {Apify.stopEvents();await closePromise;expect(wsClosed).toBe(true);++ // Due to some race condition or leaks in this test implementation with shared static register of events,+ // this test sometimes ends without actually closing the WS connection, resulting in failures of the following+ // test that will reuse the existing ws connection instead of new one. Short wait helps to mitigate that.+ await sleep(10);});test('should send persist state events in regular interval', async () => {@@ -133,9 +140,7 @@ describe('Apify.events', () => {clock.tick(60001);clock.tick(60001);clock.tick(60001);- await Apify.stopEvents();- const eventCount = eventsReceived.length;- expect(eventCount).toBe(3);- expect(eventsReceived.length).toEqual(eventCount);+ Apify.stopEvents();+ expect(eventsReceived.length).toBe(3);});});diff --git a/test/main.test.js b/test/main.test.jsindex 1a964dfa1..a9d458b7e 100644--- a/test/main.test.js+++ b/test/main.test.js@@ -7,7 +7,6 @@ import ApifyDefault from '../build/index';// eslint-disable-next-line import/no-duplicatesimport * as ApifyWithWildcard from '../build/index';import LocalStorageDirEmulator from './local_storage_dir_emulator';-import * as utils from '../build/utils';// eslint-disable-next-line global-requireconst Apify = require('../build');@@ -28,7 +27,6 @@ describe('Apify module', () => {describe('Apify functions for storages', () => {let localStorageEmulator;- let localStorageDir;beforeAll(async () => {localStorageEmulator = new LocalStorageDirEmulator();@@ -36,7 +34,7 @@ describe('Apify functions for storages', () => {beforeEach(async () => {const storageDir = await localStorageEmulator.init();- utils.apifyStorageLocal = utils.newStorageLocal({ storageDir });+ Apify.Configuration.getGlobalConfig().set('localStorageDir', storageDir);});afterAll(async () => {@@ -45,7 +43,6 @@ describe('Apify functions for storages', () => {describe('Apify.getInput', () => {test('should work', async () => {- process.env[ENV_VARS.LOCAL_STORAGE_DIR] = localStorageDir;const defaultStore = await Apify.openKeyValueStore();// Uses default value.const oldGet = defaultStore.getValue;@@ -57,7 +54,6 @@ describe('Apify functions for storages', () => {defaultStore.getValue = async (key) => expect(key).toBe('some-value');await Apify.getInput();- delete process.env[ENV_VARS.LOCAL_STORAGE_DIR];delete process.env[ENV_VARS.INPUT_KEY];defaultStore.getValue = oldGet;diff --git a/test/playwright_utils.test.js b/test/playwright_utils.test.jsindex 87ec8143e..0f766744c 100644--- a/test/playwright_utils.test.js+++ b/test/playwright_utils.test.js@@ -1,7 +1,6 @@import playwright from 'playwright';import Apify from '../build/index';import LocalStorageDirEmulator from './local_storage_dir_emulator';-import * as utils from '../build/utils';const { utils: { log } } = Apify;@@ -17,7 +16,7 @@ describe('Apify.utils.playwright', () => {beforeEach(async () => {const storageDir = await localStorageEmulator.init();- utils.apifyStorageLocal = utils.newStorageLocal({ storageDir });+ Apify.Configuration.getGlobalConfig().set('localStorageDir', storageDir);});afterAll(async () => {diff --git a/test/proxy_configuration.test.js b/test/proxy_configuration.test.jsindex 1332dc005..96c39dcae 100644--- a/test/proxy_configuration.test.js+++ b/test/proxy_configuration.test.js@@ -67,7 +67,6 @@ describe('ProxyConfiguration', () => {const apifyProxyCountry = 'CZ';const input = {- useApifyProxy: true,apifyProxyGroups,apifyProxyCountry,};diff --git a/test/puppeteer_utils.test.js b/test/puppeteer_utils.test.jsindex c2a45da81..3b4037e77 100644--- a/test/puppeteer_utils.test.js+++ b/test/puppeteer_utils.test.js@@ -3,7 +3,6 @@ import path from 'path';import Apify from '../build/index';import * as keyValueStore from '../build/storages/key_value_store';import LocalStorageDirEmulator from './local_storage_dir_emulator';-import * as utils from '../build/utils';const { utils: { log } } = Apify;@@ -19,7 +18,7 @@ describe('Apify.utils.puppeteer', () => {beforeEach(async () => {const storageDir = await localStorageEmulator.init();- utils.apifyStorageLocal = utils.newStorageLocal({ storageDir });+ Apify.Configuration.getGlobalConfig().set('localStorageDir', storageDir);});afterAll(async () => {@@ -281,7 +280,7 @@ describe('Apify.utils.puppeteer', () => {compileScript(scriptStringBad);throw new Error('Should fail.');} catch (err) {- // TODO figure out why the err.message comes out empty in the logs.+ // TODO figure out why the err.message comes out empty in the logs.expect(err.message).toMatch(/Unexpected token '?const'?/);}const browser = await Apify[launchName](launchContext);diff --git a/test/session_pool/session_pool.test.js b/test/session_pool/session_pool.test.jsindex 6def80638..cacac4bd4 100644--- a/test/session_pool/session_pool.test.js+++ b/test/session_pool/session_pool.test.js@@ -1,7 +1,6 @@import { SessionPool, openSessionPool } from '../../build/session_pool/session_pool';import Apify from '../../build';import events from '../../build/events';-import * as utils from '../../build/utils';import { ACTOR_EVENT_NAMES_EX } from '../../build/constants';import { Session } from '../../build/session_pool/session';import LocalStorageDirEmulator from '../local_storage_dir_emulator';@@ -17,7 +16,7 @@ describe('SessionPool - testing session pool', () => {beforeEach(async () => {const storageDir = await localStorageEmulator.init();- utils.apifyStorageLocal = utils.newStorageLocal({ storageDir });+ Apify.Configuration.getGlobalConfig().set('localStorageDir', storageDir);sessionPool = await Apify.openSessionPool();});@@ -29,7 +28,6 @@ describe('SessionPool - testing session pool', () => {await localStorageEmulator.destroy();});- // eslint-disable-linetest('should initialize with default values for first time', async () => {expect(sessionPool.sessions.length).toBeDefined();expect(sessionPool.maxPoolSize).toBeDefined();@@ -93,7 +91,7 @@ describe('SessionPool - testing session pool', () => {sessionPool = await Apify.openSessionPool({ sessionOptions: { maxAgeSecs: 100, maxUsageCount: 10 } });const session = await sessionPool.getSession();expect(sessionPool.sessions.length).toBe(1);- expect(session.id).toBeDefined(); // eslint-disable-line+ expect(session.id).toBeDefined();expect(session.maxAgeSecs).toEqual(sessionPool.sessionOptions.maxAgeSecs);expect(session.maxAgeSecs).toEqual(sessionPool.sessionOptions.maxAgeSecs);expect(session.sessionPool).toEqual(sessionPool);@@ -191,9 +189,9 @@ describe('SessionPool - testing session pool', () => {});test('should create session', async () => {- await sessionPool._createSession(); // eslint-disable-line+ await sessionPool._createSession(); // eslint-disable-lineexpect(sessionPool.sessions.length).toBe(1);- expect(sessionPool.sessions[0].id).toBeDefined(); // eslint-disable-line+ expect(sessionPool.sessions[0].id).toBeDefined();});describe('should persist state', () => {@@ -293,13 +291,13 @@ describe('SessionPool - testing session pool', () => {let isCalled;const createSessionFunction = (sessionPool2) => {isCalled = true;- expect(sessionPool2 instanceof SessionPool).toBe(true); // eslint-disable-line+ expect(sessionPool2 instanceof SessionPool).toBe(true);return new Session({ sessionPool: sessionPool2 });};const newSessionPool = await Apify.openSessionPool({ createSessionFunction });const session = await newSessionPool.getSession();- expect(isCalled).toBe(true); // eslint-disable-line- expect(session.constructor.name).toBe("Session") // eslint-disable-line+ expect(isCalled).toBe(true);+ expect(session.constructor.name).toBe('Session');});it('should remove persist state event listener', async () => {diff --git a/test/stealth/stealth.test.js b/test/stealth/stealth.test.jsindex 4468e9335..bf593a72e 100644--- a/test/stealth/stealth.test.js+++ b/test/stealth/stealth.test.js@@ -1,9 +1,10 @@+/* eslint-disable no-console */+import scanner from 'fpscanner';import path from 'path';import Apify from '../../build';import LocalStorageDirEmulator from '../local_storage_dir_emulator';-import * as utils from '../../build/utils';const fingerPrintPath = require.resolve('fpcollect/dist/fpCollect.min.js');const pathToHTML = path.join(__dirname, 'test_html.html');@@ -25,7 +26,7 @@ describe('Stealth - testing headless chrome hiding tricks', () => {beforeEach(async () => {const storageDir = await localStorageEmulator.init();- utils.apifyStorageLocal = utils.newStorageLocal({ storageDir });+ Apify.Configuration.getGlobalConfig().set('localStorageDir', storageDir);});afterAll(async () => {diff --git a/test/storages/dataset.test.js b/test/storages/dataset.test.jsindex b2ad77538..b8a9384f0 100644--- a/test/storages/dataset.test.js+++ b/test/storages/dataset.test.js@@ -9,7 +9,7 @@ import {chunkBySize,} from '../../build/storages/dataset';import * as Apify from '../../build';-import StorageManager from '../../build/storages/storage_manager';+import { StorageManager } from '../../build/storages/storage_manager';jest.mock('../../build/storages/storage_manager');diff --git a/test/storages/key_value_store.test.js b/test/storages/key_value_store.test.jsindex 21a783e8d..a66fb1007 100644--- a/test/storages/key_value_store.test.js+++ b/test/storages/key_value_store.test.js@@ -6,7 +6,7 @@ import {KeyValueStore,maybeStringify,} from '../../build/storages/key_value_store';-import StorageManager from '../../build/storages/storage_manager';+import { StorageManager } from '../../build/storages/storage_manager';import * as Apify from '../../build';jest.mock('../../build/storages/storage_manager');diff --git a/test/storages/request_queue.test.js b/test/storages/request_queue.test.jsindex 920b190bc..324cb9961 100644--- a/test/storages/request_queue.test.js+++ b/test/storages/request_queue.test.js@@ -6,7 +6,7 @@ import {API_PROCESSED_REQUESTS_DELAY_MILLIS,STORAGE_CONSISTENCY_DELAY_MILLIS,} from '../../build/storages/request_queue';-import StorageManager from '../../build/storages/storage_manager';+import { StorageManager } from '../../build/storages/storage_manager';jest.mock('../../build/storages/storage_manager');diff --git a/test/utils.test.js b/test/utils.test.jsindex bd2eb5b74..9fa6f5c04 100644--- a/test/utils.test.js+++ b/test/utils.test.js@@ -715,7 +715,6 @@ describe('utils.printOutdatedSdkWarning()', () => {test('should correctly work when outdated', () => {process.env[ENV_VARS.SDK_LATEST_VERSION] = semver.inc(currentVersion, 'minor');- console.log(process.env[ENV_VARS.SDK_LATEST_VERSION]);logMock.expects('warning').once();utils.printOutdatedSdkWarning();delete process.env[ENV_VARS.SDK_LATEST_VERSION];diff --git a/types-apify/apify-shared/consts.d.ts b/types-apify/apify-shared/consts.d.tsdeleted file mode 100644index a440a6af8..000000000--- a/types-apify/apify-shared/consts.d.ts+++ /dev/null@@ -1,54 +0,0 @@-declare module 'apify-shared/consts' {- export const ACTOR_EVENT_NAMES: {- MIGRATING: string;- SYSTEM_INFO: string;- CPU_INFO: string;- };- export const REQUEST_QUEUE_HEAD_MAX_LIMIT: number;- export const ENV_VARS: {- MEMORY_MBYTES: string;- API_BASE_URL: string;- IS_AT_HOME: string;- SDK_LATEST_VERSION: string;- TOKEN: string;- ACTOR_RUN_ID: string;- CONTAINER_PORT: string;- CONTAINER_URL: string;- LOCAL_STORAGE_DIR: string;- DEFAULT_DATASET_ID: string;- USER_ID: string;- DEFAULT_KEY_VALUE_STORE_ID: string;- ACTOR_EVENTS_WS_URL: string;- INPUT_KEY: string;- HEADLESS: string;- XVFB: string;- PROXY_PASSWORD: string;- DEFAULT_REQUEST_QUEUE_ID: string;- CHROME_EXECUTABLE_PATH: string;- };- export const KEY_VALUE_STORE_KEYS: {- INPUT: string;- };- export const LOCAL_STORAGE_SUBDIRS: {- datasets: string;- requestQueues: string;- keyValueStores: string;- };- export const MAX_PAYLOAD_SIZE_BYTES: {-- };- export const INTEGER_ENV_VARS: {-- };- export const ACT_JOB_TERMINAL_STATUSES: {-- };- export const ACT_JOB_STATUSES: {-- };- export const LOCAL_ENV_VARS: {- [index: string]: string;- CONTAINER_PORT: string;- CONTAINER_URL: string;- };-}diff --git a/types-apify/apify-shared/linked_list.d.ts b/types-apify/apify-shared/linked_list.d.tsdeleted file mode 100644index af351b409..000000000--- a/types-apify/apify-shared/linked_list.d.ts+++ /dev/null@@ -1,7 +0,0 @@-declare module 'apify-shared/linked_list' {- class LinkedList {-- }-- export = LinkedList;-}diff --git a/types-apify/apify-shared/list_dictionary.d.ts b/types-apify/apify-shared/list_dictionary.d.tsdeleted file mode 100644index 6ad372c2c..000000000--- a/types-apify/apify-shared/list_dictionary.d.ts+++ /dev/null@@ -1,7 +0,0 @@-declare module 'apify-shared/list_dictionary' {- class ListDictionary {-- }-- export = ListDictionary;-}diff --git a/types-apify/apify-shared/lru_cache.d.ts b/types-apify/apify-shared/lru_cache.d.tsdeleted file mode 100644index 924b3322a..000000000--- a/types-apify/apify-shared/lru_cache.d.ts+++ /dev/null@@ -1,4 +0,0 @@-declare module 'apify-shared/lru_cache' {- const LruCache: any;- export = LruCache;-}diff --git a/types-apify/apify-shared/regexs.d.ts b/types-apify/apify-shared/regexs.d.tsdeleted file mode 100644index 12393d056..000000000--- a/types-apify/apify-shared/regexs.d.ts+++ /dev/null@@ -1,4 +0,0 @@-declare module 'apify-shared/regexs' {- export const APIFY_PROXY_VALUE_REGEX: RegExp;- export const KEY_VALUE_STORE_KEY_REGEX: RegExp;-}diff --git a/types-apify/apify-shared/streams_utilities.d.ts b/types-apify/apify-shared/streams_utilities.d.tsdeleted file mode 100644index 98ca50890..000000000--- a/types-apify/apify-shared/streams_utilities.d.ts+++ /dev/null@@ -1,4 +0,0 @@-declare module 'apify-shared/streams_utilities' {- export function readStreamToString(response: any, encoding: any): any;- export function concatStreamToBuffer(response: any): any;-}diff --git a/types-apify/apify-shared/utilities.d.ts b/types-apify/apify-shared/utilities.d.tsdeleted file mode 100644index c1e4ce0cb..000000000--- a/types-apify/apify-shared/utilities.d.ts+++ /dev/null@@ -1,11 +0,0 @@-declare module 'apify-shared/utilities' {- export function checkParamPrototypeOrThrow(...args: any): any;- export function betterSetInterval(f: Function, timeout: number): any;- export function betterClearInterval(intervalId: any): any;- export function promisifyServerListen(server: any): (port: any) => Promise<any>;- export function cryptoRandomObjectId(len?: number): string;- export function leftpad(val: number, len: number, char: number): string;- export const jsonStringifyExtended: typeof JSON.stringify;- export function normalizeUrl(url: any, keep: boolean): any;- export function getRandomInt(from: number): number;-}diff --git a/website/i18n/en.json b/website/i18n/en.jsonindex 92f5c872a..103d6e18f 100644--- a/website/i18n/en.json+++ b/website/i18n/en.json@@ -23,6 +23,9 @@"api/cheerio-crawler": {"title": "CheerioCrawler"},+ "api/configuration": {+ "title": "Configuration"+ },"api/dataset": {"title": "Dataset"},@@ -194,6 +197,9 @@"typedefs/adhoc-webhook": {"title": "AdhocWebhook"},+ "typedefs/apify-class": {+ "title": "ApifyClass"+ },"typedefs/apify-env": {"title": "ApifyEnv"},diff --git a/website/sidebars.json b/website/sidebars.jsonindex 763f5737e..8cf5923b2 100644--- a/website/sidebars.json+++ b/website/sidebars.json@@ -38,6 +38,7 @@],"API Reference": ["api/apify",+ "api/configuration",{"type": "subcategory","label": "Crawlers",