@rspack/cli 2.0.0-beta.5 → 2.0.0-beta.7

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.
package/dist/index.js CHANGED
@@ -1 +1,1296 @@
1
- export { RspackCLI, defineConfig, definePlugin } from "./131.js";
1
+ import * as __rspack_external_module from "module";
2
+ import * as __rspack_external_path from "path";
3
+ import { __webpack_require__ } from "./rslib-runtime.js";
4
+ import node_path from "node:path";
5
+ import node_util from "node:util";
6
+ import { rspack } from "@rspack/core";
7
+ import node_fs from "node:fs";
8
+ import { createRequire } from "node:module";
9
+ import { pathToFileURL } from "node:url";
10
+ __webpack_require__.add({
11
+ "../../node_modules/.pnpm/pirates@4.0.7/node_modules/pirates/lib/index.js" (module, exports, __webpack_require__) {
12
+ module = __webpack_require__.nmd(module);
13
+ const BuiltinModule = __webpack_require__("module");
14
+ const path = __webpack_require__("path");
15
+ const nodeModulesRegex = /^(?:.*[\\/])?node_modules(?:[\\/].*)?$/;
16
+ const Module = module.constructor.length > 1 ? module.constructor : BuiltinModule;
17
+ const HOOK_RETURNED_NOTHING_ERROR_MESSAGE = "[Pirates] A hook returned a non-string, or nothing at all! This is a violation of intergalactic law!\n--------------------\nIf you have no idea what this means or what Pirates is, let me explain: Pirates is a module that makes it easy to implement require hooks. One of the require hooks you're using uses it. One of these require hooks didn't return anything from it's handler, so we don't know what to do. You might want to debug this.";
18
+ function shouldCompile(filename, exts, matcher, ignoreNodeModules) {
19
+ if ('string' != typeof filename) return false;
20
+ if (-1 === exts.indexOf(path.extname(filename))) return false;
21
+ const resolvedFilename = path.resolve(filename);
22
+ if (ignoreNodeModules && nodeModulesRegex.test(resolvedFilename)) return false;
23
+ if (matcher && 'function' == typeof matcher) return !!matcher(resolvedFilename);
24
+ return true;
25
+ }
26
+ function addHook(hook, opts = {}) {
27
+ let reverted = false;
28
+ const loaders = [];
29
+ const oldLoaders = [];
30
+ let exts;
31
+ const originalJSLoader = Module._extensions['.js'];
32
+ const matcher = opts.matcher || null;
33
+ const ignoreNodeModules = false !== opts.ignoreNodeModules;
34
+ exts = opts.extensions || opts.exts || opts.extension || opts.ext || [
35
+ '.js'
36
+ ];
37
+ if (!Array.isArray(exts)) exts = [
38
+ exts
39
+ ];
40
+ exts.forEach((ext)=>{
41
+ if ('string' != typeof ext) throw new TypeError(`Invalid Extension: ${ext}`);
42
+ const oldLoader = Module._extensions[ext] || originalJSLoader;
43
+ oldLoaders[ext] = Module._extensions[ext];
44
+ loaders[ext] = Module._extensions[ext] = function(mod, filename) {
45
+ let compile;
46
+ if (!reverted) {
47
+ if (shouldCompile(filename, exts, matcher, ignoreNodeModules)) {
48
+ compile = mod._compile;
49
+ mod._compile = function(code) {
50
+ mod._compile = compile;
51
+ const newCode = hook(code, filename);
52
+ if ('string' != typeof newCode) throw new Error(HOOK_RETURNED_NOTHING_ERROR_MESSAGE);
53
+ return mod._compile(newCode, filename);
54
+ };
55
+ }
56
+ }
57
+ oldLoader(mod, filename);
58
+ };
59
+ });
60
+ return function() {
61
+ if (reverted) return;
62
+ reverted = true;
63
+ exts.forEach((ext)=>{
64
+ if (Module._extensions[ext] === loaders[ext]) if (oldLoaders[ext]) Module._extensions[ext] = oldLoaders[ext];
65
+ else delete Module._extensions[ext];
66
+ });
67
+ };
68
+ }
69
+ exports.addHook = addHook;
70
+ },
71
+ module (module) {
72
+ module.exports = __rspack_external_module;
73
+ },
74
+ path (module) {
75
+ module.exports = __rspack_external_path;
76
+ }
77
+ });
78
+ function toArr(any) {
79
+ return null == any ? [] : Array.isArray(any) ? any : [
80
+ any
81
+ ];
82
+ }
83
+ function toVal(out, key, val, opts) {
84
+ var x, old = out[key], nxt = ~opts.string.indexOf(key) ? null == val || true === val ? "" : String(val) : "boolean" == typeof val ? val : ~opts.boolean.indexOf(key) ? "false" === val ? false : "true" === val || (out._.push((x = +val, 0 * x === 0) ? x : val), !!val) : (x = +val, 0 * x === 0) ? x : val;
85
+ out[key] = null == old ? nxt : Array.isArray(old) ? old.concat(nxt) : [
86
+ old,
87
+ nxt
88
+ ];
89
+ }
90
+ function lib_default(args, opts) {
91
+ args = args || [];
92
+ opts = opts || {};
93
+ var k, arr, arg, name, val, out = {
94
+ _: []
95
+ };
96
+ var i = 0, j = 0, idx = 0, len = args.length;
97
+ const alibi = void 0 !== opts.alias;
98
+ const strict = void 0 !== opts.unknown;
99
+ const defaults = void 0 !== opts.default;
100
+ opts.alias = opts.alias || {};
101
+ opts.string = toArr(opts.string);
102
+ opts.boolean = toArr(opts.boolean);
103
+ if (alibi) for(k in opts.alias){
104
+ arr = opts.alias[k] = toArr(opts.alias[k]);
105
+ for(i = 0; i < arr.length; i++)(opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
106
+ }
107
+ for(i = opts.boolean.length; i-- > 0;){
108
+ arr = opts.alias[opts.boolean[i]] || [];
109
+ for(j = arr.length; j-- > 0;)opts.boolean.push(arr[j]);
110
+ }
111
+ for(i = opts.string.length; i-- > 0;){
112
+ arr = opts.alias[opts.string[i]] || [];
113
+ for(j = arr.length; j-- > 0;)opts.string.push(arr[j]);
114
+ }
115
+ if (defaults) for(k in opts.default){
116
+ name = typeof opts.default[k];
117
+ arr = opts.alias[k] = opts.alias[k] || [];
118
+ if (void 0 !== opts[name]) {
119
+ opts[name].push(k);
120
+ for(i = 0; i < arr.length; i++)opts[name].push(arr[i]);
121
+ }
122
+ }
123
+ const keys = strict ? Object.keys(opts.alias) : [];
124
+ for(i = 0; i < len; i++){
125
+ arg = args[i];
126
+ if ("--" === arg) {
127
+ out._ = out._.concat(args.slice(++i));
128
+ break;
129
+ }
130
+ for(j = 0; j < arg.length && 45 === arg.charCodeAt(j); j++);
131
+ if (0 === j) out._.push(arg);
132
+ else if ("no-" === arg.substring(j, j + 3)) {
133
+ name = arg.substring(j + 3);
134
+ if (strict && !~keys.indexOf(name)) return opts.unknown(arg);
135
+ out[name] = false;
136
+ } else {
137
+ for(idx = j + 1; idx < arg.length && 61 !== arg.charCodeAt(idx); idx++);
138
+ name = arg.substring(j, idx);
139
+ val = arg.substring(++idx) || i + 1 === len || 45 === ("" + args[i + 1]).charCodeAt(0) || args[++i];
140
+ arr = 2 === j ? [
141
+ name
142
+ ] : name;
143
+ for(idx = 0; idx < arr.length; idx++){
144
+ name = arr[idx];
145
+ if (strict && !~keys.indexOf(name)) return opts.unknown("-".repeat(j) + name);
146
+ toVal(out, name, idx + 1 < arr.length || val, opts);
147
+ }
148
+ }
149
+ }
150
+ if (defaults) {
151
+ for(k in opts.default)if (void 0 === out[k]) out[k] = opts.default[k];
152
+ }
153
+ if (alibi) for(k in out){
154
+ arr = opts.alias[k] || [];
155
+ while(arr.length > 0)out[arr.shift()] = out[k];
156
+ }
157
+ return out;
158
+ }
159
+ function removeBrackets(v) {
160
+ return v.replace(/[<[].+/, "").trim();
161
+ }
162
+ function findAllBrackets(v) {
163
+ const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
164
+ const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
165
+ const res = [];
166
+ const parse = (match)=>{
167
+ let variadic = false;
168
+ let value = match[1];
169
+ if (value.startsWith("...")) {
170
+ value = value.slice(3);
171
+ variadic = true;
172
+ }
173
+ return {
174
+ required: match[0].startsWith("<"),
175
+ value,
176
+ variadic
177
+ };
178
+ };
179
+ let angledMatch;
180
+ while(angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v))res.push(parse(angledMatch));
181
+ let squareMatch;
182
+ while(squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v))res.push(parse(squareMatch));
183
+ return res;
184
+ }
185
+ function getMriOptions(options) {
186
+ const result = {
187
+ alias: {},
188
+ boolean: []
189
+ };
190
+ for (const [index, option] of options.entries()){
191
+ if (option.names.length > 1) result.alias[option.names[0]] = option.names.slice(1);
192
+ if (option.isBoolean) if (option.negated) {
193
+ if (!options.some((o, i)=>i !== index && o.names.some((name)=>option.names.includes(name)) && "boolean" == typeof o.required)) result.boolean.push(option.names[0]);
194
+ } else result.boolean.push(option.names[0]);
195
+ }
196
+ return result;
197
+ }
198
+ function findLongest(arr) {
199
+ return arr.sort((a, b)=>a.length > b.length ? -1 : 1)[0];
200
+ }
201
+ function padRight(str, length) {
202
+ return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
203
+ }
204
+ function camelcase(input) {
205
+ return input.replaceAll(/([a-z])-([a-z])/g, (_, p1, p2)=>p1 + p2.toUpperCase());
206
+ }
207
+ function setDotProp(obj, keys, val) {
208
+ let current = obj;
209
+ for(let i = 0; i < keys.length; i++){
210
+ const key = keys[i];
211
+ if (i === keys.length - 1) {
212
+ current[key] = val;
213
+ return;
214
+ }
215
+ if (null == current[key]) {
216
+ const nextKeyIsArrayIndex = +keys[i + 1] > -1;
217
+ current[key] = nextKeyIsArrayIndex ? [] : {};
218
+ }
219
+ current = current[key];
220
+ }
221
+ }
222
+ function setByType(obj, transforms) {
223
+ for (const key of Object.keys(transforms)){
224
+ const transform = transforms[key];
225
+ if (transform.shouldTransform) {
226
+ obj[key] = [
227
+ obj[key]
228
+ ].flat();
229
+ if ("function" == typeof transform.transformFunction) obj[key] = obj[key].map(transform.transformFunction);
230
+ }
231
+ }
232
+ }
233
+ function getFileName(input) {
234
+ const m = /([^\\/]+)$/.exec(input);
235
+ return m ? m[1] : "";
236
+ }
237
+ function camelcaseOptionName(name) {
238
+ return name.split(".").map((v, i)=>0 === i ? camelcase(v) : v).join(".");
239
+ }
240
+ var CACError = class extends Error {
241
+ constructor(message){
242
+ super(message);
243
+ this.name = "CACError";
244
+ if ("function" != typeof Error.captureStackTrace) this.stack = new Error(message).stack;
245
+ }
246
+ };
247
+ var Option = class {
248
+ rawName;
249
+ description;
250
+ name;
251
+ names;
252
+ isBoolean;
253
+ required;
254
+ config;
255
+ negated;
256
+ constructor(rawName, description, config){
257
+ this.rawName = rawName;
258
+ this.description = description;
259
+ this.config = Object.assign({}, config);
260
+ rawName = rawName.replaceAll(".*", "");
261
+ this.negated = false;
262
+ this.names = removeBrackets(rawName).split(",").map((v)=>{
263
+ let name = v.trim().replace(/^-{1,2}/, "");
264
+ if (name.startsWith("no-")) {
265
+ this.negated = true;
266
+ name = name.replace(/^no-/, "");
267
+ }
268
+ return camelcaseOptionName(name);
269
+ }).sort((a, b)=>a.length > b.length ? 1 : -1);
270
+ this.name = this.names.at(-1);
271
+ if (this.negated && null == this.config.default) this.config.default = true;
272
+ if (rawName.includes("<")) this.required = true;
273
+ else if (rawName.includes("[")) this.required = false;
274
+ else this.isBoolean = true;
275
+ }
276
+ };
277
+ let runtimeProcessArgs;
278
+ let runtimeInfo;
279
+ if ("u" > typeof process) {
280
+ let runtimeName;
281
+ runtimeName = "u" > typeof Deno && "string" == typeof Deno.version?.deno ? "deno" : "u" > typeof Bun && "string" == typeof Bun.version ? "bun" : "node";
282
+ runtimeInfo = `${process.platform}-${process.arch} ${runtimeName}-${process.version}`;
283
+ runtimeProcessArgs = process.argv;
284
+ } else runtimeInfo = "u" < typeof navigator ? "unknown" : `${navigator.platform} ${navigator.userAgent}`;
285
+ var Command = class {
286
+ rawName;
287
+ description;
288
+ config;
289
+ cli;
290
+ options;
291
+ aliasNames;
292
+ name;
293
+ args;
294
+ commandAction;
295
+ usageText;
296
+ versionNumber;
297
+ examples;
298
+ helpCallback;
299
+ globalCommand;
300
+ constructor(rawName, description, config = {}, cli){
301
+ this.rawName = rawName;
302
+ this.description = description;
303
+ this.config = config;
304
+ this.cli = cli;
305
+ this.options = [];
306
+ this.aliasNames = [];
307
+ this.name = removeBrackets(rawName);
308
+ this.args = findAllBrackets(rawName);
309
+ this.examples = [];
310
+ }
311
+ usage(text) {
312
+ this.usageText = text;
313
+ return this;
314
+ }
315
+ allowUnknownOptions() {
316
+ this.config.allowUnknownOptions = true;
317
+ return this;
318
+ }
319
+ ignoreOptionDefaultValue() {
320
+ this.config.ignoreOptionDefaultValue = true;
321
+ return this;
322
+ }
323
+ version(version, customFlags = "-v, --version") {
324
+ this.versionNumber = version;
325
+ this.option(customFlags, "Display version number");
326
+ return this;
327
+ }
328
+ example(example) {
329
+ this.examples.push(example);
330
+ return this;
331
+ }
332
+ option(rawName, description, config) {
333
+ const option = new Option(rawName, description, config);
334
+ this.options.push(option);
335
+ return this;
336
+ }
337
+ alias(name) {
338
+ this.aliasNames.push(name);
339
+ return this;
340
+ }
341
+ action(callback) {
342
+ this.commandAction = callback;
343
+ return this;
344
+ }
345
+ isMatched(name) {
346
+ return this.name === name || this.aliasNames.includes(name);
347
+ }
348
+ get isDefaultCommand() {
349
+ return "" === this.name || this.aliasNames.includes("!");
350
+ }
351
+ get isGlobalCommand() {
352
+ return this instanceof GlobalCommand;
353
+ }
354
+ hasOption(name) {
355
+ name = name.split(".")[0];
356
+ return this.options.find((option)=>option.names.includes(name));
357
+ }
358
+ outputHelp() {
359
+ const { name, commands } = this.cli;
360
+ const { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand;
361
+ let sections = [
362
+ {
363
+ body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
364
+ }
365
+ ];
366
+ sections.push({
367
+ title: "Usage",
368
+ body: ` $ ${name} ${this.usageText || this.rawName}`
369
+ });
370
+ if ((this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0) {
371
+ const longestCommandName = findLongest(commands.map((command)=>command.rawName));
372
+ sections.push({
373
+ title: "Commands",
374
+ body: commands.map((command)=>` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`).join("\n")
375
+ }, {
376
+ title: "For more info, run any command with the `--help` flag",
377
+ body: commands.map((command)=>` $ ${name}${"" === command.name ? "" : ` ${command.name}`} --help`).join("\n")
378
+ });
379
+ }
380
+ let options = this.isGlobalCommand ? globalOptions : [
381
+ ...this.options,
382
+ ...globalOptions || []
383
+ ];
384
+ if (!this.isGlobalCommand && !this.isDefaultCommand) options = options.filter((option)=>"version" !== option.name);
385
+ if (options.length > 0) {
386
+ const longestOptionName = findLongest(options.map((option)=>option.rawName));
387
+ sections.push({
388
+ title: "Options",
389
+ body: options.map((option)=>` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${void 0 === option.config.default ? "" : `(default: ${option.config.default})`}`).join("\n")
390
+ });
391
+ }
392
+ if (this.examples.length > 0) sections.push({
393
+ title: "Examples",
394
+ body: this.examples.map((example)=>{
395
+ if ("function" == typeof example) return example(name);
396
+ return example;
397
+ }).join("\n")
398
+ });
399
+ if (helpCallback) sections = helpCallback(sections) || sections;
400
+ console.info(sections.map((section)=>section.title ? `${section.title}:\n${section.body}` : section.body).join("\n\n"));
401
+ }
402
+ outputVersion() {
403
+ const { name } = this.cli;
404
+ const { versionNumber } = this.cli.globalCommand;
405
+ if (versionNumber) console.info(`${name}/${versionNumber} ${runtimeInfo}`);
406
+ }
407
+ checkRequiredArgs() {
408
+ const minimalArgsCount = this.args.filter((arg)=>arg.required).length;
409
+ if (this.cli.args.length < minimalArgsCount) throw new CACError(`missing required args for command \`${this.rawName}\``);
410
+ }
411
+ checkUnknownOptions() {
412
+ const { options, globalCommand } = this.cli;
413
+ if (!this.config.allowUnknownOptions) {
414
+ 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}`}\``);
415
+ }
416
+ }
417
+ checkOptionValue() {
418
+ const { options: parsedOptions, globalCommand } = this.cli;
419
+ const options = [
420
+ ...globalCommand.options,
421
+ ...this.options
422
+ ];
423
+ for (const option of options){
424
+ const value = parsedOptions[option.name.split(".")[0]];
425
+ if (option.required) {
426
+ const hasNegated = options.some((o)=>o.negated && o.names.includes(option.name));
427
+ if (true === value || false === value && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`);
428
+ }
429
+ }
430
+ }
431
+ checkUnusedArgs() {
432
+ const maximumArgsCount = this.args.some((arg)=>arg.variadic) ? 1 / 0 : this.args.length;
433
+ if (maximumArgsCount < this.cli.args.length) throw new CACError(`Unused args: ${this.cli.args.slice(maximumArgsCount).map((arg)=>`\`${arg}\``).join(", ")}`);
434
+ }
435
+ };
436
+ var GlobalCommand = class extends Command {
437
+ constructor(cli){
438
+ super("@@global@@", "", {}, cli);
439
+ }
440
+ };
441
+ var CAC = class extends EventTarget {
442
+ name;
443
+ commands;
444
+ globalCommand;
445
+ matchedCommand;
446
+ matchedCommandName;
447
+ rawArgs;
448
+ args;
449
+ options;
450
+ showHelpOnExit;
451
+ showVersionOnExit;
452
+ constructor(name = ""){
453
+ super();
454
+ this.name = name;
455
+ this.commands = [];
456
+ this.rawArgs = [];
457
+ this.args = [];
458
+ this.options = {};
459
+ this.globalCommand = new GlobalCommand(this);
460
+ this.globalCommand.usage("<command> [options]");
461
+ }
462
+ usage(text) {
463
+ this.globalCommand.usage(text);
464
+ return this;
465
+ }
466
+ command(rawName, description, config) {
467
+ const command = new Command(rawName, description || "", config, this);
468
+ command.globalCommand = this.globalCommand;
469
+ this.commands.push(command);
470
+ return command;
471
+ }
472
+ option(rawName, description, config) {
473
+ this.globalCommand.option(rawName, description, config);
474
+ return this;
475
+ }
476
+ help(callback) {
477
+ this.globalCommand.option("-h, --help", "Display this message");
478
+ this.globalCommand.helpCallback = callback;
479
+ this.showHelpOnExit = true;
480
+ return this;
481
+ }
482
+ version(version, customFlags = "-v, --version") {
483
+ this.globalCommand.version(version, customFlags);
484
+ this.showVersionOnExit = true;
485
+ return this;
486
+ }
487
+ example(example) {
488
+ this.globalCommand.example(example);
489
+ return this;
490
+ }
491
+ outputHelp() {
492
+ if (this.matchedCommand) this.matchedCommand.outputHelp();
493
+ else this.globalCommand.outputHelp();
494
+ }
495
+ outputVersion() {
496
+ this.globalCommand.outputVersion();
497
+ }
498
+ setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
499
+ this.args = args;
500
+ this.options = options;
501
+ if (matchedCommand) this.matchedCommand = matchedCommand;
502
+ if (matchedCommandName) this.matchedCommandName = matchedCommandName;
503
+ return this;
504
+ }
505
+ unsetMatchedCommand() {
506
+ this.matchedCommand = void 0;
507
+ this.matchedCommandName = void 0;
508
+ }
509
+ parse(argv, { run = true } = {}) {
510
+ if (!argv) {
511
+ if (!runtimeProcessArgs) throw new Error("No argv provided and runtime process argv is not available.");
512
+ argv = runtimeProcessArgs;
513
+ }
514
+ this.rawArgs = argv;
515
+ if (!this.name) this.name = argv[1] ? getFileName(argv[1]) : "cli";
516
+ let shouldParse = true;
517
+ for (const command of this.commands){
518
+ const parsed = this.mri(argv.slice(2), command);
519
+ const commandName = parsed.args[0];
520
+ if (command.isMatched(commandName)) {
521
+ shouldParse = false;
522
+ const parsedInfo = {
523
+ ...parsed,
524
+ args: parsed.args.slice(1)
525
+ };
526
+ this.setParsedInfo(parsedInfo, command, commandName);
527
+ this.dispatchEvent(new CustomEvent(`command:${commandName}`, {
528
+ detail: command
529
+ }));
530
+ }
531
+ }
532
+ if (shouldParse) {
533
+ for (const command of this.commands)if (command.isDefaultCommand) {
534
+ shouldParse = false;
535
+ const parsed = this.mri(argv.slice(2), command);
536
+ this.setParsedInfo(parsed, command);
537
+ this.dispatchEvent(new CustomEvent("command:!", {
538
+ detail: command
539
+ }));
540
+ }
541
+ }
542
+ if (shouldParse) {
543
+ const parsed = this.mri(argv.slice(2));
544
+ this.setParsedInfo(parsed);
545
+ }
546
+ if (this.options.help && this.showHelpOnExit) {
547
+ this.outputHelp();
548
+ run = false;
549
+ this.unsetMatchedCommand();
550
+ }
551
+ if (this.options.version && this.showVersionOnExit && null == this.matchedCommandName) {
552
+ this.outputVersion();
553
+ run = false;
554
+ this.unsetMatchedCommand();
555
+ }
556
+ const parsedArgv = {
557
+ args: this.args,
558
+ options: this.options
559
+ };
560
+ if (run) this.runMatchedCommand();
561
+ if (!this.matchedCommand && this.args[0]) this.dispatchEvent(new CustomEvent("command:*", {
562
+ detail: this.args[0]
563
+ }));
564
+ return parsedArgv;
565
+ }
566
+ mri(argv, command) {
567
+ const cliOptions = [
568
+ ...this.globalCommand.options,
569
+ ...command ? command.options : []
570
+ ];
571
+ const mriOptions = getMriOptions(cliOptions);
572
+ let argsAfterDoubleDashes = [];
573
+ const doubleDashesIndex = argv.indexOf("--");
574
+ if (-1 !== doubleDashesIndex) {
575
+ argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
576
+ argv = argv.slice(0, doubleDashesIndex);
577
+ }
578
+ let parsed = lib_default(argv, mriOptions);
579
+ parsed = Object.keys(parsed).reduce((res, name)=>({
580
+ ...res,
581
+ [camelcaseOptionName(name)]: parsed[name]
582
+ }), {
583
+ _: []
584
+ });
585
+ const args = parsed._;
586
+ const options = {
587
+ "--": argsAfterDoubleDashes
588
+ };
589
+ const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
590
+ const transforms = Object.create(null);
591
+ for (const cliOption of cliOptions){
592
+ if (!ignoreDefault && void 0 !== cliOption.config.default) for (const name of cliOption.names)options[name] = cliOption.config.default;
593
+ if (Array.isArray(cliOption.config.type) && void 0 === transforms[cliOption.name]) {
594
+ transforms[cliOption.name] = Object.create(null);
595
+ transforms[cliOption.name].shouldTransform = true;
596
+ transforms[cliOption.name].transformFunction = cliOption.config.type[0];
597
+ }
598
+ }
599
+ for (const key of Object.keys(parsed))if ("_" !== key) {
600
+ setDotProp(options, key.split("."), parsed[key]);
601
+ setByType(options, transforms);
602
+ }
603
+ return {
604
+ args,
605
+ options
606
+ };
607
+ }
608
+ runMatchedCommand() {
609
+ const { args, options, matchedCommand: command } = this;
610
+ if (!command || !command.commandAction) return;
611
+ command.checkUnknownOptions();
612
+ command.checkOptionValue();
613
+ command.checkRequiredArgs();
614
+ command.checkUnusedArgs();
615
+ const actionArgs = [];
616
+ command.args.forEach((arg, index)=>{
617
+ if (arg.variadic) actionArgs.push(args.slice(index));
618
+ else actionArgs.push(args[index]);
619
+ });
620
+ actionArgs.push(options);
621
+ return command.commandAction.apply(this, actionArgs);
622
+ }
623
+ };
624
+ const cac = (name = "")=>new CAC(name);
625
+ const commonOptions = (command)=>command.option('-c, --config <path>', 'config file').option('--config-name <name>', 'Name(s) of the configuration to use.', {
626
+ type: [
627
+ String
628
+ ],
629
+ default: []
630
+ }).option('--config-loader <loader>', 'Specify the loader to load the config file, can be `native` or `register`.', {
631
+ default: 'register'
632
+ }).option('--env <env>', 'env passed to config function', {
633
+ type: [
634
+ String
635
+ ],
636
+ default: []
637
+ }).option('--node-env <value>', 'sets `process.env.NODE_ENV` to be specified value');
638
+ function normalizeDevtoolOption(value) {
639
+ if ('string' == typeof value) {
640
+ const trimmed = value.trim();
641
+ if ('' === trimmed || 'false' === trimmed) return false;
642
+ if ('true' === trimmed) return 'source-map';
643
+ return trimmed;
644
+ }
645
+ if ('boolean' == typeof value) return value ? 'source-map' : false;
646
+ }
647
+ const normalizeCommonOptions = (options, action)=>{
648
+ const isEmptyArray = (arr)=>Array.isArray(arr) && 0 === arr.length;
649
+ for (const key of [
650
+ 'entry',
651
+ 'configName'
652
+ ]){
653
+ const val = options[key];
654
+ if (isEmptyArray(val)) options[key] = void 0;
655
+ }
656
+ const env = Array.isArray(options.env) ? normalizeEnvToObject(options) : {};
657
+ options.env = env;
658
+ if ('serve' === action) setBuiltinEnvArg(env, 'SERVE', true);
659
+ else if ('build' === action) if (options.watch) setBuiltinEnvArg(env, 'WATCH', true);
660
+ else {
661
+ setBuiltinEnvArg(env, 'BUNDLE', true);
662
+ setBuiltinEnvArg(env, 'BUILD', true);
663
+ }
664
+ if ('devtool' in options) options.devtool = normalizeDevtoolOption(options.devtool);
665
+ };
666
+ const commonOptionsForBuildAndServe = (command)=>command.option('-d, --devtool <value>', 'specify a developer tool for debugging. Defaults to `cheap-module-source-map` in development and `source-map` in production.').option('--entry <entry>', 'entry file', {
667
+ type: [
668
+ String
669
+ ],
670
+ default: []
671
+ }).option('-m, --mode <mode>', 'mode').option('-o, --output-path <dir>', 'output path dir').option('-w, --watch', 'watch');
672
+ function setBuiltinEnvArg(env, envNameSuffix, value) {
673
+ const envName = `RSPACK_${envNameSuffix}`;
674
+ if (!(envName in env)) env[envName] = value;
675
+ }
676
+ function normalizeEnvToObject(options) {
677
+ function parseValue(previous, value) {
678
+ const [allKeys, val] = value.split(/=(.+)/, 2);
679
+ const splitKeys = allKeys.split(/\.(?!$)/);
680
+ let prevRef = previous;
681
+ splitKeys.forEach((key, index)=>{
682
+ let someKey = key;
683
+ if (someKey.endsWith('=')) {
684
+ someKey = someKey.slice(0, -1);
685
+ prevRef[someKey] = void 0;
686
+ return;
687
+ }
688
+ if (!prevRef[someKey] || 'string' == typeof prevRef[someKey]) prevRef[someKey] = {};
689
+ if (index === splitKeys.length - 1) if ('string' == typeof val) prevRef[someKey] = val;
690
+ else prevRef[someKey] = true;
691
+ prevRef = prevRef[someKey];
692
+ });
693
+ return previous;
694
+ }
695
+ return (options.env ?? []).reduce(parseValue, {});
696
+ }
697
+ function setDefaultNodeEnv(options, defaultEnv) {
698
+ if (void 0 === process.env.NODE_ENV) process.env.NODE_ENV = 'string' == typeof options.nodeEnv ? options.nodeEnv : defaultEnv;
699
+ }
700
+ async function runBuild(cli, options) {
701
+ setDefaultNodeEnv(options, 'production');
702
+ normalizeCommonOptions(options, 'build');
703
+ const logger = cli.getLogger();
704
+ let createJsonStringifyStream;
705
+ if (options.json) {
706
+ const jsonExt = await import("@discoveryjs/json-ext");
707
+ createJsonStringifyStream = jsonExt.default.stringifyStream;
708
+ }
709
+ const errorHandler = (error, stats)=>{
710
+ if (error) {
711
+ logger.error(error);
712
+ process.exit(2);
713
+ }
714
+ if (stats?.hasErrors()) process.exitCode = 1;
715
+ if (!compiler || !stats) return;
716
+ const getStatsOptions = ()=>{
717
+ if (cli.isMultipleCompiler(compiler)) return {
718
+ children: compiler.compilers.map((item)=>item.options ? item.options.stats : void 0)
719
+ };
720
+ return compiler.options?.stats;
721
+ };
722
+ const statsOptions = getStatsOptions();
723
+ if (options.json && createJsonStringifyStream) {
724
+ const handleWriteError = (error)=>{
725
+ logger.error(error);
726
+ process.exit(2);
727
+ };
728
+ if (true === options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on('error', handleWriteError).pipe(process.stdout).on('error', handleWriteError).on('close', ()=>process.stdout.write('\n'));
729
+ else if ('string' == typeof options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on('error', handleWriteError).pipe(node_fs.createWriteStream(options.json)).on('error', handleWriteError).on('close', ()=>{
730
+ process.stderr.write(`[rspack-cli] ${cli.colors.green(`stats are successfully stored as json to ${options.json}`)}\n`);
731
+ });
732
+ } else {
733
+ const printedStats = stats.toString(statsOptions);
734
+ if (printedStats) logger.raw(printedStats);
735
+ }
736
+ };
737
+ const userOption = await cli.buildCompilerConfig(options, 'build');
738
+ const compiler = await cli.createCompiler(userOption, errorHandler);
739
+ if (!compiler || cli.isWatch(compiler)) return;
740
+ compiler.run((error, stats)=>{
741
+ compiler.close((closeErr)=>{
742
+ if (closeErr) logger.error(closeErr);
743
+ errorHandler(error, stats);
744
+ });
745
+ });
746
+ }
747
+ class BuildCommand {
748
+ async apply(cli) {
749
+ const command = cli.program.command('', 'run the Rspack build').alias('build').alias('bundle').alias('b');
750
+ commonOptionsForBuildAndServe(commonOptions(command)).option('--json [path]', 'emit stats json');
751
+ command.action(async (options)=>{
752
+ await runBuild(cli, options);
753
+ });
754
+ }
755
+ }
756
+ class PreviewCommand {
757
+ async apply(cli) {
758
+ const command = cli.program.command('preview [dir]', 'run the Rspack server for build output').alias('p');
759
+ commonOptions(command).option('--public-path <path>', 'static resource server path').option('--port <port>', 'preview server port').option('--host <host>', 'preview server host').option('--open', 'open browser').option('--server <config>', 'Configuration items for the server.');
760
+ command.action(async (dir, options)=>{
761
+ setDefaultNodeEnv(options, 'production');
762
+ normalizeCommonOptions(options, 'preview');
763
+ let RspackDevServer;
764
+ try {
765
+ const devServerModule = await import("@rspack/dev-server");
766
+ RspackDevServer = devServerModule.RspackDevServer;
767
+ } catch (error) {
768
+ const logger = cli.getLogger();
769
+ if (error?.code === 'MODULE_NOT_FOUND' || error?.code === 'ERR_MODULE_NOT_FOUND') logger.error('The "@rspack/dev-server" package is required to use the preview command.\nPlease install it by running:\n pnpm add -D @rspack/dev-server\n or\n npm install -D @rspack/dev-server');
770
+ else logger.error('Failed to load "@rspack/dev-server":\n' + (error?.message || String(error)));
771
+ process.exit(1);
772
+ }
773
+ let { config } = await cli.loadConfig(options);
774
+ config = await getPreviewConfig(config, options, dir);
775
+ if (!Array.isArray(config)) config = [
776
+ config
777
+ ];
778
+ const singleConfig = config.find((item)=>item.devServer) || config[0];
779
+ const devServerOptions = singleConfig.devServer;
780
+ try {
781
+ const compiler = rspack({
782
+ entry: {}
783
+ });
784
+ if (!compiler) return;
785
+ const server = new RspackDevServer(devServerOptions, compiler);
786
+ await server.start();
787
+ } catch (error) {
788
+ const logger = cli.getLogger();
789
+ logger.error(error);
790
+ process.exit(2);
791
+ }
792
+ });
793
+ }
794
+ }
795
+ async function getPreviewConfig(item, options, dir) {
796
+ const DEFAULT_ROOT = 'dist';
797
+ const internalPreviewConfig = async (item)=>{
798
+ item.devServer = {
799
+ static: {
800
+ directory: dir ? node_path.join(item.context ?? process.cwd(), dir) : item.output?.path ?? node_path.join(item.context ?? process.cwd(), DEFAULT_ROOT),
801
+ publicPath: options.publicPath ?? '/'
802
+ },
803
+ port: options.port ?? 8080,
804
+ proxy: item.devServer?.proxy,
805
+ host: options.host ?? item.devServer?.host,
806
+ open: options.open ?? item.devServer?.open,
807
+ server: options.server ?? item.devServer?.server,
808
+ historyApiFallback: item.devServer?.historyApiFallback
809
+ };
810
+ return item;
811
+ };
812
+ if (Array.isArray(item)) return Promise.all(item.map(internalPreviewConfig));
813
+ return internalPreviewConfig(item);
814
+ }
815
+ function normalizeHotOption(value) {
816
+ if ('false' === value) return false;
817
+ if ('true' === value) return true;
818
+ return value;
819
+ }
820
+ class ServeCommand {
821
+ async apply(cli) {
822
+ const command = cli.program.command('serve', 'run the rspack dev server.').alias('server').alias('s').alias('dev');
823
+ commonOptionsForBuildAndServe(commonOptions(command)).option('--hot [mode]', 'enables hot module replacement').option('--port <port>', 'allows to specify a port to use').option('--host <host>', 'allows to specify a hostname to use');
824
+ command.action(async (cliOptions)=>{
825
+ setDefaultNodeEnv(cliOptions, 'development');
826
+ normalizeCommonOptions(cliOptions, 'serve');
827
+ cliOptions.hot = normalizeHotOption(cliOptions.hot);
828
+ let RspackDevServer;
829
+ try {
830
+ const devServerModule = await import("@rspack/dev-server");
831
+ RspackDevServer = devServerModule.RspackDevServer;
832
+ } catch (error) {
833
+ const logger = cli.getLogger();
834
+ if (error?.code === 'MODULE_NOT_FOUND' || error?.code === 'ERR_MODULE_NOT_FOUND') logger.error('The "@rspack/dev-server" package is required to use the serve command.\nPlease install it by running:\n pnpm add -D @rspack/dev-server\n or\n npm install -D @rspack/dev-server');
835
+ else logger.error('Failed to load "@rspack/dev-server":\n' + (error?.message || String(error)));
836
+ process.exit(1);
837
+ }
838
+ const userConfig = await cli.buildCompilerConfig(cliOptions, 'serve');
839
+ const compiler = await cli.createCompiler(userConfig);
840
+ if (!compiler) return;
841
+ const isMultiCompiler = cli.isMultipleCompiler(compiler);
842
+ const compilers = isMultiCompiler ? compiler.compilers : [
843
+ compiler
844
+ ];
845
+ const userConfigs = isMultiCompiler ? userConfig : [
846
+ userConfig
847
+ ];
848
+ const possibleCompilers = compilers.filter((compiler)=>compiler.options.devServer);
849
+ const usedPorts = [];
850
+ const servers = [];
851
+ const compilerForDevServer = possibleCompilers.length > 0 ? possibleCompilers[0] : compilers[0];
852
+ for (const [index, compiler] of compilers.entries()){
853
+ const userConfig = userConfigs[index];
854
+ const devServer = compiler.options.devServer ??= {};
855
+ const isWebAppOnly = compiler.platform.web && !compiler.platform.node && !compiler.platform.nwjs && !compiler.platform.electron && !compiler.platform.webworker;
856
+ if (isWebAppOnly && void 0 === userConfig.lazyCompilation) compiler.options.lazyCompilation = {
857
+ imports: true,
858
+ entries: false
859
+ };
860
+ devServer.hot = cliOptions.hot ?? devServer.hot ?? true;
861
+ if (false !== devServer.client) {
862
+ if (true === devServer.client || null == devServer.client) devServer.client = {};
863
+ devServer.client = {
864
+ overlay: {
865
+ errors: true,
866
+ warnings: false
867
+ },
868
+ ...devServer.client
869
+ };
870
+ }
871
+ }
872
+ const devServerOptions = compilerForDevServer.options.devServer ??= {};
873
+ const { setupMiddlewares } = devServerOptions;
874
+ const lazyCompileMiddleware = rspack.lazyCompilationMiddleware(compiler);
875
+ devServerOptions.setupMiddlewares = (middlewares, server)=>{
876
+ let finalMiddlewares = middlewares;
877
+ if (setupMiddlewares) finalMiddlewares = setupMiddlewares(finalMiddlewares, server);
878
+ return [
879
+ ...finalMiddlewares,
880
+ lazyCompileMiddleware
881
+ ];
882
+ };
883
+ devServerOptions.hot = cliOptions.hot ?? devServerOptions.hot ?? true;
884
+ devServerOptions.host = cliOptions.host || devServerOptions.host;
885
+ devServerOptions.port = cliOptions.port ?? devServerOptions.port;
886
+ if (false !== devServerOptions.client) {
887
+ if (true === devServerOptions.client || null == devServerOptions.client) devServerOptions.client = {};
888
+ devServerOptions.client = {
889
+ overlay: {
890
+ errors: true,
891
+ warnings: false
892
+ },
893
+ ...devServerOptions.client
894
+ };
895
+ }
896
+ if (devServerOptions.port) {
897
+ const portNumber = Number(devServerOptions.port);
898
+ if (!Number.isNaN(portNumber)) {
899
+ if (usedPorts.find((port)=>portNumber === port)) throw new Error('Unique ports must be specified for each devServer option in your rspack configuration. Alternatively, run only 1 devServer config using the --config-name flag to specify your desired config.');
900
+ usedPorts.push(portNumber);
901
+ }
902
+ }
903
+ try {
904
+ const server = new RspackDevServer(devServerOptions, compiler);
905
+ await server.start();
906
+ servers.push(server);
907
+ } catch (error) {
908
+ const logger = cli.getLogger();
909
+ logger.error(error);
910
+ process.exit(2);
911
+ }
912
+ });
913
+ }
914
+ }
915
+ const readPackageUp = (cwd = process.cwd())=>{
916
+ let currentDir = node_path.resolve(cwd);
917
+ let packageJsonPath = node_path.join(currentDir, 'package.json');
918
+ while(!node_fs.existsSync(packageJsonPath)){
919
+ const parentDir = node_path.dirname(currentDir);
920
+ if (parentDir === currentDir) return null;
921
+ currentDir = parentDir;
922
+ packageJsonPath = node_path.join(currentDir, 'package.json');
923
+ }
924
+ try {
925
+ return JSON.parse(node_fs.readFileSync(packageJsonPath, 'utf8'));
926
+ } catch {
927
+ return null;
928
+ }
929
+ };
930
+ const utils_readPackageUp = readPackageUp;
931
+ const isEsmFile = (filePath)=>{
932
+ if (/\.(mjs|mts)$/.test(filePath)) return true;
933
+ if (/\.(cjs|cts)$/.test(filePath)) return false;
934
+ const packageJson = utils_readPackageUp(node_path.dirname(filePath));
935
+ return packageJson?.type === 'module';
936
+ };
937
+ const crossImport_require = createRequire(import.meta.url);
938
+ const crossImport = async (path)=>{
939
+ if (isEsmFile(path)) {
940
+ const url = pathToFileURL(path).href;
941
+ const { default: config } = await import(url);
942
+ return config;
943
+ }
944
+ let result = crossImport_require(path);
945
+ if (result && 'object' == typeof result && 'default' in result) result = result.default || {};
946
+ return result;
947
+ };
948
+ const DEFAULT_EXTENSIONS = [
949
+ '.js',
950
+ '.ts',
951
+ '.mjs',
952
+ '.mts',
953
+ '.cjs',
954
+ '.cts'
955
+ ];
956
+ const findConfig = (basePath)=>DEFAULT_EXTENSIONS.map((ext)=>basePath + ext).find(node_fs.existsSync);
957
+ const utils_findConfig = findConfig;
958
+ const TS_EXTENSION = [
959
+ '.ts',
960
+ '.cts',
961
+ '.mts'
962
+ ];
963
+ const isTsFile = (configPath)=>{
964
+ const ext = node_path.extname(configPath);
965
+ return TS_EXTENSION.includes(ext);
966
+ };
967
+ const utils_isTsFile = isTsFile;
968
+ const lib = __webpack_require__("../../node_modules/.pnpm/pirates@4.0.7/node_modules/pirates/lib/index.js");
969
+ const loadConfig_require = createRequire(import.meta.url);
970
+ const injectInlineSourceMap = ({ code, map })=>{
971
+ if (map) {
972
+ const base64Map = Buffer.from(map, 'utf8').toString('base64');
973
+ const sourceMapContent = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${base64Map}`;
974
+ return `${code}\n${sourceMapContent}`;
975
+ }
976
+ return code;
977
+ };
978
+ function compile(sourcecode, filename) {
979
+ const { code, map } = rspack.experiments.swc.transformSync(sourcecode, {
980
+ jsc: {
981
+ parser: {
982
+ syntax: "typescript",
983
+ tsx: false,
984
+ decorators: true,
985
+ dynamicImport: true
986
+ }
987
+ },
988
+ filename: filename,
989
+ module: {
990
+ type: 'commonjs'
991
+ },
992
+ sourceMaps: true,
993
+ isModule: true
994
+ });
995
+ return injectInlineSourceMap({
996
+ code,
997
+ map
998
+ });
999
+ }
1000
+ const loadConfig_DEFAULT_CONFIG_NAME = 'rspack.config';
1001
+ const registerLoader = (configPath)=>{
1002
+ if (isEsmFile(configPath) && utils_isTsFile(configPath)) return;
1003
+ if (!utils_isTsFile(configPath)) throw new Error(`config file "${configPath}" is not supported.`);
1004
+ (0, lib.addHook)((code, filename)=>{
1005
+ try {
1006
+ return compile(code, filename);
1007
+ } catch (err) {
1008
+ throw new Error(`Failed to transform file "${filename}" when loading TypeScript config file:\n ${err instanceof Error ? err.message : String(err)}`);
1009
+ }
1010
+ }, {
1011
+ exts: TS_EXTENSION
1012
+ });
1013
+ };
1014
+ const checkIsMultiRspackOptions = (config)=>Array.isArray(config);
1015
+ async function loadExtendedConfig(config, configPath, cwd, options) {
1016
+ if (checkIsMultiRspackOptions(config)) {
1017
+ const resultPathMap = new WeakMap();
1018
+ const extendedConfigs = await Promise.all(config.map(async (item)=>{
1019
+ const { config, pathMap } = await loadExtendedConfig(item, configPath, cwd, options);
1020
+ resultPathMap.set(config, pathMap.get(config));
1021
+ return config;
1022
+ }));
1023
+ extendedConfigs.parallelism = config.parallelism;
1024
+ return {
1025
+ config: extendedConfigs,
1026
+ pathMap: resultPathMap
1027
+ };
1028
+ }
1029
+ const pathMap = new WeakMap();
1030
+ pathMap.set(config, [
1031
+ configPath
1032
+ ]);
1033
+ if (!('extends' in config) || !config.extends) return {
1034
+ config,
1035
+ pathMap
1036
+ };
1037
+ const extendsList = Array.isArray(config.extends) ? config.extends : [
1038
+ config.extends
1039
+ ];
1040
+ const { extends: _, ...configWithoutExtends } = config;
1041
+ const baseDir = node_path.dirname(configPath);
1042
+ let resultConfig = configWithoutExtends;
1043
+ pathMap.set(resultConfig, [
1044
+ configPath
1045
+ ]);
1046
+ for (const extendPath of extendsList){
1047
+ let resolvedPath;
1048
+ if (extendPath.startsWith('.') || extendPath.startsWith('/') || extendPath.includes(':\\')) {
1049
+ resolvedPath = node_path.resolve(baseDir, extendPath);
1050
+ if (!node_path.extname(resolvedPath)) {
1051
+ const foundConfig = utils_findConfig(resolvedPath);
1052
+ if (foundConfig) resolvedPath = foundConfig;
1053
+ else throw new Error(`Extended configuration file "${resolvedPath}" not found.`);
1054
+ }
1055
+ } else try {
1056
+ resolvedPath = loadConfig_require.resolve(extendPath, {
1057
+ paths: [
1058
+ baseDir,
1059
+ cwd
1060
+ ]
1061
+ });
1062
+ } catch {
1063
+ throw new Error(`Cannot find module '${extendPath}' to extend from.`);
1064
+ }
1065
+ if (!node_fs.existsSync(resolvedPath)) throw new Error(`Extended configuration file "${resolvedPath}" not found.`);
1066
+ if (utils_isTsFile(resolvedPath) && 'register' === options.configLoader) registerLoader(resolvedPath);
1067
+ let loadedConfig = await crossImport(resolvedPath);
1068
+ if ('function' == typeof loadedConfig) {
1069
+ loadedConfig = loadedConfig(options.env, options);
1070
+ if ('function' == typeof loadedConfig.then) loadedConfig = await loadedConfig;
1071
+ }
1072
+ const { config: extendedConfig, pathMap: extendedPathMap } = await loadExtendedConfig(loadedConfig, resolvedPath, cwd, options);
1073
+ const configPaths = [
1074
+ ...pathMap.get(resultConfig) || [],
1075
+ ...extendedPathMap.get(extendedConfig) || []
1076
+ ];
1077
+ resultConfig = rspack.util.cleverMerge(extendedConfig, resultConfig);
1078
+ pathMap.set(resultConfig, configPaths);
1079
+ }
1080
+ return {
1081
+ config: resultConfig,
1082
+ pathMap
1083
+ };
1084
+ }
1085
+ async function loadRspackConfig(options, cwd = process.cwd()) {
1086
+ let configPath = '';
1087
+ if (options.config) {
1088
+ configPath = node_path.resolve(cwd, options.config);
1089
+ if (!node_fs.existsSync(configPath)) throw new Error(`config file "${configPath}" not found.`);
1090
+ } else {
1091
+ const defaultConfig = utils_findConfig(node_path.resolve(cwd, loadConfig_DEFAULT_CONFIG_NAME));
1092
+ if (!defaultConfig) return null;
1093
+ configPath = defaultConfig;
1094
+ }
1095
+ if (utils_isTsFile(configPath) && 'register' === options.configLoader) registerLoader(configPath);
1096
+ const loadedConfig = await crossImport(configPath);
1097
+ return {
1098
+ loadedConfig,
1099
+ configPath
1100
+ };
1101
+ }
1102
+ function isEnvColorSupported() {
1103
+ if ("u" < typeof process) return false;
1104
+ const p = process;
1105
+ const argv = p.argv ?? [];
1106
+ const env = p.env ?? {};
1107
+ return !('NO_COLOR' in env || argv.includes('--no-color')) && ('FORCE_COLOR' in env || argv.includes('--color') || 'win32' === p.platform || p.stdout?.isTTY && 'dumb' !== env.TERM || 'CI' in env);
1108
+ }
1109
+ function createAnsiFormatter(open, close, replace = open) {
1110
+ const closeLength = close.length;
1111
+ return (input)=>{
1112
+ const string = String(input);
1113
+ let index = string.indexOf(close, open.length);
1114
+ if (-1 === index) return open + string + close;
1115
+ let result = '';
1116
+ let cursor = 0;
1117
+ do {
1118
+ result += string.substring(cursor, index) + replace;
1119
+ cursor = index + closeLength;
1120
+ index = string.indexOf(close, cursor);
1121
+ }while (-1 !== index);
1122
+ return open + result + string.substring(cursor) + close;
1123
+ };
1124
+ }
1125
+ class RspackCLI {
1126
+ colors;
1127
+ program;
1128
+ constructor(){
1129
+ const program = cac('rspack');
1130
+ this.colors = this.createColors();
1131
+ this.program = program;
1132
+ program.help();
1133
+ program.version("2.0.0-beta.7");
1134
+ }
1135
+ async buildCompilerConfig(options, rspackCommand) {
1136
+ let { config, pathMap } = await this.loadConfig(options);
1137
+ config = await this.buildConfig(config, pathMap, options, rspackCommand);
1138
+ return config;
1139
+ }
1140
+ async createCompiler(config, callback) {
1141
+ const isWatch = Array.isArray(config) ? config.some((i)=>i.watch) : config.watch;
1142
+ let compiler;
1143
+ try {
1144
+ compiler = rspack(config, isWatch ? callback : void 0);
1145
+ if (!isWatch && compiler) compiler.unsafeFastDrop = true;
1146
+ } catch (e) {
1147
+ if (e instanceof rspack.ValidationError) {
1148
+ this.getLogger().error(e.message);
1149
+ process.exit(2);
1150
+ } else if (e instanceof Error) {
1151
+ if ('function' == typeof callback) callback(e);
1152
+ else this.getLogger().error(e);
1153
+ return null;
1154
+ }
1155
+ throw e;
1156
+ }
1157
+ return compiler;
1158
+ }
1159
+ createColors(useColor) {
1160
+ const envSupported = isEnvColorSupported();
1161
+ const enabled = useColor ?? envSupported;
1162
+ if (!enabled) {
1163
+ const passthrough = (text)=>String(text);
1164
+ return {
1165
+ isColorSupported: false,
1166
+ red: passthrough,
1167
+ yellow: passthrough,
1168
+ cyan: passthrough,
1169
+ green: passthrough
1170
+ };
1171
+ }
1172
+ return {
1173
+ isColorSupported: true,
1174
+ red: createAnsiFormatter('\x1b[31m', '\x1b[39m'),
1175
+ green: createAnsiFormatter('\x1b[32m', '\x1b[39m'),
1176
+ yellow: createAnsiFormatter('\x1b[33m', '\x1b[39m'),
1177
+ cyan: createAnsiFormatter('\x1b[36m', '\x1b[39m')
1178
+ };
1179
+ }
1180
+ getLogger() {
1181
+ return {
1182
+ error: (val)=>console.error(`[rspack-cli] ${this.colors.red(node_util.format(val))}`),
1183
+ warn: (val)=>console.warn(`[rspack-cli] ${this.colors.yellow(val)}`),
1184
+ info: (val)=>console.info(`[rspack-cli] ${this.colors.cyan(val)}`),
1185
+ success: (val)=>console.log(`[rspack-cli] ${this.colors.green(val)}`),
1186
+ log: (val)=>console.log(`[rspack-cli] ${val}`),
1187
+ raw: (val)=>console.log(val)
1188
+ };
1189
+ }
1190
+ async run(argv) {
1191
+ await this.registerCommands();
1192
+ this.program.parse(argv);
1193
+ }
1194
+ async registerCommands() {
1195
+ const builtinCommands = [
1196
+ new BuildCommand(),
1197
+ new ServeCommand(),
1198
+ new PreviewCommand()
1199
+ ];
1200
+ for (const command of builtinCommands)await command.apply(this);
1201
+ }
1202
+ async buildConfig(item, pathMap, options, command) {
1203
+ const isBuild = 'build' === command;
1204
+ const isServe = 'serve' === command;
1205
+ const internalBuildConfig = async (item)=>{
1206
+ if (options.entry) item.entry = {
1207
+ main: options.entry.map((x)=>node_path.resolve(process.cwd(), x))[0]
1208
+ };
1209
+ item.output = item.output || {};
1210
+ if (options.outputPath) item.output.path = node_path.resolve(process.cwd(), options.outputPath);
1211
+ if (process.env.RSPACK_PROFILE) {
1212
+ const { applyProfile } = await import("./profile.js");
1213
+ await applyProfile(process.env.RSPACK_PROFILE, process.env.RSPACK_TRACE_LAYER, process.env.RSPACK_TRACE_OUTPUT);
1214
+ }
1215
+ if (options.watch) item.watch = options.watch;
1216
+ if (!item.mode) item.mode = isBuild ? 'production' : 'development';
1217
+ if (options.mode) item.mode = options.mode;
1218
+ if (void 0 === item.devtool) item.devtool = isBuild ? false : 'cheap-module-source-map';
1219
+ if (void 0 !== options.devtool) item.devtool = options.devtool;
1220
+ if (isServe) {
1221
+ const installed = (item.plugins ||= []).find((item)=>item instanceof rspack.ProgressPlugin);
1222
+ if (!installed) (item.plugins ??= []).push(new rspack.ProgressPlugin());
1223
+ }
1224
+ const cacheOptions = item.cache;
1225
+ if ('object' == typeof cacheOptions && 'persistent' === cacheOptions.type) {
1226
+ const configPaths = pathMap.get(item);
1227
+ if (configPaths) cacheOptions.buildDependencies = [
1228
+ ...configPaths,
1229
+ ...cacheOptions.buildDependencies || []
1230
+ ];
1231
+ }
1232
+ if (void 0 === item.stats) item.stats = {
1233
+ preset: 'errors-warnings',
1234
+ timings: true
1235
+ };
1236
+ else if ('boolean' == typeof item.stats) item.stats = item.stats ? {
1237
+ preset: 'normal'
1238
+ } : {
1239
+ preset: 'none'
1240
+ };
1241
+ else if ('string' == typeof item.stats) item.stats = {
1242
+ preset: item.stats
1243
+ };
1244
+ return item;
1245
+ };
1246
+ if (Array.isArray(item)) return Promise.all(item.map(internalBuildConfig));
1247
+ return internalBuildConfig(item);
1248
+ }
1249
+ async loadConfig(options) {
1250
+ const config = await loadRspackConfig(options);
1251
+ if (!config) return {
1252
+ config: this.filterConfig(options, {}),
1253
+ pathMap: new WeakMap()
1254
+ };
1255
+ let { loadedConfig, configPath } = config;
1256
+ if ('function' == typeof loadedConfig) {
1257
+ let functionResult = loadedConfig(options.env, options);
1258
+ if ('function' == typeof functionResult.then) functionResult = await functionResult;
1259
+ loadedConfig = functionResult;
1260
+ }
1261
+ const { config: extendedConfig, pathMap } = await loadExtendedConfig(loadedConfig, configPath, process.cwd(), options);
1262
+ return {
1263
+ config: this.filterConfig(options, extendedConfig),
1264
+ pathMap
1265
+ };
1266
+ }
1267
+ filterConfig(options, config) {
1268
+ if (options.configName) {
1269
+ const notFoundConfigNames = [];
1270
+ config = options.configName.map((configName)=>{
1271
+ let found;
1272
+ found = Array.isArray(config) ? config.find((options)=>options.name === configName) : config.name === configName ? config : void 0;
1273
+ if (!found) notFoundConfigNames.push(configName);
1274
+ return found;
1275
+ });
1276
+ if (notFoundConfigNames.length > 0) {
1277
+ this.getLogger().error(notFoundConfigNames.map((configName)=>`Configuration with the name "${configName}" was not found.`).join(' '));
1278
+ process.exit(2);
1279
+ }
1280
+ }
1281
+ return config;
1282
+ }
1283
+ isMultipleCompiler(compiler) {
1284
+ return Boolean(compiler.compilers);
1285
+ }
1286
+ isWatch(compiler) {
1287
+ return Boolean(this.isMultipleCompiler(compiler) ? compiler.compilers.some((compiler)=>compiler.options.watch) : compiler.options.watch);
1288
+ }
1289
+ }
1290
+ function defineConfig(config) {
1291
+ return config;
1292
+ }
1293
+ function definePlugin(plugin) {
1294
+ return plugin;
1295
+ }
1296
+ export { RspackCLI, defineConfig, definePlugin };