@ohos-ports/rsbuild-core 2.2.9-beta.0 → 2.2.13-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +12 -0
  2. package/bin/rsbuild.js +3 -1
  3. package/compiled/@rstackjs/load-config/package.json +1 -1
  4. package/compiled/css-loader/index.js +2 -2
  5. package/compiled/html-rspack-plugin/index.d.ts +16 -2
  6. package/compiled/html-rspack-plugin/index.js +78 -28
  7. package/compiled/jiti/lib/jiti-cli.mjs +0 -0
  8. package/compiled/postcss/index.js +1 -1
  9. package/compiled/postcss/package.json +1 -1
  10. package/compiled/postcss-loader/index.js +6 -6
  11. package/compiled/ws/index.d.ts +4 -0
  12. package/compiled/ws/package.json +1 -1
  13. package/dist/1.js +84 -0
  14. package/dist/client/hmr.js +7 -2
  15. package/dist/client/overlay.js +9 -6
  16. package/dist/cssUrlLoader.mjs +18 -7
  17. package/dist/helpers/index.d.ts +1 -0
  18. package/dist/helpers/path.d.ts +9 -0
  19. package/dist/http-proxy-middleware.js +1 -1
  20. package/dist/index.d.ts +1 -1
  21. package/dist/index.js +2 -1
  22. package/dist/launch-editor-middleware.js +1 -1
  23. package/dist/loader/cssUrlLoader.d.ts +1 -0
  24. package/dist/m.js +446 -353
  25. package/dist/manifest-plugin.js +1 -1
  26. package/dist/memfs.js +1 -1
  27. package/dist/plugins/fileSize.d.ts +11 -0
  28. package/dist/server/assets-middleware/getFileFromUrl.d.ts +1 -0
  29. package/dist/server/assets-middleware/setupOutputFileSystem.d.ts +1 -2
  30. package/dist/server/assets-middleware/setupWriteToDisk.d.ts +19 -7
  31. package/dist/server/browserLogs.d.ts +5 -2
  32. package/dist/server/gracefulShutdown.d.ts +1 -2
  33. package/dist/server/helper.d.ts +2 -2
  34. package/dist/server/hostCheck.d.ts +7 -0
  35. package/dist/trace-mapping.js +16 -14
  36. package/dist/types/config.d.ts +21 -2
  37. package/dist/types/plugin.d.ts +1 -0
  38. package/dist/ws.js +2 -2
  39. package/package.json +8 -49
package/dist/m.js CHANGED
@@ -2,8 +2,8 @@
2
2
  let runtimeProcessArgs, runtimeInfo, swcHelpersPath, pluginHelper_htmlPlugin;
3
3
  import { rspackRequire, moduleFactories, compatGetDefaultExport, createFakeNamespaceObject } from "./rslib-runtime.js";
4
4
  import { rspack as core_rspack } from "@rspack/core";
5
- import node_util, { promisify, stripVTControlCharacters } from "node:util";
6
- import node_path, { dirname as external_node_path_dirname, isAbsolute as external_node_path_isAbsolute, join, posix, relative, resolve as external_node_path_resolve, sep, win32 } from "node:path";
5
+ import node_util, { format as external_node_util_format, promisify, stripVTControlCharacters } from "node:util";
6
+ import node_path, { dirname, isAbsolute as external_node_path_isAbsolute, join, posix, relative, resolve as external_node_path_resolve, sep } from "node:path";
7
7
  import { builtinModules, createRequire, createRequire as __rspack_createRequire } from "node:module";
8
8
  import node_fs, { existsSync } from "node:fs";
9
9
  import node_os, { constants } from "node:os";
@@ -12,8 +12,10 @@ import { URL as external_node_url_URL, pathToFileURL, fileURLToPath as __rspack_
12
12
  import { isPromise, isRegExp } from "node:util/types";
13
13
  import { readFile } from "node:fs/promises";
14
14
  import node_zlib, { constants as external_node_zlib_constants } from "node:zlib";
15
- import { once } from "node:events";
16
- import { cachedImport, getTinyglobby } from "./r.js";
15
+ import { once as external_node_events_once } from "node:events";
16
+ import { isIP } from "node:net";
17
+ import { ALL_INTERFACES_IPV4, IMAGE_EXTENSIONS, ASSETS_DIST_DIR, FONT_DIST_DIR, AUDIO_EXTENSIONS, ensureAbsolutePath, NODE_MODULES_REGEX, FONT_EXTENSIONS, HMR_SOCKET_PATH, WASM_DIST_DIR, VIDEO_EXTENSIONS, BROWSER_LOG_PREFIX, toPosixPath, TRACK_EXTENSIONS, IMAGE_DIST_DIR, RSBUILD_OUTPUTS_PATH, DEFAULT_STACK_TRACE, LOADER_PATH, ASSET_EXTENSIONS, SVG_DIST_DIR, isWindows, COMPILED_PATH, WORKER_QUERY_REGEX, TS_CONFIG_FILE, dedupeNestedPaths, CSS_REGEX, relativeWithin, LAZY_COMPILATION_IDENTIFIER, DEFAULT_BROWSERSLIST, JS_REGEX, MEDIA_DIST_DIR, SCRIPT_REGEX, DEFAULT_WEB_BROWSERSLIST, getCompiledPath, normalizeRuleConditionPath, getPathnameFromUrl, toRelativePath, isDeno, CSS_DIST_DIR, INLINE_QUERY_REGEX, STATIC_PATH, RAW_QUERY_REGEX, PLUGIN_SWC_NAME, CLIENT_PATH, getCommonParentPath, LOCALHOST, JS_DIST_DIR, URL_QUERY_REGEX } from "./1.js";
18
+ import { cachedImport as cachedImport_cachedImport, getTinyglobby } from "./r.js";
17
19
  var superClass, superClass1, __rspack_import_meta_filename__ = __rspack_fileURLToPath(import.meta.url);
18
20
  let __rspack_createRequire_require = __rspack_createRequire(import.meta.url);
19
21
  moduleFactories.add({
@@ -388,8 +390,8 @@ moduleFactories.add({
388
390
  return (asyncHooks.AsyncResource && (res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn')), res && res.runInAsyncScope) ? res.runInAsyncScope.bind(res, fn, null) : fn;
389
391
  }
390
392
  },
391
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/d0e1ffed59e3d657674e04f8f91182ccde1db31e7c7c0f00dd625e998ab50180/node_modules/postcss-load-config/src/index.js" (module) {
392
- let yaml, { resolve } = __rspack_createRequire_require("node:path"), config = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/lilconfig/3.1.3/8e9a79516bf61f8427342cef50cdad2cdc2572f42288ba8053b88eadfdc0ebef/node_modules/lilconfig/src/index.js"), loadOptions = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/d0e1ffed59e3d657674e04f8f91182ccde1db31e7c7c0f00dd625e998ab50180/node_modules/postcss-load-config/src/options.js"), loadPlugins = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/d0e1ffed59e3d657674e04f8f91182ccde1db31e7c7c0f00dd625e998ab50180/node_modules/postcss-load-config/src/plugins.js"), req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/d0e1ffed59e3d657674e04f8f91182ccde1db31e7c7c0f00dd625e998ab50180/node_modules/postcss-load-config/src/req.js");
393
+ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/baf07bf9099810ce2e0c00768f056c90b47d57b154f4b8912460449b9922899a/node_modules/postcss-load-config/src/index.js" (module) {
394
+ let yaml, { resolve } = __rspack_createRequire_require("node:path"), config = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/lilconfig/3.1.3/8e9a79516bf61f8427342cef50cdad2cdc2572f42288ba8053b88eadfdc0ebef/node_modules/lilconfig/src/index.js"), loadOptions = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/baf07bf9099810ce2e0c00768f056c90b47d57b154f4b8912460449b9922899a/node_modules/postcss-load-config/src/options.js"), loadPlugins = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/baf07bf9099810ce2e0c00768f056c90b47d57b154f4b8912460449b9922899a/node_modules/postcss-load-config/src/plugins.js"), req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/baf07bf9099810ce2e0c00768f056c90b47d57b154f4b8912460449b9922899a/node_modules/postcss-load-config/src/req.js");
393
395
  async function processResult(ctx, result) {
394
396
  let obj, file = result.filepath || '', projectConfig = ((obj = result.config) && obj.__esModule ? obj : {
395
397
  default: obj
@@ -462,8 +464,8 @@ moduleFactories.add({
462
464
  });
463
465
  };
464
466
  },
465
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/d0e1ffed59e3d657674e04f8f91182ccde1db31e7c7c0f00dd625e998ab50180/node_modules/postcss-load-config/src/options.js" (module) {
466
- let req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/d0e1ffed59e3d657674e04f8f91182ccde1db31e7c7c0f00dd625e998ab50180/node_modules/postcss-load-config/src/req.js");
467
+ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/baf07bf9099810ce2e0c00768f056c90b47d57b154f4b8912460449b9922899a/node_modules/postcss-load-config/src/options.js" (module) {
468
+ let req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/baf07bf9099810ce2e0c00768f056c90b47d57b154f4b8912460449b9922899a/node_modules/postcss-load-config/src/req.js");
467
469
  module.exports = async function options(config, file) {
468
470
  if (config.parser && 'string' == typeof config.parser) try {
469
471
  config.parser = await req(config.parser, file);
@@ -483,8 +485,8 @@ moduleFactories.add({
483
485
  return config;
484
486
  };
485
487
  },
486
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/d0e1ffed59e3d657674e04f8f91182ccde1db31e7c7c0f00dd625e998ab50180/node_modules/postcss-load-config/src/plugins.js" (module) {
487
- let req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/d0e1ffed59e3d657674e04f8f91182ccde1db31e7c7c0f00dd625e998ab50180/node_modules/postcss-load-config/src/req.js");
488
+ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/baf07bf9099810ce2e0c00768f056c90b47d57b154f4b8912460449b9922899a/node_modules/postcss-load-config/src/plugins.js" (module) {
489
+ let req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/baf07bf9099810ce2e0c00768f056c90b47d57b154f4b8912460449b9922899a/node_modules/postcss-load-config/src/req.js");
488
490
  async function load(plugin, options, file) {
489
491
  try {
490
492
  if (null == options || 0 === Object.keys(options).length) return await req(plugin, file);
@@ -500,7 +502,7 @@ moduleFactories.add({
500
502
  }), list;
501
503
  };
502
504
  },
503
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/d0e1ffed59e3d657674e04f8f91182ccde1db31e7c7c0f00dd625e998ab50180/node_modules/postcss-load-config/src/req.js" (module) {
505
+ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/baf07bf9099810ce2e0c00768f056c90b47d57b154f4b8912460449b9922899a/node_modules/postcss-load-config/src/req.js" (module) {
504
506
  let tsx, jiti, { createRequire } = __rspack_createRequire_require("node:module"), { pathToFileURL } = __rspack_createRequire_require("node:url"), TS_EXT_RE = /\.[mc]?ts$/, importError = [];
505
507
  module.exports = async function req(name, rootFile = __rspack_import_meta_filename__) {
506
508
  let url = createRequire(rootFile).resolve(name);
@@ -719,14 +721,14 @@ function findAllBrackets(v) {
719
721
  }
720
722
  function getMriOptions(options) {
721
723
  let result = {
722
- alias: {},
724
+ alias: Object.create(null),
723
725
  boolean: []
724
726
  };
725
727
  for (let [index, option] of options.entries())option.names.length > 1 && (result.alias[option.names[0]] = option.names.slice(1)), option.isBoolean && (option.negated && options.some((o, i)=>i !== index && o.names.some((name)=>option.names.includes(name)) && "boolean" == typeof o.required) || result.boolean.push(option.names[0]));
726
728
  return result;
727
729
  }
728
730
  function findLongest(arr) {
729
- return arr.sort((a, b)=>a.length > b.length ? -1 : 1)[0];
731
+ return arr.sort((a, b)=>b.length - a.length)[0];
730
732
  }
731
733
  function padRight(str, length) {
732
734
  return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
@@ -734,7 +736,13 @@ function padRight(str, length) {
734
736
  function camelcase(input) {
735
737
  return input.replaceAll(/([a-z])-([a-z])/g, (_, p1, p2)=>p1 + p2.toUpperCase());
736
738
  }
739
+ let UNSAFE_KEYS = new Set([
740
+ "__proto__",
741
+ "constructor",
742
+ "prototype"
743
+ ]);
737
744
  function setDotProp(obj, keys, val) {
745
+ if (keys.some((key)=>UNSAFE_KEYS.has(key))) return;
738
746
  let current = obj;
739
747
  for(let i = 0; i < keys.length; i++){
740
748
  let key = keys[i];
@@ -750,12 +758,9 @@ function setDotProp(obj, keys, val) {
750
758
  }
751
759
  }
752
760
  function setByType(obj, transforms) {
753
- for (let key of Object.keys(transforms)){
754
- let transform = transforms[key];
755
- transform.shouldTransform && (obj[key] = [
756
- obj[key]
757
- ].flat(), "function" == typeof transform.transformFunction && (obj[key] = obj[key].map(transform.transformFunction)));
758
- }
761
+ for (let [key, transform] of Object.entries(transforms))transform.shouldTransform && (obj[key] = [
762
+ obj[key]
763
+ ].flat(), "function" == typeof transform.transformFunction && (obj[key] = obj[key].map(transform.transformFunction)));
759
764
  }
760
765
  function getFileName(input) {
761
766
  let m = /([^\\/]+)$/.exec(input);
@@ -781,7 +786,7 @@ var CACError = class extends Error {
781
786
  this.rawName = rawName, this.description = description, this.config = Object.assign({}, config), rawName = rawName.replaceAll(".*", ""), this.negated = !1, this.names = removeBrackets(rawName).split(",").map((v)=>{
782
787
  let name = v.trim().replace(/^-{1,2}/, "");
783
788
  return name.startsWith("no-") && (this.negated = !0, name = name.replace(/^no-/, "")), camelcaseOptionName(name);
784
- }).sort((a, b)=>a.length > b.length ? 1 : -1), this.name = this.names.at(-1), this.negated && null == this.config.default && (this.config.default = !0), rawName.includes("<") ? this.required = !0 : rawName.includes("[") ? this.required = !1 : this.isBoolean = !0;
789
+ }).sort((a, b)=>a.length - b.length), this.name = this.names.at(-1), this.negated && null == this.config.default && (this.config.default = !0), rawName.includes("<") ? this.required = !0 : rawName.includes("[") ? this.required = !1 : this.isBoolean = !0;
785
790
  }
786
791
  };
787
792
  if ("u" > typeof process) {
@@ -841,7 +846,7 @@ var Command = class {
841
846
  return this instanceof GlobalCommand;
842
847
  }
843
848
  hasOption(name) {
844
- return name = name.split(".")[0], this.options.find((option)=>option.names.includes(name));
849
+ return name = name.split(".", 1)[0], this.options.find((option)=>option.names.includes(name));
845
850
  }
846
851
  outputHelp() {
847
852
  let { name, commands } = this.cli, { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand, sections = [
@@ -898,7 +903,7 @@ var Command = class {
898
903
  ...this.options
899
904
  ];
900
905
  for (let option of options){
901
- let value = parsedOptions[option.name.split(".")[0]];
906
+ let value = parsedOptions[option.name.split(".", 1)[0]];
902
907
  if (option.required) {
903
908
  let hasNegated = options.some((o)=>o.negated && o.names.includes(option.name));
904
909
  if (!0 === value || !1 === value && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`);
@@ -1018,7 +1023,7 @@ var Command = class {
1018
1023
  if (!ignoreDefault && void 0 !== cliOption.config.default) for (let name of cliOption.names)options[name] = cliOption.config.default;
1019
1024
  Array.isArray(cliOption.config.type) && void 0 === transforms[cliOption.name] && (transforms[cliOption.name] = Object.create(null), transforms[cliOption.name].shouldTransform = !0, transforms[cliOption.name].transformFunction = cliOption.config.type[0]);
1020
1025
  }
1021
- for (let key of Object.keys(parsed))"_" !== key && (setDotProp(options, key.split("."), parsed[key]), setByType(options, transforms));
1026
+ for (let [key, value] of Object.entries(parsed))"_" !== key && (setDotProp(options, key.split("."), value), setByType(options, transforms));
1022
1027
  return {
1023
1028
  args,
1024
1029
  options
@@ -1033,62 +1038,7 @@ var Command = class {
1033
1038
  arg.variadic ? actionArgs.push(args.slice(index)) : actionArgs.push(args[index]);
1034
1039
  }), actionArgs.push(options), command.commandAction.apply(this, actionArgs);
1035
1040
  }
1036
- };
1037
- let isDeno = "u" > typeof Deno, isWindows = 'win32' === process.platform, dirname = import.meta.dirname, STATIC_PATH = join(dirname, '../static'), CLIENT_PATH = join(dirname, 'client'), COMPILED_PATH = join(dirname, '../compiled'), RSBUILD_OUTPUTS_PATH = '.rsbuild', LOCALHOST = 'localhost', ALL_INTERFACES_IPV4 = '0.0.0.0', DEFAULT_STACK_TRACE = 'summary', DEFAULT_WEB_BROWSERSLIST = [
1038
- 'chrome >= 107',
1039
- 'edge >= 107',
1040
- 'firefox >= 104',
1041
- 'safari >= 16'
1042
- ], DEFAULT_BROWSERSLIST = {
1043
- web: DEFAULT_WEB_BROWSERSLIST,
1044
- 'web-worker': DEFAULT_WEB_BROWSERSLIST,
1045
- node: [
1046
- 'node >= 20'
1047
- ]
1048
- }, JS_REGEX = /\.(?:js|mjs|cjs|jsx)$/, SCRIPT_REGEX = /\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts)$/, CSS_REGEX = /\.css$/, RAW_QUERY_REGEX = /[?&]raw(?:&|=|$)/, INLINE_QUERY_REGEX = /[?&]inline(?:&|=|$)/, URL_QUERY_REGEX = /[?&]url(?:&|=|$)/, WORKER_QUERY_REGEX = /[?&]worker(?:&|=|$)/, NODE_MODULES_REGEX = /[\\/]node_modules[\\/]/, PLUGIN_SWC_NAME = 'rsbuild:swc', PLUGIN_CSS_NAME = 'rsbuild:css', FONT_EXTENSIONS = [
1049
- 'woff',
1050
- 'woff2',
1051
- 'eot',
1052
- 'ttf',
1053
- 'otf',
1054
- 'ttc'
1055
- ], ASSET_EXTENSIONS = [
1056
- 'webmanifest',
1057
- 'pdf',
1058
- 'txt'
1059
- ], IMAGE_EXTENSIONS = [
1060
- 'png',
1061
- 'jpg',
1062
- 'jpeg',
1063
- 'pjpeg',
1064
- 'pjp',
1065
- 'gif',
1066
- 'bmp',
1067
- 'webp',
1068
- 'ico',
1069
- 'apng',
1070
- 'avif',
1071
- 'tif',
1072
- 'tiff',
1073
- 'jfif',
1074
- 'cur',
1075
- 'jxl'
1076
- ], VIDEO_EXTENSIONS = [
1077
- 'mp4',
1078
- 'webm',
1079
- 'ogg',
1080
- 'mov'
1081
- ], AUDIO_EXTENSIONS = [
1082
- 'mp3',
1083
- 'wav',
1084
- 'flac',
1085
- 'aac',
1086
- 'm4a',
1087
- 'opus'
1088
- ], TRACK_EXTENSIONS = [
1089
- 'vtt'
1090
- ], LAZY_COMPILATION_IDENTIFIER = 'lazy-compilation-proxy';
1091
- var __webpack_modules__ = {}, __webpack_module_cache__ = {};
1041
+ }, __webpack_modules__ = {}, __webpack_module_cache__ = {};
1092
1042
  function dist_webpack_require_(moduleId) {
1093
1043
  var cachedModule = __webpack_module_cache__[moduleId];
1094
1044
  if (void 0 !== cachedModule) return cachedModule.exports;
@@ -2144,7 +2094,7 @@ let vendors_require = createRequire(import.meta.url);
2144
2094
  var cjs_0_default = compatGetDefaultExport(rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/deepmerge/4.3.1/56471899410038644780b3527c5076e78d3f57091a0da3ac0daf6d994929353d/node_modules/deepmerge/dist/cjs.js"));
2145
2095
  let setNodeEnv = (env)=>{
2146
2096
  process.env.NODE_ENV = env;
2147
- }, isFunction = (func)=>'function' == typeof func, isObject = (obj)=>'[object Object]' === Object.prototype.toString.call(obj), objectPrototype = Object.prototype, helpers_getProto = Object.getPrototypeOf, isPlainObject = (obj)=>null !== obj && 'object' == typeof obj && helpers_getProto(obj) === objectPrototype, helpers_castArray = (arr)=>void 0 === arr ? [] : Array.isArray(arr) ? arr : [
2097
+ }, isCI = ()=>!!process.env.CI && 'false' !== process.env.CI, isFunction = (func)=>'function' == typeof func, isObject = (obj)=>'[object Object]' === Object.prototype.toString.call(obj), objectPrototype = Object.prototype, helpers_getProto = Object.getPrototypeOf, isPlainObject = (obj)=>null !== obj && 'object' == typeof obj && helpers_getProto(obj) === objectPrototype, helpers_castArray = (arr)=>void 0 === arr ? [] : Array.isArray(arr) ? arr : [
2148
2098
  arr
2149
2099
  ], cloneDeep = (value)=>null == value ? value : cjs_0_default()({}, value, {
2150
2100
  isMergeableObject: isPlainObject
@@ -2202,7 +2152,7 @@ function pick(obj, keys) {
2202
2152
  for (let key of keys)void 0 !== obj[key] && (result[key] = obj[key]);
2203
2153
  return result;
2204
2154
  }
2205
- let isTTY = (type = 'stdout')=>('stdin' === type ? process.stdin.isTTY : process.stdout.isTTY) && !process.env.CI, getCrypto = cachedImport(()=>import("node:crypto"));
2155
+ let isTTY = (type = 'stdout')=>('stdin' === type ? process.stdin.isTTY : process.stdout.isTTY) && !isCI(), getCrypto = cachedImport_cachedImport(()=>import("node:crypto"));
2206
2156
  async function helpers_hash(data) {
2207
2157
  let crypto = await getCrypto();
2208
2158
  return crypto.hash ? crypto.hash('sha256', data, 'hex').slice(0, 16) : crypto.createHash('sha256').update(data).digest('hex').slice(0, 16);
@@ -2413,12 +2363,12 @@ function createEnvironmentAsyncHook() {
2413
2363
  return params;
2414
2364
  },
2415
2365
  callBatch: async ({ environment, args: params })=>{
2416
- let results = [];
2417
- for (let callback of [
2366
+ let callbacks = [
2418
2367
  ...preGroup,
2419
2368
  ...defaultGroup,
2420
2369
  ...postGroup
2421
- ]){
2370
+ ], results = [];
2371
+ for (let callback of callbacks){
2422
2372
  if (environment && callback.environment && callback.environment !== environment) continue;
2423
2373
  let result = await callback.handler(...params);
2424
2374
  results.push(result);
@@ -2427,12 +2377,19 @@ function createEnvironmentAsyncHook() {
2427
2377
  }
2428
2378
  };
2429
2379
  }
2380
+ let SKIP_CALLBACK = Symbol('skip callback');
2430
2381
  function createAsyncHook() {
2431
- let preGroup = [], postGroup = [], defaultGroup = [];
2382
+ let preGroup = [], postGroup = [], defaultGroup = [], register = (cb, once)=>{
2383
+ let { handler, order } = isFunction(cb) ? {
2384
+ handler: cb
2385
+ } : cb, group = defaultGroup;
2386
+ if ('pre' === order ? group = preGroup : 'post' === order && (group = postGroup), !once) return void group.push(handler);
2387
+ let called = !1, onceCallback = (...args)=>called ? SKIP_CALLBACK : (called = !0, group.splice(group.indexOf(onceCallback), 1), handler(...args));
2388
+ group.push(onceCallback);
2389
+ };
2432
2390
  return {
2433
- tap: (cb)=>{
2434
- isFunction(cb) ? defaultGroup.push(cb) : 'pre' === cb.order ? preGroup.push(cb.handler) : 'post' === cb.order ? postGroup.push(cb.handler) : defaultGroup.push(cb.handler);
2435
- },
2391
+ tap: (cb)=>register(cb, !1),
2392
+ tapOnce: (cb)=>register(cb, !0),
2436
2393
  callChain: async (...params)=>{
2437
2394
  for (let callback of [
2438
2395
  ...preGroup,
@@ -2440,19 +2397,19 @@ function createAsyncHook() {
2440
2397
  ...postGroup
2441
2398
  ]){
2442
2399
  let result = await callback(...params);
2443
- void 0 !== result && (params[0] = result);
2400
+ result !== SKIP_CALLBACK && void 0 !== result && (params[0] = result);
2444
2401
  }
2445
2402
  return params;
2446
2403
  },
2447
2404
  callBatch: async (...params)=>{
2448
- let results = [];
2449
- for (let callback of [
2405
+ let callbacks = [
2450
2406
  ...preGroup,
2451
2407
  ...defaultGroup,
2452
2408
  ...postGroup
2453
- ]){
2409
+ ], results = [];
2410
+ for (let callback of callbacks){
2454
2411
  let result = await callback(...params);
2455
- results.push(result);
2412
+ result !== SKIP_CALLBACK && results.push(result);
2456
2413
  }
2457
2414
  return results;
2458
2415
  }
@@ -2509,9 +2466,14 @@ let onBeforeCompile = ({ compiler, beforeCompile, beforeEnvironmentCompile, isWa
2509
2466
  !compilerDone && (compilerDone = !0, doneCompilers++), compilerStats[compilerIndex] = stats;
2510
2467
  let lastCompilerDone = doneCompilers === compilers.length;
2511
2468
  await onEnvironmentDone(index, stats), lastCompilerDone && await onDone(new MultiStatsCtor(compilerStats));
2512
- }), compiler.hooks.invalid.tap('rsbuild:done', ()=>{
2513
- compilerDone && (compilerDone = !1, doneCompilers--);
2514
2469
  });
2470
+ let resetDoneState = ()=>{
2471
+ compilerDone && (compilerDone = !1, doneCompilers--);
2472
+ };
2473
+ compiler.hooks.invalid.tap('rsbuild:done', resetDoneState), compiler.hooks.watchRun.tap({
2474
+ name: 'rsbuild:done',
2475
+ stage: -1 / 0
2476
+ }, resetDoneState);
2515
2477
  }
2516
2478
  } else compiler.hooks.done.tapPromise('rsbuild:done', async (stats)=>{
2517
2479
  await onEnvironmentDone(0, stats), await onDone(stats);
@@ -2619,30 +2581,7 @@ function loadConfig(opts) {
2619
2581
  return pickEnv(config, opts);
2620
2582
  }
2621
2583
  }
2622
- function toRelativePath(base, filepath) {
2623
- let relativePath = relative(base, filepath);
2624
- return '' === relativePath ? `.${sep}` : relativePath.startsWith('.') ? relativePath : `.${sep}${relativePath}`;
2625
- }
2626
- function getCommonParentPath(paths) {
2627
- let uniquePaths = [
2628
- ...new Set(paths)
2629
- ];
2630
- if (1 === uniquePaths.length) return uniquePaths[0];
2631
- let [first, ...rest] = uniquePaths.map((p)=>p.split(sep)), common = [];
2632
- for(let i = 0; i < first.length; i++){
2633
- let segment = first[i];
2634
- if (rest.every((p)=>p[i] === segment)) common.push(segment);
2635
- else break;
2636
- }
2637
- return common.join(sep);
2638
- }
2639
- let ensureAbsolutePath = (base, filePath)=>external_node_path_isAbsolute(filePath) ? filePath : join(base, filePath), getPathnameFromUrl = (url)=>{
2640
- try {
2641
- return url ? new URL(url, 'http://localhost').pathname : url;
2642
- } catch {
2643
- return url;
2644
- }
2645
- }, dedupeNestedPaths = (paths)=>paths.sort((p1, p2)=>p2.length > p1.length ? -1 : 1).reduce((prev, curr)=>prev.some((p)=>curr.startsWith(p) || curr === p) ? prev : prev.concat(curr), []), toPosixPath = (filepath)=>'/' === sep ? filepath : filepath.replace(/\\/g, '/'), normalizeRuleConditionPath = (filepath)=>isWindows && 'string' == typeof filepath && filepath.includes('/') && win32.isAbsolute(filepath) ? filepath.replace(/\//g, '\\') : filepath, isFileSync = (filePath)=>{
2584
+ let isFileSync = (filePath)=>{
2646
2585
  try {
2647
2586
  return node_fs.statSync(filePath, {
2648
2587
  throwIfNoEntry: !1
@@ -2784,7 +2723,7 @@ let OVERRIDE_PATHS = new Set([
2784
2723
  writeToDisk: !1,
2785
2724
  cliShortcuts: !1,
2786
2725
  client: {
2787
- path: '/rsbuild-hmr',
2726
+ path: HMR_SOCKET_PATH,
2788
2727
  port: '',
2789
2728
  host: '',
2790
2729
  overlay: !0,
@@ -2795,6 +2734,7 @@ let OVERRIDE_PATHS = new Set([
2795
2734
  server: {
2796
2735
  port: 3000,
2797
2736
  host: LOCALHOST,
2737
+ allowedHosts: !0,
2798
2738
  open: !1,
2799
2739
  base: '/',
2800
2740
  htmlFallback: 'index',
@@ -2821,7 +2761,7 @@ let OVERRIDE_PATHS = new Set([
2821
2761
  scriptLoading: 'defer',
2822
2762
  implementation: 'js'
2823
2763
  },
2824
- resolve: (swcHelpersPath || (swcHelpersPath = external_node_path_dirname(vendors_require.resolve('@swc/helpers/package.json'))), {
2764
+ resolve: (swcHelpersPath || (swcHelpersPath = dirname(vendors_require.resolve('@swc/helpers/package.json'))), {
2825
2765
  alias: {
2826
2766
  '@swc/helpers': swcHelpersPath
2827
2767
  },
@@ -2847,14 +2787,14 @@ let OVERRIDE_PATHS = new Set([
2847
2787
  cleanDistPath: 'auto',
2848
2788
  distPath: {
2849
2789
  root: "dist",
2850
- css: 'static/css',
2851
- svg: 'static/svg',
2852
- font: 'static/font',
2790
+ css: CSS_DIST_DIR,
2791
+ svg: SVG_DIST_DIR,
2792
+ font: FONT_DIST_DIR,
2853
2793
  html: "./",
2854
- wasm: 'static/wasm',
2855
- image: 'static/image',
2856
- media: 'static/media',
2857
- assets: 'static/assets',
2794
+ wasm: WASM_DIST_DIR,
2795
+ image: IMAGE_DIST_DIR,
2796
+ media: MEDIA_DIST_DIR,
2797
+ assets: ASSETS_DIST_DIR,
2858
2798
  favicon: "./"
2859
2799
  },
2860
2800
  assetPrefix: "/",
@@ -2930,7 +2870,7 @@ let withDefaultConfig = async (rootPath, userConfig)=>{
2930
2870
  imports: !0,
2931
2871
  entries: !1
2932
2872
  }), !config.source.tsconfigPath) {
2933
- let tsconfigPath = join(rootPath, 'tsconfig.json');
2873
+ let tsconfigPath = join(rootPath, TS_CONFIG_FILE);
2934
2874
  await isFileExists(tsconfigPath) && (config.source.tsconfigPath = tsconfigPath);
2935
2875
  }
2936
2876
  return config;
@@ -3201,7 +3141,7 @@ function initPluginAPI({ context, pluginManager }) {
3201
3141
  if (descriptor.targets && !descriptor.targets.includes(target) || descriptor.environments && !descriptor.environments.includes(environmentContext.name)) return;
3202
3142
  let rule = chain.module.rule(id);
3203
3143
  descriptor.test && rule.test(descriptor.test), descriptor.resourceQuery && rule.resourceQuery(descriptor.resourceQuery), descriptor.layer && rule.layer(descriptor.layer), descriptor.issuerLayer && rule.issuerLayer(descriptor.issuerLayer), descriptor.issuer && rule.issuer(descriptor.issuer), descriptor.with && rule.with(descriptor.with), descriptor.mimetype && rule.mimetype(descriptor.mimetype), descriptor.order && 'default' !== descriptor.order ? rule.enforce(descriptor.order) : descriptor.enforce && rule.enforce(descriptor.enforce);
3204
- let loaderPath = join(dirname, descriptor.raw ? 'transformRawLoader.mjs' : 'transformLoader.mjs');
3144
+ let loaderPath = join(LOADER_PATH, descriptor.raw ? 'transformRawLoader.mjs' : 'transformLoader.mjs');
3205
3145
  rule.use(id).loader(loaderPath).options({
3206
3146
  id,
3207
3147
  getEnvironment: ()=>environmentContext
@@ -3363,7 +3303,7 @@ function createPublicContext(context) {
3363
3303
  async function createContext(options, userConfig, logger, loadConfigResult) {
3364
3304
  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, hooks = initHooks();
3365
3305
  return {
3366
- version: "2.2.9",
3306
+ version: "2.2.13",
3367
3307
  rootPath,
3368
3308
  configFile: loadConfigResult?.filePath ?? userConfig._privateMeta?.configFilePath,
3369
3309
  configFileDependencies: loadConfigResult?.dependencies ?? userConfig._privateMeta?.configFileDependencies ?? [],
@@ -3902,7 +3842,7 @@ async function initRsbuildConfig({ context, pluginManager }) {
3902
3842
  }, applyEnvironmentDefaultConfig = (config)=>{
3903
3843
  config.source.entry && 0 !== Object.keys(config.source.entry).length || (config.source.entry = (defaultEntry || (defaultEntry = getDefaultEntry(rootPath)), defaultEntry));
3904
3844
  let isServer = 'node' === config.output.target;
3905
- return void 0 === config.output.distPath.js && (config.output.distPath.js = isServer ? '' : 'static/js'), void 0 === config.output.module && (config.output.module = isServer), void 0 === config.output.minify && (config.output.minify = !isServer), config;
3845
+ return void 0 === config.output.distPath.js && (config.output.distPath.js = isServer ? '' : JS_DIST_DIR), void 0 === config.output.module && (config.output.module = isServer), void 0 === config.output.minify && (config.output.minify = !isServer), config;
3906
3846
  };
3907
3847
  if (environments && Object.keys(environments).length > 0) {
3908
3848
  let resolvedEnvironments = Object.fromEntries(Object.entries(environments).filter(([name])=>isEnvironmentEnabled(name)).map(([name, config])=>[
@@ -4032,7 +3972,7 @@ async function createCompiler_createCompiler(options) {
4032
3972
  if (item1 < item2) return -1;
4033
3973
  }
4034
3974
  return 0;
4035
- })(version, '2.2.2') >= 0)) throw Error(`${color.dim('[rsbuild]')} The current Rspack version does not meet the requirements, the minimum supported version of Rspack is ${color.green("2.2.2")}`);
3975
+ })(version, '2.2.3') >= 0)) throw Error(`${color.dim('[rsbuild]')} The current Rspack version does not meet the requirements, the minimum supported version of Rspack is ${color.green("2.2.3")}`);
4036
3976
  let isMultiCompiler = rspackConfigs.length > 1, compiler = isMultiCompiler ? core_rspack(rspackConfigs) : core_rspack(rspackConfigs[0]);
4037
3977
  'true' === process.env.RSPACK_UNSAFE_FAST_DROP && (compiler.unsafeFastDrop = !0);
4038
3978
  let isVersionLogged = !1, isCompiling = !1, hasFatalError = !1, compilers = isMultiCompiler ? compiler.compilers : [
@@ -4047,9 +3987,9 @@ async function createCompiler_createCompiler(options) {
4047
3987
  if ('LazyCompilation' === name && 'string' == typeof log && log.startsWith(LAZY_COMPILATION_IDENTIFIER)) {
4048
3988
  let resource = log.split(' ')[0];
4049
3989
  if (!resource) return;
4050
- let { rootPath } = context, absolutePath = resource.split('!').pop();
4051
- if (absolutePath?.startsWith(rootPath)) {
4052
- let relativePath = absolutePath.replace(rootPath, '');
3990
+ let { rootPath } = context, rootPrefix = rootPath.endsWith(sep) ? rootPath : rootPath + sep, absolutePath = resource.split('!').pop();
3991
+ if (absolutePath?.startsWith(rootPrefix)) {
3992
+ let relativePath = absolutePath.slice(rootPrefix.length);
4053
3993
  lazyModules.add(relativePath);
4054
3994
  }
4055
3995
  }
@@ -4079,8 +4019,9 @@ async function createCompiler_createCompiler(options) {
4079
4019
  let digits = seconds >= 0.01 ? 2 : 3;
4080
4020
  return format(seconds.toFixed(digits), 's');
4081
4021
  }
4082
- if (seconds < 60) return format(seconds.toFixed(1), 's');
4083
- let minutesLabel = format(Math.floor(seconds / 60).toFixed(0), 'm'), remainingSeconds = seconds % 60;
4022
+ let roundedSeconds = Math.round(10 * seconds) / 10;
4023
+ if (roundedSeconds < 60) return format(roundedSeconds.toFixed(1), 's');
4024
+ let minutesLabel = format(Math.floor(roundedSeconds / 60).toFixed(0), 'm'), remainingSeconds = roundedSeconds % 60;
4084
4025
  if (0 === remainingSeconds) return minutesLabel;
4085
4026
  let secondsLabel = format(remainingSeconds.toFixed(+(remainingSeconds % 1 != 0)), 's');
4086
4027
  return `${minutesLabel} ${secondsLabel}`;
@@ -4167,7 +4108,7 @@ async function createCompiler_createCompiler(options) {
4167
4108
  rspackConfigs
4168
4109
  };
4169
4110
  }
4170
- let getChokidar = cachedImport(()=>import("./chokidar.js").then((m)=>m.chokidar_namespaceObject)), DEFAULT_WATCH_FILE_EVENTS = [
4111
+ let getChokidar = cachedImport_cachedImport(()=>import("./chokidar.js").then((m)=>m.chokidar_namespaceObject)), DEFAULT_WATCH_FILE_EVENTS = [
4171
4112
  'add',
4172
4113
  'change',
4173
4114
  'unlink'
@@ -4299,7 +4240,7 @@ function watchFilesForRestart({ watchFiles, context, restartContext }) {
4299
4240
  } catch (error) {
4300
4241
  logger.error(error);
4301
4242
  }
4302
- })), close = ()=>(closePromise || (closePromise = watchersPromise.then((watchers)=>Promise.all(watchers.map((watcher)=>watcher?.close()))).then(()=>{})), closePromise);
4243
+ })), close = ()=>(closePromise || (closePromise = watchersPromise.then((watchers)=>Promise.all(watchers.filter((watcher)=>void 0 !== watcher).map((watcher)=>watcher.close()))).then(()=>{})), closePromise);
4303
4244
  return {
4304
4245
  close
4305
4246
  };
@@ -4938,10 +4879,7 @@ async function getBuildDependencies(context, environmentContext, additionalDepen
4938
4879
  tailwindConfig
4939
4880
  ]), additionalDependencies && (buildDependencies.additional = additionalDependencies), buildDependencies;
4940
4881
  }
4941
- let addTrailingSep = (dir)=>dir.endsWith(sep) ? dir : dir + sep, isStrictSubdir = (parent, child)=>{
4942
- let parentDir = addTrailingSep(parent), childDir = addTrailingSep(child);
4943
- return parentDir !== childDir && childDir.startsWith(parentDir);
4944
- }, normalizeCleanDistPath = (userOptions)=>{
4882
+ let normalizeCleanDistPath = (userOptions)=>{
4945
4883
  let defaultOptions = {
4946
4884
  enable: 'auto'
4947
4885
  };
@@ -5012,7 +4950,7 @@ function parseMinifyOptions(config) {
5012
4950
  cssOptions: minify.cssOptions
5013
4951
  };
5014
4952
  }
5015
- var postcss_load_config_src_default = compatGetDefaultExport(rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/d0e1ffed59e3d657674e04f8f91182ccde1db31e7c7c0f00dd625e998ab50180/node_modules/postcss-load-config/src/index.js"));
4953
+ var postcss_load_config_src_default = compatGetDefaultExport(rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/baf07bf9099810ce2e0c00768f056c90b47d57b154f4b8912460449b9922899a/node_modules/postcss-load-config/src/index.js"));
5016
4954
  async function getLightningCSSLoaderOptions(config, targets, minify) {
5017
4955
  let userOptions = 'object' == typeof config.tools.lightningcssLoader ? config.tools.lightningcssLoader : {}, initialOptions = {
5018
4956
  targets,
@@ -5045,7 +4983,7 @@ let getPostcssLoaderOptions = async ({ config, root, postcssrcCache })=>{
5045
4983
  let extraPlugins = [], userOptions = await loadUserPostcssrc(root, postcssrcCache);
5046
4984
  userOptions.plugins ||= [];
5047
4985
  let defaultOptions = {
5048
- implementation: join(COMPILED_PATH, 'postcss', 'index.js'),
4986
+ implementation: getCompiledPath('postcss'),
5049
4987
  postcssOptions: userOptions,
5050
4988
  sourceMap: getCSSSourceMap(config)
5051
4989
  }, finalOptions = await reduceConfigsWithContext({
@@ -5193,12 +5131,35 @@ function pluginExternals() {
5193
5131
  ...autoExternalRules
5194
5132
  ] : autoExternalRules : externals;
5195
5133
  mergedExternals && chain.externals(mergedExternals);
5196
- }), api.onBeforeCreateCompiler(({ bundlerConfigs })=>{
5197
- for (let config of bundlerConfigs)(Array.isArray(config.target) ? config.target.includes('webworker') : 'webworker' === config.target) && config.externals && delete config.externals;
5198
5134
  });
5199
5135
  }
5200
5136
  };
5201
5137
  }
5138
+ function createAssetProcessor() {
5139
+ let failure, active = 0, waiting = [];
5140
+ return async (names, processAsset)=>{
5141
+ let cursor = 0, consume = async ()=>{
5142
+ for(; cursor < names.length && !failure;){
5143
+ let index = cursor++;
5144
+ active >= 16 ? await new Promise((resolve)=>waiting.push(resolve)) : active++;
5145
+ try {
5146
+ if (failure) return;
5147
+ await processAsset(names[index], index);
5148
+ } catch (error) {
5149
+ failure ??= {
5150
+ error
5151
+ };
5152
+ } finally{
5153
+ let next = waiting.shift();
5154
+ next ? next() : active--;
5155
+ }
5156
+ }
5157
+ };
5158
+ if (await Promise.all(Array.from({
5159
+ length: Math.min(16, names.length)
5160
+ }, consume)), failure) throw failure.error;
5161
+ };
5162
+ }
5202
5163
  function getCompression(compressed) {
5203
5164
  let { type = 'gzip', level = 6 } = 'object' == typeof compressed ? compressed : {};
5204
5165
  return 'brotli' === type ? {
@@ -5217,19 +5178,19 @@ function getCompression(compressed) {
5217
5178
  totalKey: 'totalGzipSize'
5218
5179
  };
5219
5180
  }
5220
- async function calcCompressedSize(input, type, level) {
5221
- return (await new Promise((resolve, reject)=>{
5222
- let callback = (err, result)=>{
5223
- err ? reject(err) : resolve(result);
5224
- };
5225
- 'brotli' === type ? node_zlib.brotliCompress(input, {
5181
+ function calcCompressedSize(input, type, level) {
5182
+ return new Promise((resolve, reject)=>{
5183
+ let stream = 'brotli' === type ? node_zlib.createBrotliCompress({
5226
5184
  params: {
5227
5185
  [node_zlib.constants.BROTLI_PARAM_QUALITY]: level
5228
5186
  }
5229
- }, callback) : node_zlib.gzip(input, {
5187
+ }) : node_zlib.createGzip({
5230
5188
  level
5231
- }, callback);
5232
- })).length;
5189
+ }), size = 0;
5190
+ stream.on('data', (chunk)=>{
5191
+ size += chunk.length;
5192
+ }), stream.on('error', reject), stream.on('end', ()=>resolve(size)), stream.end(input);
5193
+ });
5233
5194
  }
5234
5195
  function getSnapshotPath(dir, snapshotHash) {
5235
5196
  return snapshotHash ? node_path.join(dir, `rsbuild/file-sizes-${snapshotHash}.json`) : node_path.join(dir, 'rsbuild/file-sizes.json');
@@ -5279,11 +5240,30 @@ function getHeader(maxFileLength, maxSizeLength, fileHeader, compressionHeader)
5279
5240
  let calcFileSize = (len)=>{
5280
5241
  let val = len / 1000;
5281
5242
  return `${val.toFixed(val < 1 ? 2 : 1)} kB`;
5282
- }, COMPRESSIBLE_REGEX = /\.(?:js|mjs|cjs|jsx|ts|tsx|mts|cts|css|html|json|svg|txt|xml|xhtml|wasm|manifest|md)$/i, isCompressible = (assetName)=>COMPRESSIBLE_REGEX.test(assetName), getFilePath = (assetName)=>{
5283
- let queryIndex = assetName.indexOf('?');
5284
- return -1 === queryIndex ? assetName : assetName.slice(0, queryIndex);
5285
- };
5286
- async function printFileSizes(options, stats, rootPath, distPath, environmentName, previousSizes, saveSnapshot) {
5243
+ }, COMPRESSIBLE_REGEX = /\.(?:js|mjs|cjs|jsx|ts|tsx|mts|cts|css|html|json|svg|txt|xml|xhtml|wasm|manifest|md)$/i;
5244
+ async function getFileSizes(options, compilation, processAssets) {
5245
+ if (!1 === options.detail && !1 === options.total) return [];
5246
+ let { exclude, include } = options, compression = getCompression(options.compressed), fileSizes = [], compilationAssets = compilation.assets, names = Object.getOwnPropertyNames(compilationAssets);
5247
+ return await processAssets(names, async (assetName, index)=>{
5248
+ let queryIndex, filePath = -1 === (queryIndex = assetName.indexOf('?')) ? assetName : assetName.slice(0, queryIndex);
5249
+ if (!exclude && EXCLUDE_ASSET_REGEX.test(filePath)) return;
5250
+ let value = compilationAssets[assetName], content = options.compressed && COMPRESSIBLE_REGEX.test(filePath) ? value.buffer() : void 0, size = void 0 === content ? value.size() : content.length;
5251
+ if (exclude || include) {
5252
+ let publicAsset = {
5253
+ name: filePath,
5254
+ size
5255
+ };
5256
+ if (exclude?.(publicAsset) || include && !include(publicAsset)) return;
5257
+ }
5258
+ let compressedSize = void 0 === content ? null : await calcCompressedSize(content, compression.type, compression.level);
5259
+ fileSizes[index] = {
5260
+ filePath,
5261
+ size,
5262
+ compressedSize
5263
+ };
5264
+ }), fileSizes.filter(Boolean);
5265
+ }
5266
+ function printFileSizes(options, fileSizes, rootPath, distPath, environmentName, previousSizes, saveSnapshot) {
5287
5267
  let logs = [], compression = getCompression(options.compressed), prev = previousSizes?.[environmentName], showDetail = !1 !== options.detail, showDiff = !1 !== options.diff && null !== previousSizes, prevType = prev?.compressionType ?? (!!prev?.totalGzipSize && 'gzip'), showCompressedDiff = showDiff && prevType === compression.type, showTotal = !1 !== options.total;
5288
5268
  if (!showTotal && !showDetail) return {
5289
5269
  logs
@@ -5293,52 +5273,45 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
5293
5273
  totalSize: 0,
5294
5274
  totalGzipSize: 0,
5295
5275
  compressionType: !!options.compressed && compression.type
5296
- } : null, formatAsset = (filePath, size, compressedSize)=>{
5297
- let normalizedPath = '';
5298
- (snapshot || showDiff) && (normalizedPath = normalizeFilePath(filePath), snapshot && (snapshot.files[normalizedPath] = {
5299
- size,
5300
- [compression.sizeKey]: compressedSize ?? void 0
5301
- }));
5302
- let sizeLabel = calcFileSize(size), sizeLabelLength = sizeLabel.length, compressedSizeLabel = compressedSize ? getAssetColor(compressedSize)(calcFileSize(compressedSize)) : null;
5303
- if (showDiff) {
5304
- let sizeData = prev?.files[normalizedPath], sizeDiff = size - (sizeData?.size ?? 0);
5305
- if (isSignificantDiff(sizeDiff)) {
5306
- let { label, length } = formatDiff(sizeDiff);
5307
- sizeLabel += ` ${label}`, sizeLabelLength += length + 1;
5308
- }
5309
- if (null !== compressedSize && showCompressedDiff) {
5310
- let compressedDiff = compressedSize - (sizeData?.[compression.sizeKey] ?? 0);
5311
- isSignificantDiff(compressedDiff) && (compressedSizeLabel += ` ${formatDiff(compressedDiff).label}`);
5312
- }
5313
- }
5314
- let separatorIndex = filePath.lastIndexOf('/'), folderLabel = -1 === separatorIndex ? rootFolderLabel : `${node_path.join(relativeDistPath, filePath.slice(0, separatorIndex))}${node_path.sep}`, filename = -1 === separatorIndex ? filePath : filePath.slice(separatorIndex + 1);
5315
- return {
5316
- filePath,
5317
- filenameLabel: color.dim(folderLabel) + (JS_REGEX.test(filename) ? color.cyan(filename) : filename.endsWith('.css') ? color.yellow(filename) : filename.endsWith('.html') ? color.green(filename) : color.magenta(filename)),
5318
- filenameLength: folderLabel.length + filename.length,
5319
- size,
5320
- sizeLabel,
5321
- sizeLabelLength,
5322
- compressedSize,
5323
- compressedSizeLabel
5324
- };
5325
- }, getAssets = async ()=>{
5326
- let { exclude, include } = options, formattedAssets = [], compilationAssets = stats.compilation.assets;
5327
- for (let assetName of Object.keys(compilationAssets)){
5328
- let filePath = getFilePath(assetName);
5329
- if (!exclude && EXCLUDE_ASSET_REGEX.test(filePath)) continue;
5330
- let value = compilationAssets[assetName], content = options.compressed && isCompressible(filePath) ? value.source() : void 0, size = void 0 === content ? value.size() : Buffer.byteLength(content);
5331
- if (exclude || include) {
5332
- let publicAsset = {
5333
- name: filePath,
5334
- size
5335
- };
5336
- if (exclude?.(publicAsset) || include && !include(publicAsset)) continue;
5276
+ } : null, assets = fileSizes.map(({ filePath, size, compressedSize })=>((filePath, size, compressedSize)=>{
5277
+ let normalizedPath = '';
5278
+ if ((snapshot || showDetail && showDiff) && (normalizedPath = normalizeFilePath(filePath), snapshot && (snapshot.files[normalizedPath] = {
5279
+ size,
5280
+ [compression.sizeKey]: compressedSize ?? void 0
5281
+ })), !showDetail) return {
5282
+ filePath,
5283
+ filenameLabel: '',
5284
+ filenameLength: 0,
5285
+ size,
5286
+ sizeLabel: '',
5287
+ sizeLabelLength: 0,
5288
+ compressedSize,
5289
+ compressedSizeLabel: null
5290
+ };
5291
+ let sizeLabel = calcFileSize(size), sizeLabelLength = sizeLabel.length, compressedSizeLabel = compressedSize ? getAssetColor(compressedSize)(calcFileSize(compressedSize)) : null;
5292
+ if (showDiff) {
5293
+ let sizeData = prev?.files[normalizedPath], sizeDiff = size - (sizeData?.size ?? 0);
5294
+ if (isSignificantDiff(sizeDiff)) {
5295
+ let { label, length } = formatDiff(sizeDiff);
5296
+ sizeLabel += ` ${label}`, sizeLabelLength += length + 1;
5297
+ }
5298
+ if (null !== compressedSize && showCompressedDiff) {
5299
+ let compressedDiff = compressedSize - (sizeData?.[compression.sizeKey] ?? 0);
5300
+ isSignificantDiff(compressedDiff) && (compressedSizeLabel += ` ${formatDiff(compressedDiff).label}`);
5301
+ }
5337
5302
  }
5338
- void 0 === content ? formattedAssets.push(formatAsset(filePath, size, null)) : formattedAssets.push(calcCompressedSize(content, compression.type, compression.level).then((compressedSize)=>formatAsset(filePath, size, compressedSize)));
5339
- }
5340
- return (await Promise.all(formattedAssets)).sort((a, b)=>a.size - b.size);
5341
- }, assets = await getAssets();
5303
+ let separatorIndex = filePath.lastIndexOf('/'), folderLabel = -1 === separatorIndex ? rootFolderLabel : `${node_path.join(relativeDistPath, filePath.slice(0, separatorIndex))}${node_path.sep}`, filename = -1 === separatorIndex ? filePath : filePath.slice(separatorIndex + 1);
5304
+ return {
5305
+ filePath,
5306
+ filenameLabel: color.dim(folderLabel) + (JS_REGEX.test(filename) ? color.cyan(filename) : filename.endsWith('.css') ? color.yellow(filename) : filename.endsWith('.html') ? color.green(filename) : color.magenta(filename)),
5307
+ filenameLength: folderLabel.length + filename.length,
5308
+ size,
5309
+ sizeLabel,
5310
+ sizeLabelLength,
5311
+ compressedSize,
5312
+ compressedSizeLabel
5313
+ };
5314
+ })(filePath, size, compressedSize)).sort((a, b)=>a.size - b.size);
5342
5315
  if (0 === assets.length) return {
5343
5316
  logs
5344
5317
  };
@@ -5422,7 +5395,18 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
5422
5395
  snapshot
5423
5396
  };
5424
5397
  }
5425
- let isNonceTag = (tag)=>"script" === tag.tag || 'style' === tag.tag || 'link' === tag.tag && tag.attrs?.rel === 'preload' && tag.attrs?.as === "script", entryNameSymbol = Symbol('entryName'), VOID_TAGS = [
5398
+ let fileSize_normalizeConfig = (config)=>{
5399
+ let { printFileSize } = config.performance, defaultConfig = {
5400
+ total: !0,
5401
+ detail: !0,
5402
+ diff: !1,
5403
+ compressed: 'node' !== config.output.target
5404
+ };
5405
+ return !0 === printFileSize ? defaultConfig : {
5406
+ ...defaultConfig,
5407
+ ...printFileSize
5408
+ };
5409
+ }, isNonceTag = (tag)=>"script" === tag.tag || 'style' === tag.tag || 'link' === tag.tag && tag.attrs?.rel === 'preload' && tag.attrs?.as === "script", entryNameSymbol = Symbol('entryName'), VOID_TAGS = [
5426
5410
  'area',
5427
5411
  'base',
5428
5412
  'br',
@@ -5874,7 +5858,7 @@ let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
5874
5858
  });
5875
5859
  });
5876
5860
  } catch (e) {
5877
- if ('EADDRINUSE' !== e.code) throw e;
5861
+ if (!(e instanceof Error) || !('code' in e) || 'EADDRINUSE' !== e.code) throw e;
5878
5862
  port++, attempts++;
5879
5863
  }
5880
5864
  if (!found) throw Error(`${color.dim('[rsbuild:server]')} Failed to find an available port after ${tryLimits + 1} attempts, starting from ${color.yellow(original)}.`);
@@ -6074,7 +6058,7 @@ function doesChunkBelongToHtml({ chunk, htmlPluginData }) {
6074
6058
  let { options } = htmlPluginData.plugin;
6075
6059
  return recursiveChunkEntryNames(chunk).some((chunkName)=>isChunksFiltered(chunkName, options?.chunks, options?.excludeChunks));
6076
6060
  }
6077
- let getManifestPlugin = cachedImport(()=>import("./manifest-plugin.js").then(rspackRequire.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/rspack-manifest-plugin/5.2.2/5acfc0b855cb5cd205a81b2c264b6bdf3a41cbc273715b263f9fdb82cc7ae49c/node_modules/rspack-manifest-plugin/dist/index.js"))), isCSSPath = (filePath)=>filePath.endsWith('.css');
6061
+ let getManifestPlugin = cachedImport_cachedImport(()=>import("./manifest-plugin.js").then(rspackRequire.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/rspack-manifest-plugin/5.2.2/cbeeb1bf16831c5d12121244c2e0e825d7a61324a587214ca9e44e464c6b1496/node_modules/rspack-manifest-plugin/dist/index.js"))), isCSSPath = (filePath)=>filePath.endsWith('.css');
6078
6062
  function normalizeManifestObjectConfig(manifest) {
6079
6063
  let defaultOptions = {
6080
6064
  prefix: !0,
@@ -6138,7 +6122,7 @@ async function applyAlias({ chain, config, rootPath, logger }) {
6138
6122
  continue;
6139
6123
  }
6140
6124
  try {
6141
- pkgPath = external_node_path_dirname(vendors_require.resolve(`${pkgName}/package.json`, {
6125
+ pkgPath = dirname(vendors_require.resolve(`${pkgName}/package.json`, {
6142
6126
  paths: [
6143
6127
  rootPath
6144
6128
  ]
@@ -6154,7 +6138,7 @@ async function applyAlias({ chain, config, rootPath, logger }) {
6154
6138
  'node_modules',
6155
6139
  ...pkgName.split('/')
6156
6140
  ].join(sep);
6157
- for(; !pkgPath.endsWith(trailing) && pkgPath.includes('node_modules');)pkgPath = external_node_path_dirname(pkgPath);
6141
+ for(; !pkgPath.endsWith(trailing) && pkgPath.includes('node_modules');)pkgPath = dirname(pkgPath);
6158
6142
  } catch {
6159
6143
  logger.debug(`${color.dim('[rsbuild:resolve]')} The package ${color.yellow(pkgName)} is not resolved in the project, dedupe option for ${color.yellow(pkgName)} will be ignored.`);
6160
6144
  continue;
@@ -6760,7 +6744,7 @@ function destroyStream(stream, suppress) {
6760
6744
  'number' == typeof fd && this.close();
6761
6745
  }), 'function' == typeof stream.addListener && suppress && (stream.removeAllListeners('error'), stream.addListener('error', ()=>{}));
6762
6746
  }
6763
- let getRangeParser = cachedImport(()=>import("./range-parser.js").then(createFakeNamespaceObject.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/range-parser/1.3.0/d49e5dcb9d0e39475844e240fad8cd1db6a58f4144f7ede43d9755e2fce5babc/node_modules/range-parser/index.js", 23))), parseRangeHeaders = async (value)=>{
6747
+ let getRangeParser = cachedImport_cachedImport(()=>import("./range-parser.js").then(createFakeNamespaceObject.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/range-parser/1.3.0/d49e5dcb9d0e39475844e240fad8cd1db6a58f4144f7ede43d9755e2fce5babc/node_modules/range-parser/index.js", 23))), parseRangeHeaders = async (value)=>{
6764
6748
  let { default: rangeParser } = await getRangeParser(), [len, rangeHeader] = value.split('|');
6765
6749
  return rangeParser(Number(len), rangeHeader, {
6766
6750
  combine: !0
@@ -6843,6 +6827,10 @@ function createAssetsMiddleware(context, ready, outputFileSystem) {
6843
6827
  }
6844
6828
  -2 === parsedRanges ? logger.error("[rsbuild:middleware] A malformed 'Range' header was provided. A regular response will be sent for this request.") : parsedRanges.length > 1 && logger.error("[rsbuild:middleware] A 'Range' header with multiple ranges was provided. Multiple ranges are not supported, so a regular response will be sent for this request."), -2 !== parsedRanges && 1 === parsedRanges.length && (res.statusCode = 206, res.setHeader('Content-Range', getValueContentRangeHeader('bytes', size, parsedRanges[0])), [offset, len] = getOffsetAndLenFromRange(parsedRanges[0]));
6845
6829
  }
6830
+ if ('HEAD' === req.method) {
6831
+ res.setHeader('Content-Length', len), 404 === res.statusCode && (res.statusCode = 200), res.end();
6832
+ return;
6833
+ }
6846
6834
  let [start, end] = calcStartAndEnd(offset, len);
6847
6835
  try {
6848
6836
  readStream = createReadStream(filename, outputFileSystem, start, end);
@@ -6850,10 +6838,7 @@ function createAssetsMiddleware(context, ready, outputFileSystem) {
6850
6838
  await goNext();
6851
6839
  return;
6852
6840
  }
6853
- if (res.setHeader('Content-Length', len), 'HEAD' === req.method) {
6854
- 404 === res.statusCode && (res.statusCode = 200), res.end();
6855
- return;
6856
- }
6841
+ res.setHeader('Content-Length', len);
6857
6842
  let cleanup = ()=>{
6858
6843
  destroyStream(readStream, !0);
6859
6844
  };
@@ -6871,37 +6856,41 @@ function createAssetsMiddleware(context, ready, outputFileSystem) {
6871
6856
  });
6872
6857
  };
6873
6858
  }
6874
- async function setupOutputFileSystem(writeToDisk, compilers) {
6875
- if (!0 !== writeToDisk) {
6859
+ async function setupOutputFileSystem(writeAllToDisk, compilers) {
6860
+ if (!writeAllToDisk) {
6876
6861
  let { createMemoryFileSystem } = await import("./memfs.js"), outputFileSystem = createMemoryFileSystem();
6877
6862
  for (let compiler of compilers)compiler.outputFileSystem = outputFileSystem;
6878
6863
  }
6879
6864
  let compiler = compilers.find((compiler)=>!!compiler.outputFileSystem);
6880
6865
  return compiler?.outputFileSystem ?? node_fs;
6881
6866
  }
6882
- function setupWriteToDisk(compilers, writeToDisk, logger) {
6883
- for (let compiler of compilers)compiler.hooks.emit.tap('DevMiddleware', ()=>{
6884
- compiler.__hasRsbuildAssetEmittedCallback || (compiler.hooks.assetEmitted.tapAsync('DevMiddleware', (_file, info, callback)=>{
6885
- let { targetPath, content, compilation } = info;
6886
- if (!(!writeToDisk || 'function' != typeof writeToDisk || writeToDisk(targetPath, compilation.name))) return void callback();
6887
- let dir = node_path.dirname(targetPath), name = compiler.options.name ? `Child "${compiler.options.name}": ` : '';
6888
- node_fs.mkdir(dir, {
6889
- recursive: !0
6890
- }, (mkdirError)=>{
6891
- if (mkdirError) {
6892
- logger.error(`[rsbuild:middleware] ${name}Unable to write "${dir}" directory to disk:\n${mkdirError.message}`), callback(mkdirError);
6893
- return;
6894
- }
6895
- node_fs.writeFile(targetPath, content, (writeFileError)=>{
6896
- if (writeFileError) {
6897
- logger.error(`[rsbuild:middleware] ${name}Unable to write "${targetPath}" asset to disk:\n${writeFileError.message}`), callback(writeFileError);
6867
+ function setupWriteToDisk(compilers, writeToDiskList, logger) {
6868
+ for (let [index, compiler] of compilers.entries()){
6869
+ let writeToDisk = writeToDiskList[index];
6870
+ writeToDisk && compiler.hooks.emit.tap('DevMiddleware', ()=>{
6871
+ compiler.__hasRsbuildAssetEmittedCallback || (compiler.hooks.assetEmitted.tapAsync('DevMiddleware', (_file, info, callback)=>{
6872
+ if (compiler.outputFileSystem === node_fs) return void callback();
6873
+ let { targetPath } = info;
6874
+ if ('function' == typeof writeToDisk && !writeToDisk(targetPath)) return void callback();
6875
+ let { content } = info, dir = node_path.dirname(targetPath), name = compiler.options.name ? `Child "${compiler.options.name}": ` : '';
6876
+ node_fs.mkdir(dir, {
6877
+ recursive: !0
6878
+ }, (mkdirError)=>{
6879
+ if (mkdirError) {
6880
+ logger.error(`[rsbuild:middleware] ${name}Unable to write "${dir}" directory to disk:\n${mkdirError.message}`), callback(mkdirError);
6898
6881
  return;
6899
6882
  }
6900
- callback();
6883
+ node_fs.writeFile(targetPath, content, (writeFileError)=>{
6884
+ if (writeFileError) {
6885
+ logger.error(`[rsbuild:middleware] ${name}Unable to write "${targetPath}" asset to disk:\n${writeFileError.message}`), callback(writeFileError);
6886
+ return;
6887
+ }
6888
+ callback();
6889
+ });
6901
6890
  });
6902
- });
6903
- }), compiler.__hasRsbuildAssetEmittedCallback = !0);
6904
- });
6891
+ }), compiler.__hasRsbuildAssetEmittedCallback = !0);
6892
+ });
6893
+ }
6905
6894
  }
6906
6895
  let noop = ()=>{}, normalizeLiveReload = (liveReload)=>'boolean' == typeof liveReload ? {
6907
6896
  enabled: liveReload,
@@ -6940,8 +6929,7 @@ init(
6940
6929
  }).apply(compiler);
6941
6930
  }
6942
6931
  let assets_middleware_assetsMiddleware = async ({ config, compiler, context, socketServer, resolvedPort })=>{
6943
- var config1;
6944
- let watching, writeToDiskValues, { logger } = context, resolvedHost = await resolveHostname(config.server.host), { environments, environmentList } = context;
6932
+ let watching, { logger } = context, resolvedHost = await resolveHostname(config.server.host), { environmentList } = context;
6945
6933
  applyToCompiler(compiler, (compiler, index)=>{
6946
6934
  let environment = environmentList[index];
6947
6935
  if (!environment) return;
@@ -7005,14 +6993,11 @@ let assets_middleware_assetsMiddleware = async ({ config, compiler, context, soc
7005
6993
  'done' === context.buildState.status && flushCallbacks();
7006
6994
  });
7007
6995
  });
7008
- let writeToDisk = (config1 = config.dev, 1 === new Set(writeToDiskValues = environmentList.map((env)=>env.config.dev.writeToDisk)).size ? writeToDiskValues[0] : (filePath, name)=>{
7009
- let { writeToDisk } = config1;
7010
- return name && environments[name] && (writeToDisk = environments[name].config.dev.writeToDisk ?? writeToDisk), 'function' == typeof writeToDisk ? writeToDisk(filePath) : writeToDisk;
7011
- });
7012
- writeToDisk && setupWriteToDisk(compilers, writeToDisk, logger);
6996
+ let writeToDiskList = environmentList.map((environment)=>environment.config.dev.writeToDisk);
6997
+ writeToDiskList.some(Boolean) && setupWriteToDisk(compilers, writeToDiskList, logger);
7013
6998
  let instance = createAssetsMiddleware(context, (callback)=>{
7014
6999
  'done' === context.buildState.status || 'failed' === context.buildState.status ? callback() : callbacks.push(callback);
7015
- }, await setupOutputFileSystem(writeToDisk, compilers));
7000
+ }, await setupOutputFileSystem(writeToDiskList.every((writeToDisk)=>!0 === writeToDisk), compilers));
7016
7001
  return instance.watch = ()=>{
7017
7002
  if (compiler.watching) watching = compiler.watching;
7018
7003
  else {
@@ -7093,15 +7078,17 @@ function parseNode(line) {
7093
7078
  column: parts[4] ? +parts[4] : null
7094
7079
  } : null;
7095
7080
  }
7096
- let getTraceMapping = cachedImport(()=>import("./trace-mapping.js").then((m)=>m.trace_mapping_namespaceObject)), isValidMethodName = (methodName)=>'<unknown>' !== methodName && !/[\\/]/.test(methodName), isRspackRuntimeStack = (value)=>!!value && (value.includes('__webpack_require__') || value.startsWith('webpack/runtime/')), parseFrame = async (frame, fs, context, cachedTraceMap)=>{
7097
- let { file, column, lineNumber } = frame, sourceMapInfo = await getFileFromUrl(`${file}.map`, fs, context);
7098
- if (!sourceMapInfo || 'errorCode' in sourceMapInfo) return;
7099
- let { TraceMap, originalPositionFor } = await getTraceMapping(), sourceMapPath = sourceMapInfo.filename;
7081
+ let getTraceMapping = cachedImport_cachedImport(()=>import("./trace-mapping.js").then((m)=>m.trace_mapping_namespaceObject)), isValidMethodName = (methodName)=>'<unknown>' !== methodName && !/[\\/]/.test(methodName), isRspackRuntimeStack = (value)=>!!value && (value.includes('__webpack_require__') || value.startsWith('webpack/runtime/')), parseFrame = async (frame, fs, context, cache)=>{
7082
+ let { file, column, lineNumber } = frame, sourceMapUrl = `${file}.map`, sourceMapPathPromise = cache.sourceMapPaths.get(sourceMapUrl);
7083
+ sourceMapPathPromise || (sourceMapPathPromise = getFileFromUrl(sourceMapUrl, fs, context).then((info)=>!info || 'errorCode' in info ? void 0 : info.filename), cache.sourceMapPaths.set(sourceMapUrl, sourceMapPathPromise));
7084
+ let sourceMapPath = await sourceMapPathPromise;
7085
+ if (!sourceMapPath) return;
7086
+ let { TraceMap, originalPositionFor } = await getTraceMapping();
7100
7087
  try {
7101
- let tracer = cachedTraceMap.get(sourceMapPath);
7088
+ let tracer = cache.traceMaps.get(sourceMapPath);
7102
7089
  if (!tracer) {
7103
7090
  let sourceMap = await readFileAsync(fs, sourceMapPath);
7104
- tracer = new TraceMap(sourceMap.toString()), cachedTraceMap.set(sourceMapPath, tracer);
7091
+ tracer = new TraceMap(sourceMap.toString()), cache.traceMaps.set(sourceMapPath, tracer);
7105
7092
  }
7106
7093
  let originalPosition = originalPositionFor(tracer, {
7107
7094
  line: lineNumber ?? 0,
@@ -7114,10 +7101,10 @@ let getTraceMapping = cachedImport(()=>import("./trace-mapping.js").then((m)=>m.
7114
7101
  } catch (error) {
7115
7102
  error instanceof Error && context.logger.debug('failed to map source map position:', error);
7116
7103
  }
7117
- }, resolveOriginalLocation = async (stackFrames, fs, context, cachedTraceMap)=>{
7104
+ }, resolveOriginalLocation = async (stackFrames, fs, context, cache)=>{
7118
7105
  let frame = stackFrames.find((frame)=>null !== frame.file && null !== frame.column && null !== frame.lineNumber && SCRIPT_REGEX.test(frame.file));
7119
7106
  if (!frame) return;
7120
- let parsedFrame = await parseFrame(frame, fs, context, cachedTraceMap);
7107
+ let parsedFrame = await parseFrame(frame, fs, context, cache);
7121
7108
  if (!parsedFrame) return;
7122
7109
  let { sourceMapPath, originalPosition } = parsedFrame;
7123
7110
  return {
@@ -7136,10 +7123,10 @@ let getTraceMapping = cachedImport(()=>import("./trace-mapping.js").then((m)=>m.
7136
7123
  }, formatFrameLocation = (frame)=>{
7137
7124
  let { file, lineNumber, column } = frame;
7138
7125
  if (file) return null !== lineNumber ? null !== column ? `${file}:${lineNumber}:${column}` : `${file}:${lineNumber}` : file;
7139
- }, formatFullStack = async (stackFrames, context, fs, cachedTraceMap)=>{
7126
+ }, formatFullStack = async (stackFrames, context, fs, cache)=>{
7140
7127
  let formattedFrames = [];
7141
7128
  for (let frame of stackFrames){
7142
- let location, parsedFrame = await parseFrame(frame, fs, context, cachedTraceMap), { methodName } = frame, parts = [];
7129
+ let location, parsedFrame = await parseFrame(frame, fs, context, cache), { methodName } = frame, parts = [];
7143
7130
  isValidMethodName(methodName) && parts.push(methodName);
7144
7131
  let parsed = !1;
7145
7132
  if (parsedFrame) {
@@ -7162,13 +7149,13 @@ let getTraceMapping = cachedImport(()=>import("./trace-mapping.js").then((m)=>m.
7162
7149
  }
7163
7150
  let shouldFilterRspackRuntime = formattedFrames.some((frame)=>!frame.isRspackRuntime && frame.hasLocation);
7164
7151
  return formattedFrames.filter((frame)=>!(shouldFilterRspackRuntime && frame.isRspackRuntime)).map((frame)=>frame.text).join('');
7165
- }, formatBrowserErrorLog = async (message, context, fs, stackTrace, stackFrames, cachedTraceMap)=>{
7152
+ }, formatBrowserErrorLog = async (message, context, fs, stackTrace, stackFrames, cache)=>{
7166
7153
  var log;
7167
7154
  let log1 = color.red(message);
7168
7155
  if (stackFrames?.length) switch(stackTrace){
7169
7156
  case 'summary':
7170
7157
  {
7171
- let resolved = await resolveOriginalLocation(stackFrames, fs, context, cachedTraceMap);
7158
+ let resolved = await resolveOriginalLocation(stackFrames, fs, context, cache);
7172
7159
  if (!resolved) break;
7173
7160
  let { frame, location } = resolved, { methodName } = frame, suffix = '';
7174
7161
  isValidMethodName(methodName) && (suffix += ` at ${methodName}`), location && (suffix += ` (${location})`), log1 += suffix ? color.dim(suffix) : '';
@@ -7176,7 +7163,7 @@ let getTraceMapping = cachedImport(()=>import("./trace-mapping.js").then((m)=>m.
7176
7163
  }
7177
7164
  case 'full':
7178
7165
  {
7179
- let fullStack = await formatFullStack(stackFrames, context, fs, cachedTraceMap);
7166
+ let fullStack = await formatFullStack(stackFrames, context, fs, cache);
7180
7167
  fullStack && (log1 += fullStack);
7181
7168
  }
7182
7169
  }
@@ -7356,8 +7343,11 @@ class SocketServer {
7356
7343
  if (!environment) return;
7357
7344
  let { browserLogs, client } = environment.config.dev;
7358
7345
  if ('client-error' === payload.type && !context.buildState.hasErrors && browserLogs) {
7359
- let stackTrace = isObject(browserLogs) && browserLogs.stackTrace || DEFAULT_STACK_TRACE, outputFs = this.getOutputFileSystem(), stackFrames = payload.stack ? stack_trace_parser_esm_parse(payload.stack) : null, cachedTraceMap = new Map(), log = await formatBrowserErrorLog(payload.message, context, outputFs, stackTrace, stackFrames, cachedTraceMap);
7360
- if (this.reportedBrowserLogs.has(log) || (this.reportedBrowserLogs.add(log), this.context.logger.error(`${color.cyan('[browser]')} ${log}`)), ((overlay, payload)=>{
7346
+ let stackTrace = isObject(browserLogs) && browserLogs.stackTrace || DEFAULT_STACK_TRACE, outputFs = this.getOutputFileSystem(), stackFrames = payload.stack ? stack_trace_parser_esm_parse(payload.stack) : null, cache = {
7347
+ sourceMapPaths: new Map(),
7348
+ traceMaps: new Map()
7349
+ }, log = await formatBrowserErrorLog(payload.message, context, outputFs, stackTrace, stackFrames, cache);
7350
+ if (this.reportedBrowserLogs.has(log) || (this.reportedBrowserLogs.add(log), this.context.logger.error(`${color.cyan(BROWSER_LOG_PREFIX)} ${log}`)), ((overlay, payload)=>{
7361
7351
  if (!isRuntimeOverlayEnabled(overlay)) return !1;
7362
7352
  if ('object' == typeof overlay && 'function' == typeof overlay.runtime) {
7363
7353
  let error;
@@ -7365,7 +7355,7 @@ class SocketServer {
7365
7355
  }
7366
7356
  return !0;
7367
7357
  })(client.overlay, payload)) {
7368
- let resolvedLog = 'full' === stackTrace ? log : await formatBrowserErrorLog(payload.message, context, outputFs, 'full', stackFrames, cachedTraceMap);
7358
+ let resolvedLog = 'full' === stackTrace ? log : await formatBrowserErrorLog(payload.message, context, outputFs, 'full', stackFrames, cache);
7369
7359
  this.sendMessage({
7370
7360
  type: 'resolved-client-error',
7371
7361
  data: {
@@ -7476,7 +7466,7 @@ class BuildManager {
7476
7466
  this.compiler.close(()=>{
7477
7467
  resolve();
7478
7468
  });
7479
- });
7469
+ }), this.context.socketServer === this.socketServer && (this.context.socketServer = void 0);
7480
7470
  }
7481
7471
  readFileSync = (fileName)=>'readFileSync' in this.outputFileSystem ? this.outputFileSystem.readFileSync(fileName, 'utf-8') : node_fs.readFileSync(fileName, 'utf-8');
7482
7472
  async setupCompilationMiddleware() {
@@ -7490,7 +7480,7 @@ class BuildManager {
7490
7480
  this.assetsMiddleware = middleware;
7491
7481
  }
7492
7482
  }
7493
- let isCliShortcutsEnabled = (config)=>config.dev.cliShortcuts && isTTY('stdin');
7483
+ let activeInterfaces = 0, isCliShortcutsEnabled = (config)=>config.dev.cliShortcuts && isTTY('stdin');
7494
7484
  async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls, restartServer, customShortcuts, logger }) {
7495
7485
  let shortcuts = [
7496
7486
  {
@@ -7534,7 +7524,9 @@ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls,
7534
7524
  let { createInterface } = await import("node:readline"), rl = createInterface({
7535
7525
  input: process.stdin
7536
7526
  });
7537
- return rl.on('line', (input)=>{
7527
+ return activeInterfaces++, rl.once('close', ()=>{
7528
+ --activeInterfaces > 0 && process.stdin.resume();
7529
+ }), rl.on('line', (input)=>{
7538
7530
  if ('h' === (input = input.trim().toLowerCase())) {
7539
7531
  let message = `\n ${color.bold(color.blue('Shortcuts:'))}\n`;
7540
7532
  for (let shortcut of shortcuts)message += ` ${shortcut.description}\n`;
@@ -7557,7 +7549,11 @@ function gzipMiddleware_gzipMiddleware({ filter, level = node_zlib.constants.Z_B
7557
7549
  if (filter && !filter(req, res)) return void next();
7558
7550
  let accept = req.headers['accept-encoding'], encoding = 'string' == typeof accept && ENCODING_REGEX.test(accept);
7559
7551
  if ('HEAD' === req.method || !encoding) return void next();
7560
- 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 = ()=>{
7552
+ let started = !1, on = res.on.bind(res), end = res.end.bind(res), write = res.write.bind(res), writeHead = res.writeHead.bind(res), listeners = [];
7553
+ res.flush = ()=>{
7554
+ gzip?.flush(node_zlib.constants.Z_SYNC_FLUSH);
7555
+ };
7556
+ let start = ()=>{
7561
7557
  if (started) return;
7562
7558
  if (started = !0, ((res)=>{
7563
7559
  if (res.getHeader('Content-Encoding')) return !1;
@@ -7567,14 +7563,17 @@ function gzipMiddleware_gzipMiddleware({ filter, level = node_zlib.constants.Z_B
7567
7563
  if (!CONTENT_TYPE_REGEX.test(contentTypeValue) || 'text/event-stream' === contentTypeValue.split(';', 1)[0].trim().toLowerCase()) return !1;
7568
7564
  let size = res.getHeader('Content-Length');
7569
7565
  return void 0 === size || Number(size) > 1024;
7570
- })(res)) for (let listener of (res.setHeader('Content-Encoding', 'gzip'), res.removeHeader('Content-Length'), (gzip = node_zlib.createGzip({
7571
- level
7572
- })).on('data', (chunk)=>{
7573
- write(chunk) || gzip.pause();
7574
- }), on('drain', ()=>gzip.resume()), gzip.on('end', ()=>{
7575
- end();
7576
- }), listeners))gzip.on(...listener);
7577
- else for (let listener of listeners)on.apply(res, listener);
7566
+ })(res)) {
7567
+ let contentLength = Number(res.getHeader('Content-Length'));
7568
+ for (let listener of (res.setHeader('Content-Encoding', 'gzip'), res.removeHeader('Content-Length'), (gzip = node_zlib.createGzip({
7569
+ level,
7570
+ chunkSize: contentLength > 524288 ? 65536 : void 0
7571
+ })).on('data', (chunk)=>{
7572
+ write(chunk) || gzip.pause();
7573
+ }), on('drain', ()=>gzip.resume()), on('close', ()=>gzip.destroy()), gzip.on('end', ()=>{
7574
+ end();
7575
+ }), listeners))gzip.on(...listener);
7576
+ } else for (let listener of listeners)on.apply(res, listener);
7578
7577
  let statusCode = writeHeadStatus ?? res.statusCode;
7579
7578
  void 0 !== writeHeadMessage ? writeHead(statusCode, writeHeadMessage) : writeHead(statusCode);
7580
7579
  };
@@ -7679,7 +7678,17 @@ let faviconFallbackMiddleware = (req, res, next)=>{
7679
7678
  resolve(!!stats?.isFile());
7680
7679
  });
7681
7680
  }), isFileExistsInDistPaths = async (distPaths, filename, outputFileSystem)=>{
7682
- for (let distPath of distPaths)if (await middlewares_isFileExists(node_path.join(distPath, filename), outputFileSystem)) return !0;
7681
+ let decodedFilename;
7682
+ try {
7683
+ decodedFilename = decodeURIComponent(filename);
7684
+ } catch {
7685
+ return !1;
7686
+ }
7687
+ if (decodedFilename.includes('\0') || UP_PATH_REGEXP.test(decodedFilename) && UP_PATH_REGEXP.test(node_path.normalize(`./${decodedFilename}`))) return !1;
7688
+ for (let distPath of distPaths){
7689
+ let filePath = node_path.join(distPath, decodedFilename);
7690
+ if (await middlewares_isFileExists(filePath, outputFileSystem)) return !0;
7691
+ }
7683
7692
  return !1;
7684
7693
  }, maybeHTMLRequest = (req)=>{
7685
7694
  if (!req.url || !req.headers || 'GET' !== req.method && 'HEAD' !== req.method) return !1;
@@ -7737,14 +7746,14 @@ function formatProxyOptions(proxyOptions, logger) {
7737
7746
  let logPrefix = color.dim('[http-proxy-middleware]: '), defaultOptions = {
7738
7747
  changeOrigin: !0,
7739
7748
  logger: {
7740
- info (msg) {
7741
- logger.debug(logPrefix + msg);
7749
+ info (msg, ...args) {
7750
+ logger.debug(logPrefix + external_node_util_format(msg, ...args));
7742
7751
  },
7743
- warn: (msg)=>{
7744
- logger.warn(logPrefix + msg);
7752
+ warn: (msg, ...args)=>{
7753
+ logger.warn(logPrefix + external_node_util_format(msg, ...args));
7745
7754
  },
7746
- error: (msg)=>{
7747
- logger.error(logPrefix + msg);
7755
+ error: (msg, ...args)=>{
7756
+ logger.error(logPrefix + external_node_util_format(msg, ...args));
7748
7757
  }
7749
7758
  }
7750
7759
  };
@@ -7762,7 +7771,10 @@ function formatProxyOptions(proxyOptions, logger) {
7762
7771
  async function createProxyMiddleware(proxyOptions, logger) {
7763
7772
  let formattedOptions = formatProxyOptions(proxyOptions, logger), proxyMiddlewares = [], middlewares = [], { createProxyMiddleware: baseMiddleware } = await import("./http-proxy-middleware.js");
7764
7773
  for (let opts of formattedOptions){
7765
- let proxyMiddleware = baseMiddleware(opts), middleware = async (req, res, next)=>{
7774
+ let proxyMiddleware = baseMiddleware({
7775
+ ...opts,
7776
+ ws: !1
7777
+ }), middleware = async (req, res, next)=>{
7766
7778
  let bypassUrl = 'function' == typeof opts.bypass ? await opts.bypass(req, res, opts) : null;
7767
7779
  !1 === bypassUrl ? (res.statusCode = 404, next()) : 'string' == typeof bypassUrl ? (req.url = bypassUrl, next()) : !0 === bypassUrl ? next() : proxyMiddleware(req, res, next);
7768
7780
  };
@@ -7799,7 +7811,7 @@ let applyDefaultMiddlewares = async ({ config, buildManager, context, devServer,
7799
7811
  })), middlewares.use('/__open-in-editor', async (req, res, next)=>{
7800
7812
  try {
7801
7813
  (await (launchEditorHandlerPromise ??= (async ()=>{
7802
- let { default: launchEditorMiddleware } = await import("./launch-editor-middleware.js").then(createFakeNamespaceObject.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/launch-editor-middleware/2.14.1/6d555a60526ad6844dc2673e73b564ffd44ca896ac31b809c7cc243f8e135c00/node_modules/launch-editor-middleware/index.js", 23));
7814
+ let { default: launchEditorMiddleware } = await import("./launch-editor-middleware.js").then(createFakeNamespaceObject.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/launch-editor-middleware/2.14.2/46c81dbb0ad4cd8f776539a7cfaa5ea6144007363b919f05970ca6624282dcce/node_modules/launch-editor-middleware/index.js", 23));
7803
7815
  return launchEditorMiddleware();
7804
7816
  })()))(req, res, next);
7805
7817
  } catch (err) {
@@ -7867,7 +7879,10 @@ let applyDefaultMiddlewares = async ({ config, buildManager, context, devServer,
7867
7879
  environments: devServer.environments,
7868
7880
  logger
7869
7881
  })), buildManager && (middlewares.use(buildManager.assetsMiddleware), upgradeEvents.push(buildManager.socketServer.upgrade), middlewares.use(function hotUpdateJsonFallbackMiddleware(req, res, next) {
7870
- req.url?.endsWith('.hot-update.json') && 'OPTIONS' !== req.method ? notFoundMiddleware(req, res, next) : next();
7882
+ let url = req.url;
7883
+ if (!url || 'OPTIONS' === req.method) return void next();
7884
+ let queryIndex = url.indexOf('?'), end = -1 === queryIndex ? url.length : queryIndex;
7885
+ url.endsWith('.hot-update.json', end) || url.endsWith('.hot-update.json.mjs', end) ? notFoundMiddleware(req, res, next) : next();
7871
7886
  })), buildManager && middlewares.use(getHtmlCompletionMiddleware({
7872
7887
  assetsMiddleware: buildManager.assetsMiddleware,
7873
7888
  distPaths: [
@@ -8065,7 +8080,7 @@ class CommonJsRunner extends BasicRunner {
8065
8080
  let dynamicImport = cachedDynamicImport ??= Function('specifier', 'return import(specifier)');
8066
8081
  return vm.compileFunction(content, args, {
8067
8082
  filename: file.path,
8068
- importModuleDynamically: async (specifier)=>await dynamicImport(specifier)
8083
+ importModuleDynamically: dynamicImport
8069
8084
  }).call(m.exports, ...argValues), this.postExecute(m, file), m.exports;
8070
8085
  };
8071
8086
  }
@@ -8190,17 +8205,15 @@ let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>{
8190
8205
  cleanupCallbacks.add(callback);
8191
8206
  }, removeCleanup = (callback)=>{
8192
8207
  cleanupCallbacks.delete(callback);
8193
- }, shutdownRefCount = 0, setupGracefulShutdown = ()=>{
8194
- shutdownRefCount++;
8195
- let onSigterm = ()=>{
8196
- handleTermination(constants.signals.SIGTERM + 128);
8197
- };
8198
- process.once('SIGTERM', onSigterm);
8199
- let isCI = 'true' === process.env.CI, onStdinEnd = ()=>{
8200
- handleTermination(0);
8201
- };
8202
- return isCI || process.stdin.on('end', onStdinEnd), ()=>{
8203
- !(--shutdownRefCount > 0) && (process.removeListener('SIGTERM', onSigterm), isCI || process.stdin.removeListener('end', onStdinEnd));
8208
+ }, shutdownRefCount = 0, onSigterm = ()=>{
8209
+ handleTermination(constants.signals.SIGTERM + 128);
8210
+ }, onStdinEnd = ()=>{
8211
+ handleTermination(0);
8212
+ }, setupGracefulShutdown = ()=>{
8213
+ 1 == ++shutdownRefCount && (process.once('SIGTERM', onSigterm), isCI() || process.stdin.on('end', onStdinEnd));
8214
+ let cleanedUp = !1;
8215
+ return ()=>{
8216
+ cleanedUp || (cleanedUp = !0, --shutdownRefCount > 0 || (process.removeListener('SIGTERM', onSigterm), process.stdin.removeListener('end', onStdinEnd)));
8204
8217
  };
8205
8218
  }, createHttpServer = async ({ serverConfig, middlewares })=>{
8206
8219
  if (serverConfig.https) {
@@ -8213,7 +8226,44 @@ let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>{
8213
8226
  }
8214
8227
  let { createServer } = await import("node:http");
8215
8228
  return createServer(middlewares);
8216
- }, getPublicPathname = (publicPath)=>'auto' === publicPath || '' === publicPath ? '' : getPathnameFromUrl(publicPath.endsWith('/') ? publicPath : `${publicPath}/`), getPublicPathnames = (publicPaths, base)=>publicPaths.map(getPublicPathname).map((prefix)=>base && '/' !== base ? removeBasePath(prefix, base) : prefix);
8229
+ }, HOST_CHECK_ERROR = 'Blocked request: disallowed or invalid Host header. To allow a trusted hostname, add it to server.allowedHosts.';
8230
+ function createHostCheckMiddleware(allowedHosts) {
8231
+ return (req, res, next)=>{
8232
+ isRequestHostAllowed(req.headers, allowedHosts) ? next() : (res.writeHead(403, {
8233
+ 'Content-Type': 'text/plain; charset=utf-8'
8234
+ }), res.end(HOST_CHECK_ERROR));
8235
+ };
8236
+ }
8237
+ function withHostCheck(onUpgrade, allowedHosts) {
8238
+ return (req, socket, head)=>{
8239
+ if (!isRequestHostAllowed(req.headers, allowedHosts)) {
8240
+ socket.end(`HTTP/1.1 403 Forbidden\r\nConnection: close\r\nContent-Type: text/plain; charset=utf-8\r\nContent-Length: ${Buffer.byteLength(HOST_CHECK_ERROR)}\r\n\r\n` + HOST_CHECK_ERROR), socket.destroySoon();
8241
+ return;
8242
+ }
8243
+ onUpgrade(req, socket, head);
8244
+ };
8245
+ }
8246
+ function isRequestHostAllowed(headers, allowedHosts) {
8247
+ let { host, ':authority': authority } = headers;
8248
+ if (void 0 !== authority && void 0 !== host && authority !== host) return !1;
8249
+ let hostHeader = authority ?? host;
8250
+ return 'string' == typeof hostHeader && isHostAllowed(hostHeader, allowedHosts);
8251
+ }
8252
+ let normalizeHostname = (hostname)=>hostname.toLowerCase().replace(/\.$/, '');
8253
+ function isHostAllowed(hostHeader, allowedHosts) {
8254
+ let hostname;
8255
+ if (!hostHeader || /[\s/@\\?#%]/.test(hostHeader)) return !1;
8256
+ try {
8257
+ hostname = normalizeHostname(new URL(`http://${hostHeader}`).hostname);
8258
+ } catch {
8259
+ return !1;
8260
+ }
8261
+ return !!(hostname.startsWith('[') || isIP(hostname) || 'localhost' === hostname || hostname.endsWith('.localhost')) || allowedHosts.some((allowedHost)=>{
8262
+ let normalized = normalizeHostname(allowedHost);
8263
+ return hostname === normalized || normalized.startsWith('.') && (hostname === normalized.slice(1) || hostname.endsWith(normalized));
8264
+ });
8265
+ }
8266
+ let getPublicPathname = (publicPath)=>'auto' === publicPath || '' === publicPath ? '' : getPathnameFromUrl(publicPath.endsWith('/') ? publicPath : `${publicPath}/`), getPublicPathnames = (publicPaths, base)=>publicPaths.map(getPublicPathname).map((prefix)=>base && '/' !== base ? removeBasePath(prefix, base) : prefix);
8217
8267
  async function applyServerSetup(setup, context) {
8218
8268
  let postCallbacks = [];
8219
8269
  for (let handler of helpers_castArray(setup || [])){
@@ -8318,12 +8368,18 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8318
8368
  protocol,
8319
8369
  clearCache: !0,
8320
8370
  logger
8321
- }), state = {}, cleanupGracefulShutdown = middlewareMode ? null : setupGracefulShutdown(), closeServerResources = ()=>(closingPromise || (hotConnectCallbacks = void 0, unregisterRestart?.(), unregisterRestart = void 0, closingPromise = (async ()=>{
8371
+ }), state = {}, webSocketServers = new Set(), cleanupGracefulShutdown = middlewareMode ? null : setupGracefulShutdown(), closeServerResources = ()=>{
8372
+ if (closingPromise) return closingPromise;
8373
+ hotConnectCallbacks = void 0;
8374
+ let onUpgrade = state.devMiddlewares?.onUpgrade;
8375
+ if (onUpgrade && webSocketServers) for (let server of webSocketServers)server.removeListener('upgrade', onUpgrade);
8376
+ return webSocketServers = void 0, unregisterRestart?.(), unregisterRestart = void 0, closingPromise = (async ()=>{
8322
8377
  removeCleanup(closeServer), cleanupGracefulShutdown?.(), await context.hooks.onCloseDevServer.callBatch(), await Promise.all([
8323
8378
  state.devMiddlewares?.close(),
8324
8379
  state.fileWatcher?.close()
8325
8380
  ]);
8326
- })()), closingPromise), closeServer = async ()=>{
8381
+ })();
8382
+ }, closeServer = async ()=>{
8327
8383
  await state.restartWatcher?.close(), await closeServerResources();
8328
8384
  }, restartServer = async ()=>{
8329
8385
  let restarted = await requestRestart({
@@ -8346,7 +8402,7 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8346
8402
  customShortcuts: shortcutsOptions.custom,
8347
8403
  logger
8348
8404
  });
8349
- context.hooks.onCloseDevServer.tap(cleanup);
8405
+ context.hooks.onCloseDevServer.tapOnce(cleanup);
8350
8406
  }
8351
8407
  !getPortSilently && portTip && logger.info(portTip);
8352
8408
  }, cacheableLoadBundle = createCacheableFunction(loadBundle), cacheableTransformedHtml = createCacheableFunction((_stats, entryName, utils)=>((entryName, utils)=>{
@@ -8393,7 +8449,12 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8393
8449
  }
8394
8450
  };
8395
8451
  });
8396
- let { connect } = await import("./connect-next.js"), middlewares = connect(), httpServer = middlewareMode ? null : await createHttpServer({
8452
+ let { connect } = await import("./connect-next.js"), middlewares = connect(), allowedHosts = !0 === config.server.allowedHosts ? void 0 : [
8453
+ ...config.server.allowedHosts,
8454
+ host
8455
+ ];
8456
+ allowedHosts && middlewares.use(createHostCheckMiddleware(allowedHosts));
8457
+ let httpServer = middlewareMode ? null : await createHttpServer({
8397
8458
  serverConfig: config.server,
8398
8459
  middlewares
8399
8460
  }), devServer = {
@@ -8405,12 +8466,14 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8405
8466
  listen: async ()=>{
8406
8467
  if (!httpServer) throw Error(`${color.dim('[rsbuild:server]')} Can not listen dev server as ${color.yellow('server.middlewareMode')} is enabled.`);
8407
8468
  let serverTerminator = getServerTerminator(httpServer);
8408
- logger.debug('listen dev server'), context.hooks.onCloseDevServer.tap(serverTerminator);
8469
+ logger.debug('listen dev server'), context.hooks.onCloseDevServer.tapOnce(serverTerminator);
8409
8470
  try {
8410
8471
  return httpServer.listen({
8411
8472
  host,
8412
8473
  port
8413
- }), await once(httpServer, 'listening'), middlewares.use(optionsFallbackMiddleware), middlewares.use(notFoundMiddleware), state.devMiddlewares && httpServer.on('upgrade', state.devMiddlewares.onUpgrade), logger.debug('listen dev server done'), await devServer.afterListen(), {
8474
+ }), await external_node_events_once(httpServer, 'listening'), middlewares.use(optionsFallbackMiddleware), middlewares.use(notFoundMiddleware), devServer.connectWebSocket({
8475
+ server: httpServer
8476
+ }), logger.debug('listen dev server done'), await devServer.afterListen(), {
8414
8477
  port,
8415
8478
  urls: urls.map((item)=>item.url),
8416
8479
  server: devServer
@@ -8432,7 +8495,7 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8432
8495
  });
8433
8496
  },
8434
8497
  connectWebSocket: ({ server })=>{
8435
- state.devMiddlewares && server.on('upgrade', state.devMiddlewares.onUpgrade);
8498
+ state.devMiddlewares && webSocketServers && !webSocketServers.has(server) && (server.on('upgrade', state.devMiddlewares.onUpgrade), webSocketServers.add(server));
8436
8499
  },
8437
8500
  close: closeServer,
8438
8501
  printUrls,
@@ -8448,7 +8511,7 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8448
8511
  })).filter((item)=>'function' == typeof item),
8449
8512
  ...setupPostCallbacks
8450
8513
  ];
8451
- return runCompile ? context.hooks.onBeforeCreateCompiler.tap(beforeCreateCompiler) : await beforeCreateCompiler(), state.buildManager = runCompile ? await startCompile() : void 0, state.fileWatcher = await setupWatchFiles({
8514
+ return runCompile ? context.hooks.onBeforeCreateCompiler.tapOnce(beforeCreateCompiler) : await beforeCreateCompiler(), state.buildManager = runCompile ? await startCompile() : void 0, state.fileWatcher = await setupWatchFiles({
8452
8515
  config,
8453
8516
  buildManager: state.buildManager,
8454
8517
  root: context.rootPath
@@ -8458,14 +8521,19 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8458
8521
  devServer,
8459
8522
  context,
8460
8523
  postCallbacks
8461
- }), state.buildManager?.watch(), unregisterRestart = context.restartManager.registerCleanup(closeServerResources), state.restartWatcher = watchFilesForRestart({
8524
+ }), allowedHosts && (state.devMiddlewares.onUpgrade = withHostCheck(state.devMiddlewares.onUpgrade, allowedHosts)), state.buildManager?.watch(), unregisterRestart = context.restartManager.registerCleanup(closeServerResources), state.restartWatcher = watchFilesForRestart({
8462
8525
  watchFiles: config.dev.watchFiles,
8463
8526
  context,
8464
8527
  restartContext
8465
8528
  }), logger.debug('create dev server done'), devServer;
8466
8529
  }
8467
8530
  async function startPreviewServer(context, config, { getPortSilently } = {}) {
8468
- let { logger } = context, { connect } = await import("./connect-next.js"), middlewares = connect(), { port, portTip } = await resolvePort(config), serverConfig = config.server, { host, headers, proxy, historyApiFallback, compress, base, cors } = serverConfig, assetPrefixes = context.environmentList.map((environment)=>environment.config.output.assetPrefix);
8531
+ let cleanupCliShortcuts, { logger } = context, { connect } = await import("./connect-next.js"), middlewares = connect(), { port, portTip } = await resolvePort(config), serverConfig = config.server, { host, headers, proxy, historyApiFallback, compress, base, cors } = serverConfig, allowedHosts = !0 === serverConfig.allowedHosts ? void 0 : [
8532
+ ...serverConfig.allowedHosts,
8533
+ host
8534
+ ];
8535
+ allowedHosts && middlewares.use(createHostCheckMiddleware(allowedHosts));
8536
+ let assetPrefixes = context.environmentList.map((environment)=>environment.config.output.assetPrefix);
8469
8537
  context.publicPathnames = getPublicPathnames(assetPrefixes, base);
8470
8538
  let protocol = serverConfig.https ? 'https' : 'http', routes = getRoutes(context), urls = await getAddressUrls({
8471
8539
  protocol,
@@ -8475,7 +8543,7 @@ async function startPreviewServer(context, config, { getPortSilently } = {}) {
8475
8543
  serverConfig,
8476
8544
  middlewares
8477
8545
  }), cleanupGracefulShutdown = setupGracefulShutdown(), serverTerminator = getServerTerminator(httpServer), closingPromise = null, closeServer = async ()=>(closingPromise || (closingPromise = (async ()=>{
8478
- removeCleanup(closeServer), cleanupGracefulShutdown(), await serverTerminator();
8546
+ removeCleanup(closeServer), cleanupGracefulShutdown(), cleanupCliShortcuts?.(), await serverTerminator();
8479
8547
  })()), closingPromise), printUrls = (options)=>printServerURLs({
8480
8548
  urls,
8481
8549
  port,
@@ -8524,7 +8592,7 @@ async function startPreviewServer(context, config, { getPortSilently } = {}) {
8524
8592
  }), proxy) {
8525
8593
  let { middlewares: proxyMiddlewares, upgrade } = await createProxyMiddleware(proxy, logger);
8526
8594
  for (let middleware of proxyMiddlewares)middlewares.use(middleware);
8527
- httpServer.on('upgrade', upgrade);
8595
+ httpServer.on('upgrade', allowedHosts ? withHostCheck(upgrade, allowedHosts) : upgrade);
8528
8596
  }
8529
8597
  for (let callback of (compress && middlewares.use(gzipMiddleware_gzipMiddleware({
8530
8598
  level: external_node_zlib_constants.Z_DEFAULT_COMPRESSION,
@@ -8540,13 +8608,13 @@ async function startPreviewServer(context, config, { getPortSilently } = {}) {
8540
8608
  if (httpServer.listen({
8541
8609
  host,
8542
8610
  port
8543
- }), await once(httpServer, 'listening'), await context.hooks.onAfterStartPreviewServer.callBatch({
8611
+ }), await external_node_events_once(httpServer, 'listening'), await context.hooks.onAfterStartPreviewServer.callBatch({
8544
8612
  port,
8545
8613
  routes,
8546
8614
  environments: context.environments
8547
8615
  }), registerCleanup(closeServer), printUrls(), cliShortcutsEnabled) {
8548
8616
  let shortcutsOptions = 'boolean' == typeof config.dev.cliShortcuts ? {} : config.dev.cliShortcuts;
8549
- await setupCliShortcuts({
8617
+ cleanupCliShortcuts = await setupCliShortcuts({
8550
8618
  openPage,
8551
8619
  closeServer,
8552
8620
  printUrls,
@@ -8757,11 +8825,7 @@ function applyDefaultPlugins(pluginManager, context) {
8757
8825
  library: {
8758
8826
  type: isESM ? 'module' : 'commonjs2'
8759
8827
  }
8760
- }), isESM) {
8761
- if ('web-worker' === target) throw Error('[rsbuild:config] `output.module: true` is not supported for web-worker target.');
8762
- chain.node.set('__dirname', !1).set('__filename', !1), chain.output.module(!0).chunkFormat('module').chunkLoading('import').workerChunkLoading('import');
8763
- }
8764
- if (config.output.copy) {
8828
+ }), isESM && (chain.node.set('__dirname', !1).set('__filename', !1), chain.output.module(!0).chunkFormat('module').chunkLoading('import').workerChunkLoading('import')), config.output.copy) {
8765
8829
  let { copy } = config.output, options = Array.isArray(copy) ? {
8766
8830
  patterns: copy
8767
8831
  } : copy;
@@ -8810,27 +8874,31 @@ function applyDefaultPlugins(pluginManager, context) {
8810
8874
  {
8811
8875
  name: 'rsbuild:file-size',
8812
8876
  setup (api) {
8813
- api.onAfterBuild(async ({ stats, isFirstCompile })=>{
8877
+ let fileSizeResults, processAssets;
8878
+ api.onBeforeBuild(({ isFirstCompile })=>{
8879
+ fileSizeResults = isFirstCompile ? [] : void 0, processAssets = isFirstCompile ? createAssetProcessor() : void 0;
8880
+ }), api.onAfterCreateCompiler(({ compiler })=>{
8881
+ 'build' === context.action && applyToCompiler(compiler, (compiler, index)=>{
8882
+ let { config } = context.environmentList[index];
8883
+ !1 !== config.performance.printFileSize && compiler.hooks.emit.tapPromise({
8884
+ name: 'rsbuild:file-size',
8885
+ stage: 1 / 0
8886
+ }, async (compilation)=>{
8887
+ fileSizeResults && processAssets && !compilation.errors.length && (fileSizeResults[index] = getFileSizes(fileSize_normalizeConfig(config), compilation, processAssets), await fileSizeResults[index].catch(()=>{}));
8888
+ });
8889
+ });
8890
+ }), api.onAfterBuild(async ({ stats, isFirstCompile })=>{
8891
+ let results = fileSizeResults;
8892
+ fileSizeResults = void 0, processAssets = void 0;
8814
8893
  let { hasErrors } = context.buildState;
8815
- if (!stats || hasErrors || !isFirstCompile) return;
8816
- let environments = context.environmentList.filter(({ config })=>!1 !== config.performance.printFileSize);
8894
+ if (!stats || hasErrors || !isFirstCompile || !results) return;
8895
+ let environments = context.environmentList.filter(({ index })=>void 0 !== results[index]);
8817
8896
  if (!environments.length) return;
8818
8897
  let showDiff = environments.some((environment)=>{
8819
8898
  let { printFileSize } = environment.config.performance;
8820
8899
  return 'object' == typeof printFileSize && !!printFileSize.diff;
8821
8900
  }), { configFile } = api.context, snapshotHash = showDiff && configFile ? await helpers_hash(configFile) : '', snapshotPath = showDiff ? getSnapshotPath(api.context.cachePath, snapshotHash) : '', prevSnapshots = showDiff ? await loadPrevSnapshots(snapshotPath) : null, nextSnapshots = {}, logs = await Promise.all(environments.map(async ({ name, index, config, distPath })=>{
8822
- let statsItem = 'stats' in stats ? stats.stats[index] : stats, { logs: sizeLogs, snapshot } = await printFileSizes(((config)=>{
8823
- let { printFileSize } = config.performance, defaultConfig = {
8824
- total: !0,
8825
- detail: !0,
8826
- diff: !1,
8827
- compressed: 'node' !== config.output.target
8828
- };
8829
- return !0 === printFileSize ? defaultConfig : {
8830
- ...defaultConfig,
8831
- ...printFileSize
8832
- };
8833
- })(config), statsItem, api.context.rootPath, distPath, name, prevSnapshots, showDiff);
8901
+ let { logs: sizeLogs, snapshot } = printFileSizes(fileSize_normalizeConfig(config), await results[index], api.context.rootPath, distPath, name, prevSnapshots, showDiff);
8834
8902
  return snapshot && (nextSnapshots[name] = snapshot), sizeLogs.join('\n');
8835
8903
  })).catch((err)=>{
8836
8904
  api.logger.warn('Failed to print file size.'), api.logger.warn(err);
@@ -8846,7 +8914,7 @@ function applyDefaultPlugins(pluginManager, context) {
8846
8914
  for (let pathInfo of [
8847
8915
  ...Object.values(params.environments).reduce((result, curr)=>(result.some((item)=>item.distPath === curr.distPath) || result.push(curr), result), []).map((environment)=>((environment, isDev)=>{
8848
8916
  let { rootPath } = api.context, { config, distPath } = environment, { enable, keep } = normalizeCleanDistPath(config.output.cleanDistPath);
8849
- return 'auto' === enable ? isDev && !config.dev.writeToDisk ? void 0 : isStrictSubdir(rootPath, distPath) ? {
8917
+ return 'auto' === enable ? isDev && !config.dev.writeToDisk ? void 0 : relativeWithin(rootPath, distPath) ? {
8850
8918
  path: distPath,
8851
8919
  keep
8852
8920
  } : (api.logger.warn('The dist path is not a subdir of root path, Rsbuild will not empty it.'), api.logger.warn(`Please set ${color.yellow('`output.cleanDistPath`')} config manually.`), api.logger.warn(`Current root path: ${color.dim(rootPath)}`), void api.logger.warn(`Current dist path: ${color.dim(distPath)}`)) : !0 === enable ? {
@@ -8856,7 +8924,7 @@ function applyDefaultPlugins(pluginManager, context) {
8856
8924
  })(environment, params.isDev)),
8857
8925
  (()=>{
8858
8926
  let { rootPath, distPath } = api.context, config = api.getNormalizedConfig(), targetPath = join(distPath, RSBUILD_OUTPUTS_PATH), { enable } = normalizeCleanDistPath(config.output.cleanDistPath);
8859
- if (!0 === enable || 'auto' === enable && isStrictSubdir(rootPath, targetPath)) return {
8927
+ if (!0 === enable || 'auto' === enable && relativeWithin(rootPath, targetPath)) return {
8860
8928
  path: targetPath
8861
8929
  };
8862
8930
  })()
@@ -9212,7 +9280,7 @@ try {
9212
9280
  type: 'text'
9213
9281
  }).type('asset/source');
9214
9282
  let urlRule = cssRule.oneOf(CHAIN_ID.ONE_OF.CSS_URL).resourceQuery(URL_QUERY_REGEX);
9215
- urlRule.use(CHAIN_ID.USE.CSS_URL).loader(node_path.join(dirname, 'cssUrlLoader.mjs'));
9283
+ urlRule.use(CHAIN_ID.USE.CSS_URL).loader(node_path.join(LOADER_PATH, 'cssUrlLoader.mjs'));
9216
9284
  let inlineRule = cssRule.oneOf(CHAIN_ID.ONE_OF.CSS_INLINE).resourceQuery(INLINE_QUERY_REGEX);
9217
9285
  cssRule.oneOf(CHAIN_ID.ONE_OF.CSS_RAW).type('asset/source').resourceQuery(RAW_QUERY_REGEX);
9218
9286
  let mainRule = cssRule.oneOf(CHAIN_ID.ONE_OF.CSS_MAIN), emitCss = config.output.emitCss ?? 'web' === target;
@@ -9221,26 +9289,45 @@ try {
9221
9289
  initial: {},
9222
9290
  config: config.tools.styleLoader
9223
9291
  });
9224
- mainRule.use(CHAIN_ID.USE.STYLE).loader(join(COMPILED_PATH, 'style-loader', 'index.js')).options(styleLoaderOptions);
9292
+ mainRule.use(CHAIN_ID.USE.STYLE).loader(getCompiledPath('style-loader')).options(styleLoaderOptions);
9225
9293
  } else mainRule.use(CHAIN_ID.USE.MINI_CSS_EXTRACT).loader(core_rspack.CssExtractRspackPlugin.loader).options(config.tools.cssExtract.loaderOptions);
9226
- else mainRule.use(CHAIN_ID.USE.IGNORE_CSS).loader(node_path.join(dirname, 'ignoreCssLoader.mjs'));
9294
+ else mainRule.use(CHAIN_ID.USE.IGNORE_CSS).loader(node_path.join(LOADER_PATH, 'ignoreCssLoader.mjs'));
9227
9295
  let importLoaders = {
9228
9296
  normal: 0,
9229
9297
  inline: 0
9230
9298
  }, updateRules = async (callback, options = {})=>{
9231
9299
  options.skipMain || await callback(mainRule, 'main'), await callback(inlineRule, 'inline'), await callback(urlRule, 'url');
9232
- }, cssLoaderPath = join(COMPILED_PATH, 'css-loader', 'index.js');
9233
- if (await updateRules((rule)=>{
9300
+ }, cssLoaderPath = getCompiledPath('css-loader');
9301
+ await updateRules((rule)=>{
9234
9302
  rule.use(CHAIN_ID.USE.CSS).loader(cssLoaderPath);
9235
- }), !1 !== config.tools.lightningcssLoader) {
9303
+ });
9304
+ let cssUrlMinimized = !1;
9305
+ if (!1 !== config.tools.lightningcssLoader) {
9236
9306
  emitCss && importLoaders.normal++, importLoaders.inline++;
9237
- let minifyCss = parseMinifyOptions(config).minifyCss, { browserslist } = environment;
9307
+ let { minifyCss, cssOptions } = parseMinifyOptions(config), { browserslist } = environment;
9238
9308
  if ('node' === target) {
9239
9309
  let webEnvironment = Object.values(environments).find((env)=>'web' === env.config.output.target);
9240
- webEnvironment && (browserslist = webEnvironment.browserslist, minifyCss = parseMinifyOptions(webEnvironment.config).minifyCss);
9310
+ if (webEnvironment) {
9311
+ browserslist = webEnvironment.browserslist;
9312
+ let webMinifyOptions = parseMinifyOptions(webEnvironment.config);
9313
+ minifyCss = webMinifyOptions.minifyCss, cssOptions ??= webMinifyOptions.cssOptions;
9314
+ }
9241
9315
  }
9316
+ let cssUrlMinimizerOptions = minifyCss ? ((cssOptions)=>{
9317
+ let options = helpers_castArray(cssOptions), { minimizerOptions, test, include, exclude } = options[0] ?? {};
9318
+ return !(options.length > 1 || [
9319
+ test,
9320
+ include,
9321
+ exclude
9322
+ ].some((value)=>void 0 !== value)) && (minimizerOptions ?? {});
9323
+ })(cssOptions) : {};
9242
9324
  await updateRules(async (rule, type)=>{
9243
9325
  let minify = ('inline' === type || 'url' === type || config.output.injectStyles) && minifyCss, lightningcssOptions = await getLightningCSSLoaderOptions(config, browserslist, minify);
9326
+ if ('url' === type && !0 === lightningcssOptions.minify && !1 !== cssUrlMinimizerOptions) {
9327
+ var loaderOptions;
9328
+ let options;
9329
+ loaderOptions = lightningcssOptions, options = cjs_0_default()(loaderOptions, cssUrlMinimizerOptions), isPlainObject(cssUrlMinimizerOptions.targets) && (options.targets = cssUrlMinimizerOptions.targets), lightningcssOptions = options, cssUrlMinimized = !0;
9330
+ }
9244
9331
  rule.use(CHAIN_ID.USE.LIGHTNINGCSS).loader('builtin:lightningcss-loader').options(lightningcssOptions);
9245
9332
  }, {
9246
9333
  skipMain: !emitCss
@@ -9253,7 +9340,7 @@ try {
9253
9340
  });
9254
9341
  if ('function' == typeof postcssLoaderOptions.postcssOptions || postcssLoaderOptions.postcssOptions?.plugins?.length) {
9255
9342
  emitCss && importLoaders.normal++, importLoaders.inline++;
9256
- let postcssLoaderPath = join(COMPILED_PATH, 'postcss-loader', 'index.js');
9343
+ let postcssLoaderPath = getCompiledPath('postcss-loader');
9257
9344
  await updateRules((rule)=>{
9258
9345
  rule.use(CHAIN_ID.USE.POSTCSS).loader(postcssLoaderPath).options(postcssLoaderOptions);
9259
9346
  }, {
@@ -9282,7 +9369,8 @@ try {
9282
9369
  let cssUrlFilename = getFilename(config, 'css', isProd), cssUrlPath = config.output.distPath.css;
9283
9370
  urlRule.use(CHAIN_ID.USE.CSS_URL).options({
9284
9371
  filename: 'function' == typeof cssUrlFilename ? (pathData, assetInfo)=>posix.join(cssUrlPath, cssUrlFilename(pathData, assetInfo)) : posix.join(cssUrlPath, cssUrlFilename),
9285
- modules: cssLoaderOptions.modules
9372
+ modules: cssLoaderOptions.modules,
9373
+ minimized: cssUrlMinimized
9286
9374
  });
9287
9375
  let isStringExport = 'string' === cssLoaderOptions.exportType;
9288
9376
  if (isStringExport && mainRule.uses.has(CHAIN_ID.USE.MINI_CSS_EXTRACT) && mainRule.uses.delete(CHAIN_ID.USE.MINI_CSS_EXTRACT), emitCss && !config.output.injectStyles && !isStringExport) {
@@ -9366,7 +9454,7 @@ try {
9366
9454
  api.modifyBundlerChain({
9367
9455
  order: 'pre',
9368
9456
  handler: (chain, { CHAIN_ID })=>{
9369
- chain.module.rule(CHAIN_ID.RULE.JS).oneOf(CHAIN_ID.ONE_OF.JS_WORKER).resourceQuery(WORKER_QUERY_REGEX).type("javascript/auto").use(CHAIN_ID.USE.WORKER_QUERY).loader(node_path.join(dirname, 'workerLoader.mjs'));
9457
+ chain.module.rule(CHAIN_ID.RULE.JS).oneOf(CHAIN_ID.ONE_OF.JS_WORKER).resourceQuery(WORKER_QUERY_REGEX).type("javascript/auto").use(CHAIN_ID.USE.WORKER_QUERY).loader(node_path.join(LOADER_PATH, 'workerLoader.mjs'));
9370
9458
  }
9371
9459
  });
9372
9460
  }
@@ -10067,10 +10155,15 @@ let canReadExport = (module)=>null !== module && ('object' == typeof module || '
10067
10155
  if ('default' === exportName) return canReadExport(configModule) && 'default' in configModule ? configModule.default : configModule;
10068
10156
  if (canReadExport(configModule) && Object.hasOwn(configModule, exportName)) return configModule[exportName];
10069
10157
  throw Error(`Cannot find export ${exportName} in config file: ${configPath}`);
10070
- }, loadWithJiti = async (configPath, exportName, fresh)=>{
10158
+ }, cachedImport = (importer)=>{
10159
+ let promise;
10160
+ return ()=>promise ??= importer().catch((error)=>{
10161
+ throw promise = void 0, error;
10162
+ });
10163
+ }, getJiti = cachedImport(()=>import("../compiled/jiti/lib/jiti.mjs")), loadWithJiti = async (configPath, exportName, fresh)=>{
10071
10164
  let createJiti;
10072
10165
  try {
10073
- ({ createJiti } = await import("../compiled/jiti/lib/jiti.mjs"));
10166
+ ({ createJiti } = await getJiti());
10074
10167
  } catch (error) {
10075
10168
  throw Error('The "jiti" package is required to load this config. Install it with your package manager.', {
10076
10169
  cause: error
@@ -10096,13 +10189,13 @@ let canReadExport = (module)=>null !== module && ('object' == typeof module || '
10096
10189
  function getConfigMeta(config) {
10097
10190
  if (null !== config && 'object' == typeof config && Object.hasOwn(config, CONFIG_META)) return config[CONFIG_META];
10098
10191
  }
10099
- let JS_CONFIG_REGEXP = /\.(?:js|mjs|cjs)$/, loadWithNative = async (configPath, fresh)=>{
10192
+ let getFreshImport = cachedImport(()=>import("./freshImport.js")), JS_CONFIG_REGEXP = /\.(?:js|mjs|cjs)$/, loadWithNative = async (configPath, fresh)=>{
10100
10193
  let configFileURL = pathToFileURL(configPath).href;
10101
10194
  if (!fresh) return {
10102
10195
  configModule: await import(configFileURL),
10103
10196
  dependencies: []
10104
10197
  };
10105
- let { freshImport } = await import("./freshImport.js"), freshImportResult = await freshImport(configFileURL);
10198
+ let { freshImport } = await getFreshImport(), freshImportResult = await freshImport(configFileURL);
10106
10199
  return freshImportResult ? {
10107
10200
  configModule: freshImportResult.result,
10108
10201
  dependencies: freshImportResult.dependencies.sort()
@@ -10257,7 +10350,7 @@ let applyServerOptions = (command)=>{
10257
10350
  };
10258
10351
  function setupCommands(argv) {
10259
10352
  let cli = ((name = "")=>new CAC(name))('rsbuild');
10260
- cli.version("2.2.9"), cli.option('--base <base>', 'Set the base path of the server').option('-c, --config <config>', 'Set the configuration file (relative or absolute path)').option('--config-loader <loader>', 'Set the config file loader (auto | jiti | native)', {
10353
+ cli.version("2.2.13"), cli.option('--base <base>', 'Set the base path of the server').option('-c, --config <config>', 'Set the configuration file (relative or absolute path)').option('--config-loader <loader>', 'Set the config file loader (auto | jiti | native)', {
10261
10354
  default: 'auto'
10262
10355
  }).option('--dist-path <dir>', 'Set the root directory of output files').option('--source-map', 'Enable source map').option('--env-dir <dir>', 'Set the directory for loading `.env` files').option('--env-mode <mode>', 'Set the env mode to load the `.env.[mode]` file').option('--environment <name>', 'Set the environment name(s) to build', {
10263
10356
  type: [
@@ -10322,7 +10415,7 @@ function setupCommands(argv) {
10322
10415
  }
10323
10416
  function showGreeting() {
10324
10417
  let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
10325
- src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.2.9\n`);
10418
+ src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.2.13\n`);
10326
10419
  }
10327
10420
  function setupLogLevel(argv) {
10328
10421
  if (argv.length <= 3) return;
@@ -10344,5 +10437,5 @@ function runCLI({ argv = process.argv } = {}) {
10344
10437
  src_logger.error('Failed to start Rsbuild CLI.'), src_logger.error(err), process.exit(1);
10345
10438
  }
10346
10439
  }
10347
- let src_version = "2.2.9";
10348
- export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, core_rspack as rspack, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig_loadConfig as loadConfig, loadEnv, logger_createLogger as createLogger, mergeRsbuildConfig, mrmime_lookup, runCLI, src_logger as logger, src_version as version };
10440
+ let src_version = "2.2.13";
10441
+ export { core_rspack as rspack, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig_loadConfig as loadConfig, loadEnv, logger_createLogger as createLogger, mergeRsbuildConfig, mrmime_lookup, runCLI, src_logger as logger, src_version as version };