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