@rspack/cli 2.0.0-rc.0 → 2.0.0-rc.2

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