You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

946 lines
28 KiB

  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 { O as colors, I as createLogger, r as resolveConfig } from './chunks/dep-Bid9ssRr.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 'esbuild';
  13. import 'path';
  14. import 'fs';
  15. import 'node:child_process';
  16. import 'node:http';
  17. import 'node:https';
  18. import 'tty';
  19. import 'util';
  20. import 'net';
  21. import 'url';
  22. import 'http';
  23. import 'stream';
  24. import 'os';
  25. import 'child_process';
  26. import 'node:os';
  27. import 'node:net';
  28. import 'node:dns';
  29. import 'vite/module-runner';
  30. import 'rollup/parseAst';
  31. import 'node:buffer';
  32. import 'module';
  33. import 'node:readline';
  34. import 'node:process';
  35. import 'node:events';
  36. import 'crypto';
  37. import 'node:assert';
  38. import 'node:v8';
  39. import 'node:worker_threads';
  40. import 'https';
  41. import 'tls';
  42. import 'zlib';
  43. import 'buffer';
  44. import 'assert';
  45. import 'node:querystring';
  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 cleanGlobalCLIOptions(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.configLoader;
  676. delete ret.d;
  677. delete ret.debug;
  678. delete ret.f;
  679. delete ret.filter;
  680. delete ret.m;
  681. delete ret.mode;
  682. delete ret.w;
  683. if ("sourcemap" in ret) {
  684. const sourcemap = ret.sourcemap;
  685. ret.sourcemap = sourcemap === "true" ? true : sourcemap === "false" ? false : ret.sourcemap;
  686. }
  687. if ("watch" in ret) {
  688. const watch = ret.watch;
  689. ret.watch = watch ? {} : void 0;
  690. }
  691. return ret;
  692. }
  693. function cleanBuilderCLIOptions(options) {
  694. const ret = { ...options };
  695. delete ret.app;
  696. return ret;
  697. }
  698. const convertHost = (v) => {
  699. if (typeof v === "number") {
  700. return String(v);
  701. }
  702. return v;
  703. };
  704. const convertBase = (v) => {
  705. if (v === 0) {
  706. return "";
  707. }
  708. return v;
  709. };
  710. cli.option("-c, --config <file>", `[string] use specified config file`).option("--base <path>", `[string] public base path (default: /)`, {
  711. type: [convertBase]
  712. }).option("-l, --logLevel <level>", `[string] info | warn | error | silent`).option("--clearScreen", `[boolean] allow/disable clear screen when logging`).option(
  713. "--configLoader <loader>",
  714. `[string] use 'bundle' to bundle the config with esbuild, or 'runner' (experimental) to process it on the fly, or 'native' (experimental) to load using the native runtime (default: bundle)`
  715. ).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`);
  716. 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(
  717. "--force",
  718. `[boolean] force the optimizer to ignore the cache and re-bundle`
  719. ).action(async (root, options) => {
  720. filterDuplicateOptions(options);
  721. const { createServer } = await import('./chunks/dep-Bid9ssRr.js').then(function (n) { return n.S; });
  722. try {
  723. const server = await createServer({
  724. root,
  725. base: options.base,
  726. mode: options.mode,
  727. configFile: options.config,
  728. configLoader: options.configLoader,
  729. logLevel: options.logLevel,
  730. clearScreen: options.clearScreen,
  731. server: cleanGlobalCLIOptions(options),
  732. forceOptimizeDeps: options.force
  733. });
  734. if (!server.httpServer) {
  735. throw new Error("HTTP server not available");
  736. }
  737. await server.listen();
  738. const info = server.config.logger.info;
  739. const modeString = options.mode && options.mode !== "development" ? ` ${colors.bgGreen(` ${colors.bold(options.mode)} `)}` : "";
  740. const viteStartTime = global.__vite_start_time ?? false;
  741. const startupDurationString = viteStartTime ? colors.dim(
  742. `ready in ${colors.reset(
  743. colors.bold(Math.ceil(performance.now() - viteStartTime))
  744. )} ms`
  745. ) : "";
  746. const hasExistingLogs = process.stdout.bytesWritten > 0 || process.stderr.bytesWritten > 0;
  747. info(
  748. `
  749. ${colors.green(
  750. `${colors.bold("VITE")} v${VERSION}`
  751. )}${modeString} ${startupDurationString}
  752. `,
  753. {
  754. clear: !hasExistingLogs
  755. }
  756. );
  757. server.printUrls();
  758. const customShortcuts = [];
  759. if (profileSession) {
  760. customShortcuts.push({
  761. key: "p",
  762. description: "start/stop the profiler",
  763. async action(server2) {
  764. if (profileSession) {
  765. await stopProfiler(server2.config.logger.info);
  766. } else {
  767. const inspector = await import('node:inspector').then(
  768. (r) => r.default
  769. );
  770. await new Promise((res) => {
  771. profileSession = new inspector.Session();
  772. profileSession.connect();
  773. profileSession.post("Profiler.enable", () => {
  774. profileSession.post("Profiler.start", () => {
  775. server2.config.logger.info("Profiler started");
  776. res();
  777. });
  778. });
  779. });
  780. }
  781. }
  782. });
  783. }
  784. server.bindCLIShortcuts({ print: true, customShortcuts });
  785. } catch (e) {
  786. const logger = createLogger(options.logLevel);
  787. logger.error(colors.red(`error when starting dev server:
  788. ${e.stack}`), {
  789. error: e
  790. });
  791. stopProfiler(logger.info);
  792. process.exit(1);
  793. }
  794. });
  795. cli.command("build [root]", "build for production").option("--target <target>", `[string] transpile target (default: 'modules')`).option("--outDir <dir>", `[string] output directory (default: dist)`).option(
  796. "--assetsDir <dir>",
  797. `[string] directory under outDir to place assets in (default: assets)`
  798. ).option(
  799. "--assetsInlineLimit <number>",
  800. `[number] static asset base64 inline threshold in bytes (default: 4096)`
  801. ).option(
  802. "--ssr [entry]",
  803. `[string] build specified entry for server-side rendering`
  804. ).option(
  805. "--sourcemap [output]",
  806. `[boolean | "inline" | "hidden"] output source maps for build (default: false)`
  807. ).option(
  808. "--minify [minifier]",
  809. `[boolean | "terser" | "esbuild"] enable/disable minification, or specify minifier to use (default: esbuild)`
  810. ).option("--manifest [name]", `[boolean | string] emit build manifest json`).option("--ssrManifest [name]", `[boolean | string] emit ssr manifest json`).option(
  811. "--emptyOutDir",
  812. `[boolean] force empty outDir when it's outside of root`
  813. ).option("-w, --watch", `[boolean] rebuilds when modules have changed on disk`).option("--app", `[boolean] same as \`builder: {}\``).action(
  814. async (root, options) => {
  815. filterDuplicateOptions(options);
  816. const { createBuilder } = await import('./chunks/dep-Bid9ssRr.js').then(function (n) { return n.T; });
  817. const buildOptions = cleanGlobalCLIOptions(
  818. cleanBuilderCLIOptions(options)
  819. );
  820. try {
  821. const inlineConfig = {
  822. root,
  823. base: options.base,
  824. mode: options.mode,
  825. configFile: options.config,
  826. configLoader: options.configLoader,
  827. logLevel: options.logLevel,
  828. clearScreen: options.clearScreen,
  829. build: buildOptions,
  830. ...options.app ? { builder: {} } : {}
  831. };
  832. const builder = await createBuilder(inlineConfig, null);
  833. await builder.buildApp();
  834. } catch (e) {
  835. createLogger(options.logLevel).error(
  836. colors.red(`error during build:
  837. ${e.stack}`),
  838. { error: e }
  839. );
  840. process.exit(1);
  841. } finally {
  842. stopProfiler((message) => createLogger(options.logLevel).info(message));
  843. }
  844. }
  845. );
  846. cli.command(
  847. "optimize [root]",
  848. "pre-bundle dependencies (deprecated, the pre-bundle process runs automatically and does not need to be called)"
  849. ).option(
  850. "--force",
  851. `[boolean] force the optimizer to ignore the cache and re-bundle`
  852. ).action(
  853. async (root, options) => {
  854. filterDuplicateOptions(options);
  855. const { optimizeDeps } = await import('./chunks/dep-Bid9ssRr.js').then(function (n) { return n.R; });
  856. try {
  857. const config = await resolveConfig(
  858. {
  859. root,
  860. base: options.base,
  861. configFile: options.config,
  862. configLoader: options.configLoader,
  863. logLevel: options.logLevel,
  864. mode: options.mode
  865. },
  866. "serve"
  867. );
  868. await optimizeDeps(config, options.force, true);
  869. } catch (e) {
  870. createLogger(options.logLevel).error(
  871. colors.red(`error when optimizing deps:
  872. ${e.stack}`),
  873. { error: e }
  874. );
  875. process.exit(1);
  876. }
  877. }
  878. );
  879. 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(
  880. async (root, options) => {
  881. filterDuplicateOptions(options);
  882. const { preview } = await import('./chunks/dep-Bid9ssRr.js').then(function (n) { return n.U; });
  883. try {
  884. const server = await preview({
  885. root,
  886. base: options.base,
  887. configFile: options.config,
  888. configLoader: options.configLoader,
  889. logLevel: options.logLevel,
  890. mode: options.mode,
  891. build: {
  892. outDir: options.outDir
  893. },
  894. preview: {
  895. port: options.port,
  896. strictPort: options.strictPort,
  897. host: options.host,
  898. open: options.open
  899. }
  900. });
  901. server.printUrls();
  902. server.bindCLIShortcuts({ print: true });
  903. } catch (e) {
  904. createLogger(options.logLevel).error(
  905. colors.red(`error when starting preview server:
  906. ${e.stack}`),
  907. { error: e }
  908. );
  909. process.exit(1);
  910. } finally {
  911. stopProfiler((message) => createLogger(options.logLevel).info(message));
  912. }
  913. }
  914. );
  915. cli.help();
  916. cli.version(VERSION);
  917. cli.parse();
  918. export { stopProfiler };