cli.mjs 36 KB

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