Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@puppeteer/browsers

Package Overview
Dependencies
Maintainers
2
Versions
47
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@puppeteer/browsers - npm Package Compare versions

Comparing version 0.0.5 to 0.1.0

lib/cjs/main.d.ts

4

lib/cjs/browsers/browsers.d.ts

@@ -18,3 +18,3 @@ /**

import * as firefox from './firefox.js';
import { Browser, BrowserPlatform } from './types.js';
import { Browser, BrowserPlatform, ChromeReleaseChannel, ProfileOptions } from './types.js';
export declare const downloadUrls: {

@@ -32,2 +32,4 @@ chrome: typeof chrome.resolveDownloadUrl;

export declare function resolveBuildId(browser: Browser, platform: BrowserPlatform, tag: string): Promise<string>;
export declare function createProfile(browser: Browser, opts: ProfileOptions): Promise<void>;
export declare function resolveSystemExecutablePath(browser: Browser, platform: BrowserPlatform, channel: ChromeReleaseChannel): string;
//# sourceMappingURL=browsers.d.ts.map

@@ -41,3 +41,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveBuildId = exports.BrowserPlatform = exports.Browser = exports.executablePathByBrowser = exports.downloadUrls = void 0;
exports.resolveSystemExecutablePath = exports.createProfile = exports.resolveBuildId = exports.BrowserPlatform = exports.Browser = exports.executablePathByBrowser = exports.downloadUrls = void 0;
const chrome = __importStar(require("./chrome.js"));

@@ -76,2 +76,22 @@ const firefox = __importStar(require("./firefox.js"));

exports.resolveBuildId = resolveBuildId;
async function createProfile(browser, opts) {
switch (browser) {
case types_js_1.Browser.FIREFOX:
return await firefox.createProfile(opts);
case types_js_1.Browser.CHROME:
case types_js_1.Browser.CHROMIUM:
throw new Error(`Profile creation is not support for ${browser} yet`);
}
}
exports.createProfile = createProfile;
function resolveSystemExecutablePath(browser, platform, channel) {
switch (browser) {
case types_js_1.Browser.FIREFOX:
throw new Error('System browser detection is not supported for Firefox yet.');
case types_js_1.Browser.CHROME:
case types_js_1.Browser.CHROMIUM:
return chrome.resolveSystemExecutablePath(platform, channel);
}
}
exports.resolveSystemExecutablePath = resolveSystemExecutablePath;
//# sourceMappingURL=browsers.js.map

@@ -16,6 +16,7 @@ /**

*/
import { BrowserPlatform } from './types.js';
import { BrowserPlatform, ChromeReleaseChannel } from './types.js';
export declare function resolveDownloadUrl(platform: BrowserPlatform, buildId: string, baseUrl?: string): string;
export declare function relativeExecutablePath(platform: BrowserPlatform, _buildId: string): string;
export declare function resolveBuildId(platform: BrowserPlatform, _channel?: 'latest'): Promise<string>;
export declare function resolveSystemExecutablePath(platform: BrowserPlatform, channel: ChromeReleaseChannel): string;
//# sourceMappingURL=chrome.d.ts.map

@@ -21,3 +21,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveBuildId = exports.relativeExecutablePath = exports.resolveDownloadUrl = void 0;
exports.resolveSystemExecutablePath = exports.resolveBuildId = exports.relativeExecutablePath = exports.resolveDownloadUrl = void 0;
const path_1 = __importDefault(require("path"));

@@ -97,2 +97,41 @@ const httpUtil_js_1 = require("../httpUtil.js");

exports.resolveBuildId = resolveBuildId;
function resolveSystemExecutablePath(platform, channel) {
switch (platform) {
case types_js_1.BrowserPlatform.WIN64:
case types_js_1.BrowserPlatform.WIN32:
switch (channel) {
case types_js_1.ChromeReleaseChannel.STABLE:
return `${process.env['PROGRAMFILES']}\\Google\\Chrome\\Application\\chrome.exe`;
case types_js_1.ChromeReleaseChannel.BETA:
return `${process.env['PROGRAMFILES']}\\Google\\Chrome Beta\\Application\\chrome.exe`;
case types_js_1.ChromeReleaseChannel.CANARY:
return `${process.env['PROGRAMFILES']}\\Google\\Chrome SxS\\Application\\chrome.exe`;
case types_js_1.ChromeReleaseChannel.DEV:
return `${process.env['PROGRAMFILES']}\\Google\\Chrome Dev\\Application\\chrome.exe`;
}
case types_js_1.BrowserPlatform.MAC_ARM:
case types_js_1.BrowserPlatform.MAC:
switch (channel) {
case types_js_1.ChromeReleaseChannel.STABLE:
return '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
case types_js_1.ChromeReleaseChannel.BETA:
return '/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta';
case types_js_1.ChromeReleaseChannel.CANARY:
return '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary';
case types_js_1.ChromeReleaseChannel.DEV:
return '/Applications/Google Chrome Dev.app/Contents/MacOS/Google Chrome Dev';
}
case types_js_1.BrowserPlatform.LINUX:
switch (channel) {
case types_js_1.ChromeReleaseChannel.STABLE:
return '/opt/google/chrome/chrome';
case types_js_1.ChromeReleaseChannel.BETA:
return '/opt/google/chrome-beta/chrome';
case types_js_1.ChromeReleaseChannel.DEV:
return '/opt/google/chrome-unstable/chrome';
}
}
throw new Error(`Unable to detect browser executable path for '${channel}' on ${platform}.`);
}
exports.resolveSystemExecutablePath = resolveSystemExecutablePath;
//# sourceMappingURL=chrome.js.map

@@ -16,6 +16,7 @@ /**

*/
import { BrowserPlatform } from './types.js';
import { BrowserPlatform, ProfileOptions } from './types.js';
export declare function resolveDownloadUrl(platform: BrowserPlatform, buildId: string, baseUrl?: string): string;
export declare function relativeExecutablePath(platform: BrowserPlatform, _buildId: string): string;
export declare function resolveBuildId(channel?: 'FIREFOX_NIGHTLY'): Promise<string>;
export declare function createProfile(options: ProfileOptions): Promise<void>;
//# sourceMappingURL=firefox.d.ts.map

@@ -21,3 +21,4 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveBuildId = exports.relativeExecutablePath = exports.resolveDownloadUrl = void 0;
exports.createProfile = exports.resolveBuildId = exports.relativeExecutablePath = exports.resolveDownloadUrl = void 0;
const fs_1 = __importDefault(require("fs"));
const path_1 = __importDefault(require("path"));

@@ -81,2 +82,202 @@ const httpUtil_js_1 = require("../httpUtil.js");

exports.resolveBuildId = resolveBuildId;
async function createProfile(options) {
if (!fs_1.default.existsSync(options.path)) {
await fs_1.default.promises.mkdir(options.path, {
recursive: true,
});
}
await writePreferences({
preferences: {
...defaultProfilePreferences(options.preferences),
...options.preferences,
},
path: options.path,
});
}
exports.createProfile = createProfile;
function defaultProfilePreferences(extraPrefs) {
const server = 'dummy.test';
const defaultPrefs = {
// Make sure Shield doesn't hit the network.
'app.normandy.api_url': '',
// Disable Firefox old build background check
'app.update.checkInstallTime': false,
// Disable automatically upgrading Firefox
'app.update.disabledForTesting': true,
// Increase the APZ content response timeout to 1 minute
'apz.content_response_timeout': 60000,
// Prevent various error message on the console
// jest-puppeteer asserts that no error message is emitted by the console
'browser.contentblocking.features.standard': '-tp,tpPrivate,cookieBehavior0,-cm,-fp',
// Enable the dump function: which sends messages to the system
// console
// https://bugzilla.mozilla.org/show_bug.cgi?id=1543115
'browser.dom.window.dump.enabled': true,
// Disable topstories
'browser.newtabpage.activity-stream.feeds.system.topstories': false,
// Always display a blank page
'browser.newtabpage.enabled': false,
// Background thumbnails in particular cause grief: and disabling
// thumbnails in general cannot hurt
'browser.pagethumbnails.capturing_disabled': true,
// Disable safebrowsing components.
'browser.safebrowsing.blockedURIs.enabled': false,
'browser.safebrowsing.downloads.enabled': false,
'browser.safebrowsing.malware.enabled': false,
'browser.safebrowsing.passwords.enabled': false,
'browser.safebrowsing.phishing.enabled': false,
// Disable updates to search engines.
'browser.search.update': false,
// Do not restore the last open set of tabs if the browser has crashed
'browser.sessionstore.resume_from_crash': false,
// Skip check for default browser on startup
'browser.shell.checkDefaultBrowser': false,
// Disable newtabpage
'browser.startup.homepage': 'about:blank',
// Do not redirect user when a milstone upgrade of Firefox is detected
'browser.startup.homepage_override.mstone': 'ignore',
// Start with a blank page about:blank
'browser.startup.page': 0,
// Do not allow background tabs to be zombified on Android: otherwise for
// tests that open additional tabs: the test harness tab itself might get
// unloaded
'browser.tabs.disableBackgroundZombification': false,
// Do not warn when closing all other open tabs
'browser.tabs.warnOnCloseOtherTabs': false,
// Do not warn when multiple tabs will be opened
'browser.tabs.warnOnOpen': false,
// Disable the UI tour.
'browser.uitour.enabled': false,
// Turn off search suggestions in the location bar so as not to trigger
// network connections.
'browser.urlbar.suggest.searches': false,
// Disable first run splash page on Windows 10
'browser.usedOnWindows10.introURL': '',
// Do not warn on quitting Firefox
'browser.warnOnQuit': false,
// Defensively disable data reporting systems
'datareporting.healthreport.documentServerURI': `http://${server}/dummy/healthreport/`,
'datareporting.healthreport.logging.consoleEnabled': false,
'datareporting.healthreport.service.enabled': false,
'datareporting.healthreport.service.firstRun': false,
'datareporting.healthreport.uploadEnabled': false,
// Do not show datareporting policy notifications which can interfere with tests
'datareporting.policy.dataSubmissionEnabled': false,
'datareporting.policy.dataSubmissionPolicyBypassNotification': true,
// DevTools JSONViewer sometimes fails to load dependencies with its require.js.
// This doesn't affect Puppeteer but spams console (Bug 1424372)
'devtools.jsonview.enabled': false,
// Disable popup-blocker
'dom.disable_open_during_load': false,
// Enable the support for File object creation in the content process
// Required for |Page.setFileInputFiles| protocol method.
'dom.file.createInChild': true,
// Disable the ProcessHangMonitor
'dom.ipc.reportProcessHangs': false,
// Disable slow script dialogues
'dom.max_chrome_script_run_time': 0,
'dom.max_script_run_time': 0,
// Only load extensions from the application and user profile
// AddonManager.SCOPE_PROFILE + AddonManager.SCOPE_APPLICATION
'extensions.autoDisableScopes': 0,
'extensions.enabledScopes': 5,
// Disable metadata caching for installed add-ons by default
'extensions.getAddons.cache.enabled': false,
// Disable installing any distribution extensions or add-ons.
'extensions.installDistroAddons': false,
// Disabled screenshots extension
'extensions.screenshots.disabled': true,
// Turn off extension updates so they do not bother tests
'extensions.update.enabled': false,
// Turn off extension updates so they do not bother tests
'extensions.update.notifyUser': false,
// Make sure opening about:addons will not hit the network
'extensions.webservice.discoverURL': `http://${server}/dummy/discoveryURL`,
// Temporarily force disable BFCache in parent (https://bit.ly/bug-1732263)
'fission.bfcacheInParent': false,
// Force all web content to use a single content process
'fission.webContentIsolationStrategy': 0,
// Allow the application to have focus even it runs in the background
'focusmanager.testmode': true,
// Disable useragent updates
'general.useragent.updates.enabled': false,
// Always use network provider for geolocation tests so we bypass the
// macOS dialog raised by the corelocation provider
'geo.provider.testing': true,
// Do not scan Wifi
'geo.wifi.scan': false,
// No hang monitor
'hangmonitor.timeout': 0,
// Show chrome errors and warnings in the error console
'javascript.options.showInConsole': true,
// Disable download and usage of OpenH264: and Widevine plugins
'media.gmp-manager.updateEnabled': false,
// Prevent various error message on the console
// jest-puppeteer asserts that no error message is emitted by the console
'network.cookie.cookieBehavior': 0,
// Disable experimental feature that is only available in Nightly
'network.cookie.sameSite.laxByDefault': false,
// Do not prompt for temporary redirects
'network.http.prompt-temp-redirect': false,
// Disable speculative connections so they are not reported as leaking
// when they are hanging around
'network.http.speculative-parallel-limit': 0,
// Do not automatically switch between offline and online
'network.manage-offline-status': false,
// Make sure SNTP requests do not hit the network
'network.sntp.pools': server,
// Disable Flash.
'plugin.state.flash': 0,
'privacy.trackingprotection.enabled': false,
// Can be removed once Firefox 89 is no longer supported
// https://bugzilla.mozilla.org/show_bug.cgi?id=1710839
'remote.enabled': true,
// Don't do network connections for mitm priming
'security.certerrors.mitm.priming.enabled': false,
// Local documents have access to all other local documents,
// including directory listings
'security.fileuri.strict_origin_policy': false,
// Do not wait for the notification button security delay
'security.notification_enable_delay': 0,
// Ensure blocklist updates do not hit the network
'services.settings.server': `http://${server}/dummy/blocklist/`,
// Do not automatically fill sign-in forms with known usernames and
// passwords
'signon.autofillForms': false,
// Disable password capture, so that tests that include forms are not
// influenced by the presence of the persistent doorhanger notification
'signon.rememberSignons': false,
// Disable first-run welcome page
'startup.homepage_welcome_url': 'about:blank',
// Disable first-run welcome page
'startup.homepage_welcome_url.additional': '',
// Disable browser animations (tabs, fullscreen, sliding alerts)
'toolkit.cosmeticAnimations.enabled': false,
// Prevent starting into safe mode after application crashes
'toolkit.startup.max_resumed_crashes': -1,
};
return Object.assign(defaultPrefs, extraPrefs);
}
/**
* Populates the user.js file with custom preferences as needed to allow
* Firefox's CDP support to properly function. These preferences will be
* automatically copied over to prefs.js during startup of Firefox. To be
* able to restore the original values of preferences a backup of prefs.js
* will be created.
*
* @param prefs - List of preferences to add.
* @param profilePath - Firefox profile to write the preferences to.
*/
async function writePreferences(options) {
const lines = Object.entries(options.preferences).map(([key, value]) => {
return `user_pref(${JSON.stringify(key)}, ${JSON.stringify(value)});`;
});
await fs_1.default.promises.writeFile(path_1.default.join(options.path, 'user.js'), lines.join('\n'));
// Create a backup of the preferences file if it already exitsts.
const prefsPath = path_1.default.join(options.path, 'prefs.js');
if (fs_1.default.existsSync(prefsPath)) {
const prefsBackupPath = path_1.default.join(options.path, 'prefs.js.puppeteer');
await fs_1.default.promises.copyFile(prefsPath, prefsBackupPath);
}
}
//# sourceMappingURL=firefox.js.map

@@ -45,2 +45,12 @@ /**

}
export interface ProfileOptions {
preferences: Record<string, unknown>;
path: string;
}
export declare enum ChromeReleaseChannel {
STABLE = "stable",
DEV = "dev",
CANARY = "canary",
BETA = "beta"
}
//# sourceMappingURL=types.d.ts.map

@@ -41,3 +41,3 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.BrowserTag = exports.downloadUrls = exports.BrowserPlatform = exports.Browser = void 0;
exports.ChromeReleaseChannel = exports.BrowserTag = exports.downloadUrls = exports.BrowserPlatform = exports.Browser = void 0;
const chrome = __importStar(require("./chrome.js"));

@@ -75,2 +75,9 @@ const firefox = __importStar(require("./firefox.js"));

})(BrowserTag = exports.BrowserTag || (exports.BrowserTag = {}));
var ChromeReleaseChannel;
(function (ChromeReleaseChannel) {
ChromeReleaseChannel["STABLE"] = "stable";
ChromeReleaseChannel["DEV"] = "dev";
ChromeReleaseChannel["CANARY"] = "canary";
ChromeReleaseChannel["BETA"] = "beta";
})(ChromeReleaseChannel = exports.ChromeReleaseChannel || (exports.ChromeReleaseChannel = {}));
//# sourceMappingURL=types.js.map

@@ -31,3 +31,3 @@ "use strict";

};
var _CLI_instances, _CLI_cachePath, _CLI_parseBrowser, _CLI_parseBuildId, _CLI_toMegabytes, _CLI_makeProgressCallback;
var _CLI_instances, _CLI_cachePath, _CLI_defineBrowserParameter, _CLI_definePlatformParameter, _CLI_definePathParameter, _CLI_parseBrowser, _CLI_parseBuildId, _CLI_toMegabytes, _CLI_makeProgressCallback;
Object.defineProperty(exports, "__esModule", { value: true });

@@ -52,23 +52,5 @@ exports.CLI = void 0;

.command('install <browser>', 'Download and install the specified browser', yargs => {
yargs.positional('browser', {
description: 'The browser version',
type: 'string',
coerce: (opt) => {
return {
name: __classPrivateFieldGet(this, _CLI_instances, "m", _CLI_parseBrowser).call(this, opt),
buildId: __classPrivateFieldGet(this, _CLI_instances, "m", _CLI_parseBuildId).call(this, opt),
};
},
});
yargs.option('platform', {
type: 'string',
desc: 'Platform that the binary needs to be compatible with.',
choices: Object.values(types_js_1.BrowserPlatform),
defaultDescription: 'Auto-detected by default.',
});
yargs.option('path', {
type: 'string',
desc: 'Path where the browsers will be downloaded to and installed from',
default: process.cwd(),
});
__classPrivateFieldGet(this, _CLI_instances, "m", _CLI_defineBrowserParameter).call(this, yargs);
__classPrivateFieldGet(this, _CLI_instances, "m", _CLI_definePlatformParameter).call(this, yargs);
__classPrivateFieldGet(this, _CLI_instances, "m", _CLI_definePathParameter).call(this, yargs);
}, async (argv) => {

@@ -97,37 +79,31 @@ var _a, _b, _c;

.command('launch <browser>', 'Launch the specified browser', yargs => {
yargs.positional('browser', {
description: 'The browser version',
type: 'string',
coerce: (opt) => {
return {
name: __classPrivateFieldGet(this, _CLI_instances, "m", _CLI_parseBrowser).call(this, opt),
buildId: __classPrivateFieldGet(this, _CLI_instances, "m", _CLI_parseBuildId).call(this, opt),
};
},
});
__classPrivateFieldGet(this, _CLI_instances, "m", _CLI_defineBrowserParameter).call(this, yargs);
__classPrivateFieldGet(this, _CLI_instances, "m", _CLI_definePlatformParameter).call(this, yargs);
__classPrivateFieldGet(this, _CLI_instances, "m", _CLI_definePathParameter).call(this, yargs);
yargs.option('detached', {
type: 'boolean',
desc: 'Whether to detach the child process.',
desc: 'Detach the child process.',
default: false,
});
yargs.option('platform', {
type: 'string',
desc: 'Platform that the binary needs to be compatible with.',
choices: Object.values(types_js_1.BrowserPlatform),
defaultDescription: 'Auto-detected by default.',
yargs.option('system', {
type: 'boolean',
desc: 'Search for a browser installed on the system instead of the cache folder.',
default: false,
});
yargs.option('path', {
type: 'string',
desc: 'Path where the browsers will be downloaded to and installed from',
default: process.cwd(),
});
}, async (argv) => {
var _a;
const args = argv;
const executablePath = (0, launcher_js_1.computeExecutablePath)({
browser: args.browser.name,
buildId: args.browser.buildId,
cacheDir: (_a = args.path) !== null && _a !== void 0 ? _a : __classPrivateFieldGet(this, _CLI_cachePath, "f"),
platform: args.platform,
});
const executablePath = args.system
? (0, launcher_js_1.computeSystemExecutablePath)({
browser: args.browser.name,
// TODO: throw an error if not a ChromeReleaseChannel is provided.
channel: args.browser.buildId,
platform: args.platform,
})
: (0, launcher_js_1.computeExecutablePath)({
browser: args.browser.name,
buildId: args.browser.buildId,
cacheDir: (_a = args.path) !== null && _a !== void 0 ? _a : __classPrivateFieldGet(this, _CLI_cachePath, "f"),
platform: args.platform,
});
(0, launcher_js_1.launch)({

@@ -144,3 +120,27 @@ executablePath,

exports.CLI = CLI;
_CLI_cachePath = new WeakMap(), _CLI_instances = new WeakSet(), _CLI_parseBrowser = function _CLI_parseBrowser(version) {
_CLI_cachePath = new WeakMap(), _CLI_instances = new WeakSet(), _CLI_defineBrowserParameter = function _CLI_defineBrowserParameter(yargs) {
yargs.positional('browser', {
description: 'The browser version',
type: 'string',
coerce: (opt) => {
return {
name: __classPrivateFieldGet(this, _CLI_instances, "m", _CLI_parseBrowser).call(this, opt),
buildId: __classPrivateFieldGet(this, _CLI_instances, "m", _CLI_parseBuildId).call(this, opt),
};
},
});
}, _CLI_definePlatformParameter = function _CLI_definePlatformParameter(yargs) {
yargs.option('platform', {
type: 'string',
desc: 'Platform that the binary needs to be compatible with.',
choices: Object.values(types_js_1.BrowserPlatform),
defaultDescription: 'Auto-detected by default.',
});
}, _CLI_definePathParameter = function _CLI_definePathParameter(yargs) {
yargs.option('path', {
type: 'string',
desc: 'Path to the root folder for the browser downloads and installation',
default: process.cwd(),
});
}, _CLI_parseBrowser = function _CLI_parseBrowser(version) {
return version.split('@').shift();

@@ -147,0 +147,0 @@ }, _CLI_parseBuildId = function _CLI_parseBuildId(version) {

@@ -18,2 +18,3 @@ /**

import { Browser, BrowserPlatform } from './browsers/browsers.js';
import { ChromeReleaseChannel } from './browsers/types.js';
/**

@@ -38,3 +39,3 @@ * @public

/**
* Determines which buildId to dowloand. BuildId should uniquely identify
* Determines which buildId to download. BuildId should uniquely identify
* binaries and they are used for caching.

@@ -45,2 +46,22 @@ */

export declare function computeExecutablePath(options: Options): string;
/**
* @public
*/
export interface SystemOptions {
/**
* Determines which platform the browser will be suited for.
*
* @defaultValue Auto-detected.
*/
platform?: BrowserPlatform;
/**
* Determines which browser to fetch.
*/
browser: Browser;
/**
* Release channel to look for on the system.
*/
channel: ChromeReleaseChannel;
}
export declare function computeSystemExecutablePath(options: SystemOptions): string;
type LaunchOptions = {

@@ -58,2 +79,4 @@ executablePath: string;

export declare function launch(opts: LaunchOptions): Process;
export declare const CDP_WEBSOCKET_ENDPOINT_REGEX: RegExp;
export declare const WEBDRIVER_BIDI_WEBSOCKET_ENDPOINT_REGEX: RegExp;
declare class Process {

@@ -64,2 +87,3 @@ #private;

kill(): void;
waitForLineOutput(regex: RegExp, timeout?: number): Promise<string>;
}

@@ -66,0 +90,0 @@ /**

@@ -33,6 +33,8 @@ "use strict";

Object.defineProperty(exports, "__esModule", { value: true });
exports.isErrnoException = exports.isErrorLike = exports.launch = exports.computeExecutablePath = void 0;
exports.isErrnoException = exports.isErrorLike = exports.WEBDRIVER_BIDI_WEBSOCKET_ENDPOINT_REGEX = exports.CDP_WEBSOCKET_ENDPOINT_REGEX = exports.launch = exports.computeSystemExecutablePath = exports.computeExecutablePath = void 0;
const child_process_1 = __importDefault(require("child_process"));
const fs_1 = require("fs");
const os_1 = __importDefault(require("os"));
const path_1 = __importDefault(require("path"));
const readline_1 = __importDefault(require("readline"));
const browsers_js_1 = require("./browsers/browsers.js");

@@ -53,2 +55,18 @@ const CacheStructure_js_1 = require("./CacheStructure.js");

exports.computeExecutablePath = computeExecutablePath;
function computeSystemExecutablePath(options) {
var _a;
(_a = options.platform) !== null && _a !== void 0 ? _a : (options.platform = (0, detectPlatform_js_1.detectBrowserPlatform)());
if (!options.platform) {
throw new Error(`Cannot download a binary for the provided platform: ${os_1.default.platform()} (${os_1.default.arch()})`);
}
const path = (0, browsers_js_1.resolveSystemExecutablePath)(options.browser, options.platform, options.channel);
try {
(0, fs_1.accessSync)(path);
}
catch (error) {
throw new Error(`Could not find Google Chrome executable for channel '${options.channel}' at '${path}'.`);
}
return path;
}
exports.computeSystemExecutablePath = computeSystemExecutablePath;
function launch(opts) {

@@ -58,2 +76,4 @@ return new Process(opts);

exports.launch = launch;
exports.CDP_WEBSOCKET_ENDPOINT_REGEX = /^DevTools listening on (ws:\/\/.*)$/;
exports.WEBDRIVER_BIDI_WEBSOCKET_ENDPOINT_REGEX = /^WebDriver BiDi listening on (ws:\/\/.*)$/;
class Process {

@@ -172,2 +192,46 @@ constructor(opts) {

}
waitForLineOutput(regex, timeout) {
if (!__classPrivateFieldGet(this, _Process_browserProcess, "f").stderr) {
throw new Error('`browserProcess` does not have stderr.');
}
const rl = readline_1.default.createInterface(__classPrivateFieldGet(this, _Process_browserProcess, "f").stderr);
let stderr = '';
return new Promise((resolve, reject) => {
rl.on('line', onLine);
rl.on('close', onClose);
__classPrivateFieldGet(this, _Process_browserProcess, "f").on('exit', onClose);
__classPrivateFieldGet(this, _Process_browserProcess, "f").on('error', onClose);
const timeoutId = timeout ? setTimeout(onTimeout, timeout) : 0;
const cleanup = () => {
if (timeoutId) {
clearTimeout(timeoutId);
}
rl.off('line', onLine);
rl.off('close', onClose);
__classPrivateFieldGet(this, _Process_browserProcess, "f").off('exit', onClose);
__classPrivateFieldGet(this, _Process_browserProcess, "f").off('error', onClose);
};
function onClose(error) {
cleanup();
reject(new Error([
`Failed to launch the browser process!${error ? ' ' + error.message : ''}`,
stderr,
].join('\n')));
}
function onTimeout() {
cleanup();
reject(new Error(`Timed out after ${timeout} ms while waiting for the WS endpoint URL to appear in stdout!`));
}
function onLine(line) {
stderr += line + '\n';
const match = line.match(regex);
if (!match) {
return;
}
cleanup();
// The RegExp matches, so this will obviously exist.
resolve(match[1]);
}
});
}
}

@@ -174,0 +238,0 @@ _Process_executablePath = new WeakMap(), _Process_args = new WeakMap(), _Process_browserProcess = new WeakMap(), _Process_exited = new WeakMap(), _Process_browserProcessExiting = new WeakMap(), _Process_onDriverProcessExit = new WeakMap(), _Process_onDriverProcessSignal = new WeakMap(), _Process_instances = new WeakSet(), _Process_configureStdio = function _Process_configureStdio(opts) {

@@ -18,3 +18,3 @@ /**

import * as firefox from './firefox.js';
import { Browser, BrowserPlatform } from './types.js';
import { Browser, BrowserPlatform, ChromeReleaseChannel, ProfileOptions } from './types.js';
export declare const downloadUrls: {

@@ -32,2 +32,4 @@ chrome: typeof chrome.resolveDownloadUrl;

export declare function resolveBuildId(browser: Browser, platform: BrowserPlatform, tag: string): Promise<string>;
export declare function createProfile(browser: Browser, opts: ProfileOptions): Promise<void>;
export declare function resolveSystemExecutablePath(browser: Browser, platform: BrowserPlatform, channel: ChromeReleaseChannel): string;
//# sourceMappingURL=browsers.d.ts.map

@@ -18,3 +18,3 @@ /**

import * as firefox from './firefox.js';
import { Browser, BrowserPlatform, BrowserTag } from './types.js';
import { Browser, BrowserPlatform, BrowserTag, } from './types.js';
export const downloadUrls = {

@@ -48,2 +48,20 @@ [Browser.CHROME]: chrome.resolveDownloadUrl,

}
export async function createProfile(browser, opts) {
switch (browser) {
case Browser.FIREFOX:
return await firefox.createProfile(opts);
case Browser.CHROME:
case Browser.CHROMIUM:
throw new Error(`Profile creation is not support for ${browser} yet`);
}
}
export function resolveSystemExecutablePath(browser, platform, channel) {
switch (browser) {
case Browser.FIREFOX:
throw new Error('System browser detection is not supported for Firefox yet.');
case Browser.CHROME:
case Browser.CHROMIUM:
return chrome.resolveSystemExecutablePath(platform, channel);
}
}
//# sourceMappingURL=browsers.js.map

@@ -16,6 +16,7 @@ /**

*/
import { BrowserPlatform } from './types.js';
import { BrowserPlatform, ChromeReleaseChannel } from './types.js';
export declare function resolveDownloadUrl(platform: BrowserPlatform, buildId: string, baseUrl?: string): string;
export declare function relativeExecutablePath(platform: BrowserPlatform, _buildId: string): string;
export declare function resolveBuildId(platform: BrowserPlatform, _channel?: 'latest'): Promise<string>;
export declare function resolveSystemExecutablePath(platform: BrowserPlatform, channel: ChromeReleaseChannel): string;
//# sourceMappingURL=chrome.d.ts.map

@@ -18,3 +18,3 @@ /**

import { httpRequest } from '../httpUtil.js';
import { BrowserPlatform } from './types.js';
import { BrowserPlatform, ChromeReleaseChannel } from './types.js';
function archive(platform, buildId) {

@@ -88,2 +88,40 @@ switch (platform) {

}
export function resolveSystemExecutablePath(platform, channel) {
switch (platform) {
case BrowserPlatform.WIN64:
case BrowserPlatform.WIN32:
switch (channel) {
case ChromeReleaseChannel.STABLE:
return `${process.env['PROGRAMFILES']}\\Google\\Chrome\\Application\\chrome.exe`;
case ChromeReleaseChannel.BETA:
return `${process.env['PROGRAMFILES']}\\Google\\Chrome Beta\\Application\\chrome.exe`;
case ChromeReleaseChannel.CANARY:
return `${process.env['PROGRAMFILES']}\\Google\\Chrome SxS\\Application\\chrome.exe`;
case ChromeReleaseChannel.DEV:
return `${process.env['PROGRAMFILES']}\\Google\\Chrome Dev\\Application\\chrome.exe`;
}
case BrowserPlatform.MAC_ARM:
case BrowserPlatform.MAC:
switch (channel) {
case ChromeReleaseChannel.STABLE:
return '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
case ChromeReleaseChannel.BETA:
return '/Applications/Google Chrome Beta.app/Contents/MacOS/Google Chrome Beta';
case ChromeReleaseChannel.CANARY:
return '/Applications/Google Chrome Canary.app/Contents/MacOS/Google Chrome Canary';
case ChromeReleaseChannel.DEV:
return '/Applications/Google Chrome Dev.app/Contents/MacOS/Google Chrome Dev';
}
case BrowserPlatform.LINUX:
switch (channel) {
case ChromeReleaseChannel.STABLE:
return '/opt/google/chrome/chrome';
case ChromeReleaseChannel.BETA:
return '/opt/google/chrome-beta/chrome';
case ChromeReleaseChannel.DEV:
return '/opt/google/chrome-unstable/chrome';
}
}
throw new Error(`Unable to detect browser executable path for '${channel}' on ${platform}.`);
}
//# sourceMappingURL=chrome.js.map

@@ -16,6 +16,7 @@ /**

*/
import { BrowserPlatform } from './types.js';
import { BrowserPlatform, ProfileOptions } from './types.js';
export declare function resolveDownloadUrl(platform: BrowserPlatform, buildId: string, baseUrl?: string): string;
export declare function relativeExecutablePath(platform: BrowserPlatform, _buildId: string): string;
export declare function resolveBuildId(channel?: 'FIREFOX_NIGHTLY'): Promise<string>;
export declare function createProfile(options: ProfileOptions): Promise<void>;
//# sourceMappingURL=firefox.d.ts.map

@@ -16,2 +16,3 @@ /**

*/
import fs from 'fs';
import path from 'path';

@@ -72,2 +73,201 @@ import { httpRequest } from '../httpUtil.js';

}
export async function createProfile(options) {
if (!fs.existsSync(options.path)) {
await fs.promises.mkdir(options.path, {
recursive: true,
});
}
await writePreferences({
preferences: {
...defaultProfilePreferences(options.preferences),
...options.preferences,
},
path: options.path,
});
}
function defaultProfilePreferences(extraPrefs) {
const server = 'dummy.test';
const defaultPrefs = {
// Make sure Shield doesn't hit the network.
'app.normandy.api_url': '',
// Disable Firefox old build background check
'app.update.checkInstallTime': false,
// Disable automatically upgrading Firefox
'app.update.disabledForTesting': true,
// Increase the APZ content response timeout to 1 minute
'apz.content_response_timeout': 60000,
// Prevent various error message on the console
// jest-puppeteer asserts that no error message is emitted by the console
'browser.contentblocking.features.standard': '-tp,tpPrivate,cookieBehavior0,-cm,-fp',
// Enable the dump function: which sends messages to the system
// console
// https://bugzilla.mozilla.org/show_bug.cgi?id=1543115
'browser.dom.window.dump.enabled': true,
// Disable topstories
'browser.newtabpage.activity-stream.feeds.system.topstories': false,
// Always display a blank page
'browser.newtabpage.enabled': false,
// Background thumbnails in particular cause grief: and disabling
// thumbnails in general cannot hurt
'browser.pagethumbnails.capturing_disabled': true,
// Disable safebrowsing components.
'browser.safebrowsing.blockedURIs.enabled': false,
'browser.safebrowsing.downloads.enabled': false,
'browser.safebrowsing.malware.enabled': false,
'browser.safebrowsing.passwords.enabled': false,
'browser.safebrowsing.phishing.enabled': false,
// Disable updates to search engines.
'browser.search.update': false,
// Do not restore the last open set of tabs if the browser has crashed
'browser.sessionstore.resume_from_crash': false,
// Skip check for default browser on startup
'browser.shell.checkDefaultBrowser': false,
// Disable newtabpage
'browser.startup.homepage': 'about:blank',
// Do not redirect user when a milstone upgrade of Firefox is detected
'browser.startup.homepage_override.mstone': 'ignore',
// Start with a blank page about:blank
'browser.startup.page': 0,
// Do not allow background tabs to be zombified on Android: otherwise for
// tests that open additional tabs: the test harness tab itself might get
// unloaded
'browser.tabs.disableBackgroundZombification': false,
// Do not warn when closing all other open tabs
'browser.tabs.warnOnCloseOtherTabs': false,
// Do not warn when multiple tabs will be opened
'browser.tabs.warnOnOpen': false,
// Disable the UI tour.
'browser.uitour.enabled': false,
// Turn off search suggestions in the location bar so as not to trigger
// network connections.
'browser.urlbar.suggest.searches': false,
// Disable first run splash page on Windows 10
'browser.usedOnWindows10.introURL': '',
// Do not warn on quitting Firefox
'browser.warnOnQuit': false,
// Defensively disable data reporting systems
'datareporting.healthreport.documentServerURI': `http://${server}/dummy/healthreport/`,
'datareporting.healthreport.logging.consoleEnabled': false,
'datareporting.healthreport.service.enabled': false,
'datareporting.healthreport.service.firstRun': false,
'datareporting.healthreport.uploadEnabled': false,
// Do not show datareporting policy notifications which can interfere with tests
'datareporting.policy.dataSubmissionEnabled': false,
'datareporting.policy.dataSubmissionPolicyBypassNotification': true,
// DevTools JSONViewer sometimes fails to load dependencies with its require.js.
// This doesn't affect Puppeteer but spams console (Bug 1424372)
'devtools.jsonview.enabled': false,
// Disable popup-blocker
'dom.disable_open_during_load': false,
// Enable the support for File object creation in the content process
// Required for |Page.setFileInputFiles| protocol method.
'dom.file.createInChild': true,
// Disable the ProcessHangMonitor
'dom.ipc.reportProcessHangs': false,
// Disable slow script dialogues
'dom.max_chrome_script_run_time': 0,
'dom.max_script_run_time': 0,
// Only load extensions from the application and user profile
// AddonManager.SCOPE_PROFILE + AddonManager.SCOPE_APPLICATION
'extensions.autoDisableScopes': 0,
'extensions.enabledScopes': 5,
// Disable metadata caching for installed add-ons by default
'extensions.getAddons.cache.enabled': false,
// Disable installing any distribution extensions or add-ons.
'extensions.installDistroAddons': false,
// Disabled screenshots extension
'extensions.screenshots.disabled': true,
// Turn off extension updates so they do not bother tests
'extensions.update.enabled': false,
// Turn off extension updates so they do not bother tests
'extensions.update.notifyUser': false,
// Make sure opening about:addons will not hit the network
'extensions.webservice.discoverURL': `http://${server}/dummy/discoveryURL`,
// Temporarily force disable BFCache in parent (https://bit.ly/bug-1732263)
'fission.bfcacheInParent': false,
// Force all web content to use a single content process
'fission.webContentIsolationStrategy': 0,
// Allow the application to have focus even it runs in the background
'focusmanager.testmode': true,
// Disable useragent updates
'general.useragent.updates.enabled': false,
// Always use network provider for geolocation tests so we bypass the
// macOS dialog raised by the corelocation provider
'geo.provider.testing': true,
// Do not scan Wifi
'geo.wifi.scan': false,
// No hang monitor
'hangmonitor.timeout': 0,
// Show chrome errors and warnings in the error console
'javascript.options.showInConsole': true,
// Disable download and usage of OpenH264: and Widevine plugins
'media.gmp-manager.updateEnabled': false,
// Prevent various error message on the console
// jest-puppeteer asserts that no error message is emitted by the console
'network.cookie.cookieBehavior': 0,
// Disable experimental feature that is only available in Nightly
'network.cookie.sameSite.laxByDefault': false,
// Do not prompt for temporary redirects
'network.http.prompt-temp-redirect': false,
// Disable speculative connections so they are not reported as leaking
// when they are hanging around
'network.http.speculative-parallel-limit': 0,
// Do not automatically switch between offline and online
'network.manage-offline-status': false,
// Make sure SNTP requests do not hit the network
'network.sntp.pools': server,
// Disable Flash.
'plugin.state.flash': 0,
'privacy.trackingprotection.enabled': false,
// Can be removed once Firefox 89 is no longer supported
// https://bugzilla.mozilla.org/show_bug.cgi?id=1710839
'remote.enabled': true,
// Don't do network connections for mitm priming
'security.certerrors.mitm.priming.enabled': false,
// Local documents have access to all other local documents,
// including directory listings
'security.fileuri.strict_origin_policy': false,
// Do not wait for the notification button security delay
'security.notification_enable_delay': 0,
// Ensure blocklist updates do not hit the network
'services.settings.server': `http://${server}/dummy/blocklist/`,
// Do not automatically fill sign-in forms with known usernames and
// passwords
'signon.autofillForms': false,
// Disable password capture, so that tests that include forms are not
// influenced by the presence of the persistent doorhanger notification
'signon.rememberSignons': false,
// Disable first-run welcome page
'startup.homepage_welcome_url': 'about:blank',
// Disable first-run welcome page
'startup.homepage_welcome_url.additional': '',
// Disable browser animations (tabs, fullscreen, sliding alerts)
'toolkit.cosmeticAnimations.enabled': false,
// Prevent starting into safe mode after application crashes
'toolkit.startup.max_resumed_crashes': -1,
};
return Object.assign(defaultPrefs, extraPrefs);
}
/**
* Populates the user.js file with custom preferences as needed to allow
* Firefox's CDP support to properly function. These preferences will be
* automatically copied over to prefs.js during startup of Firefox. To be
* able to restore the original values of preferences a backup of prefs.js
* will be created.
*
* @param prefs - List of preferences to add.
* @param profilePath - Firefox profile to write the preferences to.
*/
async function writePreferences(options) {
const lines = Object.entries(options.preferences).map(([key, value]) => {
return `user_pref(${JSON.stringify(key)}, ${JSON.stringify(value)});`;
});
await fs.promises.writeFile(path.join(options.path, 'user.js'), lines.join('\n'));
// Create a backup of the preferences file if it already exitsts.
const prefsPath = path.join(options.path, 'prefs.js');
if (fs.existsSync(prefsPath)) {
const prefsBackupPath = path.join(options.path, 'prefs.js.puppeteer');
await fs.promises.copyFile(prefsPath, prefsBackupPath);
}
}
//# sourceMappingURL=firefox.js.map

@@ -45,2 +45,12 @@ /**

}
export interface ProfileOptions {
preferences: Record<string, unknown>;
path: string;
}
export declare enum ChromeReleaseChannel {
STABLE = "stable",
DEV = "dev",
CANARY = "canary",
BETA = "beta"
}
//# sourceMappingURL=types.d.ts.map

@@ -48,2 +48,9 @@ /**

})(BrowserTag || (BrowserTag = {}));
export var ChromeReleaseChannel;
(function (ChromeReleaseChannel) {
ChromeReleaseChannel["STABLE"] = "stable";
ChromeReleaseChannel["DEV"] = "dev";
ChromeReleaseChannel["CANARY"] = "canary";
ChromeReleaseChannel["BETA"] = "beta";
})(ChromeReleaseChannel || (ChromeReleaseChannel = {}));
//# sourceMappingURL=types.js.map

@@ -27,3 +27,3 @@ /**

};
var _CLI_instances, _CLI_cachePath, _CLI_parseBrowser, _CLI_parseBuildId, _CLI_toMegabytes, _CLI_makeProgressCallback;
var _CLI_instances, _CLI_cachePath, _CLI_defineBrowserParameter, _CLI_definePlatformParameter, _CLI_definePathParameter, _CLI_parseBrowser, _CLI_parseBuildId, _CLI_toMegabytes, _CLI_makeProgressCallback;
import ProgressBar from 'progress';

@@ -33,6 +33,6 @@ import yargs from 'yargs';

import { resolveBuildId } from './browsers/browsers.js';
import { BrowserPlatform } from './browsers/types.js';
import { BrowserPlatform, } from './browsers/types.js';
import { detectBrowserPlatform } from './detectPlatform.js';
import { fetch } from './fetch.js';
import { computeExecutablePath, launch } from './launcher.js';
import { computeExecutablePath, computeSystemExecutablePath, launch, } from './launcher.js';
export class CLI {

@@ -47,23 +47,5 @@ constructor(cachePath = process.cwd()) {

.command('install <browser>', 'Download and install the specified browser', yargs => {
yargs.positional('browser', {
description: 'The browser version',
type: 'string',
coerce: (opt) => {
return {
name: __classPrivateFieldGet(this, _CLI_instances, "m", _CLI_parseBrowser).call(this, opt),
buildId: __classPrivateFieldGet(this, _CLI_instances, "m", _CLI_parseBuildId).call(this, opt),
};
},
});
yargs.option('platform', {
type: 'string',
desc: 'Platform that the binary needs to be compatible with.',
choices: Object.values(BrowserPlatform),
defaultDescription: 'Auto-detected by default.',
});
yargs.option('path', {
type: 'string',
desc: 'Path where the browsers will be downloaded to and installed from',
default: process.cwd(),
});
__classPrivateFieldGet(this, _CLI_instances, "m", _CLI_defineBrowserParameter).call(this, yargs);
__classPrivateFieldGet(this, _CLI_instances, "m", _CLI_definePlatformParameter).call(this, yargs);
__classPrivateFieldGet(this, _CLI_instances, "m", _CLI_definePathParameter).call(this, yargs);
}, async (argv) => {

@@ -92,37 +74,31 @@ var _a, _b, _c;

.command('launch <browser>', 'Launch the specified browser', yargs => {
yargs.positional('browser', {
description: 'The browser version',
type: 'string',
coerce: (opt) => {
return {
name: __classPrivateFieldGet(this, _CLI_instances, "m", _CLI_parseBrowser).call(this, opt),
buildId: __classPrivateFieldGet(this, _CLI_instances, "m", _CLI_parseBuildId).call(this, opt),
};
},
});
__classPrivateFieldGet(this, _CLI_instances, "m", _CLI_defineBrowserParameter).call(this, yargs);
__classPrivateFieldGet(this, _CLI_instances, "m", _CLI_definePlatformParameter).call(this, yargs);
__classPrivateFieldGet(this, _CLI_instances, "m", _CLI_definePathParameter).call(this, yargs);
yargs.option('detached', {
type: 'boolean',
desc: 'Whether to detach the child process.',
desc: 'Detach the child process.',
default: false,
});
yargs.option('platform', {
type: 'string',
desc: 'Platform that the binary needs to be compatible with.',
choices: Object.values(BrowserPlatform),
defaultDescription: 'Auto-detected by default.',
yargs.option('system', {
type: 'boolean',
desc: 'Search for a browser installed on the system instead of the cache folder.',
default: false,
});
yargs.option('path', {
type: 'string',
desc: 'Path where the browsers will be downloaded to and installed from',
default: process.cwd(),
});
}, async (argv) => {
var _a;
const args = argv;
const executablePath = computeExecutablePath({
browser: args.browser.name,
buildId: args.browser.buildId,
cacheDir: (_a = args.path) !== null && _a !== void 0 ? _a : __classPrivateFieldGet(this, _CLI_cachePath, "f"),
platform: args.platform,
});
const executablePath = args.system
? computeSystemExecutablePath({
browser: args.browser.name,
// TODO: throw an error if not a ChromeReleaseChannel is provided.
channel: args.browser.buildId,
platform: args.platform,
})
: computeExecutablePath({
browser: args.browser.name,
buildId: args.browser.buildId,
cacheDir: (_a = args.path) !== null && _a !== void 0 ? _a : __classPrivateFieldGet(this, _CLI_cachePath, "f"),
platform: args.platform,
});
launch({

@@ -138,3 +114,27 @@ executablePath,

}
_CLI_cachePath = new WeakMap(), _CLI_instances = new WeakSet(), _CLI_parseBrowser = function _CLI_parseBrowser(version) {
_CLI_cachePath = new WeakMap(), _CLI_instances = new WeakSet(), _CLI_defineBrowserParameter = function _CLI_defineBrowserParameter(yargs) {
yargs.positional('browser', {
description: 'The browser version',
type: 'string',
coerce: (opt) => {
return {
name: __classPrivateFieldGet(this, _CLI_instances, "m", _CLI_parseBrowser).call(this, opt),
buildId: __classPrivateFieldGet(this, _CLI_instances, "m", _CLI_parseBuildId).call(this, opt),
};
},
});
}, _CLI_definePlatformParameter = function _CLI_definePlatformParameter(yargs) {
yargs.option('platform', {
type: 'string',
desc: 'Platform that the binary needs to be compatible with.',
choices: Object.values(BrowserPlatform),
defaultDescription: 'Auto-detected by default.',
});
}, _CLI_definePathParameter = function _CLI_definePathParameter(yargs) {
yargs.option('path', {
type: 'string',
desc: 'Path to the root folder for the browser downloads and installation',
default: process.cwd(),
});
}, _CLI_parseBrowser = function _CLI_parseBrowser(version) {
return version.split('@').shift();

@@ -141,0 +141,0 @@ }, _CLI_parseBuildId = function _CLI_parseBuildId(version) {

@@ -18,2 +18,3 @@ /**

import { Browser, BrowserPlatform } from './browsers/browsers.js';
import { ChromeReleaseChannel } from './browsers/types.js';
/**

@@ -38,3 +39,3 @@ * @public

/**
* Determines which buildId to dowloand. BuildId should uniquely identify
* Determines which buildId to download. BuildId should uniquely identify
* binaries and they are used for caching.

@@ -45,2 +46,22 @@ */

export declare function computeExecutablePath(options: Options): string;
/**
* @public
*/
export interface SystemOptions {
/**
* Determines which platform the browser will be suited for.
*
* @defaultValue Auto-detected.
*/
platform?: BrowserPlatform;
/**
* Determines which browser to fetch.
*/
browser: Browser;
/**
* Release channel to look for on the system.
*/
channel: ChromeReleaseChannel;
}
export declare function computeSystemExecutablePath(options: SystemOptions): string;
type LaunchOptions = {

@@ -58,2 +79,4 @@ executablePath: string;

export declare function launch(opts: LaunchOptions): Process;
export declare const CDP_WEBSOCKET_ENDPOINT_REGEX: RegExp;
export declare const WEBDRIVER_BIDI_WEBSOCKET_ENDPOINT_REGEX: RegExp;
declare class Process {

@@ -64,2 +87,3 @@ #private;

kill(): void;
waitForLineOutput(regex: RegExp, timeout?: number): Promise<string>;
}

@@ -66,0 +90,0 @@ /**

@@ -29,5 +29,7 @@ /**

import childProcess from 'child_process';
import { accessSync } from 'fs';
import os from 'os';
import path from 'path';
import { executablePathByBrowser, } from './browsers/browsers.js';
import readline from 'readline';
import { executablePathByBrowser, resolveSystemExecutablePath, } from './browsers/browsers.js';
import { CacheStructure } from './CacheStructure.js';

@@ -46,5 +48,22 @@ import { debug } from './debug.js';

}
export function computeSystemExecutablePath(options) {
var _a;
(_a = options.platform) !== null && _a !== void 0 ? _a : (options.platform = detectBrowserPlatform());
if (!options.platform) {
throw new Error(`Cannot download a binary for the provided platform: ${os.platform()} (${os.arch()})`);
}
const path = resolveSystemExecutablePath(options.browser, options.platform, options.channel);
try {
accessSync(path);
}
catch (error) {
throw new Error(`Could not find Google Chrome executable for channel '${options.channel}' at '${path}'.`);
}
return path;
}
export function launch(opts) {
return new Process(opts);
}
export const CDP_WEBSOCKET_ENDPOINT_REGEX = /^DevTools listening on (ws:\/\/.*)$/;
export const WEBDRIVER_BIDI_WEBSOCKET_ENDPOINT_REGEX = /^WebDriver BiDi listening on (ws:\/\/.*)$/;
class Process {

@@ -163,2 +182,46 @@ constructor(opts) {

}
waitForLineOutput(regex, timeout) {
if (!__classPrivateFieldGet(this, _Process_browserProcess, "f").stderr) {
throw new Error('`browserProcess` does not have stderr.');
}
const rl = readline.createInterface(__classPrivateFieldGet(this, _Process_browserProcess, "f").stderr);
let stderr = '';
return new Promise((resolve, reject) => {
rl.on('line', onLine);
rl.on('close', onClose);
__classPrivateFieldGet(this, _Process_browserProcess, "f").on('exit', onClose);
__classPrivateFieldGet(this, _Process_browserProcess, "f").on('error', onClose);
const timeoutId = timeout ? setTimeout(onTimeout, timeout) : 0;
const cleanup = () => {
if (timeoutId) {
clearTimeout(timeoutId);
}
rl.off('line', onLine);
rl.off('close', onClose);
__classPrivateFieldGet(this, _Process_browserProcess, "f").off('exit', onClose);
__classPrivateFieldGet(this, _Process_browserProcess, "f").off('error', onClose);
};
function onClose(error) {
cleanup();
reject(new Error([
`Failed to launch the browser process!${error ? ' ' + error.message : ''}`,
stderr,
].join('\n')));
}
function onTimeout() {
cleanup();
reject(new Error(`Timed out after ${timeout} ms while waiting for the WS endpoint URL to appear in stdout!`));
}
function onLine(line) {
stderr += line + '\n';
const match = line.match(regex);
if (!match) {
return;
}
cleanup();
// The RegExp matches, so this will obviously exist.
resolve(match[1]);
}
});
}
}

@@ -165,0 +228,0 @@ _Process_executablePath = new WeakMap(), _Process_args = new WeakMap(), _Process_browserProcess = new WeakMap(), _Process_exited = new WeakMap(), _Process_browserProcessExiting = new WeakMap(), _Process_onDriverProcessExit = new WeakMap(), _Process_onDriverProcessSignal = new WeakMap(), _Process_instances = new WeakSet(), _Process_configureStdio = function _Process_configureStdio(opts) {

{
"name": "@puppeteer/browsers",
"version": "0.0.5",
"version": "0.1.0",
"description": "Download and launch browsers",

@@ -14,2 +14,9 @@ "scripts": {

},
"main": "./lib/cjs/main.js",
"exports": {
".": {
"import": "./lib/esm/main.js",
"require": "./lib/cjs/main.js"
}
},
"wireit": {

@@ -72,2 +79,3 @@ "build": {

"proxy-from-env": "1.1.0",
"rimraf": "4.4.0",
"tar-fs": "2.1.1",

@@ -74,0 +82,0 @@ "unbzip2-stream": "1.4.3",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc