source: node_modules/vite/dist/node/cli.js@ de83113

Last change on this file since de83113 was 57e58a3, checked in by ste08 <sjovanoska@…>, 4 months ago

Initial commit

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