@rsbuild/core 2.2.12 → 2.2.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/m.js CHANGED
@@ -13,6 +13,7 @@ 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
15
  import { once as external_node_events_once } from "node:events";
16
+ import { isIP } from "node:net";
16
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";
17
18
  import { cachedImport as cachedImport_cachedImport, getTinyglobby } from "./r.js";
18
19
  var superClass, superClass1, __rspack_import_meta_filename__ = __rspack_fileURLToPath(import.meta.url);
@@ -389,8 +390,8 @@ moduleFactories.add({
389
390
  return (asyncHooks.AsyncResource && (res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn')), res && res.runInAsyncScope) ? res.runInAsyncScope.bind(res, fn, null) : fn;
390
391
  }
391
392
  },
392
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/d0e1ffed59e3d657674e04f8f91182ccde1db31e7c7c0f00dd625e998ab50180/node_modules/postcss-load-config/src/index.js" (module) {
393
- 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");
394
395
  async function processResult(ctx, result) {
395
396
  let obj, file = result.filepath || '', projectConfig = ((obj = result.config) && obj.__esModule ? obj : {
396
397
  default: obj
@@ -463,8 +464,8 @@ moduleFactories.add({
463
464
  });
464
465
  };
465
466
  },
466
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/d0e1ffed59e3d657674e04f8f91182ccde1db31e7c7c0f00dd625e998ab50180/node_modules/postcss-load-config/src/options.js" (module) {
467
- 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");
468
469
  module.exports = async function options(config, file) {
469
470
  if (config.parser && 'string' == typeof config.parser) try {
470
471
  config.parser = await req(config.parser, file);
@@ -484,8 +485,8 @@ moduleFactories.add({
484
485
  return config;
485
486
  };
486
487
  },
487
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/d0e1ffed59e3d657674e04f8f91182ccde1db31e7c7c0f00dd625e998ab50180/node_modules/postcss-load-config/src/plugins.js" (module) {
488
- 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");
489
490
  async function load(plugin, options, file) {
490
491
  try {
491
492
  if (null == options || 0 === Object.keys(options).length) return await req(plugin, file);
@@ -501,7 +502,7 @@ moduleFactories.add({
501
502
  }), list;
502
503
  };
503
504
  },
504
- "../../../../../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) {
505
506
  let tsx, jiti, { createRequire } = __rspack_createRequire_require("node:module"), { pathToFileURL } = __rspack_createRequire_require("node:url"), TS_EXT_RE = /\.[mc]?ts$/, importError = [];
506
507
  module.exports = async function req(name, rootFile = __rspack_import_meta_filename__) {
507
508
  let url = createRequire(rootFile).resolve(name);
@@ -720,14 +721,14 @@ function findAllBrackets(v) {
720
721
  }
721
722
  function getMriOptions(options) {
722
723
  let result = {
723
- alias: {},
724
+ alias: Object.create(null),
724
725
  boolean: []
725
726
  };
726
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]));
727
728
  return result;
728
729
  }
729
730
  function findLongest(arr) {
730
- return arr.sort((a, b)=>a.length > b.length ? -1 : 1)[0];
731
+ return arr.sort((a, b)=>b.length - a.length)[0];
731
732
  }
732
733
  function padRight(str, length) {
733
734
  return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
@@ -735,7 +736,13 @@ function padRight(str, length) {
735
736
  function camelcase(input) {
736
737
  return input.replaceAll(/([a-z])-([a-z])/g, (_, p1, p2)=>p1 + p2.toUpperCase());
737
738
  }
739
+ let UNSAFE_KEYS = new Set([
740
+ "__proto__",
741
+ "constructor",
742
+ "prototype"
743
+ ]);
738
744
  function setDotProp(obj, keys, val) {
745
+ if (keys.some((key)=>UNSAFE_KEYS.has(key))) return;
739
746
  let current = obj;
740
747
  for(let i = 0; i < keys.length; i++){
741
748
  let key = keys[i];
@@ -751,12 +758,9 @@ function setDotProp(obj, keys, val) {
751
758
  }
752
759
  }
753
760
  function setByType(obj, transforms) {
754
- for (let key of Object.keys(transforms)){
755
- let transform = transforms[key];
756
- transform.shouldTransform && (obj[key] = [
757
- obj[key]
758
- ].flat(), "function" == typeof transform.transformFunction && (obj[key] = obj[key].map(transform.transformFunction)));
759
- }
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)));
760
764
  }
761
765
  function getFileName(input) {
762
766
  let m = /([^\\/]+)$/.exec(input);
@@ -782,7 +786,7 @@ var CACError = class extends Error {
782
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)=>{
783
787
  let name = v.trim().replace(/^-{1,2}/, "");
784
788
  return name.startsWith("no-") && (this.negated = !0, name = name.replace(/^no-/, "")), camelcaseOptionName(name);
785
- }).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;
786
790
  }
787
791
  };
788
792
  if ("u" > typeof process) {
@@ -842,7 +846,7 @@ var Command = class {
842
846
  return this instanceof GlobalCommand;
843
847
  }
844
848
  hasOption(name) {
845
- 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));
846
850
  }
847
851
  outputHelp() {
848
852
  let { name, commands } = this.cli, { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand, sections = [
@@ -899,7 +903,7 @@ var Command = class {
899
903
  ...this.options
900
904
  ];
901
905
  for (let option of options){
902
- let value = parsedOptions[option.name.split(".")[0]];
906
+ let value = parsedOptions[option.name.split(".", 1)[0]];
903
907
  if (option.required) {
904
908
  let hasNegated = options.some((o)=>o.negated && o.names.includes(option.name));
905
909
  if (!0 === value || !1 === value && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`);
@@ -1019,7 +1023,7 @@ var Command = class {
1019
1023
  if (!ignoreDefault && void 0 !== cliOption.config.default) for (let name of cliOption.names)options[name] = cliOption.config.default;
1020
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]);
1021
1025
  }
1022
- 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));
1023
1027
  return {
1024
1028
  args,
1025
1029
  options
@@ -2730,6 +2734,7 @@ let OVERRIDE_PATHS = new Set([
2730
2734
  server: {
2731
2735
  port: 3000,
2732
2736
  host: LOCALHOST,
2737
+ allowedHosts: !0,
2733
2738
  open: !1,
2734
2739
  base: '/',
2735
2740
  htmlFallback: 'index',
@@ -3298,7 +3303,7 @@ function createPublicContext(context) {
3298
3303
  async function createContext(options, userConfig, logger, loadConfigResult) {
3299
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();
3300
3305
  return {
3301
- version: "2.2.12",
3306
+ version: "2.2.13",
3302
3307
  rootPath,
3303
3308
  configFile: loadConfigResult?.filePath ?? userConfig._privateMeta?.configFilePath,
3304
3309
  configFileDependencies: loadConfigResult?.dependencies ?? userConfig._privateMeta?.configFileDependencies ?? [],
@@ -4235,7 +4240,7 @@ function watchFilesForRestart({ watchFiles, context, restartContext }) {
4235
4240
  } catch (error) {
4236
4241
  logger.error(error);
4237
4242
  }
4238
- })), 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);
4239
4244
  return {
4240
4245
  close
4241
4246
  };
@@ -4945,7 +4950,7 @@ function parseMinifyOptions(config) {
4945
4950
  cssOptions: minify.cssOptions
4946
4951
  };
4947
4952
  }
4948
- 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"));
4949
4954
  async function getLightningCSSLoaderOptions(config, targets, minify) {
4950
4955
  let userOptions = 'object' == typeof config.tools.lightningcssLoader ? config.tools.lightningcssLoader : {}, initialOptions = {
4951
4956
  targets,
@@ -5130,6 +5135,31 @@ function pluginExternals() {
5130
5135
  }
5131
5136
  };
5132
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
+ }
5133
5163
  function getCompression(compressed) {
5134
5164
  let { type = 'gzip', level = 6 } = 'object' == typeof compressed ? compressed : {};
5135
5165
  return 'brotli' === type ? {
@@ -5210,11 +5240,30 @@ function getHeader(maxFileLength, maxSizeLength, fileHeader, compressionHeader)
5210
5240
  let calcFileSize = (len)=>{
5211
5241
  let val = len / 1000;
5212
5242
  return `${val.toFixed(val < 1 ? 2 : 1)} kB`;
5213
- }, 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)=>{
5214
- let queryIndex = assetName.indexOf('?');
5215
- return -1 === queryIndex ? assetName : assetName.slice(0, queryIndex);
5216
- };
5217
- 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) {
5218
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;
5219
5268
  if (!showTotal && !showDetail) return {
5220
5269
  logs
@@ -5224,52 +5273,45 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
5224
5273
  totalSize: 0,
5225
5274
  totalGzipSize: 0,
5226
5275
  compressionType: !!options.compressed && compression.type
5227
- } : null, formatAsset = (filePath, size, compressedSize)=>{
5228
- let normalizedPath = '';
5229
- (snapshot || showDiff) && (normalizedPath = normalizeFilePath(filePath), snapshot && (snapshot.files[normalizedPath] = {
5230
- size,
5231
- [compression.sizeKey]: compressedSize ?? void 0
5232
- }));
5233
- let sizeLabel = calcFileSize(size), sizeLabelLength = sizeLabel.length, compressedSizeLabel = compressedSize ? getAssetColor(compressedSize)(calcFileSize(compressedSize)) : null;
5234
- if (showDiff) {
5235
- let sizeData = prev?.files[normalizedPath], sizeDiff = size - (sizeData?.size ?? 0);
5236
- if (isSignificantDiff(sizeDiff)) {
5237
- let { label, length } = formatDiff(sizeDiff);
5238
- sizeLabel += ` ${label}`, sizeLabelLength += length + 1;
5239
- }
5240
- if (null !== compressedSize && showCompressedDiff) {
5241
- let compressedDiff = compressedSize - (sizeData?.[compression.sizeKey] ?? 0);
5242
- isSignificantDiff(compressedDiff) && (compressedSizeLabel += ` ${formatDiff(compressedDiff).label}`);
5243
- }
5244
- }
5245
- 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);
5246
- return {
5247
- filePath,
5248
- 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)),
5249
- filenameLength: folderLabel.length + filename.length,
5250
- size,
5251
- sizeLabel,
5252
- sizeLabelLength,
5253
- compressedSize,
5254
- compressedSizeLabel
5255
- };
5256
- }, getAssets = async ()=>{
5257
- let { exclude, include } = options, formattedAssets = [], compilationAssets = stats.compilation.assets;
5258
- for (let assetName of Object.keys(compilationAssets)){
5259
- let filePath = getFilePath(assetName);
5260
- if (!exclude && EXCLUDE_ASSET_REGEX.test(filePath)) continue;
5261
- let value = compilationAssets[assetName], content = options.compressed && isCompressible(filePath) ? value.source() : void 0, size = void 0 === content ? value.size() : Buffer.byteLength(content);
5262
- if (exclude || include) {
5263
- let publicAsset = {
5264
- name: filePath,
5265
- size
5266
- };
5267
- 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
+ }
5268
5302
  }
5269
- void 0 === content ? formattedAssets.push(formatAsset(filePath, size, null)) : formattedAssets.push(calcCompressedSize(content, compression.type, compression.level).then((compressedSize)=>formatAsset(filePath, size, compressedSize)));
5270
- }
5271
- return (await Promise.all(formattedAssets)).sort((a, b)=>a.size - b.size);
5272
- }, 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);
5273
5315
  if (0 === assets.length) return {
5274
5316
  logs
5275
5317
  };
@@ -5353,7 +5395,18 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
5353
5395
  snapshot
5354
5396
  };
5355
5397
  }
5356
- 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 = [
5357
5410
  'area',
5358
5411
  'base',
5359
5412
  'br',
@@ -5805,7 +5858,7 @@ let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
5805
5858
  });
5806
5859
  });
5807
5860
  } catch (e) {
5808
- if ('EADDRINUSE' !== e.code) throw e;
5861
+ if (!(e instanceof Error) || !('code' in e) || 'EADDRINUSE' !== e.code) throw e;
5809
5862
  port++, attempts++;
5810
5863
  }
5811
5864
  if (!found) throw Error(`${color.dim('[rsbuild:server]')} Failed to find an available port after ${tryLimits + 1} attempts, starting from ${color.yellow(original)}.`);
@@ -6005,7 +6058,7 @@ function doesChunkBelongToHtml({ chunk, htmlPluginData }) {
6005
6058
  let { options } = htmlPluginData.plugin;
6006
6059
  return recursiveChunkEntryNames(chunk).some((chunkName)=>isChunksFiltered(chunkName, options?.chunks, options?.excludeChunks));
6007
6060
  }
6008
- 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/c829036b5a98f872a31c12f9fca915a8b3b1d943468219bdea4197081cf13ac8/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');
6009
6062
  function normalizeManifestObjectConfig(manifest) {
6010
6063
  let defaultOptions = {
6011
6064
  prefix: !0,
@@ -7718,7 +7771,10 @@ function formatProxyOptions(proxyOptions, logger) {
7718
7771
  async function createProxyMiddleware(proxyOptions, logger) {
7719
7772
  let formattedOptions = formatProxyOptions(proxyOptions, logger), proxyMiddlewares = [], middlewares = [], { createProxyMiddleware: baseMiddleware } = await import("./http-proxy-middleware.js");
7720
7773
  for (let opts of formattedOptions){
7721
- let proxyMiddleware = baseMiddleware(opts), middleware = async (req, res, next)=>{
7774
+ let proxyMiddleware = baseMiddleware({
7775
+ ...opts,
7776
+ ws: !1
7777
+ }), middleware = async (req, res, next)=>{
7722
7778
  let bypassUrl = 'function' == typeof opts.bypass ? await opts.bypass(req, res, opts) : null;
7723
7779
  !1 === bypassUrl ? (res.statusCode = 404, next()) : 'string' == typeof bypassUrl ? (req.url = bypassUrl, next()) : !0 === bypassUrl ? next() : proxyMiddleware(req, res, next);
7724
7780
  };
@@ -7755,7 +7811,7 @@ let applyDefaultMiddlewares = async ({ config, buildManager, context, devServer,
7755
7811
  })), middlewares.use('/__open-in-editor', async (req, res, next)=>{
7756
7812
  try {
7757
7813
  (await (launchEditorHandlerPromise ??= (async ()=>{
7758
- 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));
7759
7815
  return launchEditorMiddleware();
7760
7816
  })()))(req, res, next);
7761
7817
  } catch (err) {
@@ -8170,7 +8226,44 @@ let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>{
8170
8226
  }
8171
8227
  let { createServer } = await import("node:http");
8172
8228
  return createServer(middlewares);
8173
- }, 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);
8174
8267
  async function applyServerSetup(setup, context) {
8175
8268
  let postCallbacks = [];
8176
8269
  for (let handler of helpers_castArray(setup || [])){
@@ -8356,7 +8449,12 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8356
8449
  }
8357
8450
  };
8358
8451
  });
8359
- 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({
8360
8458
  serverConfig: config.server,
8361
8459
  middlewares
8362
8460
  }), devServer = {
@@ -8423,14 +8521,19 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8423
8521
  devServer,
8424
8522
  context,
8425
8523
  postCallbacks
8426
- }), 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({
8427
8525
  watchFiles: config.dev.watchFiles,
8428
8526
  context,
8429
8527
  restartContext
8430
8528
  }), logger.debug('create dev server done'), devServer;
8431
8529
  }
8432
8530
  async function startPreviewServer(context, config, { getPortSilently } = {}) {
8433
- 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, 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);
8434
8537
  context.publicPathnames = getPublicPathnames(assetPrefixes, base);
8435
8538
  let protocol = serverConfig.https ? 'https' : 'http', routes = getRoutes(context), urls = await getAddressUrls({
8436
8539
  protocol,
@@ -8489,7 +8592,7 @@ async function startPreviewServer(context, config, { getPortSilently } = {}) {
8489
8592
  }), proxy) {
8490
8593
  let { middlewares: proxyMiddlewares, upgrade } = await createProxyMiddleware(proxy, logger);
8491
8594
  for (let middleware of proxyMiddlewares)middlewares.use(middleware);
8492
- httpServer.on('upgrade', upgrade);
8595
+ httpServer.on('upgrade', allowedHosts ? withHostCheck(upgrade, allowedHosts) : upgrade);
8493
8596
  }
8494
8597
  for (let callback of (compress && middlewares.use(gzipMiddleware_gzipMiddleware({
8495
8598
  level: external_node_zlib_constants.Z_DEFAULT_COMPRESSION,
@@ -8771,27 +8874,31 @@ function applyDefaultPlugins(pluginManager, context) {
8771
8874
  {
8772
8875
  name: 'rsbuild:file-size',
8773
8876
  setup (api) {
8774
- 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;
8775
8893
  let { hasErrors } = context.buildState;
8776
- if (!stats || hasErrors || !isFirstCompile) return;
8777
- 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]);
8778
8896
  if (!environments.length) return;
8779
8897
  let showDiff = environments.some((environment)=>{
8780
8898
  let { printFileSize } = environment.config.performance;
8781
8899
  return 'object' == typeof printFileSize && !!printFileSize.diff;
8782
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 })=>{
8783
- let statsItem = 'stats' in stats ? stats.stats[index] : stats, { logs: sizeLogs, snapshot } = await printFileSizes(((config)=>{
8784
- let { printFileSize } = config.performance, defaultConfig = {
8785
- total: !0,
8786
- detail: !0,
8787
- diff: !1,
8788
- compressed: 'node' !== config.output.target
8789
- };
8790
- return !0 === printFileSize ? defaultConfig : {
8791
- ...defaultConfig,
8792
- ...printFileSize
8793
- };
8794
- })(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);
8795
8902
  return snapshot && (nextSnapshots[name] = snapshot), sizeLogs.join('\n');
8796
8903
  })).catch((err)=>{
8797
8904
  api.logger.warn('Failed to print file size.'), api.logger.warn(err);
@@ -10243,7 +10350,7 @@ let applyServerOptions = (command)=>{
10243
10350
  };
10244
10351
  function setupCommands(argv) {
10245
10352
  let cli = ((name = "")=>new CAC(name))('rsbuild');
10246
- cli.version("2.2.12"), 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)', {
10247
10354
  default: 'auto'
10248
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', {
10249
10356
  type: [
@@ -10308,7 +10415,7 @@ function setupCommands(argv) {
10308
10415
  }
10309
10416
  function showGreeting() {
10310
10417
  let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
10311
- src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.2.12\n`);
10418
+ src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.2.13\n`);
10312
10419
  }
10313
10420
  function setupLogLevel(argv) {
10314
10421
  if (argv.length <= 3) return;
@@ -10330,5 +10437,5 @@ function runCLI({ argv = process.argv } = {}) {
10330
10437
  src_logger.error('Failed to start Rsbuild CLI.'), src_logger.error(err), process.exit(1);
10331
10438
  }
10332
10439
  }
10333
- let src_version = "2.2.12";
10440
+ let src_version = "2.2.13";
10334
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 };