import puppeteer from 'puppeteer-extra';
// add stealth plugin and use defaults (all evasion techniques)
import StealthPlugin from 'puppeteer-extra-plugin-stealth';
import locateChrome from 'locate-chrome';
import { getConfig } from '../shared/config';
puppeteer.use(StealthPlugin());
const CACHE = [];
export function inactivateBrowser(b) {
    const item = CACHE.find(x => x.browser === b);
    if (item) {
        item.active = false;
    }
}
export async function closeAllBrowsers() {
    for (const item of CACHE) {
        await item.browser.close();
    }
}
export async function getBrowser(proxy, headless = true) {
    const b = CACHE.find(item => {
        if (item.active) {
            return false;
        }
        if (proxy) {
            return item.proxy === proxy;
        }
        else if (item.proxy) {
            return false;
        }
        return true;
    });
    if (b) {
        return b.browser;
    }
    const executablePath = await locateChrome();
    // https://github.com/puppeteer/puppeteer/issues/745
    const config = {
        headless: true,
        args: getConfig('puppeteer-args').slice(0),
        timeout: 0,
        executablePath,
    };
    const item = { active: true, proxy };
    if (proxy) {
        config.args.push(`--proxy-server=${proxy}`);
    }
    item.browser = await puppeteer.launch({
        dumpio: true,
        ...config,
    });
    CACHE.push(item);
    return item.browser;
}
//# sourceMappingURL=browser.js.map