UNPKG

@sparticuz/chromium

Version:

Chromium Binary for Serverless Platforms

283 lines (282 loc) 12.9 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; const node_fs_1 = require("node:fs"); const follow_redirects_1 = require("follow-redirects"); const lambdafs_1 = __importDefault(require("./lambdafs")); const node_path_1 = require("node:path"); const node_url_1 = require("node:url"); const helper_1 = require("./helper"); const nodeMajorVersion = parseInt(process.versions.node.split(".")[0] ?? ""); // Setup the lambda environment if ((0, helper_1.isRunningInAwsLambda)(nodeMajorVersion)) { (0, helper_1.setupLambdaEnvironment)("/tmp/al2/lib"); } else if ((0, helper_1.isRunningInAwsLambdaNode20)(nodeMajorVersion)) { (0, helper_1.setupLambdaEnvironment)("/tmp/al2023/lib"); } class Chromium { /** * If true, the graphics stack and webgl is enabled, * If false, webgl will be disabled. * (If false, the swiftshader.tar.br file will also not extract) */ static graphicsMode = true; /** * Downloads or symlinks a custom font and returns its basename, patching the environment so that Chromium can find it. */ static font(input) { process.env["HOME"] ??= "/tmp"; if ((0, node_fs_1.existsSync)(`${process.env["HOME"]}/.fonts`) !== true) { (0, node_fs_1.mkdirSync)(`${process.env["HOME"]}/.fonts`); } return new Promise((resolve, reject) => { if (/^https?:[/][/]/i.test(input) !== true) { input = `file://${input}`; } const url = new node_url_1.URL(input); const output = `${process.env["HOME"]}/.fonts/${url.pathname .split("/") .pop()}`; if ((0, node_fs_1.existsSync)(output) === true) { return resolve(output.split("/").pop()); } if (url.protocol === "file:") { (0, node_fs_1.access)(url.pathname, (error) => { if (error != null) { return reject(error); } (0, node_fs_1.symlink)(url.pathname, output, (error) => { return error != null ? reject(error) : resolve(url.pathname.split("/").pop()); }); }); } else { follow_redirects_1.https.get(input, (response) => { if (response.statusCode !== 200) { return reject(`Unexpected status code: ${response.statusCode}.`); } const stream = (0, node_fs_1.createWriteStream)(output); stream.once("error", (error) => { return reject(error); }); response.on("data", (chunk) => { stream.write(chunk); }); response.once("end", () => { stream.end(() => { return resolve(url.pathname.split("/").pop()); }); }); }); } }); } /** * Returns a list of additional Chromium flags recommended for serverless environments. * The canonical list of flags can be found on https://peter.sh/experiments/chromium-command-line-switches/. */ static get args() { /** * These are the default args in puppeteer. * https://github.com/puppeteer/puppeteer/blob/3a31070d054fa3cd8116ca31c578807ed8d6f987/packages/puppeteer-core/src/node/ChromeLauncher.ts#L185 */ const puppeteerFlags = [ "--allow-pre-commit-input", "--disable-background-networking", "--disable-background-timer-throttling", "--disable-backgrounding-occluded-windows", "--disable-breakpad", "--disable-client-side-phishing-detection", "--disable-component-extensions-with-background-pages", "--disable-component-update", "--disable-default-apps", "--disable-dev-shm-usage", "--disable-extensions", "--disable-hang-monitor", "--disable-ipc-flooding-protection", "--disable-popup-blocking", "--disable-prompt-on-repost", "--disable-renderer-backgrounding", "--disable-sync", "--enable-automation", // TODO(sadym): remove '--enable-blink-features=IdleDetection' once // IdleDetection is turned on by default. "--enable-blink-features=IdleDetection", "--export-tagged-pdf", "--force-color-profile=srgb", "--metrics-recording-only", "--no-first-run", "--password-store=basic", "--use-mock-keychain", ]; const puppeteerDisableFeatures = [ "Translate", "BackForwardCache", // AcceptCHFrame disabled because of crbug.com/1348106. "AcceptCHFrame", "MediaRouter", "OptimizationHints", ]; const puppeteerEnableFeatures = ["NetworkServiceInProcess2"]; const chromiumFlags = [ "--disable-domain-reliability", // https://github.com/GoogleChrome/chrome-launcher/blob/main/docs/chrome-flags-for-tools.md#background-networking "--disable-print-preview", // https://source.chromium.org/search?q=lang:cpp+symbol:kDisablePrintPreview&ss=chromium "--disable-speech-api", // https://source.chromium.org/search?q=lang:cpp+symbol:kDisableSpeechAPI&ss=chromium "--disk-cache-size=33554432", // https://source.chromium.org/search?q=lang:cpp+symbol:kDiskCacheSize&ss=chromium "--mute-audio", // https://source.chromium.org/search?q=lang:cpp+symbol:kMuteAudio&ss=chromium "--no-default-browser-check", // https://source.chromium.org/search?q=lang:cpp+symbol:kNoDefaultBrowserCheck&ss=chromium "--no-pings", // https://source.chromium.org/search?q=lang:cpp+symbol:kNoPings&ss=chromium "--single-process", // Needs to be single-process to avoid `prctl(PR_SET_NO_NEW_PRIVS) failed` error "--font-render-hinting=none", // https://github.com/puppeteer/puppeteer/issues/2410#issuecomment-560573612 ]; const chromiumDisableFeatures = [ "AudioServiceOutOfProcess", "IsolateOrigins", "site-per-process", ]; const chromiumEnableFeatures = ["SharedArrayBuffer"]; const graphicsFlags = [ "--hide-scrollbars", // https://source.chromium.org/search?q=lang:cpp+symbol:kHideScrollbars&ss=chromium "--ignore-gpu-blocklist", // https://source.chromium.org/search?q=lang:cpp+symbol:kIgnoreGpuBlocklist&ss=chromium "--in-process-gpu", // https://source.chromium.org/search?q=lang:cpp+symbol:kInProcessGPU&ss=chromium "--window-size=1920,1080", // https://source.chromium.org/search?q=lang:cpp+symbol:kWindowSize&ss=chromium ]; // https://chromium.googlesource.com/chromium/src/+/main/docs/gpu/swiftshader.md this.graphics ? graphicsFlags.push( // As the unsafe WebGL fallback, SwANGLE (ANGLE + SwiftShader Vulkan) "--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader") : graphicsFlags.push("--disable-webgl"); const insecureFlags = [ "--allow-running-insecure-content", // https://source.chromium.org/search?q=lang:cpp+symbol:kAllowRunningInsecureContent&ss=chromium "--disable-setuid-sandbox", // https://source.chromium.org/search?q=lang:cpp+symbol:kDisableSetuidSandbox&ss=chromium "--disable-site-isolation-trials", // https://source.chromium.org/search?q=lang:cpp+symbol:kDisableSiteIsolation&ss=chromium "--disable-web-security", // https://source.chromium.org/search?q=lang:cpp+symbol:kDisableWebSecurity&ss=chromium "--no-sandbox", // https://source.chromium.org/search?q=lang:cpp+symbol:kNoSandbox&ss=chromium "--no-zygote", // https://source.chromium.org/search?q=lang:cpp+symbol:kNoZygote&ss=chromium ]; const headlessFlags = [ this.headless === "shell" ? "--headless='shell'" : "--headless", ]; return [ ...puppeteerFlags, ...chromiumFlags, `--disable-features=${[ ...puppeteerDisableFeatures, ...chromiumDisableFeatures, ].join(",")}`, `--enable-features=${[ ...puppeteerEnableFeatures, ...chromiumEnableFeatures, ].join(",")}`, ...graphicsFlags, ...insecureFlags, ...headlessFlags, ]; } /** * Returns sensible default viewport settings for serverless environments. */ static get defaultViewport() { return { deviceScaleFactor: 1, hasTouch: false, height: 1080, isLandscape: true, isMobile: false, width: 1920, }; } /** * Inflates the included version of Chromium * @param input The location of the `bin` folder * @returns The path to the `chromium` binary */ static async executablePath(input) { /** * If the `chromium` binary already exists in /tmp/chromium, return it. */ if ((0, node_fs_1.existsSync)("/tmp/chromium") === true) { return Promise.resolve("/tmp/chromium"); } /** * If input is a valid URL, download and extract the file. It will extract to /tmp/chromium-pack * and executablePath will be recursively called on that location, which will then extract * the brotli files to the correct locations */ if (input && (0, helper_1.isValidUrl)(input)) { return this.executablePath(await (0, helper_1.downloadAndExtract)(input)); } /** * If input is defined, use that as the location of the brotli files, * otherwise, the default location is ../bin. * A custom location is needed for workflows that using custom packaging. */ input ??= (0, node_path_1.join)(__dirname, "..", "bin"); /** * If the input directory doesn't exist, throw an error. */ if (!(0, node_fs_1.existsSync)(input)) { throw new Error(`The input directory "${input}" does not exist.`); } // Extract the required files const promises = [ lambdafs_1.default.inflate(`${input}/chromium.br`), lambdafs_1.default.inflate(`${input}/fonts.tar.br`), lambdafs_1.default.inflate(`${input}/swiftshader.tar.br`), ]; if ((0, helper_1.isRunningInAwsLambda)(nodeMajorVersion)) { // If running in AWS Lambda, extract more required files promises.push(lambdafs_1.default.inflate(`${input}/al2.tar.br`)); } if ((0, helper_1.isRunningInAwsLambdaNode20)(nodeMajorVersion)) { promises.push(lambdafs_1.default.inflate(`${input}/al2023.tar.br`)); } // Await all extractions const result = await Promise.all(promises); // Returns the first result of the promise, which is the location of the `chromium` binary return result.shift(); } /** * Returns the headless mode. * "shell" means the `chrome-headless-shell` headless mode. * @returns "shell" */ static get headless() { return "shell"; } /** * Sets the headless mode. * "shell" means the 'old' (legacy, chromium < 112) headless mode. * `true` means the 'new' headless mode. * https://developer.chrome.com/articles/new-headless/#try-out-the-new-headless * @deprecated 'New' headless mode will not be coming to chrome-headless-shell */ static set setHeadlessMode(_value) { console.warn("setHeadlessMode is deprecated. The headless mode is set to 'shell'."); } /** * Returns whether the graphics stack is enabled or disabled * @returns boolean */ static get graphics() { return this.graphicsMode; } /** * Sets whether the graphics stack is enabled or disabled. * @param true means the stack is enabled. WebGL will work. * @param false means that the stack is disabled. WebGL will not work. * @default true */ static set setGraphicsMode(value) { if (typeof value !== "boolean") { throw new Error(`Graphics mode must be a boolean, you entered '${value}'`); } this.graphicsMode = value; } } module.exports = Chromium;