@rsbuild/core 1.7.0-beta.0 → 1.7.0-beta.2

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/131.js CHANGED
@@ -1,19 +1,24 @@
1
1
  /*! For license information please see 131.js.LICENSE.txt */
2
2
  "use strict";
3
- let swcHelpersPath, pluginHelper_htmlPlugin, cssExtractPlugin;
3
+ let flagForceColor, swcHelpersPath, pluginHelper_htmlPlugin, cssExtractPlugin;
4
+ import { fileURLToPath as __rspack_fileURLToPath } from "node:url";
5
+ import { createRequire as __rspack_createRequire } from "node:module";
4
6
  let __rspack_createRequire_require = __rspack_createRequire(import.meta.url);
5
7
  import * as __rspack_external_async_hooks from "async_hooks";
6
8
  import * as __rspack_external_fs from "fs";
9
+ import * as __rspack_external_node_module_ab9f2194 from "node:module";
7
10
  import * as __rspack_external_node_path_c5b9b54f from "node:path";
11
+ import * as __rspack_external_node_url_e96de089 from "node:url";
8
12
  import * as __rspack_external_os from "os";
9
13
  import * as __rspack_external_path from "path";
10
14
  import * as __rspack_external_url from "url";
11
15
  import { __webpack_require__ } from "./rslib-runtime.js";
16
+ import node_process from "node:process";
17
+ import node_os, { constants as external_node_os_constants } from "node:os";
18
+ import node_tty from "node:tty";
12
19
  import { EventEmitter } from "events";
13
20
  import { promisify as external_node_util_promisify, stripVTControlCharacters } from "node:util";
14
21
  import node_fs, { existsSync } from "node:fs";
15
- import node_os, { constants as external_node_os_constants } from "node:os";
16
- import node_process from "node:process";
17
22
  import { isPromise, isRegExp } from "node:util/types";
18
23
  import node_zlib from "node:zlib";
19
24
  __webpack_require__.add({
@@ -951,7 +956,179 @@ __webpack_require__.r(provider_helpers_namespaceObject), __webpack_require__.d(p
951
956
  setCssExtractPlugin: ()=>setCssExtractPlugin,
952
957
  setHTMLPlugin: ()=>setHTMLPlugin
953
958
  });
954
- let external_node_module_ = __webpack_require__("node:module"), rspack_rspack = (0, external_node_module_.createRequire)(import.meta.url)('@rspack/core'), external_node_path_ = __webpack_require__("node:path"), external_node_url_ = __webpack_require__("node:url"), constants_filename = (0, external_node_url_.fileURLToPath)(import.meta.url), constants_dirname = (0, external_node_path_.dirname)(constants_filename), isDeno = 'undefined' != typeof Deno, isWindows = 'win32' === process.platform, ROOT_DIST_DIR = 'dist', LOADER_PATH = (0, external_node_path_.join)(constants_dirname), STATIC_PATH = (0, external_node_path_.join)(constants_dirname, '../static'), CLIENT_PATH = (0, external_node_path_.join)(constants_dirname, 'client'), COMPILED_PATH = (0, external_node_path_.join)(constants_dirname, '../compiled'), RSBUILD_OUTPUTS_PATH = '.rsbuild', DEFAULT_DEV_HOST = '0.0.0.0', DEFAULT_ASSET_PREFIX = '/', DEFAULT_STACK_TRACE = 'summary', DEFAULT_WEB_BROWSERSLIST = [
959
+ let external_node_module_ = __webpack_require__("node:module"), rspack_rspack = (0, external_node_module_.createRequire)(import.meta.url)('@rspack/core');
960
+ function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : node_process.argv) {
961
+ let prefix = flag.startsWith('-') ? '' : 1 === flag.length ? '-' : '--', position = argv.indexOf(prefix + flag), terminatorPosition = argv.indexOf('--');
962
+ return -1 !== position && (-1 === terminatorPosition || position < terminatorPosition);
963
+ }
964
+ let { env: dist_env } = node_process;
965
+ function envForceColor() {
966
+ if (!('FORCE_COLOR' in dist_env)) return;
967
+ if ('true' === dist_env.FORCE_COLOR) return 1;
968
+ if ('false' === dist_env.FORCE_COLOR) return 0;
969
+ if (0 === dist_env.FORCE_COLOR.length) return 1;
970
+ let level = Math.min(Number.parseInt(dist_env.FORCE_COLOR, 10), 3);
971
+ if ([
972
+ 0,
973
+ 1,
974
+ 2,
975
+ 3
976
+ ].includes(level)) return level;
977
+ }
978
+ function translateLevel(level) {
979
+ return 0 !== level && {
980
+ level,
981
+ hasBasic: !0,
982
+ has256: level >= 2,
983
+ has16m: level >= 3
984
+ };
985
+ }
986
+ function _supportsColor(haveStream, { streamIsTTY, sniffFlags = !0 } = {}) {
987
+ let noFlagForceColor = envForceColor();
988
+ void 0 !== noFlagForceColor && (flagForceColor = noFlagForceColor);
989
+ let forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
990
+ if (0 === forceColor) return 0;
991
+ if (sniffFlags) {
992
+ if (hasFlag('color=16m') || hasFlag('color=full') || hasFlag('color=truecolor')) return 3;
993
+ if (hasFlag('color=256')) return 2;
994
+ }
995
+ if ('TF_BUILD' in dist_env && 'AGENT_NAME' in dist_env) return 1;
996
+ if (haveStream && !streamIsTTY && void 0 === forceColor) return 0;
997
+ let min = forceColor || 0;
998
+ if ('dumb' === dist_env.TERM) return min;
999
+ if ('win32' === node_process.platform) {
1000
+ let osRelease = node_os.release().split('.');
1001
+ return Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586 ? Number(osRelease[2]) >= 14931 ? 3 : 2 : 1;
1002
+ }
1003
+ if ('CI' in dist_env) return [
1004
+ 'GITHUB_ACTIONS',
1005
+ 'GITEA_ACTIONS',
1006
+ 'CIRCLECI'
1007
+ ].some((key)=>key in dist_env) ? 3 : [
1008
+ 'TRAVIS',
1009
+ 'APPVEYOR',
1010
+ 'GITLAB_CI',
1011
+ 'BUILDKITE',
1012
+ 'DRONE'
1013
+ ].some((sign)=>sign in dist_env) || 'codeship' === dist_env.CI_NAME ? 1 : min;
1014
+ if ('TEAMCITY_VERSION' in dist_env) return +!!/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(dist_env.TEAMCITY_VERSION);
1015
+ if ('truecolor' === dist_env.COLORTERM || 'xterm-kitty' === dist_env.TERM || 'xterm-ghostty' === dist_env.TERM || 'wezterm' === dist_env.TERM) return 3;
1016
+ if ('TERM_PROGRAM' in dist_env) {
1017
+ let version = Number.parseInt((dist_env.TERM_PROGRAM_VERSION || '').split('.')[0], 10);
1018
+ switch(dist_env.TERM_PROGRAM){
1019
+ case 'iTerm.app':
1020
+ return version >= 3 ? 3 : 2;
1021
+ case 'Apple_Terminal':
1022
+ return 2;
1023
+ }
1024
+ }
1025
+ return /-256(color)?$/i.test(dist_env.TERM) ? 2 : /^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(dist_env.TERM) || 'COLORTERM' in dist_env ? 1 : min;
1026
+ }
1027
+ function createSupportsColor(stream, options = {}) {
1028
+ return translateLevel(_supportsColor(stream, {
1029
+ streamIsTTY: stream && stream.isTTY,
1030
+ ...options
1031
+ }));
1032
+ }
1033
+ hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false') || hasFlag('color=never') ? flagForceColor = 0 : (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') || hasFlag('color=always')) && (flagForceColor = 1);
1034
+ let supportsColor = {
1035
+ stdout: createSupportsColor({
1036
+ isTTY: node_tty.isatty(1)
1037
+ }),
1038
+ stderr: createSupportsColor({
1039
+ isTTY: node_tty.isatty(2)
1040
+ })
1041
+ }, colorLevel = supportsColor.stdout ? supportsColor.stdout.level : 0, errorStackRegExp = /at [^\r\n]{0,200}:\d+:\d+[\s\)]*$/, anonymousErrorStackRegExp = /at [^\r\n]{0,200}\(<anonymous>\)$/, indexErrorStackRegExp = /at [^\r\n]{0,200}\(index\s\d+\)$/, formatter = (open, close, replace = open)=>colorLevel >= 2 ? (input)=>{
1042
+ let string = '' + input, index = string.indexOf(close, open.length);
1043
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
1044
+ } : String, replaceClose = (string, close, replace, index)=>{
1045
+ let start = string.substring(0, index) + replace, end = string.substring(index + close.length), nextIndex = end.indexOf(close);
1046
+ return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end;
1047
+ }, bold = formatter('\x1b[1m', '\x1b[22m', '\x1b[22m\x1b[1m'), red = formatter('\x1b[31m', '\x1b[39m'), green = formatter('\x1b[32m', '\x1b[39m'), yellow = formatter('\x1b[33m', '\x1b[39m'), magenta = formatter('\x1b[35m', '\x1b[39m'), cyan = formatter('\x1b[36m', '\x1b[39m'), gray = formatter('\x1b[90m', '\x1b[39m'), isWord = (char)=>!/[\s\n]/.test(char), LOG_LEVEL = {
1048
+ silent: -1,
1049
+ error: 0,
1050
+ warn: 1,
1051
+ info: 2,
1052
+ log: 2,
1053
+ verbose: 3
1054
+ }, LOG_TYPES = {
1055
+ error: {
1056
+ label: 'error',
1057
+ level: 'error',
1058
+ color: red
1059
+ },
1060
+ warn: {
1061
+ label: 'warn',
1062
+ level: 'warn',
1063
+ color: yellow
1064
+ },
1065
+ info: {
1066
+ label: 'info',
1067
+ level: 'info',
1068
+ color: cyan
1069
+ },
1070
+ start: {
1071
+ label: 'start',
1072
+ level: 'info',
1073
+ color: cyan
1074
+ },
1075
+ ready: {
1076
+ label: 'ready',
1077
+ level: 'info',
1078
+ color: green
1079
+ },
1080
+ success: {
1081
+ label: 'success',
1082
+ level: 'info',
1083
+ color: green
1084
+ },
1085
+ log: {
1086
+ level: 'info'
1087
+ },
1088
+ debug: {
1089
+ label: 'debug',
1090
+ level: 'verbose',
1091
+ color: magenta
1092
+ }
1093
+ }, normalizeErrorMessage = (err)=>{
1094
+ if (err.stack) {
1095
+ let [name, ...rest] = err.stack.split('\n');
1096
+ return name.startsWith('Error: ') && (name = name.slice(7)), `${name}\n${gray(rest.join('\n'))}`;
1097
+ }
1098
+ return err.message;
1099
+ }, src_logger = ((options = {})=>{
1100
+ let maxLevel = options.level || 'info', log = (type, message, ...args)=>{
1101
+ let logType = LOG_TYPES[type], { level } = logType;
1102
+ if (LOG_LEVEL[level] > LOG_LEVEL[maxLevel]) return;
1103
+ if (null == message) return console.log();
1104
+ let label = '', text = '';
1105
+ if ('label' in logType && (label = (logType.label || '').padEnd(7), label = bold(logType.color ? logType.color(label) : label)), message instanceof Error) {
1106
+ text += normalizeErrorMessage(message);
1107
+ let { cause } = message;
1108
+ cause && (text += yellow('\n [cause]: '), text += cause instanceof Error ? normalizeErrorMessage(cause) : String(cause));
1109
+ } else text = 'error' === level && 'string' == typeof message ? message.split('\n').map((line)=>errorStackRegExp.test(line) || anonymousErrorStackRegExp.test(line) || indexErrorStackRegExp.test(line) ? gray(line) : line).join('\n') : `${message}`;
1110
+ console['error' === level || 'warn' === level ? level : 'log'](label.length ? `${label} ${text}` : text, ...args);
1111
+ }, logger = {
1112
+ greet: (message)=>log('log', ((message)=>{
1113
+ if (colorLevel < 3) return 2 === colorLevel ? bold(cyan(message)) : message;
1114
+ let chars = [
1115
+ ...message
1116
+ ], steps = chars.filter(isWord).length, r = 189, g = 255, b = 243, rStep = -115 / steps, gStep = -61 / steps, bStep = -89 / steps, output = '';
1117
+ for (let char of chars)isWord(char) && (r += rStep, g += gStep, b += bStep), output += `\x1b[38;2;${Math.round(r)};${Math.round(g)};${Math.round(b)}m${char}\x1b[39m`;
1118
+ return bold(output);
1119
+ })(message))
1120
+ };
1121
+ return Object.keys(LOG_TYPES).forEach((key)=>{
1122
+ logger[key] = (...args)=>log(key, ...args);
1123
+ }), Object.defineProperty(logger, 'level', {
1124
+ get: ()=>maxLevel,
1125
+ set (val) {
1126
+ maxLevel = val;
1127
+ }
1128
+ }), logger.override = (customLogger)=>{
1129
+ Object.assign(logger, customLogger);
1130
+ }, logger;
1131
+ })(), external_node_path_ = __webpack_require__("node:path"), external_node_url_ = __webpack_require__("node:url"), constants_filename = (0, external_node_url_.fileURLToPath)(import.meta.url), constants_dirname = (0, external_node_path_.dirname)(constants_filename), isDeno = "u" > typeof Deno, isWindows = 'win32' === process.platform, ROOT_DIST_DIR = 'dist', LOADER_PATH = (0, external_node_path_.join)(constants_dirname), STATIC_PATH = (0, external_node_path_.join)(constants_dirname, '../static'), CLIENT_PATH = (0, external_node_path_.join)(constants_dirname, 'client'), COMPILED_PATH = (0, external_node_path_.join)(constants_dirname, '../compiled'), RSBUILD_OUTPUTS_PATH = '.rsbuild', DEFAULT_DEV_HOST = '0.0.0.0', DEFAULT_ASSET_PREFIX = '/', DEFAULT_STACK_TRACE = 'summary', DEFAULT_WEB_BROWSERSLIST = [
955
1132
  'chrome >= 87',
956
1133
  'edge >= 88',
957
1134
  'firefox >= 78',
@@ -997,7 +1174,7 @@ let external_node_module_ = __webpack_require__("node:module"), rspack_rspack =
997
1174
  'aac',
998
1175
  'm4a',
999
1176
  'opus'
1000
- ], LAZY_COMPILATION_IDENTIFIER = 'lazy-compilation-proxy', vendors_require = (0, external_node_module_.createRequire)(import.meta.url), requireCompiledPackage = (name)=>vendors_require(`${COMPILED_PATH}/${name}/index.js`), color = requireCompiledPackage('picocolors'), logger = requireCompiledPackage('rslog').logger, isDebug = ()=>{
1177
+ ], LAZY_COMPILATION_IDENTIFIER = 'lazy-compilation-proxy', vendors_require = (0, external_node_module_.createRequire)(import.meta.url), requireCompiledPackage = (name)=>vendors_require(`${COMPILED_PATH}/${name}/index.js`), color = requireCompiledPackage('picocolors'), isDebug = ()=>{
1001
1178
  if (!process.env.DEBUG) return !1;
1002
1179
  let values = process.env.DEBUG.toLocaleLowerCase().split(',');
1003
1180
  return [
@@ -1005,7 +1182,7 @@ let external_node_module_ = __webpack_require__("node:module"), rspack_rspack =
1005
1182
  'builder',
1006
1183
  '*'
1007
1184
  ].some((key)=>values.includes(key));
1008
- };
1185
+ }, isVerbose = ()=>'verbose' === src_logger.level;
1009
1186
  function getTime() {
1010
1187
  let now = new Date(), hours = String(now.getHours()).padStart(2, '0'), minutes = String(now.getMinutes()).padStart(2, '0'), seconds = String(now.getSeconds()).padStart(2, '0');
1011
1188
  return `${hours}:${minutes}:${seconds}`;
@@ -1059,9 +1236,9 @@ function mri2(args, opts) {
1059
1236
  if (alibi) for(k in out)for(arr = opts.alias[k] || []; arr.length > 0;)out[arr.shift()] = out[k];
1060
1237
  return out;
1061
1238
  }
1062
- isDebug() && (logger.level = 'verbose'), logger.override({
1239
+ isDebug() && (src_logger.level = 'verbose'), src_logger.override({
1063
1240
  debug: (message, ...args)=>{
1064
- if ('verbose' !== logger.level) return;
1241
+ if ('verbose' !== src_logger.level) return;
1065
1242
  let time = color.gray(getTime());
1066
1243
  console.log(` ${color.magenta('rsbuild')} ${time} ${message}`, ...args);
1067
1244
  }
@@ -2403,7 +2580,7 @@ function formatModuleTrace(stats, errorFile, level) {
2403
2580
  moduleNames[0] !== formatted && moduleNames.unshift(formatted);
2404
2581
  }
2405
2582
  let trace = moduleNames.slice().reverse();
2406
- return trace.length > 4 && 'verbose' !== logger.level && (trace = [
2583
+ return trace.length > 4 && !isVerbose() && (trace = [
2407
2584
  ...trace.slice(0, 2),
2408
2585
  `… (${trace.length - 2 - 2} hidden)`,
2409
2586
  ...trace.slice(trace.length - 2)
@@ -2459,8 +2636,8 @@ function formatStatsError(stats, root, level = 'error') {
2459
2636
  }
2460
2637
  let prefix = root + external_node_path_.sep;
2461
2638
  return (fileName.startsWith(prefix) && (fileName = fileName.replace(prefix, `.${external_node_path_.sep}`)), /:\d+:\d+/.test(fileName)) ? `File: ${color.cyan(fileName)}\n` : stats.loc ? `File: ${color.cyan(`${fileName}:${stats.loc}`)}\n` : `File: ${color.cyan(`${fileName}:1:1`)}\n`;
2462
- })(fileName, stats, root)}${stats.message}`, verbose = 'verbose' === logger.level;
2463
- if (verbose && (stats.details && (message += `\nDetails: ${stats.details}\n`), stats.stack && (message += `\n${stats.stack}`)), 'error' === level || 'verbose' === logger.level) {
2639
+ })(fileName, stats, root)}${stats.message}`, verbose = isVerbose();
2640
+ if (verbose && (stats.details && (message += `\nDetails: ${stats.details}\n`), stats.stack && (message += `\n${stats.stack}`)), 'error' === level || isVerbose()) {
2464
2641
  let moduleTrace = formatModuleTrace(stats, fileName, level);
2465
2642
  moduleTrace && (message += moduleTrace);
2466
2643
  }
@@ -2549,7 +2726,7 @@ function getStatsOptions(compiler, action) {
2549
2726
  errors: !0,
2550
2727
  warnings: !0,
2551
2728
  moduleTrace: !0,
2552
- errorStack: 'verbose' === logger.level
2729
+ errorStack: isVerbose()
2553
2730
  };
2554
2731
  if ('dev' === action && (defaultOptions = {
2555
2732
  ...defaultOptions,
@@ -2587,7 +2764,7 @@ function formatStats(stats, hasErrors, root) {
2587
2764
  }
2588
2765
  return {};
2589
2766
  }
2590
- let removeLoaderChainDelimiter = (moduleId)=>'verbose' === logger.level ? moduleId : moduleId.split('!=!')[0];
2767
+ let removeLoaderChainDelimiter = (moduleId)=>isVerbose() ? moduleId : moduleId.split('!=!')[0];
2591
2768
  function _define_property(obj, key, value) {
2592
2769
  return key in obj ? Object.defineProperty(obj, key, {
2593
2770
  value: value,
@@ -2753,7 +2930,7 @@ async function emptyDir(dir, keep = [], checkExists = !0) {
2753
2930
  !keep.some((reg)=>reg.test(toPosixPath(fullPath))) && (entry.isDirectory() ? (await emptyDir(fullPath, keep, !1), keep.length || await node_fs.promises.rmdir(fullPath)) : await node_fs.promises.unlink(fullPath));
2754
2931
  }));
2755
2932
  } catch (err) {
2756
- logger.debug(`failed to empty dir: ${dir}`), logger.debug(err);
2933
+ src_logger.debug(`failed to empty dir: ${dir}`), src_logger.debug(err);
2757
2934
  }
2758
2935
  }
2759
2936
  let OVERRIDE_PATHS = new Set([
@@ -3056,7 +3233,7 @@ function createPluginManager() {
3056
3233
  let { before, environment } = options || {};
3057
3234
  for (let newPlugin of newPlugins)if (newPlugin) if (validatePlugin(newPlugin), before) {
3058
3235
  let index = plugins.findIndex((item)=>item.instance.name === before);
3059
- -1 === index ? (logger.warn(`Plugin "${before}" does not exist.`), plugins.push({
3236
+ -1 === index ? (src_logger.warn(`Plugin "${before}" does not exist.`), plugins.push({
3060
3237
  environment,
3061
3238
  instance: newPlugin
3062
3239
  })) : plugins.splice(index, 0, {
@@ -3075,7 +3252,7 @@ function createPluginManager() {
3075
3252
  };
3076
3253
  }
3077
3254
  async function initPlugins({ context, pluginManager }) {
3078
- logger.debug('initializing plugins');
3255
+ src_logger.debug('initializing plugins');
3079
3256
  let plugins = pluginManager.getAllPluginsWithMeta();
3080
3257
  plugins = ((plugins)=>{
3081
3258
  let allLines = [];
@@ -3138,11 +3315,11 @@ async function initPlugins({ context, pluginManager }) {
3138
3315
  await setup(context.getPluginAPI(environment));
3139
3316
  }
3140
3317
  }
3141
- logger.debug('plugins initialized');
3318
+ src_logger.debug('plugins initialized');
3142
3319
  }
3143
3320
  function getHTMLPathByEntry(entryName, config) {
3144
3321
  let filename = getFilename(config, 'html').replace('[name]', entryName), prefix = config.output.distPath.html;
3145
- return prefix.startsWith('/') && logger.warn(`${color.dim('[rsbuild:config]')} Absolute path is not recommended at ${color.yellow(`output.distPath.html: "${prefix}"`)}, use relative path instead.`), external_node_path_.posix.join(prefix, filename).replace(/^\/+/, '');
3322
+ return prefix.startsWith('/') && src_logger.warn(`${color.dim('[rsbuild:config]')} Absolute path is not recommended at ${color.yellow(`output.distPath.html: "${prefix}"`)}, use relative path instead.`), external_node_path_.posix.join(prefix, filename).replace(/^\/+/, '');
3146
3323
  }
3147
3324
  let mapProcessAssetsStage = (compiler, stage)=>{
3148
3325
  let { Compilation } = compiler.webpack;
@@ -3257,7 +3434,7 @@ function initPluginAPI({ context, pluginManager }) {
3257
3434
  return (environment)=>({
3258
3435
  context: publicContext,
3259
3436
  expose,
3260
- logger: logger,
3437
+ logger: src_logger,
3261
3438
  transform: (descriptor, handler)=>{
3262
3439
  let id = `rsbuild-transform-${transformId++}`;
3263
3440
  transformer[id] = handler, hooks.modifyBundlerChain.tapEnvironment({
@@ -3402,7 +3579,7 @@ async function updateEnvironmentContext(context, configs) {
3402
3579
  webSocketToken
3403
3580
  }, readonlyEnvironmentContext = new Proxy(environmentContext, {
3404
3581
  get: (target, prop)=>target[prop],
3405
- set: (target, prop, newValue)=>('manifest' === prop ? target[prop] = newValue : logger.error(`EnvironmentContext is readonly, you can not assign to the "environment.${prop}" prop.`), !0)
3582
+ set: (target, prop, newValue)=>('manifest' === prop ? target[prop] = newValue : src_logger.error(`EnvironmentContext is readonly, you can not assign to the "environment.${prop}" prop.`), !0)
3406
3583
  });
3407
3584
  context.environmentList[index] = readonlyEnvironmentContext, context.environments[name] = readonlyEnvironmentContext;
3408
3585
  }
@@ -3426,13 +3603,13 @@ function createPublicContext(context) {
3426
3603
  get (target, prop) {
3427
3604
  if (exposedKeys.includes(prop)) return target[prop];
3428
3605
  },
3429
- set: (_, prop)=>(logger.error(`Context is readonly, you can not assign to the "context.${prop}" prop.`), !0)
3606
+ set: (_, prop)=>(src_logger.error(`Context is readonly, you can not assign to the "context.${prop}" prop.`), !0)
3430
3607
  });
3431
3608
  }
3432
3609
  async function createContext(options, userConfig) {
3433
3610
  let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = (0, external_node_path_.join)(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, bundlerType = userConfig.provider ? 'webpack' : 'rspack';
3434
3611
  return {
3435
- version: "1.7.0-beta.0",
3612
+ version: "1.7.0-beta.2",
3436
3613
  rootPath,
3437
3614
  distPath: '',
3438
3615
  cachePath,
@@ -3495,7 +3672,7 @@ async function outputInspectConfigFiles({ rawBundlerConfigs, rawEnvironmentConfi
3495
3672
  recursive: !0
3496
3673
  }), await Promise.all(files.map(async (item)=>node_fs.promises.writeFile(item.path, `export default ${item.content}`)));
3497
3674
  let fileInfos = files.map((item)=>` - ${color.bold(color.yellow(item.label))}: ${color.underline(item.path)}`).join('\n');
3498
- logger.success(`config inspection completed, generated files: \n\n${fileInfos}\n`);
3675
+ src_logger.success(`config inspection completed, generated files: \n\n${fileInfos}\n`);
3499
3676
  }
3500
3677
  function stringifyConfig(config, verbose) {
3501
3678
  return src_class.toString(config, {
@@ -3595,7 +3772,7 @@ function reduceConfigsMergeContext({ initial, config, ctx, mergeFn = Object.assi
3595
3772
  }), initial) : config ?? initial;
3596
3773
  }
3597
3774
  async function modifyBundlerChain(context, utils) {
3598
- logger.debug('applying modifyBundlerChain hook');
3775
+ src_logger.debug('applying modifyBundlerChain hook');
3599
3776
  let bundlerChain = new src_class(), [modifiedBundlerChain] = await context.hooks.modifyBundlerChain.callChain({
3600
3777
  environment: utils.environment.name,
3601
3778
  args: [
@@ -3604,7 +3781,7 @@ async function modifyBundlerChain(context, utils) {
3604
3781
  ]
3605
3782
  });
3606
3783
  if (utils.environment.config.tools?.bundlerChain) for (let item of helpers_castArray(utils.environment.config.tools.bundlerChain))await item(modifiedBundlerChain, utils);
3607
- return logger.debug('applied modifyBundlerChain hook'), modifiedBundlerChain;
3784
+ return src_logger.debug('applied modifyBundlerChain hook'), modifiedBundlerChain;
3608
3785
  }
3609
3786
  let configChain_CHAIN_ID = {
3610
3787
  RULE: {
@@ -3693,7 +3870,7 @@ let configChain_CHAIN_ID = {
3693
3870
  cssExtractPlugin = plugin;
3694
3871
  };
3695
3872
  async function modifyRspackConfig(context, rspackConfig, chainUtils) {
3696
- logger.debug('applying modifyRspackConfig hook');
3873
+ src_logger.debug('applying modifyRspackConfig hook');
3697
3874
  let currentConfig = rspackConfig, utils = getConfigUtils(()=>currentConfig, chainUtils);
3698
3875
  if ([currentConfig] = await context.hooks.modifyRspackConfig.callChain({
3699
3876
  environment: utils.environment.name,
@@ -3713,7 +3890,7 @@ async function modifyRspackConfig(context, rspackConfig, chainUtils) {
3713
3890
  mergeFn: (...args)=>currentConfig = utils.mergeConfig.call(utils, args)
3714
3891
  });
3715
3892
  }
3716
- return logger.debug('applied modifyRspackConfig hook'), currentConfig;
3893
+ return src_logger.debug('applied modifyRspackConfig hook'), currentConfig;
3717
3894
  }
3718
3895
  function getConfigUtils(getCurrentConfig, chainUtils) {
3719
3896
  return {
@@ -3766,7 +3943,7 @@ function validateRspackConfig(config) {
3766
3943
  throw Error(`${color.dim('[rsbuild:plugin]')} "${color.yellow(name)}" appears to be an Rsbuild plugin. It cannot be used as an Rspack plugin.`);
3767
3944
  }
3768
3945
  }
3769
- config.devServer && logger.warn(`${color.dim('[rsbuild:config]')} Find invalid Rspack config: "${color.yellow('devServer')}". Note that Rspack's "devServer" config is not supported by Rsbuild. You can use Rsbuild's "dev" config to configure the Rsbuild dev server.`);
3946
+ config.devServer && src_logger.warn(`${color.dim('[rsbuild:config]')} Find invalid Rspack config: "${color.yellow('devServer')}". Note that Rspack's "devServer" config is not supported by Rsbuild. You can use Rsbuild's "dev" config to configure the Rsbuild dev server.`);
3770
3947
  }
3771
3948
  async function generateRspackConfig({ target, context, environmentName }) {
3772
3949
  let chainUtils = getChainUtils(target, context.environments[environmentName], context.environments), { BannerPlugin, DefinePlugin, IgnorePlugin, ProvidePlugin, SourceMapDevToolPlugin, HotModuleReplacementPlugin } = rspack_rspack, rspackConfig = (await modifyBundlerChain(context, {
@@ -3793,14 +3970,14 @@ let allowedEnvironmentDevKeys = [
3793
3970
  'lazyCompilation'
3794
3971
  ];
3795
3972
  async function modifyRsbuildConfig(context) {
3796
- logger.debug('applying modifyRsbuildConfig hook');
3973
+ src_logger.debug('applying modifyRsbuildConfig hook');
3797
3974
  let pluginsCount = context.config.plugins?.length ?? 0, [modified] = await context.hooks.modifyRsbuildConfig.callChain(context.config, {
3798
3975
  mergeRsbuildConfig: mergeRsbuildConfig
3799
3976
  });
3800
- context.config = modified, (modified.plugins?.length ?? 0) !== pluginsCount && logger.warn(`${color.dim('[rsbuild]')} Cannot change plugins via ${color.yellow('modifyRsbuildConfig')} as plugins are already initialized when it executes.`), logger.debug('applied modifyRsbuildConfig hook');
3977
+ context.config = modified, (modified.plugins?.length ?? 0) !== pluginsCount && src_logger.warn(`${color.dim('[rsbuild]')} Cannot change plugins via ${color.yellow('modifyRsbuildConfig')} as plugins are already initialized when it executes.`), src_logger.debug('applied modifyRsbuildConfig hook');
3801
3978
  }
3802
3979
  async function modifyEnvironmentConfig(context, config, name) {
3803
- logger.debug(`applying modifyEnvironmentConfig hook (${name})`);
3980
+ src_logger.debug(`applying modifyEnvironmentConfig hook (${name})`);
3804
3981
  let [modified] = await context.hooks.modifyEnvironmentConfig.callChain({
3805
3982
  environment: name,
3806
3983
  args: [
@@ -3811,7 +3988,7 @@ async function modifyEnvironmentConfig(context, config, name) {
3811
3988
  }
3812
3989
  ]
3813
3990
  });
3814
- return logger.debug(`applied modifyEnvironmentConfig hook (${name})`), modified;
3991
+ return src_logger.debug(`applied modifyEnvironmentConfig hook (${name})`), modified;
3815
3992
  }
3816
3993
  let createEnvironmentNotFoundError = (environments = [])=>{
3817
3994
  let envList = color.yellow(environments.join(','));
@@ -3908,7 +4085,7 @@ async function initRsbuildConfig({ context, pluginManager }) {
3908
4085
  'web-worker'
3909
4086
  ];
3910
4087
  for (let name of environmentNames){
3911
- environmentNameRegexp.test(name) || logger.warn(`${color.dim('[rsbuild:config]')} Environment name "${color.yellow(name)}" contains invalid characters. Only letters, numbers, "-", "_", and "$" are allowed.`);
4088
+ environmentNameRegexp.test(name) || src_logger.warn(`${color.dim('[rsbuild:config]')} Environment name "${color.yellow(name)}" contains invalid characters. Only letters, numbers, "-", "_", and "$" are allowed.`);
3912
4089
  let outputConfig = config.environments[name].output;
3913
4090
  if (outputConfig.target && !validTargets.includes(outputConfig.target)) throw Error(`${color.dim('[rsbuild:config]')} Invalid value of ${color.yellow('output.target')}: ${color.yellow(`"${outputConfig.target}"`)}, valid values are: ${color.yellow(validTargets.join(', '))}`);
3914
4091
  }
@@ -3966,20 +4143,20 @@ function printBuildLog(compiler, context, lazyModules) {
3966
4143
  let { modifiedFiles } = compiler, changedFiles = modifiedFiles?.size ? Array.from(modifiedFiles) : lazyModules.size ? Array.from(lazyModules) : null;
3967
4144
  if (changedFiles?.length) {
3968
4145
  let fileInfo = formatFileList(changedFiles, context.rootPath);
3969
- logger.start(`building ${color.dim(fileInfo)}`);
4146
+ src_logger.start(`building ${color.dim(fileInfo)}`);
3970
4147
  return;
3971
4148
  }
3972
4149
  let removedFiles = compiler.removedFiles ? Array.from(compiler.removedFiles) : null;
3973
4150
  if (removedFiles?.length) {
3974
- if (removedFiles.every((item)=>item.includes('virtual'))) return void logger.start(`building ${color.dim('virtual modules')}`);
4151
+ if (removedFiles.every((item)=>item.includes('virtual'))) return void src_logger.start(`building ${color.dim('virtual modules')}`);
3975
4152
  let fileInfo = formatFileList(removedFiles, context.rootPath);
3976
- return void logger.start(`building ${color.dim(`removed ${fileInfo}`)}`);
4153
+ return void src_logger.start(`building ${color.dim(`removed ${fileInfo}`)}`);
3977
4154
  }
3978
- logger.start('build started...');
4155
+ src_logger.start('build started...');
3979
4156
  }
3980
4157
  async function createCompiler_createCompiler(options) {
3981
4158
  let version;
3982
- logger.debug('creating compiler');
4159
+ src_logger.debug('creating compiler');
3983
4160
  let HOOK_NAME = 'rsbuild:compiler', { context } = options, { rspackConfigs } = await initConfigs(options);
3984
4161
  if (await context.hooks.onBeforeCreateCompiler.callBatch({
3985
4162
  bundlerConfigs: rspackConfigs,
@@ -3996,7 +4173,7 @@ async function createCompiler_createCompiler(options) {
3996
4173
  let isMultiCompiler = rspackConfigs.length > 1, compiler = isMultiCompiler ? rspack_rspack(rspackConfigs) : rspack_rspack(rspackConfigs[0]);
3997
4174
  'true' === process.env.RSPACK_UNSAFE_FAST_DROP && (compiler.unsafeFastDrop = !0);
3998
4175
  let isVersionLogged = !1, isCompiling = !1, logRspackVersion = ()=>{
3999
- isVersionLogged || (logger.debug(`using Rspack v${rspack_rspack.rspackVersion}`), isVersionLogged = !0);
4176
+ isVersionLogged || (src_logger.debug(`using Rspack v${rspack_rspack.rspackVersion}`), isVersionLogged = !0);
4000
4177
  }, lazyModules = new Set();
4001
4178
  compiler.hooks.infrastructureLog.tap(HOOK_NAME, (name, _, args)=>{
4002
4179
  let log = args[0];
@@ -4018,14 +4195,14 @@ async function createCompiler_createCompiler(options) {
4018
4195
  }), compiler.hooks.invalid.tap(HOOK_NAME, ()=>{
4019
4196
  context.buildState.stats = null, context.buildState.status = 'idle', context.buildState.hasErrors = !1;
4020
4197
  }), 'build' === context.action && (isMultiCompiler ? compiler.compilers[0] : compiler).hooks.run.tap(HOOK_NAME, ()=>{
4021
- logger.info('build started...'), logRspackVersion();
4198
+ src_logger.info('build started...'), logRspackVersion();
4022
4199
  });
4023
4200
  let printTime = (index, hasErrors)=>{
4024
4201
  if (null === startTime) return;
4025
4202
  let { name } = context.environmentList[index], time = Date.now() - startTime;
4026
4203
  context.buildState.time[name] = time;
4027
4204
  let suffix = isMultiCompiler ? color.dim(` (${name})`) : '', timeStr = `${prettyTime(time / 1000)}${suffix}`;
4028
- hasErrors ? logger.error(`build failed in ${timeStr}`) : logger.ready(`built in ${timeStr}`);
4205
+ hasErrors ? src_logger.error(`build failed in ${timeStr}`) : src_logger.ready(`built in ${timeStr}`);
4029
4206
  };
4030
4207
  return isMultiCompiler && compiler.compilers.forEach((item, index)=>{
4031
4208
  item.hooks.done.tap(HOOK_NAME, (stats)=>{
@@ -4035,7 +4212,7 @@ async function createCompiler_createCompiler(options) {
4035
4212
  let stats = getRsbuildStats(statsInstance, compiler, context.action), hasErrors = statsInstance.hasErrors();
4036
4213
  context.buildState.stats = stats, context.buildState.status = 'done', context.buildState.hasErrors = hasErrors, context.socketServer?.onBuildDone();
4037
4214
  let { message, level } = formatStats(stats, hasErrors, options.context.rootPath);
4038
- 'error' === level && logger.error(message), 'warning' === level && logger.warn(message), isMultiCompiler || printTime(0, hasErrors), isCompiling = !1;
4215
+ 'error' === level && src_logger.error(message), 'warning' === level && src_logger.warn(message), isMultiCompiler || printTime(0, hasErrors), isCompiling = !1;
4039
4216
  }), 'dev' === context.action && registerDevHook({
4040
4217
  context,
4041
4218
  compiler,
@@ -4044,7 +4221,7 @@ async function createCompiler_createCompiler(options) {
4044
4221
  }), await context.hooks.onAfterCreateCompiler.callBatch({
4045
4222
  compiler,
4046
4223
  environments: context.environments
4047
- }), logger.debug('compiler created'), {
4224
+ }), src_logger.debug('compiler created'), {
4048
4225
  compiler,
4049
4226
  rspackConfigs
4050
4227
  };
@@ -4065,7 +4242,7 @@ let RSPACK_BUILD_ERROR = 'Rspack build failed.', build_build = async (initOption
4065
4242
  }), watch) {
4066
4243
  let watchOptions = bundlerConfigs ? bundlerConfigs.map((options)=>options.watchOptions || {}) : [];
4067
4244
  return compiler.watch(watchOptions.length > 1 ? watchOptions : watchOptions[0] || {}, (err)=>{
4068
- err && logger.error(err);
4245
+ err && src_logger.error(err);
4069
4246
  }), {
4070
4247
  close: ()=>new Promise((resolve)=>{
4071
4248
  compiler.close(()=>{
@@ -4077,7 +4254,7 @@ let RSPACK_BUILD_ERROR = 'Rspack build failed.', build_build = async (initOption
4077
4254
  let { stats } = await new Promise((resolve, reject)=>{
4078
4255
  compiler.run((err, stats)=>{
4079
4256
  compiler.close((closeErr)=>{
4080
- closeErr && logger.error('Failed to close compiler: ', closeErr), err ? reject(err) : context.buildState.hasErrors ? reject(Error(RSPACK_BUILD_ERROR)) : resolve({
4257
+ closeErr && src_logger.error('Failed to close compiler: ', closeErr), err ? reject(err) : context.buildState.hasErrors ? reject(Error(RSPACK_BUILD_ERROR)) : resolve({
4081
4258
  stats
4082
4259
  });
4083
4260
  });
@@ -4106,7 +4283,7 @@ function loadEnv({ cwd = process.cwd(), mode = process.env.NODE_ENV || '', prefi
4106
4283
  `.env.${mode}`,
4107
4284
  `.env.${mode}.local`
4108
4285
  ].map((filename)=>(0, external_node_path_.join)(cwd, filename)).filter(isFileSync), parsed = {};
4109
- for (let envPath of filePaths)Object.assign(parsed, loadEnv_parse(node_fs.readFileSync(envPath))), logger.debug('loaded env file:', envPath);
4286
+ for (let envPath of filePaths)Object.assign(parsed, loadEnv_parse(node_fs.readFileSync(envPath))), src_logger.debug('loaded env file:', envPath);
4110
4287
  parsed.NODE_ENV && (processEnv.NODE_ENV = parsed.NODE_ENV), (0, main.expand)({
4111
4288
  parsed,
4112
4289
  processEnv
@@ -4182,7 +4359,7 @@ async function validateWebpackCache(cacheDirectory, buildDependencies) {
4182
4359
  try {
4183
4360
  prevBuildDependencies = JSON.parse(rawConfigFile);
4184
4361
  } catch (e) {
4185
- logger.debug('failed to parse the previous buildDependencies.json', e);
4362
+ src_logger.debug('failed to parse the previous buildDependencies.json', e);
4186
4363
  }
4187
4364
  if (JSON.stringify(prevBuildDependencies) === JSON.stringify(buildDependencies)) return;
4188
4365
  await node_fs.promises.rm(cacheDirectory, {
@@ -4195,7 +4372,7 @@ async function validateWebpackCache(cacheDirectory, buildDependencies) {
4195
4372
  recursive: !0
4196
4373
  }), await node_fs.promises.writeFile(configFile, JSON.stringify(buildDependencies));
4197
4374
  } catch (e) {
4198
- logger.debug('failed to write the buildDependencies.json', e);
4375
+ src_logger.debug('failed to write the buildDependencies.json', e);
4199
4376
  }
4200
4377
  }
4201
4378
  function getCacheDirectory({ cacheDirectory }, context) {
@@ -4326,7 +4503,7 @@ function checkProcessEnvSecurity(define) {
4326
4503
  if (!value) return;
4327
4504
  let check = (value)=>{
4328
4505
  let pathKey = Object.keys(value).find((key)=>'path' === key.toLowerCase() && value[key] === process.env[key]);
4329
- pathKey && logger.warn(`${color.dim('[rsbuild:config]')} The ${color.yellow('"source.define"')} option includes an object with the key ${color.yellow(JSON.stringify(pathKey))} under ${color.yellow('"process.env"')}, indicating potential exposure of all environment variables. This can lead to security risks and should be avoided.`);
4506
+ pathKey && src_logger.warn(`${color.dim('[rsbuild:config]')} The ${color.yellow('"source.define"')} option includes an object with the key ${color.yellow(JSON.stringify(pathKey))} under ${color.yellow('"process.env"')}, indicating potential exposure of all environment variables. This can lead to security risks and should be avoided.`);
4330
4507
  };
4331
4508
  if ('object' == typeof value) return void check(value);
4332
4509
  if ('string' == typeof value) try {
@@ -4371,7 +4548,7 @@ async function saveSnapshots(snapshotPath, snapshots) {
4371
4548
  recursive: !0
4372
4549
  }), await node_fs.promises.writeFile(snapshotPath, JSON.stringify(snapshots, null, 2));
4373
4550
  } catch (err) {
4374
- logger.debug('Failed to save file size snapshots:', err);
4551
+ src_logger.debug('Failed to save file size snapshots:', err);
4375
4552
  }
4376
4553
  }
4377
4554
  let EXCLUDE_ASSET_REGEX = /\.(?:map|LICENSE\.txt|d\.ts)$/, excludeAsset = (asset)=>EXCLUDE_ASSET_REGEX.test(asset.name), isSignificantDiff = (diff)=>Math.abs(diff) >= 10, formatDiff = (diff)=>{
@@ -4603,7 +4780,7 @@ class RsbuildHtmlPlugin {
4603
4780
  try {
4604
4781
  if (!(buffer = await external_node_util_promisify(compilation.inputFileSystem.readFile)(inputFilename))) throw Error('Buffer is undefined');
4605
4782
  } catch (error) {
4606
- return logger.debug(`read favicon error: ${error}`), addCompilationError(compilation, `${color.dim('[rsbuild:html]')} Failed to read the favicon file at ${color.yellow(inputFilename)}.`), null;
4783
+ return src_logger.debug(`read favicon error: ${error}`), addCompilationError(compilation, `${color.dim('[rsbuild:html]')} Failed to read the favicon file at ${color.yellow(inputFilename)}.`), null;
4607
4784
  }
4608
4785
  let source = new compiler.webpack.sources.RawSource(buffer, !1), outputFilename = external_node_path_.default.posix.join(faviconDistPath, name);
4609
4786
  return compilation.emitAsset(outputFilename, source), outputFilename;
@@ -4911,7 +5088,7 @@ function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls
4911
5088
  }
4912
5089
  if (0 === urls.length || 0 === routes.length && !useCustomUrl) return null;
4913
5090
  let message = getURLMessages(urls, routes);
4914
- return !trailingLineBreak && message.endsWith('\n') && (message = message.slice(0, -1)), logger.log(message), message;
5091
+ return !trailingLineBreak && message.endsWith('\n') && (message = message.slice(0, -1)), src_logger.log(message), message;
4915
5092
  }
4916
5093
  let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
4917
5094
  'string' == typeof port && (port = Number.parseInt(port, 10)), strictPort && (tryLimits = 1);
@@ -5043,9 +5220,9 @@ async function openBrowser(url) {
5043
5220
  if (chromiumBrowser) return await execAsync(`osascript openChrome.applescript "${encodeURI(url)}" "${chromiumBrowser}"`, {
5044
5221
  cwd: STATIC_PATH
5045
5222
  }), !0;
5046
- logger.debug('failed to find the target browser.');
5223
+ src_logger.debug('failed to find the target browser.');
5047
5224
  } catch (err) {
5048
- logger.debug("failed to open start URL with apple script."), logger.debug(err);
5225
+ src_logger.debug("failed to open start URL with apple script."), src_logger.debug(err);
5049
5226
  }
5050
5227
  }
5051
5228
  let { apps, default: baseOpen } = await import("./0~open.js").then((mod)=>({
@@ -5060,10 +5237,10 @@ async function openBrowser(url) {
5060
5237
  }
5061
5238
  } : {};
5062
5239
  return (await baseOpen(url, options)).on('error', (err)=>{
5063
- logger.error('Failed to launch browser in child process', err);
5240
+ src_logger.error('Failed to launch browser in child process', err);
5064
5241
  }), !0;
5065
5242
  } catch (err) {
5066
- return logger.error('Failed to launch browser.'), logger.error(err), !1;
5243
+ return src_logger.error('Failed to launch browser.'), src_logger.error(err), !1;
5067
5244
  }
5068
5245
  }
5069
5246
  let openedURLs = [], replacePortPlaceholder = (url, port)=>url.replace(/<port>/g, String(port));
@@ -5178,13 +5355,13 @@ function applyAlias({ chain, config, rootPath }) {
5178
5355
  initial: {},
5179
5356
  config: config.resolve.alias
5180
5357
  });
5181
- if (config.source.alias && (logger.warn(`${color.dim('[rsbuild:config]')} The ${color.yellow('"source.alias"')} config is deprecated, use ${color.yellow('"resolve.alias"')} instead.`), mergedAlias = reduceConfigs({
5358
+ if (config.source.alias && (src_logger.warn(`${color.dim('[rsbuild:config]')} The ${color.yellow('"source.alias"')} config is deprecated, use ${color.yellow('"resolve.alias"')} instead.`), mergedAlias = reduceConfigs({
5182
5359
  initial: mergedAlias,
5183
5360
  config: config.source.alias
5184
5361
  })), config.resolve.dedupe) for (let pkgName of config.resolve.dedupe){
5185
5362
  let pkgPath;
5186
5363
  if (mergedAlias[pkgName]) {
5187
- logger.debug(`${color.dim('[rsbuild:resolve]')} The package ${color.yellow(pkgName)} is already in the alias config, dedupe option for ${color.yellow(pkgName)} will be ignored.`);
5364
+ src_logger.debug(`${color.dim('[rsbuild:resolve]')} The package ${color.yellow(pkgName)} is already in the alias config, dedupe option for ${color.yellow(pkgName)} will be ignored.`);
5188
5365
  continue;
5189
5366
  }
5190
5367
  try {
@@ -5206,7 +5383,7 @@ function applyAlias({ chain, config, rootPath }) {
5206
5383
  ].join(external_node_path_.sep);
5207
5384
  for(; !pkgPath.endsWith(trailing) && pkgPath.includes('node_modules');)pkgPath = (0, external_node_path_.dirname)(pkgPath);
5208
5385
  } catch {
5209
- 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.`);
5386
+ src_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.`);
5210
5387
  continue;
5211
5388
  }
5212
5389
  mergedAlias[pkgName] = pkgPath;
@@ -5775,7 +5952,7 @@ function createMiddleware(context, ready, outputFileSystem) {
5775
5952
  let resolved = await getFileFromUrl(req.url, outputFileSystem, context);
5776
5953
  if (!resolved) return void await goNext();
5777
5954
  if ('errorCode' in resolved) {
5778
- 403 === resolved.errorCode ? logger.error(`[rsbuild:middleware] Malicious path "${req.url}".`) : 400 === resolved.errorCode && logger.error(`[rsbuild:middleware] Invalid pathname "${req.url}".`), sendError(res, resolved.errorCode);
5955
+ 403 === resolved.errorCode ? src_logger.error(`[rsbuild:middleware] Malicious path "${req.url}".`) : 400 === resolved.errorCode && src_logger.error(`[rsbuild:middleware] Invalid pathname "${req.url}".`), sendError(res, resolved.errorCode);
5779
5956
  return;
5780
5957
  }
5781
5958
  let { fsStats, filename } = resolved, { size } = fsStats, len = size, offset = 0;
@@ -5802,10 +5979,10 @@ function createMiddleware(context, ready, outputFileSystem) {
5802
5979
  if (rangeHeader) {
5803
5980
  let parsedRanges = await parseRangeHeaders(`${size}|${rangeHeader}`);
5804
5981
  if (isRangeFresh() || (parsedRanges = []), -1 === parsedRanges) {
5805
- logger.error("[rsbuild:middleware] Unsatisfiable range for 'Range' header."), res.setHeader('Content-Range', getValueContentRangeHeader('bytes', size)), sendError(res, 416);
5982
+ src_logger.error("[rsbuild:middleware] Unsatisfiable range for 'Range' header."), res.setHeader('Content-Range', getValueContentRangeHeader('bytes', size)), sendError(res, 416);
5806
5983
  return;
5807
5984
  }
5808
- -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]));
5985
+ -2 === parsedRanges ? src_logger.error("[rsbuild:middleware] A malformed 'Range' header was provided. A regular response will be sent for this request.") : parsedRanges.length > 1 && src_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]));
5809
5986
  }
5810
5987
  let [start, end] = calcStartAndEnd(offset, len);
5811
5988
  try {
@@ -5854,12 +6031,12 @@ function setupWriteToDisk(compilers, writeToDisk) {
5854
6031
  recursive: !0
5855
6032
  }, (mkdirError)=>{
5856
6033
  if (mkdirError) {
5857
- logger.error(`[rsbuild:middleware] ${name}Unable to write "${dir}" directory to disk:\n${mkdirError.message}`), callback(mkdirError);
6034
+ src_logger.error(`[rsbuild:middleware] ${name}Unable to write "${dir}" directory to disk:\n${mkdirError.message}`), callback(mkdirError);
5858
6035
  return;
5859
6036
  }
5860
6037
  node_fs.writeFile(targetPath, content, (writeFileError)=>{
5861
6038
  if (writeFileError) {
5862
- logger.error(`[rsbuild:middleware] ${name}Unable to write "${targetPath}" asset to disk:\n${writeFileError.message}`), callback(writeFileError);
6039
+ src_logger.error(`[rsbuild:middleware] ${name}Unable to write "${targetPath}" asset to disk:\n${writeFileError.message}`), callback(writeFileError);
5863
6040
  return;
5864
6041
  }
5865
6042
  callback();
@@ -5880,16 +6057,15 @@ function applyHMREntry({ config, compiler, token, resolvedHost, resolvedPort })
5880
6057
  '<port>' === clientConfig.port && (clientConfig.port = resolvedPort);
5881
6058
  let hmrEntry = `import { init } from '${toPosixPath((0, external_node_path_.join)(CLIENT_PATH, 'hmr.js'))}';
5882
6059
  ${config.dev.client.overlay ? `import '${toPosixPath((0, external_node_path_.join)(CLIENT_PATH, 'overlay.js'))}';` : ''}
5883
-
5884
- init({
5885
- token: '${token}',
5886
- config: ${JSON.stringify(clientConfig)},
5887
- serverHost: ${JSON.stringify(resolvedHost)},
5888
- serverPort: ${resolvedPort},
5889
- liveReload: ${config.dev.liveReload},
5890
- browserLogs: ${!!config.dev.browserLogs},
5891
- logLevel: ${JSON.stringify(config.dev.client.logLevel)}
5892
- });
6060
+ init(
6061
+ '${token}',
6062
+ ${JSON.stringify(clientConfig)},
6063
+ ${JSON.stringify(resolvedHost)},
6064
+ ${resolvedPort},
6065
+ ${config.dev.liveReload},
6066
+ ${!!config.dev.browserLogs},
6067
+ ${JSON.stringify(config.dev.client.logLevel)}
6068
+ )
5893
6069
  `;
5894
6070
  new compiler.webpack.EntryPlugin(compiler.context, createVirtualModule(hmrEntry), {
5895
6071
  name: void 0
@@ -5973,7 +6149,7 @@ let assets_middleware_assetsMiddleware = async ({ config, compiler, context, soc
5973
6149
  else {
5974
6150
  let watchOptions = compilers.length > 1 ? compilers.map(({ options })=>options.watchOptions || {}) : compilers[0].options.watchOptions || {};
5975
6151
  watching = compiler.watch(watchOptions, (error)=>{
5976
- error && (error.message?.includes('× Error:') && (error.message = error.message.replace('× Error:', '').trim()), logger.error(error));
6152
+ error && (error.message?.includes('× Error:') && (error.message = error.message.replace('× Error:', '').trim()), src_logger.error(error));
5977
6153
  });
5978
6154
  }
5979
6155
  }, instance.close = (callback = noop)=>{
@@ -6048,33 +6224,32 @@ function parseNode(line) {
6048
6224
  column: parts[4] ? +parts[4] : null
6049
6225
  } : null;
6050
6226
  }
6051
- let isValidMethodName = (methodName)=>'<unknown>' !== methodName && !/[\\/]/.test(methodName);
6052
- function getOriginalPosition(rawSourceMap, line, column) {
6053
- let { TraceMap, originalPositionFor } = requireCompiledPackage('@jridgewell/trace-mapping');
6054
- return originalPositionFor(new TraceMap(rawSourceMap), {
6055
- line,
6056
- column
6057
- });
6058
- }
6059
- let parseFrame = async (frame, fs, context)=>{
6227
+ let isValidMethodName = (methodName)=>'<unknown>' !== methodName && !/[\\/]/.test(methodName), parseFrame = async (frame, fs, context, cachedTraceMap)=>{
6060
6228
  let { file, column, lineNumber } = frame, sourceMapInfo = await getFileFromUrl(`${file}.map`, fs, context);
6061
6229
  if (!sourceMapInfo || 'errorCode' in sourceMapInfo) return;
6062
- let readFile = external_node_util_promisify(fs.readFile);
6230
+ let { TraceMap, originalPositionFor } = requireCompiledPackage('@jridgewell/trace-mapping'), sourceMapPath = sourceMapInfo.filename;
6063
6231
  try {
6064
- let sourceMap = await readFile(sourceMapInfo.filename);
6065
- if (sourceMap) return {
6066
- sourceMapPath: sourceMapInfo.filename,
6067
- originalPosition: getOriginalPosition(sourceMap.toString(), lineNumber ?? 0, column ?? 0)
6232
+ let tracer = cachedTraceMap.get(sourceMapPath);
6233
+ if (!tracer) {
6234
+ let readFile = external_node_util_promisify(fs.readFile), sourceMap = await readFile(sourceMapPath);
6235
+ if (!sourceMap) return;
6236
+ tracer = new TraceMap(sourceMap.toString()), cachedTraceMap.set(sourceMapPath, tracer);
6237
+ }
6238
+ let originalPosition = originalPositionFor(tracer, {
6239
+ line: lineNumber ?? 0,
6240
+ column: column ?? 0
6241
+ });
6242
+ return {
6243
+ sourceMapPath,
6244
+ originalPosition
6068
6245
  };
6069
6246
  } catch (error) {
6070
- error instanceof Error && logger.debug(`failed to map source map position: ${error.message}`);
6247
+ error instanceof Error && src_logger.debug(`failed to map source map position: ${error.message}`);
6071
6248
  }
6072
- }, resolveOriginalLocation = async (stack, fs, context)=>{
6073
- let parsed = stack_trace_parser_esm_parse(stack);
6074
- if (!parsed.length) return;
6075
- let frame = parsed.find((frame)=>null !== frame.file && null !== frame.column && null !== frame.lineNumber && SCRIPT_REGEX.test(frame.file));
6249
+ }, resolveOriginalLocation = async (stackFrames, fs, context, cachedTraceMap)=>{
6250
+ let frame = stackFrames.find((frame)=>null !== frame.file && null !== frame.column && null !== frame.lineNumber && SCRIPT_REGEX.test(frame.file));
6076
6251
  if (!frame) return;
6077
- let parsedFrame = await parseFrame(frame, fs, context);
6252
+ let parsedFrame = await parseFrame(frame, fs, context, cachedTraceMap);
6078
6253
  if (!parsedFrame) return;
6079
6254
  let { sourceMapPath, originalPosition } = parsedFrame;
6080
6255
  return {
@@ -6082,40 +6257,41 @@ let parseFrame = async (frame, fs, context)=>{
6082
6257
  location: formatOriginalLocation(sourceMapPath, originalPosition, context)
6083
6258
  };
6084
6259
  }, formatOriginalLocation = (sourceMapPath, originalMapping, context)=>{
6085
- let absoluteSourcePath, { source, line, column } = originalMapping;
6260
+ let { source, line, column } = originalMapping;
6086
6261
  if (!source) return;
6087
- let result = (absoluteSourcePath = external_node_path_.default.isAbsolute(source) ? source : external_node_path_.default.join(external_node_path_.default.dirname(sourceMapPath), source), external_node_path_.default.relative(context.rootPath, absoluteSourcePath));
6262
+ let result = ((source, sourceMapPath, context)=>{
6263
+ if (source.startsWith('webpack/runtime/')) return source;
6264
+ let absoluteSourcePath = external_node_path_.default.isAbsolute(source) ? source : external_node_path_.default.join(external_node_path_.default.dirname(sourceMapPath), source);
6265
+ return external_node_path_.default.relative(context.rootPath, absoluteSourcePath);
6266
+ })(source, sourceMapPath, context);
6088
6267
  return null !== line && (result += null === column ? `:${line}` : `:${line}:${column}`), result;
6089
6268
  }, formatFrameLocation = (frame)=>{
6090
6269
  let { file, lineNumber, column } = frame;
6091
6270
  if (file) return null !== lineNumber ? null !== column ? `${file}:${lineNumber}:${column}` : `${file}:${lineNumber}` : file;
6092
- }, formatFullStack = async (stack, context, fs)=>{
6093
- let parsed = stack_trace_parser_esm_parse(stack);
6094
- if (!parsed.length) return;
6271
+ }, formatFullStack = async (stackFrames, context, fs, cachedTraceMap)=>{
6095
6272
  let result = '';
6096
- for (let frame of parsed){
6097
- let parsedFrame = await parseFrame(frame, fs, context), { methodName } = frame, parts = [];
6098
- if (isValidMethodName(methodName) && parts.push(methodName), parsedFrame) {
6273
+ for (let frame of stackFrames){
6274
+ let parsedFrame = await parseFrame(frame, fs, context, cachedTraceMap), { methodName } = frame, parts = [];
6275
+ isValidMethodName(methodName) && parts.push(methodName);
6276
+ let parsed = !1;
6277
+ if (parsedFrame) {
6099
6278
  let { sourceMapPath, originalPosition } = parsedFrame, originalLocation = formatOriginalLocation(sourceMapPath, originalPosition, context);
6100
- if (originalLocation) parts.push(originalLocation);
6101
- else {
6102
- let frameString = formatFrameLocation(frame);
6103
- frameString && parts.push(frameString);
6104
- }
6105
- } else {
6279
+ originalLocation && (parts.push(originalLocation), parsed = !0);
6280
+ }
6281
+ if (!parsed && isVerbose()) {
6106
6282
  let frameString = formatFrameLocation(frame);
6107
6283
  frameString && parts.push(frameString);
6108
6284
  }
6109
6285
  parts[0] && (result += `\n at ${parts[0]}`), parts[1] && (result += ` (${parts[1]})`);
6110
6286
  }
6111
6287
  return result;
6112
- }, formatBrowserErrorLog = async (message, context, fs, stackTrace)=>{
6288
+ }, formatBrowserErrorLog = async (message, context, fs, stackTrace, stackFrames, cachedTraceMap)=>{
6113
6289
  var log;
6114
- let log1 = `${color.cyan('[browser]')} ${color.red(message.message)}`;
6115
- if (message.stack) switch(stackTrace){
6290
+ let log1 = color.red(message);
6291
+ if (stackFrames?.length) switch(stackTrace){
6116
6292
  case 'summary':
6117
6293
  {
6118
- let resolved = await resolveOriginalLocation(message.stack, fs, context);
6294
+ let resolved = await resolveOriginalLocation(stackFrames, fs, context, cachedTraceMap);
6119
6295
  if (!resolved) break;
6120
6296
  let { frame, location } = resolved, { methodName } = frame, suffix = '';
6121
6297
  isValidMethodName(methodName) && (suffix += ` at ${methodName}`), location && (suffix += ` (${location})`), log1 += suffix ? color.dim(suffix) : '';
@@ -6123,7 +6299,7 @@ let parseFrame = async (frame, fs, context)=>{
6123
6299
  }
6124
6300
  case 'full':
6125
6301
  {
6126
- let fullStack = await formatFullStack(message.stack, context, fs);
6302
+ let fullStack = await formatFullStack(stackFrames, context, fs, cachedTraceMap);
6127
6303
  fullStack && (log1 += fullStack);
6128
6304
  }
6129
6305
  }
@@ -6170,9 +6346,9 @@ function ansiHTML(text) {
6170
6346
  return ansiCodes.length > 0 && (ret += Array(ansiCodes.length + 1).join('</span>')), ret;
6171
6347
  }
6172
6348
  function convertLinksInHtml(text, root) {
6173
- let PATH_RE = /(?:\.\.?[/\\]|(file:\/\/\/)?[a-zA-Z]:\\|(file:\/\/)?\/|[A-Za-z0-9._-]+[/\\])[^\s:]*:\d+:\d+/g, URL_RE = /(https?:\/\/(?:[\w-]+\.)+[a-z0-9](?:[\w-.~:/?#[\]@!$&'*+,;=])*)/gi, NODE_INTERNAL_RE = /node:internal[/\\]/, FILE_URI_WINDOWS_RE = /^file:\/\/\/([A-Za-z]:)/, FILE_URI_UNIX_RE = /^file:\/\//;
6349
+ let PATH_RE = /(?:\.\.?[/\\]|(file:\/\/\/)?[a-zA-Z]:\\|(file:\/\/)?\/|[A-Za-z0-9._-]+[/\\])[^\s:]*:\d+:\d+/g, URL_RE = /(https?:\/\/(?:[\w-]+\.)+[a-z0-9](?:[\w-.~:/?#[\]@!$&'*+,;=])*)/gi, NODE_INTERNAL_RE = /node:internal[/\\]/, RSPACK_RUNTIME_RE = /webpack\/runtime\//, FILE_URI_WINDOWS_RE = /^file:\/\/\/([A-Za-z]:)/, FILE_URI_UNIX_RE = /^file:\/\//;
6174
6350
  return text.split('\n').map((line)=>{
6175
- if (NODE_INTERNAL_RE.test(line)) return line;
6351
+ if (NODE_INTERNAL_RE.test(line) || RSPACK_RUNTIME_RE.test(line)) return line;
6176
6352
  let replacedLine = line.replace(PATH_RE, (file)=>{
6177
6353
  let hasClosingSpan = (file = ((file)=>{
6178
6354
  if (!file.startsWith('file://')) return file;
@@ -6184,141 +6360,6 @@ function convertLinksInHtml(text, root) {
6184
6360
  return replacedLine.replace(URL_RE, (url)=>`<a class="url-link" href="${url}" target="_blank" rel="noopener noreferrer">${url}</a>`);
6185
6361
  }).join('\n');
6186
6362
  }
6187
- function genOverlayHTML(errors, root) {
6188
- let htmlItems = errors.map((item)=>convertLinksInHtml(ansiHTML(escapeHtml(item)), root));
6189
- return `
6190
- <style>
6191
- .root {
6192
- position: fixed;
6193
- z-index: 9999;
6194
- top: 0;
6195
- left: 0;
6196
- width: 100%;
6197
- height: 100%;
6198
- overflow-y: scroll;
6199
- margin: 0;
6200
- background: rgba(0, 0, 0, 0.66);
6201
- cursor: pointer;
6202
- }
6203
- .container {
6204
- font-family: Menlo, Consolas, monospace;
6205
- line-height: 1.6;
6206
- width: 960px;
6207
- max-width: 85%;
6208
- color: #d8d8d8;
6209
- margin: 32px auto;
6210
- padding: 32px 40px;
6211
- position: relative;
6212
- background: #181818;
6213
- border-radius: 24px;
6214
- box-shadow: 0 19px 38px rgba(0,0,0,0.30), 0 15px 12px rgba(0,0,0,0.22);
6215
- overflow: hidden;
6216
- direction: ltr;
6217
- text-align: left;
6218
- box-sizing: border-box;
6219
- cursor: default;
6220
- }
6221
- .title {
6222
- margin: 0 0 20px;
6223
- padding-bottom: 12px;
6224
- font-size: 17px;
6225
- font-weight: 600;
6226
- color: #fb6a6a;
6227
- border-bottom: 2px solid rgba(252,94,94,.66);
6228
- }
6229
- .content {
6230
- margin: 0;
6231
- font-size: 14px;
6232
- font-family: inherit;
6233
- white-space: pre-wrap;
6234
- word-break: break-all;
6235
- scrollbar-width: none;
6236
- }
6237
- .content::-webkit-scrollbar {
6238
- display: none;
6239
- }
6240
- .file-link,
6241
- .url-link,
6242
- .config-link {
6243
- cursor: pointer;
6244
- text-decoration: underline;
6245
- text-underline-offset: 3px;
6246
- &:hover {
6247
- opacity: 0.8;
6248
- }
6249
- &:active {
6250
- opacity: 0.6;
6251
- }
6252
- }
6253
- .file-link {
6254
- color: #6eecf7;
6255
- }
6256
- .url-link {
6257
- color: #eff986;
6258
- }
6259
- .config-link {
6260
- color: inherit;
6261
- text-decoration: none;
6262
- }
6263
- .close {
6264
- position: absolute;
6265
- top: 27px;
6266
- right: 32px;
6267
- width: 32px;
6268
- height: 32px;
6269
- cursor: pointer;
6270
- }
6271
- .close:hover {
6272
- opacity: 0.8;
6273
- }
6274
- .close:active {
6275
- opacity: 0.6;
6276
- }
6277
- .close:before,
6278
- .close:after {
6279
- position: absolute;
6280
- left: 16px;
6281
- top: 8px;
6282
- content: ' ';
6283
- height: 18px;
6284
- width: 2px;
6285
- border-radius: 4px;
6286
- background-color: #b8b8b8;
6287
- }
6288
- .close:before {
6289
- transform: rotate(45deg);
6290
- }
6291
- .close:after {
6292
- transform: rotate(-45deg);
6293
- }
6294
- .footer {
6295
- font-size: 12px;
6296
- color: #7e6a92;
6297
- margin-top: 20px;
6298
- padding-top: 12px;
6299
- border-top: 2px solid rgba(126,106,146,.6);
6300
- }
6301
- .footer p {
6302
- margin: 4px 0 0;
6303
- }
6304
- .footer span {
6305
- color: #a88dc3;
6306
- }
6307
- </style>
6308
-
6309
- <div class="root">
6310
- <div class="container">
6311
- <div class="close"></div>
6312
- <p class="title">Build failed</p>
6313
- <pre class="content">${htmlItems.join('\n\n').trim()}</pre>
6314
- <footer class="footer">
6315
- <p><span>Fix error</span>, click outside, or press Esc to close the overlay.</p>
6316
- <p>Disable overlay by setting Rsbuild's <span><a class="config-link" target="_blank" rel="noopener noreferrer" href="https://rsbuild.rs/config/dev/client">dev.client.overlay</a></span> config to false.<p>
6317
- </footer>
6318
- </div>
6319
- </div>
6320
- `;
6321
- }
6322
6363
  function isEqualSet(a, b) {
6323
6364
  return a.size === b.size && [
6324
6365
  ...a
@@ -6362,7 +6403,7 @@ class SocketServer {
6362
6403
  noServer: !0,
6363
6404
  path: this.options.client?.path
6364
6405
  }), this.wsServer.on('error', (err)=>{
6365
- logger.error(err);
6406
+ src_logger.error(err);
6366
6407
  }), this.heartbeatTimer = setTimeout(this.checkSockets, 30000).unref(), this.wsServer.on('connection', (socket, req)=>{
6367
6408
  let query = parseQueryString(req);
6368
6409
  this.onConnect(socket, query.token);
@@ -6374,12 +6415,12 @@ class SocketServer {
6374
6415
  });
6375
6416
  }
6376
6417
  sendError(errors, token) {
6377
- let formattedErrors = errors.map((item)=>formatStatsError(item, this.context.rootPath));
6418
+ let { rootPath } = this.context, formattedErrors = errors.map((item)=>formatStatsError(item, rootPath)), html = formattedErrors.map((error)=>convertLinksInHtml(ansiHTML(escapeHtml(error)), rootPath)).join('\n\n').trim();
6378
6419
  this.sockWrite({
6379
6420
  type: 'errors',
6380
6421
  data: {
6381
6422
  text: formattedErrors,
6382
- html: genOverlayHTML(formattedErrors, this.context.rootPath)
6423
+ html
6383
6424
  }
6384
6425
  }, token);
6385
6426
  }
@@ -6417,12 +6458,21 @@ class SocketServer {
6417
6458
  socket.isAlive = !0;
6418
6459
  }), socket.on('message', async (data)=>{
6419
6460
  try {
6420
- let message = JSON.parse('string' == typeof data ? data : data.toString()), config = this.context.normalizedConfig;
6461
+ let payload = JSON.parse('string' == typeof data ? data : data.toString()), { context } = this, config = context.normalizedConfig;
6421
6462
  if (!config) return;
6422
- let { browserLogs } = config.dev;
6423
- if ('client-error' === message.type && 'rspack' === this.context.bundlerType && !this.context.buildState.hasErrors && browserLogs) {
6424
- let stackTrace = isObject(browserLogs) && browserLogs.stackTrace || DEFAULT_STACK_TRACE, log = await formatBrowserErrorLog(message, this.context, this.getOutputFileSystem(), stackTrace);
6425
- this.reportedBrowserLogs.has(log) || (this.reportedBrowserLogs.add(log), logger.error(log));
6463
+ let { browserLogs, client } = config.dev;
6464
+ if ('client-error' === payload.type && 'rspack' === context.bundlerType && !context.buildState.hasErrors && browserLogs) {
6465
+ 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);
6466
+ if (this.reportedBrowserLogs.has(log) || (this.reportedBrowserLogs.add(log), src_logger.error(`${color.cyan('[browser]')} ${log}`)), 'object' == typeof client.overlay && client.overlay.runtime) {
6467
+ let resolvedLog = 'full' === stackTrace ? log : await formatBrowserErrorLog(payload.message, context, outputFs, 'full', stackFrames, cachedTraceMap);
6468
+ this.sockWrite({
6469
+ type: 'resolved-client-error',
6470
+ data: {
6471
+ id: payload.id,
6472
+ message: convertLinksInHtml(ansiHTML(escapeHtml(resolvedLog)), void 0)
6473
+ }
6474
+ }, token);
6475
+ }
6426
6476
  }
6427
6477
  } catch {}
6428
6478
  });
@@ -6559,7 +6609,7 @@ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls,
6559
6609
  }
6560
6610
  ].filter(Boolean);
6561
6611
  if (customShortcuts && !Array.isArray(shortcuts = customShortcuts(shortcuts))) throw Error(`${color.dim('[rsbuild:config]')} ${color.yellow('dev.cliShortcuts')} option must return an array of shortcuts.`);
6562
- help && logger.log(!0 === help ? ` ➜ ${color.dim('press')} ${color.bold('h + enter')} ${color.dim('to show shortcuts')}\n` : ` ➜ ${help}\n`);
6612
+ help && src_logger.log(!0 === help ? ` ➜ ${color.dim('press')} ${color.bold('h + enter')} ${color.dim('to show shortcuts')}\n` : ` ➜ ${help}\n`);
6563
6613
  let { createInterface } = await import("node:readline"), rl = createInterface({
6564
6614
  input: process.stdin
6565
6615
  });
@@ -6567,7 +6617,7 @@ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls,
6567
6617
  if ('h' === input) {
6568
6618
  let message = `\n ${color.bold(color.blue('Shortcuts:'))}\n`;
6569
6619
  for (let shortcut of shortcuts)message += ` ${shortcut.description}\n`;
6570
- logger.log(message);
6620
+ src_logger.log(message);
6571
6621
  }
6572
6622
  for (let shortcut of shortcuts)if (input === shortcut.key) return void shortcut.action();
6573
6623
  }), ()=>{
@@ -6613,15 +6663,15 @@ function historyApiFallback_historyApiFallbackMiddleware(options = {}) {
6613
6663
  let rewriteTarget, { headers } = req;
6614
6664
  if (!req.url) return void next();
6615
6665
  if ('GET' !== req.method && 'HEAD' !== req.method) {
6616
- logger.debug('Not rewriting', req.method, req.url, 'because the method is not GET or HEAD.'), next();
6666
+ src_logger.debug('Not rewriting', req.method, req.url, 'because the method is not GET or HEAD.'), next();
6617
6667
  return;
6618
6668
  }
6619
6669
  if (!headers || 'string' != typeof headers.accept) {
6620
- logger.debug('Not rewriting', req.method, req.url, 'because the client did not send an HTTP accept header.'), next();
6670
+ src_logger.debug('Not rewriting', req.method, req.url, 'because the client did not send an HTTP accept header.'), next();
6621
6671
  return;
6622
6672
  }
6623
6673
  if (0 === headers.accept.indexOf('application/json')) {
6624
- logger.debug('Not rewriting', req.method, req.url, 'because the client prefers JSON.'), next();
6674
+ src_logger.debug('Not rewriting', req.method, req.url, 'because the client prefers JSON.'), next();
6625
6675
  return;
6626
6676
  }
6627
6677
  let rewrites = options.rewrites || [], htmlAcceptHeaders = options.htmlAcceptHeaders || [
@@ -6629,7 +6679,7 @@ function historyApiFallback_historyApiFallbackMiddleware(options = {}) {
6629
6679
  '*/*'
6630
6680
  ], { accept } = headers;
6631
6681
  if (!htmlAcceptHeaders.some((item)=>accept.includes(item))) {
6632
- logger.debug('Not rewriting', req.method, req.url, 'because the client does not accept HTML.'), next();
6682
+ src_logger.debug('Not rewriting', req.method, req.url, 'because the client does not accept HTML.'), next();
6633
6683
  return;
6634
6684
  }
6635
6685
  let parsedUrl = parseReqUrl(req);
@@ -6642,16 +6692,16 @@ function historyApiFallback_historyApiFallbackMiddleware(options = {}) {
6642
6692
  parsedUrl,
6643
6693
  match,
6644
6694
  request: req
6645
- })).charAt(0) && logger.debug('We recommend using an absolute path for the rewrite target.', 'Received a non-absolute rewrite target', rewriteTarget, 'for URL', req.url), logger.debug('Rewriting', req.method, req.url, 'to', rewriteTarget), req.url = rewriteTarget, next();
6695
+ })).charAt(0) && src_logger.debug('We recommend using an absolute path for the rewrite target.', 'Received a non-absolute rewrite target', rewriteTarget, 'for URL', req.url), src_logger.debug('Rewriting', req.method, req.url, 'to', rewriteTarget), req.url = rewriteTarget, next();
6646
6696
  return;
6647
6697
  }
6648
6698
  let { pathname } = parsedUrl;
6649
6699
  if (pathname && pathname.lastIndexOf('.') > pathname.lastIndexOf('/') && !0 !== options.disableDotRule) {
6650
- logger.debug('Not rewriting', req.method, req.url, 'because the path includes a dot (.) character.'), next();
6700
+ src_logger.debug('Not rewriting', req.method, req.url, 'because the path includes a dot (.) character.'), next();
6651
6701
  return;
6652
6702
  }
6653
6703
  let index = options.index || '/index.html';
6654
- logger.debug('Rewriting', req.method, req.url, 'to', index), req.url = index, next();
6704
+ src_logger.debug('Rewriting', req.method, req.url, 'to', index), req.url = index, next();
6655
6705
  };
6656
6706
  }
6657
6707
  function parseReqUrl(req) {
@@ -6669,7 +6719,7 @@ let faviconFallbackMiddleware = (req, res, next)=>{
6669
6719
  let _startAt = process.hrtime();
6670
6720
  on_finished_default()(res, ()=>{
6671
6721
  let method = req.method, url = req.originalUrl || req.url, status = Number(res.statusCode), statusColor = status >= 500 ? color.red : status >= 400 ? color.yellow : status >= 300 ? color.cyan : status >= 200 ? color.green : (res)=>res, endAt = process.hrtime(), totalTime = (endAt[0] - _startAt[0]) * 1e3 + (endAt[1] - _startAt[1]) * 1e-6;
6672
- logger.debug(`${statusColor(status)} ${method} ${url} ${color.dim(`${totalTime.toFixed(3)} ms`)}`);
6722
+ src_logger.debug(`${statusColor(status)} ${method} ${url} ${color.dim(`${totalTime.toFixed(3)} ms`)}`);
6673
6723
  }), next();
6674
6724
  };
6675
6725
  }, notFoundMiddleware = (_req, res, _next)=>{
@@ -6720,7 +6770,7 @@ function formatProxyOptions(proxyOptions) {
6720
6770
  context,
6721
6771
  changeOrigin: !0,
6722
6772
  logLevel: 'warn',
6723
- logProvider: ()=>logger
6773
+ logProvider: ()=>src_logger
6724
6774
  };
6725
6775
  'string' == typeof options ? opts.target = options : Object.assign(opts, options), ret.push(opts);
6726
6776
  }
@@ -7079,7 +7129,7 @@ async function startWatchFiles({ paths, options, type = 'reload-page' }, buildMa
7079
7129
  }
7080
7130
  async function devServer_createDevServer(options, createCompiler, config, { compiler: customCompiler, getPortSilently, runCompile = !0 } = {}) {
7081
7131
  let lastStats, fileWatcher, devMiddlewares;
7082
- logger.debug('create dev server');
7132
+ src_logger.debug('create dev server');
7083
7133
  let { port, host, https, portTip } = await getServerConfig({
7084
7134
  config
7085
7135
  }), { middlewareMode } = config.server, { context } = options, routes = getRoutes(context), root = context.rootPath;
@@ -7152,7 +7202,7 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
7152
7202
  });
7153
7203
  context.hooks.onCloseDevServer.tap(cleanup);
7154
7204
  }
7155
- !getPortSilently && portTip && logger.info(portTip);
7205
+ !getPortSilently && portTip && src_logger.info(portTip);
7156
7206
  }, cacheableLoadBundle = createCacheableFunction(loadBundle), cacheableTransformedHtml = createCacheableFunction((_stats, entryName, utils)=>((entryName, utils)=>{
7157
7207
  let { htmlPaths, distPath } = utils.environment, htmlPath = htmlPaths[entryName];
7158
7208
  if (!htmlPath) throw Error(`${color.dim('[rsbuild:getTransformedHtml]')} Failed to get HTML file by entryName: ${color.yellow(entryName)}`);
@@ -7197,13 +7247,13 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
7197
7247
  listen: async ()=>{
7198
7248
  if (!httpServer) throw Error(`${color.dim('[rsbuild:server]')} Can not listen dev server as ${color.yellow('server.middlewareMode')} is enabled.`);
7199
7249
  let serverTerminator = getServerTerminator(httpServer);
7200
- return logger.debug('listen dev server'), context.hooks.onCloseDevServer.tap(serverTerminator), new Promise((resolve)=>{
7250
+ return src_logger.debug('listen dev server'), context.hooks.onCloseDevServer.tap(serverTerminator), new Promise((resolve)=>{
7201
7251
  httpServer.listen({
7202
7252
  host,
7203
7253
  port
7204
7254
  }, async (err)=>{
7205
7255
  if (err) throw err;
7206
- middlewares.use(optionsFallbackMiddleware), middlewares.use(notFoundMiddleware), devMiddlewares && httpServer.on('upgrade', devMiddlewares.onUpgrade), logger.debug('listen dev server done'), await devServerAPI.afterListen(), onBeforeRestartServer(devServerAPI.close), resolve({
7256
+ middlewares.use(optionsFallbackMiddleware), middlewares.use(notFoundMiddleware), devMiddlewares && httpServer.on('upgrade', devMiddlewares.onUpgrade), src_logger.debug('listen dev server done'), await devServerAPI.afterListen(), onBeforeRestartServer(devServerAPI.close), resolve({
7207
7257
  port,
7208
7258
  urls: urls.map((item)=>item.url),
7209
7259
  server: {
@@ -7238,7 +7288,7 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
7238
7288
  root
7239
7289
  }), (devMiddlewares = ((options)=>{
7240
7290
  let middlewares = [], { buildManager } = options;
7241
- 'verbose' === logger.level && middlewares.push(getRequestLoggerMiddleware());
7291
+ isVerbose() && middlewares.push(getRequestLoggerMiddleware());
7242
7292
  let { before, after } = ((config, devServerAPI)=>{
7243
7293
  let setupMiddlewares = config.dev.setupMiddlewares || [], serverOptions = pick(devServerAPI, [
7244
7294
  'sockWrite',
@@ -7336,7 +7386,7 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
7336
7386
  }
7337
7387
  res.end('</body></html>');
7338
7388
  } catch (err) {
7339
- logger.error(err), res.writeHead(500), res.end('Failed to list the files');
7389
+ src_logger.error(err), res.writeHead(500), res.end('Failed to list the files');
7340
7390
  }
7341
7391
  })({
7342
7392
  environments: devServerAPI.environments
@@ -7375,7 +7425,7 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
7375
7425
  let filePath = external_node_path_.default.join(distPath, 'index.html');
7376
7426
  if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) {
7377
7427
  let newUrl = '/index.html';
7378
- 'verbose' === logger.level && logger.debug(` ${req.method} ${req.url} ${color.yellow('fallback to')} ${newUrl}`), req.url = newUrl, buildManager.assetsMiddleware(req, res, (...args)=>{
7428
+ isVerbose() && src_logger.debug(` ${req.method} ${req.url} ${color.yellow('fallback to')} ${newUrl}`), req.url = newUrl, buildManager.assetsMiddleware(req, res, (...args)=>{
7379
7429
  next(...args);
7380
7430
  });
7381
7431
  return;
@@ -7408,7 +7458,7 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
7408
7458
  context,
7409
7459
  postCallbacks
7410
7460
  })).middlewares))Array.isArray(item) ? middlewares.use(...item) : middlewares.use(item);
7411
- return buildManager?.watch(), logger.debug('create dev server done'), devServerAPI;
7461
+ return buildManager?.watch(), src_logger.debug('create dev server done'), devServerAPI;
7412
7462
  }
7413
7463
  let rspackProvider = ({ context, pluginManager, rsbuildOptions })=>{
7414
7464
  let createCompiler = async ()=>(await createCompiler_createCompiler({
@@ -7487,7 +7537,7 @@ class RsbuildProdServer {
7487
7537
  }
7488
7538
  async applyDefaultMiddlewares() {
7489
7539
  let { headers, proxy, historyApiFallback, compress, base, cors } = this.options.serverConfig;
7490
- if ('verbose' === logger.level && this.middlewares.use(getRequestLoggerMiddleware()), cors) {
7540
+ if (isVerbose() && this.middlewares.use(getRequestLoggerMiddleware()), cors) {
7491
7541
  let corsMiddleware = requireCompiledPackage('cors');
7492
7542
  this.middlewares.use(corsMiddleware('boolean' == typeof cors ? {} : cors));
7493
7543
  }
@@ -7590,7 +7640,7 @@ async function startProdServer(context, config, { getPortSilently } = {}) {
7590
7640
  customShortcuts: shortcutsOptions.custom
7591
7641
  });
7592
7642
  }
7593
- !getPortSilently && portTip && logger.info(portTip), resolve({
7643
+ !getPortSilently && portTip && src_logger.info(portTip), resolve({
7594
7644
  port,
7595
7645
  urls: urls.map((item)=>item.url),
7596
7646
  server: {
@@ -7605,7 +7655,7 @@ function applyDefaultPlugins(pluginManager, context) {
7605
7655
  {
7606
7656
  name: 'rsbuild:basic',
7607
7657
  setup (api) {
7608
- api.modifyBundlerChain((chain, { isDev, isProd, target, bundler, environment, CHAIN_ID })=>{
7658
+ api.modifyBundlerChain((chain, { isDev, target, bundler, environment, CHAIN_ID })=>{
7609
7659
  let { config } = environment;
7610
7660
  chain.name(environment.name), chain.context(api.context.rootPath), chain.mode(environment.config.mode), chain.infrastructureLogging({
7611
7661
  level: 'error'
@@ -7619,7 +7669,7 @@ function applyDefaultPlugins(pluginManager, context) {
7619
7669
  javascript: {
7620
7670
  typeReexportsPresence: 'tolerant'
7621
7671
  }
7622
- }), chain.optimization.inlineExports(isProd), chain.experiments({
7672
+ }), chain.experiments({
7623
7673
  ...chain.get('experiments'),
7624
7674
  rspackFuture: {
7625
7675
  bundlerInfo: {
@@ -7660,39 +7710,20 @@ function applyDefaultPlugins(pluginManager, context) {
7660
7710
  {
7661
7711
  name: 'rsbuild:source-map',
7662
7712
  setup (api) {
7663
- let DEFAULT_SOURCE_MAP_TEMPLATE = '[absolute-resource-path]', enableCssSourceMap = (config)=>{
7664
- let { sourceMap } = config.output;
7665
- return 'object' == typeof sourceMap && sourceMap.css;
7666
- };
7667
7713
  api.modifyBundlerChain((chain, { bundler, environment, isDev, target })=>{
7668
7714
  let { config } = environment, devtool = ((config)=>{
7669
7715
  let { sourceMap } = config.output, isProd = 'production' === config.mode;
7670
7716
  return !1 !== sourceMap && (!0 === sourceMap ? isProd ? 'source-map' : 'cheap-module-source-map' : void 0 === sourceMap.js ? !isProd && 'cheap-module-source-map' : sourceMap.js);
7671
7717
  })(config);
7672
- chain.devtool(devtool), isDev && 'web' === target ? chain.output.devtoolModuleFilenameTemplate((info)=>toPosixPath(info.absoluteResourcePath)) : chain.output.devtoolModuleFilenameTemplate(DEFAULT_SOURCE_MAP_TEMPLATE), !devtool && enableCssSourceMap(config) && chain.plugin('source-map-css').use(bundler.SourceMapDevToolPlugin, [
7718
+ chain.devtool(devtool), isDev && 'web' === target || 'webpack' === api.context.bundlerType ? chain.output.devtoolModuleFilenameTemplate((info)=>toPosixPath(info.absoluteResourcePath)) : chain.output.devtoolModuleFilenameTemplate('[relative-resource-path]'), !devtool && ((config)=>{
7719
+ let { sourceMap } = config.output;
7720
+ return 'object' == typeof sourceMap && sourceMap.css;
7721
+ })(config) && chain.plugin('source-map-css').use(bundler.SourceMapDevToolPlugin, [
7673
7722
  {
7674
7723
  test: /\.css$/,
7675
7724
  filename: '[file].map[query]'
7676
7725
  }
7677
7726
  ]);
7678
- }), api.processAssets({
7679
- stage: 'optimize-transfer'
7680
- }, ({ assets, compilation, sources, environment })=>{
7681
- if (!compilation.options.devtool && !enableCssSourceMap(environment.config) || compilation.outputOptions.devtoolModuleFilenameTemplate !== DEFAULT_SOURCE_MAP_TEMPLATE) return;
7682
- let { distPath } = environment;
7683
- for (let [filename, asset] of Object.entries(assets)){
7684
- let map;
7685
- if (!filename.endsWith('.map')) continue;
7686
- let rawSource = asset.source();
7687
- try {
7688
- map = JSON.parse(Buffer.isBuffer(rawSource) ? rawSource.toString() : rawSource);
7689
- } catch {
7690
- continue;
7691
- }
7692
- if (!Array.isArray(map.sources)) continue;
7693
- let mapDir = external_node_path_.default.dirname(external_node_path_.default.join(distPath, filename)), isSourcesUpdated = !1;
7694
- map.sources = map.sources.map((source)=>external_node_path_.default.isAbsolute(source) ? (isSourcesUpdated = !0, toPosixPath(external_node_path_.default.relative(mapDir, source))) : source), isSourcesUpdated && compilation.updateAsset(filename, new sources.RawSource(JSON.stringify(map)));
7695
- }
7696
7727
  });
7697
7728
  }
7698
7729
  },
@@ -7725,7 +7756,7 @@ function applyDefaultPlugins(pluginManager, context) {
7725
7756
  buildDependencies
7726
7757
  });
7727
7758
  }), api.onAfterCreateCompiler(()=>{
7728
- cacheEnabled && 'rspack' === api.context.bundlerType && logger.debug('Rspack persistent cache enabled');
7759
+ cacheEnabled && 'rspack' === api.context.bundlerType && src_logger.debug('Rspack persistent cache enabled');
7729
7760
  });
7730
7761
  }
7731
7762
  },
@@ -7807,7 +7838,7 @@ function applyDefaultPlugins(pluginManager, context) {
7807
7838
  chain,
7808
7839
  config,
7809
7840
  rootPath: api.context.rootPath
7810
- }), chain.module.rule(CHAIN_ID.RULE.MJS).test(/\.m?js/).resolve.set('fullySpecified', !1), config.source.aliasStrategy && logger.warn(`${color.dim('[rsbuild:config]')} The ${color.yellow('"source.aliasStrategy"')} config is deprecated, use ${color.yellow('"resolve.aliasStrategy"')} instead.`);
7841
+ }), chain.module.rule(CHAIN_ID.RULE.MJS).test(/\.m?js/).resolve.set('fullySpecified', !1), config.source.aliasStrategy && src_logger.warn(`${color.dim('[rsbuild:config]')} The ${color.yellow('"source.aliasStrategy"')} config is deprecated, use ${color.yellow('"resolve.aliasStrategy"')} instead.`);
7811
7842
  let aliasStrategy = config.source.aliasStrategy ?? config.resolve.aliasStrategy;
7812
7843
  tsconfigPath && 'rspack' === api.context.bundlerType && 'prefer-tsconfig' === aliasStrategy && chain.resolve.tsConfig({
7813
7844
  configFile: tsconfigPath,
@@ -7843,9 +7874,9 @@ function applyDefaultPlugins(pluginManager, context) {
7843
7874
  })(config), statsItem, api.context.rootPath, distPath, name, prevSnapshots);
7844
7875
  return snapshot && (nextSnapshots[name] = snapshot), sizeLogs.join('\n');
7845
7876
  })).catch((err)=>{
7846
- logger.warn('Failed to print file size.'), logger.warn(err);
7877
+ src_logger.warn('Failed to print file size.'), src_logger.warn(err);
7847
7878
  });
7848
- logs && logger.log(logs.join('\n')), showDiff && await saveSnapshots(snapshotPath, nextSnapshots);
7879
+ logs && src_logger.log(logs.join('\n')), showDiff && await saveSnapshots(snapshotPath, nextSnapshots);
7849
7880
  });
7850
7881
  }
7851
7882
  },
@@ -7859,7 +7890,7 @@ function applyDefaultPlugins(pluginManager, context) {
7859
7890
  return 'auto' === enable ? isDev && !config.dev.writeToDisk ? void 0 : isStrictSubdir(rootPath, distPath) ? {
7860
7891
  path: distPath,
7861
7892
  keep
7862
- } : (logger.warn('The dist path is not a subdir of root path, Rsbuild will not empty it.'), logger.warn(`Please set ${color.yellow('`output.cleanDistPath`')} config manually.`), logger.warn(`Current root path: ${color.dim(rootPath)}`), void logger.warn(`Current dist path: ${color.dim(distPath)}`)) : !0 === enable ? {
7893
+ } : (src_logger.warn('The dist path is not a subdir of root path, Rsbuild will not empty it.'), src_logger.warn(`Please set ${color.yellow('`output.cleanDistPath`')} config manually.`), src_logger.warn(`Current root path: ${color.dim(rootPath)}`), void src_logger.warn(`Current dist path: ${color.dim(distPath)}`)) : !0 === enable ? {
7863
7894
  path: distPath,
7864
7895
  keep
7865
7896
  } : void 0;
@@ -8159,16 +8190,35 @@ function applyDefaultPlugins(pluginManager, context) {
8159
8190
  ],
8160
8191
  raw: !0
8161
8192
  }, ({ code, emitFile, resourcePath })=>{
8162
- let name, name1 = (name = resourcePath && external_node_path_.default.parse(resourcePath).name) ? `${name}.node` : null;
8163
- if (null === name1) throw Error(`${color.dim('[rsbuild:node-addons]')} Failed to load Node.js addon: ${color.yellow(resourcePath)}`);
8164
- return emitFile(name1, code), `
8193
+ let name, filename = (name = resourcePath && external_node_path_.default.parse(resourcePath).name) ? `${name}.node` : null;
8194
+ if (null === filename) throw Error(`${color.dim('[rsbuild:node-addons]')} Failed to load Node.js addon: ${color.yellow(resourcePath)}`);
8195
+ emitFile(filename, code);
8196
+ let config = api.getNormalizedConfig(), handleErrorSnippet = `throw new Error('Failed to load Node.js addon: "${filename}"', {
8197
+ cause: error,
8198
+ });`;
8199
+ return config.output.module ? `
8200
+ import path from "node:path";
8201
+ import { createRequire } from "node:module";
8202
+ import { fileURLToPath } from "node:url";
8203
+
8204
+ const __filename = fileURLToPath(import.meta.url);
8205
+ const __dirname = path.dirname(__filename);
8206
+ const require = createRequire(import.meta.url);
8207
+
8208
+ let native;
8165
8209
  try {
8166
- const path = require("node:path");
8167
- process.dlopen(module, path.join(__dirname, "${name1}"));
8210
+ native = require(path.join(__dirname, "${filename}"));
8168
8211
  } catch (error) {
8169
- throw new Error('Failed to load Node.js addon: "${name1}"', {
8170
- cause: error,
8171
- });
8212
+ ${handleErrorSnippet}
8213
+ }
8214
+
8215
+ export default native;
8216
+ ` : `
8217
+ try {
8218
+ const path = __non_webpack_require__("node:path");
8219
+ module.exports = __non_webpack_require__(path.join(__dirname, "${filename}"));
8220
+ } catch (error) {
8221
+ ${handleErrorSnippet}
8172
8222
  }
8173
8223
  `;
8174
8224
  });
@@ -8459,7 +8509,7 @@ try {
8459
8509
  ...chain.output.get('library'),
8460
8510
  type: 'module'
8461
8511
  }), 'web-worker' === target) throw Error('[rsbuild:config] `output.module` is not supported for web-worker target.');
8462
- chain.output.module(!0).chunkFormat('module').chunkLoading('import').workerChunkLoading('import'), chain.experiments({
8512
+ chain.node.set('__dirname', !1).set('__filename', !1), chain.output.module(!0).chunkFormat('module').chunkLoading('import').workerChunkLoading('import'), chain.experiments({
8463
8513
  ...chain.get('experiments'),
8464
8514
  outputModule: !0
8465
8515
  });
@@ -8587,19 +8637,19 @@ try {
8587
8637
  ]
8588
8638
  });
8589
8639
  } catch {
8590
- logger.warn(`\`process.env.RSDOCTOR\` enabled, please install ${color.bold(color.yellow(packageName))} package.`);
8640
+ src_logger.warn(`\`process.env.RSDOCTOR\` enabled, please install ${color.bold(color.yellow(packageName))} package.`);
8591
8641
  return;
8592
8642
  }
8593
8643
  try {
8594
8644
  let moduleURL = isWindows ? (0, external_node_url_.pathToFileURL)(packagePath).href : packagePath;
8595
8645
  module = await import(moduleURL);
8596
8646
  } catch {
8597
- logger.error(`\`process.env.RSDOCTOR\` enabled, but failed to load ${color.bold(color.yellow(packageName))} module.`);
8647
+ src_logger.error(`\`process.env.RSDOCTOR\` enabled, but failed to load ${color.bold(color.yellow(packageName))} module.`);
8598
8648
  return;
8599
8649
  }
8600
8650
  if (module && module[pluginName]) {
8601
8651
  for (let config of bundlerConfigs)config.plugins ||= [], config.plugins.push(new module[pluginName]());
8602
- logger.info(`${color.bold(color.yellow(packageName))} enabled.`);
8652
+ src_logger.info(`${color.bold(color.yellow(packageName))} enabled.`);
8603
8653
  }
8604
8654
  });
8605
8655
  }
@@ -8798,7 +8848,7 @@ try {
8798
8848
  }), api.onAfterCreateCompiler(()=>{
8799
8849
  if (manifestFilenames.size <= 1) return void manifestFilenames.clear();
8800
8850
  let environmentNames = Array.from(manifestFilenames.keys()), filenames = Array.from(manifestFilenames.values());
8801
- new Set(filenames).size !== filenames.length && logger.warn(`${color.dim('[rsbuild:manifest]')} The ${color.yellow('"manifest.filename"')} option must be unique when there are multiple environments (${environmentNames.join(', ')}), otherwise the manifest file will be overwritten.`), manifestFilenames.clear();
8851
+ new Set(filenames).size !== filenames.length && src_logger.warn(`${color.dim('[rsbuild:manifest]')} The ${color.yellow('"manifest.filename"')} option must be unique when there are multiple environments (${environmentNames.join(', ')}), otherwise the manifest file will be overwritten.`), manifestFilenames.clear();
8802
8852
  });
8803
8853
  }
8804
8854
  },
@@ -8816,7 +8866,7 @@ try {
8816
8866
  api.onBeforeBuild(async ({ isFirstCompile })=>{
8817
8867
  isFirstCompile && await onStart();
8818
8868
  }), api.onBeforeStartDevServer(onStart), api.onExit(()=>{
8819
- traceOutput && (rspack_rspack.experiments.globalTrace.cleanup(), logger.info(`profile file saved to ${color.cyan(traceOutput)}`));
8869
+ traceOutput && (rspack_rspack.experiments.globalTrace.cleanup(), src_logger.info(`profile file saved to ${color.cyan(traceOutput)}`));
8820
8870
  });
8821
8871
  }
8822
8872
  },
@@ -8853,7 +8903,7 @@ try {
8853
8903
  let crossorigin = chain.output.get('crossOriginLoading');
8854
8904
  (!1 === crossorigin || void 0 === crossorigin) && chain.output.crossOriginLoading('anonymous');
8855
8905
  let { algorithm = 'sha384' } = sri;
8856
- chain.plugin(CHAIN_ID.PLUGIN.SUBRESOURCE_INTEGRITY).use(rspack.experiments.SubresourceIntegrityPlugin, [
8906
+ chain.plugin(CHAIN_ID.PLUGIN.SUBRESOURCE_INTEGRITY).use(rspack.SubresourceIntegrityPlugin, [
8857
8907
  {
8858
8908
  enabled: !0,
8859
8909
  hashFuncNames: helpers_castArray(algorithm),
@@ -8916,7 +8966,7 @@ async function createRsbuild(options = {}) {
8916
8966
  cwd: options.cwd,
8917
8967
  ...'boolean' == typeof options.loadEnv ? {} : options.loadEnv
8918
8968
  }) : null, configOrFactory = options.config ?? options.rsbuildConfig, config = isFunction(configOrFactory) ? await configOrFactory() : configOrFactory || {};
8919
- config.logLevel && !isDebug() && (logger.level = config.logLevel), applyEnvsToConfig(config, envs);
8969
+ config.logLevel && !isDebug() && (src_logger.level = config.logLevel), applyEnvsToConfig(config, envs);
8920
8970
  let resolvedOptions = {
8921
8971
  cwd: process.cwd(),
8922
8972
  callerName: 'rsbuild',
@@ -8928,7 +8978,7 @@ async function createRsbuild(options = {}) {
8928
8978
  });
8929
8979
  context.getPluginAPI = getPluginAPI;
8930
8980
  let globalPluginAPI = getPluginAPI();
8931
- logger.debug('registering default plugins'), applyDefaultPlugins(pluginManager, context), logger.debug('default plugins registered');
8981
+ src_logger.debug('registering default plugins'), applyDefaultPlugins(pluginManager, context), src_logger.debug('default plugins registered');
8932
8982
  let provider = config.provider || rspackProvider, providerInstance = await provider({
8933
8983
  context,
8934
8984
  pluginManager,
@@ -9024,7 +9074,7 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
9024
9074
  if (customConfig) {
9025
9075
  let customConfigPath = (0, external_node_path_.isAbsolute)(customConfig) ? customConfig : (0, external_node_path_.join)(root, customConfig);
9026
9076
  if (node_fs.existsSync(customConfigPath)) return customConfigPath;
9027
- logger.warn(`Cannot find config file: ${color.dim(customConfigPath)}\n`);
9077
+ throw Error(`${color.dim('[rsbuild:loadConfig]')} Cannot find config file: ${color.dim(customConfigPath)}`);
9028
9078
  }
9029
9079
  for (let file of [
9030
9080
  'rsbuild.config.mjs',
@@ -9039,7 +9089,7 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
9039
9089
  }
9040
9090
  return null;
9041
9091
  })(cwd, path);
9042
- if (!configFilePath) return logger.debug('no config file found.'), {
9092
+ if (!configFilePath) return src_logger.debug('no config file found.'), {
9043
9093
  content: {},
9044
9094
  filePath: configFilePath
9045
9095
  };
@@ -9051,8 +9101,8 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
9051
9101
  configExport = exportModule.default ? exportModule.default : exportModule;
9052
9102
  } catch (err) {
9053
9103
  let errorMessage = `Failed to load file with native loader: ${color.dim(configFilePath)}`;
9054
- if ('native' === loader) throw logger.error(errorMessage), err;
9055
- logger.debug(`${errorMessage}, fallback to jiti.`), logger.debug(err);
9104
+ if ('native' === loader) throw src_logger.error(errorMessage), err;
9105
+ src_logger.debug(`${errorMessage}, fallback to jiti.`), src_logger.debug(err);
9056
9106
  }
9057
9107
  if (void 0 === configExport) try {
9058
9108
  let { createJiti } = await import("jiti"), jiti = createJiti(constants_filename, {
@@ -9067,7 +9117,7 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
9067
9117
  default: !0
9068
9118
  });
9069
9119
  } catch (err) {
9070
- throw logger.error(`Failed to load file with jiti: ${color.dim(configFilePath)}`), err;
9120
+ throw src_logger.error(`Failed to load file with jiti: ${color.dim(configFilePath)}`), err;
9071
9121
  }
9072
9122
  if ('function' == typeof configExport) {
9073
9123
  let command = process.argv[2], nodeEnv = process.env.NODE_ENV || '', result = await configExport({
@@ -9083,7 +9133,7 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
9083
9133
  };
9084
9134
  }
9085
9135
  if (!isObject(configExport)) throw Error(`${color.dim('[rsbuild:loadConfig]')} The config must be an object or a function that returns an object, get ${color.yellow(configExport)}`);
9086
- return logger.debug('configuration loaded from:', configFilePath), {
9136
+ return src_logger.debug('configuration loaded from:', configFilePath), {
9087
9137
  content: applyMetaInfo(configExport),
9088
9138
  filePath: configFilePath
9089
9139
  };
@@ -9136,7 +9186,7 @@ async function init_init({ cliOptions, isRestart, isBuildWatch = !1 }) {
9136
9186
  });
9137
9187
  }), rsbuild;
9138
9188
  } catch (err) {
9139
- if (isRestart) logger.error(err);
9189
+ if (isRestart) src_logger.error(err);
9140
9190
  else throw err;
9141
9191
  }
9142
9192
  }
@@ -9145,8 +9195,8 @@ let cleaners = [], onBeforeRestartServer = (cleaner)=>{
9145
9195
  }, beforeRestart = async ({ filePath, clear = !0, id })=>{
9146
9196
  if (clear && isTTY() && !process.env.DEBUG && process.stdout.write('\x1B[H\x1B[2J'), filePath) {
9147
9197
  let filename = external_node_path_.default.basename(filePath);
9148
- logger.info(`restarting ${id} as ${color.yellow(filename)} changed\n`);
9149
- } else logger.info(`restarting ${id}...\n`);
9198
+ src_logger.info(`restarting ${id} as ${color.yellow(filename)} changed\n`);
9199
+ } else src_logger.info(`restarting ${id}...\n`);
9150
9200
  for (let cleaner of cleaners)await cleaner();
9151
9201
  cleaners = [];
9152
9202
  }, restartDevServer = async ({ filePath, clear = !0 } = {})=>{
@@ -9184,7 +9234,7 @@ async function watchFilesForRestart({ files, rsbuild, isBuildWatch, watchOptions
9184
9234
  filePath
9185
9235
  }) : await restartDevServer({
9186
9236
  filePath
9187
- })) ? await watcher.close() : logger.error(isBuildWatch ? 'Restart build failed.' : 'Restart server failed.'), restarting = !1);
9237
+ })) ? await watcher.close() : src_logger.error(isBuildWatch ? 'Restart build failed.' : 'Restart server failed.'), restarting = !1);
9188
9238
  };
9189
9239
  watcher.on('add', onChange), watcher.on('change', onChange), watcher.on('unlink', onChange);
9190
9240
  }
@@ -9193,7 +9243,7 @@ let applyServerOptions = (command)=>{
9193
9243
  };
9194
9244
  function setupCommands() {
9195
9245
  let cli = ((name = "")=>new CAC(name))('rsbuild');
9196
- cli.version("1.7.0-beta.0"), 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)', {
9246
+ cli.version("1.7.0-beta.2"), 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)', {
9197
9247
  default: 'auto'
9198
9248
  }).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', {
9199
9249
  type: [
@@ -9209,7 +9259,7 @@ function setupCommands() {
9209
9259
  });
9210
9260
  await rsbuild?.startDevServer();
9211
9261
  } catch (err) {
9212
- logger.error('Failed to start dev server.'), logger.error(err), process.exit(1);
9262
+ src_logger.error('Failed to start dev server.'), src_logger.error(err), process.exit(1);
9213
9263
  }
9214
9264
  }), buildCommand.option('-w, --watch', 'Enable watch mode to automatically rebuild on file changes').action(async (options)=>{
9215
9265
  try {
@@ -9222,7 +9272,7 @@ function setupCommands() {
9222
9272
  });
9223
9273
  buildInstance && (options.watch ? onBeforeRestartServer(buildInstance.close) : await buildInstance.close());
9224
9274
  } catch (err) {
9225
- err instanceof Error && err.message === RSPACK_BUILD_ERROR || logger.error('Failed to build.'), logger.error(err), process.exit(1);
9275
+ err instanceof Error && err.message === RSPACK_BUILD_ERROR || src_logger.error('Failed to build.'), src_logger.error(err), process.exit(1);
9226
9276
  }
9227
9277
  }), previewCommand.action(async (options)=>{
9228
9278
  try {
@@ -9231,7 +9281,7 @@ function setupCommands() {
9231
9281
  });
9232
9282
  await rsbuild?.preview();
9233
9283
  } catch (err) {
9234
- logger.error('Failed to start preview server.'), logger.error(err), process.exit(1);
9284
+ src_logger.error('Failed to start preview server.'), src_logger.error(err), process.exit(1);
9235
9285
  }
9236
9286
  }), inspectCommand.option('--output <output>', 'Set the output path for inspection results').option('--verbose', 'Show complete function definitions in output').action(async (options)=>{
9237
9287
  try {
@@ -9244,7 +9294,7 @@ function setupCommands() {
9244
9294
  writeToDisk: !0
9245
9295
  });
9246
9296
  } catch (err) {
9247
- logger.error('Failed to inspect config.'), logger.error(err), process.exit(1);
9297
+ src_logger.error('Failed to inspect config.'), src_logger.error(err), process.exit(1);
9248
9298
  }
9249
9299
  }), cli.help((sections)=>{
9250
9300
  for (let section of (sections.shift(), sections))'Usage' === section.title && (section.body = section.body.replace('$ rsbuild', color.yellow("$ rsbuild [command] [options]"))), 'Commands' === section.title && (section.body = section.body.replace(` ${devDescription}`, `dev ${devDescription}`)), section.title?.startsWith('For more info') ? (section.title = color.dim(' For details on a sub-command, run'), section.body = color.dim(' $ rsbuild <command> -h')) : section.title = color.cyan(section.title);
@@ -9262,7 +9312,7 @@ function initNodeEnv() {
9262
9312
  }
9263
9313
  function showGreeting() {
9264
9314
  let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
9265
- logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v1.7.0-beta.0\n`);
9315
+ src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v1.7.0-beta.2\n`);
9266
9316
  }
9267
9317
  function setupLogLevel() {
9268
9318
  let logLevelIndex = process.argv.findIndex((item)=>'--log-level' === item || '--logLevel' === item);
@@ -9272,7 +9322,7 @@ function setupLogLevel() {
9272
9322
  'warn',
9273
9323
  'error',
9274
9324
  'silent'
9275
- ].includes(level) && !isDebug() && (logger.level = level);
9325
+ ].includes(level) && !isDebug() && (src_logger.level = level);
9276
9326
  }
9277
9327
  }
9278
9328
  function runCLI() {
@@ -9280,12 +9330,8 @@ function runCLI() {
9280
9330
  try {
9281
9331
  setupCommands();
9282
9332
  } catch (err) {
9283
- logger.error('Failed to start Rsbuild CLI.'), logger.error(err);
9333
+ src_logger.error('Failed to start Rsbuild CLI.'), src_logger.error(err);
9284
9334
  }
9285
9335
  }
9286
- let src_version = "1.7.0-beta.0";
9287
- import * as __rspack_external_node_module_ab9f2194 from "node:module";
9288
- import { createRequire as __rspack_createRequire } from "node:module";
9289
- import * as __rspack_external_node_url_e96de089 from "node:url";
9290
- import { fileURLToPath as __rspack_fileURLToPath } from "node:url";
9291
- export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, external_node_util_promisify, loadConfig_loadConfig as loadConfig, loadEnv, logger, mergeRsbuildConfig, node_fs, node_os, node_process, rspack_rspack as rspack, runCLI, src_version as version };
9336
+ let src_version = "1.7.0-beta.2";
9337
+ export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, external_node_util_promisify, loadConfig_loadConfig as loadConfig, loadEnv, mergeRsbuildConfig, node_fs, node_os, node_process, rspack_rspack as rspack, runCLI, src_logger as logger, src_version as version };