"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getHeadlessPool = void 0;
const tslib_1 = require("tslib");
const genericPool = tslib_1.__importStar(require("generic-pool"));
const env_1 = require("@things-factory/env");
try {
    var puppeteer = require('puppeteer');
}
catch (err) {
    env_1.logger.error(err);
}
var headlessPool;
function getHeadlessPool() {
    if (!headlessPool) {
        headlessPool = genericPool.createPool({
            create() {
                console.log('headless-pool-for-process about to create');
                return initializeChromium();
            },
            validate(browser) {
                return Promise.race([
                    new Promise(res => setTimeout(() => res(false), 1500)),
                    browser
                        //@ts-ignore
                        .version()
                        .then(_ => true)
                        .catch(_ => false)
                ]);
            },
            destroy(browser) {
                //@ts-ignore
                return browser.close();
            }
        }, {
            min: 2,
            max: 10,
            testOnBorrow: true,
            acquireTimeoutMillis: 15000
        });
    }
    return headlessPool;
}
exports.getHeadlessPool = getHeadlessPool;
const CHROMIUM_PATH = env_1.config.get('CHROMIUM_PATH');
async function initializeChromium() {
    try {
        if (!puppeteer) {
            return;
        }
        var launchSetting = {
            args: ['--hide-scrollbars', '--mute-audio', '--no-sandbox', '--use-gl=egl'],
            headless: 'new'
        };
        if (CHROMIUM_PATH) {
            launchSetting['executablePath'] = CHROMIUM_PATH;
        }
        const browser = await puppeteer.launch(launchSetting);
        return browser;
    }
    catch (err) {
        env_1.logger.error(err);
    }
}
//# sourceMappingURL=headless-pool-for-process.js.map