cli.mjs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209
  1. import { n as onExit, t as watch } from "./shared/watch-DPhTjCBr.mjs";
  2. import { D as version$1, E as package_default } from "./shared/bindingify-input-options-DCTviPFW.mjs";
  3. import { t as arraify } from "./shared/misc-DOSKtd97.mjs";
  4. import { a as getOutputCliKeys, c as styleText, i as getInputCliKeys, n as logger, o as validateCliOptions, r as getCliSchemaInfo } from "./shared/create-bundler-option-DLv8UpsD.mjs";
  5. import { t as rolldown } from "./shared/rolldown-jmAeXo_f.mjs";
  6. import { t as loadConfig } from "./shared/load-config-B55tUA4L.mjs";
  7. import path from "node:path";
  8. import g$1 from "node:process";
  9. import { performance } from "node:perf_hooks";
  10. //#region ../../node_modules/.pnpm/cac@7.0.0/node_modules/cac/dist/index.js
  11. function toArr(any) {
  12. return any == null ? [] : Array.isArray(any) ? any : [any];
  13. }
  14. function toVal(out, key, val, opts) {
  15. var x, old = out[key], nxt = !!~opts.string.indexOf(key) ? val == null || val === true ? "" : String(val) : typeof val === "boolean" ? val : !!~opts.boolean.indexOf(key) ? val === "false" ? false : val === "true" || (out._.push((x = +val, x * 0 === 0) ? x : val), !!val) : (x = +val, x * 0 === 0) ? x : val;
  16. out[key] = old == null ? nxt : Array.isArray(old) ? old.concat(nxt) : [old, nxt];
  17. }
  18. function lib_default(args, opts) {
  19. args = args || [];
  20. opts = opts || {};
  21. var k, arr, arg, name, val, out = { _: [] };
  22. var i = 0, j = 0, idx = 0, len = args.length;
  23. const alibi = opts.alias !== void 0;
  24. const strict = opts.unknown !== void 0;
  25. const defaults = opts.default !== void 0;
  26. opts.alias = opts.alias || {};
  27. opts.string = toArr(opts.string);
  28. opts.boolean = toArr(opts.boolean);
  29. if (alibi) for (k in opts.alias) {
  30. arr = opts.alias[k] = toArr(opts.alias[k]);
  31. for (i = 0; i < arr.length; i++) (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
  32. }
  33. for (i = opts.boolean.length; i-- > 0;) {
  34. arr = opts.alias[opts.boolean[i]] || [];
  35. for (j = arr.length; j-- > 0;) opts.boolean.push(arr[j]);
  36. }
  37. for (i = opts.string.length; i-- > 0;) {
  38. arr = opts.alias[opts.string[i]] || [];
  39. for (j = arr.length; j-- > 0;) opts.string.push(arr[j]);
  40. }
  41. if (defaults) for (k in opts.default) {
  42. name = typeof opts.default[k];
  43. arr = opts.alias[k] = opts.alias[k] || [];
  44. if (opts[name] !== void 0) {
  45. opts[name].push(k);
  46. for (i = 0; i < arr.length; i++) opts[name].push(arr[i]);
  47. }
  48. }
  49. const keys = strict ? Object.keys(opts.alias) : [];
  50. for (i = 0; i < len; i++) {
  51. arg = args[i];
  52. if (arg === "--") {
  53. out._ = out._.concat(args.slice(++i));
  54. break;
  55. }
  56. for (j = 0; j < arg.length; j++) if (arg.charCodeAt(j) !== 45) break;
  57. if (j === 0) out._.push(arg);
  58. else if (arg.substring(j, j + 3) === "no-") {
  59. name = arg.substring(j + 3);
  60. if (strict && !~keys.indexOf(name)) return opts.unknown(arg);
  61. out[name] = false;
  62. } else {
  63. for (idx = j + 1; idx < arg.length; idx++) if (arg.charCodeAt(idx) === 61) break;
  64. name = arg.substring(j, idx);
  65. val = arg.substring(++idx) || i + 1 === len || ("" + args[i + 1]).charCodeAt(0) === 45 || args[++i];
  66. arr = j === 2 ? [name] : name;
  67. for (idx = 0; idx < arr.length; idx++) {
  68. name = arr[idx];
  69. if (strict && !~keys.indexOf(name)) return opts.unknown("-".repeat(j) + name);
  70. toVal(out, name, idx + 1 < arr.length || val, opts);
  71. }
  72. }
  73. }
  74. if (defaults) {
  75. for (k in opts.default) if (out[k] === void 0) out[k] = opts.default[k];
  76. }
  77. if (alibi) for (k in out) {
  78. arr = opts.alias[k] || [];
  79. while (arr.length > 0) out[arr.shift()] = out[k];
  80. }
  81. return out;
  82. }
  83. function removeBrackets(v) {
  84. return v.replace(/[<[].+/, "").trim();
  85. }
  86. function findAllBrackets(v) {
  87. const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
  88. const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
  89. const res = [];
  90. const parse = (match) => {
  91. let variadic = false;
  92. let value = match[1];
  93. if (value.startsWith("...")) {
  94. value = value.slice(3);
  95. variadic = true;
  96. }
  97. return {
  98. required: match[0].startsWith("<"),
  99. value,
  100. variadic
  101. };
  102. };
  103. let angledMatch;
  104. while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) res.push(parse(angledMatch));
  105. let squareMatch;
  106. while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) res.push(parse(squareMatch));
  107. return res;
  108. }
  109. function getMriOptions(options) {
  110. const result = {
  111. alias: {},
  112. boolean: []
  113. };
  114. for (const [index, option] of options.entries()) {
  115. if (option.names.length > 1) result.alias[option.names[0]] = option.names.slice(1);
  116. if (option.isBoolean) if (option.negated) {
  117. if (!options.some((o, i) => {
  118. return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
  119. })) result.boolean.push(option.names[0]);
  120. } else result.boolean.push(option.names[0]);
  121. }
  122. return result;
  123. }
  124. function findLongest(arr) {
  125. return arr.sort((a, b) => {
  126. return a.length > b.length ? -1 : 1;
  127. })[0];
  128. }
  129. function padRight(str, length) {
  130. return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
  131. }
  132. function camelcase(input) {
  133. return input.replaceAll(/([a-z])-([a-z])/g, (_, p1, p2) => {
  134. return p1 + p2.toUpperCase();
  135. });
  136. }
  137. function setDotProp(obj, keys, val) {
  138. let current = obj;
  139. for (let i = 0; i < keys.length; i++) {
  140. const key = keys[i];
  141. if (i === keys.length - 1) {
  142. current[key] = val;
  143. return;
  144. }
  145. if (current[key] == null) {
  146. const nextKeyIsArrayIndex = +keys[i + 1] > -1;
  147. current[key] = nextKeyIsArrayIndex ? [] : {};
  148. }
  149. current = current[key];
  150. }
  151. }
  152. function setByType(obj, transforms) {
  153. for (const key of Object.keys(transforms)) {
  154. const transform = transforms[key];
  155. if (transform.shouldTransform) {
  156. obj[key] = [obj[key]].flat();
  157. if (typeof transform.transformFunction === "function") obj[key] = obj[key].map(transform.transformFunction);
  158. }
  159. }
  160. }
  161. function getFileName(input) {
  162. const m = /([^\\/]+)$/.exec(input);
  163. return m ? m[1] : "";
  164. }
  165. function camelcaseOptionName(name) {
  166. return name.split(".").map((v, i) => {
  167. return i === 0 ? camelcase(v) : v;
  168. }).join(".");
  169. }
  170. var CACError = class extends Error {
  171. constructor(message) {
  172. super(message);
  173. this.name = "CACError";
  174. if (typeof Error.captureStackTrace !== "function") this.stack = new Error(message).stack;
  175. }
  176. };
  177. var Option = class {
  178. rawName;
  179. description;
  180. /** Option name */
  181. name;
  182. /** Option name and aliases */
  183. names;
  184. isBoolean;
  185. required;
  186. config;
  187. negated;
  188. constructor(rawName, description, config) {
  189. this.rawName = rawName;
  190. this.description = description;
  191. this.config = Object.assign({}, config);
  192. rawName = rawName.replaceAll(".*", "");
  193. this.negated = false;
  194. this.names = removeBrackets(rawName).split(",").map((v) => {
  195. let name = v.trim().replace(/^-{1,2}/, "");
  196. if (name.startsWith("no-")) {
  197. this.negated = true;
  198. name = name.replace(/^no-/, "");
  199. }
  200. return camelcaseOptionName(name);
  201. }).sort((a, b) => a.length > b.length ? 1 : -1);
  202. this.name = this.names.at(-1);
  203. if (this.negated && this.config.default == null) this.config.default = true;
  204. if (rawName.includes("<")) this.required = true;
  205. else if (rawName.includes("[")) this.required = false;
  206. else this.isBoolean = true;
  207. }
  208. };
  209. let runtimeProcessArgs;
  210. let runtimeInfo;
  211. if (typeof process !== "undefined") {
  212. let runtimeName;
  213. if (typeof Deno !== "undefined" && typeof Deno.version?.deno === "string") runtimeName = "deno";
  214. else if (typeof Bun !== "undefined" && typeof Bun.version === "string") runtimeName = "bun";
  215. else runtimeName = "node";
  216. runtimeInfo = `${process.platform}-${process.arch} ${runtimeName}-${process.version}`;
  217. runtimeProcessArgs = process.argv;
  218. } else if (typeof navigator === "undefined") runtimeInfo = `unknown`;
  219. else runtimeInfo = `${navigator.platform} ${navigator.userAgent}`;
  220. var Command = class {
  221. rawName;
  222. description;
  223. config;
  224. cli;
  225. options;
  226. aliasNames;
  227. name;
  228. args;
  229. commandAction;
  230. usageText;
  231. versionNumber;
  232. examples;
  233. helpCallback;
  234. globalCommand;
  235. constructor(rawName, description, config = {}, cli) {
  236. this.rawName = rawName;
  237. this.description = description;
  238. this.config = config;
  239. this.cli = cli;
  240. this.options = [];
  241. this.aliasNames = [];
  242. this.name = removeBrackets(rawName);
  243. this.args = findAllBrackets(rawName);
  244. this.examples = [];
  245. }
  246. usage(text) {
  247. this.usageText = text;
  248. return this;
  249. }
  250. allowUnknownOptions() {
  251. this.config.allowUnknownOptions = true;
  252. return this;
  253. }
  254. ignoreOptionDefaultValue() {
  255. this.config.ignoreOptionDefaultValue = true;
  256. return this;
  257. }
  258. version(version, customFlags = "-v, --version") {
  259. this.versionNumber = version;
  260. this.option(customFlags, "Display version number");
  261. return this;
  262. }
  263. example(example) {
  264. this.examples.push(example);
  265. return this;
  266. }
  267. /**
  268. * Add a option for this command
  269. * @param rawName Raw option name(s)
  270. * @param description Option description
  271. * @param config Option config
  272. */
  273. option(rawName, description, config) {
  274. const option = new Option(rawName, description, config);
  275. this.options.push(option);
  276. return this;
  277. }
  278. alias(name) {
  279. this.aliasNames.push(name);
  280. return this;
  281. }
  282. action(callback) {
  283. this.commandAction = callback;
  284. return this;
  285. }
  286. /**
  287. * Check if a command name is matched by this command
  288. * @param name Command name
  289. */
  290. isMatched(name) {
  291. return this.name === name || this.aliasNames.includes(name);
  292. }
  293. get isDefaultCommand() {
  294. return this.name === "" || this.aliasNames.includes("!");
  295. }
  296. get isGlobalCommand() {
  297. return this instanceof GlobalCommand;
  298. }
  299. /**
  300. * Check if an option is registered in this command
  301. * @param name Option name
  302. */
  303. hasOption(name) {
  304. name = name.split(".")[0];
  305. return this.options.find((option) => {
  306. return option.names.includes(name);
  307. });
  308. }
  309. outputHelp() {
  310. const { name, commands } = this.cli;
  311. const { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand;
  312. let sections = [{ body: `${name}${versionNumber ? `/${versionNumber}` : ""}` }];
  313. sections.push({
  314. title: "Usage",
  315. body: ` $ ${name} ${this.usageText || this.rawName}`
  316. });
  317. if ((this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0) {
  318. const longestCommandName = findLongest(commands.map((command) => command.rawName));
  319. sections.push({
  320. title: "Commands",
  321. body: commands.map((command) => {
  322. return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
  323. }).join("\n")
  324. }, {
  325. title: `For more info, run any command with the \`--help\` flag`,
  326. body: commands.map((command) => ` $ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
  327. });
  328. }
  329. let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
  330. if (!this.isGlobalCommand && !this.isDefaultCommand) options = options.filter((option) => option.name !== "version");
  331. if (options.length > 0) {
  332. const longestOptionName = findLongest(options.map((option) => option.rawName));
  333. sections.push({
  334. title: "Options",
  335. body: options.map((option) => {
  336. return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === void 0 ? "" : `(default: ${option.config.default})`}`;
  337. }).join("\n")
  338. });
  339. }
  340. if (this.examples.length > 0) sections.push({
  341. title: "Examples",
  342. body: this.examples.map((example) => {
  343. if (typeof example === "function") return example(name);
  344. return example;
  345. }).join("\n")
  346. });
  347. if (helpCallback) sections = helpCallback(sections) || sections;
  348. console.info(sections.map((section) => {
  349. return section.title ? `${section.title}:\n${section.body}` : section.body;
  350. }).join("\n\n"));
  351. }
  352. outputVersion() {
  353. const { name } = this.cli;
  354. const { versionNumber } = this.cli.globalCommand;
  355. if (versionNumber) console.info(`${name}/${versionNumber} ${runtimeInfo}`);
  356. }
  357. checkRequiredArgs() {
  358. const minimalArgsCount = this.args.filter((arg) => arg.required).length;
  359. if (this.cli.args.length < minimalArgsCount) throw new CACError(`missing required args for command \`${this.rawName}\``);
  360. }
  361. /**
  362. * Check if the parsed options contain any unknown options
  363. *
  364. * Exit and output error when true
  365. */
  366. checkUnknownOptions() {
  367. const { options, globalCommand } = this.cli;
  368. if (!this.config.allowUnknownOptions) {
  369. for (const name of Object.keys(options)) if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
  370. }
  371. }
  372. /**
  373. * Check if the required string-type options exist
  374. */
  375. checkOptionValue() {
  376. const { options: parsedOptions, globalCommand } = this.cli;
  377. const options = [...globalCommand.options, ...this.options];
  378. for (const option of options) {
  379. const value = parsedOptions[option.name.split(".")[0]];
  380. if (option.required) {
  381. const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
  382. if (value === true || value === false && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`);
  383. }
  384. }
  385. }
  386. /**
  387. * Check if the number of args is more than expected
  388. */
  389. checkUnusedArgs() {
  390. const maximumArgsCount = this.args.some((arg) => arg.variadic) ? Infinity : this.args.length;
  391. if (maximumArgsCount < this.cli.args.length) throw new CACError(`Unused args: ${this.cli.args.slice(maximumArgsCount).map((arg) => `\`${arg}\``).join(", ")}`);
  392. }
  393. };
  394. var GlobalCommand = class extends Command {
  395. constructor(cli) {
  396. super("@@global@@", "", {}, cli);
  397. }
  398. };
  399. var CAC = class extends EventTarget {
  400. /** The program name to display in help and version message */
  401. name;
  402. commands;
  403. globalCommand;
  404. matchedCommand;
  405. matchedCommandName;
  406. /**
  407. * Raw CLI arguments
  408. */
  409. rawArgs;
  410. /**
  411. * Parsed CLI arguments
  412. */
  413. args;
  414. /**
  415. * Parsed CLI options, camelCased
  416. */
  417. options;
  418. showHelpOnExit;
  419. showVersionOnExit;
  420. /**
  421. * @param name The program name to display in help and version message
  422. */
  423. constructor(name = "") {
  424. super();
  425. this.name = name;
  426. this.commands = [];
  427. this.rawArgs = [];
  428. this.args = [];
  429. this.options = {};
  430. this.globalCommand = new GlobalCommand(this);
  431. this.globalCommand.usage("<command> [options]");
  432. }
  433. /**
  434. * Add a global usage text.
  435. *
  436. * This is not used by sub-commands.
  437. */
  438. usage(text) {
  439. this.globalCommand.usage(text);
  440. return this;
  441. }
  442. /**
  443. * Add a sub-command
  444. */
  445. command(rawName, description, config) {
  446. const command = new Command(rawName, description || "", config, this);
  447. command.globalCommand = this.globalCommand;
  448. this.commands.push(command);
  449. return command;
  450. }
  451. /**
  452. * Add a global CLI option.
  453. *
  454. * Which is also applied to sub-commands.
  455. */
  456. option(rawName, description, config) {
  457. this.globalCommand.option(rawName, description, config);
  458. return this;
  459. }
  460. /**
  461. * Show help message when `-h, --help` flags appear.
  462. *
  463. */
  464. help(callback) {
  465. this.globalCommand.option("-h, --help", "Display this message");
  466. this.globalCommand.helpCallback = callback;
  467. this.showHelpOnExit = true;
  468. return this;
  469. }
  470. /**
  471. * Show version number when `-v, --version` flags appear.
  472. *
  473. */
  474. version(version, customFlags = "-v, --version") {
  475. this.globalCommand.version(version, customFlags);
  476. this.showVersionOnExit = true;
  477. return this;
  478. }
  479. /**
  480. * Add a global example.
  481. *
  482. * This example added here will not be used by sub-commands.
  483. */
  484. example(example) {
  485. this.globalCommand.example(example);
  486. return this;
  487. }
  488. /**
  489. * Output the corresponding help message
  490. * When a sub-command is matched, output the help message for the command
  491. * Otherwise output the global one.
  492. *
  493. */
  494. outputHelp() {
  495. if (this.matchedCommand) this.matchedCommand.outputHelp();
  496. else this.globalCommand.outputHelp();
  497. }
  498. /**
  499. * Output the version number.
  500. *
  501. */
  502. outputVersion() {
  503. this.globalCommand.outputVersion();
  504. }
  505. setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
  506. this.args = args;
  507. this.options = options;
  508. if (matchedCommand) this.matchedCommand = matchedCommand;
  509. if (matchedCommandName) this.matchedCommandName = matchedCommandName;
  510. return this;
  511. }
  512. unsetMatchedCommand() {
  513. this.matchedCommand = void 0;
  514. this.matchedCommandName = void 0;
  515. }
  516. /**
  517. * Parse argv
  518. */
  519. parse(argv, { run = true } = {}) {
  520. if (!argv) {
  521. if (!runtimeProcessArgs) throw new Error("No argv provided and runtime process argv is not available.");
  522. argv = runtimeProcessArgs;
  523. }
  524. this.rawArgs = argv;
  525. if (!this.name) this.name = argv[1] ? getFileName(argv[1]) : "cli";
  526. let shouldParse = true;
  527. for (const command of this.commands) {
  528. const parsed = this.mri(argv.slice(2), command);
  529. const commandName = parsed.args[0];
  530. if (command.isMatched(commandName)) {
  531. shouldParse = false;
  532. const parsedInfo = {
  533. ...parsed,
  534. args: parsed.args.slice(1)
  535. };
  536. this.setParsedInfo(parsedInfo, command, commandName);
  537. this.dispatchEvent(new CustomEvent(`command:${commandName}`, { detail: command }));
  538. }
  539. }
  540. if (shouldParse) {
  541. for (const command of this.commands) if (command.isDefaultCommand) {
  542. shouldParse = false;
  543. const parsed = this.mri(argv.slice(2), command);
  544. this.setParsedInfo(parsed, command);
  545. this.dispatchEvent(new CustomEvent("command:!", { detail: command }));
  546. }
  547. }
  548. if (shouldParse) {
  549. const parsed = this.mri(argv.slice(2));
  550. this.setParsedInfo(parsed);
  551. }
  552. if (this.options.help && this.showHelpOnExit) {
  553. this.outputHelp();
  554. run = false;
  555. this.unsetMatchedCommand();
  556. }
  557. if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
  558. this.outputVersion();
  559. run = false;
  560. this.unsetMatchedCommand();
  561. }
  562. const parsedArgv = {
  563. args: this.args,
  564. options: this.options
  565. };
  566. if (run) this.runMatchedCommand();
  567. if (!this.matchedCommand && this.args[0]) this.dispatchEvent(new CustomEvent("command:*", { detail: this.args[0] }));
  568. return parsedArgv;
  569. }
  570. mri(argv, command) {
  571. const cliOptions = [...this.globalCommand.options, ...command ? command.options : []];
  572. const mriOptions = getMriOptions(cliOptions);
  573. let argsAfterDoubleDashes = [];
  574. const doubleDashesIndex = argv.indexOf("--");
  575. if (doubleDashesIndex !== -1) {
  576. argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
  577. argv = argv.slice(0, doubleDashesIndex);
  578. }
  579. let parsed = lib_default(argv, mriOptions);
  580. parsed = Object.keys(parsed).reduce((res, name) => {
  581. return {
  582. ...res,
  583. [camelcaseOptionName(name)]: parsed[name]
  584. };
  585. }, { _: [] });
  586. const args = parsed._;
  587. const options = { "--": argsAfterDoubleDashes };
  588. const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
  589. const transforms = Object.create(null);
  590. for (const cliOption of cliOptions) {
  591. if (!ignoreDefault && cliOption.config.default !== void 0) for (const name of cliOption.names) options[name] = cliOption.config.default;
  592. if (Array.isArray(cliOption.config.type) && transforms[cliOption.name] === void 0) {
  593. transforms[cliOption.name] = Object.create(null);
  594. transforms[cliOption.name].shouldTransform = true;
  595. transforms[cliOption.name].transformFunction = cliOption.config.type[0];
  596. }
  597. }
  598. for (const key of Object.keys(parsed)) if (key !== "_") {
  599. setDotProp(options, key.split("."), parsed[key]);
  600. setByType(options, transforms);
  601. }
  602. return {
  603. args,
  604. options
  605. };
  606. }
  607. runMatchedCommand() {
  608. const { args, options, matchedCommand: command } = this;
  609. if (!command || !command.commandAction) return;
  610. command.checkUnknownOptions();
  611. command.checkOptionValue();
  612. command.checkRequiredArgs();
  613. command.checkUnusedArgs();
  614. const actionArgs = [];
  615. command.args.forEach((arg, index) => {
  616. if (arg.variadic) actionArgs.push(args.slice(index));
  617. else actionArgs.push(args[index]);
  618. });
  619. actionArgs.push(options);
  620. return command.commandAction.apply(this, actionArgs);
  621. }
  622. };
  623. /**
  624. * @param name The program name to display in help and version message
  625. */
  626. const cac = (name = "") => new CAC(name);
  627. //#endregion
  628. //#region src/cli/arguments/alias.ts
  629. const alias = {
  630. config: {
  631. abbreviation: "c",
  632. hint: "filename"
  633. },
  634. configLoader: { hint: "loader" },
  635. help: { abbreviation: "h" },
  636. version: { abbreviation: "v" },
  637. watch: { abbreviation: "w" },
  638. dir: {
  639. abbreviation: "d",
  640. requireValue: true
  641. },
  642. file: {
  643. abbreviation: "o",
  644. requireValue: true
  645. },
  646. external: { abbreviation: "e" },
  647. format: { abbreviation: "f" },
  648. name: { abbreviation: "n" },
  649. globals: { abbreviation: "g" },
  650. sourcemap: { abbreviation: "s" },
  651. minify: { abbreviation: "m" },
  652. platform: { abbreviation: "p" },
  653. assetFileNames: { hint: "name" },
  654. chunkFileNames: { hint: "name" },
  655. entryFileNames: { hint: "name" },
  656. externalLiveBindings: { reverse: true },
  657. treeshake: { reverse: true },
  658. preserveEntrySignatures: { reverse: true },
  659. moduleTypes: { hint: "types" }
  660. };
  661. //#endregion
  662. //#region src/cli/arguments/utils.ts
  663. function setNestedProperty(obj, path, value) {
  664. const keys = path.split(".");
  665. let current = obj;
  666. for (let i = 0; i < keys.length - 1; i++) {
  667. if (!current[keys[i]]) current[keys[i]] = {};
  668. current = current[keys[i]];
  669. }
  670. const finalKey = keys[keys.length - 1];
  671. Object.defineProperty(current, finalKey, {
  672. value,
  673. writable: true,
  674. enumerable: true,
  675. configurable: true
  676. });
  677. }
  678. function camelCaseToKebabCase(str) {
  679. return str.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`);
  680. }
  681. //#endregion
  682. //#region src/cli/arguments/normalize.ts
  683. const reservedKeys = /* @__PURE__ */ new Set([
  684. "help",
  685. "version",
  686. "config",
  687. "watch",
  688. "environment",
  689. "configLoader"
  690. ]);
  691. function normalizeCliOptions(cliOptions, positionals) {
  692. const [data, errors] = validateCliOptions(cliOptions);
  693. if (errors?.length) {
  694. errors.forEach((error) => {
  695. logger.error(`${error}. You can use \`rolldown -h\` to see the help.`);
  696. });
  697. process.exit(1);
  698. }
  699. const options = data ?? {};
  700. const result = {
  701. input: {},
  702. output: {},
  703. help: options.help ?? false,
  704. version: options.version ?? false,
  705. watch: options.watch ?? false
  706. };
  707. if (typeof options.config === "string") result.config = options.config;
  708. else if (options.config === true) result.config = "";
  709. if (options.environment !== void 0) result.environment = options.environment;
  710. if (options.configLoader !== void 0) result.configLoader = options.configLoader;
  711. const keysOfInput = new Set(getInputCliKeys());
  712. const keysOfOutput = new Set(getOutputCliKeys());
  713. for (let [key, value] of Object.entries(options)) {
  714. const [primary] = key.split(".");
  715. if (keysOfInput.has(primary)) setNestedProperty(result.input, key, value);
  716. else if (keysOfOutput.has(primary)) setNestedProperty(result.output, key, value);
  717. else if (!reservedKeys.has(key)) {
  718. logger.error(`Unknown option: ${key}`);
  719. process.exit(1);
  720. }
  721. }
  722. if (!result.config && positionals.length > 0) {
  723. if (Array.isArray(result.input.input)) result.input.input.push(...positionals);
  724. else result.input.input = positionals;
  725. }
  726. return result;
  727. }
  728. //#endregion
  729. //#region src/cli/arguments/index.ts
  730. const schemaInfo = getCliSchemaInfo();
  731. const options = Object.fromEntries(Object.entries(schemaInfo).filter(([_key, info]) => info.type !== "never").map(([key, info]) => {
  732. const config = alias[key];
  733. let description = info?.description ?? config?.description ?? "";
  734. if (config?.reverse) {
  735. if (description.startsWith("enable")) description = description.replace("enable", "disable");
  736. else if (!description.startsWith("Avoid")) description = `disable ${description}`;
  737. }
  738. const result = {
  739. type: info.type === "boolean" ? "boolean" : "string",
  740. description
  741. };
  742. if (config?.abbreviation) result.short = config.abbreviation;
  743. if (config?.hint) result.hint = config.hint;
  744. return [config?.reverse ? `no-${key}` : key, result];
  745. }));
  746. const knownKeys = new Set(Object.keys(schemaInfo));
  747. for (const key of Object.keys(schemaInfo)) {
  748. const dotIdx = key.indexOf(".");
  749. if (dotIdx > 0) knownKeys.add(key.substring(0, dotIdx));
  750. }
  751. const shortAliases = /* @__PURE__ */ new Set();
  752. for (const config of Object.values(alias)) if (config?.abbreviation) shortAliases.add(config.abbreviation);
  753. function kebabToCamelCase(input) {
  754. return input.replaceAll(/([a-z])-([a-z])/g, (_, p1, p2) => {
  755. return p1 + p2.toUpperCase();
  756. });
  757. }
  758. function camelizeNestedKeys(value) {
  759. const result = {};
  760. for (const [key, nestedValue] of Object.entries(value)) if (Array.isArray(nestedValue)) result[kebabToCamelCase(key)] = nestedValue;
  761. else if (nestedValue && typeof nestedValue === "object") result[kebabToCamelCase(key)] = camelizeNestedKeys(nestedValue);
  762. else result[kebabToCamelCase(key)] = nestedValue;
  763. return result;
  764. }
  765. function parseCliArguments() {
  766. const cli = cac("rolldown");
  767. for (const [key, info] of Object.entries(schemaInfo)) {
  768. if (info.type === "never") continue;
  769. const config = alias[key];
  770. let rawName = "";
  771. if (config?.abbreviation) rawName += `-${config.abbreviation}, `;
  772. if (config?.reverse) rawName += `--no-${key}`;
  773. else rawName += `--${key}`;
  774. if (info.type !== "boolean" && !config?.reverse) {
  775. if (config?.requireValue) rawName += ` <${config?.hint ?? key}>`;
  776. else rawName += ` [${config?.hint ?? key}]`;
  777. }
  778. cli.option(rawName, info.description ?? config?.description ?? "");
  779. }
  780. let parsedInput = [];
  781. let parsedOptions = {};
  782. const cmd = cli.command("[...input]", "");
  783. cmd.allowUnknownOptions();
  784. cmd.ignoreOptionDefaultValue();
  785. cmd.action((input, opts) => {
  786. parsedInput = input;
  787. parsedOptions = opts;
  788. });
  789. try {
  790. cli.parse(process.argv, { run: true });
  791. } catch (err) {
  792. if (err?.name === "CACError") {
  793. const match = err.message.match(/option `(.+?)` value is missing/);
  794. if (match) {
  795. const optName = match[1].replace(/ [<[].*/, "").replace(/^-\w, /, "");
  796. logger.error(`Option \`${optName}\` requires a value but none was provided.`);
  797. } else logger.error(err.message);
  798. process.exit(1);
  799. }
  800. throw err;
  801. }
  802. delete parsedOptions["--"];
  803. for (const short of shortAliases) delete parsedOptions[short];
  804. for (const key of Object.keys(parsedOptions)) if (key === "__proto__" || key === "constructor" || key === "prototype" || key.startsWith("__proto__.") || key.startsWith("constructor.") || key.startsWith("prototype.")) delete parsedOptions[key];
  805. const unknownKeys = Object.keys(parsedOptions).filter((k) => !knownKeys.has(k));
  806. if (unknownKeys.length > 0) {
  807. unknownKeys.sort();
  808. const single = unknownKeys.length === 1;
  809. logger.warn(`Option \`${unknownKeys.join(",")}\` ${single ? "is" : "are"} unrecognized. We will ignore ${single ? "this" : "those"} option${single ? "" : "s"}.`);
  810. }
  811. parsedOptions = camelizeNestedKeys(parsedOptions);
  812. const rawArgs = { ...parsedOptions };
  813. for (const key of unknownKeys) delete parsedOptions[key];
  814. for (const [key, value] of Object.entries(parsedOptions)) {
  815. const type = schemaInfo[key]?.type;
  816. if (Array.isArray(value)) {
  817. if (type !== "array" && type !== "object") parsedOptions[key] = value[value.length - 1];
  818. } else if (type === "array" && typeof value === "string") parsedOptions[key] = [value];
  819. }
  820. for (const [schemaKey, info] of Object.entries(schemaInfo)) {
  821. if (info.type !== "object") continue;
  822. const parts = schemaKey.split(".");
  823. let parent = parsedOptions;
  824. for (let i = 0; i < parts.length - 1; i++) parent = parent?.[parts[i]];
  825. const leafKey = parts[parts.length - 1];
  826. const value = parent?.[leafKey];
  827. if (value === void 0) continue;
  828. const values = Array.isArray(value) ? value : [value];
  829. if (typeof values[0] !== "string") continue;
  830. let usedDeprecatedSyntax = false;
  831. const result = {};
  832. for (const v of values) for (const pair of String(v).split(",")) {
  833. const colonIdx = pair.indexOf(":");
  834. const eqIdx = pair.indexOf("=");
  835. let k;
  836. let val;
  837. if (colonIdx > 0 && (eqIdx === -1 || colonIdx < eqIdx)) {
  838. k = pair.slice(0, colonIdx);
  839. val = pair.slice(colonIdx + 1);
  840. } else if (eqIdx > 0) {
  841. k = pair.slice(0, eqIdx);
  842. val = pair.slice(eqIdx + 1);
  843. usedDeprecatedSyntax = true;
  844. } else continue;
  845. result[k] = val;
  846. }
  847. if (usedDeprecatedSyntax) {
  848. const optionName = camelCaseToKebabCase(schemaKey);
  849. logger.warn(`Using \`key=value\` syntax for \`--${optionName}\` is deprecated. Use \`key:value\` instead.`);
  850. }
  851. parent[leafKey] = result;
  852. }
  853. return {
  854. ...normalizeCliOptions(parsedOptions, parsedInput),
  855. rawArgs
  856. };
  857. }
  858. //#endregion
  859. //#region src/utils/clear-screen.ts
  860. const CLEAR_SCREEN = "\x1Bc";
  861. function getClearScreenFunction(options) {
  862. const isTTY = process.stdout.isTTY;
  863. const isAnyOptionNotAllowingClearScreen = arraify(options).some(({ watch }) => watch === false || watch?.clearScreen === false);
  864. if (isTTY && !isAnyOptionNotAllowingClearScreen) return () => {
  865. process.stdout.write(CLEAR_SCREEN);
  866. };
  867. }
  868. //#endregion
  869. //#region \0@oxc-project+runtime@0.152.0/helpers/esm/usingCtx.js
  870. function _usingCtx() {
  871. var r = "function" == typeof SuppressedError ? SuppressedError : function(r, e) {
  872. var n = Error();
  873. return n.name = "SuppressedError", n.error = r, n.suppressed = e, n;
  874. }, e = {}, n = [];
  875. function using(r, e) {
  876. if (null != e) {
  877. if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
  878. if (r) var o = e[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
  879. if (void 0 === o && (o = e[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r)) var t = o;
  880. if ("function" != typeof o) throw new TypeError("Object is not disposable.");
  881. t && (o = function o() {
  882. try {
  883. t.call(e);
  884. } catch (r) {
  885. return Promise.reject(r);
  886. }
  887. }), n.push({
  888. v: e,
  889. d: o,
  890. a: r
  891. });
  892. } else r && n.push({
  893. d: e,
  894. a: r
  895. });
  896. return e;
  897. }
  898. return {
  899. e,
  900. u: using.bind(null, !1),
  901. a: using.bind(null, !0),
  902. d: function d() {
  903. var o, t = this.e, s = 0;
  904. function next() {
  905. for (; o = n.pop();) try {
  906. if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
  907. if (o.d) {
  908. var r = o.d.call(o.v);
  909. if (o.a) return s |= 2, Promise.resolve(r).then(next, err);
  910. } else s |= 1;
  911. } catch (r) {
  912. return err(r);
  913. }
  914. if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
  915. if (t !== e) throw t;
  916. }
  917. function err(n) {
  918. return t = t !== e ? new r(n, t) : n, next();
  919. }
  920. return next();
  921. }
  922. };
  923. }
  924. //#endregion
  925. //#region src/cli/commands/bundle.ts
  926. async function bundleWithConfig(configPath, cliOptions, rawArgs = {}) {
  927. if (cliOptions.watch) {
  928. process.env.ROLLUP_WATCH = "true";
  929. process.env.ROLLDOWN_WATCH = "true";
  930. }
  931. const config = await loadConfig(configPath, { configLoader: cliOptions.configLoader });
  932. const resolvedConfig = typeof config === "function" ? await config(rawArgs) : config;
  933. if (typeof resolvedConfig !== "object" || resolvedConfig === null) {
  934. logger.error(`Invalid configuration from ${configPath}: expected object or array, got ${resolvedConfig}`);
  935. process.exit(1);
  936. }
  937. if (cliOptions.watch) await watchInner(resolvedConfig, cliOptions);
  938. else await bundleInner(resolvedConfig, cliOptions);
  939. }
  940. async function bundleWithCliOptions(cliOptions) {
  941. try {
  942. var _usingCtx$1 = _usingCtx();
  943. if (cliOptions.output.dir || cliOptions.output.file) {
  944. await (cliOptions.watch ? watchInner : bundleInner)({}, cliOptions);
  945. return;
  946. }
  947. if (cliOptions.watch) {
  948. logger.error("You must specify `output.dir` to use watch mode");
  949. process.exit(1);
  950. }
  951. const { output: outputs } = await _usingCtx$1.a(await rolldown(cliOptions.input)).generate(cliOptions.output);
  952. if (outputs.length === 0) {
  953. logger.error("No output generated");
  954. process.exitCode = 1;
  955. return;
  956. }
  957. for (const file of outputs) {
  958. if (outputs.length > 1) logger.log(`\n${styleText(["cyan", "bold"], `|→ ${file.fileName}:`)}\n`);
  959. console.log(file.type === "asset" ? file.source : file.code);
  960. }
  961. } catch (_) {
  962. _usingCtx$1.e = _;
  963. } finally {
  964. await _usingCtx$1.d();
  965. }
  966. }
  967. async function watchInner(config, cliOptions) {
  968. let normalizedConfig = arraify(config).map((option) => {
  969. return {
  970. ...option,
  971. ...cliOptions.input,
  972. output: arraify(option.output || {}).map((output) => {
  973. return {
  974. ...output,
  975. ...cliOptions.output
  976. };
  977. })
  978. };
  979. });
  980. const watcher = watch(normalizedConfig);
  981. onExit((code) => {
  982. Promise.resolve(watcher.close()).finally(() => {
  983. process.exit(typeof code === "number" ? code : 0);
  984. });
  985. return true;
  986. });
  987. const changedFile = [];
  988. watcher.on("change", (id, event) => {
  989. if (event.event === "update") changedFile.push(id);
  990. });
  991. const clearScreen = getClearScreenFunction(normalizedConfig);
  992. watcher.on("event", async (event) => {
  993. switch (event.code) {
  994. case "START":
  995. clearScreen?.();
  996. break;
  997. case "BUNDLE_START":
  998. if (changedFile.length > 0) logger.log(`Found ${styleText("bold", changedFile.map(relativeId).join(", "))} changed, rebuilding...`);
  999. changedFile.length = 0;
  1000. break;
  1001. case "BUNDLE_END":
  1002. await event.result.close();
  1003. logger.success(`Rebuilt ${styleText("bold", relativeId(event.output[0]))} in ${styleText("green", ms(event.duration))}.`);
  1004. break;
  1005. case "ERROR":
  1006. await event.result.close();
  1007. logger.error(event.error);
  1008. }
  1009. });
  1010. logger.log(`Waiting for changes...`);
  1011. }
  1012. async function bundleInner(config, cliOptions) {
  1013. const startTime = performance.now();
  1014. const result = [];
  1015. const configList = arraify(config);
  1016. for (const config of configList) {
  1017. const outputList = arraify(config.output || {});
  1018. const build = await rolldown({
  1019. ...config,
  1020. ...cliOptions.input
  1021. });
  1022. try {
  1023. for (const output of outputList) result.push(await build.write({
  1024. ...output,
  1025. ...cliOptions.output
  1026. }));
  1027. } finally {
  1028. await build.close();
  1029. }
  1030. }
  1031. result.forEach(printBundleOutputPretty);
  1032. logger.log(``);
  1033. const duration = performance.now() - startTime;
  1034. logger.success(`rolldown v${version$1} Finished in ${styleText("green", ms(duration))}`);
  1035. }
  1036. function printBundleOutputPretty(output) {
  1037. const outputEntries = collectOutputEntries(output.output);
  1038. printOutputEntries(outputEntries, collectOutputLayoutAdjustmentSizes(outputEntries), "<DIR>");
  1039. }
  1040. function collectOutputEntries(output) {
  1041. return output.map((chunk) => ({
  1042. type: chunk.type,
  1043. fileName: chunk.fileName,
  1044. size: chunk.type === "chunk" ? Buffer.byteLength(chunk.code) : Buffer.byteLength(chunk.source)
  1045. }));
  1046. }
  1047. function collectOutputLayoutAdjustmentSizes(entries) {
  1048. let longest = 0;
  1049. let biggestSize = 0;
  1050. for (const entry of entries) {
  1051. if (entry.fileName.length > longest) longest = entry.fileName.length;
  1052. if (entry.size > biggestSize) biggestSize = entry.size;
  1053. }
  1054. const sizePad = displaySize(biggestSize).length;
  1055. return {
  1056. longest,
  1057. biggestSize,
  1058. sizePad
  1059. };
  1060. }
  1061. const numberFormatter = new Intl.NumberFormat("en", {
  1062. maximumFractionDigits: 2,
  1063. minimumFractionDigits: 2
  1064. });
  1065. function displaySize(bytes) {
  1066. return `${numberFormatter.format(bytes / 1e3)} kB`;
  1067. }
  1068. const CHUNK_GROUPS = [{
  1069. type: "asset",
  1070. color: "green"
  1071. }, {
  1072. type: "chunk",
  1073. color: "cyan"
  1074. }];
  1075. function printOutputEntries(entries, sizeAdjustment, distPath) {
  1076. for (const group of CHUNK_GROUPS) {
  1077. const filtered = entries.filter((e) => e.type === group.type);
  1078. if (!filtered.length) continue;
  1079. for (const entry of filtered.sort((a, z) => a.size - z.size)) {
  1080. let log = styleText("dim", withTrailingSlash(distPath));
  1081. log += styleText(group.color, entry.fileName.padEnd(sizeAdjustment.longest + 2));
  1082. log += styleText("dim", entry.type);
  1083. log += styleText("dim", ` │ size: ${displaySize(entry.size).padStart(sizeAdjustment.sizePad)}`);
  1084. logger.log(log);
  1085. }
  1086. }
  1087. }
  1088. function withTrailingSlash(path) {
  1089. if (path[path.length - 1] !== "/") return `${path}/`;
  1090. return path;
  1091. }
  1092. function ms(duration) {
  1093. return duration < 1e3 ? `${duration.toFixed(2)} ms` : `${(duration / 1e3).toFixed(2)} s`;
  1094. }
  1095. function relativeId(id) {
  1096. if (!path.isAbsolute(id)) return id;
  1097. return path.relative(path.resolve(), id);
  1098. }
  1099. //#endregion
  1100. //#region src/cli/commands/help.ts
  1101. const { description, version } = package_default;
  1102. const examples = [
  1103. {
  1104. title: "Bundle with a config file `rolldown.config.mjs`",
  1105. command: "rolldown -c rolldown.config.mjs"
  1106. },
  1107. {
  1108. title: "Bundle the `src/main.ts` to `dist` with `cjs` format",
  1109. command: "rolldown src/main.ts -d dist -f cjs"
  1110. },
  1111. {
  1112. title: "Bundle the `src/main.ts` and handle the `.png` assets to Data URL",
  1113. command: "rolldown src/main.ts -d dist --moduleTypes .png=dataurl"
  1114. },
  1115. {
  1116. title: "Bundle the `src/main.tsx` and minify the output with sourcemap",
  1117. command: "rolldown src/main.tsx -d dist -m -s"
  1118. },
  1119. {
  1120. title: "Create self-executing IIFE using external jQuery as `$` and `_`",
  1121. command: "rolldown src/main.ts -d dist -n bundle -f iife -e jQuery,window._ -g jQuery=$"
  1122. }
  1123. ];
  1124. const notes = ["CLI options will override the configuration file.", "For more information, please visit https://rolldown.rs/."];
  1125. /**
  1126. * Generates the CLI help text as a string.
  1127. */
  1128. function generateHelpText() {
  1129. const lines = [];
  1130. lines.push(`${styleText("gray", `${description} (rolldown v${version})`)}`);
  1131. lines.push("");
  1132. lines.push(`${styleText(["bold", "underline"], "USAGE")} ${styleText("cyan", "rolldown -c <config>")} or ${styleText("cyan", "rolldown <input> <options>")}`);
  1133. lines.push("");
  1134. lines.push(`${styleText(["bold", "underline"], "OPTIONS")}`);
  1135. lines.push("");
  1136. lines.push(Object.entries(options).sort(([a], [b]) => {
  1137. if (options[a].short && !options[b].short) return -1;
  1138. if (!options[a].short && options[b].short) return 1;
  1139. if (options[a].short && options[b].short) return options[a].short.localeCompare(options[b].short);
  1140. return a.localeCompare(b);
  1141. }).map(([option, { type, short, hint, description }]) => {
  1142. let optionStr = ` --${option} `;
  1143. if (short) optionStr += `-${short}, `;
  1144. if (type === "string") optionStr += `<${hint ?? option}>`;
  1145. if (description && description.length > 0) description = description[0].toUpperCase() + description.slice(1);
  1146. return styleText("cyan", optionStr.padEnd(30)) + description + (description && description?.endsWith(".") ? "" : ".");
  1147. }).join("\n"));
  1148. lines.push("");
  1149. lines.push(`${styleText(["bold", "underline"], "EXAMPLES")}`);
  1150. lines.push("");
  1151. examples.forEach(({ title, command }, ord) => {
  1152. lines.push(` ${ord + 1}. ${title}:`);
  1153. lines.push(` ${styleText("cyan", command)}`);
  1154. lines.push("");
  1155. });
  1156. lines.push(`${styleText(["bold", "underline"], "NOTES")}`);
  1157. lines.push("");
  1158. notes.forEach((note) => {
  1159. lines.push(` * ${styleText("gray", note)}`);
  1160. });
  1161. return lines.join("\n");
  1162. }
  1163. function showHelp() {
  1164. logger.log(generateHelpText());
  1165. }
  1166. //#endregion
  1167. //#region src/cli/version-check.ts
  1168. function checkNodeVersion(nodeVersion) {
  1169. const currentVersion = nodeVersion.split(".");
  1170. const major = parseInt(currentVersion[0], 10);
  1171. const minor = parseInt(currentVersion[1], 10);
  1172. return major === 20 && minor >= 19 || major === 22 && minor >= 12 || major > 22;
  1173. }
  1174. //#endregion
  1175. //#region src/cli/index.ts
  1176. if (!checkNodeVersion(g$1.versions.node)) logger.warn(`You are using Node.js ${g$1.versions.node}. Rolldown requires Node.js version 20.19+ or 22.12+. Please upgrade your Node.js version.`);
  1177. async function main() {
  1178. const { rawArgs, ...cliOptions } = parseCliArguments();
  1179. if (cliOptions.environment) {
  1180. const environment = Array.isArray(cliOptions.environment) ? cliOptions.environment : [cliOptions.environment];
  1181. for (const argument of environment) for (const pair of argument.split(",")) {
  1182. const [key, ...value] = pair.split(":");
  1183. g$1.env[key] = value.length === 0 ? String(true) : value.join(":");
  1184. }
  1185. }
  1186. if (cliOptions.help) {
  1187. showHelp();
  1188. return;
  1189. }
  1190. if (cliOptions.version) {
  1191. logger.log(`rolldown v${version$1}`);
  1192. return;
  1193. }
  1194. if (cliOptions.config || cliOptions.config === "") {
  1195. await bundleWithConfig(cliOptions.config, cliOptions, rawArgs);
  1196. return;
  1197. }
  1198. if ("input" in cliOptions.input) {
  1199. await bundleWithCliOptions(cliOptions);
  1200. return;
  1201. }
  1202. showHelp();
  1203. }
  1204. main().catch((err) => {
  1205. logger.error(err);
  1206. g$1.exit(1);
  1207. });
  1208. //#endregion
  1209. export {};