cli.js 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896
  1. import path from 'node:path';
  2. import fs from 'node:fs';
  3. import { performance } from 'node:perf_hooks';
  4. import { EventEmitter } from 'events';
  5. import { A as picocolorsExports, B as bindShortcuts, w as createLogger, h as resolveConfig } from './chunks/dep-ca21228b.js';
  6. import { VERSION } from './constants.js';
  7. import 'node:url';
  8. import 'node:module';
  9. import 'tty';
  10. import 'esbuild';
  11. import 'path';
  12. import './chunks/dep-ace95160.js';
  13. import 'fs';
  14. import 'assert';
  15. import 'util';
  16. import 'net';
  17. import 'url';
  18. import 'http';
  19. import 'stream';
  20. import 'os';
  21. import 'child_process';
  22. import 'node:os';
  23. import 'node:crypto';
  24. import 'node:util';
  25. import 'node:dns';
  26. import 'resolve';
  27. import 'crypto';
  28. import 'node:buffer';
  29. import 'module';
  30. import 'node:assert';
  31. import 'node:process';
  32. import 'node:v8';
  33. import 'worker_threads';
  34. import 'zlib';
  35. import 'buffer';
  36. import 'https';
  37. import 'tls';
  38. import 'node:http';
  39. import 'node:https';
  40. import 'rollup';
  41. import 'querystring';
  42. import 'node:child_process';
  43. import 'node:readline';
  44. import 'node:zlib';
  45. function toArr(any) {
  46. return any == null ? [] : Array.isArray(any) ? any : [any];
  47. }
  48. function toVal(out, key, val, opts) {
  49. var x, old=out[key], nxt=(
  50. !!~opts.string.indexOf(key) ? (val == null || val === true ? '' : String(val))
  51. : typeof val === 'boolean' ? val
  52. : !!~opts.boolean.indexOf(key) ? (val === 'false' ? false : val === 'true' || (out._.push((x = +val,x * 0 === 0) ? x : val),!!val))
  53. : (x = +val,x * 0 === 0) ? x : val
  54. );
  55. out[key] = old == null ? nxt : (Array.isArray(old) ? old.concat(nxt) : [old, nxt]);
  56. }
  57. function mri2 (args, opts) {
  58. args = args || [];
  59. opts = opts || {};
  60. var k, arr, arg, name, val, out={ _:[] };
  61. var i=0, j=0, idx=0, len=args.length;
  62. const alibi = opts.alias !== void 0;
  63. const strict = opts.unknown !== void 0;
  64. const defaults = opts.default !== void 0;
  65. opts.alias = opts.alias || {};
  66. opts.string = toArr(opts.string);
  67. opts.boolean = toArr(opts.boolean);
  68. if (alibi) {
  69. for (k in opts.alias) {
  70. arr = opts.alias[k] = toArr(opts.alias[k]);
  71. for (i=0; i < arr.length; i++) {
  72. (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
  73. }
  74. }
  75. }
  76. for (i=opts.boolean.length; i-- > 0;) {
  77. arr = opts.alias[opts.boolean[i]] || [];
  78. for (j=arr.length; j-- > 0;) opts.boolean.push(arr[j]);
  79. }
  80. for (i=opts.string.length; i-- > 0;) {
  81. arr = opts.alias[opts.string[i]] || [];
  82. for (j=arr.length; j-- > 0;) opts.string.push(arr[j]);
  83. }
  84. if (defaults) {
  85. for (k in opts.default) {
  86. name = typeof opts.default[k];
  87. arr = opts.alias[k] = opts.alias[k] || [];
  88. if (opts[name] !== void 0) {
  89. opts[name].push(k);
  90. for (i=0; i < arr.length; i++) {
  91. opts[name].push(arr[i]);
  92. }
  93. }
  94. }
  95. }
  96. const keys = strict ? Object.keys(opts.alias) : [];
  97. for (i=0; i < len; i++) {
  98. arg = args[i];
  99. if (arg === '--') {
  100. out._ = out._.concat(args.slice(++i));
  101. break;
  102. }
  103. for (j=0; j < arg.length; j++) {
  104. if (arg.charCodeAt(j) !== 45) break; // "-"
  105. }
  106. if (j === 0) {
  107. out._.push(arg);
  108. } else if (arg.substring(j, j + 3) === 'no-') {
  109. name = arg.substring(j + 3);
  110. if (strict && !~keys.indexOf(name)) {
  111. return opts.unknown(arg);
  112. }
  113. out[name] = false;
  114. } else {
  115. for (idx=j+1; idx < arg.length; idx++) {
  116. if (arg.charCodeAt(idx) === 61) break; // "="
  117. }
  118. name = arg.substring(j, idx);
  119. val = arg.substring(++idx) || (i+1 === len || (''+args[i+1]).charCodeAt(0) === 45 || args[++i]);
  120. arr = (j === 2 ? [name] : name);
  121. for (idx=0; idx < arr.length; idx++) {
  122. name = arr[idx];
  123. if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name);
  124. toVal(out, name, (idx + 1 < arr.length) || val, opts);
  125. }
  126. }
  127. }
  128. if (defaults) {
  129. for (k in opts.default) {
  130. if (out[k] === void 0) {
  131. out[k] = opts.default[k];
  132. }
  133. }
  134. }
  135. if (alibi) {
  136. for (k in out) {
  137. arr = opts.alias[k] || [];
  138. while (arr.length > 0) {
  139. out[arr.shift()] = out[k];
  140. }
  141. }
  142. }
  143. return out;
  144. }
  145. const removeBrackets = (v) => v.replace(/[<[].+/, "").trim();
  146. const findAllBrackets = (v) => {
  147. const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
  148. const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
  149. const res = [];
  150. const parse = (match) => {
  151. let variadic = false;
  152. let value = match[1];
  153. if (value.startsWith("...")) {
  154. value = value.slice(3);
  155. variadic = true;
  156. }
  157. return {
  158. required: match[0].startsWith("<"),
  159. value,
  160. variadic
  161. };
  162. };
  163. let angledMatch;
  164. while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) {
  165. res.push(parse(angledMatch));
  166. }
  167. let squareMatch;
  168. while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) {
  169. res.push(parse(squareMatch));
  170. }
  171. return res;
  172. };
  173. const getMriOptions = (options) => {
  174. const result = {alias: {}, boolean: []};
  175. for (const [index, option] of options.entries()) {
  176. if (option.names.length > 1) {
  177. result.alias[option.names[0]] = option.names.slice(1);
  178. }
  179. if (option.isBoolean) {
  180. if (option.negated) {
  181. const hasStringTypeOption = options.some((o, i) => {
  182. return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
  183. });
  184. if (!hasStringTypeOption) {
  185. result.boolean.push(option.names[0]);
  186. }
  187. } else {
  188. result.boolean.push(option.names[0]);
  189. }
  190. }
  191. }
  192. return result;
  193. };
  194. const findLongest = (arr) => {
  195. return arr.sort((a, b) => {
  196. return a.length > b.length ? -1 : 1;
  197. })[0];
  198. };
  199. const padRight = (str, length) => {
  200. return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
  201. };
  202. const camelcase = (input) => {
  203. return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => {
  204. return p1 + p2.toUpperCase();
  205. });
  206. };
  207. const setDotProp = (obj, keys, val) => {
  208. let i = 0;
  209. let length = keys.length;
  210. let t = obj;
  211. let x;
  212. for (; i < length; ++i) {
  213. x = t[keys[i]];
  214. t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : [];
  215. }
  216. };
  217. const setByType = (obj, transforms) => {
  218. for (const key of Object.keys(transforms)) {
  219. const transform = transforms[key];
  220. if (transform.shouldTransform) {
  221. obj[key] = Array.prototype.concat.call([], obj[key]);
  222. if (typeof transform.transformFunction === "function") {
  223. obj[key] = obj[key].map(transform.transformFunction);
  224. }
  225. }
  226. }
  227. };
  228. const getFileName = (input) => {
  229. const m = /([^\\\/]+)$/.exec(input);
  230. return m ? m[1] : "";
  231. };
  232. const camelcaseOptionName = (name) => {
  233. return name.split(".").map((v, i) => {
  234. return i === 0 ? camelcase(v) : v;
  235. }).join(".");
  236. };
  237. class CACError extends Error {
  238. constructor(message) {
  239. super(message);
  240. this.name = this.constructor.name;
  241. if (typeof Error.captureStackTrace === "function") {
  242. Error.captureStackTrace(this, this.constructor);
  243. } else {
  244. this.stack = new Error(message).stack;
  245. }
  246. }
  247. }
  248. class Option {
  249. constructor(rawName, description, config) {
  250. this.rawName = rawName;
  251. this.description = description;
  252. this.config = Object.assign({}, config);
  253. rawName = rawName.replace(/\.\*/g, "");
  254. this.negated = false;
  255. this.names = removeBrackets(rawName).split(",").map((v) => {
  256. let name = v.trim().replace(/^-{1,2}/, "");
  257. if (name.startsWith("no-")) {
  258. this.negated = true;
  259. name = name.replace(/^no-/, "");
  260. }
  261. return camelcaseOptionName(name);
  262. }).sort((a, b) => a.length > b.length ? 1 : -1);
  263. this.name = this.names[this.names.length - 1];
  264. if (this.negated && this.config.default == null) {
  265. this.config.default = true;
  266. }
  267. if (rawName.includes("<")) {
  268. this.required = true;
  269. } else if (rawName.includes("[")) {
  270. this.required = false;
  271. } else {
  272. this.isBoolean = true;
  273. }
  274. }
  275. }
  276. const processArgs = process.argv;
  277. const platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
  278. class Command {
  279. constructor(rawName, description, config = {}, cli) {
  280. this.rawName = rawName;
  281. this.description = description;
  282. this.config = config;
  283. this.cli = cli;
  284. this.options = [];
  285. this.aliasNames = [];
  286. this.name = removeBrackets(rawName);
  287. this.args = findAllBrackets(rawName);
  288. this.examples = [];
  289. }
  290. usage(text) {
  291. this.usageText = text;
  292. return this;
  293. }
  294. allowUnknownOptions() {
  295. this.config.allowUnknownOptions = true;
  296. return this;
  297. }
  298. ignoreOptionDefaultValue() {
  299. this.config.ignoreOptionDefaultValue = true;
  300. return this;
  301. }
  302. version(version, customFlags = "-v, --version") {
  303. this.versionNumber = version;
  304. this.option(customFlags, "Display version number");
  305. return this;
  306. }
  307. example(example) {
  308. this.examples.push(example);
  309. return this;
  310. }
  311. option(rawName, description, config) {
  312. const option = new Option(rawName, description, config);
  313. this.options.push(option);
  314. return this;
  315. }
  316. alias(name) {
  317. this.aliasNames.push(name);
  318. return this;
  319. }
  320. action(callback) {
  321. this.commandAction = callback;
  322. return this;
  323. }
  324. isMatched(name) {
  325. return this.name === name || this.aliasNames.includes(name);
  326. }
  327. get isDefaultCommand() {
  328. return this.name === "" || this.aliasNames.includes("!");
  329. }
  330. get isGlobalCommand() {
  331. return this instanceof GlobalCommand;
  332. }
  333. hasOption(name) {
  334. name = name.split(".")[0];
  335. return this.options.find((option) => {
  336. return option.names.includes(name);
  337. });
  338. }
  339. outputHelp() {
  340. const {name, commands} = this.cli;
  341. const {
  342. versionNumber,
  343. options: globalOptions,
  344. helpCallback
  345. } = this.cli.globalCommand;
  346. let sections = [
  347. {
  348. body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
  349. }
  350. ];
  351. sections.push({
  352. title: "Usage",
  353. body: ` $ ${name} ${this.usageText || this.rawName}`
  354. });
  355. const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0;
  356. if (showCommands) {
  357. const longestCommandName = findLongest(commands.map((command) => command.rawName));
  358. sections.push({
  359. title: "Commands",
  360. body: commands.map((command) => {
  361. return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
  362. }).join("\n")
  363. });
  364. sections.push({
  365. title: `For more info, run any command with the \`--help\` flag`,
  366. body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
  367. });
  368. }
  369. let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
  370. if (!this.isGlobalCommand && !this.isDefaultCommand) {
  371. options = options.filter((option) => option.name !== "version");
  372. }
  373. if (options.length > 0) {
  374. const longestOptionName = findLongest(options.map((option) => option.rawName));
  375. sections.push({
  376. title: "Options",
  377. body: options.map((option) => {
  378. return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`;
  379. }).join("\n")
  380. });
  381. }
  382. if (this.examples.length > 0) {
  383. sections.push({
  384. title: "Examples",
  385. body: this.examples.map((example) => {
  386. if (typeof example === "function") {
  387. return example(name);
  388. }
  389. return example;
  390. }).join("\n")
  391. });
  392. }
  393. if (helpCallback) {
  394. sections = helpCallback(sections) || sections;
  395. }
  396. console.log(sections.map((section) => {
  397. return section.title ? `${section.title}:
  398. ${section.body}` : section.body;
  399. }).join("\n\n"));
  400. }
  401. outputVersion() {
  402. const {name} = this.cli;
  403. const {versionNumber} = this.cli.globalCommand;
  404. if (versionNumber) {
  405. console.log(`${name}/${versionNumber} ${platformInfo}`);
  406. }
  407. }
  408. checkRequiredArgs() {
  409. const minimalArgsCount = this.args.filter((arg) => arg.required).length;
  410. if (this.cli.args.length < minimalArgsCount) {
  411. throw new CACError(`missing required args for command \`${this.rawName}\``);
  412. }
  413. }
  414. checkUnknownOptions() {
  415. const {options, globalCommand} = this.cli;
  416. if (!this.config.allowUnknownOptions) {
  417. for (const name of Object.keys(options)) {
  418. if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) {
  419. throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
  420. }
  421. }
  422. }
  423. }
  424. checkOptionValue() {
  425. const {options: parsedOptions, globalCommand} = this.cli;
  426. const options = [...globalCommand.options, ...this.options];
  427. for (const option of options) {
  428. const value = parsedOptions[option.name.split(".")[0]];
  429. if (option.required) {
  430. const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
  431. if (value === true || value === false && !hasNegated) {
  432. throw new CACError(`option \`${option.rawName}\` value is missing`);
  433. }
  434. }
  435. }
  436. }
  437. }
  438. class GlobalCommand extends Command {
  439. constructor(cli) {
  440. super("@@global@@", "", {}, cli);
  441. }
  442. }
  443. var __assign = Object.assign;
  444. class CAC extends EventEmitter {
  445. constructor(name = "") {
  446. super();
  447. this.name = name;
  448. this.commands = [];
  449. this.rawArgs = [];
  450. this.args = [];
  451. this.options = {};
  452. this.globalCommand = new GlobalCommand(this);
  453. this.globalCommand.usage("<command> [options]");
  454. }
  455. usage(text) {
  456. this.globalCommand.usage(text);
  457. return this;
  458. }
  459. command(rawName, description, config) {
  460. const command = new Command(rawName, description || "", config, this);
  461. command.globalCommand = this.globalCommand;
  462. this.commands.push(command);
  463. return command;
  464. }
  465. option(rawName, description, config) {
  466. this.globalCommand.option(rawName, description, config);
  467. return this;
  468. }
  469. help(callback) {
  470. this.globalCommand.option("-h, --help", "Display this message");
  471. this.globalCommand.helpCallback = callback;
  472. this.showHelpOnExit = true;
  473. return this;
  474. }
  475. version(version, customFlags = "-v, --version") {
  476. this.globalCommand.version(version, customFlags);
  477. this.showVersionOnExit = true;
  478. return this;
  479. }
  480. example(example) {
  481. this.globalCommand.example(example);
  482. return this;
  483. }
  484. outputHelp() {
  485. if (this.matchedCommand) {
  486. this.matchedCommand.outputHelp();
  487. } else {
  488. this.globalCommand.outputHelp();
  489. }
  490. }
  491. outputVersion() {
  492. this.globalCommand.outputVersion();
  493. }
  494. setParsedInfo({args, options}, matchedCommand, matchedCommandName) {
  495. this.args = args;
  496. this.options = options;
  497. if (matchedCommand) {
  498. this.matchedCommand = matchedCommand;
  499. }
  500. if (matchedCommandName) {
  501. this.matchedCommandName = matchedCommandName;
  502. }
  503. return this;
  504. }
  505. unsetMatchedCommand() {
  506. this.matchedCommand = void 0;
  507. this.matchedCommandName = void 0;
  508. }
  509. parse(argv = processArgs, {
  510. run = true
  511. } = {}) {
  512. this.rawArgs = argv;
  513. if (!this.name) {
  514. this.name = argv[1] ? getFileName(argv[1]) : "cli";
  515. }
  516. let shouldParse = true;
  517. for (const command of this.commands) {
  518. const parsed = this.mri(argv.slice(2), command);
  519. const commandName = parsed.args[0];
  520. if (command.isMatched(commandName)) {
  521. shouldParse = false;
  522. const parsedInfo = __assign(__assign({}, parsed), {
  523. args: parsed.args.slice(1)
  524. });
  525. this.setParsedInfo(parsedInfo, command, commandName);
  526. this.emit(`command:${commandName}`, command);
  527. }
  528. }
  529. if (shouldParse) {
  530. for (const command of this.commands) {
  531. if (command.name === "") {
  532. shouldParse = false;
  533. const parsed = this.mri(argv.slice(2), command);
  534. this.setParsedInfo(parsed, command);
  535. this.emit(`command:!`, command);
  536. }
  537. }
  538. }
  539. if (shouldParse) {
  540. const parsed = this.mri(argv.slice(2));
  541. this.setParsedInfo(parsed);
  542. }
  543. if (this.options.help && this.showHelpOnExit) {
  544. this.outputHelp();
  545. run = false;
  546. this.unsetMatchedCommand();
  547. }
  548. if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
  549. this.outputVersion();
  550. run = false;
  551. this.unsetMatchedCommand();
  552. }
  553. const parsedArgv = {args: this.args, options: this.options};
  554. if (run) {
  555. this.runMatchedCommand();
  556. }
  557. if (!this.matchedCommand && this.args[0]) {
  558. this.emit("command:*");
  559. }
  560. return parsedArgv;
  561. }
  562. mri(argv, command) {
  563. const cliOptions = [
  564. ...this.globalCommand.options,
  565. ...command ? command.options : []
  566. ];
  567. const mriOptions = getMriOptions(cliOptions);
  568. let argsAfterDoubleDashes = [];
  569. const doubleDashesIndex = argv.indexOf("--");
  570. if (doubleDashesIndex > -1) {
  571. argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
  572. argv = argv.slice(0, doubleDashesIndex);
  573. }
  574. let parsed = mri2(argv, mriOptions);
  575. parsed = Object.keys(parsed).reduce((res, name) => {
  576. return __assign(__assign({}, res), {
  577. [camelcaseOptionName(name)]: parsed[name]
  578. });
  579. }, {_: []});
  580. const args = parsed._;
  581. const options = {
  582. "--": argsAfterDoubleDashes
  583. };
  584. const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
  585. let transforms = Object.create(null);
  586. for (const cliOption of cliOptions) {
  587. if (!ignoreDefault && cliOption.config.default !== void 0) {
  588. for (const name of cliOption.names) {
  589. options[name] = cliOption.config.default;
  590. }
  591. }
  592. if (Array.isArray(cliOption.config.type)) {
  593. if (transforms[cliOption.name] === void 0) {
  594. transforms[cliOption.name] = Object.create(null);
  595. transforms[cliOption.name]["shouldTransform"] = true;
  596. transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0];
  597. }
  598. }
  599. }
  600. for (const key of Object.keys(parsed)) {
  601. if (key !== "_") {
  602. const keys = key.split(".");
  603. setDotProp(options, keys, parsed[key]);
  604. setByType(options, transforms);
  605. }
  606. }
  607. return {
  608. args,
  609. options
  610. };
  611. }
  612. runMatchedCommand() {
  613. const {args, options, matchedCommand: command} = this;
  614. if (!command || !command.commandAction)
  615. return;
  616. command.checkUnknownOptions();
  617. command.checkOptionValue();
  618. command.checkRequiredArgs();
  619. const actionArgs = [];
  620. command.args.forEach((arg, index) => {
  621. if (arg.variadic) {
  622. actionArgs.push(args.slice(index));
  623. } else {
  624. actionArgs.push(args[index]);
  625. }
  626. });
  627. actionArgs.push(options);
  628. return command.commandAction.apply(this, actionArgs);
  629. }
  630. }
  631. const cac = (name = "") => new CAC(name);
  632. const cli = cac('vite');
  633. let profileSession = global.__vite_profile_session;
  634. let profileCount = 0;
  635. const stopProfiler = (log) => {
  636. if (!profileSession)
  637. return;
  638. return new Promise((res, rej) => {
  639. profileSession.post('Profiler.stop', (err, { profile }) => {
  640. // Write profile to disk, upload, etc.
  641. if (!err) {
  642. const outPath = path.resolve(`./vite-profile-${profileCount++}.cpuprofile`);
  643. fs.writeFileSync(outPath, JSON.stringify(profile));
  644. log(picocolorsExports.yellow(`CPU profile written to ${picocolorsExports.white(picocolorsExports.dim(outPath))}`));
  645. profileSession = undefined;
  646. res();
  647. }
  648. else {
  649. rej(err);
  650. }
  651. });
  652. });
  653. };
  654. const filterDuplicateOptions = (options) => {
  655. for (const [key, value] of Object.entries(options)) {
  656. if (Array.isArray(value)) {
  657. options[key] = value[value.length - 1];
  658. }
  659. }
  660. };
  661. /**
  662. * removing global flags before passing as command specific sub-configs
  663. */
  664. function cleanOptions(options) {
  665. const ret = { ...options };
  666. delete ret['--'];
  667. delete ret.c;
  668. delete ret.config;
  669. delete ret.base;
  670. delete ret.l;
  671. delete ret.logLevel;
  672. delete ret.clearScreen;
  673. delete ret.d;
  674. delete ret.debug;
  675. delete ret.f;
  676. delete ret.filter;
  677. delete ret.m;
  678. delete ret.mode;
  679. return ret;
  680. }
  681. cli
  682. .option('-c, --config <file>', `[string] use specified config file`)
  683. .option('--base <path>', `[string] public base path (default: /)`)
  684. .option('-l, --logLevel <level>', `[string] info | warn | error | silent`)
  685. .option('--clearScreen', `[boolean] allow/disable clear screen when logging`)
  686. .option('-d, --debug [feat]', `[string | boolean] show debug logs`)
  687. .option('-f, --filter <filter>', `[string] filter debug logs`)
  688. .option('-m, --mode <mode>', `[string] set env mode`);
  689. // dev
  690. cli
  691. .command('[root]', 'start dev server') // default command
  692. .alias('serve') // the command is called 'serve' in Vite's API
  693. .alias('dev') // alias to align with the script name
  694. .option('--host [host]', `[string] specify hostname`)
  695. .option('--port <port>', `[number] specify port`)
  696. .option('--https', `[boolean] use TLS + HTTP/2`)
  697. .option('--open [path]', `[boolean | string] open browser on startup`)
  698. .option('--cors', `[boolean] enable CORS`)
  699. .option('--strictPort', `[boolean] exit if specified port is already in use`)
  700. .option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`)
  701. .action(async (root, options) => {
  702. filterDuplicateOptions(options);
  703. // output structure is preserved even after bundling so require()
  704. // is ok here
  705. const { createServer } = await import('./chunks/dep-ca21228b.js').then(function (n) { return n.E; });
  706. try {
  707. const server = await createServer({
  708. root,
  709. base: options.base,
  710. mode: options.mode,
  711. configFile: options.config,
  712. logLevel: options.logLevel,
  713. clearScreen: options.clearScreen,
  714. optimizeDeps: { force: options.force },
  715. server: cleanOptions(options),
  716. });
  717. if (!server.httpServer) {
  718. throw new Error('HTTP server not available');
  719. }
  720. await server.listen();
  721. const info = server.config.logger.info;
  722. const viteStartTime = global.__vite_start_time ?? false;
  723. const startupDurationString = viteStartTime
  724. ? picocolorsExports.dim(`ready in ${picocolorsExports.reset(picocolorsExports.bold(Math.ceil(performance.now() - viteStartTime)))} ms`)
  725. : '';
  726. info(`\n ${picocolorsExports.green(`${picocolorsExports.bold('VITE')} v${VERSION}`)} ${startupDurationString}\n`, { clear: !server.config.logger.hasWarned });
  727. server.printUrls();
  728. bindShortcuts(server, {
  729. print: true,
  730. customShortcuts: [
  731. profileSession && {
  732. key: 'p',
  733. description: 'start/stop the profiler',
  734. async action(server) {
  735. if (profileSession) {
  736. await stopProfiler(server.config.logger.info);
  737. }
  738. else {
  739. const inspector = await import('node:inspector').then((r) => r.default);
  740. await new Promise((res) => {
  741. profileSession = new inspector.Session();
  742. profileSession.connect();
  743. profileSession.post('Profiler.enable', () => {
  744. profileSession.post('Profiler.start', () => {
  745. server.config.logger.info('Profiler started');
  746. res();
  747. });
  748. });
  749. });
  750. }
  751. },
  752. },
  753. ],
  754. });
  755. }
  756. catch (e) {
  757. const logger = createLogger(options.logLevel);
  758. logger.error(picocolorsExports.red(`error when starting dev server:\n${e.stack}`), {
  759. error: e,
  760. });
  761. stopProfiler(logger.info);
  762. process.exit(1);
  763. }
  764. });
  765. // build
  766. cli
  767. .command('build [root]', 'build for production')
  768. .option('--target <target>', `[string] transpile target (default: 'modules')`)
  769. .option('--outDir <dir>', `[string] output directory (default: dist)`)
  770. .option('--assetsDir <dir>', `[string] directory under outDir to place assets in (default: assets)`)
  771. .option('--assetsInlineLimit <number>', `[number] static asset base64 inline threshold in bytes (default: 4096)`)
  772. .option('--ssr [entry]', `[string] build specified entry for server-side rendering`)
  773. .option('--sourcemap', `[boolean] output source maps for build (default: false)`)
  774. .option('--minify [minifier]', `[boolean | "terser" | "esbuild"] enable/disable minification, ` +
  775. `or specify minifier to use (default: esbuild)`)
  776. .option('--manifest [name]', `[boolean | string] emit build manifest json`)
  777. .option('--ssrManifest [name]', `[boolean | string] emit ssr manifest json`)
  778. .option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle (experimental)`)
  779. .option('--emptyOutDir', `[boolean] force empty outDir when it's outside of root`)
  780. .option('-w, --watch', `[boolean] rebuilds when modules have changed on disk`)
  781. .action(async (root, options) => {
  782. filterDuplicateOptions(options);
  783. const { build } = await import('./chunks/dep-ca21228b.js').then(function (n) { return n.D; });
  784. const buildOptions = cleanOptions(options);
  785. try {
  786. await build({
  787. root,
  788. base: options.base,
  789. mode: options.mode,
  790. configFile: options.config,
  791. logLevel: options.logLevel,
  792. clearScreen: options.clearScreen,
  793. optimizeDeps: { force: options.force },
  794. build: buildOptions,
  795. });
  796. }
  797. catch (e) {
  798. createLogger(options.logLevel).error(picocolorsExports.red(`error during build:\n${e.stack}`), { error: e });
  799. process.exit(1);
  800. }
  801. finally {
  802. stopProfiler((message) => createLogger(options.logLevel).info(message));
  803. }
  804. });
  805. // optimize
  806. cli
  807. .command('optimize [root]', 'pre-bundle dependencies')
  808. .option('--force', `[boolean] force the optimizer to ignore the cache and re-bundle`)
  809. .action(async (root, options) => {
  810. filterDuplicateOptions(options);
  811. const { optimizeDeps } = await import('./chunks/dep-ca21228b.js').then(function (n) { return n.C; });
  812. try {
  813. const config = await resolveConfig({
  814. root,
  815. base: options.base,
  816. configFile: options.config,
  817. logLevel: options.logLevel,
  818. }, 'serve');
  819. await optimizeDeps(config, options.force, true);
  820. }
  821. catch (e) {
  822. createLogger(options.logLevel).error(picocolorsExports.red(`error when optimizing deps:\n${e.stack}`), { error: e });
  823. process.exit(1);
  824. }
  825. });
  826. cli
  827. .command('preview [root]', 'locally preview production build')
  828. .option('--host [host]', `[string] specify hostname`)
  829. .option('--port <port>', `[number] specify port`)
  830. .option('--strictPort', `[boolean] exit if specified port is already in use`)
  831. .option('--https', `[boolean] use TLS + HTTP/2`)
  832. .option('--open [path]', `[boolean | string] open browser on startup`)
  833. .option('--outDir <dir>', `[string] output directory (default: dist)`)
  834. .action(async (root, options) => {
  835. filterDuplicateOptions(options);
  836. const { preview } = await import('./chunks/dep-ca21228b.js').then(function (n) { return n.F; });
  837. try {
  838. const server = await preview({
  839. root,
  840. base: options.base,
  841. configFile: options.config,
  842. logLevel: options.logLevel,
  843. mode: options.mode,
  844. build: {
  845. outDir: options.outDir,
  846. },
  847. preview: {
  848. port: options.port,
  849. strictPort: options.strictPort,
  850. host: options.host,
  851. https: options.https,
  852. open: options.open,
  853. },
  854. });
  855. server.printUrls();
  856. }
  857. catch (e) {
  858. createLogger(options.logLevel).error(picocolorsExports.red(`error when starting preview server:\n${e.stack}`), { error: e });
  859. process.exit(1);
  860. }
  861. finally {
  862. stopProfiler((message) => createLogger(options.logLevel).info(message));
  863. }
  864. });
  865. cli.help();
  866. cli.version(VERSION);
  867. cli.parse();
  868. export { stopProfiler };