cli.js 27 KB

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