cli.js 27 KB

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