@rspack/cli 1.0.13 → 1.1.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs ADDED
@@ -0,0 +1,829 @@
1
+ import * as __WEBPACK_EXTERNAL_MODULE__rspack_core__ from "@rspack/core";
2
+ import * as __WEBPACK_EXTERNAL_MODULE_node_fs__ from "node:fs";
3
+ import * as __WEBPACK_EXTERNAL_MODULE_node_inspector__ from "node:inspector";
4
+ import * as __WEBPACK_EXTERNAL_MODULE_node_path__ from "node:path";
5
+ import * as __WEBPACK_EXTERNAL_MODULE_node_url__ from "node:url";
6
+ import * as __WEBPACK_EXTERNAL_MODULE_node_util__ from "node:util";
7
+ import * as __WEBPACK_EXTERNAL_MODULE_colorette__ from "colorette";
8
+ import * as __WEBPACK_EXTERNAL_MODULE_semver__ from "semver";
9
+ import * as __WEBPACK_EXTERNAL_MODULE_yargs__ from "yargs";
10
+ import * as __WEBPACK_EXTERNAL_MODULE_yargs_helpers__ from "yargs/helpers";
11
+ import * as __WEBPACK_EXTERNAL_MODULE_interpret__ from "interpret";
12
+ import * as __WEBPACK_EXTERNAL_MODULE_rechoir__ from "rechoir";
13
+ var __webpack_modules__ = {
14
+ "./src/utils/crossImport.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
15
+ __webpack_require__.d(__webpack_exports__, {
16
+ Z: function() {
17
+ return __WEBPACK_DEFAULT_EXPORT__;
18
+ },
19
+ y: function() {
20
+ return dynamicImport;
21
+ }
22
+ });
23
+ /* harmony import */ var node_url__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__("node:url");
24
+ /* harmony import */ var _isEsmFile__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__("./src/utils/isEsmFile.ts");
25
+ /**
26
+ * Dynamically import files. It will make sure it's not being compiled away by TS/Rslib.
27
+ */ const dynamicImport = new Function("path", "return import(path)");
28
+ const crossImport = async function(path) {
29
+ let cwd = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : process.cwd();
30
+ if ((0, _isEsmFile__WEBPACK_IMPORTED_MODULE_1__ /* ["default"] */ .Z)(path, cwd)) {
31
+ const url = (0, node_url__WEBPACK_IMPORTED_MODULE_0__.pathToFileURL)(path).href;
32
+ const { default: config } = await dynamicImport(url);
33
+ return config;
34
+ }
35
+ let result = require(path);
36
+ // compatible with export default config in common ts config
37
+ if (result && "object" == typeof result && "default" in result) result = result.default || {};
38
+ return result;
39
+ };
40
+ /* harmony default export */ const __WEBPACK_DEFAULT_EXPORT__ = crossImport;
41
+ },
42
+ "./src/utils/isEsmFile.ts": function(__unused_webpack_module, __webpack_exports__, __webpack_require__) {
43
+ // EXPORTS
44
+ __webpack_require__.d(__webpack_exports__, {
45
+ Z: ()=>/* binding */ isEsmFile
46
+ });
47
+ // EXTERNAL MODULE: external "node:path"
48
+ var external_node_path_ = __webpack_require__("node:path");
49
+ // EXTERNAL MODULE: external "node:fs"
50
+ var external_node_fs_ = __webpack_require__("node:fs");
51
+ const readPackageUp_readPackageUp = function() {
52
+ let cwd = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : process.cwd();
53
+ let currentDir = external_node_path_["default"].resolve(cwd);
54
+ let packageJsonPath = external_node_path_["default"].join(currentDir, "package.json");
55
+ while(!external_node_fs_["default"].existsSync(packageJsonPath)){
56
+ const parentDir = external_node_path_["default"].dirname(currentDir);
57
+ if (parentDir === currentDir) return null;
58
+ currentDir = parentDir;
59
+ packageJsonPath = external_node_path_["default"].join(currentDir, "package.json");
60
+ }
61
+ try {
62
+ return JSON.parse(external_node_fs_["default"].readFileSync(packageJsonPath, "utf8"));
63
+ } catch (error) {
64
+ return null;
65
+ }
66
+ };
67
+ /* harmony default export */ const readPackageUp = readPackageUp_readPackageUp;
68
+ const isEsmFile_isEsmFile = function(filePath) {
69
+ let cwd = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : process.cwd();
70
+ const ext = external_node_path_["default"].extname(filePath);
71
+ if (/\.(mjs|mts)$/.test(ext)) return true;
72
+ if (/\.(cjs|cts)/.test(ext)) return false;
73
+ const packageJson = readPackageUp(cwd);
74
+ return (null == packageJson ? void 0 : packageJson.type) === "module";
75
+ };
76
+ /* harmony default export */ const isEsmFile = isEsmFile_isEsmFile;
77
+ },
78
+ "@rspack/core": function(module) {
79
+ module.exports = __WEBPACK_EXTERNAL_MODULE__rspack_core__;
80
+ },
81
+ "node:fs": function(module) {
82
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_fs__;
83
+ },
84
+ "node:inspector": function(module) {
85
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_inspector__;
86
+ },
87
+ "node:path": function(module) {
88
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_path__;
89
+ },
90
+ "node:url": function(module) {
91
+ module.exports = __WEBPACK_EXTERNAL_MODULE_node_url__;
92
+ }
93
+ };
94
+ /************************************************************************/ // The module cache
95
+ var __webpack_module_cache__ = {};
96
+ // The require function
97
+ function __webpack_require__(moduleId) {
98
+ // Check if module is in cache
99
+ var cachedModule = __webpack_module_cache__[moduleId];
100
+ if (void 0 !== cachedModule) return cachedModule.exports;
101
+ // Create a new module (and put it into the cache)
102
+ var module = __webpack_module_cache__[moduleId] = {
103
+ exports: {}
104
+ };
105
+ // Execute the module function
106
+ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
107
+ // Return the exports of the module
108
+ return module.exports;
109
+ }
110
+ // expose the modules object (__webpack_modules__)
111
+ __webpack_require__.m = __webpack_modules__;
112
+ /************************************************************************/ // webpack/runtime/define_property_getters
113
+ (()=>{
114
+ __webpack_require__.d = function(exports, definition) {
115
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) Object.defineProperty(exports, key, {
116
+ enumerable: true,
117
+ get: definition[key]
118
+ });
119
+ };
120
+ })();
121
+ // webpack/runtime/ensure_chunk
122
+ (()=>{
123
+ __webpack_require__.f = {};
124
+ // This file contains only the entry chunk.
125
+ // The chunk loading function for additional chunks
126
+ __webpack_require__.e = function(chunkId) {
127
+ return Promise.all(Object.keys(__webpack_require__.f).reduce(function(promises, key) {
128
+ __webpack_require__.f[key](chunkId, promises);
129
+ return promises;
130
+ }, []));
131
+ };
132
+ })();
133
+ // webpack/runtime/get javascript chunk filename
134
+ (()=>{
135
+ // This function allow to reference chunks
136
+ __webpack_require__.u = function(chunkId) {
137
+ // return url for filenames not based on template
138
+ // return url for filenames based on template
139
+ return "" + chunkId + ".mjs";
140
+ };
141
+ })();
142
+ // webpack/runtime/has_own_property
143
+ (()=>{
144
+ __webpack_require__.o = function(obj, prop) {
145
+ return Object.prototype.hasOwnProperty.call(obj, prop);
146
+ };
147
+ })();
148
+ // webpack/runtime/module_chunk_loading
149
+ (()=>{
150
+ // object to store loaded and loading chunks
151
+ // undefined = chunk not loaded, null = chunk preloaded/prefetched
152
+ // [resolve, reject, Promise] = chunk loading, 0 = chunk loaded
153
+ var installedChunks = {
154
+ 980: 0
155
+ };
156
+ var installChunk = function(data) {
157
+ var ids = data.ids;
158
+ var modules = data.modules;
159
+ var runtime = data.runtime;
160
+ // add "modules" to the modules object,
161
+ // then flag all "ids" as loaded and fire callback
162
+ var moduleId, chunkId, i = 0;
163
+ for(moduleId in modules)if (__webpack_require__.o(modules, moduleId)) __webpack_require__.m[moduleId] = modules[moduleId];
164
+ if (runtime) runtime(__webpack_require__);
165
+ for(; i < ids.length; i++){
166
+ chunkId = ids[i];
167
+ if (__webpack_require__.o(installedChunks, chunkId) && installedChunks[chunkId]) installedChunks[chunkId][0]();
168
+ installedChunks[ids[i]] = 0;
169
+ }
170
+ };
171
+ __webpack_require__.f.j = function(chunkId, promises) {
172
+ // import() chunk loading for javascript
173
+ var installedChunkData = __webpack_require__.o(installedChunks, chunkId) ? installedChunks[chunkId] : void 0;
174
+ if (0 !== installedChunkData) {
175
+ // a Promise means "currently loading".
176
+ if (installedChunkData) promises.push(installedChunkData[1]);
177
+ else {
178
+ // setup Promise in chunk cache
179
+ var promise = import("./" + __webpack_require__.u(chunkId)).then(installChunk, function(e) {
180
+ if (0 !== installedChunks[chunkId]) installedChunks[chunkId] = void 0;
181
+ throw e;
182
+ });
183
+ var promise = Promise.race([
184
+ promise,
185
+ new Promise(function(resolve) {
186
+ installedChunkData = installedChunks[chunkId] = [
187
+ resolve
188
+ ];
189
+ })
190
+ ]);
191
+ promises.push(installedChunkData[1] = promise);
192
+ }
193
+ }
194
+ };
195
+ })();
196
+ // EXTERNAL MODULE: external "node:path"
197
+ var external_node_path_ = __webpack_require__("node:path");
198
+ // EXTERNAL MODULE: external "@rspack/core"
199
+ var core_ = __webpack_require__("@rspack/core");
200
+ // EXTERNAL MODULE: external "node:fs"
201
+ var external_node_fs_ = __webpack_require__("node:fs");
202
+ const commonOptions = (yargs)=>yargs.options({
203
+ config: {
204
+ g: true,
205
+ type: "string",
206
+ describe: "config file",
207
+ alias: "c"
208
+ },
209
+ entry: {
210
+ type: "array",
211
+ string: true,
212
+ describe: "entry file"
213
+ },
214
+ "output-path": {
215
+ type: "string",
216
+ describe: "output path dir",
217
+ alias: "o"
218
+ },
219
+ mode: {
220
+ type: "string",
221
+ describe: "mode",
222
+ alias: "m"
223
+ },
224
+ watch: {
225
+ type: "boolean",
226
+ default: false,
227
+ describe: "watch",
228
+ alias: "w"
229
+ },
230
+ env: {
231
+ type: "array",
232
+ string: true,
233
+ describe: "env passed to config function"
234
+ },
235
+ "node-env": {
236
+ string: true,
237
+ describe: "sets process.env.NODE_ENV to be specified value"
238
+ },
239
+ devtool: {
240
+ type: "boolean",
241
+ default: false,
242
+ describe: "devtool",
243
+ alias: "d"
244
+ },
245
+ configName: {
246
+ type: "array",
247
+ string: true,
248
+ describe: "Name of the configuration to use."
249
+ }
250
+ }).alias({
251
+ v: "version",
252
+ h: "help"
253
+ });
254
+ const previewOptions = (yargs)=>yargs.positional("dir", {
255
+ type: "string",
256
+ describe: "directory want to preview"
257
+ }).options({
258
+ publicPath: {
259
+ type: "string",
260
+ describe: "static resource server path"
261
+ },
262
+ config: {
263
+ g: true,
264
+ type: "string",
265
+ describe: "config file",
266
+ alias: "c"
267
+ },
268
+ port: {
269
+ type: "number",
270
+ describe: "preview server port"
271
+ },
272
+ host: {
273
+ type: "string",
274
+ describe: "preview server host"
275
+ },
276
+ open: {
277
+ type: "boolean",
278
+ describe: "open browser"
279
+ },
280
+ // same as devServer.server
281
+ server: {
282
+ type: "string",
283
+ describe: "Configuration items for the server."
284
+ },
285
+ configName: {
286
+ type: "array",
287
+ string: true,
288
+ describe: "Name of the configuration to use."
289
+ }
290
+ });
291
+ function normalizeEnv(argv) {
292
+ function parseValue(previous, value) {
293
+ const [allKeys, val] = value.split(/=(.+)/, 2);
294
+ const splitKeys = allKeys.split(/\.(?!$)/);
295
+ let prevRef = previous;
296
+ splitKeys.forEach((key, index)=>{
297
+ let someKey = key;
298
+ // https://github.com/webpack/webpack-cli/issues/3284
299
+ if (someKey.endsWith("=")) {
300
+ // remove '=' from key
301
+ someKey = someKey.slice(0, -1);
302
+ prevRef[someKey] = void 0;
303
+ return;
304
+ }
305
+ if (!prevRef[someKey] || "string" == typeof prevRef[someKey]) prevRef[someKey] = {};
306
+ if (index === splitKeys.length - 1) {
307
+ if ("string" == typeof val) prevRef[someKey] = val;
308
+ else prevRef[someKey] = true;
309
+ }
310
+ prevRef = prevRef[someKey];
311
+ });
312
+ return previous;
313
+ }
314
+ const envObj = (argv.env ?? []).reduce(parseValue, {});
315
+ argv.env = envObj;
316
+ }
317
+ /**
318
+ * set builtin env from cli - like `WEBPACK_BUNDLE=true`. also for `RSPACK_` prefixed.
319
+ * @param env the `argv.env` object
320
+ * @param envNameSuffix the added env will be `WEBPACK_${envNameSuffix}` and `RSPACK_${envNameSuffix}`
321
+ * @param value
322
+ */ function setBuiltinEnvArg(env, envNameSuffix, value) {
323
+ const envNames = [
324
+ // TODO: breaking change
325
+ // `WEBPACK_${envNameSuffix}`,
326
+ `RSPACK_${envNameSuffix}`
327
+ ];
328
+ for (const envName of envNames){
329
+ if (!(envName in env)) env[envName] = value;
330
+ }
331
+ }
332
+ /**
333
+ * infer `argv.env` as an object for it was transformed from array to object after `normalizeEnv` middleware
334
+ * @returns the reference of `argv.env` object
335
+ */ function ensureEnvObject(options) {
336
+ if (Array.isArray(options.env)) // in case that cli haven't got `normalizeEnv` middleware applied
337
+ normalizeEnv(options);
338
+ options.env = options.env || {};
339
+ return options.env;
340
+ }
341
+ class BuildCommand {
342
+ async apply(cli) {
343
+ cli.program.command([
344
+ "build",
345
+ "$0",
346
+ "bundle",
347
+ "b"
348
+ ], "run the rspack build", (yargs)=>commonOptions(yargs).options({
349
+ analyze: {
350
+ type: "boolean",
351
+ default: false,
352
+ describe: "analyze"
353
+ },
354
+ json: {
355
+ describe: "emit stats json"
356
+ },
357
+ profile: {
358
+ type: "boolean",
359
+ default: false,
360
+ describe: "capture timing information for each module"
361
+ }
362
+ }), async (options)=>{
363
+ const env = ensureEnvObject(options);
364
+ if (options.watch) setBuiltinEnvArg(env, "WATCH", true);
365
+ else {
366
+ setBuiltinEnvArg(env, "BUNDLE", true);
367
+ setBuiltinEnvArg(env, "BUILD", true);
368
+ }
369
+ const logger = cli.getLogger();
370
+ let createJsonStringifyStream;
371
+ if (options.json) {
372
+ const jsonExt = await import("@discoveryjs/json-ext");
373
+ createJsonStringifyStream = jsonExt.default.stringifyStream;
374
+ }
375
+ const errorHandler = (error, stats)=>{
376
+ if (error) {
377
+ logger.error(error);
378
+ process.exit(2);
379
+ }
380
+ if (null == stats ? void 0 : stats.hasErrors()) process.exitCode = 1;
381
+ if (!compiler || !stats) return;
382
+ const statsOptions = cli.isMultipleCompiler(compiler) ? {
383
+ children: compiler.compilers.map((compiler)=>compiler.options ? compiler.options.stats : void 0)
384
+ } : compiler.options ? compiler.options.stats : void 0;
385
+ if (options.json && createJsonStringifyStream) {
386
+ const handleWriteError = (error)=>{
387
+ logger.error(error);
388
+ process.exit(2);
389
+ };
390
+ if (true === options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on("error", handleWriteError).pipe(process.stdout).on("error", handleWriteError).on("close", ()=>process.stdout.write("\n"));
391
+ else if ("string" == typeof options.json) createJsonStringifyStream(stats.toJson(statsOptions)).on("error", handleWriteError).pipe(external_node_fs_.createWriteStream(options.json)).on("error", handleWriteError) // Use stderr to logging
392
+ .on("close", ()=>{
393
+ process.stderr.write(`[rspack-cli] ${cli.colors.green(`stats are successfully stored as json to ${options.json}`)}\n`);
394
+ });
395
+ } else {
396
+ const printedStats = stats.toString(statsOptions);
397
+ // Avoid extra empty line when `stats: 'none'`
398
+ if (printedStats) logger.raw(printedStats);
399
+ }
400
+ };
401
+ const rspackOptions = {
402
+ ...options,
403
+ argv: {
404
+ ...options
405
+ }
406
+ };
407
+ const compiler = await cli.createCompiler(rspackOptions, "build", errorHandler);
408
+ if (!compiler || cli.isWatch(compiler)) return;
409
+ compiler.run((error, stats)=>{
410
+ // If there is a compilation error, the close method should not be called,
411
+ // Otherwise Rspack may generate invalid caches.
412
+ if (error || (null == stats ? void 0 : stats.hasErrors())) errorHandler(error, stats);
413
+ else compiler.close((closeErr)=>{
414
+ if (closeErr) logger.error(closeErr);
415
+ errorHandler(error, stats);
416
+ });
417
+ });
418
+ });
419
+ }
420
+ }
421
+ const defaultRoot = "dist";
422
+ class PreviewCommand {
423
+ async apply(cli) {
424
+ cli.program.command([
425
+ "preview [dir]",
426
+ "preview",
427
+ "p"
428
+ ], "run the rspack server for build output", previewOptions, async (options)=>{
429
+ // config、configName are necessary for loadConfig
430
+ const rspackOptions = {
431
+ config: options.config,
432
+ configName: options.configName,
433
+ argv: {
434
+ ...options
435
+ }
436
+ };
437
+ const { RspackDevServer } = await import("@rspack/dev-server");
438
+ let config = await cli.loadConfig(rspackOptions);
439
+ config = await getPreviewConfig(config, options);
440
+ if (!Array.isArray(config)) config = [
441
+ config
442
+ ];
443
+ // find the possible devServer config
444
+ config = config.find((item)=>item.devServer) || config[0];
445
+ const devServerOptions = config.devServer;
446
+ try {
447
+ const compiler = (0, core_.rspack)({
448
+ entry: {}
449
+ });
450
+ if (!compiler) return;
451
+ const server = new RspackDevServer(devServerOptions, compiler);
452
+ await server.start();
453
+ } catch (error) {
454
+ const logger = cli.getLogger();
455
+ logger.error(error);
456
+ process.exit(2);
457
+ }
458
+ });
459
+ }
460
+ }
461
+ // get the devServerOptions from the config
462
+ async function getPreviewConfig(item, options) {
463
+ const internalPreviewConfig = async (item)=>{
464
+ var _item_output, _item_devServer, _item_devServer1, _item_devServer2, _item_devServer3, _item_devServer4;
465
+ // all of the options that a preview static server needs(maybe not all)
466
+ item.devServer = {
467
+ static: {
468
+ directory: options.dir ? external_node_path_["default"].join(item.context ?? process.cwd(), options.dir) : (null === (_item_output = item.output) || void 0 === _item_output ? void 0 : _item_output.path) ?? external_node_path_["default"].join(item.context ?? process.cwd(), defaultRoot),
469
+ publicPath: options.publicPath ?? "/"
470
+ },
471
+ port: options.port ?? 8080,
472
+ proxy: null === (_item_devServer = item.devServer) || void 0 === _item_devServer ? void 0 : _item_devServer.proxy,
473
+ host: options.host ?? (null === (_item_devServer1 = item.devServer) || void 0 === _item_devServer1 ? void 0 : _item_devServer1.host),
474
+ open: options.open ?? (null === (_item_devServer2 = item.devServer) || void 0 === _item_devServer2 ? void 0 : _item_devServer2.open),
475
+ server: options.server ?? (null === (_item_devServer3 = item.devServer) || void 0 === _item_devServer3 ? void 0 : _item_devServer3.server),
476
+ historyApiFallback: null === (_item_devServer4 = item.devServer) || void 0 === _item_devServer4 ? void 0 : _item_devServer4.historyApiFallback
477
+ };
478
+ return item;
479
+ };
480
+ if (Array.isArray(item)) return Promise.all(item.map(internalPreviewConfig));
481
+ return internalPreviewConfig(item);
482
+ }
483
+ class ServeCommand {
484
+ async apply(cli) {
485
+ cli.program.command([
486
+ "serve",
487
+ "server",
488
+ "s",
489
+ "dev"
490
+ ], "run the rspack dev server.", (yargs)=>commonOptions(yargs).options({
491
+ hot: {
492
+ coerce: (arg)=>{
493
+ if ("boolean" == typeof arg || "only" === arg) return arg;
494
+ if ("false" === arg) return false;
495
+ return true;
496
+ },
497
+ describe: "enables hot module replacement"
498
+ },
499
+ port: {
500
+ type: "number",
501
+ coerce: (arg)=>Number.isInteger(arg) ? arg : void 0,
502
+ describe: "allows to specify a port to use"
503
+ },
504
+ host: {
505
+ type: "string",
506
+ describe: "allows to specify a hostname to use"
507
+ }
508
+ }), async (options)=>{
509
+ setBuiltinEnvArg(ensureEnvObject(options), "SERVE", true);
510
+ const rspackOptions = {
511
+ ...options,
512
+ argv: {
513
+ ...options
514
+ }
515
+ };
516
+ /**
517
+ * webpack-dev-server will set `process.env.WEBPACK_SERVE` to true
518
+ * when its module is imported, so we have to lazy load the package
519
+ * to make sure the envvar is not set on build mode.
520
+ * when run in serve mode, we have to load the package before config
521
+ * module is imported so that the envvar `process.env.WEBPACK_SERVE`
522
+ * got in config module could be `true`.
523
+ * related issue: https://github.com/web-infra-dev/rspack/issues/6359
524
+ */ const { RspackDevServer } = await import("@rspack/dev-server");
525
+ const compiler = await cli.createCompiler(rspackOptions, "serve");
526
+ if (!compiler) return;
527
+ const compilers = cli.isMultipleCompiler(compiler) ? compiler.compilers : [
528
+ compiler
529
+ ];
530
+ const possibleCompilers = compilers.filter((compiler)=>compiler.options.devServer);
531
+ const usedPorts = [];
532
+ const servers = [];
533
+ /**
534
+ * Webpack uses an Array of compilerForDevServer,
535
+ * however according to it's doc https://webpack.js.org/configuration/dev-server/#devserverhot
536
+ * It should use only the first one
537
+ *
538
+ * Choose the one for configure devServer
539
+ */ const compilerForDevServer = possibleCompilers.length > 0 ? possibleCompilers[0] : compilers[0];
540
+ /**
541
+ * Rspack relies on devServer.hot to enable HMR
542
+ */ for (const compiler of compilers){
543
+ const devServer = compiler.options.devServer ??= {};
544
+ devServer.hot = options.hot ?? devServer.hot ?? true;
545
+ if (false !== devServer.client) {
546
+ if (true === devServer.client || null == devServer.client) devServer.client = {};
547
+ devServer.client = {
548
+ overlay: {
549
+ errors: true,
550
+ warnings: false
551
+ },
552
+ ...devServer.client
553
+ };
554
+ }
555
+ }
556
+ const result = compilerForDevServer.options.devServer ??= {};
557
+ /**
558
+ * Enable this to tell Rspack that we need to enable React Refresh by default
559
+ */ result.hot = options.hot ?? result.hot ?? true;
560
+ result.host = options.host || result.host;
561
+ result.port = options.port || result.port;
562
+ if (false !== result.client) {
563
+ if (true === result.client || null == result.client) result.client = {};
564
+ result.client = {
565
+ overlay: {
566
+ errors: true,
567
+ warnings: false
568
+ },
569
+ ...result.client
570
+ };
571
+ }
572
+ const devServerOptions = result;
573
+ if (devServerOptions.port) {
574
+ const portNumber = Number(devServerOptions.port);
575
+ if (!Number.isNaN(portNumber)) {
576
+ 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.");
577
+ usedPorts.push(portNumber);
578
+ }
579
+ }
580
+ try {
581
+ const server = new RspackDevServer(devServerOptions, compiler);
582
+ await server.start();
583
+ servers.push(server);
584
+ } catch (error) {
585
+ const logger = cli.getLogger();
586
+ logger.error(error);
587
+ process.exit(2);
588
+ }
589
+ });
590
+ }
591
+ }
592
+ // EXTERNAL MODULE: ./src/utils/crossImport.ts
593
+ var crossImport = __webpack_require__("./src/utils/crossImport.ts");
594
+ const DEFAULT_EXTENSIONS = [
595
+ ".js",
596
+ ".ts",
597
+ ".mjs",
598
+ ".mts",
599
+ ".cjs",
600
+ ".cts"
601
+ ];
602
+ /**
603
+ * Takes a basePath like `webpack.config`, return `webpack.config.{ext}` if
604
+ * exists. returns undefined if none of them exists
605
+ */ const findConfig = (basePath)=>DEFAULT_EXTENSIONS.map((ext)=>basePath + ext).find(external_node_fs_["default"].existsSync);
606
+ /* harmony default export */ const utils_findConfig = findConfig;
607
+ // EXTERNAL MODULE: ./src/utils/isEsmFile.ts + 1 modules
608
+ var isEsmFile = __webpack_require__("./src/utils/isEsmFile.ts");
609
+ const isTsFile = (configPath)=>{
610
+ const ext = external_node_path_["default"].extname(configPath);
611
+ return /\.(c|m)?ts$/.test(ext);
612
+ };
613
+ /* harmony default export */ const utils_isTsFile = isTsFile;
614
+ const loadConfig_DEFAULT_CONFIG_NAME = "rspack.config";
615
+ const registerLoader = (configPath)=>{
616
+ const ext = external_node_path_["default"].extname(configPath);
617
+ // TODO implement good `.mts` support after https://github.com/gulpjs/rechoir/issues/43
618
+ // For ESM and `.mts` you need to use: 'NODE_OPTIONS="--loader ts-node/esm" rspack build --config ./rspack.config.mts'
619
+ if ((0, isEsmFile /* default */ .Z)(configPath) && utils_isTsFile(configPath)) return;
620
+ const extensions = Object.fromEntries(Object.entries(__WEBPACK_EXTERNAL_MODULE_interpret__["default"].extensions).filter((param)=>{
621
+ let [key] = param;
622
+ return key === ext;
623
+ }));
624
+ if (0 === Object.keys(extensions).length) throw new Error(`config file "${configPath}" is not supported.`);
625
+ try {
626
+ __WEBPACK_EXTERNAL_MODULE_rechoir__["default"].prepare(extensions, configPath);
627
+ } catch (error) {
628
+ const failures = null == error ? void 0 : error.failures;
629
+ if (failures) {
630
+ const messages = failures.map((failure)=>failure.error.message);
631
+ throw new Error(`${messages.join("\n")}`);
632
+ }
633
+ throw error;
634
+ }
635
+ };
636
+ async function loadRspackConfig(options) {
637
+ let cwd = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : process.cwd();
638
+ if (options.config) {
639
+ const configPath = external_node_path_["default"].resolve(cwd, options.config);
640
+ if (!external_node_fs_["default"].existsSync(configPath)) throw new Error(`config file "${configPath}" not found.`);
641
+ utils_isTsFile(configPath) && registerLoader(configPath);
642
+ return (0, crossImport /* default */ .Z)(configPath, cwd);
643
+ }
644
+ const defaultConfig = utils_findConfig(external_node_path_["default"].resolve(cwd, loadConfig_DEFAULT_CONFIG_NAME));
645
+ if (defaultConfig) {
646
+ utils_isTsFile(defaultConfig) && registerLoader(defaultConfig);
647
+ return (0, crossImport /* default */ .Z)(defaultConfig, cwd);
648
+ }
649
+ return {};
650
+ }
651
+ function _define_property(obj, key, value) {
652
+ if (key in obj) Object.defineProperty(obj, key, {
653
+ value: value,
654
+ enumerable: true,
655
+ configurable: true,
656
+ writable: true
657
+ });
658
+ else obj[key] = value;
659
+ return obj;
660
+ }
661
+ class RspackCLI {
662
+ async createCompiler(options, rspackCommand, callback) {
663
+ var _process_env, _process;
664
+ process.env.RSPACK_CONFIG_VALIDATE ??= "loose";
665
+ process.env.WATCHPACK_WATCHER_LIMIT = process.env.WATCHPACK_WATCHER_LIMIT || "20";
666
+ const nodeEnv = null === (_process = process) || void 0 === _process ? void 0 : null === (_process_env = _process.env) || void 0 === _process_env ? void 0 : _process_env.NODE_ENV;
667
+ const rspackCommandDefaultEnv = "build" === rspackCommand ? "production" : "development";
668
+ if ("string" == typeof options.nodeEnv) process.env.NODE_ENV = nodeEnv || options.nodeEnv;
669
+ else process.env.NODE_ENV = nodeEnv || rspackCommandDefaultEnv;
670
+ let config = await this.loadConfig(options);
671
+ config = await this.buildConfig(config, options, rspackCommand);
672
+ const isWatch = Array.isArray(config) ? config.some((i)=>i.watch) : config.watch;
673
+ let compiler;
674
+ try {
675
+ compiler = (0, core_.rspack)(config, isWatch ? callback : void 0);
676
+ } catch (e) {
677
+ // Aligned with webpack-cli
678
+ // See: https://github.com/webpack/webpack-cli/blob/eea6adf7d34dfbfd3b5b784ece4a4664834f5a6a/packages/webpack-cli/src/webpack-cli.ts#L2394
679
+ if (e instanceof core_.ValidationError) {
680
+ this.getLogger().error(e.message);
681
+ process.exit(2);
682
+ } else if (e instanceof Error) {
683
+ if ("function" == typeof callback) callback(e);
684
+ else this.getLogger().error(e);
685
+ return null;
686
+ }
687
+ throw e;
688
+ }
689
+ return compiler;
690
+ }
691
+ createColors(useColor) {
692
+ const shouldUseColor = useColor || __WEBPACK_EXTERNAL_MODULE_colorette__.isColorSupported;
693
+ return {
694
+ ...(0, __WEBPACK_EXTERNAL_MODULE_colorette__.createColors)({
695
+ useColor: shouldUseColor
696
+ }),
697
+ isColorSupported: shouldUseColor
698
+ };
699
+ }
700
+ getLogger() {
701
+ return {
702
+ error: (val)=>console.error(`[rspack-cli] ${this.colors.red(__WEBPACK_EXTERNAL_MODULE_node_util__["default"].format(val))}`),
703
+ warn: (val)=>console.warn(`[rspack-cli] ${this.colors.yellow(val)}`),
704
+ info: (val)=>console.info(`[rspack-cli] ${this.colors.cyan(val)}`),
705
+ success: (val)=>console.log(`[rspack-cli] ${this.colors.green(val)}`),
706
+ log: (val)=>console.log(`[rspack-cli] ${val}`),
707
+ raw: (val)=>console.log(val)
708
+ };
709
+ }
710
+ async run(argv) {
711
+ if (__WEBPACK_EXTERNAL_MODULE_semver__["default"].lt(__WEBPACK_EXTERNAL_MODULE_semver__["default"].clean(process.version), "14.0.0")) this.getLogger().warn(`Minimum recommended Node.js version is 14.0.0, current version is ${process.version}`);
712
+ this.program.showHelpOnFail(false);
713
+ this.program.usage("[options]");
714
+ this.program.scriptName("rspack");
715
+ this.program.strictCommands(true).strict(true);
716
+ this.program.middleware(normalizeEnv);
717
+ this.registerCommands();
718
+ await this.program.parseAsync((0, __WEBPACK_EXTERNAL_MODULE_yargs_helpers__.hideBin)(argv));
719
+ }
720
+ async registerCommands() {
721
+ const builtinCommands = [
722
+ new BuildCommand(),
723
+ new ServeCommand(),
724
+ new PreviewCommand()
725
+ ];
726
+ for (const command of builtinCommands)command.apply(this);
727
+ }
728
+ async buildConfig(item, options, command) {
729
+ const isBuild = "build" === command;
730
+ const isServe = "serve" === command;
731
+ const commandDefaultEnv = isBuild ? "production" : "development";
732
+ const internalBuildConfig = async (item)=>{
733
+ if (options.entry) item.entry = {
734
+ main: options.entry.map((x)=>external_node_path_["default"].resolve(process.cwd(), x))[0] // Fix me when entry supports array
735
+ };
736
+ // to set output.path
737
+ item.output = item.output || {};
738
+ if (options["output-path"]) item.output.path = external_node_path_["default"].resolve(process.cwd(), options["output-path"]);
739
+ if (options.analyze) {
740
+ const { BundleAnalyzerPlugin } = await import("webpack-bundle-analyzer");
741
+ (item.plugins ??= []).push({
742
+ name: "rspack-bundle-analyzer",
743
+ apply (compiler) {
744
+ new BundleAnalyzerPlugin({
745
+ generateStatsFile: true
746
+ }).apply(compiler);
747
+ }
748
+ });
749
+ }
750
+ if (options.profile) item.profile = true;
751
+ if (process.env.RSPACK_PROFILE) {
752
+ const { applyProfile } = await __webpack_require__.e(/* import() */ "629").then(__webpack_require__.bind(__webpack_require__, "./src/utils/profile.ts"));
753
+ await applyProfile(process.env.RSPACK_PROFILE, item);
754
+ }
755
+ // cli --watch overrides the watch config
756
+ if (options.watch) item.watch = options.watch;
757
+ // auto set default mode if user config don't set it
758
+ if (!item.mode) item.mode = commandDefaultEnv ?? "none";
759
+ // user parameters always has highest priority than default mode and config mode
760
+ if (options.mode) item.mode = options.mode;
761
+ // false is also a valid value for sourcemap, so don't override it
762
+ if (void 0 === item.devtool) item.devtool = isBuild ? "source-map" : "cheap-module-source-map";
763
+ if (isServe) {
764
+ const installed = (item.plugins ||= []).find((item)=>item instanceof core_.ProgressPlugin);
765
+ if (!installed) (item.plugins ??= []).push(new core_.ProgressPlugin());
766
+ }
767
+ if (void 0 === item.stats) item.stats = {
768
+ preset: "errors-warnings",
769
+ timings: true
770
+ };
771
+ else if ("boolean" == typeof item.stats) item.stats = item.stats ? {
772
+ preset: "normal"
773
+ } : {
774
+ preset: "none"
775
+ };
776
+ else if ("string" == typeof item.stats) item.stats = {
777
+ preset: item.stats
778
+ };
779
+ if (this.colors.isColorSupported && void 0 === item.stats.colors) item.stats.colors = true;
780
+ return item;
781
+ };
782
+ if (Array.isArray(item)) return Promise.all(item.map(internalBuildConfig));
783
+ return internalBuildConfig(item);
784
+ }
785
+ async loadConfig(options) {
786
+ let loadedConfig = await loadRspackConfig(options);
787
+ if (options.configName) {
788
+ const notFoundConfigNames = [];
789
+ loadedConfig = options.configName.map((configName)=>{
790
+ let found;
791
+ found = Array.isArray(loadedConfig) ? loadedConfig.find((options)=>options.name === configName) : loadedConfig.name === configName ? loadedConfig : void 0;
792
+ if (!found) notFoundConfigNames.push(configName);
793
+ // WARNING: if config is not found, the program will exit
794
+ // so assert here is okay to avoid runtime filtering
795
+ return found;
796
+ });
797
+ if (notFoundConfigNames.length > 0) {
798
+ this.getLogger().error(notFoundConfigNames.map((configName)=>`Configuration with the name "${configName}" was not found.`).join(" "));
799
+ process.exit(2);
800
+ }
801
+ }
802
+ if ("function" == typeof loadedConfig) {
803
+ var _options_argv;
804
+ loadedConfig = loadedConfig(null === (_options_argv = options.argv) || void 0 === _options_argv ? void 0 : _options_argv.env, options.argv);
805
+ // if return promise we should await its result
806
+ if ("function" == typeof loadedConfig.then) loadedConfig = await loadedConfig;
807
+ }
808
+ return loadedConfig;
809
+ }
810
+ isMultipleCompiler(compiler) {
811
+ return Boolean(compiler.compilers);
812
+ }
813
+ isWatch(compiler) {
814
+ return Boolean(this.isMultipleCompiler(compiler) ? compiler.compilers.some((compiler)=>compiler.options.watch) : compiler.options.watch);
815
+ }
816
+ constructor(){
817
+ _define_property(this, "colors", void 0);
818
+ _define_property(this, "program", void 0);
819
+ this.colors = this.createColors();
820
+ this.program = (0, __WEBPACK_EXTERNAL_MODULE_yargs__["default"])();
821
+ }
822
+ }
823
+ function defineConfig(config) {
824
+ return config;
825
+ }
826
+ function definePlugin(plugin) {
827
+ return plugin;
828
+ }
829
+ export { RspackCLI, defineConfig, definePlugin };