@voidzero-dev/vite-plus-core 0.1.3 → 0.1.5-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/dist/rolldown/cli.mjs +617 -184
  2. package/dist/rolldown/config.d.mts +1 -1
  3. package/dist/rolldown/config.mjs +8 -8
  4. package/dist/rolldown/experimental-index.d.mts +2 -2
  5. package/dist/rolldown/experimental-index.mjs +8 -8
  6. package/dist/rolldown/filter-index.d.mts +1 -1
  7. package/dist/rolldown/index.d.mts +1 -1
  8. package/dist/rolldown/index.mjs +8 -8
  9. package/dist/rolldown/parallel-plugin-worker.mjs +5 -5
  10. package/dist/rolldown/parallel-plugin.d.mts +1 -1
  11. package/dist/rolldown/parse-ast-index.mjs +2 -2
  12. package/dist/rolldown/plugins-index.d.mts +2 -2
  13. package/dist/rolldown/plugins-index.mjs +3 -3
  14. package/dist/rolldown/shared/{bindingify-input-options-DdW_FOGG.mjs → bindingify-input-options-DkwIzK4F.mjs} +6 -3
  15. package/dist/rolldown/shared/{constructors-ColrbLxz.d.mts → constructors-Bnr_ApVf.d.mts} +1 -1
  16. package/dist/rolldown/shared/{constructors-CQlws1EK.mjs → constructors-D91FHkmz.mjs} +1 -1
  17. package/dist/rolldown/shared/{define-config-BqZZMLjO.d.mts → define-config-B1jccsL9.d.mts} +18 -0
  18. package/dist/rolldown/shared/{error-FTNambir.mjs → error-tpgdcGrK.mjs} +1 -1
  19. package/dist/rolldown/shared/{load-config-DBRCgd9m.mjs → load-config-Dapgaecf.mjs} +1 -1
  20. package/dist/rolldown/shared/{normalize-string-or-regex-CJTjKt5t.mjs → normalize-string-or-regex-BCllTl21.mjs} +1 -1
  21. package/dist/rolldown/shared/{parse-q7gzDQmi.mjs → parse-DFYpKkKl.mjs} +1 -1
  22. package/dist/rolldown/shared/{rolldown-BJMdRJb1.mjs → rolldown-DK6iIJl8.mjs} +1 -1
  23. package/dist/rolldown/shared/{rolldown-build-DKv2K096.mjs → rolldown-build-rw0HCMhn.mjs} +9 -6
  24. package/dist/rolldown/shared/{transform-CQppMqL8.mjs → transform-BSCulZAO.mjs} +2 -2
  25. package/dist/rolldown/shared/{watch-BeMWbIuq.mjs → watch-D8uEZyLj.mjs} +4 -4
  26. package/dist/rolldown/utils-index.mjs +4 -4
  27. package/dist/tsdown/{build-TmLngPCw-CBoVPzkZ.js → build-BG-XbM6V-hoyhQqI3.js} +41 -153
  28. package/dist/tsdown/build-DHPfiKA--CvTonTfC.js +5 -0
  29. package/dist/tsdown/{debug-tOJ_PtrM-C-Do1Twv.js → debug-C4FmgzkJ-B6m_gRpz.js} +2 -2
  30. package/dist/tsdown/{detect-DK-FDZQ9-CHuRhyUG.js → detect-J1_Vd1yf-BWDiPZkP.js} +1 -1
  31. package/dist/tsdown/{dist-DCol2bGA.js → dist-C9Oecl0H.js} +2 -2
  32. package/dist/tsdown/{dist-Ba2DZx1w.js → dist-Dx-jtFHM.js} +2 -4
  33. package/dist/tsdown/{index-node-Djp92Gzb-B-AUHI4t.js → index-node-Bpsmc0eX-jMz9gD3P.js} +1 -1
  34. package/dist/tsdown/index-types.d.ts +8556 -176
  35. package/dist/tsdown/index.js +5 -5
  36. package/dist/tsdown/{main-DYgM-9Cb.js → main-DN-_H9u2.js} +3 -3
  37. package/dist/tsdown/run.js +3 -3
  38. package/dist/tsdown/{tsc-CberiTDq.js → tsc-OwK9UHsV.js} +1 -1
  39. package/dist/vite/client/client.mjs +112 -0
  40. package/dist/vite/node/chunks/logger.js +1 -1
  41. package/dist/vite/node/chunks/node.js +823 -494
  42. package/dist/vite/node/cli.js +201 -63
  43. package/dist/vite/node/index.d.ts +15 -12
  44. package/dist/vite/node/index.js +1 -1
  45. package/dist/vite/node/module-runner.d.ts +5 -1
  46. package/dist/vite/types/customEvent.d.ts +27 -0
  47. package/package.json +9 -9
  48. package/dist/tsdown/build-gOkJM1H9-D9ngUBpk.js +0 -5
  49. /package/dist/rolldown/shared/{binding-COZdHtee.mjs → binding-BSVL02lq.mjs} +0 -0
  50. /package/dist/tsdown/{filename-BDcjeHGl.js → filename-tIvGuRvQ.js} +0 -0
@@ -1,17 +1,496 @@
1
- import "./shared/binding-COZdHtee.mjs";
2
- import { n as onExit, t as watch } from "./shared/watch-BeMWbIuq.mjs";
3
- import "./shared/normalize-string-or-regex-CJTjKt5t.mjs";
4
- import { S as version, x as description } from "./shared/bindingify-input-options-DdW_FOGG.mjs";
1
+ import "./shared/binding-BSVL02lq.mjs";
2
+ import { n as onExit, t as watch } from "./shared/watch-D8uEZyLj.mjs";
3
+ import "./shared/normalize-string-or-regex-BCllTl21.mjs";
4
+ import { S as version, x as description } from "./shared/bindingify-input-options-DkwIzK4F.mjs";
5
5
  import { t as arraify } from "./shared/misc-DJYbNKZX.mjs";
6
- import { a as getInputCliKeys, i as getCliSchemaInfo, l as styleText$1, o as getOutputCliKeys, r as logger, s as validateCliOptions } from "./shared/rolldown-build-DKv2K096.mjs";
7
- import "./shared/error-FTNambir.mjs";
8
- import "./shared/parse-q7gzDQmi.mjs";
9
- import { t as rolldown } from "./shared/rolldown-BJMdRJb1.mjs";
10
- import { t as loadConfig } from "./shared/load-config-DBRCgd9m.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-rw0HCMhn.mjs";
7
+ import "./shared/error-tpgdcGrK.mjs";
8
+ import "./shared/parse-DFYpKkKl.mjs";
9
+ import { t as rolldown } from "./shared/rolldown-DK6iIJl8.mjs";
10
+ import { t as loadConfig } from "./shared/load-config-Dapgaecf.mjs";
11
11
  import path from "node:path";
12
- import { parseArgs } from "node:util";
13
12
  import process$1 from "node:process";
13
+ import { EventEmitter } from "events";
14
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
15
494
  //#region src/cli/arguments/alias.ts
16
495
  const alias = {
17
496
  config: {
@@ -33,27 +512,15 @@ const alias = {
33
512
  format: { abbreviation: "f" },
34
513
  name: { abbreviation: "n" },
35
514
  globals: { abbreviation: "g" },
36
- sourcemap: {
37
- abbreviation: "s",
38
- default: true
39
- },
515
+ sourcemap: { abbreviation: "s" },
40
516
  minify: { abbreviation: "m" },
41
517
  platform: { abbreviation: "p" },
42
518
  assetFileNames: { hint: "name" },
43
519
  chunkFileNames: { hint: "name" },
44
520
  entryFileNames: { hint: "name" },
45
- externalLiveBindings: {
46
- default: true,
47
- reverse: true
48
- },
49
- treeshake: {
50
- default: true,
51
- reverse: true
52
- },
53
- preserveEntrySignatures: {
54
- default: "strict",
55
- reverse: true
56
- },
521
+ externalLiveBindings: { reverse: true },
522
+ treeshake: { reverse: true },
523
+ preserveEntrySignatures: { reverse: true },
57
524
  moduleTypes: { hint: "types" }
58
525
  };
59
526
  //#endregion
@@ -76,24 +543,17 @@ function setNestedProperty(obj, path, value) {
76
543
  function camelCaseToKebabCase(str) {
77
544
  return str.replace(/[A-Z]/g, (match) => `-${match.toLowerCase()}`);
78
545
  }
79
- function kebabCaseToCamelCase(str) {
80
- return str.replace(/-./g, (match) => match[1].toUpperCase());
81
- }
82
546
  //#endregion
83
547
  //#region src/cli/arguments/normalize.ts
548
+ const reservedKeys = new Set([
549
+ "help",
550
+ "version",
551
+ "config",
552
+ "watch",
553
+ "environment"
554
+ ]);
84
555
  function normalizeCliOptions(cliOptions, positionals) {
85
- const prototypePollutionKeys = [
86
- "__proto__",
87
- "constructor",
88
- "prototype"
89
- ];
90
- const unflattenedCliOptions = {};
91
- for (let [key, value] of Object.entries(cliOptions)) if (prototypePollutionKeys.includes(key)) {} else if (key.includes(".")) {
92
- const [parentKey] = key.split(".");
93
- unflattenedCliOptions[parentKey] ??= {};
94
- setNestedProperty(unflattenedCliOptions, key, value);
95
- } else unflattenedCliOptions[key] = value;
96
- const [data, errors] = validateCliOptions(unflattenedCliOptions);
556
+ const [data, errors] = validateCliOptions(cliOptions);
97
557
  if (errors?.length) {
98
558
  errors.forEach((error) => {
99
559
  logger.error(`${error}. You can use \`rolldown -h\` to see the help.`);
@@ -109,21 +569,15 @@ function normalizeCliOptions(cliOptions, positionals) {
109
569
  watch: options.watch ?? false
110
570
  };
111
571
  if (typeof options.config === "string") result.config = options.config;
572
+ else if (options.config === true) result.config = "";
112
573
  if (options.environment !== void 0) result.environment = options.environment;
113
- const keysOfInput = getInputCliKeys();
114
- const keysOfOutput = getOutputCliKeys();
115
- const reservedKeys = [
116
- "help",
117
- "version",
118
- "config",
119
- "watch",
120
- "environment"
121
- ];
574
+ const keysOfInput = new Set(getInputCliKeys());
575
+ const keysOfOutput = new Set(getOutputCliKeys());
122
576
  for (let [key, value] of Object.entries(options)) {
123
577
  const [primary] = key.split(".");
124
- if (keysOfInput.includes(primary)) setNestedProperty(result.input, key, value);
125
- else if (keysOfOutput.includes(primary)) setNestedProperty(result.output, key, value);
126
- else if (!reservedKeys.includes(key)) {
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)) {
127
581
  logger.error(`Unknown option: ${key}`);
128
582
  process.exit(1);
129
583
  }
@@ -136,119 +590,99 @@ function normalizeCliOptions(cliOptions, positionals) {
136
590
  //#region src/cli/arguments/index.ts
137
591
  const schemaInfo = getCliSchemaInfo();
138
592
  const options = Object.fromEntries(Object.entries(schemaInfo).filter(([_key, info]) => info.type !== "never").map(([key, info]) => {
139
- const config = Object.getOwnPropertyDescriptor(alias, key)?.value;
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
+ }
140
599
  const result = {
141
600
  type: info.type === "boolean" ? "boolean" : "string",
142
- description: info?.description ?? config?.description ?? "",
143
- hint: config?.hint
601
+ description
144
602
  };
145
- if (config && config?.abbreviation) result.short = config?.abbreviation;
146
- if (config && config.reverse) {
147
- if (result.description.startsWith("enable")) result.description = result.description.replace("enable", "disable");
148
- else if (!result.description.startsWith("Avoid")) result.description = `disable ${result.description}`;
149
- }
150
- key = camelCaseToKebabCase(key);
151
- return [config?.reverse ? `no-${key}` : key, result];
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];
152
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);
153
615
  function parseCliArguments() {
154
- const { values, tokens, positionals } = parseArgs({
155
- options,
156
- tokens: true,
157
- allowPositionals: true,
158
- strict: false
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;
159
636
  });
160
- let invalid_options = tokens.filter((token) => token.kind === "option").map((option) => {
161
- let negative = false;
162
- if (option.name.startsWith("no-")) {
163
- const name = kebabCaseToCamelCase(option.name.substring(3));
164
- if (name in schemaInfo) {
165
- delete values[option.name];
166
- option.name = name;
167
- negative = true;
168
- }
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);
169
647
  }
170
- delete values[option.name];
171
- option.name = kebabCaseToCamelCase(option.name);
172
- let originalInfo = schemaInfo[option.name];
173
- if (!originalInfo) return {
174
- name: option.name,
175
- value: option.value
176
- };
177
- let type = originalInfo.type;
178
- if (type === "string" && typeof option.value !== "string") {
179
- let opt = option;
180
- let config = Object.getOwnPropertyDescriptor(alias, opt.name)?.value;
181
- if (config?.requireValue) {
182
- logger.error(`Option \`--${camelCaseToKebabCase(opt.name)}\` requires a value but none was provided.`);
183
- process.exit(1);
184
- }
185
- Object.defineProperty(values, opt.name, {
186
- value: config?.default ?? "",
187
- enumerable: true,
188
- configurable: true,
189
- writable: true
190
- });
191
- } else if (type === "object" && typeof option.value === "string") {
192
- const pairs = option.value.split(",").map((x) => x.split("="));
193
- if (!values[option.name]) Object.defineProperty(values, option.name, {
194
- value: {},
195
- enumerable: true,
196
- configurable: true,
197
- writable: true
198
- });
199
- for (const [key, value] of pairs) if (key && value) Object.defineProperty(values[option.name], key, {
200
- value,
201
- enumerable: true,
202
- configurable: true,
203
- writable: true
204
- });
205
- } else if (type === "array" && typeof option.value === "string") {
206
- if (!values[option.name]) Object.defineProperty(values, option.name, {
207
- value: [],
208
- enumerable: true,
209
- configurable: true,
210
- writable: true
211
- });
212
- values[option.name].push(option.value);
213
- } else if (type === "boolean") Object.defineProperty(values, option.name, {
214
- value: !negative,
215
- enumerable: true,
216
- configurable: true,
217
- writable: true
218
- });
219
- else if (type === "union") {
220
- let defaultValue = Object.getOwnPropertyDescriptor(alias, option.name)?.value;
221
- Object.defineProperty(values, option.name, {
222
- value: option.value ?? defaultValue?.default ?? "",
223
- enumerable: true,
224
- configurable: true,
225
- writable: true
226
- });
227
- } else Object.defineProperty(values, option.name, {
228
- value: option.value ?? "",
229
- enumerable: true,
230
- configurable: true,
231
- writable: true
232
- });
233
- }).filter((item) => {
234
- return item !== void 0;
235
- });
236
- invalid_options.sort((a, b) => {
237
- return a.name.localeCompare(b.name);
238
- });
239
- if (invalid_options.length !== 0) {
240
- let single = invalid_options.length === 1;
241
- logger.warn(`Option \`${invalid_options.map((item) => item.name).join(",")}\` ${single ? "is" : "are"} unrecognized. We will ignore ${single ? "this" : "those"} option${single ? "" : "s"}.`);
242
- }
243
- let rawArgs = {
244
- ...values,
245
- ...invalid_options.reduce((acc, cur) => {
246
- acc[cur.name] = cur.value;
247
- return acc;
248
- }, Object.create(null))
249
- };
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
+ const result = {};
678
+ for (const v of values) for (const pair of String(v).split(",")) {
679
+ const [k, ...rest] = pair.split("=");
680
+ if (k && rest.length > 0) result[k] = rest.join("=");
681
+ }
682
+ parent[leafKey] = result;
683
+ }
250
684
  return {
251
- ...normalizeCliOptions(values, positionals),
685
+ ...normalizeCliOptions(parsedOptions, parsedInput),
252
686
  rawArgs
253
687
  };
254
688
  }
@@ -351,7 +785,7 @@ async function bundleWithCliOptions(cliOptions) {
351
785
  process.exit(1);
352
786
  }
353
787
  for (const file of outputs) {
354
- if (outputs.length > 1) logger.log(`\n${styleText$1(["cyan", "bold"], `|→ ${file.fileName}:`)}\n`);
788
+ if (outputs.length > 1) logger.log(`\n${styleText(["cyan", "bold"], `|→ ${file.fileName}:`)}\n`);
355
789
  console.log(file.type === "asset" ? file.source : file.code);
356
790
  }
357
791
  } catch (_) {
@@ -391,12 +825,12 @@ async function watchInner(config, cliOptions) {
391
825
  clearScreen?.();
392
826
  break;
393
827
  case "BUNDLE_START":
394
- if (changedFile.length > 0) logger.log(`Found ${styleText$1("bold", changedFile.map(relativeId).join(", "))} changed, rebuilding...`);
828
+ if (changedFile.length > 0) logger.log(`Found ${styleText("bold", changedFile.map(relativeId).join(", "))} changed, rebuilding...`);
395
829
  changedFile.length = 0;
396
830
  break;
397
831
  case "BUNDLE_END":
398
832
  await event.result.close();
399
- logger.success(`Rebuilt ${styleText$1("bold", relativeId(event.output[0]))} in ${styleText$1("green", ms(event.duration))}.`);
833
+ logger.success(`Rebuilt ${styleText("bold", relativeId(event.output[0]))} in ${styleText("green", ms(event.duration))}.`);
400
834
  break;
401
835
  case "ERROR":
402
836
  await event.result.close();
@@ -429,7 +863,7 @@ async function bundleInner(config, cliOptions) {
429
863
  result.forEach(printBundleOutputPretty);
430
864
  logger.log(``);
431
865
  const duration = performance.now() - startTime;
432
- logger.success(`rolldown v${version} Finished in ${styleText$1("green", ms(duration))}`);
866
+ logger.success(`rolldown v${version} Finished in ${styleText("green", ms(duration))}`);
433
867
  }
434
868
  function printBundleOutputPretty(output) {
435
869
  const outputEntries = collectOutputEntries(output.output);
@@ -475,10 +909,10 @@ function printOutputEntries(entries, sizeAdjustment, distPath) {
475
909
  const filtered = entries.filter((e) => e.type === group.type);
476
910
  if (!filtered.length) continue;
477
911
  for (const entry of filtered.sort((a, z) => a.size - z.size)) {
478
- let log = styleText$1("dim", withTrailingSlash(distPath));
479
- log += styleText$1(group.color, entry.fileName.padEnd(sizeAdjustment.longest + 2));
480
- log += styleText$1("dim", entry.type);
481
- log += styleText$1("dim", ` │ size: ${displaySize(entry.size).padStart(sizeAdjustment.sizePad)}`);
912
+ let log = styleText("dim", withTrailingSlash(distPath));
913
+ log += styleText(group.color, entry.fileName.padEnd(sizeAdjustment.longest + 2));
914
+ log += styleText("dim", entry.type);
915
+ log += styleText("dim", ` │ size: ${displaySize(entry.size).padStart(sizeAdjustment.sizePad)}`);
482
916
  logger.log(log);
483
917
  }
484
918
  }
@@ -518,22 +952,17 @@ const examples = [
518
952
  command: "rolldown src/main.ts -d dist -n bundle -f iife -e jQuery,window._ -g jQuery=$"
519
953
  }
520
954
  ];
521
- const notes = [
522
- "Due to the API limitation, you need to pass `-s` for `.map` sourcemap file as the last argument.",
523
- "If you are using the configuration, please pass the `-c` as the last argument if you ignore the default configuration file.",
524
- "CLI options will override the configuration file.",
525
- "For more information, please visit https://rolldown.rs/."
526
- ];
955
+ const notes = ["CLI options will override the configuration file.", "For more information, please visit https://rolldown.rs/."];
527
956
  /**
528
957
  * Generates the CLI help text as a string.
529
958
  */
530
959
  function generateHelpText() {
531
960
  const lines = [];
532
- lines.push(`${styleText$1("gray", `${description} (rolldown v${version})`)}`);
961
+ lines.push(`${styleText("gray", `${description} (rolldown v${version})`)}`);
533
962
  lines.push("");
534
- lines.push(`${styleText$1(["bold", "underline"], "USAGE")} ${styleText$1("cyan", "rolldown -c <config>")} or ${styleText$1("cyan", "rolldown <input> <options>")}`);
963
+ lines.push(`${styleText(["bold", "underline"], "USAGE")} ${styleText("cyan", "rolldown -c <config>")} or ${styleText("cyan", "rolldown <input> <options>")}`);
535
964
  lines.push("");
536
- lines.push(`${styleText$1(["bold", "underline"], "OPTIONS")}`);
965
+ lines.push(`${styleText(["bold", "underline"], "OPTIONS")}`);
537
966
  lines.push("");
538
967
  lines.push(Object.entries(options).sort(([a], [b]) => {
539
968
  if (options[a].short && !options[b].short) return -1;
@@ -546,20 +975,20 @@ function generateHelpText() {
546
975
  if (short) optionStr += `-${short}, `;
547
976
  if (type === "string") optionStr += `<${hint ?? option}>`;
548
977
  if (description && description.length > 0) description = description[0].toUpperCase() + description.slice(1);
549
- return styleText$1("cyan", optionStr.padEnd(30)) + description + (description && description?.endsWith(".") ? "" : ".");
978
+ return styleText("cyan", optionStr.padEnd(30)) + description + (description && description?.endsWith(".") ? "" : ".");
550
979
  }).join("\n"));
551
980
  lines.push("");
552
- lines.push(`${styleText$1(["bold", "underline"], "EXAMPLES")}`);
981
+ lines.push(`${styleText(["bold", "underline"], "EXAMPLES")}`);
553
982
  lines.push("");
554
983
  examples.forEach(({ title, command }, ord) => {
555
984
  lines.push(` ${ord + 1}. ${title}:`);
556
- lines.push(` ${styleText$1("cyan", command)}`);
985
+ lines.push(` ${styleText("cyan", command)}`);
557
986
  lines.push("");
558
987
  });
559
- lines.push(`${styleText$1(["bold", "underline"], "NOTES")}`);
988
+ lines.push(`${styleText(["bold", "underline"], "NOTES")}`);
560
989
  lines.push("");
561
990
  notes.forEach((note) => {
562
- lines.push(` * ${styleText$1("gray", note)}`);
991
+ lines.push(` * ${styleText("gray", note)}`);
563
992
  });
564
993
  return lines.join("\n");
565
994
  }
@@ -586,6 +1015,14 @@ async function main() {
586
1015
  process$1.env[key] = value.length === 0 ? String(true) : value.join(":");
587
1016
  }
588
1017
  }
1018
+ if (cliOptions.help) {
1019
+ showHelp();
1020
+ return;
1021
+ }
1022
+ if (cliOptions.version) {
1023
+ logger.log(`rolldown v${version}`);
1024
+ return;
1025
+ }
589
1026
  if (cliOptions.config || cliOptions.config === "") {
590
1027
  await bundleWithConfig(cliOptions.config, cliOptions, rawArgs);
591
1028
  return;
@@ -594,10 +1031,6 @@ async function main() {
594
1031
  await bundleWithCliOptions(cliOptions);
595
1032
  return;
596
1033
  }
597
- if (cliOptions.version) {
598
- logger.log(`rolldown v${version}`);
599
- return;
600
- }
601
1034
  showHelp();
602
1035
  }
603
1036
  main().catch((err) => {