@rsbuild/core 1.4.11 → 1.4.13

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.
Files changed (35) hide show
  1. package/compiled/css-loader/index.js +18 -18
  2. package/compiled/html-rspack-plugin/index.js +14 -14
  3. package/compiled/launch-editor-middleware/index.js +32 -21
  4. package/compiled/launch-editor-middleware/package.json +1 -1
  5. package/compiled/postcss-load-config/index.js +10 -10
  6. package/compiled/postcss-loader/index.js +6 -6
  7. package/compiled/rsbuild-dev-middleware/index.js +25 -25
  8. package/compiled/rspack-chain/package.json +1 -1
  9. package/compiled/rspack-chain/types/index.d.ts +11 -0
  10. package/compiled/rspack-manifest-plugin/index.js +4 -4
  11. package/compiled/style-loader/index.js +10 -10
  12. package/dist/client/hmr.js +13 -2
  13. package/dist/client/overlay.js +3 -1
  14. package/dist/index.cjs +1322 -217
  15. package/dist/index.js +1304 -209
  16. package/dist/transformLoader.mjs +7 -5
  17. package/dist/transformRawLoader.mjs +7 -5
  18. package/dist-types/configChain.d.ts +1 -1
  19. package/dist-types/constants.d.ts +1 -0
  20. package/dist-types/helpers/index.d.ts +2 -2
  21. package/dist-types/helpers/stats.d.ts +1 -0
  22. package/dist-types/rspack-plugins/RsbuildHtmlPlugin.d.ts +1 -0
  23. package/dist-types/server/compilationMiddleware.d.ts +0 -4
  24. package/dist-types/server/devServer.d.ts +7 -2
  25. package/dist-types/server/historyApiFallback.d.ts +2 -0
  26. package/dist-types/server/socketServer.d.ts +24 -7
  27. package/dist-types/types/config.d.ts +20 -10
  28. package/dist-types/types/hooks.d.ts +1 -1
  29. package/dist-types/types/plugin.d.ts +1 -2
  30. package/package.json +9 -10
  31. package/compiled/connect-history-api-fallback/index.d.ts +0 -1
  32. package/compiled/connect-history-api-fallback/index.js +0 -149
  33. package/compiled/connect-history-api-fallback/license +0 -21
  34. package/compiled/connect-history-api-fallback/package.json +0 -1
  35. package/compiled/rspack-chain/index.js +0 -1769
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  /*! For license information please see index.js.LICENSE.txt */
2
- let swcHelpersPath, pluginHelper_htmlPlugin, cssExtractPlugin, isDockerCached, cachedResult;
2
+ let swcHelpersPath, pluginHelper_htmlPlugin, cssExtractPlugin, isDockerCached, cachedResult, hmrClientPath, overlayClientPath;
3
3
  import { createRequire } from "node:module";
4
4
  import { logger } from "../compiled/rslog/index.js";
5
5
  import node_path, { dirname, isAbsolute as external_node_path_isAbsolute, join, posix, relative, sep } from "node:path";
@@ -9,15 +9,13 @@ import node_fs, { constants as external_node_fs_constants, existsSync } from "no
9
9
  import { EventEmitter } from "events";
10
10
  import node_os, { constants as external_node_os_constants } from "node:os";
11
11
  import node_process from "node:process";
12
- import rspack_chain from "../compiled/rspack-chain/index.js";
13
12
  import { isPromise, isRegExp } from "node:util/types";
14
13
  import { promisify as external_node_util_promisify } from "node:util";
15
- import { lookup } from "../compiled/mrmime/index.js";
16
14
  import node_zlib from "node:zlib";
17
15
  import { Buffer as external_node_buffer_Buffer } from "node:buffer";
18
16
  import node_child_process, { execFile } from "node:child_process";
19
17
  import promises from "node:fs/promises";
20
- var EsmMode, __webpack_modules__ = {
18
+ var superClass, superClass1, EsmMode, __webpack_modules__ = {
21
19
  "../../node_modules/.pnpm/clone-deep@4.0.1/node_modules/clone-deep/index.js": function(module, __unused_webpack_exports, __webpack_require__) {
22
20
  let clone = __webpack_require__("../../node_modules/.pnpm/shallow-clone@3.0.1/node_modules/shallow-clone/index.js"), typeOf = __webpack_require__("../../node_modules/.pnpm/kind-of@6.0.3/node_modules/kind-of/index.js"), isPlainObject = __webpack_require__("../../node_modules/.pnpm/is-plain-object@2.0.4/node_modules/is-plain-object/index.js");
23
21
  module.exports = function cloneDeep(val, instanceClone) {
@@ -176,6 +174,298 @@ var EsmMode, __webpack_modules__ = {
176
174
  return null != val && 'object' == typeof val && !1 === Array.isArray(val);
177
175
  };
178
176
  },
177
+ "../../node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/array.js": function(__unused_webpack_module, exports) {
178
+ Object.defineProperty(exports, "__esModule", {
179
+ value: !0
180
+ }), exports.arrayToString = void 0, exports.arrayToString = (array, space, next)=>{
181
+ let values = array.map(function(value, index) {
182
+ let result = next(value, index);
183
+ return void 0 === result ? String(result) : space + result.split("\n").join(`\n${space}`);
184
+ }).join(space ? ",\n" : ","), eol = space && values ? "\n" : "";
185
+ return `[${eol}${values}${eol}]`;
186
+ };
187
+ },
188
+ "../../node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/function.js": function(__unused_webpack_module, exports, __webpack_require__) {
189
+ Object.defineProperty(exports, "__esModule", {
190
+ value: !0
191
+ }), exports.FunctionParser = exports.dedentFunction = exports.functionToString = exports.USED_METHOD_KEY = void 0;
192
+ let quote_1 = __webpack_require__("../../node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/quote.js"), METHOD_NAMES_ARE_QUOTED = '"' === ({
193
+ " " () {}
194
+ })[" "].toString().charAt(0), FUNCTION_PREFIXES = {
195
+ Function: "function ",
196
+ GeneratorFunction: "function* ",
197
+ AsyncFunction: "async function ",
198
+ AsyncGeneratorFunction: "async function* "
199
+ }, METHOD_PREFIXES = {
200
+ Function: "",
201
+ GeneratorFunction: "*",
202
+ AsyncFunction: "async ",
203
+ AsyncGeneratorFunction: "async *"
204
+ }, TOKENS_PRECEDING_REGEXPS = new Set("case delete else in instanceof new return throw typeof void , ; : + - ! ~ & | ^ * / % < > ? =".split(" "));
205
+ function dedentFunction(fnString) {
206
+ let found;
207
+ for (let line of fnString.split("\n").slice(1)){
208
+ let m = /^[\s\t]+/.exec(line);
209
+ if (!m) return fnString;
210
+ let [str] = m;
211
+ void 0 === found ? found = str : str.length < found.length && (found = str);
212
+ }
213
+ return found ? fnString.split(`\n${found}`).join("\n") : fnString;
214
+ }
215
+ exports.USED_METHOD_KEY = new WeakSet(), exports.functionToString = (fn, space, next, key)=>{
216
+ let name = "string" == typeof key ? key : void 0;
217
+ return void 0 !== name && exports.USED_METHOD_KEY.add(fn), new FunctionParser(fn, space, next, name).stringify();
218
+ }, exports.dedentFunction = dedentFunction;
219
+ class FunctionParser {
220
+ constructor(fn, indent, next, key){
221
+ this.fn = fn, this.indent = indent, this.next = next, this.key = key, this.pos = 0, this.hadKeyword = !1, this.fnString = Function.prototype.toString.call(fn), this.fnType = fn.constructor.name, this.keyQuote = void 0 === key ? "" : quote_1.quoteKey(key, next), this.keyPrefix = void 0 === key ? "" : `${this.keyQuote}:${indent ? " " : ""}`, this.isMethodCandidate = void 0 !== key && ("" === this.fn.name || this.fn.name === key);
222
+ }
223
+ stringify() {
224
+ let value = this.tryParse();
225
+ return value ? dedentFunction(value) : `${this.keyPrefix}void ${this.next(this.fnString)}`;
226
+ }
227
+ getPrefix() {
228
+ return this.isMethodCandidate && !this.hadKeyword ? METHOD_PREFIXES[this.fnType] + this.keyQuote : this.keyPrefix + FUNCTION_PREFIXES[this.fnType];
229
+ }
230
+ tryParse() {
231
+ if ("}" !== this.fnString[this.fnString.length - 1]) return this.keyPrefix + this.fnString;
232
+ if (this.fn.name) {
233
+ let result = this.tryStrippingName();
234
+ if (result) return result;
235
+ }
236
+ let prevPos = this.pos;
237
+ if ("class" === this.consumeSyntax()) return this.fnString;
238
+ if (this.pos = prevPos, this.tryParsePrefixTokens()) {
239
+ let result = this.tryStrippingName();
240
+ if (result) return result;
241
+ let offset = this.pos;
242
+ switch(this.consumeSyntax("WORD_LIKE")){
243
+ case "WORD_LIKE":
244
+ this.isMethodCandidate && !this.hadKeyword && (offset = this.pos);
245
+ case "()":
246
+ if ("=>" === this.fnString.substr(this.pos, 2)) return this.keyPrefix + this.fnString;
247
+ this.pos = offset;
248
+ case '"':
249
+ case "'":
250
+ case "[]":
251
+ return this.getPrefix() + this.fnString.substr(this.pos);
252
+ }
253
+ }
254
+ }
255
+ tryStrippingName() {
256
+ if (METHOD_NAMES_ARE_QUOTED) return;
257
+ let start = this.pos, prefix = this.fnString.substr(this.pos, this.fn.name.length);
258
+ if (prefix === this.fn.name && (this.pos += prefix.length, "()" === this.consumeSyntax() && "{}" === this.consumeSyntax() && this.pos === this.fnString.length)) return (this.isMethodCandidate || !quote_1.isValidVariableName(prefix)) && (start += prefix.length), this.getPrefix() + this.fnString.substr(start);
259
+ this.pos = start;
260
+ }
261
+ tryParsePrefixTokens() {
262
+ let posPrev = this.pos;
263
+ switch(this.hadKeyword = !1, this.fnType){
264
+ case "AsyncFunction":
265
+ if ("async" !== this.consumeSyntax()) return !1;
266
+ posPrev = this.pos;
267
+ case "Function":
268
+ return "function" === this.consumeSyntax() ? this.hadKeyword = !0 : this.pos = posPrev, !0;
269
+ case "AsyncGeneratorFunction":
270
+ if ("async" !== this.consumeSyntax()) return !1;
271
+ case "GeneratorFunction":
272
+ let token = this.consumeSyntax();
273
+ return "function" === token && (token = this.consumeSyntax(), this.hadKeyword = !0), "*" === token;
274
+ }
275
+ }
276
+ consumeSyntax(wordLikeToken) {
277
+ let m = this.consumeMatch(/^(?:([A-Za-z_0-9$\xA0-\uFFFF]+)|=>|\+\+|\-\-|.)/);
278
+ if (!m) return;
279
+ let [token, match] = m;
280
+ if (this.consumeWhitespace(), match) return wordLikeToken || match;
281
+ switch(token){
282
+ case "(":
283
+ return this.consumeSyntaxUntil("(", ")");
284
+ case "[":
285
+ return this.consumeSyntaxUntil("[", "]");
286
+ case "{":
287
+ return this.consumeSyntaxUntil("{", "}");
288
+ case "`":
289
+ return this.consumeTemplate();
290
+ case '"':
291
+ return this.consumeRegExp(/^(?:[^\\"]|\\.)*"/, '"');
292
+ case "'":
293
+ return this.consumeRegExp(/^(?:[^\\']|\\.)*'/, "'");
294
+ }
295
+ return token;
296
+ }
297
+ consumeSyntaxUntil(startToken, endToken) {
298
+ let isRegExpAllowed = !0;
299
+ for(;;){
300
+ let token = this.consumeSyntax();
301
+ if (token === endToken) return startToken + endToken;
302
+ if (!token || ")" === token || "]" === token || "}" === token) return;
303
+ "/" === token && isRegExpAllowed && this.consumeMatch(/^(?:\\.|[^\\\/\n[]|\[(?:\\.|[^\]])*\])+\/[a-z]*/) ? (isRegExpAllowed = !1, this.consumeWhitespace()) : isRegExpAllowed = TOKENS_PRECEDING_REGEXPS.has(token);
304
+ }
305
+ }
306
+ consumeMatch(re) {
307
+ let m = re.exec(this.fnString.substr(this.pos));
308
+ return m && (this.pos += m[0].length), m;
309
+ }
310
+ consumeRegExp(re, token) {
311
+ let m = re.exec(this.fnString.substr(this.pos));
312
+ if (m) return this.pos += m[0].length, this.consumeWhitespace(), token;
313
+ }
314
+ consumeTemplate() {
315
+ for(;;){
316
+ if (this.consumeMatch(/^(?:[^`$\\]|\\.|\$(?!{))*/), "`" === this.fnString[this.pos]) return this.pos++, this.consumeWhitespace(), "`";
317
+ if (!("${" === this.fnString.substr(this.pos, 2) && (this.pos += 2, this.consumeWhitespace(), this.consumeSyntaxUntil("{", "}")))) return;
318
+ }
319
+ }
320
+ consumeWhitespace() {
321
+ this.consumeMatch(/^(?:\s|\/\/.*|\/\*[^]*?\*\/)*/);
322
+ }
323
+ }
324
+ exports.FunctionParser = FunctionParser;
325
+ },
326
+ "../../node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/index.js": function(__unused_webpack_module, exports, __webpack_require__) {
327
+ exports.stringify = void 0;
328
+ let stringify_1 = __webpack_require__("../../node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/stringify.js"), quote_1 = __webpack_require__("../../node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/quote.js"), ROOT_SENTINEL = Symbol("root");
329
+ exports.stringify = function(value, replacer, indent, options = {}) {
330
+ var replacer1;
331
+ let space = "string" == typeof indent ? indent : " ".repeat(indent || 0), path = [], stack = new Set(), tracking = new Map(), unpack = new Map(), valueCount = 0, { maxDepth = 100, references = !1, skipUndefinedProperties = !1, maxValues = 100000 } = options, valueToString = (replacer1 = replacer) ? (value, space, next, key)=>replacer1(value, space, (value)=>stringify_1.toString(value, space, next, key), key) : stringify_1.toString, onNext = (value, key)=>{
332
+ if (++valueCount > maxValues || skipUndefinedProperties && void 0 === value || path.length > maxDepth) return;
333
+ if (void 0 === key) return valueToString(value, space, onNext, key);
334
+ path.push(key);
335
+ let result = builder(value, key === ROOT_SENTINEL ? void 0 : key);
336
+ return path.pop(), result;
337
+ }, builder = references ? (value, key)=>{
338
+ if (null !== value && ("object" == typeof value || "function" == typeof value || "symbol" == typeof value)) {
339
+ if (tracking.has(value)) return unpack.set(path.slice(1), tracking.get(value)), valueToString(void 0, space, onNext, key);
340
+ tracking.set(value, path.slice(1));
341
+ }
342
+ return valueToString(value, space, onNext, key);
343
+ } : (value, key)=>{
344
+ if (stack.has(value)) return;
345
+ stack.add(value);
346
+ let result = valueToString(value, space, onNext, key);
347
+ return stack.delete(value), result;
348
+ }, result = onNext(value, ROOT_SENTINEL);
349
+ if (unpack.size) {
350
+ let sp = space ? " " : "", eol = space ? "\n" : "", wrapper = `var x${sp}=${sp}${result};${eol}`;
351
+ for (let [key, value] of unpack.entries()){
352
+ let keyPath = quote_1.stringifyPath(key, onNext), valuePath = quote_1.stringifyPath(value, onNext);
353
+ wrapper += `x${keyPath}${sp}=${sp}x${valuePath};${eol}`;
354
+ }
355
+ return `(function${sp}()${sp}{${eol}${wrapper}return x;${eol}}())`;
356
+ }
357
+ return result;
358
+ };
359
+ },
360
+ "../../node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/object.js": function(__unused_webpack_module, exports, __webpack_require__) {
361
+ Object.defineProperty(exports, "__esModule", {
362
+ value: !0
363
+ }), exports.objectToString = void 0;
364
+ let quote_1 = __webpack_require__("../../node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/quote.js"), function_1 = __webpack_require__("../../node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/function.js"), array_1 = __webpack_require__("../../node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/array.js");
365
+ exports.objectToString = (value, space, next, key)=>{
366
+ if ("function" == typeof Buffer && Buffer.isBuffer(value)) return `Buffer.from(${next(value.toString("base64"))}, 'base64')`;
367
+ if ("object" == typeof global && value === global) return globalToString(value, space, next, key);
368
+ let toString = OBJECT_TYPES[Object.prototype.toString.call(value)];
369
+ return toString ? toString(value, space, next, key) : void 0;
370
+ };
371
+ let globalToString = (value, space, next)=>`Function(${next("return this")})()`, OBJECT_TYPES = {
372
+ "[object Array]": array_1.arrayToString,
373
+ "[object Object]": (obj, indent, next, key)=>{
374
+ let eol = indent ? "\n" : "", space = indent ? " " : "", values = Object.keys(obj).reduce(function(values, key) {
375
+ let fn = obj[key], result = next(fn, key);
376
+ if (void 0 === result) return values;
377
+ let value = result.split("\n").join(`\n${indent}`);
378
+ return function_1.USED_METHOD_KEY.has(fn) ? values.push(`${indent}${value}`) : values.push(`${indent}${quote_1.quoteKey(key, next)}:${space}${value}`), values;
379
+ }, []).join(`,${eol}`);
380
+ return "" === values ? "{}" : `{${eol}${values}${eol}}`;
381
+ },
382
+ "[object Error]": (error, space, next)=>`new Error(${next(error.message)})`,
383
+ "[object Date]": (date)=>`new Date(${date.getTime()})`,
384
+ "[object String]": (str, space, next)=>`new String(${next(str.toString())})`,
385
+ "[object Number]": (num)=>`new Number(${num})`,
386
+ "[object Boolean]": (bool)=>`new Boolean(${bool})`,
387
+ "[object Set]": (set, space, next)=>`new Set(${next(Array.from(set))})`,
388
+ "[object Map]": (map, space, next)=>`new Map(${next(Array.from(map))})`,
389
+ "[object RegExp]": String,
390
+ "[object global]": globalToString,
391
+ "[object Window]": globalToString
392
+ };
393
+ },
394
+ "../../node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/quote.js": function(__unused_webpack_module, exports) {
395
+ Object.defineProperty(exports, "__esModule", {
396
+ value: !0
397
+ }), exports.stringifyPath = exports.quoteKey = exports.isValidVariableName = exports.IS_VALID_IDENTIFIER = exports.quoteString = void 0;
398
+ let ESCAPABLE = /[\\\'\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, META_CHARS = new Map([
399
+ [
400
+ "\b",
401
+ "\\b"
402
+ ],
403
+ [
404
+ "\t",
405
+ "\\t"
406
+ ],
407
+ [
408
+ "\n",
409
+ "\\n"
410
+ ],
411
+ [
412
+ "\f",
413
+ "\\f"
414
+ ],
415
+ [
416
+ "\r",
417
+ "\\r"
418
+ ],
419
+ [
420
+ "'",
421
+ "\\'"
422
+ ],
423
+ [
424
+ '"',
425
+ '\\"'
426
+ ],
427
+ [
428
+ "\\",
429
+ "\\\\"
430
+ ]
431
+ ]);
432
+ function escapeChar(char) {
433
+ return META_CHARS.get(char) || `\\u${`0000${char.charCodeAt(0).toString(16)}`.slice(-4)}`;
434
+ }
435
+ exports.quoteString = function(str) {
436
+ return `'${str.replace(ESCAPABLE, escapeChar)}'`;
437
+ };
438
+ let RESERVED_WORDS = new Set("break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield".split(" "));
439
+ function isValidVariableName(name) {
440
+ return "string" == typeof name && !RESERVED_WORDS.has(name) && exports.IS_VALID_IDENTIFIER.test(name);
441
+ }
442
+ exports.IS_VALID_IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/, exports.isValidVariableName = isValidVariableName, exports.quoteKey = function(key, next) {
443
+ return isValidVariableName(key) ? key : next(key);
444
+ }, exports.stringifyPath = function(path, next) {
445
+ let result = "";
446
+ for (let key of path)isValidVariableName(key) ? result += `.${key}` : result += `[${next(key)}]`;
447
+ return result;
448
+ };
449
+ },
450
+ "../../node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/stringify.js": function(__unused_webpack_module, exports, __webpack_require__) {
451
+ Object.defineProperty(exports, "__esModule", {
452
+ value: !0
453
+ }), exports.toString = void 0;
454
+ let quote_1 = __webpack_require__("../../node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/quote.js"), object_1 = __webpack_require__("../../node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/object.js"), function_1 = __webpack_require__("../../node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/function.js"), PRIMITIVE_TYPES = {
455
+ string: quote_1.quoteString,
456
+ number: (value)=>Object.is(value, -0) ? "-0" : String(value),
457
+ boolean: String,
458
+ symbol: (value, space, next)=>{
459
+ let key = Symbol.keyFor(value);
460
+ return void 0 !== key ? `Symbol.for(${next(key)})` : `Symbol(${next(value.description)})`;
461
+ },
462
+ bigint: (value, space, next)=>`BigInt(${next(String(value))})`,
463
+ undefined: String,
464
+ object: object_1.objectToString,
465
+ function: function_1.functionToString
466
+ };
467
+ exports.toString = (value, space, next, key)=>null === value ? "null" : PRIMITIVE_TYPES[typeof value](value, space, next, key);
468
+ },
179
469
  "../../node_modules/.pnpm/kind-of@6.0.3/node_modules/kind-of/index.js": function(module) {
180
470
  var toString = Object.prototype.toString;
181
471
  function ctorName(val) {
@@ -765,7 +1055,737 @@ __webpack_require__.r(provider_helpers_namespaceObject), __webpack_require__.d(p
765
1055
  setHTMLPlugin: ()=>setHTMLPlugin
766
1056
  });
767
1057
  let rspack_rspack = createRequire(import.meta.url)('@rspack/core');
768
- var cjs = __webpack_require__("../../node_modules/.pnpm/deepmerge@4.3.1/node_modules/deepmerge/dist/cjs.js"), cjs_default = __webpack_require__.n(cjs);
1058
+ var cjs = __webpack_require__("../../node_modules/.pnpm/deepmerge@4.3.1/node_modules/deepmerge/dist/cjs.js"), cjs_default = __webpack_require__.n(cjs), dist = __webpack_require__("../../node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/index.js");
1059
+ function createMap(superClass) {
1060
+ return class extends superClass {
1061
+ extend(methods) {
1062
+ return this.shorthands = methods, methods.forEach((method)=>{
1063
+ this[method] = (value)=>this.set(method, value);
1064
+ }), this;
1065
+ }
1066
+ clear() {
1067
+ return this.store.clear(), this;
1068
+ }
1069
+ delete(key) {
1070
+ return this.store.delete(key), this;
1071
+ }
1072
+ order() {
1073
+ let entries = [
1074
+ ...this.store
1075
+ ].reduce((acc, [key, value])=>(acc[key] = value, acc), {}), names = Object.keys(entries), order = [
1076
+ ...names
1077
+ ];
1078
+ return names.forEach((name)=>{
1079
+ if (!entries[name]) return;
1080
+ let { __before, __after } = entries[name];
1081
+ __before && order.includes(__before) ? (order.splice(order.indexOf(name), 1), order.splice(order.indexOf(__before), 0, name)) : __after && order.includes(__after) && (order.splice(order.indexOf(name), 1), order.splice(order.indexOf(__after) + 1, 0, name));
1082
+ }), {
1083
+ entries,
1084
+ order
1085
+ };
1086
+ }
1087
+ entries() {
1088
+ let { entries, order } = this.order();
1089
+ if (order.length) return entries;
1090
+ }
1091
+ values() {
1092
+ let { entries, order } = this.order();
1093
+ return order.map((name)=>entries[name]);
1094
+ }
1095
+ get(key) {
1096
+ return this.store.get(key);
1097
+ }
1098
+ getOrCompute(key, fn) {
1099
+ return this.has(key) || this.set(key, fn()), this.get(key);
1100
+ }
1101
+ has(key) {
1102
+ return this.store.has(key);
1103
+ }
1104
+ set(key, value) {
1105
+ return this.store.set(key, value), this;
1106
+ }
1107
+ merge(obj, omit = []) {
1108
+ return Object.keys(obj).forEach((key)=>{
1109
+ if (omit.includes(key)) return;
1110
+ let value = obj[key];
1111
+ (Array.isArray(value) || 'object' == typeof value) && null !== value && this.has(key) ? this.set(key, cjs(this.get(key), value)) : this.set(key, value);
1112
+ }), this;
1113
+ }
1114
+ clean(obj) {
1115
+ return Object.keys(obj).reduce((acc, key)=>{
1116
+ let value = obj[key];
1117
+ return void 0 === value || Array.isArray(value) && !value.length || '[object Object]' === Object.prototype.toString.call(value) && !Object.keys(value).length || (acc[key] = value), acc;
1118
+ }, {});
1119
+ }
1120
+ when(condition, whenTruthy = Function.prototype, whenFalsy = Function.prototype) {
1121
+ return condition ? whenTruthy(this) : whenFalsy(this), this;
1122
+ }
1123
+ constructor(...args){
1124
+ super(...args), this.store = new Map();
1125
+ }
1126
+ };
1127
+ }
1128
+ function createChainable(superClass) {
1129
+ return class extends superClass {
1130
+ batch(handler) {
1131
+ return handler(this), this;
1132
+ }
1133
+ end() {
1134
+ return this.parent;
1135
+ }
1136
+ constructor(parent){
1137
+ super(), this.parent = parent;
1138
+ }
1139
+ };
1140
+ }
1141
+ let ChainedMap = createMap(createChainable(Object)), ChainedValueMap = (superClass = createMap(createChainable(class extends Function {
1142
+ classCall() {
1143
+ throw Error('not implemented');
1144
+ }
1145
+ constructor(){
1146
+ return super(), new Proxy(this, {
1147
+ apply: (target, thisArg, args)=>target.classCall(...args)
1148
+ });
1149
+ }
1150
+ })), class extends superClass {
1151
+ set(...args) {
1152
+ return this.useMap = !0, this.value = void 0, super.set(...args);
1153
+ }
1154
+ clear() {
1155
+ return this.value = void 0, super.clear();
1156
+ }
1157
+ classCall(value) {
1158
+ return this.clear(), this.useMap = !1, this.value = value, this.parent;
1159
+ }
1160
+ entries() {
1161
+ return this.useMap ? super.entries() : this.value;
1162
+ }
1163
+ values() {
1164
+ return this.useMap ? super.values() : this.value;
1165
+ }
1166
+ constructor(...args){
1167
+ super(...args), this.value = void 0, this.useMap = !0;
1168
+ }
1169
+ }), ChainedSet = (superClass1 = createChainable(Object), class extends superClass1 {
1170
+ add(value) {
1171
+ return this.store.add(value), this;
1172
+ }
1173
+ prepend(value) {
1174
+ return this.store = new Set([
1175
+ value,
1176
+ ...this.store
1177
+ ]), this;
1178
+ }
1179
+ clear() {
1180
+ return this.store.clear(), this;
1181
+ }
1182
+ delete(value) {
1183
+ return this.store.delete(value), this;
1184
+ }
1185
+ values() {
1186
+ return [
1187
+ ...this.store
1188
+ ];
1189
+ }
1190
+ has(value) {
1191
+ return this.store.has(value);
1192
+ }
1193
+ merge(arr) {
1194
+ return void 0 !== arr && (this.store = new Set([
1195
+ ...this.store,
1196
+ ...arr
1197
+ ])), this;
1198
+ }
1199
+ when(condition, whenTruthy = Function.prototype, whenFalsy = Function.prototype) {
1200
+ return condition ? whenTruthy(this) : whenFalsy(this), this;
1201
+ }
1202
+ constructor(...args){
1203
+ super(...args), this.store = new Set();
1204
+ }
1205
+ }), Orderable = (Class)=>class extends Class {
1206
+ before(name) {
1207
+ if (this.__after) throw Error(`Unable to set .before(${JSON.stringify(name)}) with existing value for .after()`);
1208
+ return this.__before = name, this;
1209
+ }
1210
+ after(name) {
1211
+ if (this.__before) throw Error(`Unable to set .after(${JSON.stringify(name)}) with existing value for .before()`);
1212
+ return this.__after = name, this;
1213
+ }
1214
+ merge(obj, omit = []) {
1215
+ return obj.before && this.before(obj.before), obj.after && this.after(obj.after), super.merge(obj, [
1216
+ ...omit,
1217
+ 'before',
1218
+ 'after'
1219
+ ]);
1220
+ }
1221
+ }, src_Plugin = Orderable(class extends ChainedMap {
1222
+ use(plugin, args = []) {
1223
+ return this.set('plugin', plugin).set('args', args);
1224
+ }
1225
+ tap(f) {
1226
+ if (!this.has('plugin')) throw Error(`Cannot call .tap() on a plugin that has not yet been defined. Call ${this.type}('${this.name}').use(<Plugin>) first.`);
1227
+ return this.set('args', f(this.get('args') || [])), this;
1228
+ }
1229
+ set(key, value) {
1230
+ if ('args' === key && !Array.isArray(value)) throw Error('args must be an array of arguments');
1231
+ return super.set(key, value);
1232
+ }
1233
+ merge(obj, omit = []) {
1234
+ return 'plugin' in obj && this.set('plugin', obj.plugin), 'args' in obj && this.set('args', obj.args), super.merge(obj, [
1235
+ ...omit,
1236
+ 'args',
1237
+ 'plugin'
1238
+ ]);
1239
+ }
1240
+ toConfig() {
1241
+ let init = this.get('init'), plugin = this.get('plugin'), args = this.get('args'), pluginPath = null;
1242
+ if (void 0 === plugin) throw Error(`Invalid ${this.type} configuration: ${this.type}('${this.name}').use(<Plugin>) was not called to specify the plugin`);
1243
+ 'string' == typeof plugin && (plugin = require(pluginPath = plugin));
1244
+ let constructorName = plugin.__expression ? `(${plugin.__expression})` : plugin.name, config = init(plugin, args);
1245
+ return Object.defineProperties(config, {
1246
+ __pluginName: {
1247
+ value: this.name
1248
+ },
1249
+ __pluginType: {
1250
+ value: this.type
1251
+ },
1252
+ __pluginArgs: {
1253
+ value: args
1254
+ },
1255
+ __pluginConstructorName: {
1256
+ value: constructorName
1257
+ },
1258
+ __pluginPath: {
1259
+ value: pluginPath
1260
+ }
1261
+ }), config;
1262
+ }
1263
+ constructor(parent, name, type = 'plugin'){
1264
+ super(parent), this.name = name, this.type = type, this.extend([
1265
+ 'init'
1266
+ ]), this.init((Plugin, args = [])=>'function' == typeof Plugin ? new Plugin(...args) : Plugin);
1267
+ }
1268
+ }), childMaps = [
1269
+ 'alias',
1270
+ 'fallback',
1271
+ 'byDependency',
1272
+ 'extensionAlias'
1273
+ ], childSets = [
1274
+ 'aliasFields',
1275
+ 'conditionNames',
1276
+ "descriptionFiles",
1277
+ 'extensions',
1278
+ 'mainFields',
1279
+ 'mainFiles',
1280
+ 'exportsFields',
1281
+ 'importsFields',
1282
+ 'restrictions',
1283
+ 'roots',
1284
+ 'modules'
1285
+ ];
1286
+ class Resolve_class extends ChainedMap {
1287
+ plugin(name) {
1288
+ return this.plugins.getOrCompute(name, ()=>new src_Plugin(this, name, 'resolve.plugin'));
1289
+ }
1290
+ get(key) {
1291
+ return childMaps.includes(key) ? this[key].entries() : childSets.includes(key) ? this[key].values() : super.get(key);
1292
+ }
1293
+ toConfig() {
1294
+ let config = Object.assign(this.entries() || {}, {
1295
+ plugins: this.plugins.values().map((plugin)=>plugin.toConfig())
1296
+ });
1297
+ return childMaps.forEach((key)=>{
1298
+ config[key] = this[key].entries();
1299
+ }), childSets.forEach((key)=>{
1300
+ config[key] = this[key].values();
1301
+ }), this.clean(config);
1302
+ }
1303
+ merge(obj, omit = []) {
1304
+ !omit.includes('plugin') && 'plugin' in obj && Object.keys(obj.plugin).forEach((name)=>this.plugin(name).merge(obj.plugin[name]));
1305
+ let omissions = [
1306
+ ...childMaps,
1307
+ ...childSets
1308
+ ];
1309
+ return omissions.forEach((key)=>{
1310
+ !omit.includes(key) && key in obj && this[key].merge(obj[key]);
1311
+ }), super.merge(obj, [
1312
+ ...omit,
1313
+ ...omissions,
1314
+ 'plugin'
1315
+ ]);
1316
+ }
1317
+ constructor(parent){
1318
+ super(parent), childMaps.forEach((key)=>{
1319
+ this[key] = new ChainedMap(this);
1320
+ }), childSets.forEach((key)=>{
1321
+ this[key] = new ChainedSet(this);
1322
+ }), this.plugins = new ChainedMap(this), this.extend([
1323
+ 'cachePredicate',
1324
+ 'cacheWithContext',
1325
+ 'enforceExtension',
1326
+ 'symlinks',
1327
+ 'unsafeCache',
1328
+ 'preferRelative',
1329
+ 'preferAbsolute',
1330
+ 'tsConfig'
1331
+ ]);
1332
+ }
1333
+ }
1334
+ class ResolveLoader_class extends Resolve_class {
1335
+ toConfig() {
1336
+ return this.clean({
1337
+ modules: this.modules.values(),
1338
+ moduleExtensions: this.moduleExtensions.values(),
1339
+ packageMains: this.packageMains.values(),
1340
+ ...super.toConfig()
1341
+ });
1342
+ }
1343
+ merge(obj, omit = []) {
1344
+ let omissions = [
1345
+ 'modules',
1346
+ 'moduleExtensions',
1347
+ 'packageMains'
1348
+ ];
1349
+ return omissions.forEach((key)=>{
1350
+ !omit.includes(key) && key in obj && this[key].merge(obj[key]);
1351
+ }), super.merge(obj, [
1352
+ ...omit,
1353
+ ...omissions
1354
+ ]);
1355
+ }
1356
+ constructor(parent){
1357
+ super(parent), this.modules = new ChainedSet(this), this.moduleExtensions = new ChainedSet(this), this.packageMains = new ChainedSet(this);
1358
+ }
1359
+ }
1360
+ class Output_class extends ChainedMap {
1361
+ constructor(parent){
1362
+ super(parent), this.extend([
1363
+ 'auxiliaryComment',
1364
+ 'charset',
1365
+ 'chunkFilename',
1366
+ 'chunkLoadTimeout',
1367
+ 'chunkLoadingGlobal',
1368
+ 'chunkLoading',
1369
+ 'chunkFormat',
1370
+ 'enabledChunkLoadingTypes',
1371
+ 'crossOriginLoading',
1372
+ 'devtoolFallbackModuleFilenameTemplate',
1373
+ 'devtoolModuleFilenameTemplate',
1374
+ 'devtoolNamespace',
1375
+ 'filename',
1376
+ 'assetModuleFilename',
1377
+ 'globalObject',
1378
+ 'uniqueName',
1379
+ 'hashDigest',
1380
+ 'hashDigestLength',
1381
+ 'hashFunction',
1382
+ 'hashSalt',
1383
+ 'hotUpdateChunkFilename',
1384
+ 'hotUpdateGlobal',
1385
+ 'hotUpdateMainFilename',
1386
+ 'library',
1387
+ 'libraryExport',
1388
+ 'libraryTarget',
1389
+ 'importFunctionName',
1390
+ 'path',
1391
+ 'pathinfo',
1392
+ 'publicPath',
1393
+ "scriptType",
1394
+ 'sourceMapFilename',
1395
+ 'sourcePrefix',
1396
+ 'strictModuleErrorHandling',
1397
+ 'strictModuleExceptionHandling',
1398
+ 'umdNamedDefine',
1399
+ 'workerChunkLoading',
1400
+ 'enabledLibraryTypes',
1401
+ 'environment',
1402
+ 'compareBeforeEmit',
1403
+ 'wasmLoading',
1404
+ 'webassemblyModuleFilename',
1405
+ 'enabledWasmLoadingTypes',
1406
+ 'iife',
1407
+ 'module',
1408
+ 'clean'
1409
+ ]);
1410
+ }
1411
+ }
1412
+ class DevServer_class extends ChainedMap {
1413
+ toConfig() {
1414
+ return this.clean({
1415
+ allowedHosts: this.allowedHosts.values(),
1416
+ ...this.entries() || {}
1417
+ });
1418
+ }
1419
+ merge(obj, omit = []) {
1420
+ return !omit.includes('allowedHosts') && 'allowedHosts' in obj && this.allowedHosts.merge(obj.allowedHosts), super.merge(obj, [
1421
+ 'allowedHosts'
1422
+ ]);
1423
+ }
1424
+ constructor(parent){
1425
+ super(parent), this.allowedHosts = new ChainedSet(this), this.extend([
1426
+ 'after',
1427
+ 'before',
1428
+ 'bonjour',
1429
+ 'clientLogLevel',
1430
+ 'compress',
1431
+ 'contentBase',
1432
+ 'contentBasePublicPath',
1433
+ 'disableHostCheck',
1434
+ 'filename',
1435
+ 'headers',
1436
+ 'historyApiFallback',
1437
+ 'host',
1438
+ 'hot',
1439
+ 'hotOnly',
1440
+ 'http2',
1441
+ 'https',
1442
+ 'index',
1443
+ 'injectClient',
1444
+ 'injectHot',
1445
+ 'inline',
1446
+ 'lazy',
1447
+ 'liveReload',
1448
+ 'mimeTypes',
1449
+ 'noInfo',
1450
+ 'onListening',
1451
+ 'open',
1452
+ 'openPage',
1453
+ 'overlay',
1454
+ 'pfx',
1455
+ 'pfxPassphrase',
1456
+ 'port',
1457
+ 'proxy',
1458
+ 'progress',
1459
+ 'public',
1460
+ 'publicPath',
1461
+ 'quiet',
1462
+ 'serveIndex',
1463
+ 'setup',
1464
+ 'socket',
1465
+ 'sockHost',
1466
+ 'sockPath',
1467
+ 'sockPort',
1468
+ 'staticOptions',
1469
+ 'stats',
1470
+ 'stdin',
1471
+ 'transportMode',
1472
+ 'useLocalIp',
1473
+ 'watchContentBase',
1474
+ 'watchOptions',
1475
+ 'writeToDisk'
1476
+ ]);
1477
+ }
1478
+ }
1479
+ let Use = Orderable(class extends ChainedMap {
1480
+ tap(f) {
1481
+ return this.options(f(this.get('options'))), this;
1482
+ }
1483
+ merge(obj, omit = []) {
1484
+ return !omit.includes('loader') && 'loader' in obj && this.loader(obj.loader), !omit.includes('options') && 'options' in obj && this.options(cjs(this.store.get('options') || {}, obj.options)), super.merge(obj, [
1485
+ ...omit,
1486
+ 'loader',
1487
+ 'options'
1488
+ ]);
1489
+ }
1490
+ toConfig() {
1491
+ let config = this.clean(this.entries() || {});
1492
+ return Object.defineProperties(config, {
1493
+ __useName: {
1494
+ value: this.name
1495
+ },
1496
+ __ruleNames: {
1497
+ value: this.parent && this.parent.names
1498
+ },
1499
+ __ruleTypes: {
1500
+ value: this.parent && this.parent.ruleTypes
1501
+ }
1502
+ }), config;
1503
+ }
1504
+ constructor(parent, name){
1505
+ super(parent), this.name = name, this.extend([
1506
+ 'loader',
1507
+ 'options',
1508
+ 'parallel'
1509
+ ]);
1510
+ }
1511
+ });
1512
+ function toArray(arr) {
1513
+ return Array.isArray(arr) ? arr : [
1514
+ arr
1515
+ ];
1516
+ }
1517
+ let Rule_Rule = Orderable(class extends ChainedMap {
1518
+ use(name) {
1519
+ return this.uses.getOrCompute(name, ()=>new Use(this, name));
1520
+ }
1521
+ rule(name) {
1522
+ return this.rules.getOrCompute(name, ()=>new Rule_Rule(this, name, 'rule'));
1523
+ }
1524
+ oneOf(name) {
1525
+ return this.oneOfs.getOrCompute(name, ()=>new Rule_Rule(this, name, 'oneOf'));
1526
+ }
1527
+ pre() {
1528
+ return this.enforce('pre');
1529
+ }
1530
+ post() {
1531
+ return this.enforce('post');
1532
+ }
1533
+ toConfig() {
1534
+ let config = this.clean(Object.assign(this.entries() || {}, {
1535
+ include: this.include.values(),
1536
+ exclude: this.exclude.values(),
1537
+ rules: this.rules.values().map((rule)=>rule.toConfig()),
1538
+ oneOf: this.oneOfs.values().map((oneOf)=>oneOf.toConfig()),
1539
+ use: this.uses.values().map((use)=>use.toConfig()),
1540
+ resolve: this.resolve.toConfig()
1541
+ }));
1542
+ return Object.defineProperties(config, {
1543
+ __ruleNames: {
1544
+ value: this.names
1545
+ },
1546
+ __ruleTypes: {
1547
+ value: this.ruleTypes
1548
+ }
1549
+ }), config;
1550
+ }
1551
+ merge(obj, omit = []) {
1552
+ return !omit.includes('include') && 'include' in obj && this.include.merge(toArray(obj.include)), !omit.includes('exclude') && 'exclude' in obj && this.exclude.merge(toArray(obj.exclude)), !omit.includes('use') && 'use' in obj && Object.keys(obj.use).forEach((name)=>this.use(name).merge(obj.use[name])), !omit.includes('rules') && 'rules' in obj && Object.keys(obj.rules).forEach((name)=>this.rule(name).merge(obj.rules[name])), !omit.includes('oneOf') && 'oneOf' in obj && Object.keys(obj.oneOf).forEach((name)=>this.oneOf(name).merge(obj.oneOf[name])), !omit.includes('resolve') && 'resolve' in obj && this.resolve.merge(obj.resolve), !omit.includes('test') && 'test' in obj && this.test(obj.test instanceof RegExp || 'function' == typeof obj.test ? obj.test : new RegExp(obj.test)), super.merge(obj, [
1553
+ ...omit,
1554
+ 'include',
1555
+ 'exclude',
1556
+ 'use',
1557
+ 'rules',
1558
+ 'oneOf',
1559
+ 'resolve',
1560
+ 'test'
1561
+ ]);
1562
+ }
1563
+ constructor(parent, name, ruleType = 'rule'){
1564
+ super(parent), this.ruleName = name, this.names = [], this.ruleType = ruleType, this.ruleTypes = [];
1565
+ let rule = this;
1566
+ for(; rule instanceof Rule_Rule;)this.names.unshift(rule.ruleName), this.ruleTypes.unshift(rule.ruleType), rule = rule.parent;
1567
+ this.uses = new ChainedMap(this), this.include = new ChainedSet(this), this.exclude = new ChainedSet(this), this.rules = new ChainedMap(this), this.oneOfs = new ChainedMap(this), this.resolve = new Resolve_class(this), this.resolve.extend([
1568
+ 'fullySpecified'
1569
+ ]), this.extend([
1570
+ 'dependency',
1571
+ 'enforce',
1572
+ 'issuer',
1573
+ 'issuerLayer',
1574
+ 'layer',
1575
+ 'mimetype',
1576
+ 'parser',
1577
+ 'generator',
1578
+ 'resource',
1579
+ 'resourceFragment',
1580
+ 'resourceQuery',
1581
+ 'sideEffects',
1582
+ 'with',
1583
+ 'test',
1584
+ 'type'
1585
+ ]);
1586
+ }
1587
+ });
1588
+ class Module_class extends ChainedMap {
1589
+ defaultRule(name) {
1590
+ return this.defaultRules.getOrCompute(name, ()=>new Rule_Rule(this, name, 'defaultRule'));
1591
+ }
1592
+ rule(name) {
1593
+ return this.rules.getOrCompute(name, ()=>new Rule_Rule(this, name, 'rule'));
1594
+ }
1595
+ toConfig() {
1596
+ return this.clean(Object.assign(this.entries() || {}, {
1597
+ defaultRules: this.defaultRules.values().map((r)=>r.toConfig()),
1598
+ generator: this.generator.entries(),
1599
+ parser: this.parser.entries(),
1600
+ rules: this.rules.values().map((r)=>r.toConfig())
1601
+ }));
1602
+ }
1603
+ merge(obj, omit = []) {
1604
+ return !omit.includes('rule') && 'rule' in obj && Object.keys(obj.rule).forEach((name)=>this.rule(name).merge(obj.rule[name])), !omit.includes('defaultRule') && 'defaultRule' in obj && Object.keys(obj.defaultRule).forEach((name)=>this.defaultRule(name).merge(obj.defaultRule[name])), super.merge(obj, [
1605
+ 'rule',
1606
+ 'defaultRule'
1607
+ ]);
1608
+ }
1609
+ constructor(parent){
1610
+ super(parent), this.rules = new ChainedMap(this), this.defaultRules = new ChainedMap(this), this.generator = new ChainedMap(this), this.parser = new ChainedMap(this), this.extend([
1611
+ 'noParse',
1612
+ 'unsafeCache',
1613
+ 'wrappedContextCritical',
1614
+ 'exprContextRegExp',
1615
+ 'wrappedContextRecursive',
1616
+ 'strictExportPresence',
1617
+ 'wrappedContextRegExp'
1618
+ ]);
1619
+ }
1620
+ }
1621
+ class Optimization_class extends ChainedMap {
1622
+ minimizer(name) {
1623
+ if (Array.isArray(name)) throw Error("optimization.minimizer() no longer supports being passed an array. Either switch to the new syntax (https://github.com/neutrinojs/webpack-chain#config-optimization-minimizers-adding) or downgrade to webpack-chain 4. If using Vue this likely means a Vue plugin has not yet been updated to support Vue CLI 4+.");
1624
+ return this.minimizers.getOrCompute(name, ()=>new src_Plugin(this, name, 'optimization.minimizer'));
1625
+ }
1626
+ toConfig() {
1627
+ return this.clean(Object.assign(this.entries() || {}, {
1628
+ splitChunks: this.splitChunks.entries(),
1629
+ minimizer: this.minimizers.values().map((plugin)=>plugin.toConfig())
1630
+ }));
1631
+ }
1632
+ merge(obj, omit = []) {
1633
+ return !omit.includes('minimizer') && 'minimizer' in obj && Object.keys(obj.minimizer).forEach((name)=>this.minimizer(name).merge(obj.minimizer[name])), super.merge(obj, [
1634
+ ...omit,
1635
+ 'minimizer'
1636
+ ]);
1637
+ }
1638
+ constructor(parent){
1639
+ super(parent), this.minimizers = new ChainedMap(this), this.splitChunks = new ChainedValueMap(this), this.extend([
1640
+ 'minimize',
1641
+ 'runtimeChunk',
1642
+ 'emitOnErrors',
1643
+ 'moduleIds',
1644
+ 'chunkIds',
1645
+ 'nodeEnv',
1646
+ 'mangleWasmImports',
1647
+ 'removeAvailableModules',
1648
+ 'removeEmptyChunks',
1649
+ 'mergeDuplicateChunks',
1650
+ 'flagIncludedChunks',
1651
+ 'providedExports',
1652
+ 'usedExports',
1653
+ 'concatenateModules',
1654
+ 'sideEffects',
1655
+ 'portableRecords',
1656
+ 'mangleExports',
1657
+ 'innerGraph',
1658
+ 'realContentHash',
1659
+ 'avoidEntryIife'
1660
+ ]);
1661
+ }
1662
+ }
1663
+ class Performance_class extends ChainedValueMap {
1664
+ constructor(parent){
1665
+ super(parent), this.extend([
1666
+ 'assetFilter',
1667
+ 'hints',
1668
+ 'maxAssetSize',
1669
+ 'maxEntrypointSize'
1670
+ ]);
1671
+ }
1672
+ }
1673
+ let castArray = (value)=>Array.isArray(value) ? value : [
1674
+ value
1675
+ ];
1676
+ class src_class extends ChainedMap {
1677
+ static toString(config, { verbose = !1, configPrefix = 'config' } = {}) {
1678
+ return (0, dist.stringify)(config, (value, indent, stringify)=>{
1679
+ if (value && value.__pluginName) {
1680
+ let prefix = `/* ${configPrefix}.${value.__pluginType}('${value.__pluginName}') */\n`, constructorExpression = value.__pluginPath ? `(require(${stringify(value.__pluginPath)}))` : value.__pluginConstructorName;
1681
+ if (constructorExpression) {
1682
+ let args = stringify(value.__pluginArgs).slice(1, -1);
1683
+ return `${prefix}new ${constructorExpression}(${args})`;
1684
+ }
1685
+ return prefix + stringify(value.__pluginArgs && value.__pluginArgs.length ? {
1686
+ args: value.__pluginArgs
1687
+ } : {});
1688
+ }
1689
+ if (value && value.__ruleNames) {
1690
+ let ruleTypes = value.__ruleTypes;
1691
+ return `/* ${configPrefix}.module${value.__ruleNames.map((r, index)=>`.${ruleTypes ? ruleTypes[index] : 'rule'}('${r}')`).join('')}${value.__useName ? `.use('${value.__useName}')` : ""} */\n` + stringify(value);
1692
+ }
1693
+ return value && value.__expression ? value.__expression : 'function' == typeof value && !verbose && value.toString().length > 100 ? "function () { /* omitted long function */ }" : stringify(value);
1694
+ }, 2);
1695
+ }
1696
+ entry(name) {
1697
+ return this.entryPoints.getOrCompute(name, ()=>new ChainedSet(this));
1698
+ }
1699
+ plugin(name) {
1700
+ return this.plugins.getOrCompute(name, ()=>new src_Plugin(this, name));
1701
+ }
1702
+ toConfig() {
1703
+ let entryPoints = this.entryPoints.entries() || {}, baseConfig = this.entries() || {};
1704
+ return this.clean(Object.assign(baseConfig, {
1705
+ node: this.node.entries(),
1706
+ output: this.output.entries(),
1707
+ resolve: this.resolve.toConfig(),
1708
+ resolveLoader: this.resolveLoader.toConfig(),
1709
+ devServer: this.devServer.toConfig(),
1710
+ module: this.module.toConfig(),
1711
+ optimization: this.optimization.toConfig(),
1712
+ plugins: this.plugins.values().map((plugin)=>plugin.toConfig()),
1713
+ performance: this.performance.entries(),
1714
+ entry: ((entryPoints)=>{
1715
+ let entry = Object.keys(entryPoints).reduce((acc, key)=>Object.assign(acc, {
1716
+ [key]: entryPoints[key].values()
1717
+ }), {}), formattedEntry = {};
1718
+ for (let [entryName, entryValue] of Object.entries(entry)){
1719
+ let entryImport = [], entryDescription = null;
1720
+ for (let item of castArray(entryValue)){
1721
+ if ('string' == typeof item) {
1722
+ entryImport.push(item);
1723
+ continue;
1724
+ }
1725
+ item.import && entryImport.push(...castArray(item.import)), entryDescription ? Object.assign(entryDescription, item) : entryDescription = item;
1726
+ }
1727
+ formattedEntry[entryName] = entryDescription ? {
1728
+ ...entryDescription,
1729
+ import: entryImport
1730
+ } : entryImport;
1731
+ }
1732
+ return formattedEntry;
1733
+ })(entryPoints)
1734
+ }));
1735
+ }
1736
+ toString(options) {
1737
+ return this.constructor.toString(this.toConfig(), options);
1738
+ }
1739
+ merge(obj = {}, omit = []) {
1740
+ let omissions = [
1741
+ 'node',
1742
+ 'output',
1743
+ 'resolve',
1744
+ 'resolveLoader',
1745
+ 'devServer',
1746
+ 'optimization',
1747
+ 'performance',
1748
+ 'module'
1749
+ ];
1750
+ return !omit.includes('entry') && 'entry' in obj && Object.keys(obj.entry).forEach((name)=>this.entry(name).merge([].concat(obj.entry[name]))), !omit.includes('plugin') && 'plugin' in obj && Object.keys(obj.plugin).forEach((name)=>this.plugin(name).merge(obj.plugin[name])), omissions.forEach((key)=>{
1751
+ !omit.includes(key) && key in obj && this[key].merge(obj[key]);
1752
+ }), super.merge(obj, [
1753
+ ...omit,
1754
+ ...omissions,
1755
+ 'entry',
1756
+ 'plugin'
1757
+ ]);
1758
+ }
1759
+ constructor(){
1760
+ super(), this.entryPoints = new ChainedMap(this), this.output = new Output_class(this), this.module = new Module_class(this), this.resolve = new Resolve_class(this), this.resolveLoader = new ResolveLoader_class(this), this.optimization = new Optimization_class(this), this.plugins = new ChainedMap(this), this.devServer = new DevServer_class(this), this.performance = new Performance_class(this), this.node = new ChainedValueMap(this), this.extend([
1761
+ 'context',
1762
+ 'mode',
1763
+ 'devtool',
1764
+ 'target',
1765
+ 'watch',
1766
+ 'watchOptions',
1767
+ 'externals',
1768
+ 'externalsType',
1769
+ 'externalsPresets',
1770
+ 'stats',
1771
+ 'experiments',
1772
+ 'amd',
1773
+ 'bail',
1774
+ 'cache',
1775
+ 'dependencies',
1776
+ 'ignoreWarnings',
1777
+ 'loader',
1778
+ 'parallelism',
1779
+ 'profile',
1780
+ 'recordsPath',
1781
+ 'recordsInputPath',
1782
+ 'recordsOutputPath',
1783
+ 'name',
1784
+ 'infrastructureLogging',
1785
+ 'snapshot'
1786
+ ]);
1787
+ }
1788
+ }
769
1789
  let constants_filename = fileURLToPath(import.meta.url), constants_dirname = dirname(constants_filename), ROOT_DIST_DIR = 'dist', LOADER_PATH = join(constants_dirname), STATIC_PATH = join(constants_dirname, '../static'), COMPILED_PATH = join(constants_dirname, '../compiled'), RSBUILD_OUTPUTS_PATH = '.rsbuild', DEFAULT_DEV_HOST = '0.0.0.0', DEFAULT_ASSET_PREFIX = '/', DEFAULT_WEB_BROWSERSLIST = [
770
1790
  'chrome >= 87',
771
1791
  'edge >= 88',
@@ -986,7 +2006,16 @@ function formatStatsMessages(stats, verbose) {
986
2006
  let getAllStatsErrors = (statsData)=>{
987
2007
  var _statsData_errors, _statsData_children;
988
2008
  return statsData.errorsCount && (null == (_statsData_errors = statsData.errors) ? void 0 : _statsData_errors.length) === 0 ? null == (_statsData_children = statsData.children) ? void 0 : _statsData_children.reduce((errors, curr)=>errors.concat(curr.errors || []), []) : statsData.errors;
989
- }, getAllStatsWarnings = (statsData)=>{
2009
+ }, getAssetsFromStats = (stats)=>stats.toJson({
2010
+ all: !1,
2011
+ assets: !0,
2012
+ cachedAssets: !0,
2013
+ groupAssetsByInfo: !1,
2014
+ groupAssetsByPath: !1,
2015
+ groupAssetsByChunk: !1,
2016
+ groupAssetsByExtension: !1,
2017
+ groupAssetsByEmitStatus: !1
2018
+ }).assets || [], getAllStatsWarnings = (statsData)=>{
990
2019
  var _statsData_warnings, _statsData_children;
991
2020
  return statsData.warningsCount && (null == (_statsData_warnings = statsData.warnings) ? void 0 : _statsData_warnings.length) === 0 ? null == (_statsData_children = statsData.children) ? void 0 : _statsData_children.reduce((warnings, curr)=>warnings.concat(curr.warnings || []), []) : statsData.warnings;
992
2021
  };
@@ -1031,7 +2060,7 @@ function formatStats(statsData, hasErrors) {
1031
2060
  }
1032
2061
  let rspackMinVersion = '1.2.4', setNodeEnv = (env)=>{
1033
2062
  process.env.NODE_ENV = env;
1034
- }, isFunction = (func)=>'function' == typeof func, isObject = (obj)=>'[object Object]' === Object.prototype.toString.call(obj), isPlainObject = (obj)=>null !== obj && 'object' == typeof obj && Object.getPrototypeOf(obj) === Object.prototype, castArray = (arr)=>void 0 === arr ? [] : Array.isArray(arr) ? arr : [
2063
+ }, isFunction = (func)=>'function' == typeof func, isObject = (obj)=>'[object Object]' === Object.prototype.toString.call(obj), isPlainObject = (obj)=>null !== obj && 'object' == typeof obj && Object.getPrototypeOf(obj) === Object.prototype, helpers_castArray = (arr)=>void 0 === arr ? [] : Array.isArray(arr) ? arr : [
1035
2064
  arr
1036
2065
  ], cloneDeep = (value)=>null == value ? value : cjs_default()({}, value, {
1037
2066
  isMergeableObject: isPlainObject
@@ -1126,10 +2155,10 @@ function toArr(any) {
1126
2155
  isDebug() && (logger.level = 'verbose'), logger.override({
1127
2156
  debug: (message, ...args)=>{
1128
2157
  if ('verbose' !== logger.level) return;
1129
- let time = picocolors.gray(`${function() {
2158
+ let time = picocolors.gray(function() {
1130
2159
  let now = new Date(), hours = String(now.getHours()).padStart(2, '0'), minutes = String(now.getMinutes()).padStart(2, '0'), seconds = String(now.getSeconds()).padStart(2, '0');
1131
2160
  return `${hours}:${minutes}:${seconds}`;
1132
- }()}`);
2161
+ }());
1133
2162
  console.log(` ${picocolors.magenta('rsbuild')} ${time} ${message}`, ...args);
1134
2163
  }
1135
2164
  });
@@ -1448,9 +2477,11 @@ function createEnvironmentAsyncHook() {
1448
2477
  };
1449
2478
  return {
1450
2479
  tapEnvironment,
1451
- tap: (handler)=>tapEnvironment({
2480
+ tap: (handler)=>{
2481
+ tapEnvironment({
1452
2482
  handler
1453
- }),
2483
+ });
2484
+ },
1454
2485
  callChain: async ({ environment, args: params })=>{
1455
2486
  for (let callback of [
1456
2487
  ...preGroup,
@@ -1564,13 +2595,13 @@ let onBeforeCompile = ({ compiler, beforeCompile, beforeEnvironmentCompiler, isW
1564
2595
  };
1565
2596
  onBeforeCompile({
1566
2597
  compiler,
1567
- beforeCompile: async ()=>await context.hooks.onBeforeBuild.callBatch({
2598
+ beforeCompile: async ()=>context.hooks.onBeforeBuild.callBatch({
1568
2599
  bundlerConfigs,
1569
2600
  environments: context.environments,
1570
2601
  isWatch,
1571
2602
  isFirstCompile
1572
2603
  }),
1573
- beforeEnvironmentCompiler: async (buildIndex)=>await context.hooks.onBeforeEnvironmentCompile.callBatch({
2604
+ beforeEnvironmentCompiler: async (buildIndex)=>context.hooks.onBeforeEnvironmentCompile.callBatch({
1574
2605
  environment: environmentList[buildIndex].name,
1575
2606
  args: [
1576
2607
  {
@@ -1611,7 +2642,7 @@ let onBeforeCompile = ({ compiler, beforeCompile, beforeEnvironmentCompiler, isW
1611
2642
  };
1612
2643
  onBeforeCompile({
1613
2644
  compiler,
1614
- beforeEnvironmentCompiler: async (buildIndex)=>await context.hooks.onBeforeEnvironmentCompile.callBatch({
2645
+ beforeEnvironmentCompiler: async (buildIndex)=>context.hooks.onBeforeEnvironmentCompile.callBatch({
1615
2646
  environment: environmentList[buildIndex].name,
1616
2647
  args: [
1617
2648
  {
@@ -1720,8 +2751,8 @@ let configCache = {}, OVERRIDE_PATHS = [
1720
2751
  y
1721
2752
  ];
1722
2753
  if (pair.some(Array.isArray)) return 'output.copy' !== path || pair.every(Array.isArray) ? [
1723
- ...castArray(x),
1724
- ...castArray(y)
2754
+ ...helpers_castArray(x),
2755
+ ...helpers_castArray(y)
1725
2756
  ] : Array.isArray(x) ? merge({
1726
2757
  patterns: x
1727
2758
  }, y, path) : merge(x, {
@@ -1815,7 +2846,8 @@ let configCache = {}, OVERRIDE_PATHS = [
1815
2846
  wasm: 'static/wasm',
1816
2847
  image: 'static/image',
1817
2848
  media: 'static/media',
1818
- assets: 'static/assets'
2849
+ assets: 'static/assets',
2850
+ favicon: './'
1819
2851
  },
1820
2852
  assetPrefix: DEFAULT_ASSET_PREFIX,
1821
2853
  filename: {},
@@ -1959,7 +2991,7 @@ async function initPlugins({ context, pluginManager }) {
1959
2991
  let { name, setup } = instance;
1960
2992
  if (!(removedPlugins.has(name) || environment && (null == (_removedEnvPlugins_environment = removedEnvPlugins[environment]) ? void 0 : _removedEnvPlugins_environment.has(name)))) {
1961
2993
  if (instance.apply && context.action) if (isFunction(instance.apply)) {
1962
- if (!1 === instance.apply(context.originalConfig, {
2994
+ if (!instance.apply(context.originalConfig, {
1963
2995
  action: context.action
1964
2996
  })) continue;
1965
2997
  } else {
@@ -2094,7 +3126,7 @@ async function updateEnvironmentContext(context, configs) {
2094
3126
  async function createContext(options, userConfig) {
2095
3127
  let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = join(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, bundlerType = userConfig.provider ? 'webpack' : 'rspack';
2096
3128
  return {
2097
- version: "1.4.11",
3129
+ version: "1.4.13",
2098
3130
  rootPath,
2099
3131
  distPath: '',
2100
3132
  cachePath,
@@ -2171,7 +3203,7 @@ async function outputInspectConfigFiles({ rawBundlerConfigs, rawEnvironmentConfi
2171
3203
  logger.success(`config inspection completed, generated files: \n\n${fileInfos}\n`);
2172
3204
  }
2173
3205
  function stringifyConfig(config, verbose) {
2174
- return (0, rspack_chain.toString)(config, {
3206
+ return src_class.toString(config, {
2175
3207
  verbose
2176
3208
  });
2177
3209
  }
@@ -2271,14 +3303,14 @@ var webpack_merge_dist = __webpack_require__("../../node_modules/.pnpm/webpack-m
2271
3303
  async function modifyBundlerChain(context, utils) {
2272
3304
  var _utils_environment_config_tools;
2273
3305
  logger.debug('modify bundler chain');
2274
- let bundlerChain = new rspack_chain(), [modifiedBundlerChain] = await context.hooks.modifyBundlerChain.callChain({
3306
+ let bundlerChain = new src_class(), [modifiedBundlerChain] = await context.hooks.modifyBundlerChain.callChain({
2275
3307
  environment: utils.environment.name,
2276
3308
  args: [
2277
3309
  bundlerChain,
2278
3310
  utils
2279
3311
  ]
2280
3312
  });
2281
- if (null == (_utils_environment_config_tools = utils.environment.config.tools) ? void 0 : _utils_environment_config_tools.bundlerChain) for (let item of castArray(utils.environment.config.tools.bundlerChain))await item(modifiedBundlerChain, utils);
3313
+ if (null == (_utils_environment_config_tools = utils.environment.config.tools) ? void 0 : _utils_environment_config_tools.bundlerChain) for (let item of helpers_castArray(utils.environment.config.tools.bundlerChain))await item(modifiedBundlerChain, utils);
2282
3314
  return logger.debug('modify bundler chain done'), modifiedBundlerChain;
2283
3315
  }
2284
3316
  let configChain_CHAIN_ID = {
@@ -2397,19 +3429,19 @@ async function getConfigUtils(config, chainUtils) {
2397
3429
  ...chainUtils,
2398
3430
  mergeConfig: webpack_merge_dist.merge,
2399
3431
  addRules (rules) {
2400
- let ruleArr = castArray(rules);
3432
+ let ruleArr = helpers_castArray(rules);
2401
3433
  config.module || (config.module = {}), config.module.rules || (config.module.rules = []), config.module.rules.unshift(...ruleArr);
2402
3434
  },
2403
3435
  appendRules (rules) {
2404
- let ruleArr = castArray(rules);
3436
+ let ruleArr = helpers_castArray(rules);
2405
3437
  config.module || (config.module = {}), config.module.rules || (config.module.rules = []), config.module.rules.push(...ruleArr);
2406
3438
  },
2407
3439
  prependPlugins (plugins) {
2408
- let pluginArr = castArray(plugins);
3440
+ let pluginArr = helpers_castArray(plugins);
2409
3441
  config.plugins || (config.plugins = []), config.plugins.unshift(...pluginArr);
2410
3442
  },
2411
3443
  appendPlugins (plugins) {
2412
- let pluginArr = castArray(plugins);
3444
+ let pluginArr = helpers_castArray(plugins);
2413
3445
  config.plugins || (config.plugins = []), config.plugins.push(...pluginArr);
2414
3446
  },
2415
3447
  removePlugin (pluginName) {
@@ -2421,7 +3453,7 @@ function getChainUtils(target, environment) {
2421
3453
  return {
2422
3454
  rspack: rspack_rspack,
2423
3455
  environment,
2424
- env: process.env.NODE_ENV,
3456
+ env: process.env.NODE_ENV || '',
2425
3457
  target,
2426
3458
  isDev: 'development' === environment.config.mode,
2427
3459
  isProd: 'production' === environment.config.mode,
@@ -2452,6 +3484,14 @@ async function generateRspackConfig({ target, context, environment }) {
2452
3484
  }
2453
3485
  return config.devServer && logger.warn(`${picocolors.dim('[rsbuild:config]')} Find invalid Rspack config: "${picocolors.yellow('devServer')}". Note that Rspack's "devServer" config is not supported by Rsbuild. You can use Rsbuild's "dev" config to configure the Rsbuild dev server.`), rspackConfig;
2454
3486
  }
3487
+ let allowedEnvironmentDevKeys = [
3488
+ 'hmr',
3489
+ 'liveReload',
3490
+ 'writeToDisk',
3491
+ 'assetPrefix',
3492
+ 'progressBar',
3493
+ 'lazyCompilation'
3494
+ ];
2455
3495
  async function modifyRsbuildConfig(context) {
2456
3496
  var _context_config_plugins, _modified_plugins;
2457
3497
  logger.debug('modify Rsbuild config');
@@ -2485,7 +3525,7 @@ async function initRsbuildConfig({ context, pluginManager }) {
2485
3525
  ...createDefaultConfig(),
2486
3526
  mode: (()=>{
2487
3527
  if (config.mode) return config.mode;
2488
- let nodeEnv = process.env.NODE_ENV;
3528
+ let nodeEnv = process.env.NODE_ENV || '';
2489
3529
  return 'production' === nodeEnv || 'development' === nodeEnv ? nodeEnv : 'none';
2490
3530
  })()
2491
3531
  }, config), { watchFiles } = mergedConfig.dev;
@@ -2518,13 +3558,7 @@ async function initRsbuildConfig({ context, pluginManager }) {
2518
3558
  applyEnvironmentDefaultConfig({
2519
3559
  ...mergeRsbuildConfig({
2520
3560
  ...rsbuildSharedConfig,
2521
- dev: pick(dev, [
2522
- 'writeToDisk',
2523
- 'hmr',
2524
- 'assetPrefix',
2525
- 'progressBar',
2526
- 'lazyCompilation'
2527
- ])
3561
+ dev: pick(dev, allowedEnvironmentDevKeys)
2528
3562
  }, config)
2529
3563
  })
2530
3564
  ]));
@@ -2536,24 +3570,18 @@ async function initRsbuildConfig({ context, pluginManager }) {
2536
3570
  return {
2537
3571
  [defaultEnvironmentName]: applyEnvironmentDefaultConfig({
2538
3572
  ...rsbuildSharedConfig,
2539
- dev: pick(dev, [
2540
- 'hmr',
2541
- 'assetPrefix',
2542
- 'progressBar',
2543
- 'lazyCompilation',
2544
- 'writeToDisk'
2545
- ])
3573
+ dev: pick(dev, allowedEnvironmentDevKeys)
2546
3574
  })
2547
3575
  };
2548
- })(normalizedBaseConfig, context.rootPath, context.specifiedEnvironments), { dev: { hmr: _hmr, assetPrefix: _assetPrefix, progressBar: _progressBar, lazyCompilation: _lazyCompilation, writeToDisk: _writeToDisk, ...rsbuildSharedDev }, server } = normalizedBaseConfig, tsconfigPaths = new Set();
3576
+ })(normalizedBaseConfig, context.rootPath, context.specifiedEnvironments), tsconfigPaths = new Set();
2549
3577
  for (let [name, config] of Object.entries(mergedEnvironments)){
2550
3578
  let environmentConfig = await modifyEnvironmentConfig(context, config, name), normalizedEnvironmentConfig = {
2551
3579
  ...environmentConfig,
2552
3580
  dev: {
2553
- ...environmentConfig.dev,
2554
- ...rsbuildSharedDev
3581
+ ...normalizedBaseConfig.dev,
3582
+ ...environmentConfig.dev
2555
3583
  },
2556
- server
3584
+ server: normalizedBaseConfig.server
2557
3585
  }, { tsconfigPath } = normalizedEnvironmentConfig.source;
2558
3586
  if (tsconfigPath) {
2559
3587
  let absoluteTsconfigPath = ensureAbsolutePath(context.rootPath, tsconfigPath);
@@ -2747,7 +3775,7 @@ let RSPACK_BUILD_ERROR = 'Rspack build failed.', build_build = async (initOption
2747
3775
  };
2748
3776
  var main = __webpack_require__("../../node_modules/.pnpm/dotenv-expand@12.0.2/node_modules/dotenv-expand/lib/main.js");
2749
3777
  let DOTENV_LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
2750
- function loadEnv({ cwd = process.cwd(), mode = process.env.NODE_ENV, prefixes = [
3778
+ function loadEnv({ cwd = process.cwd(), mode = process.env.NODE_ENV || '', prefixes = [
2751
3779
  'PUBLIC_'
2752
3780
  ], processEnv = process.env } = {}) {
2753
3781
  if ('local' === mode) throw Error(`${picocolors.dim('[rsbuild:loadEnv]')} ${picocolors.yellow('local')} cannot be used as a value for env mode, because ${picocolors.yellow('.env.local')} represents a temporary local file. Please use another value.`);
@@ -2792,7 +3820,7 @@ let chainStaticAssetRule = ({ emit, rule, maxSize, filename, assetType })=>{
2792
3820
  let generatorOptions = {
2793
3821
  filename
2794
3822
  };
2795
- !1 === emit && (generatorOptions.emit = !1), rule.oneOf(`${assetType}-asset-url`).type('asset/resource').resourceQuery(/^\?(__inline=false|url)$/).set('generator', generatorOptions), rule.oneOf(`${assetType}-asset-inline`).type('asset/inline').resourceQuery(INLINE_QUERY_REGEX), rule.oneOf(`${assetType}-asset-raw`).type('asset/source').resourceQuery(RAW_QUERY_REGEX), rule.oneOf(`${assetType}-asset`).type('asset').parser({
3823
+ emit || (generatorOptions.emit = !1), rule.oneOf(`${assetType}-asset-url`).type('asset/resource').resourceQuery(/^\?(__inline=false|url)$/).set('generator', generatorOptions), rule.oneOf(`${assetType}-asset-inline`).type('asset/inline').resourceQuery(INLINE_QUERY_REGEX), rule.oneOf(`${assetType}-asset-raw`).type('asset/source').resourceQuery(RAW_QUERY_REGEX), rule.oneOf(`${assetType}-asset`).type('asset').parser({
2796
3824
  dataUrlCondition: {
2797
3825
  maxSize
2798
3826
  }
@@ -2864,7 +3892,7 @@ let addTrailingSep = (dir)=>dir.endsWith(sep) ? dir : dir + sep, isStrictSubdir
2864
3892
  }, parseMinifyOptions = (config)=>{
2865
3893
  let isProd = 'production' === config.mode, { minify } = config.output;
2866
3894
  if ('boolean' == typeof minify) {
2867
- let shouldMinify = !0 === minify && isProd;
3895
+ let shouldMinify = minify && isProd;
2868
3896
  return {
2869
3897
  minifyJs: shouldMinify,
2870
3898
  minifyCss: shouldMinify
@@ -2916,12 +3944,12 @@ let getPostcssLoaderOptions = async ({ config, root, postcssrcCache })=>{
2916
3944
  config: config.tools.postcss,
2917
3945
  ctx: {
2918
3946
  addPlugins (plugins) {
2919
- extraPlugins.push(...castArray(plugins));
3947
+ extraPlugins.push(...helpers_castArray(plugins));
2920
3948
  }
2921
3949
  }
2922
3950
  });
2923
3951
  finalOptions.postcssOptions ||= {};
2924
- let updatePostcssOptions = (options)=>(options.plugins ||= [], extraPlugins.length && options.plugins.push(...extraPlugins), options.plugins = options.plugins.map((plugin)=>'function' == typeof plugin && !0 === plugin.postcss ? plugin() : plugin), options.config = !1, options), { postcssOptions } = finalOptions;
3952
+ let updatePostcssOptions = (options)=>(options.plugins ||= [], extraPlugins.length && options.plugins.push(...extraPlugins), options.plugins = options.plugins.map((plugin)=>'function' == typeof plugin && plugin.postcss ? plugin() : plugin), options.config = !1, options), { postcssOptions } = finalOptions;
2925
3953
  if ('function' == typeof postcssOptions) {
2926
3954
  let postcssOptionsWrapper = (loaderContext)=>{
2927
3955
  let options = postcssOptions(loaderContext);
@@ -2966,16 +3994,7 @@ async function printFileSizes(options, stats, rootPath, environmentName) {
2966
3994
  }, getAssets = async ()=>{
2967
3995
  let distPath = stats.compilation.outputOptions.path;
2968
3996
  if (!distPath) return [];
2969
- let filteredAssets = (stats.toJson({
2970
- all: !1,
2971
- assets: !0,
2972
- cachedAssets: !0,
2973
- groupAssetsByInfo: !1,
2974
- groupAssetsByPath: !1,
2975
- groupAssetsByChunk: !1,
2976
- groupAssetsByExtension: !1,
2977
- groupAssetsByEmitStatus: !1
2978
- }).assets || []).filter((asset)=>{
3997
+ let filteredAssets = getAssetsFromStats(stats).filter((asset)=>{
2979
3998
  let assetInfo = {
2980
3999
  name: asset.name,
2981
4000
  size: asset.size
@@ -3085,22 +4104,26 @@ let entryNameSymbol = Symbol('entryName'), VOID_TAGS = [
3085
4104
  }));
3086
4105
  class RsbuildHtmlPlugin {
3087
4106
  apply(compiler) {
3088
- let emitFavicon = async (compilation, favicon)=>{
4107
+ let emitFavicon = async ({ compilation, favicon, faviconDistPath })=>{
3089
4108
  let buffer, name = node_path.basename(favicon);
3090
4109
  if (compilation.assets[name]) return name;
3091
4110
  if (!compilation.inputFileSystem) return addCompilationError(compilation, `${picocolors.dim('[rsbuild:html]')} Failed to read the favicon file as ${picocolors.yellow('compilation.inputFileSystem')} is not available.`), null;
3092
- let filename = node_path.isAbsolute(favicon) ? favicon : node_path.join(compilation.compiler.context, favicon);
4111
+ let inputFilename = node_path.isAbsolute(favicon) ? favicon : node_path.join(compilation.compiler.context, favicon);
3093
4112
  try {
3094
- if (!(buffer = await external_node_util_promisify(compilation.inputFileSystem.readFile)(filename))) throw Error('Buffer is undefined');
4113
+ if (!(buffer = await external_node_util_promisify(compilation.inputFileSystem.readFile)(inputFilename))) throw Error('Buffer is undefined');
3095
4114
  } catch (error) {
3096
- return logger.debug(`read favicon error: ${error}`), addCompilationError(compilation, `${picocolors.dim('[rsbuild:html]')} Failed to read the favicon file at ${picocolors.yellow(filename)}.`), null;
4115
+ return logger.debug(`read favicon error: ${error}`), addCompilationError(compilation, `${picocolors.dim('[rsbuild:html]')} Failed to read the favicon file at ${picocolors.yellow(inputFilename)}.`), null;
3097
4116
  }
3098
- let source = new compiler.webpack.sources.RawSource(buffer, !1);
3099
- return compilation.emitAsset(name, source), name;
3100
- }, addFavicon = async (headTags, favicon, compilation, publicPath)=>{
4117
+ let source = new compiler.webpack.sources.RawSource(buffer, !1), outputFilename = node_path.posix.join(faviconDistPath, name);
4118
+ return compilation.emitAsset(outputFilename, source), outputFilename;
4119
+ }, addFavicon = async ({ headTags, favicon, faviconDistPath, compilation, publicPath })=>{
3101
4120
  let href = favicon;
3102
4121
  if (!isURL(favicon)) {
3103
- let name = await emitFavicon(compilation, favicon);
4122
+ let name = await emitFavicon({
4123
+ compilation,
4124
+ favicon,
4125
+ faviconDistPath
4126
+ });
3104
4127
  if (null === name) return;
3105
4128
  href = ensureAssetPrefix(name, publicPath);
3106
4129
  }
@@ -3124,7 +4147,7 @@ class RsbuildHtmlPlugin {
3124
4147
  hooks.alterAssetTagGroups.tapPromise(this.name, async (data)=>{
3125
4148
  let extraData = getExtraDataByPlugin(data.plugin);
3126
4149
  if (!extraData) return data;
3127
- let { headTags, bodyTags } = data, { favicon, context, tagConfig, entryName, environment, templateContent } = extraData;
4150
+ let { headTags, bodyTags } = data, { favicon, faviconDistPath, context, tagConfig, entryName, environment, templateContent } = extraData;
3128
4151
  if (!(templateContent && /<title/i.test(templateContent) && /<\/title/i.test(templateContent))) {
3129
4152
  var _data_plugin_options;
3130
4153
  ((headTags, title = '')=>{
@@ -3137,7 +4160,13 @@ class RsbuildHtmlPlugin {
3137
4160
  });
3138
4161
  })(headTags, null == (_data_plugin_options = data.plugin.options) ? void 0 : _data_plugin_options.title);
3139
4162
  }
3140
- favicon && await addFavicon(headTags, favicon, compilation, data.publicPath);
4163
+ favicon && await addFavicon({
4164
+ headTags,
4165
+ favicon,
4166
+ faviconDistPath,
4167
+ compilation,
4168
+ publicPath: data.publicPath
4169
+ });
3141
4170
  let tags = {
3142
4171
  headTags: headTags.map(formatBasicTag),
3143
4172
  bodyTags: bodyTags.map(formatBasicTag)
@@ -3652,10 +4681,10 @@ function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls
3652
4681
  }
3653
4682
  let message = '', maxNameLength = Math.max(...routes.map((r)=>r.entryName.length));
3654
4683
  return urls.forEach(({ label, url }, index)=>{
3655
- for (let r of (index > 0 && (message += '\n'), message += ` ${`\u{279C} ${label}`}\n`, routes))message += ` ${picocolors.dim('-')} ${picocolors.dim(r.entryName.padEnd(maxNameLength + 4))}${picocolors.cyan(normalizeUrl(`${url}${r.pathname}`))}\n`;
4684
+ for (let r of (index > 0 && (message += '\n'), message += ` \u{279C} ${label}\n`, routes))message += ` ${picocolors.dim('-')} ${picocolors.dim(r.entryName.padEnd(maxNameLength + 4))}${picocolors.cyan(normalizeUrl(`${url}${r.pathname}`))}\n`;
3656
4685
  }), message;
3657
4686
  }(urls, routes);
3658
- return !1 === trailingLineBreak && message.endsWith('\n') && (message = message.slice(0, -1)), logger.log(message), message;
4687
+ return !trailingLineBreak && message.endsWith('\n') && (message = message.slice(0, -1)), logger.log(message), message;
3659
4688
  }
3660
4689
  let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
3661
4690
  'string' == typeof port && (port = Number.parseInt(port, 10)), strictPort && (tryLimits = 1);
@@ -3756,7 +4785,9 @@ function getServerTerminator(server) {
3756
4785
  listened = !0;
3757
4786
  }), ()=>new Promise((resolve, reject)=>{
3758
4787
  for (let socket of pendingSockets)socket.destroy();
3759
- listened ? server.close((err)=>err ? reject(err) : resolve()) : resolve();
4788
+ listened ? server.close((err)=>{
4789
+ err ? reject(err) : resolve();
4790
+ }) : resolve();
3760
4791
  });
3761
4792
  }
3762
4793
  let supportedChromiumBrowsers = [
@@ -3820,7 +4851,7 @@ async function server_open_open({ https, port, routes, config, clearCache }) {
3820
4851
  } : Array.isArray(open) ? {
3821
4852
  targets: open
3822
4853
  } : {
3823
- targets: open.target ? castArray(open.target) : [],
4854
+ targets: open.target ? helpers_castArray(open.target) : [],
3824
4855
  before: open.before
3825
4856
  };
3826
4857
  })(config);
@@ -3929,8 +4960,8 @@ class HtmlResourceHintsPlugin {
3929
4960
  return chunks;
3930
4961
  }(compilation, options.type), sortedFilteredFiles = ((files, include, exclude)=>{
3931
4962
  let includeRegExp = [], excludeRegExp = [], includeFn = [], excludeFn = [];
3932
- if (include) for (let item of castArray(include))'string' == typeof item ? includeRegExp.push(new RegExp(item)) : isFunction(item) ? includeFn.push(item) : includeRegExp.push(item);
3933
- if (exclude) for (let item of castArray(exclude))'string' == typeof item ? excludeRegExp.push(new RegExp(item)) : isFunction(item) ? excludeFn.push(item) : excludeRegExp.push(item);
4963
+ if (include) for (let item of helpers_castArray(include))'string' == typeof item ? includeRegExp.push(new RegExp(item)) : isFunction(item) ? includeFn.push(item) : includeRegExp.push(item);
4964
+ if (exclude) for (let item of helpers_castArray(exclude))'string' == typeof item ? excludeRegExp.push(new RegExp(item)) : isFunction(item) ? excludeFn.push(item) : excludeRegExp.push(item);
3934
4965
  return files.filter((file)=>{
3935
4966
  let includeMatched = !1;
3936
4967
  for (let item of includeRegExp)item.test(file) && (includeMatched = !0);
@@ -4210,16 +5241,23 @@ async function getResolvedClientConfig(clientConfig, serverConfig) {
4210
5241
  port: serverConfig.port
4211
5242
  };
4212
5243
  }
4213
- let getCompilationMiddleware = async (compiler, options)=>{
4214
- let { default: rsbuildDevMiddleware } = await import("../compiled/rsbuild-dev-middleware/index.js"), { clientPaths, callbacks, devConfig, serverConfig } = options, resolvedClientConfig = await getResolvedClientConfig(devConfig.client, serverConfig);
5244
+ let compilationMiddleware_require = createRequire(import.meta.url), getCompilationMiddleware = async (compiler, options)=>{
5245
+ let { default: rsbuildDevMiddleware } = await import("../compiled/rsbuild-dev-middleware/index.js"), { callbacks, devConfig, serverConfig } = options, resolvedClientConfig = await getResolvedClientConfig(devConfig.client, serverConfig);
4215
5246
  return applyToCompiler(compiler, (compiler, index)=>{
4216
- var _Object_values_find;
4217
- let token = null == (_Object_values_find = Object.values(options.environments).find((env)=>env.index === index)) ? void 0 : _Object_values_find.webSocketToken;
4218
- token && (clientPaths && function({ compiler, clientPaths, devConfig, resolvedClientConfig, token }) {
4219
- if (((compiler)=>{
5247
+ let environment = Object.values(options.environments).find((env)=>env.index === index);
5248
+ if (!environment) return;
5249
+ let token = environment.webSocketToken;
5250
+ token && (!function({ config, compiler, devConfig, resolvedClientConfig, token }) {
5251
+ if (!((compiler)=>{
4220
5252
  let { target } = compiler.options;
4221
5253
  return !!target && (Array.isArray(target) ? target.includes('web') : 'web' === target);
4222
- })(compiler)) for (let clientPath of (new compiler.webpack.DefinePlugin({
5254
+ })(compiler)) return;
5255
+ let clientPaths = function(devConfig) {
5256
+ var _devConfig_client;
5257
+ let clientPaths = [];
5258
+ return (devConfig.hmr || devConfig.liveReload) && (hmrClientPath || (hmrClientPath = compilationMiddleware_require.resolve('@rsbuild/core/client/hmr')), clientPaths.push(hmrClientPath), (null == (_devConfig_client = devConfig.client) ? void 0 : _devConfig_client.overlay) && (overlayClientPath || (overlayClientPath = compilationMiddleware_require.resolve('@rsbuild/core/client/overlay')), clientPaths.push(overlayClientPath))), clientPaths;
5259
+ }(config.dev);
5260
+ if (clientPaths.length) for (let clientPath of (new compiler.webpack.DefinePlugin({
4223
5261
  RSBUILD_WEB_SOCKET_TOKEN: JSON.stringify(token),
4224
5262
  RSBUILD_CLIENT_CONFIG: JSON.stringify(devConfig.client),
4225
5263
  RSBUILD_RESOLVED_CLIENT_CONFIG: JSON.stringify(resolvedClientConfig),
@@ -4229,10 +5267,10 @@ let getCompilationMiddleware = async (compiler, options)=>{
4229
5267
  }).apply(compiler);
4230
5268
  }({
4231
5269
  compiler,
4232
- clientPaths,
4233
5270
  devConfig,
4234
5271
  resolvedClientConfig,
4235
- token
5272
+ token,
5273
+ config: environment.config
4236
5274
  }), (({ compiler, token, callbacks: { onDone, onInvalid } })=>{
4237
5275
  if (((compiler)=>{
4238
5276
  let { target } = compiler.options;
@@ -4330,9 +5368,6 @@ class SocketServer {
4330
5368
  socket && this.send(socket, messageStr);
4331
5369
  } else for (let socket of this.sockets.values())this.send(socket, messageStr);
4332
5370
  }
4333
- singleWrite(socket, message) {
4334
- this.send(socket, JSON.stringify(message));
4335
- }
4336
5371
  async close() {
4337
5372
  for (let socket of (this.clearHeartbeatTimer(), this.wsServer.removeAllListeners(), this.wsServer.clients))socket.terminate();
4338
5373
  for (let socket of this.sockets.values())socket.close();
@@ -4347,8 +5382,6 @@ class SocketServer {
4347
5382
  socket.isAlive = !0;
4348
5383
  }), this.sockets.set(token, socket), socket.on('close', ()=>{
4349
5384
  this.sockets.delete(token);
4350
- }), (this.options.hmr || this.options.liveReload) && this.singleWrite(socket, {
4351
- type: 'hot'
4352
5385
  }), this.stats && this.sendStats({
4353
5386
  force: !0,
4354
5387
  token
@@ -4387,13 +5420,13 @@ class SocketServer {
4387
5420
  let initialChunks = this.initialChunks[token], shouldReload = !!statsJson.entrypoints && !!initialChunks && !(initialChunks.size === newInitialChunks.size && [
4388
5421
  ...initialChunks
4389
5422
  ].every((value)=>newInitialChunks.has(value)));
4390
- if (this.initialChunks[token] = newInitialChunks, shouldReload) return this.sockWrite({
5423
+ if (this.initialChunks[token] = newInitialChunks, shouldReload) return void this.sockWrite({
4391
5424
  type: 'static-changed'
4392
5425
  }, token);
4393
- if (!force && statsJson && !statsJson.errorsCount && statsJson.assets && statsJson.assets.every((asset)=>!asset.emitted)) return this.sockWrite({
5426
+ if (!force && statsJson && !statsJson.errorsCount && statsJson.assets && statsJson.assets.every((asset)=>!asset.emitted)) return void this.sockWrite({
4394
5427
  type: 'ok'
4395
5428
  }, token);
4396
- if (this.sockWrite({
5429
+ if (statsJson.hash && this.sockWrite({
4397
5430
  type: 'hash',
4398
5431
  data: statsJson.hash
4399
5432
  }, token), statsJson.errorsCount) {
@@ -4401,7 +5434,7 @@ class SocketServer {
4401
5434
  errors: getAllStatsErrors(statsJson),
4402
5435
  warnings: []
4403
5436
  });
4404
- return this.sockWrite({
5437
+ this.sockWrite({
4405
5438
  type: 'errors',
4406
5439
  data: {
4407
5440
  text: formattedErrors,
@@ -4561,20 +5594,22 @@ class SocketServer {
4561
5594
  }(formattedErrors, root)
4562
5595
  }
4563
5596
  }, token);
5597
+ return;
4564
5598
  }
4565
5599
  if (statsJson.warningsCount) {
4566
5600
  let { warnings: formattedWarnings } = formatStatsMessages({
4567
5601
  warnings: getAllStatsWarnings(statsJson),
4568
5602
  errors: []
4569
5603
  });
4570
- return this.sockWrite({
5604
+ this.sockWrite({
4571
5605
  type: 'warnings',
4572
5606
  data: {
4573
5607
  text: formattedWarnings
4574
5608
  }
4575
5609
  }, token);
5610
+ return;
4576
5611
  }
4577
- return this.sockWrite({
5612
+ this.sockWrite({
4578
5613
  type: 'ok'
4579
5614
  }, token);
4580
5615
  }
@@ -4603,7 +5638,6 @@ function compilationManager_define_property(obj, key, value) {
4603
5638
  writable: !0
4604
5639
  }) : obj[key] = value, obj;
4605
5640
  }
4606
- let compilationManager_require = createRequire(import.meta.url);
4607
5641
  class CompilationManager {
4608
5642
  async init() {
4609
5643
  await this.setupCompilationMiddleware(), await this.socketServer.prepare();
@@ -4625,25 +5659,17 @@ class CompilationManager {
4625
5659
  });
4626
5660
  }
4627
5661
  async setupCompilationMiddleware() {
4628
- let { devConfig, serverConfig, publicPaths, environments } = this, clientPaths = function(devConfig) {
4629
- var _devConfig_client;
4630
- let clientPaths = [];
4631
- return (devConfig.hmr || devConfig.liveReload) && (clientPaths.push(compilationManager_require.resolve('@rsbuild/core/client/hmr')), (null == (_devConfig_client = devConfig.client) ? void 0 : _devConfig_client.overlay) && clientPaths.push(`${compilationManager_require.resolve('@rsbuild/core/client/overlay')}`)), clientPaths;
4632
- }(devConfig), middleware = await getCompilationMiddleware(this.compiler, {
5662
+ let { devConfig, serverConfig, publicPaths, environments } = this, middleware = await getCompilationMiddleware(this.compiler, {
4633
5663
  callbacks: {
4634
5664
  onInvalid: (token, fileName)=>{
4635
5665
  if ('string' == typeof fileName && fileName.endsWith('.html')) return void this.socketServer.sockWrite({
4636
5666
  type: 'static-changed'
4637
5667
  }, token);
4638
- this.socketServer.sockWrite({
4639
- type: 'invalid'
4640
- }, token);
4641
5668
  },
4642
5669
  onDone: (token, stats)=>{
4643
5670
  this.socketServer.updateStats(stats, token);
4644
5671
  }
4645
5672
  },
4646
- clientPaths,
4647
5673
  devConfig,
4648
5674
  serverConfig,
4649
5675
  environments
@@ -4673,10 +5699,10 @@ class CompilationManager {
4673
5699
  }
4674
5700
  let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xml/i, gzipMiddleware = ({ filter, level = node_zlib.constants.Z_BEST_SPEED } = {})=>(req, res, next)=>{
4675
5701
  let gzip, writeHeadStatus;
4676
- if (filter && !1 === filter(req, res)) return void next();
5702
+ if (filter && !filter(req, res)) return void next();
4677
5703
  let accept = req.headers['accept-encoding'], encoding = 'string' == typeof accept && ENCODING_REGEX.test(accept);
4678
5704
  if ('HEAD' === req.method || !encoding) return void next();
4679
- let started = !1, { end, write, on, writeHead } = res, listeners = [], start = ()=>{
5705
+ let started = !1, on = res.on.bind(res), end = res.end.bind(res), write = res.write.bind(res), writeHead = res.writeHead.bind(res), listeners = [], start = ()=>{
4680
5706
  if (!started) {
4681
5707
  if (started = !0, ((res)=>{
4682
5708
  if (res.getHeader('Content-Encoding')) return !1;
@@ -4687,22 +5713,77 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
4687
5713
  })(res)) for (let listener of (res.setHeader('Content-Encoding', 'gzip'), res.removeHeader('Content-Length'), (gzip = node_zlib.createGzip({
4688
5714
  level
4689
5715
  })).on('data', (chunk)=>{
4690
- !1 === write.call(res, chunk) && gzip.pause();
4691
- }), on.call(res, 'drain', ()=>gzip.resume()), gzip.on('end', ()=>{
4692
- end.call(res);
5716
+ write(chunk) || gzip.pause();
5717
+ }), on('drain', ()=>gzip.resume()), gzip.on('end', ()=>{
5718
+ end();
4693
5719
  }), listeners))gzip.on.apply(gzip, listener);
4694
5720
  else for (let listener of listeners)on.apply(res, listener);
4695
- writeHead.call(res, writeHeadStatus ?? res.statusCode);
5721
+ writeHead(writeHeadStatus ?? res.statusCode);
4696
5722
  }
4697
5723
  };
4698
5724
  res.writeHead = (status, reason, headers)=>{
4699
5725
  if (reason) for (let [key, value] of Object.entries(headers || reason))res.setHeader(key, value);
4700
5726
  return writeHeadStatus = status, res;
4701
- }, res.write = (...args)=>(start(), gzip ? gzip.write(...args) : write.apply(res, args)), res.end = (...args)=>(start(), gzip ? gzip.end(...args) : end.apply(res, args)), res.on = (type, listener)=>(started ? gzip && 'drain' === type ? gzip.on(type, listener) : on.call(res, type, listener) : listeners.push([
5727
+ }, res.write = (...args)=>(start(), gzip ? gzip.write(...args) : write.apply(res, args)), res.end = (...args)=>(start(), gzip ? gzip.end(...args) : end.apply(res, args)), res.on = (type, listener)=>(started ? gzip && 'drain' === type ? gzip.on(type, listener) : on(type, listener) : listeners.push([
4702
5728
  type,
4703
5729
  listener
4704
5730
  ]), res), next();
4705
- }, faviconFallbackMiddleware = (req, res, next)=>{
5731
+ };
5732
+ function historyApiFallbackMiddleware(options = {}) {
5733
+ return (req, _res, next)=>{
5734
+ let rewriteTarget, { headers } = req;
5735
+ if (!req.url) return void next();
5736
+ if ('GET' !== req.method && 'HEAD' !== req.method) {
5737
+ logger.debug('Not rewriting', req.method, req.url, 'because the method is not GET or HEAD.'), next();
5738
+ return;
5739
+ }
5740
+ if (!headers || 'string' != typeof headers.accept) {
5741
+ logger.debug('Not rewriting', req.method, req.url, 'because the client did not send an HTTP accept header.'), next();
5742
+ return;
5743
+ }
5744
+ if (0 === headers.accept.indexOf('application/json')) {
5745
+ logger.debug('Not rewriting', req.method, req.url, 'because the client prefers JSON.'), next();
5746
+ return;
5747
+ }
5748
+ let rewrites = options.rewrites || [], htmlAcceptHeaders = options.htmlAcceptHeaders || [
5749
+ 'text/html',
5750
+ '*/*'
5751
+ ], { accept } = headers;
5752
+ if (!htmlAcceptHeaders.some((item)=>accept.includes(item))) {
5753
+ logger.debug('Not rewriting', req.method, req.url, 'because the client does not accept HTML.'), next();
5754
+ return;
5755
+ }
5756
+ let parsedUrl = function(req) {
5757
+ let proto = req.headers['x-forwarded-proto'] || 'http', host = req.headers['x-forwarded-host'] || req.headers.host || 'localhost';
5758
+ try {
5759
+ return new external_node_url_URL(req.url || '/', `${proto}://${host}`);
5760
+ } catch {
5761
+ return null;
5762
+ }
5763
+ }(req);
5764
+ if (null === parsedUrl) return void next();
5765
+ for (let rewrite of rewrites){
5766
+ var _parsedUrl_pathname;
5767
+ let match = null == (_parsedUrl_pathname = parsedUrl.pathname) ? void 0 : _parsedUrl_pathname.match(rewrite.from);
5768
+ if (!match) continue;
5769
+ let rule = rewrite.to;
5770
+ '/' !== (rewriteTarget = 'string' == typeof rule ? rule : rule({
5771
+ parsedUrl,
5772
+ match,
5773
+ request: req
5774
+ })).charAt(0) && logger.debug('We recommend using an absolute path for the rewrite target.', 'Received a non-absolute rewrite target', rewriteTarget, 'for URL', req.url), logger.debug('Rewriting', req.method, req.url, 'to', rewriteTarget), req.url = rewriteTarget, next();
5775
+ return;
5776
+ }
5777
+ let { pathname } = parsedUrl;
5778
+ if (pathname && pathname.lastIndexOf('.') > pathname.lastIndexOf('/') && !0 !== options.disableDotRule) {
5779
+ logger.debug('Not rewriting', req.method, req.url, 'because the path includes a dot (.) character.'), next();
5780
+ return;
5781
+ }
5782
+ let index = options.index || '/index.html';
5783
+ logger.debug('Rewriting', req.method, req.url, 'to', index), req.url = index, next();
5784
+ };
5785
+ }
5786
+ let faviconFallbackMiddleware = (req, res, next)=>{
4706
5787
  '/favicon.ico' === req.url ? (res.statusCode = 204, res.end()) : next();
4707
5788
  }, getRequestLoggerMiddleware = async ()=>{
4708
5789
  let { default: onFinished } = await import("../compiled/on-finished/index.js");
@@ -4732,7 +5813,10 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
4732
5813
  }, postfixRE = /[?#].*$/, getUrlPathname = (url)=>url.replace(postfixRE, ''), getBaseMiddleware = ({ base })=>async (req, res, next)=>{
4733
5814
  var _req_headers_accept;
4734
5815
  let url = req.url, pathname = getUrlPathname(url);
4735
- if (pathname.startsWith(base)) return req.url = stripBase(url, base), next();
5816
+ if (pathname.startsWith(base)) {
5817
+ req.url = stripBase(url, base), next();
5818
+ return;
5819
+ }
4736
5820
  let redirectPath = addTrailingSlash(url) !== base ? joinUrlSegments(base, url) : base;
4737
5821
  if ('/' === pathname || '/index.html' === pathname) {
4738
5822
  res.writeHead(302, {
@@ -4815,10 +5899,10 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
4815
5899
  '/__open-in-editor',
4816
5900
  launchEditorMiddleware()
4817
5901
  ]), middlewares.push((({ environments })=>async (req, res, next)=>{
4818
- if ('/rsbuild-dev-server' === getUrlPathname(req.url)) {
4819
- res.writeHead(200, {
4820
- 'Content-Type': 'text/html; charset=utf-8'
4821
- }), res.write(`<!DOCTYPE html>
5902
+ if ('/rsbuild-dev-server' !== getUrlPathname(req.url)) return void next();
5903
+ res.writeHead(200, {
5904
+ 'Content-Type': 'text/html; charset=utf-8'
5905
+ }), res.write(`<!DOCTYPE html>
4822
5906
  <html>
4823
5907
  <head>
4824
5908
  <meta charset="utf-8"/>
@@ -4861,35 +5945,35 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
4861
5945
  <h1>Assets Report</h1>
4862
5946
  </body>
4863
5947
  </html>`);
4864
- try {
4865
- for(let key in environments){
4866
- let list = [];
4867
- res.write(`<h2>Environment: ${key}</h2>`);
4868
- let environment = environments[key], { assets = [] } = (await environment.getStats()).toJson();
4869
- for (let asset of (res.write('<ul>'), assets))list.push(`<li><a target="_blank" href="${null == asset ? void 0 : asset.name}">${null == asset ? void 0 : asset.name}</a></li>`);
4870
- res.write(null == list ? void 0 : list.join('')), res.write('</ul>');
4871
- }
4872
- res.end('</body></html>');
4873
- } catch (err) {
4874
- logger.error(err), res.writeHead(500), res.end('Failed to list the files');
5948
+ try {
5949
+ for(let key in environments){
5950
+ res.write(`<h2>Environment: ${key}</h2>`);
5951
+ let list = [], environment = environments[key], stats = await environment.getStats(), assets = getAssetsFromStats(stats);
5952
+ for (let asset of (res.write('<ul>'), assets))list.push(`<li><a target="_blank" href="${null == asset ? void 0 : asset.name}">${null == asset ? void 0 : asset.name}</a></li>`);
5953
+ res.write(null == list ? void 0 : list.join('')), res.write('</ul>');
4875
5954
  }
4876
- } else next();
5955
+ res.end('</body></html>');
5956
+ } catch (err) {
5957
+ logger.error(err), res.writeHead(500), res.end('Failed to list the files');
5958
+ }
4877
5959
  })({
4878
5960
  environments: devServerAPI.environments
4879
5961
  })), compilationManager && (middlewares.push(compilationManager.middleware), upgradeEvents.push(compilationManager.socketServer.upgrade), middlewares.push((req, res, next)=>{
4880
5962
  var _req_url;
4881
5963
  (null == (_req_url = req.url) ? void 0 : _req_url.endsWith('.hot-update.json')) && 'OPTIONS' !== req.method ? (res.statusCode = 404, res.end()) : next();
4882
5964
  })), compilationManager && middlewares.push((({ distPath, compilationManager })=>async (req, res, next)=>{
4883
- if (!maybeHTMLRequest(req)) return next();
4884
- let pathname = getUrlPathname(req.url), rewrite = (newUrl)=>(req.url = newUrl, compilationManager.middleware(req, res, (...args)=>{
5965
+ if (!maybeHTMLRequest(req)) return void next();
5966
+ let pathname = getUrlPathname(req.url), rewrite = (newUrl)=>{
5967
+ req.url = newUrl, compilationManager.middleware(req, res, (...args)=>{
4885
5968
  next(...args);
4886
- }));
5969
+ });
5970
+ };
4887
5971
  if (pathname.endsWith('/')) {
4888
5972
  let newUrl = `${pathname}index.html`, filePath = node_path.join(distPath, newUrl);
4889
- if (await middlewares_isFileExists(filePath, compilationManager.outputFileSystem)) return rewrite(newUrl);
5973
+ if (await middlewares_isFileExists(filePath, compilationManager.outputFileSystem)) return void rewrite(newUrl);
4890
5974
  } else if (!node_path.extname(pathname)) {
4891
5975
  let newUrl = `${pathname}.html`, filePath = node_path.join(distPath, newUrl);
4892
- if (await middlewares_isFileExists(filePath, compilationManager.outputFileSystem)) return rewrite(newUrl);
5976
+ if (await middlewares_isFileExists(filePath, compilationManager.outputFileSystem)) return void rewrite(newUrl);
4893
5977
  }
4894
5978
  next();
4895
5979
  })({
@@ -4903,23 +5987,22 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
4903
5987
  middlewares.push(assetMiddleware);
4904
5988
  }
4905
5989
  for (let callback of postCallbacks)callback();
4906
- if (compilationManager && middlewares.push((({ htmlFallback, distPath, compilationManager })=>async (req, res, next)=>{
4907
- if (!maybeHTMLRequest(req) || '/favicon.ico' === req.url || 'index' !== htmlFallback) return next();
5990
+ return compilationManager && middlewares.push((({ htmlFallback, distPath, compilationManager })=>async (req, res, next)=>{
5991
+ if (!maybeHTMLRequest(req) || '/favicon.ico' === req.url || 'index' !== htmlFallback) return void next();
4908
5992
  let filePath = node_path.join(distPath, 'index.html');
4909
5993
  if (await middlewares_isFileExists(filePath, compilationManager.outputFileSystem)) {
4910
5994
  let newUrl = '/index.html';
4911
- return 'verbose' === logger.level && logger.debug(`${req.method} ${picocolors.gray(`${req.url} ${picocolors.yellow('fallback')} to ${newUrl}`)}`), req.url = newUrl, compilationManager.middleware(req, res, (...args)=>next(...args));
5995
+ 'verbose' === logger.level && logger.debug(`${req.method} ${picocolors.gray(`${req.url} ${picocolors.yellow('fallback')} to ${newUrl}`)}`), req.url = newUrl, compilationManager.middleware(req, res, (...args)=>{
5996
+ next(...args);
5997
+ });
5998
+ return;
4912
5999
  }
4913
6000
  next();
4914
6001
  })({
4915
6002
  compilationManager,
4916
6003
  distPath: context.distPath,
4917
6004
  htmlFallback: server.htmlFallback
4918
- })), server.historyApiFallback) {
4919
- let { default: connectHistoryApiFallback } = await import("../compiled/connect-history-api-fallback/index.js"), historyApiFallbackMiddleware = connectHistoryApiFallback(!0 === server.historyApiFallback ? {} : server.historyApiFallback);
4920
- middlewares.push(historyApiFallbackMiddleware), (null == compilationManager ? void 0 : compilationManager.middleware) && middlewares.push(compilationManager.middleware);
4921
- }
4922
- return middlewares.push(faviconFallbackMiddleware), {
6005
+ })), server.historyApiFallback && (middlewares.push(historyApiFallbackMiddleware(!0 === server.historyApiFallback ? {} : server.historyApiFallback)), (null == compilationManager ? void 0 : compilationManager.middleware) && middlewares.push(compilationManager.middleware)), middlewares.push(faviconFallbackMiddleware), {
4923
6006
  onUpgrade: (...args)=>{
4924
6007
  for (let cb of upgradeEvents)cb(...args);
4925
6008
  }
@@ -4932,7 +6015,7 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
4932
6015
  'sockWrite',
4933
6016
  'environments'
4934
6017
  ]), before = [], after = [];
4935
- for (let handler of castArray(setupMiddlewares))handler({
6018
+ for (let handler of helpers_castArray(setupMiddlewares))handler({
4936
6019
  unshift: (...handlers)=>before.unshift(...handlers),
4937
6020
  push: (...handlers)=>after.push(...handlers)
4938
6021
  }, serverOptions);
@@ -4961,12 +6044,12 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
4961
6044
  'default',
4962
6045
  ...Object.keys(something)
4963
6046
  ])
4964
- ], m = new SyntheticModule(exports, ()=>{
4965
- for (let name of exports)m.setExport(name, 'default' === name ? something : something[name]);
6047
+ ], syntheticModule = new SyntheticModule(exports, ()=>{
6048
+ for (let name of exports)syntheticModule.setExport(name, 'default' === name ? something : something[name]);
4966
6049
  }, {
4967
6050
  context
4968
6051
  });
4969
- return unlinked || (await m.link(()=>{}), m.instantiate && m.instantiate(), await m.evaluate()), m;
6052
+ return unlinked || (await syntheticModule.link(()=>{}), await syntheticModule.evaluate()), syntheticModule;
4970
6053
  };
4971
6054
  function basic_define_property(obj, key, value) {
4972
6055
  return key in obj ? Object.defineProperty(obj, key, {
@@ -5123,16 +6206,13 @@ class EsmRunner extends CommonJsRunner {
5123
6206
  initializeImportMeta: (meta, _)=>{
5124
6207
  meta.url = pathToFileURL(file.path).href;
5125
6208
  },
5126
- importModuleDynamically: async (specifier, module)=>{
5127
- let result = await _require(node_path.dirname(file.path), specifier, {
6209
+ importModuleDynamically: async (specifier, module)=>asModule(await _require(node_path.dirname(file.path), specifier, {
5128
6210
  esmMode: type_EsmMode.Evaluated
5129
- });
5130
- return await asModule(result, module.context);
5131
- }
6211
+ }), module.context)
5132
6212
  }), esmCache.set(file.path, esm)), context.esmMode === type_EsmMode.Unlinked) ? esm : (async ()=>{
5133
- if (await esm.link(async (specifier, referencingModule)=>await asModule(await _require(node_path.dirname(referencingModule.identifier ? referencingModule.identifier.slice(esmIdentifier.length + 1) : fileURLToPath(referencingModule.url)), specifier, {
6213
+ if (await esm.link(async (specifier, referencingModule)=>asModule(await _require(node_path.dirname(referencingModule.identifier ? referencingModule.identifier.slice(esmIdentifier.length + 1) : fileURLToPath(referencingModule.url)), specifier, {
5134
6214
  esmMode: type_EsmMode.Unlinked
5135
- }), referencingModule.context, !0)), esm.instantiate && esm.instantiate(), await esm.evaluate(), context.esmMode === type_EsmMode.Evaluated) return esm;
6215
+ }), referencingModule.context, !0)), await esm.evaluate(), context.esmMode === type_EsmMode.Evaluated) return esm;
5136
6216
  let ns = esm.namespace;
5137
6217
  return ns.default && ns.default instanceof Promise ? ns.default : ns;
5138
6218
  })();
@@ -5264,7 +6344,7 @@ async function watchDevFiles(devConfig, compilationManager, root) {
5264
6344
  let { watchFiles } = devConfig;
5265
6345
  if (!watchFiles) return;
5266
6346
  let watchers = [];
5267
- for (let { paths, options, type } of castArray(watchFiles)){
6347
+ for (let { paths, options, type } of helpers_castArray(watchFiles)){
5268
6348
  let watchOptions = prepareWatchOptions(paths, options, type), watcher = await startWatchFiles(watchOptions, compilationManager, root);
5269
6349
  watcher && watchers.push(watcher);
5270
6350
  }
@@ -5564,13 +6644,9 @@ class RsbuildProdServer {
5564
6644
  ...'object' == typeof compress ? compress : void 0
5565
6645
  }));
5566
6646
  }
5567
- if (base && '/' !== base && this.middlewares.use(getBaseMiddleware({
6647
+ base && '/' !== base && this.middlewares.use(getBaseMiddleware({
5568
6648
  base
5569
- })), await this.applyStaticAssetMiddleware(), historyApiFallback) {
5570
- let { default: connectHistoryApiFallback } = await import("../compiled/connect-history-api-fallback/index.js"), historyApiFallbackMiddleware = connectHistoryApiFallback(!0 === historyApiFallback ? {} : historyApiFallback);
5571
- this.middlewares.use(historyApiFallbackMiddleware), await this.applyStaticAssetMiddleware();
5572
- }
5573
- this.middlewares.use(faviconFallbackMiddleware), this.middlewares.use(optionsFallbackMiddleware), this.middlewares.use(notFoundMiddleware);
6649
+ })), await this.applyStaticAssetMiddleware(), historyApiFallback && (this.middlewares.use(historyApiFallbackMiddleware(!0 === historyApiFallback ? {} : historyApiFallback)), await this.applyStaticAssetMiddleware()), this.middlewares.use(faviconFallbackMiddleware), this.middlewares.use(optionsFallbackMiddleware), this.middlewares.use(notFoundMiddleware);
5574
6650
  }
5575
6651
  async applyStaticAssetMiddleware() {
5576
6652
  let { output: { path, assetPrefixes }, serverConfig: { htmlFallback } } = this.options, { default: sirv } = await import("../compiled/sirv/index.js"), assetMiddleware = sirv(path, {
@@ -5717,7 +6793,7 @@ async function applyDefaultPlugins(pluginManager, context) {
5717
6793
  entryPoint.add(rest);
5718
6794
  } else entryPoint.add(item);
5719
6795
  };
5720
- preEntry.forEach(addEntry), injectCoreJsEntry && addEntry(createVirtualModule('import "core-js";')), castArray(entry[entryName]).forEach(addEntry);
6796
+ preEntry.forEach(addEntry), injectCoreJsEntry && addEntry(createVirtualModule('import "core-js";')), helpers_castArray(entry[entryName]).forEach(addEntry);
5721
6797
  }
5722
6798
  }), api.onBeforeCreateCompiler(({ bundlerConfigs })=>{
5723
6799
  if (bundlerConfigs.every((config)=>!config.entry)) throw Error(`${picocolors.dim('[rsbuild:config]')} Could not find any entry module, please make sure that ${picocolors.yellow('src/index.(ts|js|tsx|jsx|mts|cts|mjs|cjs)')} exists, or customize entry through the ${picocolors.yellow('source.entry')} configuration.`);
@@ -5795,7 +6871,7 @@ async function applyDefaultPlugins(pluginManager, context) {
5795
6871
  let { dev, output, server } = config, publicPath = DEFAULT_ASSET_PREFIX;
5796
6872
  if (isDev) {
5797
6873
  if ('string' == typeof dev.assetPrefix) publicPath = dev.assetPrefix;
5798
- else if (!0 === dev.assetPrefix) {
6874
+ else if (dev.assetPrefix) {
5799
6875
  let protocol = (null == (_context_devServer1 = context.devServer) ? void 0 : _context_devServer1.https) ? 'https' : 'http', hostname = (null == (_context_devServer2 = context.devServer) ? void 0 : _context_devServer2.hostname) || DEFAULT_DEV_HOST;
5800
6876
  publicPath = hostname === DEFAULT_DEV_HOST ? `${protocol}://localhost:<port>/` : `${protocol}://${hostname}:<port>/`, server.base && '/' !== server.base && (publicPath = urlJoin(publicPath, server.base));
5801
6877
  }
@@ -5882,7 +6958,7 @@ async function applyDefaultPlugins(pluginManager, context) {
5882
6958
  mergedAlias[pkgName] = pkgPath;
5883
6959
  }
5884
6960
  for (let name of Object.keys(mergedAlias)){
5885
- let formattedValues = castArray(mergedAlias[name]).map((value)=>'string' == typeof value && value.startsWith('.') ? ensureAbsolutePath(rootPath, value) : value);
6961
+ let formattedValues = helpers_castArray(mergedAlias[name]).map((value)=>'string' == typeof value && value.startsWith('.') ? ensureAbsolutePath(rootPath, value) : value);
5886
6962
  chain.resolve.alias.set(name, 1 === formattedValues.length ? formattedValues[0] : formattedValues);
5887
6963
  }
5888
6964
  }({
@@ -6076,11 +7152,12 @@ async function applyDefaultPlugins(pluginManager, context) {
6076
7152
  let extraData = {
6077
7153
  entryName,
6078
7154
  context: context,
6079
- environment
7155
+ environment,
7156
+ faviconDistPath: config.output.distPath.favicon
6080
7157
  };
6081
7158
  extraDataMap.set(entryName, extraData), templateContent && (extraData.templateContent = templateContent);
6082
7159
  let tagConfig = ((config)=>{
6083
- let tags = castArray(config.html.tags).filter(Boolean);
7160
+ let tags = helpers_castArray(config.html.tags).filter(Boolean);
6084
7161
  if (tags.length) return {
6085
7162
  append: !0,
6086
7163
  hash: !1,
@@ -6157,7 +7234,7 @@ async function applyDefaultPlugins(pluginManager, context) {
6157
7234
  }, async ({ compilation, environment, sources })=>{
6158
7235
  let { config } = environment, { appIcon } = config.html;
6159
7236
  if (!appIcon) return;
6160
- let distDir = config.output.distPath.image, manifestFile = appIcon.filename ?? 'manifest.webmanifest', publicPath = getPublicPathFromCompiler(compilation), icons = appIcon.icons.map((icon)=>((icon, distDir, publicPath)=>{
7237
+ let { lookup } = await import("../compiled/mrmime/index.js"), distDir = config.output.distPath.image, manifestFile = appIcon.filename ?? 'manifest.webmanifest', publicPath = getPublicPathFromCompiler(compilation), icons = appIcon.icons.map((icon)=>((icon, distDir, publicPath, lookup)=>{
6161
7238
  let { src, size } = icon, cached = iconFormatMap.get(src);
6162
7239
  if (cached) return cached;
6163
7240
  let sizes = `${size}x${size}`;
@@ -6181,7 +7258,7 @@ async function applyDefaultPlugins(pluginManager, context) {
6181
7258
  mimeType: lookup(absolutePath)
6182
7259
  };
6183
7260
  return iconFormatMap.set(src, formatted), formatted;
6184
- })(icon, distDir, publicPath)), tags = [];
7261
+ })(icon, distDir, publicPath, lookup)), tags = [];
6185
7262
  for (let icon of icons){
6186
7263
  if ('web-app-manifest' === icon.target && !appIcon.name) {
6187
7264
  addCompilationError(compilation, `${picocolors.dim('[rsbuild:app-icon]')} ${picocolors.yellow('"appIcon.name"')} is required when ${picocolors.yellow('"target"')} is ${picocolors.yellow('"web-app-manifest"')}.`);
@@ -6593,7 +7670,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
6593
7670
  let finalPluginImport = ((options)=>{
6594
7671
  if (!options) return [];
6595
7672
  let imports = [];
6596
- for (let item of castArray(options))isFunction(item) ? imports = item(imports) ?? imports : imports.push(item);
7673
+ for (let item of helpers_castArray(options))isFunction(item) ? imports = item(imports) ?? imports : imports.push(item);
6597
7674
  return imports;
6598
7675
  })(pluginImport);
6599
7676
  (null == finalPluginImport ? void 0 : finalPluginImport.length) && (swcConfig.rspackExperiments ??= {}, swcConfig.rspackExperiments.import ??= [], swcConfig.rspackExperiments.import.push(...finalPluginImport));
@@ -6610,7 +7687,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
6610
7687
  default:
6611
7688
  throw Error(`${picocolors.dim('[rsbuild:swc]')} Unknown decorators version: ${picocolors.yellow(version)}`);
6612
7689
  }
6613
- }(swcConfig, config), castArray(target).includes('web') || target.includes('web-worker')) {
7690
+ }(swcConfig, config), helpers_castArray(target).includes('web') || target.includes('web-worker')) {
6614
7691
  let polyfillMode = config.output.polyfill;
6615
7692
  if ('off' === polyfillMode) swcConfig.env.mode = void 0;
6616
7693
  else {
@@ -6831,7 +7908,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
6831
7908
  if (prefetch) {
6832
7909
  let options = !0 === prefetch ? {} : prefetch;
6833
7910
  excludes.length && (options.exclude = options.exclude ? [
6834
- ...castArray(options.exclude),
7911
+ ...helpers_castArray(options.exclude),
6835
7912
  ...excludes
6836
7913
  ] : excludes), chain.plugin(CHAIN_ID.PLUGIN.HTML_PREFETCH).use(HtmlResourceHintsPlugin, [
6837
7914
  options,
@@ -6842,7 +7919,7 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
6842
7919
  if (preload) {
6843
7920
  let options = !0 === preload ? {} : preload;
6844
7921
  excludes.length && (options.exclude = options.exclude ? [
6845
- ...castArray(options.exclude),
7922
+ ...helpers_castArray(options.exclude),
6846
7923
  ...excludes
6847
7924
  ] : excludes), chain.plugin(CHAIN_ID.PLUGIN.HTML_PRELOAD).use(HtmlResourceHintsPlugin, [
6848
7925
  options,
@@ -7174,7 +8251,7 @@ async function createRsbuild(options = {}) {
7174
8251
  ...envs.publicVars,
7175
8252
  ...config.source.define
7176
8253
  }, 0 !== envs.filePaths.length && (config.dev ||= {}, config.dev.watchFiles = [
7177
- ...config.dev.watchFiles ? castArray(config.dev.watchFiles) : [],
8254
+ ...config.dev.watchFiles ? helpers_castArray(config.dev.watchFiles) : [],
7178
8255
  {
7179
8256
  paths: envs.filePaths,
7180
8257
  type: 'reload-server'
@@ -7393,42 +8470,60 @@ async function createRsbuild(options = {}) {
7393
8470
  onAfterStartProdServer: hooks.onAfterStartProdServer.tap,
7394
8471
  onBeforeStartProdServer: hooks.onBeforeStartProdServer.tap,
7395
8472
  modifyRsbuildConfig: hooks.modifyRsbuildConfig.tap,
7396
- modifyHTML: (handler)=>hooks.modifyHTML.tapEnvironment({
8473
+ modifyHTML: (handler)=>{
8474
+ hooks.modifyHTML.tapEnvironment({
7397
8475
  environment,
7398
8476
  handler
7399
- }),
7400
- modifyHTMLTags: (handler)=>hooks.modifyHTMLTags.tapEnvironment({
8477
+ });
8478
+ },
8479
+ modifyHTMLTags: (handler)=>{
8480
+ hooks.modifyHTMLTags.tapEnvironment({
7401
8481
  environment,
7402
8482
  handler
7403
- }),
7404
- modifyBundlerChain: (handler)=>hooks.modifyBundlerChain.tapEnvironment({
8483
+ });
8484
+ },
8485
+ modifyBundlerChain: (handler)=>{
8486
+ hooks.modifyBundlerChain.tapEnvironment({
7405
8487
  environment,
7406
8488
  handler
7407
- }),
7408
- modifyRspackConfig: (handler)=>hooks.modifyRspackConfig.tapEnvironment({
8489
+ });
8490
+ },
8491
+ modifyRspackConfig: (handler)=>{
8492
+ hooks.modifyRspackConfig.tapEnvironment({
7409
8493
  environment,
7410
8494
  handler
7411
- }),
7412
- modifyWebpackChain: (handler)=>hooks.modifyWebpackChain.tapEnvironment({
8495
+ });
8496
+ },
8497
+ modifyWebpackChain: (handler)=>{
8498
+ hooks.modifyWebpackChain.tapEnvironment({
7413
8499
  environment,
7414
8500
  handler
7415
- }),
7416
- modifyWebpackConfig: (handler)=>hooks.modifyWebpackConfig.tapEnvironment({
8501
+ });
8502
+ },
8503
+ modifyWebpackConfig: (handler)=>{
8504
+ hooks.modifyWebpackConfig.tapEnvironment({
7417
8505
  environment,
7418
8506
  handler
7419
- }),
7420
- modifyEnvironmentConfig: (handler)=>hooks.modifyEnvironmentConfig.tapEnvironment({
8507
+ });
8508
+ },
8509
+ modifyEnvironmentConfig: (handler)=>{
8510
+ hooks.modifyEnvironmentConfig.tapEnvironment({
7421
8511
  environment,
7422
8512
  handler
7423
- }),
7424
- onAfterEnvironmentCompile: (handler)=>hooks.onAfterEnvironmentCompile.tapEnvironment({
8513
+ });
8514
+ },
8515
+ onAfterEnvironmentCompile: (handler)=>{
8516
+ hooks.onAfterEnvironmentCompile.tapEnvironment({
7425
8517
  environment,
7426
8518
  handler
7427
- }),
7428
- onBeforeEnvironmentCompile: (handler)=>hooks.onBeforeEnvironmentCompile.tapEnvironment({
8519
+ });
8520
+ },
8521
+ onBeforeEnvironmentCompile: (handler)=>{
8522
+ hooks.onBeforeEnvironmentCompile.tapEnvironment({
7429
8523
  environment,
7430
8524
  handler
7431
- })
8525
+ });
8526
+ }
7432
8527
  });
7433
8528
  }({
7434
8529
  context,
@@ -7469,7 +8564,7 @@ async function createRsbuild(options = {}) {
7469
8564
  return startProdServer(context, config, options);
7470
8565
  },
7471
8566
  startDevServer: (...args)=>(context.action = 'dev', process.env.NODE_ENV || setNodeEnv('development'), providerInstance.startDevServer(...args)),
7472
- createCompiler: (...args)=>(context.action || (context.action = 'development' === process.env.NODE_ENV ? 'dev' : 'build'), providerInstance.createCompiler(...args)),
8567
+ createCompiler: (...args)=>(context.action || (context.action = 'development' === (process.env.NODE_ENV || '') ? 'dev' : 'build'), providerInstance.createCompiler(...args)),
7473
8568
  createDevServer: (...args)=>(context.action = 'dev', process.env.NODE_ENV || setNodeEnv('development'), providerInstance.createDevServer(...args)),
7474
8569
  ...pick(pluginManager, [
7475
8570
  'addPlugins',
@@ -7573,7 +8668,7 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
7573
8668
  throw logger.error(`Failed to load file with jiti: ${picocolors.dim(configFilePath)}`), err;
7574
8669
  }
7575
8670
  if ('function' == typeof configExport) {
7576
- let command = process.argv[2], nodeEnv = process.env.NODE_ENV, result = await configExport({
8671
+ let command = process.argv[2], nodeEnv = process.env.NODE_ENV || '', result = await configExport({
7577
8672
  env: nodeEnv,
7578
8673
  command,
7579
8674
  envMode: envMode || nodeEnv,
@@ -7600,17 +8695,17 @@ let commonOpts = {}, init_loadConfig = async (root)=>{
7600
8695
  loader: commonOpts.configLoader
7601
8696
  });
7602
8697
  return config.dev ||= {}, config.source ||= {}, config.server ||= {}, commonOpts.base && (config.server.base = commonOpts.base), commonOpts.root && (config.root = root), commonOpts.mode && (config.mode = commonOpts.mode), commonOpts.logLevel && (config.logLevel = commonOpts.logLevel), !commonOpts.open || (null == (_config_server = config.server) ? void 0 : _config_server.open) || (config.server.open = commonOpts.open), commonOpts.host && (config.server.host = commonOpts.host), commonOpts.port && (config.server.port = commonOpts.port), void 0 === config.dev.cliShortcuts && (config.dev.cliShortcuts = !0), filePath && (config.dev.watchFiles = [
7603
- ...config.dev.watchFiles ? castArray(config.dev.watchFiles) : [],
8698
+ ...config.dev.watchFiles ? helpers_castArray(config.dev.watchFiles) : [],
7604
8699
  {
7605
8700
  paths: filePath,
7606
8701
  type: 'reload-server'
7607
8702
  }
7608
8703
  ]), config;
7609
8704
  };
7610
- async function init({ cliOptions, isRestart, isBuildWatch = !1 }) {
7611
- cliOptions && (commonOpts = cliOptions);
8705
+ async function init_init({ cliOptions, isRestart, isBuildWatch = !1 }) {
8706
+ var _commonOpts_environment, envDir;
8707
+ cliOptions && (commonOpts = cliOptions), commonOpts.environment = null == (_commonOpts_environment = commonOpts.environment) ? void 0 : _commonOpts_environment.flatMap((env)=>env.split(','));
7612
8708
  try {
7613
- var envDir;
7614
8709
  let cwd = process.cwd(), root = commonOpts.root ? ensureAbsolutePath(cwd, commonOpts.root) : cwd, rsbuild = await createRsbuild({
7615
8710
  cwd: root,
7616
8711
  rsbuildConfig: ()=>init_loadConfig(root),
@@ -7625,7 +8720,7 @@ async function init({ cliOptions, isRestart, isBuildWatch = !1 }) {
7625
8720
  let files = [], config = rsbuild.getNormalizedConfig();
7626
8721
  if (config.dev.watchFiles) for (let watchConfig of config.dev.watchFiles){
7627
8722
  if ('reload-server' !== watchConfig.type) continue;
7628
- let paths = castArray(watchConfig.paths);
8723
+ let paths = helpers_castArray(watchConfig.paths);
7629
8724
  watchConfig.options ? watchFilesForRestart({
7630
8725
  files: paths,
7631
8726
  rsbuild,
@@ -7659,7 +8754,7 @@ let cleaners = [], onBeforeRestartServer = (cleaner)=>{
7659
8754
  clear,
7660
8755
  id: 'server'
7661
8756
  });
7662
- let rsbuild = await init({
8757
+ let rsbuild = await init_init({
7663
8758
  isRestart: !0
7664
8759
  });
7665
8760
  return !!rsbuild && (await rsbuild.startDevServer(), !0);
@@ -7669,7 +8764,7 @@ let cleaners = [], onBeforeRestartServer = (cleaner)=>{
7669
8764
  clear,
7670
8765
  id: 'build'
7671
8766
  });
7672
- let rsbuild = await init({
8767
+ let rsbuild = await init_init({
7673
8768
  isRestart: !0,
7674
8769
  isBuildWatch: !0
7675
8770
  });
@@ -7714,11 +8809,11 @@ async function runCLI() {
7714
8809
  ].includes(level) && (logger.level = level);
7715
8810
  }
7716
8811
  let { npm_execpath } = process.env;
7717
- (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && logger.log(), logger.greet(` Rsbuild v1.4.11\n`);
8812
+ (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && logger.log(), logger.greet(` Rsbuild v1.4.13\n`);
7718
8813
  try {
7719
8814
  !function() {
7720
8815
  let cli = ((name = "")=>new CAC(name))('rsbuild');
7721
- cli.help(), cli.version("1.4.11"), cli.option('--base <base>', 'specify the base path of the server').option('-c, --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--config-loader <loader>', 'specify the loader to load the config file, can be `jiti` or `native`', {
8816
+ cli.help(), cli.version("1.4.13"), cli.option('--base <base>', 'specify the base path of the server').option('-c, --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--config-loader <loader>', 'specify the loader to load the config file, can be `jiti` or `native`', {
7722
8817
  default: 'jiti'
7723
8818
  }).option('-r, --root <root>', 'specify the project root directory, can be an absolute path or a path relative to cwd').option('-m, --mode <mode>', 'specify the build mode, can be `development`, `production` or `none`').option('--log-level <level>', 'specify the log level, can be `info`, `warn`, `error` or `silent`').option('--env-mode <mode>', 'specify the env mode to load the `.env.[mode]` file').option('--environment <name>', 'specify the name of environment to build', {
7724
8819
  type: [
@@ -7729,7 +8824,7 @@ async function runCLI() {
7729
8824
  let devCommand = cli.command('', 'starting the dev server').alias('dev'), buildCommand = cli.command('build', 'build the app for production'), previewCommand = cli.command('preview', 'preview the production build locally'), inspectCommand = cli.command('inspect', 'inspect the Rspack and Rsbuild configs');
7730
8825
  applyServerOptions(devCommand), applyServerOptions(previewCommand), devCommand.action(async (options)=>{
7731
8826
  try {
7732
- let rsbuild = await init({
8827
+ let rsbuild = await init_init({
7733
8828
  cliOptions: options
7734
8829
  });
7735
8830
  await (null == rsbuild ? void 0 : rsbuild.startDevServer());
@@ -7738,7 +8833,7 @@ async function runCLI() {
7738
8833
  }
7739
8834
  }), buildCommand.option('-w, --watch', 'turn on watch mode, watch for changes and rebuild').action(async (options)=>{
7740
8835
  try {
7741
- let rsbuild = await init({
8836
+ let rsbuild = await init_init({
7742
8837
  cliOptions: options,
7743
8838
  isBuildWatch: options.watch
7744
8839
  }), buildInstance = await (null == rsbuild ? void 0 : rsbuild.build({
@@ -7750,7 +8845,7 @@ async function runCLI() {
7750
8845
  }
7751
8846
  }), previewCommand.action(async (options)=>{
7752
8847
  try {
7753
- let rsbuild = await init({
8848
+ let rsbuild = await init_init({
7754
8849
  cliOptions: options
7755
8850
  });
7756
8851
  await (null == rsbuild ? void 0 : rsbuild.preview());
@@ -7759,7 +8854,7 @@ async function runCLI() {
7759
8854
  }
7760
8855
  }), inspectCommand.option('--output <output>', 'specify inspect content output path').option('--verbose', 'show full function definitions in output').action(async (options)=>{
7761
8856
  try {
7762
- let rsbuild = await init({
8857
+ let rsbuild = await init_init({
7763
8858
  cliOptions: options
7764
8859
  });
7765
8860
  await (null == rsbuild ? void 0 : rsbuild.inspectConfig({
@@ -7776,5 +8871,5 @@ async function runCLI() {
7776
8871
  logger.error('Failed to start Rsbuild CLI.'), logger.error(err);
7777
8872
  }
7778
8873
  }
7779
- let src_version = "1.4.11";
8874
+ let src_version = "1.4.13";
7780
8875
  export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig_loadConfig as loadConfig, loadEnv, logger, mergeRsbuildConfig, rspack_rspack as rspack, runCLI, src_version as version };