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