@rspack-canary/cli 1.6.0-canary-17d2172b-20251016033144 → 1.6.0-canary-2ccce257-20251016173648

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,21 +1,91 @@
1
- import * as __WEBPACK_EXTERNAL_MODULE__rspack_core_e0096ff7__ from "@rspack/core";
1
+ import * as __WEBPACK_EXTERNAL_MODULE_module__ from "module";
2
2
  import * as __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__ from "node:fs";
3
3
  import * as __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__ from "node:path";
4
- import node_util from "node:util";
5
- import { createColors, isColorSupported } from "colorette";
6
- import yargs_0 from "yargs";
7
- import { hideBin } from "yargs/helpers";
8
- import { addHook } from "pirates";
9
- import { pathToFileURL } from "node:url";
4
+ import * as __WEBPACK_EXTERNAL_MODULE_path__ from "path";
5
+ import * as __WEBPACK_EXTERNAL_MODULE_node_util_1b29d436__ from "node:util";
6
+ import * as __WEBPACK_EXTERNAL_MODULE_events__ from "events";
7
+ import * as __WEBPACK_EXTERNAL_MODULE_tty__ from "tty";
8
+ import * as __WEBPACK_EXTERNAL_MODULE_node_module_ab9f2194__ from "node:module";
9
+ import * as __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__ from "node:url";
10
10
  var __webpack_modules__ = {
11
- "@rspack/core": function(module) {
12
- module.exports = __WEBPACK_EXTERNAL_MODULE__rspack_core_e0096ff7__;
11
+ "../../node_modules/.pnpm/pirates@4.0.7/node_modules/pirates/lib/index.js": function(module, exports, __webpack_require__) {
12
+ module = __webpack_require__.nmd(module);
13
+ const BuiltinModule = __webpack_require__("module");
14
+ const path = __webpack_require__("path");
15
+ const nodeModulesRegex = /^(?:.*[\\/])?node_modules(?:[\\/].*)?$/;
16
+ const Module = module.constructor.length > 1 ? module.constructor : BuiltinModule;
17
+ const HOOK_RETURNED_NOTHING_ERROR_MESSAGE = "[Pirates] A hook returned a non-string, or nothing at all! This is a violation of intergalactic law!\n--------------------\nIf you have no idea what this means or what Pirates is, let me explain: Pirates is a module that makes it easy to implement require hooks. One of the require hooks you're using uses it. One of these require hooks didn't return anything from it's handler, so we don't know what to do. You might want to debug this.";
18
+ function shouldCompile(filename, exts, matcher, ignoreNodeModules) {
19
+ if ('string' != typeof filename) return false;
20
+ if (-1 === exts.indexOf(path.extname(filename))) return false;
21
+ const resolvedFilename = path.resolve(filename);
22
+ if (ignoreNodeModules && nodeModulesRegex.test(resolvedFilename)) return false;
23
+ if (matcher && 'function' == typeof matcher) return !!matcher(resolvedFilename);
24
+ return true;
25
+ }
26
+ function addHook(hook, opts = {}) {
27
+ let reverted = false;
28
+ const loaders = [];
29
+ const oldLoaders = [];
30
+ let exts;
31
+ const originalJSLoader = Module._extensions['.js'];
32
+ const matcher = opts.matcher || null;
33
+ const ignoreNodeModules = false !== opts.ignoreNodeModules;
34
+ exts = opts.extensions || opts.exts || opts.extension || opts.ext || [
35
+ '.js'
36
+ ];
37
+ if (!Array.isArray(exts)) exts = [
38
+ exts
39
+ ];
40
+ exts.forEach((ext)=>{
41
+ if ('string' != typeof ext) throw new TypeError(`Invalid Extension: ${ext}`);
42
+ const oldLoader = Module._extensions[ext] || originalJSLoader;
43
+ oldLoaders[ext] = Module._extensions[ext];
44
+ loaders[ext] = Module._extensions[ext] = function(mod, filename) {
45
+ let compile;
46
+ if (!reverted) {
47
+ if (shouldCompile(filename, exts, matcher, ignoreNodeModules)) {
48
+ compile = mod._compile;
49
+ mod._compile = function(code) {
50
+ mod._compile = compile;
51
+ const newCode = hook(code, filename);
52
+ if ('string' != typeof newCode) throw new Error(HOOK_RETURNED_NOTHING_ERROR_MESSAGE);
53
+ return mod._compile(newCode, filename);
54
+ };
55
+ }
56
+ }
57
+ oldLoader(mod, filename);
58
+ };
59
+ });
60
+ return function() {
61
+ if (reverted) return;
62
+ reverted = true;
63
+ exts.forEach((ext)=>{
64
+ if (Module._extensions[ext] === loaders[ext]) if (oldLoaders[ext]) Module._extensions[ext] = oldLoaders[ext];
65
+ else delete Module._extensions[ext];
66
+ });
67
+ };
68
+ }
69
+ exports.addHook = addHook;
70
+ },
71
+ "./src/utils/rspackCore.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
72
+ __webpack_require__.d(__webpack_exports__, {
73
+ Z: ()=>rspack
74
+ });
75
+ const rspackCore_require = (0, __WEBPACK_EXTERNAL_MODULE_node_module_ab9f2194__.createRequire)(import.meta.url);
76
+ const rspack = rspackCore_require("@rspack/core");
77
+ },
78
+ module: function(module) {
79
+ module.exports = __WEBPACK_EXTERNAL_MODULE_module__;
13
80
  },
14
81
  "node:fs": function(module) {
15
82
  module.exports = __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__;
16
83
  },
17
84
  "node:path": function(module) {
18
85
  module.exports = __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__;
86
+ },
87
+ path: function(module) {
88
+ module.exports = __WEBPACK_EXTERNAL_MODULE_path__;
19
89
  }
20
90
  };
21
91
  var __webpack_module_cache__ = {};
@@ -23,9 +93,12 @@ function __webpack_require__(moduleId) {
23
93
  var cachedModule = __webpack_module_cache__[moduleId];
24
94
  if (void 0 !== cachedModule) return cachedModule.exports;
25
95
  var module = __webpack_module_cache__[moduleId] = {
96
+ id: moduleId,
97
+ loaded: false,
26
98
  exports: {}
27
99
  };
28
100
  __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
101
+ module.loaded = true;
29
102
  return module.exports;
30
103
  }
31
104
  __webpack_require__.m = __webpack_modules__;
@@ -50,6 +123,13 @@ __webpack_require__.m = __webpack_modules__;
50
123
  (()=>{
51
124
  __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
52
125
  })();
126
+ (()=>{
127
+ __webpack_require__.nmd = (module)=>{
128
+ module.paths = [];
129
+ if (!module.children) module.children = [];
130
+ return module;
131
+ };
132
+ })();
53
133
  (()=>{
54
134
  var installedChunks = {
55
135
  410: 0
@@ -88,72 +168,604 @@ __webpack_require__.m = __webpack_modules__;
88
168
  };
89
169
  })();
90
170
  var external_node_path_ = __webpack_require__("node:path");
91
- var core_ = __webpack_require__("@rspack/core");
92
- var external_node_fs_ = __webpack_require__("node:fs");
93
- const commonOptions = (yargs)=>yargs.options({
94
- config: {
95
- g: true,
96
- type: "string",
97
- describe: "config file",
98
- alias: "c"
99
- },
100
- configName: {
101
- type: "array",
102
- string: true,
103
- describe: "Name of the configuration to use."
104
- },
105
- configLoader: {
106
- type: "string",
107
- default: "register",
108
- describe: "Specify the loader to load the config file, can be `native` or `register`."
109
- },
110
- nodeEnv: {
111
- string: true,
112
- describe: "sets `process.env.NODE_ENV` to be specified value"
171
+ function toArr(any) {
172
+ return null == any ? [] : Array.isArray(any) ? any : [
173
+ any
174
+ ];
175
+ }
176
+ function toVal(out, key, val, opts) {
177
+ 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;
178
+ out[key] = null == old ? nxt : Array.isArray(old) ? old.concat(nxt) : [
179
+ old,
180
+ nxt
181
+ ];
182
+ }
183
+ function mri2(args, opts) {
184
+ args = args || [];
185
+ opts = opts || {};
186
+ var k, arr, arg, name, val, out = {
187
+ _: []
188
+ };
189
+ var i = 0, j = 0, idx = 0, len = args.length;
190
+ const alibi = void 0 !== opts.alias;
191
+ const strict = void 0 !== opts.unknown;
192
+ const defaults = void 0 !== opts.default;
193
+ opts.alias = opts.alias || {};
194
+ opts.string = toArr(opts.string);
195
+ opts.boolean = toArr(opts.boolean);
196
+ if (alibi) for(k in opts.alias){
197
+ arr = opts.alias[k] = toArr(opts.alias[k]);
198
+ for(i = 0; i < arr.length; i++)(opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
199
+ }
200
+ for(i = opts.boolean.length; i-- > 0;){
201
+ arr = opts.alias[opts.boolean[i]] || [];
202
+ for(j = arr.length; j-- > 0;)opts.boolean.push(arr[j]);
203
+ }
204
+ for(i = opts.string.length; i-- > 0;){
205
+ arr = opts.alias[opts.string[i]] || [];
206
+ for(j = arr.length; j-- > 0;)opts.string.push(arr[j]);
207
+ }
208
+ if (defaults) for(k in opts.default){
209
+ name = typeof opts.default[k];
210
+ arr = opts.alias[k] = opts.alias[k] || [];
211
+ if (void 0 !== opts[name]) {
212
+ opts[name].push(k);
213
+ for(i = 0; i < arr.length; i++)opts[name].push(arr[i]);
113
214
  }
114
- });
115
- const commonOptionsForBuildAndServe = (yargs)=>yargs.options({
116
- entry: {
117
- type: "array",
118
- string: true,
119
- describe: "entry file"
120
- },
121
- outputPath: {
122
- type: "string",
123
- describe: "output path dir",
124
- alias: "o"
125
- },
126
- mode: {
127
- type: "string",
128
- describe: "mode",
129
- alias: "m"
130
- },
131
- watch: {
132
- type: "boolean",
133
- default: false,
134
- describe: "watch",
135
- alias: "w"
136
- },
137
- env: {
138
- type: "array",
139
- string: true,
140
- describe: "env passed to config function"
141
- },
142
- devtool: {
143
- type: "string",
144
- describe: "Specify a developer tool for debugging. Defaults to `cheap-module-source-map` in development and `source-map` in production.",
145
- alias: "d",
146
- coerce: (arg)=>{
147
- if ("true" === arg) return "source-map";
148
- if ("false" === arg || "" === arg.trim()) return false;
149
- return arg;
215
+ }
216
+ const keys = strict ? Object.keys(opts.alias) : [];
217
+ for(i = 0; i < len; i++){
218
+ arg = args[i];
219
+ if ('--' === arg) {
220
+ out._ = out._.concat(args.slice(++i));
221
+ break;
222
+ }
223
+ for(j = 0; j < arg.length && 45 === arg.charCodeAt(j); j++);
224
+ if (0 === j) out._.push(arg);
225
+ else if ('no-' === arg.substring(j, j + 3)) {
226
+ name = arg.substring(j + 3);
227
+ if (strict && !~keys.indexOf(name)) return opts.unknown(arg);
228
+ out[name] = false;
229
+ } else {
230
+ for(idx = j + 1; idx < arg.length && 61 !== arg.charCodeAt(idx); idx++);
231
+ name = arg.substring(j, idx);
232
+ val = arg.substring(++idx) || i + 1 === len || 45 === ('' + args[i + 1]).charCodeAt(0) || args[++i];
233
+ arr = 2 === j ? [
234
+ name
235
+ ] : name;
236
+ for(idx = 0; idx < arr.length; idx++){
237
+ name = arr[idx];
238
+ if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name);
239
+ toVal(out, name, idx + 1 < arr.length || val, opts);
150
240
  }
151
241
  }
152
- }).alias({
153
- v: "version",
154
- h: "help"
155
- });
156
- function normalizeEnv(argv) {
242
+ }
243
+ if (defaults) {
244
+ for(k in opts.default)if (void 0 === out[k]) out[k] = opts.default[k];
245
+ }
246
+ if (alibi) for(k in out){
247
+ arr = opts.alias[k] || [];
248
+ while(arr.length > 0)out[arr.shift()] = out[k];
249
+ }
250
+ return out;
251
+ }
252
+ const removeBrackets = (v)=>v.replace(/[<[].+/, "").trim();
253
+ const findAllBrackets = (v)=>{
254
+ const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
255
+ const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
256
+ const res = [];
257
+ const parse = (match)=>{
258
+ let variadic = false;
259
+ let value = match[1];
260
+ if (value.startsWith("...")) {
261
+ value = value.slice(3);
262
+ variadic = true;
263
+ }
264
+ return {
265
+ required: match[0].startsWith("<"),
266
+ value,
267
+ variadic
268
+ };
269
+ };
270
+ let angledMatch;
271
+ while(angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v))res.push(parse(angledMatch));
272
+ let squareMatch;
273
+ while(squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v))res.push(parse(squareMatch));
274
+ return res;
275
+ };
276
+ const getMriOptions = (options)=>{
277
+ const result = {
278
+ alias: {},
279
+ boolean: []
280
+ };
281
+ for (const [index, option] of options.entries()){
282
+ if (option.names.length > 1) result.alias[option.names[0]] = option.names.slice(1);
283
+ if (option.isBoolean) if (option.negated) {
284
+ const hasStringTypeOption = options.some((o, i)=>i !== index && o.names.some((name)=>option.names.includes(name)) && "boolean" == typeof o.required);
285
+ if (!hasStringTypeOption) result.boolean.push(option.names[0]);
286
+ } else result.boolean.push(option.names[0]);
287
+ }
288
+ return result;
289
+ };
290
+ const findLongest = (arr)=>arr.sort((a, b)=>a.length > b.length ? -1 : 1)[0];
291
+ const padRight = (str, length)=>str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
292
+ const camelcase = (input)=>input.replace(/([a-z])-([a-z])/g, (_, p1, p2)=>p1 + p2.toUpperCase());
293
+ const setDotProp = (obj, keys, val)=>{
294
+ let i = 0;
295
+ let length = keys.length;
296
+ let t = obj;
297
+ let x;
298
+ for(; i < length; ++i){
299
+ x = t[keys[i]];
300
+ t = t[keys[i]] = i === length - 1 ? val : null != x ? x : !~keys[i + 1].indexOf(".") && +keys[i + 1] > -1 ? [] : {};
301
+ }
302
+ };
303
+ const setByType = (obj, transforms)=>{
304
+ for (const key of Object.keys(transforms)){
305
+ const transform = transforms[key];
306
+ if (transform.shouldTransform) {
307
+ obj[key] = Array.prototype.concat.call([], obj[key]);
308
+ if ("function" == typeof transform.transformFunction) obj[key] = obj[key].map(transform.transformFunction);
309
+ }
310
+ }
311
+ };
312
+ const getFileName = (input)=>{
313
+ const m = /([^\\\/]+)$/.exec(input);
314
+ return m ? m[1] : "";
315
+ };
316
+ const camelcaseOptionName = (name)=>name.split(".").map((v, i)=>0 === i ? camelcase(v) : v).join(".");
317
+ class CACError extends Error {
318
+ constructor(message){
319
+ super(message);
320
+ this.name = this.constructor.name;
321
+ if ("function" == typeof Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
322
+ else this.stack = new Error(message).stack;
323
+ }
324
+ }
325
+ class Option {
326
+ constructor(rawName, description, config){
327
+ this.rawName = rawName;
328
+ this.description = description;
329
+ this.config = Object.assign({}, config);
330
+ rawName = rawName.replace(/\.\*/g, "");
331
+ this.negated = false;
332
+ this.names = removeBrackets(rawName).split(",").map((v)=>{
333
+ let name = v.trim().replace(/^-{1,2}/, "");
334
+ if (name.startsWith("no-")) {
335
+ this.negated = true;
336
+ name = name.replace(/^no-/, "");
337
+ }
338
+ return camelcaseOptionName(name);
339
+ }).sort((a, b)=>a.length > b.length ? 1 : -1);
340
+ this.name = this.names[this.names.length - 1];
341
+ if (this.negated && null == this.config.default) this.config.default = true;
342
+ if (rawName.includes("<")) this.required = true;
343
+ else if (rawName.includes("[")) this.required = false;
344
+ else this.isBoolean = true;
345
+ }
346
+ }
347
+ const processArgs = process.argv;
348
+ const platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
349
+ class Command {
350
+ constructor(rawName, description, config = {}, cli){
351
+ this.rawName = rawName;
352
+ this.description = description;
353
+ this.config = config;
354
+ this.cli = cli;
355
+ this.options = [];
356
+ this.aliasNames = [];
357
+ this.name = removeBrackets(rawName);
358
+ this.args = findAllBrackets(rawName);
359
+ this.examples = [];
360
+ }
361
+ usage(text) {
362
+ this.usageText = text;
363
+ return this;
364
+ }
365
+ allowUnknownOptions() {
366
+ this.config.allowUnknownOptions = true;
367
+ return this;
368
+ }
369
+ ignoreOptionDefaultValue() {
370
+ this.config.ignoreOptionDefaultValue = true;
371
+ return this;
372
+ }
373
+ version(version, customFlags = "-v, --version") {
374
+ this.versionNumber = version;
375
+ this.option(customFlags, "Display version number");
376
+ return this;
377
+ }
378
+ example(example) {
379
+ this.examples.push(example);
380
+ return this;
381
+ }
382
+ option(rawName, description, config) {
383
+ const option = new Option(rawName, description, config);
384
+ this.options.push(option);
385
+ return this;
386
+ }
387
+ alias(name) {
388
+ this.aliasNames.push(name);
389
+ return this;
390
+ }
391
+ action(callback) {
392
+ this.commandAction = callback;
393
+ return this;
394
+ }
395
+ isMatched(name) {
396
+ return this.name === name || this.aliasNames.includes(name);
397
+ }
398
+ get isDefaultCommand() {
399
+ return "" === this.name || this.aliasNames.includes("!");
400
+ }
401
+ get isGlobalCommand() {
402
+ return this instanceof GlobalCommand;
403
+ }
404
+ hasOption(name) {
405
+ name = name.split(".")[0];
406
+ return this.options.find((option)=>option.names.includes(name));
407
+ }
408
+ outputHelp() {
409
+ const { name, commands } = this.cli;
410
+ const { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand;
411
+ let sections = [
412
+ {
413
+ body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
414
+ }
415
+ ];
416
+ sections.push({
417
+ title: "Usage",
418
+ body: ` $ ${name} ${this.usageText || this.rawName}`
419
+ });
420
+ const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0;
421
+ if (showCommands) {
422
+ const longestCommandName = findLongest(commands.map((command)=>command.rawName));
423
+ sections.push({
424
+ title: "Commands",
425
+ body: commands.map((command)=>` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`).join("\n")
426
+ });
427
+ sections.push({
428
+ title: "For more info, run any command with the `--help` flag",
429
+ body: commands.map((command)=>` $ ${name}${"" === command.name ? "" : ` ${command.name}`} --help`).join("\n")
430
+ });
431
+ }
432
+ let options = this.isGlobalCommand ? globalOptions : [
433
+ ...this.options,
434
+ ...globalOptions || []
435
+ ];
436
+ if (!this.isGlobalCommand && !this.isDefaultCommand) options = options.filter((option)=>"version" !== option.name);
437
+ if (options.length > 0) {
438
+ const longestOptionName = findLongest(options.map((option)=>option.rawName));
439
+ sections.push({
440
+ title: "Options",
441
+ body: options.map((option)=>` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${void 0 === option.config.default ? "" : `(default: ${option.config.default})`}`).join("\n")
442
+ });
443
+ }
444
+ if (this.examples.length > 0) sections.push({
445
+ title: "Examples",
446
+ body: this.examples.map((example)=>{
447
+ if ("function" == typeof example) return example(name);
448
+ return example;
449
+ }).join("\n")
450
+ });
451
+ if (helpCallback) sections = helpCallback(sections) || sections;
452
+ console.log(sections.map((section)=>section.title ? `${section.title}:
453
+ ${section.body}` : section.body).join("\n\n"));
454
+ }
455
+ outputVersion() {
456
+ const { name } = this.cli;
457
+ const { versionNumber } = this.cli.globalCommand;
458
+ if (versionNumber) console.log(`${name}/${versionNumber} ${platformInfo}`);
459
+ }
460
+ checkRequiredArgs() {
461
+ const minimalArgsCount = this.args.filter((arg)=>arg.required).length;
462
+ if (this.cli.args.length < minimalArgsCount) throw new CACError(`missing required args for command \`${this.rawName}\``);
463
+ }
464
+ checkUnknownOptions() {
465
+ const { options, globalCommand } = this.cli;
466
+ if (!this.config.allowUnknownOptions) {
467
+ 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}`}\``);
468
+ }
469
+ }
470
+ checkOptionValue() {
471
+ const { options: parsedOptions, globalCommand } = this.cli;
472
+ const options = [
473
+ ...globalCommand.options,
474
+ ...this.options
475
+ ];
476
+ for (const option of options){
477
+ const value = parsedOptions[option.name.split(".")[0]];
478
+ if (option.required) {
479
+ const hasNegated = options.some((o)=>o.negated && o.names.includes(option.name));
480
+ if (true === value || false === value && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`);
481
+ }
482
+ }
483
+ }
484
+ }
485
+ class GlobalCommand extends Command {
486
+ constructor(cli){
487
+ super("@@global@@", "", {}, cli);
488
+ }
489
+ }
490
+ var __assign = Object.assign;
491
+ class CAC extends __WEBPACK_EXTERNAL_MODULE_events__.EventEmitter {
492
+ constructor(name = ""){
493
+ super();
494
+ this.name = name;
495
+ this.commands = [];
496
+ this.rawArgs = [];
497
+ this.args = [];
498
+ this.options = {};
499
+ this.globalCommand = new GlobalCommand(this);
500
+ this.globalCommand.usage("<command> [options]");
501
+ }
502
+ usage(text) {
503
+ this.globalCommand.usage(text);
504
+ return this;
505
+ }
506
+ command(rawName, description, config) {
507
+ const command = new Command(rawName, description || "", config, this);
508
+ command.globalCommand = this.globalCommand;
509
+ this.commands.push(command);
510
+ return command;
511
+ }
512
+ option(rawName, description, config) {
513
+ this.globalCommand.option(rawName, description, config);
514
+ return this;
515
+ }
516
+ help(callback) {
517
+ this.globalCommand.option("-h, --help", "Display this message");
518
+ this.globalCommand.helpCallback = callback;
519
+ this.showHelpOnExit = true;
520
+ return this;
521
+ }
522
+ version(version, customFlags = "-v, --version") {
523
+ this.globalCommand.version(version, customFlags);
524
+ this.showVersionOnExit = true;
525
+ return this;
526
+ }
527
+ example(example) {
528
+ this.globalCommand.example(example);
529
+ return this;
530
+ }
531
+ outputHelp() {
532
+ if (this.matchedCommand) this.matchedCommand.outputHelp();
533
+ else this.globalCommand.outputHelp();
534
+ }
535
+ outputVersion() {
536
+ this.globalCommand.outputVersion();
537
+ }
538
+ setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
539
+ this.args = args;
540
+ this.options = options;
541
+ if (matchedCommand) this.matchedCommand = matchedCommand;
542
+ if (matchedCommandName) this.matchedCommandName = matchedCommandName;
543
+ return this;
544
+ }
545
+ unsetMatchedCommand() {
546
+ this.matchedCommand = void 0;
547
+ this.matchedCommandName = void 0;
548
+ }
549
+ parse(argv = processArgs, { run = true } = {}) {
550
+ this.rawArgs = argv;
551
+ if (!this.name) this.name = argv[1] ? getFileName(argv[1]) : "cli";
552
+ let shouldParse = true;
553
+ for (const command of this.commands){
554
+ const parsed = this.mri(argv.slice(2), command);
555
+ const commandName = parsed.args[0];
556
+ if (command.isMatched(commandName)) {
557
+ shouldParse = false;
558
+ const parsedInfo = __assign(__assign({}, parsed), {
559
+ args: parsed.args.slice(1)
560
+ });
561
+ this.setParsedInfo(parsedInfo, command, commandName);
562
+ this.emit(`command:${commandName}`, command);
563
+ }
564
+ }
565
+ if (shouldParse) {
566
+ for (const command of this.commands)if ("" === command.name) {
567
+ shouldParse = false;
568
+ const parsed = this.mri(argv.slice(2), command);
569
+ this.setParsedInfo(parsed, command);
570
+ this.emit("command:!", command);
571
+ }
572
+ }
573
+ if (shouldParse) {
574
+ const parsed = this.mri(argv.slice(2));
575
+ this.setParsedInfo(parsed);
576
+ }
577
+ if (this.options.help && this.showHelpOnExit) {
578
+ this.outputHelp();
579
+ run = false;
580
+ this.unsetMatchedCommand();
581
+ }
582
+ if (this.options.version && this.showVersionOnExit && null == this.matchedCommandName) {
583
+ this.outputVersion();
584
+ run = false;
585
+ this.unsetMatchedCommand();
586
+ }
587
+ const parsedArgv = {
588
+ args: this.args,
589
+ options: this.options
590
+ };
591
+ if (run) this.runMatchedCommand();
592
+ if (!this.matchedCommand && this.args[0]) this.emit("command:*");
593
+ return parsedArgv;
594
+ }
595
+ mri(argv, command) {
596
+ const cliOptions = [
597
+ ...this.globalCommand.options,
598
+ ...command ? command.options : []
599
+ ];
600
+ const mriOptions = getMriOptions(cliOptions);
601
+ let argsAfterDoubleDashes = [];
602
+ const doubleDashesIndex = argv.indexOf("--");
603
+ if (doubleDashesIndex > -1) {
604
+ argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
605
+ argv = argv.slice(0, doubleDashesIndex);
606
+ }
607
+ let parsed = mri2(argv, mriOptions);
608
+ parsed = Object.keys(parsed).reduce((res, name)=>__assign(__assign({}, res), {
609
+ [camelcaseOptionName(name)]: parsed[name]
610
+ }), {
611
+ _: []
612
+ });
613
+ const args = parsed._;
614
+ const options = {
615
+ "--": argsAfterDoubleDashes
616
+ };
617
+ const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
618
+ let transforms = Object.create(null);
619
+ for (const cliOption of cliOptions){
620
+ if (!ignoreDefault && void 0 !== cliOption.config.default) for (const name of cliOption.names)options[name] = cliOption.config.default;
621
+ if (Array.isArray(cliOption.config.type)) {
622
+ if (void 0 === transforms[cliOption.name]) {
623
+ transforms[cliOption.name] = Object.create(null);
624
+ transforms[cliOption.name]["shouldTransform"] = true;
625
+ transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0];
626
+ }
627
+ }
628
+ }
629
+ for (const key of Object.keys(parsed))if ("_" !== key) {
630
+ const keys = key.split(".");
631
+ setDotProp(options, keys, parsed[key]);
632
+ setByType(options, transforms);
633
+ }
634
+ return {
635
+ args,
636
+ options
637
+ };
638
+ }
639
+ runMatchedCommand() {
640
+ const { args, options, matchedCommand: command } = this;
641
+ if (!command || !command.commandAction) return;
642
+ command.checkUnknownOptions();
643
+ command.checkOptionValue();
644
+ command.checkRequiredArgs();
645
+ const actionArgs = [];
646
+ command.args.forEach((arg, index)=>{
647
+ if (arg.variadic) actionArgs.push(args.slice(index));
648
+ else actionArgs.push(args[index]);
649
+ });
650
+ actionArgs.push(options);
651
+ return command.commandAction.apply(this, actionArgs);
652
+ }
653
+ }
654
+ const cac = (name = "")=>new CAC(name);
655
+ const dist = cac;
656
+ const { env: colorette_env = {}, argv: colorette_argv = [], platform = "" } = "undefined" == typeof process ? {} : process;
657
+ const isDisabled = "NO_COLOR" in colorette_env || colorette_argv.includes("--no-color");
658
+ const isForced = "FORCE_COLOR" in colorette_env || colorette_argv.includes("--color");
659
+ const isWindows = "win32" === platform;
660
+ const isDumbTerminal = "dumb" === colorette_env.TERM;
661
+ const isCompatibleTerminal = __WEBPACK_EXTERNAL_MODULE_tty__ && __WEBPACK_EXTERNAL_MODULE_tty__.isatty && __WEBPACK_EXTERNAL_MODULE_tty__.isatty(1) && colorette_env.TERM && !isDumbTerminal;
662
+ const isCI = "CI" in colorette_env && ("GITHUB_ACTIONS" in colorette_env || "GITLAB_CI" in colorette_env || "CIRCLECI" in colorette_env);
663
+ const isColorSupported = !isDisabled && (isForced || isWindows && !isDumbTerminal || isCompatibleTerminal || isCI);
664
+ const replaceClose = (index, string, close, replace, head = string.substring(0, index) + replace, tail = string.substring(index + close.length), next = tail.indexOf(close))=>head + (next < 0 ? tail : replaceClose(next, tail, close, replace));
665
+ const clearBleed = (index, string, open, close, replace)=>index < 0 ? open + string + close : open + replaceClose(index, string, close, replace) + close;
666
+ const filterEmpty = (open, close, replace = open, at = open.length + 1)=>(string)=>string || !("" === string || void 0 === string) ? clearBleed(("" + string).indexOf(close, at), string, open, close, replace) : "";
667
+ const init = (open, close, replace)=>filterEmpty(`\x1b[${open}m`, `\x1b[${close}m`, replace);
668
+ const colorette_colors = {
669
+ reset: init(0, 0),
670
+ bold: init(1, 22, "\x1b[22m\x1b[1m"),
671
+ dim: init(2, 22, "\x1b[22m\x1b[2m"),
672
+ italic: init(3, 23),
673
+ underline: init(4, 24),
674
+ inverse: init(7, 27),
675
+ hidden: init(8, 28),
676
+ strikethrough: init(9, 29),
677
+ black: init(30, 39),
678
+ red: init(31, 39),
679
+ green: init(32, 39),
680
+ yellow: init(33, 39),
681
+ blue: init(34, 39),
682
+ magenta: init(35, 39),
683
+ cyan: init(36, 39),
684
+ white: init(37, 39),
685
+ gray: init(90, 39),
686
+ bgBlack: init(40, 49),
687
+ bgRed: init(41, 49),
688
+ bgGreen: init(42, 49),
689
+ bgYellow: init(43, 49),
690
+ bgBlue: init(44, 49),
691
+ bgMagenta: init(45, 49),
692
+ bgCyan: init(46, 49),
693
+ bgWhite: init(47, 49),
694
+ blackBright: init(90, 39),
695
+ redBright: init(91, 39),
696
+ greenBright: init(92, 39),
697
+ yellowBright: init(93, 39),
698
+ blueBright: init(94, 39),
699
+ magentaBright: init(95, 39),
700
+ cyanBright: init(96, 39),
701
+ whiteBright: init(97, 39),
702
+ bgBlackBright: init(100, 49),
703
+ bgRedBright: init(101, 49),
704
+ bgGreenBright: init(102, 49),
705
+ bgYellowBright: init(103, 49),
706
+ bgBlueBright: init(104, 49),
707
+ bgMagentaBright: init(105, 49),
708
+ bgCyanBright: init(106, 49),
709
+ bgWhiteBright: init(107, 49)
710
+ };
711
+ const createColors = ({ useColor = isColorSupported } = {})=>useColor ? colorette_colors : Object.keys(colorette_colors).reduce((colors, key)=>({
712
+ ...colors,
713
+ [key]: String
714
+ }), {});
715
+ const { reset: colorette_reset, bold, dim, italic, underline, inverse, hidden: colorette_hidden, strikethrough, black, red, green, yellow, blue, magenta, cyan, white, gray, bgBlack, bgRed, bgGreen, bgYellow, bgBlue, bgMagenta, bgCyan, bgWhite, blackBright, redBright, greenBright, yellowBright, blueBright, magentaBright, cyanBright, whiteBright, bgBlackBright, bgRedBright, bgGreenBright, bgYellowBright, bgBlueBright, bgMagentaBright, bgCyanBright, bgWhiteBright } = createColors();
716
+ var external_node_fs_ = __webpack_require__("node:fs");
717
+ const commonOptions = (command)=>command.option("-c, --config <path>", "config file").option("--config-name <name>", "Name(s) of the configuration to use.", {
718
+ type: [
719
+ String
720
+ ],
721
+ default: []
722
+ }).option("--config-loader <loader>", "Specify the loader to load the config file, can be `native` or `register`.", {
723
+ default: "register"
724
+ }).option("--env <env>", "env passed to config function", {
725
+ type: [
726
+ String
727
+ ],
728
+ default: []
729
+ }).option("--node-env <value>", "sets `process.env.NODE_ENV` to be specified value");
730
+ function normalizeDevtoolOption(value) {
731
+ if ("string" == typeof value) {
732
+ const trimmed = value.trim();
733
+ if ("" === trimmed || "false" === trimmed) return false;
734
+ if ("true" === trimmed) return "source-map";
735
+ return trimmed;
736
+ }
737
+ if ("boolean" == typeof value) return value ? "source-map" : false;
738
+ }
739
+ const normalizeCommonOptions = (options, action)=>{
740
+ const isEmptyArray = (arr)=>Array.isArray(arr) && 0 === arr.length;
741
+ for (const key of [
742
+ "entry",
743
+ "configName"
744
+ ]){
745
+ const val = options[key];
746
+ if (isEmptyArray(val)) options[key] = void 0;
747
+ }
748
+ const env = Array.isArray(options.env) ? normalizeEnvToObject(options) : {};
749
+ options.env = env;
750
+ if ("serve" === action) setBuiltinEnvArg(env, "SERVE", true);
751
+ else if ("build" === action) if (options.watch) setBuiltinEnvArg(env, "WATCH", true);
752
+ else {
753
+ setBuiltinEnvArg(env, "BUNDLE", true);
754
+ setBuiltinEnvArg(env, "BUILD", true);
755
+ }
756
+ if ("devtool" in options) options.devtool = normalizeDevtoolOption(options.devtool);
757
+ };
758
+ const commonOptionsForBuildAndServe = (command)=>command.option("--analyze", "analyze").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", {
759
+ type: [
760
+ String
761
+ ],
762
+ default: []
763
+ }).option("-m, --mode <mode>", "mode").option("-o, --output-path <dir>", "output path dir").option("--profile", "capture timing information for each module").option("-w, --watch", "watch");
764
+ function setBuiltinEnvArg(env, envNameSuffix, value) {
765
+ const envName = `RSPACK_${envNameSuffix}`;
766
+ if (!(envName in env)) env[envName] = value;
767
+ }
768
+ function normalizeEnvToObject(options) {
157
769
  function parseValue(previous, value) {
158
770
  const [allKeys, val] = value.split(/=(.+)/, 2);
159
771
  const splitKeys = allKeys.split(/\.(?!$)/);
@@ -172,155 +784,80 @@ function normalizeEnv(argv) {
172
784
  });
173
785
  return previous;
174
786
  }
175
- const envObj = (argv.env ?? []).reduce(parseValue, {});
176
- argv.env = envObj;
177
- }
178
- function setBuiltinEnvArg(env, envNameSuffix, value) {
179
- const envNames = [
180
- `RSPACK_${envNameSuffix}`
181
- ];
182
- for (const envName of envNames)if (!(envName in env)) env[envName] = value;
183
- }
184
- function ensureEnvObject(options) {
185
- if (Array.isArray(options.env)) normalizeEnv(options);
186
- options.env = options.env || {};
187
- return options.env;
787
+ return (options.env ?? []).reduce(parseValue, {});
188
788
  }
189
789
  function setDefaultNodeEnv(options, defaultEnv) {
190
- if (void 0 !== process.env.NODE_ENV) return;
191
- process.env.NODE_ENV = "string" == typeof options.nodeEnv ? options.nodeEnv : defaultEnv;
790
+ if (void 0 === process.env.NODE_ENV) process.env.NODE_ENV = "string" == typeof options.nodeEnv ? options.nodeEnv : defaultEnv;
192
791
  }
193
- class BuildCommand {
194
- async apply(cli) {
195
- cli.program.command([
196
- "build",
197
- "$0",
198
- "bundle",
199
- "b"
200
- ], "run the rspack build", (yargs)=>{
201
- commonOptionsForBuildAndServe(commonOptions(yargs)).options({
202
- analyze: {
203
- type: "boolean",
204
- default: false,
205
- describe: "analyze"
206
- },
207
- json: {
208
- describe: "emit stats json"
209
- },
210
- profile: {
211
- type: "boolean",
212
- default: false,
213
- describe: "capture timing information for each module"
214
- }
215
- });
216
- }, async (options)=>{
217
- setDefaultNodeEnv(options, "production");
218
- const env = ensureEnvObject(options);
219
- if (options.watch) setBuiltinEnvArg(env, "WATCH", true);
220
- else {
221
- setBuiltinEnvArg(env, "BUNDLE", true);
222
- setBuiltinEnvArg(env, "BUILD", true);
223
- }
224
- const logger = cli.getLogger();
225
- let createJsonStringifyStream;
226
- if (options.json) {
227
- const jsonExt = await import("@discoveryjs/json-ext");
228
- createJsonStringifyStream = jsonExt.default.stringifyStream;
229
- }
230
- const errorHandler = (error, stats)=>{
231
- if (error) {
232
- logger.error(error);
233
- process.exit(2);
234
- }
235
- if (stats?.hasErrors()) process.exitCode = 1;
236
- if (!compiler || !stats) return;
237
- const statsOptions = cli.isMultipleCompiler(compiler) ? {
238
- children: compiler.compilers.map((compiler)=>compiler.options ? compiler.options.stats : void 0)
239
- } : compiler.options ? compiler.options.stats : void 0;
240
- if (options.json && createJsonStringifyStream) {
241
- const handleWriteError = (error)=>{
242
- logger.error(error);
243
- process.exit(2);
244
- };
245
- if (true === options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on("error", handleWriteError).pipe(process.stdout).on("error", handleWriteError).on("close", ()=>process.stdout.write("\n"));
246
- else if ("string" == typeof options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on("error", handleWriteError).pipe(external_node_fs_.createWriteStream(options.json)).on("error", handleWriteError).on("close", ()=>{
247
- process.stderr.write(`[rspack-cli] ${cli.colors.green(`stats are successfully stored as json to ${options.json}`)}\n`);
248
- });
249
- } else {
250
- const printedStats = stats.toString(statsOptions);
251
- if (printedStats) logger.raw(printedStats);
252
- }
253
- };
254
- const rspackOptions = {
255
- ...options,
256
- argv: {
257
- ...options
258
- }
792
+ async function runBuild(cli, options) {
793
+ setDefaultNodeEnv(options, "production");
794
+ normalizeCommonOptions(options, "build");
795
+ const logger = cli.getLogger();
796
+ let createJsonStringifyStream;
797
+ if (options.json) {
798
+ const jsonExt = await import("@discoveryjs/json-ext");
799
+ createJsonStringifyStream = jsonExt.default.stringifyStream;
800
+ }
801
+ const errorHandler = (error, stats)=>{
802
+ if (error) {
803
+ logger.error(error);
804
+ process.exit(2);
805
+ }
806
+ if (stats?.hasErrors()) process.exitCode = 1;
807
+ if (!compiler || !stats) return;
808
+ const statsOptions = cli.isMultipleCompiler(compiler) ? {
809
+ children: compiler.compilers.map((item)=>item.options ? item.options.stats : void 0)
810
+ } : compiler.options ? compiler.options.stats : void 0;
811
+ if (options.json && createJsonStringifyStream) {
812
+ const handleWriteError = (error)=>{
813
+ logger.error(error);
814
+ process.exit(2);
259
815
  };
260
- const compiler = await cli.createCompiler(rspackOptions, "build", errorHandler);
261
- if (!compiler || cli.isWatch(compiler)) return;
262
- compiler.run((error, stats)=>{
263
- compiler.close((closeErr)=>{
264
- if (closeErr) logger.error(closeErr);
265
- errorHandler(error, stats);
266
- });
816
+ if (true === options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on("error", handleWriteError).pipe(process.stdout).on("error", handleWriteError).on("close", ()=>process.stdout.write("\n"));
817
+ else if ("string" == typeof options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on("error", handleWriteError).pipe(external_node_fs_["default"].createWriteStream(options.json)).on("error", handleWriteError).on("close", ()=>{
818
+ process.stderr.write(`[rspack-cli] ${cli.colors.green(`stats are successfully stored as json to ${options.json}`)}\n`);
267
819
  });
820
+ } else {
821
+ const printedStats = stats.toString(statsOptions);
822
+ if (printedStats) logger.raw(printedStats);
823
+ }
824
+ };
825
+ const compiler = await cli.createCompiler(options, "build", errorHandler);
826
+ if (!compiler || cli.isWatch(compiler)) return;
827
+ compiler.run((error, stats)=>{
828
+ compiler.close((closeErr)=>{
829
+ if (closeErr) logger.error(closeErr);
830
+ errorHandler(error, stats);
831
+ });
832
+ });
833
+ }
834
+ class BuildCommand {
835
+ async apply(cli) {
836
+ const command = cli.program.command("", "run the Rspack build").alias("build").alias("bundle").alias("b");
837
+ commonOptionsForBuildAndServe(commonOptions(command)).option("--json [path]", "emit stats json");
838
+ command.action(async (options)=>{
839
+ await runBuild(cli, options);
268
840
  });
269
841
  }
270
842
  }
271
- const previewOptions = (yargs)=>{
272
- yargs.positional("dir", {
273
- type: "string",
274
- describe: "directory want to preview"
275
- });
276
- return commonOptions(yargs).options({
277
- publicPath: {
278
- type: "string",
279
- describe: "static resource server path"
280
- },
281
- port: {
282
- type: "number",
283
- describe: "preview server port"
284
- },
285
- host: {
286
- type: "string",
287
- describe: "preview server host"
288
- },
289
- open: {
290
- type: "boolean",
291
- describe: "open browser"
292
- },
293
- server: {
294
- type: "string",
295
- describe: "Configuration items for the server."
296
- }
297
- });
298
- };
299
- const defaultRoot = "dist";
843
+ var rspackCore = __webpack_require__("./src/utils/rspackCore.ts");
300
844
  class PreviewCommand {
301
845
  async apply(cli) {
302
- cli.program.command([
303
- "preview [dir]",
304
- "preview",
305
- "p"
306
- ], "run the rspack server for build output", previewOptions, async (options)=>{
846
+ const command = cli.program.command("preview [dir]", "run the Rspack server for build output").alias("p");
847
+ 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.");
848
+ command.action(async (dir, options)=>{
307
849
  setDefaultNodeEnv(options, "production");
308
- const rspackOptions = {
309
- ...options,
310
- argv: {
311
- ...options
312
- }
313
- };
850
+ normalizeCommonOptions(options, "preview");
314
851
  const { RspackDevServer } = await import("@rspack/dev-server");
315
- let { config } = await cli.loadConfig(rspackOptions);
316
- config = await getPreviewConfig(config, options);
852
+ let { config } = await cli.loadConfig(options);
853
+ config = await getPreviewConfig(config, options, dir);
317
854
  if (!Array.isArray(config)) config = [
318
855
  config
319
856
  ];
320
- config = config.find((item)=>item.devServer) || config[0];
321
- const devServerOptions = config.devServer;
857
+ const singleConfig = config.find((item)=>item.devServer) || config[0];
858
+ const devServerOptions = singleConfig.devServer;
322
859
  try {
323
- const compiler = (0, core_.rspack)({
860
+ const compiler = (0, rspackCore.Z)({
324
861
  entry: {}
325
862
  });
326
863
  if (!compiler) return;
@@ -334,11 +871,12 @@ class PreviewCommand {
334
871
  });
335
872
  }
336
873
  }
337
- async function getPreviewConfig(item, options) {
874
+ async function getPreviewConfig(item, options, dir) {
875
+ const DEFAULT_ROOT = "dist";
338
876
  const internalPreviewConfig = async (item)=>{
339
877
  item.devServer = {
340
878
  static: {
341
- directory: options.dir ? external_node_path_["default"].join(item.context ?? process.cwd(), options.dir) : item.output?.path ?? external_node_path_["default"].join(item.context ?? process.cwd(), defaultRoot),
879
+ directory: dir ? external_node_path_["default"].join(item.context ?? process.cwd(), dir) : item.output?.path ?? external_node_path_["default"].join(item.context ?? process.cwd(), DEFAULT_ROOT),
342
880
  publicPath: options.publicPath ?? "/"
343
881
  },
344
882
  port: options.port ?? 8080,
@@ -353,42 +891,21 @@ async function getPreviewConfig(item, options) {
353
891
  if (Array.isArray(item)) return Promise.all(item.map(internalPreviewConfig));
354
892
  return internalPreviewConfig(item);
355
893
  }
894
+ function normalizeHotOption(value) {
895
+ if ("boolean" == typeof value || "only" === value) return value;
896
+ if ("false" === value) return false;
897
+ return true;
898
+ }
356
899
  class ServeCommand {
357
900
  async apply(cli) {
358
- cli.program.command([
359
- "serve",
360
- "server",
361
- "s",
362
- "dev"
363
- ], "run the rspack dev server.", (yargs)=>commonOptionsForBuildAndServe(commonOptions(yargs)).options({
364
- hot: {
365
- coerce: (arg)=>{
366
- if ("boolean" == typeof arg || "only" === arg) return arg;
367
- if ("false" === arg) return false;
368
- return true;
369
- },
370
- describe: "enables hot module replacement"
371
- },
372
- port: {
373
- type: "number",
374
- coerce: (arg)=>Number.isInteger(arg) ? arg : void 0,
375
- describe: "allows to specify a port to use"
376
- },
377
- host: {
378
- type: "string",
379
- describe: "allows to specify a hostname to use"
380
- }
381
- }), async (options)=>{
901
+ const command = cli.program.command("serve", "run the rspack dev server.").alias("server").alias("s").alias("dev");
902
+ 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");
903
+ command.action(async (options)=>{
382
904
  setDefaultNodeEnv(options, "development");
383
- setBuiltinEnvArg(ensureEnvObject(options), "SERVE", true);
384
- const rspackOptions = {
385
- ...options,
386
- argv: {
387
- ...options
388
- }
389
- };
905
+ normalizeCommonOptions(options, "serve");
906
+ options.hot = normalizeHotOption(options.hot);
390
907
  const { RspackDevServer } = await import("@rspack/dev-server");
391
- const compiler = await cli.createCompiler(rspackOptions, "serve");
908
+ const compiler = await cli.createCompiler(options, "serve");
392
909
  if (!compiler) return;
393
910
  const compilers = cli.isMultipleCompiler(compiler) ? compiler.compilers : [
394
911
  compiler
@@ -412,8 +929,8 @@ class ServeCommand {
412
929
  }
413
930
  }
414
931
  const result = compilerForDevServer.options.devServer ??= {};
415
- const setupMiddlewares = result.setupMiddlewares;
416
- const lazyCompileMiddleware = core_.rspack.experiments.lazyCompilationMiddleware(compiler);
932
+ const { setupMiddlewares } = result;
933
+ const lazyCompileMiddleware = rspackCore.Z.experiments.lazyCompilationMiddleware(compiler);
417
934
  result.setupMiddlewares = (middlewares, server)=>{
418
935
  let finalMiddlewares = middlewares;
419
936
  if (setupMiddlewares) finalMiddlewares = setupMiddlewares(finalMiddlewares, server);
@@ -424,7 +941,7 @@ class ServeCommand {
424
941
  };
425
942
  result.hot = options.hot ?? result.hot ?? true;
426
943
  result.host = options.host || result.host;
427
- result.port = options.port || result.port;
944
+ result.port = options.port ?? result.port;
428
945
  if (false !== result.client) {
429
946
  if (true === result.client || null == result.client) result.client = {};
430
947
  result.client = {
@@ -455,6 +972,7 @@ class ServeCommand {
455
972
  });
456
973
  }
457
974
  }
975
+ var lib = __webpack_require__("../../node_modules/.pnpm/pirates@4.0.7/node_modules/pirates/lib/index.js");
458
976
  const readPackageUp = (cwd = process.cwd())=>{
459
977
  let currentDir = external_node_path_["default"].resolve(cwd);
460
978
  let packageJsonPath = external_node_path_["default"].join(currentDir, "package.json");
@@ -481,7 +999,7 @@ const isEsmFile = (filePath, cwd = process.cwd())=>{
481
999
  const utils_isEsmFile = isEsmFile;
482
1000
  const crossImport = async (path, cwd = process.cwd())=>{
483
1001
  if (utils_isEsmFile(path, cwd)) {
484
- const url = pathToFileURL(path).href;
1002
+ const url = (0, __WEBPACK_EXTERNAL_MODULE_node_url_e96de089__.pathToFileURL)(path).href;
485
1003
  const { default: config } = await import(url);
486
1004
  return config;
487
1005
  }
@@ -509,7 +1027,7 @@ const isTsFile_isTsFile = (configPath)=>{
509
1027
  return TS_EXTENSION.includes(ext);
510
1028
  };
511
1029
  const isTsFile = isTsFile_isTsFile;
512
- const injectInlineSourceMap = ({ filename, code, map })=>{
1030
+ const injectInlineSourceMap = ({ code, map })=>{
513
1031
  if (map) {
514
1032
  const base64Map = Buffer.from(map, "utf8").toString("base64");
515
1033
  const sourceMapContent = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${base64Map}`;
@@ -518,7 +1036,7 @@ const injectInlineSourceMap = ({ filename, code, map })=>{
518
1036
  return code;
519
1037
  };
520
1038
  function compile(sourcecode, filename) {
521
- const { code, map } = core_.experiments.swc.transformSync(sourcecode, {
1039
+ const { code, map } = rspackCore.Z.experiments.swc.transformSync(sourcecode, {
522
1040
  jsc: {
523
1041
  parser: {
524
1042
  syntax: "typescript",
@@ -535,7 +1053,6 @@ function compile(sourcecode, filename) {
535
1053
  isModule: true
536
1054
  });
537
1055
  return injectInlineSourceMap({
538
- filename,
539
1056
  code,
540
1057
  map
541
1058
  });
@@ -544,7 +1061,7 @@ const loadConfig_DEFAULT_CONFIG_NAME = "rspack.config";
544
1061
  const registerLoader = (configPath)=>{
545
1062
  if (utils_isEsmFile(configPath) && isTsFile(configPath)) return;
546
1063
  if (!isTsFile(configPath)) throw new Error(`config file "${configPath}" is not supported.`);
547
- addHook((code, filename)=>{
1064
+ (0, lib.addHook)((code, filename)=>{
548
1065
  try {
549
1066
  return compile(code, filename);
550
1067
  } catch (err) {
@@ -609,7 +1126,7 @@ async function loadExtendedConfig(config, configPath, cwd, options) {
609
1126
  if (isTsFile(resolvedPath) && "register" === options.configLoader) registerLoader(resolvedPath);
610
1127
  let loadedConfig = await crossImport(resolvedPath, cwd);
611
1128
  if ("function" == typeof loadedConfig) {
612
- loadedConfig = loadedConfig(options.argv?.env, options.argv);
1129
+ loadedConfig = loadedConfig(options.env, options);
613
1130
  if ("function" == typeof loadedConfig.then) loadedConfig = await loadedConfig;
614
1131
  }
615
1132
  const { config: extendedConfig, pathMap: extendedPathMap } = await loadExtendedConfig(loadedConfig, resolvedPath, cwd, options);
@@ -617,7 +1134,7 @@ async function loadExtendedConfig(config, configPath, cwd, options) {
617
1134
  ...pathMap.get(resultConfig) || [],
618
1135
  ...extendedPathMap.get(extendedConfig) || []
619
1136
  ];
620
- resultConfig = core_.util.cleverMerge(extendedConfig, resultConfig);
1137
+ resultConfig = rspackCore.Z.util.cleverMerge(extendedConfig, resultConfig);
621
1138
  pathMap.set(resultConfig, configPaths);
622
1139
  }
623
1140
  return {
@@ -646,8 +1163,11 @@ class RspackCLI {
646
1163
  colors;
647
1164
  program;
648
1165
  constructor(){
1166
+ const program = dist("rspack");
649
1167
  this.colors = this.createColors();
650
- this.program = yargs_0();
1168
+ this.program = program;
1169
+ program.help();
1170
+ program.version("1.6.0-canary-2ccce257-20251016173648");
651
1171
  }
652
1172
  async createCompiler(options, rspackCommand, callback) {
653
1173
  process.env.RSPACK_CONFIG_VALIDATE ??= "loose";
@@ -656,9 +1176,9 @@ class RspackCLI {
656
1176
  const isWatch = Array.isArray(config) ? config.some((i)=>i.watch) : config.watch;
657
1177
  let compiler;
658
1178
  try {
659
- compiler = (0, core_.rspack)(config, isWatch ? callback : void 0);
1179
+ compiler = (0, rspackCore.Z)(config, isWatch ? callback : void 0);
660
1180
  } catch (e) {
661
- if (e instanceof core_.ValidationError) {
1181
+ if (e instanceof rspackCore.Z.ValidationError) {
662
1182
  this.getLogger().error(e.message);
663
1183
  process.exit(2);
664
1184
  } else if (e instanceof Error) {
@@ -681,7 +1201,7 @@ class RspackCLI {
681
1201
  }
682
1202
  getLogger() {
683
1203
  return {
684
- error: (val)=>console.error(`[rspack-cli] ${this.colors.red(node_util.format(val))}`),
1204
+ error: (val)=>console.error(`[rspack-cli] ${this.colors.red(__WEBPACK_EXTERNAL_MODULE_node_util_1b29d436__["default"].format(val))}`),
685
1205
  warn: (val)=>console.warn(`[rspack-cli] ${this.colors.yellow(val)}`),
686
1206
  info: (val)=>console.info(`[rspack-cli] ${this.colors.cyan(val)}`),
687
1207
  success: (val)=>console.log(`[rspack-cli] ${this.colors.green(val)}`),
@@ -690,13 +1210,8 @@ class RspackCLI {
690
1210
  };
691
1211
  }
692
1212
  async run(argv) {
693
- this.program.showHelpOnFail(false);
694
- this.program.usage("[options]");
695
- this.program.scriptName("rspack");
696
- this.program.strictCommands(true).strict(true);
697
- this.program.middleware(normalizeEnv);
698
- this.registerCommands();
699
- await this.program.parseAsync(hideBin(argv));
1213
+ await this.registerCommands();
1214
+ this.program.parse(argv);
700
1215
  }
701
1216
  async registerCommands() {
702
1217
  const builtinCommands = [
@@ -704,7 +1219,7 @@ class RspackCLI {
704
1219
  new ServeCommand(),
705
1220
  new PreviewCommand()
706
1221
  ];
707
- for (const command of builtinCommands)command.apply(this);
1222
+ for (const command of builtinCommands)await command.apply(this);
708
1223
  }
709
1224
  async buildConfig(item, pathMap, options, command) {
710
1225
  const isBuild = "build" === command;
@@ -737,8 +1252,8 @@ class RspackCLI {
737
1252
  if (void 0 === item.devtool) item.devtool = isBuild ? "source-map" : "cheap-module-source-map";
738
1253
  if (void 0 !== options.devtool) item.devtool = options.devtool;
739
1254
  if (isServe) {
740
- const installed = (item.plugins ||= []).find((item)=>item instanceof core_.ProgressPlugin);
741
- if (!installed) (item.plugins ??= []).push(new core_.ProgressPlugin());
1255
+ const installed = (item.plugins ||= []).find((item)=>item instanceof rspackCore.Z.ProgressPlugin);
1256
+ if (!installed) (item.plugins ??= []).push(new rspackCore.Z.ProgressPlugin());
742
1257
  }
743
1258
  const cacheOptions = item.experiments?.cache;
744
1259
  if ("object" == typeof cacheOptions && "persistent" === cacheOptions.type) {
@@ -774,7 +1289,7 @@ class RspackCLI {
774
1289
  };
775
1290
  let { loadedConfig, configPath } = config;
776
1291
  if ("function" == typeof loadedConfig) {
777
- let functionResult = loadedConfig(options.argv?.env, options.argv);
1292
+ let functionResult = loadedConfig(options.env, options);
778
1293
  if ("function" == typeof functionResult.then) functionResult = await functionResult;
779
1294
  loadedConfig = functionResult;
780
1295
  }