From 040c7a9ce64160c442afb08fa2cbce1fe6a37773 Mon Sep 17 00:00:00 2001 From: karishmas6 Date: Wed, 31 Jul 2024 05:43:14 +0530 Subject: [PATCH] feat(core): spawn browser context & run workflow --- mx-interpreter/interpret.ts | 42 ++++++++++++++++++++++++++++++++++++- 1 file changed, 41 insertions(+), 1 deletion(-) diff --git a/mx-interpreter/interpret.ts b/mx-interpreter/interpret.ts index fc715008..d465312f 100644 --- a/mx-interpreter/interpret.ts +++ b/mx-interpreter/interpret.ts @@ -415,5 +415,45 @@ export default class Interpreter extends EventEmitter { } } - + /** + * Spawns a browser context and runs given workflow. + * \ + * Resolves after the playback is finished. + * @param {Page} [page] Page to run the workflow on. + * @param {ParamType} params Workflow specific, set of parameters + * for the `{$param: nameofparam}` fields. + */ + public async run(page: Page, params? : ParamType) : Promise { + if (this.stopper) { + throw new Error('This Interpreter is already running a workflow. To run another workflow, please, spawn another Interpreter.'); + } + /** + * `this.workflow` with the parameters initialized. + */ + this.initializedWorkflow = Preprocessor.initWorkflow(this.workflow, params); + + // @ts-ignore + if (await page.evaluate(() => !window.scrape)) { + page.context().addInitScript({ path: path.join(__dirname, 'browserSide', 'scraper.js') }); + } + + this.stopper = () => { + this.stopper = null; + }; + + this.concurrency.addJob(() => this.runLoop(page, this.initializedWorkflow!)); + + await this.concurrency.waitForCompletion(); + + this.stopper = null; + } + + public async stop() : Promise { + if (this.stopper) { + await this.stopper(); + this.stopper = null; + } else { + throw new Error('Cannot stop, there is no running workflow!'); + } + } } \ No newline at end of file