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
Adding Apify.metamorph()
Marek Trunkat7ae319d26275
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4d3f442c7..b563ca861 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,3 +1,7 @@+xxx+===================+-- Added `Apify.metamorph()`, see documentation for more information.+xxx===================- **BREAKING CHANGE:** Reduced default `handlePageTimeoutSecs` for both `CheerioCrawler` and `PuppeteerCrawler` from 300 to 60 seconds,diff --git a/src/actor.js b/src/actor.jsindex bb9ecde53..d8a1748ed 100644--- a/src/actor.js+++ b/src/actor.js@@ -7,12 +7,14 @@ import { APIFY_PROXY_VALUE_REGEX } from 'apify-shared/regexs';import { ENV_VARS, LOCAL_ENV_VARS, ACT_JOB_TERMINAL_STATUSES, ACT_JOB_STATUSES } from 'apify-shared/consts';import { EXIT_CODES } from './constants';import { initializeEvents, stopEvents } from './events';-import { apifyClient, addCharsetToContentType } from './utils';+import { apifyClient, addCharsetToContentType, sleep } from './utils';import { maybeStringify } from './key_value_store';import { ApifyCallError } from './errors';/* globals process */+const METAMORPH_AFTER_SLEEP_MILLIS = 300000;+/*** Tries to parse a string with date.* Returns either a Date object or undefined@@ -485,6 +487,68 @@ export const callTask = async (taskId, input, options = {}) => {return Object.assign({}, updatedRun, { output });};++/**+ * Metamorphs current actor run into a run of another actor with given input.+ * After this function is called the actor container gets stopped and restarted as a run of given actor.+ *+ * @param {String} actorId+ * Either `username/actor-name` or actor ID of an actor to which we want to metamorph.+ * @param {Object|String|Buffer} [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<undefined>}+ *+ * @memberof module:Apify+ * @function+ * @name metamorph+ */+export const metamorph = async (actorId, input, options = {}) => {+ // Use optionsCopy here as maybeStringify() may override contentType+ const optionsCopy = Object.assign({}, options);+ const { acts } = apifyClient;++ checkParamOrThrow(actorId, 'actorId', 'String');+ checkParamOrThrow(optionsCopy, 'opts', 'Object');+ checkParamOrThrow(optionsCopy.build, 'options.build', 'Maybe String');+ checkParamOrThrow(optionsCopy.contentType, 'options.contentType', 'Maybe String');++ const actId = process.env[ENV_VARS.ACTOR_ID];+ const runId = process.env[ENV_VARS.ACTOR_RUN_ID];+ if (!actId) 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) {+ input = maybeStringify(input, optionsCopy);+ checkParamOrThrow(input, 'input', 'Buffer|String');+ if (optionsCopy.contentType) optionsCopy.contentType = addCharsetToContentType(optionsCopy.contentType);+ }++ await acts.metamorphRun({+ actId,+ runId,+ targetActorId: actorId,+ contentType: optionsCopy.contentType,+ body: input,+ build: optionsCopy.build,+ });++ // Wait some time for container to be stopped.+ // NOTE: option.customAfterSleepMillis is used in tests+ await sleep(optionsCopy.customAfterSleepMillis || METAMORPH_AFTER_SLEEP_MILLIS);+};+/*** Represents information about an actor run, as returned by the* [`Apify.call()`](../api/apify#module_Apify.call) or [`Apify.callTask()`](../api/apify#module_Apify.callTask) function.diff --git a/src/index.js b/src/index.jsindex 65798f325..bdb2f8a72 100644--- a/src/index.js+++ b/src/index.js@@ -1,7 +1,7 @@import EventEmitter from 'events';import log from 'apify-shared/log';import { ENV_VARS } from 'apify-shared/consts';-import { main, getEnv, call, callTask, getApifyProxyUrl } from './actor';+import { main, getEnv, call, callTask, getApifyProxyUrl, metamorph } from './actor';import AutoscaledPool from './autoscaling/autoscaled_pool';import BasicCrawler from './basic_crawler';import CheerioCrawler from './cheerio_crawler';@@ -53,6 +53,7 @@ module.exports = {getEnv,call,callTask,+ metamorph,getMemoryInfo,getApifyProxyUrl,isAtHome,diff --git a/src/utils.js b/src/utils.jsindex f2b8aef58..e5a076573 100644--- a/src/utils.js+++ b/src/utils.js@@ -392,7 +392,7 @@ export const isAtHome = () => !!process.env[ENV_VARS.IS_AT_HOME];* @memberof utils* @return {Promise}*/-const sleep = (millis) => {+export const sleep = (millis) => {return delayPromise(millis);};diff --git a/test/actor.js b/test/actor.jsindex 11cc96cb6..8f5f64df0 100644--- a/test/actor.js+++ b/test/actor.js@@ -896,6 +896,104 @@ describe('Apify.callTask()', () => {});});+describe('Apify.metamorph()', () => {+ it('works as expected', async () => {+ 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';++ process.env[ENV_VARS.ACTOR_ID] = actorId;+ process.env[ENV_VARS.ACTOR_RUN_ID] = runId;++ const actsMock = sinon.mock(Apify.client.acts);+ actsMock.expects('metamorphRun')+ .withExactArgs({+ runId,+ actId: actorId,+ targetActorId,+ body: input,+ contentType: 'application/json; charset=utf-8',+ build,+ })+ .once()+ .returns(Promise.resolve());+++ await Apify.metamorph(targetActorId, input, { contentType, build, customAfterSleepMillis: 1 });++ delete process.env[ENV_VARS.ACTOR_ID];+ delete process.env[ENV_VARS.ACTOR_RUN_ID];++ actsMock.verify();+ actsMock.restore();+ });++ it('works without opts and input', async () => {+ const runId = 'some-run-id';+ const actorId = 'some-actor-id';+ const targetActorId = 'some-target-actor-id';++ process.env[ENV_VARS.ACTOR_ID] = actorId;+ process.env[ENV_VARS.ACTOR_RUN_ID] = runId;++ const actsMock = sinon.mock(Apify.client.acts);+ actsMock.expects('metamorphRun')+ .withExactArgs({+ runId,+ actId: actorId,+ targetActorId,+ body: undefined,+ build: undefined,+ contentType: undefined,+ })+ .once()+ .returns(Promise.resolve());+++ await Apify.metamorph(targetActorId, undefined, { customAfterSleepMillis: 1 });++ delete process.env[ENV_VARS.ACTOR_ID];+ delete process.env[ENV_VARS.ACTOR_RUN_ID];++ actsMock.verify();+ actsMock.restore();+ });++ it('stringifies to JSON', async () => {+ const runId = 'some-run-id';+ const actorId = 'some-actor-id';+ const targetActorId = 'some-target-actor-id';+ const input = { foo: 'bar' };++ process.env[ENV_VARS.ACTOR_ID] = actorId;+ process.env[ENV_VARS.ACTOR_RUN_ID] = runId;++ const actsMock = sinon.mock(Apify.client.acts);+ actsMock.expects('metamorphRun')+ .withExactArgs({+ runId,+ actId: actorId,+ targetActorId,+ body: JSON.stringify(input, null, 2),+ contentType: 'application/json; charset=utf-8',+ build: undefined,+ })+ .once()+ .returns(Promise.resolve());++ await Apify.metamorph(targetActorId, input, { customAfterSleepMillis: 1 });++ delete process.env[ENV_VARS.ACTOR_ID];+ delete process.env[ENV_VARS.ACTOR_RUN_ID];++ actsMock.verify();+ actsMock.restore();+ });+});+describe('Apify.getApifyProxyUrl()', () => {it('should work', () => {process.env[ENV_VARS.PROXY_PASSWORD] = 'abc123';