import * as plugins from './smartbrowser.plugins.js'; import * as interfaces from './interfaces/index.js'; /** * SmartBrowser */ export class SmartBrowser { public headlessBrowser: plugins.smartpuppeteer.puppeteer.Browser; public smartpdf: plugins.smartpdf.SmartPdf; /** * start the SmartBrowser instance */ public async start() { this.headlessBrowser = await plugins.smartpuppeteer.getEnvAwareBrowserInstance(); // SmartPdf is lazy-initialized only when PDF methods are called } /** * ensure SmartPdf is initialized (lazy) */ private async ensureSmartPdf() { if (!this.smartpdf) { this.smartpdf = new plugins.smartpdf.SmartPdf(); await this.smartpdf.start(this.headlessBrowser); } } /** * stop the SmartBrowser instance */ public async stop() { if (this.smartpdf) { await this.smartpdf.stop(); this.smartpdf = null; } await this.headlessBrowser.close(); } /** * create a pdf from page * @param urlArg */ public async pdfFromPage(urlArg: string): Promise { await this.ensureSmartPdf(); const result = await this.smartpdf.getFullWebsiteAsSinglePdf(urlArg); return result; } /** * make a screenshot from a page * @param urlArg */ public async screenshotFromPage(urlArg: string): Promise { const pageId = plugins.smartunique.shortId(); const page = await this.headlessBrowser.newPage(); await page.goto(urlArg, { waitUntil: 'networkidle2', }); const screenshotBuffer = (await page.screenshot({ encoding: 'binary', })) as Buffer; await page.close(); return { name: pageId, id: `${pageId}.js`, buffer: screenshotBuffer, }; } /** * evalutes an expression on a page * @param urlArg * @param funcArg */ public async evaluateOnPage(urlArg: string, funcArg: () => Promise) { const page = await this.headlessBrowser.newPage(); try { await page.goto(urlArg, { waitUntil: 'networkidle2', }); const result = await page.evaluate(funcArg); return result; } finally { try { await page.close(); } catch (e) { /* page may already be closed */ } } } } import { smartpuppeteer } from './smartbrowser.plugins.js'; export { smartpuppeteer };