CLI.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. "use strict";
  2. /**
  3. * @license
  4. * Copyright 2023 Google Inc.
  5. * SPDX-License-Identifier: Apache-2.0
  6. */
  7. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  8. if (k2 === undefined) k2 = k;
  9. var desc = Object.getOwnPropertyDescriptor(m, k);
  10. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  11. desc = { enumerable: true, get: function() { return m[k]; } };
  12. }
  13. Object.defineProperty(o, k2, desc);
  14. }) : (function(o, m, k, k2) {
  15. if (k2 === undefined) k2 = k;
  16. o[k2] = m[k];
  17. }));
  18. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  19. Object.defineProperty(o, "default", { enumerable: true, value: v });
  20. }) : function(o, v) {
  21. o["default"] = v;
  22. });
  23. var __importStar = (this && this.__importStar) || function (mod) {
  24. if (mod && mod.__esModule) return mod;
  25. var result = {};
  26. if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
  27. __setModuleDefault(result, mod);
  28. return result;
  29. };
  30. var __importDefault = (this && this.__importDefault) || function (mod) {
  31. return (mod && mod.__esModule) ? mod : { "default": mod };
  32. };
  33. Object.defineProperty(exports, "__esModule", { value: true });
  34. exports.makeProgressCallback = exports.CLI = void 0;
  35. const process_1 = require("process");
  36. const readline = __importStar(require("readline"));
  37. const progress_1 = __importDefault(require("progress"));
  38. const helpers_1 = require("yargs/helpers");
  39. const yargs_1 = __importDefault(require("yargs/yargs"));
  40. const browser_data_js_1 = require("./browser-data/browser-data.js");
  41. const Cache_js_1 = require("./Cache.js");
  42. const detectPlatform_js_1 = require("./detectPlatform.js");
  43. const install_js_1 = require("./install.js");
  44. const launch_js_1 = require("./launch.js");
  45. /**
  46. * @public
  47. */
  48. class CLI {
  49. #cachePath;
  50. #rl;
  51. #scriptName = '';
  52. #allowCachePathOverride = true;
  53. #pinnedBrowsers;
  54. #prefixCommand;
  55. constructor(opts, rl) {
  56. if (!opts) {
  57. opts = {};
  58. }
  59. if (typeof opts === 'string') {
  60. opts = {
  61. cachePath: opts,
  62. };
  63. }
  64. this.#cachePath = opts.cachePath ?? process.cwd();
  65. this.#rl = rl;
  66. this.#scriptName = opts.scriptName ?? '@puppeteer/browsers';
  67. this.#allowCachePathOverride = opts.allowCachePathOverride ?? true;
  68. this.#pinnedBrowsers = opts.pinnedBrowsers;
  69. this.#prefixCommand = opts.prefixCommand;
  70. }
  71. #defineBrowserParameter(yargs) {
  72. yargs.positional('browser', {
  73. description: 'Which browser to install <browser>[@<buildId|latest>]. `latest` will try to find the latest available build. `buildId` is a browser-specific identifier such as a version or a revision.',
  74. type: 'string',
  75. coerce: (opt) => {
  76. return {
  77. name: this.#parseBrowser(opt),
  78. buildId: this.#parseBuildId(opt),
  79. };
  80. },
  81. });
  82. }
  83. #definePlatformParameter(yargs) {
  84. yargs.option('platform', {
  85. type: 'string',
  86. desc: 'Platform that the binary needs to be compatible with.',
  87. choices: Object.values(browser_data_js_1.BrowserPlatform),
  88. defaultDescription: 'Auto-detected',
  89. });
  90. }
  91. #definePathParameter(yargs, required = false) {
  92. if (!this.#allowCachePathOverride) {
  93. return;
  94. }
  95. yargs.option('path', {
  96. type: 'string',
  97. desc: 'Path to the root folder for the browser downloads and installation. The installation folder structure is compatible with the cache structure used by Puppeteer.',
  98. defaultDescription: 'Current working directory',
  99. ...(required ? {} : { default: process.cwd() }),
  100. });
  101. if (required) {
  102. yargs.demandOption('path');
  103. }
  104. }
  105. async run(argv) {
  106. const yargsInstance = (0, yargs_1.default)((0, helpers_1.hideBin)(argv));
  107. let target = yargsInstance.scriptName(this.#scriptName);
  108. if (this.#prefixCommand) {
  109. target = target.command(this.#prefixCommand.cmd, this.#prefixCommand.description, yargs => {
  110. return this.#build(yargs);
  111. });
  112. }
  113. else {
  114. target = this.#build(target);
  115. }
  116. await target
  117. .demandCommand(1)
  118. .help()
  119. .wrap(Math.min(120, yargsInstance.terminalWidth()))
  120. .parse();
  121. }
  122. #build(yargs) {
  123. const latestOrPinned = this.#pinnedBrowsers ? 'pinned' : 'latest';
  124. return yargs
  125. .command('install <browser>', 'Download and install the specified browser. If successful, the command outputs the actual browser buildId that was installed and the absolute path to the browser executable (format: <browser>@<buildID> <path>).', yargs => {
  126. this.#defineBrowserParameter(yargs);
  127. this.#definePlatformParameter(yargs);
  128. this.#definePathParameter(yargs);
  129. yargs.option('base-url', {
  130. type: 'string',
  131. desc: 'Base URL to download from',
  132. });
  133. yargs.example('$0 install chrome', `Install the ${latestOrPinned} available build of the Chrome browser.`);
  134. yargs.example('$0 install chrome@latest', 'Install the latest available build for the Chrome browser.');
  135. yargs.example('$0 install chrome@stable', 'Install the latest available build for the Chrome browser from the stable channel.');
  136. yargs.example('$0 install chrome@beta', 'Install the latest available build for the Chrome browser from the beta channel.');
  137. yargs.example('$0 install chrome@dev', 'Install the latest available build for the Chrome browser from the dev channel.');
  138. yargs.example('$0 install chrome@canary', 'Install the latest available build for the Chrome Canary browser.');
  139. yargs.example('$0 install chrome@115', 'Install the latest available build for Chrome 115.');
  140. yargs.example('$0 install chromedriver@canary', 'Install the latest available build for ChromeDriver Canary.');
  141. yargs.example('$0 install chromedriver@115', 'Install the latest available build for ChromeDriver 115.');
  142. yargs.example('$0 install chromedriver@115.0.5790', 'Install the latest available patch (115.0.5790.X) build for ChromeDriver.');
  143. yargs.example('$0 install chrome-headless-shell', 'Install the latest available chrome-headless-shell build.');
  144. yargs.example('$0 install chrome-headless-shell@beta', 'Install the latest available chrome-headless-shell build corresponding to the Beta channel.');
  145. yargs.example('$0 install chrome-headless-shell@118', 'Install the latest available chrome-headless-shell 118 build.');
  146. yargs.example('$0 install chromium@1083080', 'Install the revision 1083080 of the Chromium browser.');
  147. yargs.example('$0 install firefox', 'Install the latest nightly available build of the Firefox browser.');
  148. yargs.example('$0 install firefox@stable', 'Install the latest stable build of the Firefox browser.');
  149. yargs.example('$0 install firefox@beta', 'Install the latest beta build of the Firefox browser.');
  150. yargs.example('$0 install firefox@devedition', 'Install the latest devedition build of the Firefox browser.');
  151. yargs.example('$0 install firefox@esr', 'Install the latest ESR build of the Firefox browser.');
  152. yargs.example('$0 install firefox@nightly', 'Install the latest nightly build of the Firefox browser.');
  153. yargs.example('$0 install firefox@stable_111.0.1', 'Install a specific version of the Firefox browser.');
  154. yargs.example('$0 install firefox --platform mac', 'Install the latest Mac (Intel) build of the Firefox browser.');
  155. if (this.#allowCachePathOverride) {
  156. yargs.example('$0 install firefox --path /tmp/my-browser-cache', 'Install to the specified cache directory.');
  157. }
  158. }, async (argv) => {
  159. const args = argv;
  160. args.platform ??= (0, detectPlatform_js_1.detectBrowserPlatform)();
  161. if (!args.platform) {
  162. throw new Error(`Could not resolve the current platform`);
  163. }
  164. if (args.browser.buildId === 'pinned') {
  165. const pinnedVersion = this.#pinnedBrowsers?.[args.browser.name];
  166. if (!pinnedVersion) {
  167. throw new Error(`No pinned version found for ${args.browser.name}`);
  168. }
  169. args.browser.buildId = pinnedVersion;
  170. }
  171. const originalBuildId = args.browser.buildId;
  172. args.browser.buildId = await (0, browser_data_js_1.resolveBuildId)(args.browser.name, args.platform, args.browser.buildId);
  173. await (0, install_js_1.install)({
  174. browser: args.browser.name,
  175. buildId: args.browser.buildId,
  176. platform: args.platform,
  177. cacheDir: args.path ?? this.#cachePath,
  178. downloadProgressCallback: makeProgressCallback(args.browser.name, args.browser.buildId),
  179. baseUrl: args.baseUrl,
  180. buildIdAlias: originalBuildId !== args.browser.buildId
  181. ? originalBuildId
  182. : undefined,
  183. });
  184. console.log(`${args.browser.name}@${args.browser.buildId} ${(0, launch_js_1.computeExecutablePath)({
  185. browser: args.browser.name,
  186. buildId: args.browser.buildId,
  187. cacheDir: args.path ?? this.#cachePath,
  188. platform: args.platform,
  189. })}`);
  190. })
  191. .command('launch <browser>', 'Launch the specified browser', yargs => {
  192. this.#defineBrowserParameter(yargs);
  193. this.#definePlatformParameter(yargs);
  194. this.#definePathParameter(yargs);
  195. yargs.option('detached', {
  196. type: 'boolean',
  197. desc: 'Detach the child process.',
  198. default: false,
  199. });
  200. yargs.option('system', {
  201. type: 'boolean',
  202. desc: 'Search for a browser installed on the system instead of the cache folder.',
  203. default: false,
  204. });
  205. yargs.example('$0 launch chrome@115.0.5790.170', 'Launch Chrome 115.0.5790.170');
  206. yargs.example('$0 launch firefox@112.0a1', 'Launch the Firefox browser identified by the milestone 112.0a1.');
  207. yargs.example('$0 launch chrome@115.0.5790.170 --detached', 'Launch the browser but detach the sub-processes.');
  208. yargs.example('$0 launch chrome@canary --system', 'Try to locate the Canary build of Chrome installed on the system and launch it.');
  209. }, async (argv) => {
  210. const args = argv;
  211. const executablePath = args.system
  212. ? (0, launch_js_1.computeSystemExecutablePath)({
  213. browser: args.browser.name,
  214. // TODO: throw an error if not a ChromeReleaseChannel is provided.
  215. channel: args.browser.buildId,
  216. platform: args.platform,
  217. })
  218. : (0, launch_js_1.computeExecutablePath)({
  219. browser: args.browser.name,
  220. buildId: args.browser.buildId,
  221. cacheDir: args.path ?? this.#cachePath,
  222. platform: args.platform,
  223. });
  224. (0, launch_js_1.launch)({
  225. executablePath,
  226. detached: args.detached,
  227. });
  228. })
  229. .command('clear', this.#allowCachePathOverride
  230. ? 'Removes all installed browsers from the specified cache directory'
  231. : `Removes all installed browsers from ${this.#cachePath}`, yargs => {
  232. this.#definePathParameter(yargs, true);
  233. }, async (argv) => {
  234. const args = argv;
  235. const cacheDir = args.path ?? this.#cachePath;
  236. const rl = this.#rl ?? readline.createInterface({ input: process_1.stdin, output: process_1.stdout });
  237. rl.question(`Do you want to permanently and recursively delete the content of ${cacheDir} (yes/No)? `, answer => {
  238. rl.close();
  239. if (!['y', 'yes'].includes(answer.toLowerCase().trim())) {
  240. console.log('Cancelled.');
  241. return;
  242. }
  243. const cache = new Cache_js_1.Cache(cacheDir);
  244. cache.clear();
  245. console.log(`${cacheDir} cleared.`);
  246. });
  247. })
  248. .demandCommand(1)
  249. .help();
  250. }
  251. #parseBrowser(version) {
  252. return version.split('@').shift();
  253. }
  254. #parseBuildId(version) {
  255. const parts = version.split('@');
  256. return parts.length === 2
  257. ? parts[1]
  258. : this.#pinnedBrowsers
  259. ? 'pinned'
  260. : 'latest';
  261. }
  262. }
  263. exports.CLI = CLI;
  264. /**
  265. * @public
  266. */
  267. function makeProgressCallback(browser, buildId) {
  268. let progressBar;
  269. let lastDownloadedBytes = 0;
  270. return (downloadedBytes, totalBytes) => {
  271. if (!progressBar) {
  272. progressBar = new progress_1.default(`Downloading ${browser} ${buildId} - ${toMegabytes(totalBytes)} [:bar] :percent :etas `, {
  273. complete: '=',
  274. incomplete: ' ',
  275. width: 20,
  276. total: totalBytes,
  277. });
  278. }
  279. const delta = downloadedBytes - lastDownloadedBytes;
  280. lastDownloadedBytes = downloadedBytes;
  281. progressBar.tick(delta);
  282. };
  283. }
  284. exports.makeProgressCallback = makeProgressCallback;
  285. function toMegabytes(bytes) {
  286. const mb = bytes / 1000 / 1000;
  287. return `${Math.round(mb * 10) / 10} MB`;
  288. }
  289. //# sourceMappingURL=CLI.js.map