@rsbuild/core 2.2.9 → 2.2.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/m.js CHANGED
@@ -3,7 +3,7 @@ let runtimeProcessArgs, runtimeInfo, swcHelpersPath, pluginHelper_htmlPlugin;
3
3
  import { rspackRequire, moduleFactories, compatGetDefaultExport, createFakeNamespaceObject } from "./rslib-runtime.js";
4
4
  import { rspack as core_rspack } from "@rspack/core";
5
5
  import node_util, { promisify, stripVTControlCharacters } from "node:util";
6
- import node_path, { dirname as external_node_path_dirname, isAbsolute as external_node_path_isAbsolute, join, posix, relative, resolve as external_node_path_resolve, sep, win32 } from "node:path";
6
+ import node_path, { dirname, isAbsolute as external_node_path_isAbsolute, join, posix, relative, resolve as external_node_path_resolve, sep } from "node:path";
7
7
  import { builtinModules, createRequire, createRequire as __rspack_createRequire } from "node:module";
8
8
  import node_fs, { existsSync } from "node:fs";
9
9
  import node_os, { constants } from "node:os";
@@ -13,7 +13,8 @@ import { isPromise, isRegExp } from "node:util/types";
13
13
  import { readFile } from "node:fs/promises";
14
14
  import node_zlib, { constants as external_node_zlib_constants } from "node:zlib";
15
15
  import { once } from "node:events";
16
- import { cachedImport, getTinyglobby } from "./r.js";
16
+ import { ALL_INTERFACES_IPV4, IMAGE_EXTENSIONS, ASSETS_DIST_DIR, FONT_DIST_DIR, AUDIO_EXTENSIONS, ensureAbsolutePath, NODE_MODULES_REGEX, FONT_EXTENSIONS, HMR_SOCKET_PATH, WASM_DIST_DIR, VIDEO_EXTENSIONS, BROWSER_LOG_PREFIX, toPosixPath, TRACK_EXTENSIONS, IMAGE_DIST_DIR, RSBUILD_OUTPUTS_PATH, DEFAULT_STACK_TRACE, LOADER_PATH, ASSET_EXTENSIONS, SVG_DIST_DIR, isWindows, COMPILED_PATH, WORKER_QUERY_REGEX, TS_CONFIG_FILE, dedupeNestedPaths, CSS_REGEX, relativeWithin, LAZY_COMPILATION_IDENTIFIER, DEFAULT_BROWSERSLIST, JS_REGEX, MEDIA_DIST_DIR, SCRIPT_REGEX, DEFAULT_WEB_BROWSERSLIST, getCompiledPath, normalizeRuleConditionPath, getPathnameFromUrl, toRelativePath, isDeno, CSS_DIST_DIR, INLINE_QUERY_REGEX, STATIC_PATH, RAW_QUERY_REGEX, PLUGIN_SWC_NAME, CLIENT_PATH, getCommonParentPath, LOCALHOST, JS_DIST_DIR, URL_QUERY_REGEX } from "./1.js";
17
+ import { cachedImport as cachedImport_cachedImport, getTinyglobby } from "./r.js";
17
18
  var superClass, superClass1, __rspack_import_meta_filename__ = __rspack_fileURLToPath(import.meta.url);
18
19
  let __rspack_createRequire_require = __rspack_createRequire(import.meta.url);
19
20
  moduleFactories.add({
@@ -1033,62 +1034,7 @@ var Command = class {
1033
1034
  arg.variadic ? actionArgs.push(args.slice(index)) : actionArgs.push(args[index]);
1034
1035
  }), actionArgs.push(options), command.commandAction.apply(this, actionArgs);
1035
1036
  }
1036
- };
1037
- let isDeno = "u" > typeof Deno, isWindows = 'win32' === process.platform, dirname = import.meta.dirname, STATIC_PATH = join(dirname, '../static'), CLIENT_PATH = join(dirname, 'client'), COMPILED_PATH = join(dirname, '../compiled'), RSBUILD_OUTPUTS_PATH = '.rsbuild', LOCALHOST = 'localhost', ALL_INTERFACES_IPV4 = '0.0.0.0', DEFAULT_STACK_TRACE = 'summary', DEFAULT_WEB_BROWSERSLIST = [
1038
- 'chrome >= 107',
1039
- 'edge >= 107',
1040
- 'firefox >= 104',
1041
- 'safari >= 16'
1042
- ], DEFAULT_BROWSERSLIST = {
1043
- web: DEFAULT_WEB_BROWSERSLIST,
1044
- 'web-worker': DEFAULT_WEB_BROWSERSLIST,
1045
- node: [
1046
- 'node >= 20'
1047
- ]
1048
- }, JS_REGEX = /\.(?:js|mjs|cjs|jsx)$/, SCRIPT_REGEX = /\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts)$/, CSS_REGEX = /\.css$/, RAW_QUERY_REGEX = /[?&]raw(?:&|=|$)/, INLINE_QUERY_REGEX = /[?&]inline(?:&|=|$)/, URL_QUERY_REGEX = /[?&]url(?:&|=|$)/, WORKER_QUERY_REGEX = /[?&]worker(?:&|=|$)/, NODE_MODULES_REGEX = /[\\/]node_modules[\\/]/, PLUGIN_SWC_NAME = 'rsbuild:swc', PLUGIN_CSS_NAME = 'rsbuild:css', FONT_EXTENSIONS = [
1049
- 'woff',
1050
- 'woff2',
1051
- 'eot',
1052
- 'ttf',
1053
- 'otf',
1054
- 'ttc'
1055
- ], ASSET_EXTENSIONS = [
1056
- 'webmanifest',
1057
- 'pdf',
1058
- 'txt'
1059
- ], IMAGE_EXTENSIONS = [
1060
- 'png',
1061
- 'jpg',
1062
- 'jpeg',
1063
- 'pjpeg',
1064
- 'pjp',
1065
- 'gif',
1066
- 'bmp',
1067
- 'webp',
1068
- 'ico',
1069
- 'apng',
1070
- 'avif',
1071
- 'tif',
1072
- 'tiff',
1073
- 'jfif',
1074
- 'cur',
1075
- 'jxl'
1076
- ], VIDEO_EXTENSIONS = [
1077
- 'mp4',
1078
- 'webm',
1079
- 'ogg',
1080
- 'mov'
1081
- ], AUDIO_EXTENSIONS = [
1082
- 'mp3',
1083
- 'wav',
1084
- 'flac',
1085
- 'aac',
1086
- 'm4a',
1087
- 'opus'
1088
- ], TRACK_EXTENSIONS = [
1089
- 'vtt'
1090
- ], LAZY_COMPILATION_IDENTIFIER = 'lazy-compilation-proxy';
1091
- var __webpack_modules__ = {}, __webpack_module_cache__ = {};
1037
+ }, __webpack_modules__ = {}, __webpack_module_cache__ = {};
1092
1038
  function dist_webpack_require_(moduleId) {
1093
1039
  var cachedModule = __webpack_module_cache__[moduleId];
1094
1040
  if (void 0 !== cachedModule) return cachedModule.exports;
@@ -2144,7 +2090,7 @@ let vendors_require = createRequire(import.meta.url);
2144
2090
  var cjs_0_default = compatGetDefaultExport(rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/deepmerge/4.3.1/56471899410038644780b3527c5076e78d3f57091a0da3ac0daf6d994929353d/node_modules/deepmerge/dist/cjs.js"));
2145
2091
  let setNodeEnv = (env)=>{
2146
2092
  process.env.NODE_ENV = env;
2147
- }, isFunction = (func)=>'function' == typeof func, isObject = (obj)=>'[object Object]' === Object.prototype.toString.call(obj), objectPrototype = Object.prototype, helpers_getProto = Object.getPrototypeOf, isPlainObject = (obj)=>null !== obj && 'object' == typeof obj && helpers_getProto(obj) === objectPrototype, helpers_castArray = (arr)=>void 0 === arr ? [] : Array.isArray(arr) ? arr : [
2093
+ }, isCI = ()=>!!process.env.CI && 'false' !== process.env.CI, isFunction = (func)=>'function' == typeof func, isObject = (obj)=>'[object Object]' === Object.prototype.toString.call(obj), objectPrototype = Object.prototype, helpers_getProto = Object.getPrototypeOf, isPlainObject = (obj)=>null !== obj && 'object' == typeof obj && helpers_getProto(obj) === objectPrototype, helpers_castArray = (arr)=>void 0 === arr ? [] : Array.isArray(arr) ? arr : [
2148
2094
  arr
2149
2095
  ], cloneDeep = (value)=>null == value ? value : cjs_0_default()({}, value, {
2150
2096
  isMergeableObject: isPlainObject
@@ -2202,7 +2148,7 @@ function pick(obj, keys) {
2202
2148
  for (let key of keys)void 0 !== obj[key] && (result[key] = obj[key]);
2203
2149
  return result;
2204
2150
  }
2205
- let isTTY = (type = 'stdout')=>('stdin' === type ? process.stdin.isTTY : process.stdout.isTTY) && !process.env.CI, getCrypto = cachedImport(()=>import("node:crypto"));
2151
+ let isTTY = (type = 'stdout')=>('stdin' === type ? process.stdin.isTTY : process.stdout.isTTY) && !isCI(), getCrypto = cachedImport_cachedImport(()=>import("node:crypto"));
2206
2152
  async function helpers_hash(data) {
2207
2153
  let crypto = await getCrypto();
2208
2154
  return crypto.hash ? crypto.hash('sha256', data, 'hex').slice(0, 16) : crypto.createHash('sha256').update(data).digest('hex').slice(0, 16);
@@ -2413,12 +2359,12 @@ function createEnvironmentAsyncHook() {
2413
2359
  return params;
2414
2360
  },
2415
2361
  callBatch: async ({ environment, args: params })=>{
2416
- let results = [];
2417
- for (let callback of [
2362
+ let callbacks = [
2418
2363
  ...preGroup,
2419
2364
  ...defaultGroup,
2420
2365
  ...postGroup
2421
- ]){
2366
+ ], results = [];
2367
+ for (let callback of callbacks){
2422
2368
  if (environment && callback.environment && callback.environment !== environment) continue;
2423
2369
  let result = await callback.handler(...params);
2424
2370
  results.push(result);
@@ -2445,12 +2391,12 @@ function createAsyncHook() {
2445
2391
  return params;
2446
2392
  },
2447
2393
  callBatch: async (...params)=>{
2448
- let results = [];
2449
- for (let callback of [
2394
+ let callbacks = [
2450
2395
  ...preGroup,
2451
2396
  ...defaultGroup,
2452
2397
  ...postGroup
2453
- ]){
2398
+ ], results = [];
2399
+ for (let callback of callbacks){
2454
2400
  let result = await callback(...params);
2455
2401
  results.push(result);
2456
2402
  }
@@ -2509,9 +2455,14 @@ let onBeforeCompile = ({ compiler, beforeCompile, beforeEnvironmentCompile, isWa
2509
2455
  !compilerDone && (compilerDone = !0, doneCompilers++), compilerStats[compilerIndex] = stats;
2510
2456
  let lastCompilerDone = doneCompilers === compilers.length;
2511
2457
  await onEnvironmentDone(index, stats), lastCompilerDone && await onDone(new MultiStatsCtor(compilerStats));
2512
- }), compiler.hooks.invalid.tap('rsbuild:done', ()=>{
2513
- compilerDone && (compilerDone = !1, doneCompilers--);
2514
2458
  });
2459
+ let resetDoneState = ()=>{
2460
+ compilerDone && (compilerDone = !1, doneCompilers--);
2461
+ };
2462
+ compiler.hooks.invalid.tap('rsbuild:done', resetDoneState), compiler.hooks.watchRun.tap({
2463
+ name: 'rsbuild:done',
2464
+ stage: -1 / 0
2465
+ }, resetDoneState);
2515
2466
  }
2516
2467
  } else compiler.hooks.done.tapPromise('rsbuild:done', async (stats)=>{
2517
2468
  await onEnvironmentDone(0, stats), await onDone(stats);
@@ -2619,30 +2570,7 @@ function loadConfig(opts) {
2619
2570
  return pickEnv(config, opts);
2620
2571
  }
2621
2572
  }
2622
- function toRelativePath(base, filepath) {
2623
- let relativePath = relative(base, filepath);
2624
- return '' === relativePath ? `.${sep}` : relativePath.startsWith('.') ? relativePath : `.${sep}${relativePath}`;
2625
- }
2626
- function getCommonParentPath(paths) {
2627
- let uniquePaths = [
2628
- ...new Set(paths)
2629
- ];
2630
- if (1 === uniquePaths.length) return uniquePaths[0];
2631
- let [first, ...rest] = uniquePaths.map((p)=>p.split(sep)), common = [];
2632
- for(let i = 0; i < first.length; i++){
2633
- let segment = first[i];
2634
- if (rest.every((p)=>p[i] === segment)) common.push(segment);
2635
- else break;
2636
- }
2637
- return common.join(sep);
2638
- }
2639
- let ensureAbsolutePath = (base, filePath)=>external_node_path_isAbsolute(filePath) ? filePath : join(base, filePath), getPathnameFromUrl = (url)=>{
2640
- try {
2641
- return url ? new URL(url, 'http://localhost').pathname : url;
2642
- } catch {
2643
- return url;
2644
- }
2645
- }, dedupeNestedPaths = (paths)=>paths.sort((p1, p2)=>p2.length > p1.length ? -1 : 1).reduce((prev, curr)=>prev.some((p)=>curr.startsWith(p) || curr === p) ? prev : prev.concat(curr), []), toPosixPath = (filepath)=>'/' === sep ? filepath : filepath.replace(/\\/g, '/'), normalizeRuleConditionPath = (filepath)=>isWindows && 'string' == typeof filepath && filepath.includes('/') && win32.isAbsolute(filepath) ? filepath.replace(/\//g, '\\') : filepath, isFileSync = (filePath)=>{
2573
+ let isFileSync = (filePath)=>{
2646
2574
  try {
2647
2575
  return node_fs.statSync(filePath, {
2648
2576
  throwIfNoEntry: !1
@@ -2784,7 +2712,7 @@ let OVERRIDE_PATHS = new Set([
2784
2712
  writeToDisk: !1,
2785
2713
  cliShortcuts: !1,
2786
2714
  client: {
2787
- path: '/rsbuild-hmr',
2715
+ path: HMR_SOCKET_PATH,
2788
2716
  port: '',
2789
2717
  host: '',
2790
2718
  overlay: !0,
@@ -2821,7 +2749,7 @@ let OVERRIDE_PATHS = new Set([
2821
2749
  scriptLoading: 'defer',
2822
2750
  implementation: 'js'
2823
2751
  },
2824
- resolve: (swcHelpersPath || (swcHelpersPath = external_node_path_dirname(vendors_require.resolve('@swc/helpers/package.json'))), {
2752
+ resolve: (swcHelpersPath || (swcHelpersPath = dirname(vendors_require.resolve('@swc/helpers/package.json'))), {
2825
2753
  alias: {
2826
2754
  '@swc/helpers': swcHelpersPath
2827
2755
  },
@@ -2847,14 +2775,14 @@ let OVERRIDE_PATHS = new Set([
2847
2775
  cleanDistPath: 'auto',
2848
2776
  distPath: {
2849
2777
  root: "dist",
2850
- css: 'static/css',
2851
- svg: 'static/svg',
2852
- font: 'static/font',
2778
+ css: CSS_DIST_DIR,
2779
+ svg: SVG_DIST_DIR,
2780
+ font: FONT_DIST_DIR,
2853
2781
  html: "./",
2854
- wasm: 'static/wasm',
2855
- image: 'static/image',
2856
- media: 'static/media',
2857
- assets: 'static/assets',
2782
+ wasm: WASM_DIST_DIR,
2783
+ image: IMAGE_DIST_DIR,
2784
+ media: MEDIA_DIST_DIR,
2785
+ assets: ASSETS_DIST_DIR,
2858
2786
  favicon: "./"
2859
2787
  },
2860
2788
  assetPrefix: "/",
@@ -2930,7 +2858,7 @@ let withDefaultConfig = async (rootPath, userConfig)=>{
2930
2858
  imports: !0,
2931
2859
  entries: !1
2932
2860
  }), !config.source.tsconfigPath) {
2933
- let tsconfigPath = join(rootPath, 'tsconfig.json');
2861
+ let tsconfigPath = join(rootPath, TS_CONFIG_FILE);
2934
2862
  await isFileExists(tsconfigPath) && (config.source.tsconfigPath = tsconfigPath);
2935
2863
  }
2936
2864
  return config;
@@ -3201,7 +3129,7 @@ function initPluginAPI({ context, pluginManager }) {
3201
3129
  if (descriptor.targets && !descriptor.targets.includes(target) || descriptor.environments && !descriptor.environments.includes(environmentContext.name)) return;
3202
3130
  let rule = chain.module.rule(id);
3203
3131
  descriptor.test && rule.test(descriptor.test), descriptor.resourceQuery && rule.resourceQuery(descriptor.resourceQuery), descriptor.layer && rule.layer(descriptor.layer), descriptor.issuerLayer && rule.issuerLayer(descriptor.issuerLayer), descriptor.issuer && rule.issuer(descriptor.issuer), descriptor.with && rule.with(descriptor.with), descriptor.mimetype && rule.mimetype(descriptor.mimetype), descriptor.order && 'default' !== descriptor.order ? rule.enforce(descriptor.order) : descriptor.enforce && rule.enforce(descriptor.enforce);
3204
- let loaderPath = join(dirname, descriptor.raw ? 'transformRawLoader.mjs' : 'transformLoader.mjs');
3132
+ let loaderPath = join(LOADER_PATH, descriptor.raw ? 'transformRawLoader.mjs' : 'transformLoader.mjs');
3205
3133
  rule.use(id).loader(loaderPath).options({
3206
3134
  id,
3207
3135
  getEnvironment: ()=>environmentContext
@@ -3363,7 +3291,7 @@ function createPublicContext(context) {
3363
3291
  async function createContext(options, userConfig, logger, loadConfigResult) {
3364
3292
  let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = join(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, hooks = initHooks();
3365
3293
  return {
3366
- version: "2.2.9",
3294
+ version: "2.2.11",
3367
3295
  rootPath,
3368
3296
  configFile: loadConfigResult?.filePath ?? userConfig._privateMeta?.configFilePath,
3369
3297
  configFileDependencies: loadConfigResult?.dependencies ?? userConfig._privateMeta?.configFileDependencies ?? [],
@@ -3902,7 +3830,7 @@ async function initRsbuildConfig({ context, pluginManager }) {
3902
3830
  }, applyEnvironmentDefaultConfig = (config)=>{
3903
3831
  config.source.entry && 0 !== Object.keys(config.source.entry).length || (config.source.entry = (defaultEntry || (defaultEntry = getDefaultEntry(rootPath)), defaultEntry));
3904
3832
  let isServer = 'node' === config.output.target;
3905
- return void 0 === config.output.distPath.js && (config.output.distPath.js = isServer ? '' : 'static/js'), void 0 === config.output.module && (config.output.module = isServer), void 0 === config.output.minify && (config.output.minify = !isServer), config;
3833
+ return void 0 === config.output.distPath.js && (config.output.distPath.js = isServer ? '' : JS_DIST_DIR), void 0 === config.output.module && (config.output.module = isServer), void 0 === config.output.minify && (config.output.minify = !isServer), config;
3906
3834
  };
3907
3835
  if (environments && Object.keys(environments).length > 0) {
3908
3836
  let resolvedEnvironments = Object.fromEntries(Object.entries(environments).filter(([name])=>isEnvironmentEnabled(name)).map(([name, config])=>[
@@ -4047,9 +3975,9 @@ async function createCompiler_createCompiler(options) {
4047
3975
  if ('LazyCompilation' === name && 'string' == typeof log && log.startsWith(LAZY_COMPILATION_IDENTIFIER)) {
4048
3976
  let resource = log.split(' ')[0];
4049
3977
  if (!resource) return;
4050
- let { rootPath } = context, absolutePath = resource.split('!').pop();
4051
- if (absolutePath?.startsWith(rootPath)) {
4052
- let relativePath = absolutePath.replace(rootPath, '');
3978
+ let { rootPath } = context, rootPrefix = rootPath.endsWith(sep) ? rootPath : rootPath + sep, absolutePath = resource.split('!').pop();
3979
+ if (absolutePath?.startsWith(rootPrefix)) {
3980
+ let relativePath = absolutePath.slice(rootPrefix.length);
4053
3981
  lazyModules.add(relativePath);
4054
3982
  }
4055
3983
  }
@@ -4079,8 +4007,9 @@ async function createCompiler_createCompiler(options) {
4079
4007
  let digits = seconds >= 0.01 ? 2 : 3;
4080
4008
  return format(seconds.toFixed(digits), 's');
4081
4009
  }
4082
- if (seconds < 60) return format(seconds.toFixed(1), 's');
4083
- let minutesLabel = format(Math.floor(seconds / 60).toFixed(0), 'm'), remainingSeconds = seconds % 60;
4010
+ let roundedSeconds = Math.round(10 * seconds) / 10;
4011
+ if (roundedSeconds < 60) return format(roundedSeconds.toFixed(1), 's');
4012
+ let minutesLabel = format(Math.floor(roundedSeconds / 60).toFixed(0), 'm'), remainingSeconds = roundedSeconds % 60;
4084
4013
  if (0 === remainingSeconds) return minutesLabel;
4085
4014
  let secondsLabel = format(remainingSeconds.toFixed(+(remainingSeconds % 1 != 0)), 's');
4086
4015
  return `${minutesLabel} ${secondsLabel}`;
@@ -4167,7 +4096,7 @@ async function createCompiler_createCompiler(options) {
4167
4096
  rspackConfigs
4168
4097
  };
4169
4098
  }
4170
- let getChokidar = cachedImport(()=>import("./chokidar.js").then((m)=>m.chokidar_namespaceObject)), DEFAULT_WATCH_FILE_EVENTS = [
4099
+ let getChokidar = cachedImport_cachedImport(()=>import("./chokidar.js").then((m)=>m.chokidar_namespaceObject)), DEFAULT_WATCH_FILE_EVENTS = [
4171
4100
  'add',
4172
4101
  'change',
4173
4102
  'unlink'
@@ -4938,10 +4867,7 @@ async function getBuildDependencies(context, environmentContext, additionalDepen
4938
4867
  tailwindConfig
4939
4868
  ]), additionalDependencies && (buildDependencies.additional = additionalDependencies), buildDependencies;
4940
4869
  }
4941
- let addTrailingSep = (dir)=>dir.endsWith(sep) ? dir : dir + sep, isStrictSubdir = (parent, child)=>{
4942
- let parentDir = addTrailingSep(parent), childDir = addTrailingSep(child);
4943
- return parentDir !== childDir && childDir.startsWith(parentDir);
4944
- }, normalizeCleanDistPath = (userOptions)=>{
4870
+ let normalizeCleanDistPath = (userOptions)=>{
4945
4871
  let defaultOptions = {
4946
4872
  enable: 'auto'
4947
4873
  };
@@ -5045,7 +4971,7 @@ let getPostcssLoaderOptions = async ({ config, root, postcssrcCache })=>{
5045
4971
  let extraPlugins = [], userOptions = await loadUserPostcssrc(root, postcssrcCache);
5046
4972
  userOptions.plugins ||= [];
5047
4973
  let defaultOptions = {
5048
- implementation: join(COMPILED_PATH, 'postcss', 'index.js'),
4974
+ implementation: getCompiledPath('postcss'),
5049
4975
  postcssOptions: userOptions,
5050
4976
  sourceMap: getCSSSourceMap(config)
5051
4977
  }, finalOptions = await reduceConfigsWithContext({
@@ -5194,7 +5120,7 @@ function pluginExternals() {
5194
5120
  ] : autoExternalRules : externals;
5195
5121
  mergedExternals && chain.externals(mergedExternals);
5196
5122
  }), api.onBeforeCreateCompiler(({ bundlerConfigs })=>{
5197
- for (let config of bundlerConfigs)(Array.isArray(config.target) ? config.target.includes('webworker') : 'webworker' === config.target) && config.externals && delete config.externals;
5123
+ for (let config of bundlerConfigs)(Array.isArray(config.target) ? config.target.includes('webworker') : 'webworker' === config.target) && !config.output?.module && config.externals && delete config.externals;
5198
5124
  });
5199
5125
  }
5200
5126
  };
@@ -6074,7 +6000,7 @@ function doesChunkBelongToHtml({ chunk, htmlPluginData }) {
6074
6000
  let { options } = htmlPluginData.plugin;
6075
6001
  return recursiveChunkEntryNames(chunk).some((chunkName)=>isChunksFiltered(chunkName, options?.chunks, options?.excludeChunks));
6076
6002
  }
6077
- let getManifestPlugin = cachedImport(()=>import("./manifest-plugin.js").then(rspackRequire.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/rspack-manifest-plugin/5.2.2/5acfc0b855cb5cd205a81b2c264b6bdf3a41cbc273715b263f9fdb82cc7ae49c/node_modules/rspack-manifest-plugin/dist/index.js"))), isCSSPath = (filePath)=>filePath.endsWith('.css');
6003
+ let getManifestPlugin = cachedImport_cachedImport(()=>import("./manifest-plugin.js").then(rspackRequire.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/rspack-manifest-plugin/5.2.2/12a6328c2e9bf08e26b58fdf2ee8c0ecfe31cb73b1db951f7711492f8c9e3b25/node_modules/rspack-manifest-plugin/dist/index.js"))), isCSSPath = (filePath)=>filePath.endsWith('.css');
6078
6004
  function normalizeManifestObjectConfig(manifest) {
6079
6005
  let defaultOptions = {
6080
6006
  prefix: !0,
@@ -6138,7 +6064,7 @@ async function applyAlias({ chain, config, rootPath, logger }) {
6138
6064
  continue;
6139
6065
  }
6140
6066
  try {
6141
- pkgPath = external_node_path_dirname(vendors_require.resolve(`${pkgName}/package.json`, {
6067
+ pkgPath = dirname(vendors_require.resolve(`${pkgName}/package.json`, {
6142
6068
  paths: [
6143
6069
  rootPath
6144
6070
  ]
@@ -6154,7 +6080,7 @@ async function applyAlias({ chain, config, rootPath, logger }) {
6154
6080
  'node_modules',
6155
6081
  ...pkgName.split('/')
6156
6082
  ].join(sep);
6157
- for(; !pkgPath.endsWith(trailing) && pkgPath.includes('node_modules');)pkgPath = external_node_path_dirname(pkgPath);
6083
+ for(; !pkgPath.endsWith(trailing) && pkgPath.includes('node_modules');)pkgPath = dirname(pkgPath);
6158
6084
  } catch {
6159
6085
  logger.debug(`${color.dim('[rsbuild:resolve]')} The package ${color.yellow(pkgName)} is not resolved in the project, dedupe option for ${color.yellow(pkgName)} will be ignored.`);
6160
6086
  continue;
@@ -6760,7 +6686,7 @@ function destroyStream(stream, suppress) {
6760
6686
  'number' == typeof fd && this.close();
6761
6687
  }), 'function' == typeof stream.addListener && suppress && (stream.removeAllListeners('error'), stream.addListener('error', ()=>{}));
6762
6688
  }
6763
- let getRangeParser = cachedImport(()=>import("./range-parser.js").then(createFakeNamespaceObject.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/range-parser/1.3.0/d49e5dcb9d0e39475844e240fad8cd1db6a58f4144f7ede43d9755e2fce5babc/node_modules/range-parser/index.js", 23))), parseRangeHeaders = async (value)=>{
6689
+ let getRangeParser = cachedImport_cachedImport(()=>import("./range-parser.js").then(createFakeNamespaceObject.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/range-parser/1.3.0/d49e5dcb9d0e39475844e240fad8cd1db6a58f4144f7ede43d9755e2fce5babc/node_modules/range-parser/index.js", 23))), parseRangeHeaders = async (value)=>{
6764
6690
  let { default: rangeParser } = await getRangeParser(), [len, rangeHeader] = value.split('|');
6765
6691
  return rangeParser(Number(len), rangeHeader, {
6766
6692
  combine: !0
@@ -6882,8 +6808,9 @@ async function setupOutputFileSystem(writeToDisk, compilers) {
6882
6808
  function setupWriteToDisk(compilers, writeToDisk, logger) {
6883
6809
  for (let compiler of compilers)compiler.hooks.emit.tap('DevMiddleware', ()=>{
6884
6810
  compiler.__hasRsbuildAssetEmittedCallback || (compiler.hooks.assetEmitted.tapAsync('DevMiddleware', (_file, info, callback)=>{
6811
+ if (compiler.outputFileSystem === node_fs) return void callback();
6885
6812
  let { targetPath, content, compilation } = info;
6886
- if (!(!writeToDisk || 'function' != typeof writeToDisk || writeToDisk(targetPath, compilation.name))) return void callback();
6813
+ if (!('function' != typeof writeToDisk || writeToDisk(targetPath, compilation.name))) return void callback();
6887
6814
  let dir = node_path.dirname(targetPath), name = compiler.options.name ? `Child "${compiler.options.name}": ` : '';
6888
6815
  node_fs.mkdir(dir, {
6889
6816
  recursive: !0
@@ -7093,15 +7020,17 @@ function parseNode(line) {
7093
7020
  column: parts[4] ? +parts[4] : null
7094
7021
  } : null;
7095
7022
  }
7096
- let getTraceMapping = cachedImport(()=>import("./trace-mapping.js").then((m)=>m.trace_mapping_namespaceObject)), isValidMethodName = (methodName)=>'<unknown>' !== methodName && !/[\\/]/.test(methodName), isRspackRuntimeStack = (value)=>!!value && (value.includes('__webpack_require__') || value.startsWith('webpack/runtime/')), parseFrame = async (frame, fs, context, cachedTraceMap)=>{
7097
- let { file, column, lineNumber } = frame, sourceMapInfo = await getFileFromUrl(`${file}.map`, fs, context);
7098
- if (!sourceMapInfo || 'errorCode' in sourceMapInfo) return;
7099
- let { TraceMap, originalPositionFor } = await getTraceMapping(), sourceMapPath = sourceMapInfo.filename;
7023
+ let getTraceMapping = cachedImport_cachedImport(()=>import("./trace-mapping.js").then((m)=>m.trace_mapping_namespaceObject)), isValidMethodName = (methodName)=>'<unknown>' !== methodName && !/[\\/]/.test(methodName), isRspackRuntimeStack = (value)=>!!value && (value.includes('__webpack_require__') || value.startsWith('webpack/runtime/')), parseFrame = async (frame, fs, context, cache)=>{
7024
+ let { file, column, lineNumber } = frame, sourceMapUrl = `${file}.map`, sourceMapPathPromise = cache.sourceMapPaths.get(sourceMapUrl);
7025
+ sourceMapPathPromise || (sourceMapPathPromise = getFileFromUrl(sourceMapUrl, fs, context).then((info)=>!info || 'errorCode' in info ? void 0 : info.filename), cache.sourceMapPaths.set(sourceMapUrl, sourceMapPathPromise));
7026
+ let sourceMapPath = await sourceMapPathPromise;
7027
+ if (!sourceMapPath) return;
7028
+ let { TraceMap, originalPositionFor } = await getTraceMapping();
7100
7029
  try {
7101
- let tracer = cachedTraceMap.get(sourceMapPath);
7030
+ let tracer = cache.traceMaps.get(sourceMapPath);
7102
7031
  if (!tracer) {
7103
7032
  let sourceMap = await readFileAsync(fs, sourceMapPath);
7104
- tracer = new TraceMap(sourceMap.toString()), cachedTraceMap.set(sourceMapPath, tracer);
7033
+ tracer = new TraceMap(sourceMap.toString()), cache.traceMaps.set(sourceMapPath, tracer);
7105
7034
  }
7106
7035
  let originalPosition = originalPositionFor(tracer, {
7107
7036
  line: lineNumber ?? 0,
@@ -7114,10 +7043,10 @@ let getTraceMapping = cachedImport(()=>import("./trace-mapping.js").then((m)=>m.
7114
7043
  } catch (error) {
7115
7044
  error instanceof Error && context.logger.debug('failed to map source map position:', error);
7116
7045
  }
7117
- }, resolveOriginalLocation = async (stackFrames, fs, context, cachedTraceMap)=>{
7046
+ }, resolveOriginalLocation = async (stackFrames, fs, context, cache)=>{
7118
7047
  let frame = stackFrames.find((frame)=>null !== frame.file && null !== frame.column && null !== frame.lineNumber && SCRIPT_REGEX.test(frame.file));
7119
7048
  if (!frame) return;
7120
- let parsedFrame = await parseFrame(frame, fs, context, cachedTraceMap);
7049
+ let parsedFrame = await parseFrame(frame, fs, context, cache);
7121
7050
  if (!parsedFrame) return;
7122
7051
  let { sourceMapPath, originalPosition } = parsedFrame;
7123
7052
  return {
@@ -7136,10 +7065,10 @@ let getTraceMapping = cachedImport(()=>import("./trace-mapping.js").then((m)=>m.
7136
7065
  }, formatFrameLocation = (frame)=>{
7137
7066
  let { file, lineNumber, column } = frame;
7138
7067
  if (file) return null !== lineNumber ? null !== column ? `${file}:${lineNumber}:${column}` : `${file}:${lineNumber}` : file;
7139
- }, formatFullStack = async (stackFrames, context, fs, cachedTraceMap)=>{
7068
+ }, formatFullStack = async (stackFrames, context, fs, cache)=>{
7140
7069
  let formattedFrames = [];
7141
7070
  for (let frame of stackFrames){
7142
- let location, parsedFrame = await parseFrame(frame, fs, context, cachedTraceMap), { methodName } = frame, parts = [];
7071
+ let location, parsedFrame = await parseFrame(frame, fs, context, cache), { methodName } = frame, parts = [];
7143
7072
  isValidMethodName(methodName) && parts.push(methodName);
7144
7073
  let parsed = !1;
7145
7074
  if (parsedFrame) {
@@ -7162,13 +7091,13 @@ let getTraceMapping = cachedImport(()=>import("./trace-mapping.js").then((m)=>m.
7162
7091
  }
7163
7092
  let shouldFilterRspackRuntime = formattedFrames.some((frame)=>!frame.isRspackRuntime && frame.hasLocation);
7164
7093
  return formattedFrames.filter((frame)=>!(shouldFilterRspackRuntime && frame.isRspackRuntime)).map((frame)=>frame.text).join('');
7165
- }, formatBrowserErrorLog = async (message, context, fs, stackTrace, stackFrames, cachedTraceMap)=>{
7094
+ }, formatBrowserErrorLog = async (message, context, fs, stackTrace, stackFrames, cache)=>{
7166
7095
  var log;
7167
7096
  let log1 = color.red(message);
7168
7097
  if (stackFrames?.length) switch(stackTrace){
7169
7098
  case 'summary':
7170
7099
  {
7171
- let resolved = await resolveOriginalLocation(stackFrames, fs, context, cachedTraceMap);
7100
+ let resolved = await resolveOriginalLocation(stackFrames, fs, context, cache);
7172
7101
  if (!resolved) break;
7173
7102
  let { frame, location } = resolved, { methodName } = frame, suffix = '';
7174
7103
  isValidMethodName(methodName) && (suffix += ` at ${methodName}`), location && (suffix += ` (${location})`), log1 += suffix ? color.dim(suffix) : '';
@@ -7176,7 +7105,7 @@ let getTraceMapping = cachedImport(()=>import("./trace-mapping.js").then((m)=>m.
7176
7105
  }
7177
7106
  case 'full':
7178
7107
  {
7179
- let fullStack = await formatFullStack(stackFrames, context, fs, cachedTraceMap);
7108
+ let fullStack = await formatFullStack(stackFrames, context, fs, cache);
7180
7109
  fullStack && (log1 += fullStack);
7181
7110
  }
7182
7111
  }
@@ -7356,8 +7285,11 @@ class SocketServer {
7356
7285
  if (!environment) return;
7357
7286
  let { browserLogs, client } = environment.config.dev;
7358
7287
  if ('client-error' === payload.type && !context.buildState.hasErrors && browserLogs) {
7359
- let stackTrace = isObject(browserLogs) && browserLogs.stackTrace || DEFAULT_STACK_TRACE, outputFs = this.getOutputFileSystem(), stackFrames = payload.stack ? stack_trace_parser_esm_parse(payload.stack) : null, cachedTraceMap = new Map(), log = await formatBrowserErrorLog(payload.message, context, outputFs, stackTrace, stackFrames, cachedTraceMap);
7360
- if (this.reportedBrowserLogs.has(log) || (this.reportedBrowserLogs.add(log), this.context.logger.error(`${color.cyan('[browser]')} ${log}`)), ((overlay, payload)=>{
7288
+ let stackTrace = isObject(browserLogs) && browserLogs.stackTrace || DEFAULT_STACK_TRACE, outputFs = this.getOutputFileSystem(), stackFrames = payload.stack ? stack_trace_parser_esm_parse(payload.stack) : null, cache = {
7289
+ sourceMapPaths: new Map(),
7290
+ traceMaps: new Map()
7291
+ }, log = await formatBrowserErrorLog(payload.message, context, outputFs, stackTrace, stackFrames, cache);
7292
+ if (this.reportedBrowserLogs.has(log) || (this.reportedBrowserLogs.add(log), this.context.logger.error(`${color.cyan(BROWSER_LOG_PREFIX)} ${log}`)), ((overlay, payload)=>{
7361
7293
  if (!isRuntimeOverlayEnabled(overlay)) return !1;
7362
7294
  if ('object' == typeof overlay && 'function' == typeof overlay.runtime) {
7363
7295
  let error;
@@ -7365,7 +7297,7 @@ class SocketServer {
7365
7297
  }
7366
7298
  return !0;
7367
7299
  })(client.overlay, payload)) {
7368
- let resolvedLog = 'full' === stackTrace ? log : await formatBrowserErrorLog(payload.message, context, outputFs, 'full', stackFrames, cachedTraceMap);
7300
+ let resolvedLog = 'full' === stackTrace ? log : await formatBrowserErrorLog(payload.message, context, outputFs, 'full', stackFrames, cache);
7369
7301
  this.sendMessage({
7370
7302
  type: 'resolved-client-error',
7371
7303
  data: {
@@ -7476,7 +7408,7 @@ class BuildManager {
7476
7408
  this.compiler.close(()=>{
7477
7409
  resolve();
7478
7410
  });
7479
- });
7411
+ }), this.context.socketServer === this.socketServer && (this.context.socketServer = void 0);
7480
7412
  }
7481
7413
  readFileSync = (fileName)=>'readFileSync' in this.outputFileSystem ? this.outputFileSystem.readFileSync(fileName, 'utf-8') : node_fs.readFileSync(fileName, 'utf-8');
7482
7414
  async setupCompilationMiddleware() {
@@ -7490,7 +7422,7 @@ class BuildManager {
7490
7422
  this.assetsMiddleware = middleware;
7491
7423
  }
7492
7424
  }
7493
- let isCliShortcutsEnabled = (config)=>config.dev.cliShortcuts && isTTY('stdin');
7425
+ let activeInterfaces = 0, isCliShortcutsEnabled = (config)=>config.dev.cliShortcuts && isTTY('stdin');
7494
7426
  async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls, restartServer, customShortcuts, logger }) {
7495
7427
  let shortcuts = [
7496
7428
  {
@@ -7534,7 +7466,9 @@ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls,
7534
7466
  let { createInterface } = await import("node:readline"), rl = createInterface({
7535
7467
  input: process.stdin
7536
7468
  });
7537
- return rl.on('line', (input)=>{
7469
+ return activeInterfaces++, rl.once('close', ()=>{
7470
+ --activeInterfaces > 0 && process.stdin.resume();
7471
+ }), rl.on('line', (input)=>{
7538
7472
  if ('h' === (input = input.trim().toLowerCase())) {
7539
7473
  let message = `\n ${color.bold(color.blue('Shortcuts:'))}\n`;
7540
7474
  for (let shortcut of shortcuts)message += ` ${shortcut.description}\n`;
@@ -7557,7 +7491,11 @@ function gzipMiddleware_gzipMiddleware({ filter, level = node_zlib.constants.Z_B
7557
7491
  if (filter && !filter(req, res)) return void next();
7558
7492
  let accept = req.headers['accept-encoding'], encoding = 'string' == typeof accept && ENCODING_REGEX.test(accept);
7559
7493
  if ('HEAD' === req.method || !encoding) return void next();
7560
- let started = !1, on = res.on.bind(res), end = res.end.bind(res), write = res.write.bind(res), writeHead = res.writeHead.bind(res), listeners = [], start = ()=>{
7494
+ let started = !1, on = res.on.bind(res), end = res.end.bind(res), write = res.write.bind(res), writeHead = res.writeHead.bind(res), listeners = [];
7495
+ res.flush = ()=>{
7496
+ gzip?.flush(node_zlib.constants.Z_SYNC_FLUSH);
7497
+ };
7498
+ let start = ()=>{
7561
7499
  if (started) return;
7562
7500
  if (started = !0, ((res)=>{
7563
7501
  if (res.getHeader('Content-Encoding')) return !1;
@@ -7867,7 +7805,10 @@ let applyDefaultMiddlewares = async ({ config, buildManager, context, devServer,
7867
7805
  environments: devServer.environments,
7868
7806
  logger
7869
7807
  })), buildManager && (middlewares.use(buildManager.assetsMiddleware), upgradeEvents.push(buildManager.socketServer.upgrade), middlewares.use(function hotUpdateJsonFallbackMiddleware(req, res, next) {
7870
- req.url?.endsWith('.hot-update.json') && 'OPTIONS' !== req.method ? notFoundMiddleware(req, res, next) : next();
7808
+ let url = req.url;
7809
+ if (!url || 'OPTIONS' === req.method) return void next();
7810
+ let queryIndex = url.indexOf('?'), end = -1 === queryIndex ? url.length : queryIndex;
7811
+ url.endsWith('.hot-update.json', end) || url.endsWith('.hot-update.json.mjs', end) ? notFoundMiddleware(req, res, next) : next();
7871
7812
  })), buildManager && middlewares.use(getHtmlCompletionMiddleware({
7872
7813
  assetsMiddleware: buildManager.assetsMiddleware,
7873
7814
  distPaths: [
@@ -8065,7 +8006,7 @@ class CommonJsRunner extends BasicRunner {
8065
8006
  let dynamicImport = cachedDynamicImport ??= Function('specifier', 'return import(specifier)');
8066
8007
  return vm.compileFunction(content, args, {
8067
8008
  filename: file.path,
8068
- importModuleDynamically: async (specifier)=>await dynamicImport(specifier)
8009
+ importModuleDynamically: dynamicImport
8069
8010
  }).call(m.exports, ...argValues), this.postExecute(m, file), m.exports;
8070
8011
  };
8071
8012
  }
@@ -8190,17 +8131,15 @@ let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>{
8190
8131
  cleanupCallbacks.add(callback);
8191
8132
  }, removeCleanup = (callback)=>{
8192
8133
  cleanupCallbacks.delete(callback);
8193
- }, shutdownRefCount = 0, setupGracefulShutdown = ()=>{
8194
- shutdownRefCount++;
8195
- let onSigterm = ()=>{
8196
- handleTermination(constants.signals.SIGTERM + 128);
8197
- };
8198
- process.once('SIGTERM', onSigterm);
8199
- let isCI = 'true' === process.env.CI, onStdinEnd = ()=>{
8200
- handleTermination(0);
8201
- };
8202
- return isCI || process.stdin.on('end', onStdinEnd), ()=>{
8203
- !(--shutdownRefCount > 0) && (process.removeListener('SIGTERM', onSigterm), isCI || process.stdin.removeListener('end', onStdinEnd));
8134
+ }, shutdownRefCount = 0, onSigterm = ()=>{
8135
+ handleTermination(constants.signals.SIGTERM + 128);
8136
+ }, onStdinEnd = ()=>{
8137
+ handleTermination(0);
8138
+ }, setupGracefulShutdown = ()=>{
8139
+ 1 == ++shutdownRefCount && (process.once('SIGTERM', onSigterm), isCI() || process.stdin.on('end', onStdinEnd));
8140
+ let cleanedUp = !1;
8141
+ return ()=>{
8142
+ cleanedUp || (cleanedUp = !0, --shutdownRefCount > 0 || (process.removeListener('SIGTERM', onSigterm), process.stdin.removeListener('end', onStdinEnd)));
8204
8143
  };
8205
8144
  }, createHttpServer = async ({ serverConfig, middlewares })=>{
8206
8145
  if (serverConfig.https) {
@@ -8318,12 +8257,18 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8318
8257
  protocol,
8319
8258
  clearCache: !0,
8320
8259
  logger
8321
- }), state = {}, cleanupGracefulShutdown = middlewareMode ? null : setupGracefulShutdown(), closeServerResources = ()=>(closingPromise || (hotConnectCallbacks = void 0, unregisterRestart?.(), unregisterRestart = void 0, closingPromise = (async ()=>{
8260
+ }), state = {}, webSocketServers = new Set(), cleanupGracefulShutdown = middlewareMode ? null : setupGracefulShutdown(), closeServerResources = ()=>{
8261
+ if (closingPromise) return closingPromise;
8262
+ hotConnectCallbacks = void 0;
8263
+ let onUpgrade = state.devMiddlewares?.onUpgrade;
8264
+ if (onUpgrade && webSocketServers) for (let server of webSocketServers)server.removeListener('upgrade', onUpgrade);
8265
+ return webSocketServers = void 0, unregisterRestart?.(), unregisterRestart = void 0, closingPromise = (async ()=>{
8322
8266
  removeCleanup(closeServer), cleanupGracefulShutdown?.(), await context.hooks.onCloseDevServer.callBatch(), await Promise.all([
8323
8267
  state.devMiddlewares?.close(),
8324
8268
  state.fileWatcher?.close()
8325
8269
  ]);
8326
- })()), closingPromise), closeServer = async ()=>{
8270
+ })();
8271
+ }, closeServer = async ()=>{
8327
8272
  await state.restartWatcher?.close(), await closeServerResources();
8328
8273
  }, restartServer = async ()=>{
8329
8274
  let restarted = await requestRestart({
@@ -8410,7 +8355,9 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8410
8355
  return httpServer.listen({
8411
8356
  host,
8412
8357
  port
8413
- }), await once(httpServer, 'listening'), middlewares.use(optionsFallbackMiddleware), middlewares.use(notFoundMiddleware), state.devMiddlewares && httpServer.on('upgrade', state.devMiddlewares.onUpgrade), logger.debug('listen dev server done'), await devServer.afterListen(), {
8358
+ }), await once(httpServer, 'listening'), middlewares.use(optionsFallbackMiddleware), middlewares.use(notFoundMiddleware), devServer.connectWebSocket({
8359
+ server: httpServer
8360
+ }), logger.debug('listen dev server done'), await devServer.afterListen(), {
8414
8361
  port,
8415
8362
  urls: urls.map((item)=>item.url),
8416
8363
  server: devServer
@@ -8432,7 +8379,7 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8432
8379
  });
8433
8380
  },
8434
8381
  connectWebSocket: ({ server })=>{
8435
- state.devMiddlewares && server.on('upgrade', state.devMiddlewares.onUpgrade);
8382
+ state.devMiddlewares && webSocketServers && !webSocketServers.has(server) && (server.on('upgrade', state.devMiddlewares.onUpgrade), webSocketServers.add(server));
8436
8383
  },
8437
8384
  close: closeServer,
8438
8385
  printUrls,
@@ -8465,7 +8412,7 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8465
8412
  }), logger.debug('create dev server done'), devServer;
8466
8413
  }
8467
8414
  async function startPreviewServer(context, config, { getPortSilently } = {}) {
8468
- let { logger } = context, { connect } = await import("./connect-next.js"), middlewares = connect(), { port, portTip } = await resolvePort(config), serverConfig = config.server, { host, headers, proxy, historyApiFallback, compress, base, cors } = serverConfig, assetPrefixes = context.environmentList.map((environment)=>environment.config.output.assetPrefix);
8415
+ let cleanupCliShortcuts, { logger } = context, { connect } = await import("./connect-next.js"), middlewares = connect(), { port, portTip } = await resolvePort(config), serverConfig = config.server, { host, headers, proxy, historyApiFallback, compress, base, cors } = serverConfig, assetPrefixes = context.environmentList.map((environment)=>environment.config.output.assetPrefix);
8469
8416
  context.publicPathnames = getPublicPathnames(assetPrefixes, base);
8470
8417
  let protocol = serverConfig.https ? 'https' : 'http', routes = getRoutes(context), urls = await getAddressUrls({
8471
8418
  protocol,
@@ -8475,7 +8422,7 @@ async function startPreviewServer(context, config, { getPortSilently } = {}) {
8475
8422
  serverConfig,
8476
8423
  middlewares
8477
8424
  }), cleanupGracefulShutdown = setupGracefulShutdown(), serverTerminator = getServerTerminator(httpServer), closingPromise = null, closeServer = async ()=>(closingPromise || (closingPromise = (async ()=>{
8478
- removeCleanup(closeServer), cleanupGracefulShutdown(), await serverTerminator();
8425
+ removeCleanup(closeServer), cleanupGracefulShutdown(), cleanupCliShortcuts?.(), await serverTerminator();
8479
8426
  })()), closingPromise), printUrls = (options)=>printServerURLs({
8480
8427
  urls,
8481
8428
  port,
@@ -8546,7 +8493,7 @@ async function startPreviewServer(context, config, { getPortSilently } = {}) {
8546
8493
  environments: context.environments
8547
8494
  }), registerCleanup(closeServer), printUrls(), cliShortcutsEnabled) {
8548
8495
  let shortcutsOptions = 'boolean' == typeof config.dev.cliShortcuts ? {} : config.dev.cliShortcuts;
8549
- await setupCliShortcuts({
8496
+ cleanupCliShortcuts = await setupCliShortcuts({
8550
8497
  openPage,
8551
8498
  closeServer,
8552
8499
  printUrls,
@@ -8757,11 +8704,7 @@ function applyDefaultPlugins(pluginManager, context) {
8757
8704
  library: {
8758
8705
  type: isESM ? 'module' : 'commonjs2'
8759
8706
  }
8760
- }), isESM) {
8761
- if ('web-worker' === target) throw Error('[rsbuild:config] `output.module: true` is not supported for web-worker target.');
8762
- chain.node.set('__dirname', !1).set('__filename', !1), chain.output.module(!0).chunkFormat('module').chunkLoading('import').workerChunkLoading('import');
8763
- }
8764
- if (config.output.copy) {
8707
+ }), isESM && (chain.node.set('__dirname', !1).set('__filename', !1), chain.output.module(!0).chunkFormat('module').chunkLoading('import').workerChunkLoading('import')), config.output.copy) {
8765
8708
  let { copy } = config.output, options = Array.isArray(copy) ? {
8766
8709
  patterns: copy
8767
8710
  } : copy;
@@ -8846,7 +8789,7 @@ function applyDefaultPlugins(pluginManager, context) {
8846
8789
  for (let pathInfo of [
8847
8790
  ...Object.values(params.environments).reduce((result, curr)=>(result.some((item)=>item.distPath === curr.distPath) || result.push(curr), result), []).map((environment)=>((environment, isDev)=>{
8848
8791
  let { rootPath } = api.context, { config, distPath } = environment, { enable, keep } = normalizeCleanDistPath(config.output.cleanDistPath);
8849
- return 'auto' === enable ? isDev && !config.dev.writeToDisk ? void 0 : isStrictSubdir(rootPath, distPath) ? {
8792
+ return 'auto' === enable ? isDev && !config.dev.writeToDisk ? void 0 : relativeWithin(rootPath, distPath) ? {
8850
8793
  path: distPath,
8851
8794
  keep
8852
8795
  } : (api.logger.warn('The dist path is not a subdir of root path, Rsbuild will not empty it.'), api.logger.warn(`Please set ${color.yellow('`output.cleanDistPath`')} config manually.`), api.logger.warn(`Current root path: ${color.dim(rootPath)}`), void api.logger.warn(`Current dist path: ${color.dim(distPath)}`)) : !0 === enable ? {
@@ -8856,7 +8799,7 @@ function applyDefaultPlugins(pluginManager, context) {
8856
8799
  })(environment, params.isDev)),
8857
8800
  (()=>{
8858
8801
  let { rootPath, distPath } = api.context, config = api.getNormalizedConfig(), targetPath = join(distPath, RSBUILD_OUTPUTS_PATH), { enable } = normalizeCleanDistPath(config.output.cleanDistPath);
8859
- if (!0 === enable || 'auto' === enable && isStrictSubdir(rootPath, targetPath)) return {
8802
+ if (!0 === enable || 'auto' === enable && relativeWithin(rootPath, targetPath)) return {
8860
8803
  path: targetPath
8861
8804
  };
8862
8805
  })()
@@ -9212,7 +9155,7 @@ try {
9212
9155
  type: 'text'
9213
9156
  }).type('asset/source');
9214
9157
  let urlRule = cssRule.oneOf(CHAIN_ID.ONE_OF.CSS_URL).resourceQuery(URL_QUERY_REGEX);
9215
- urlRule.use(CHAIN_ID.USE.CSS_URL).loader(node_path.join(dirname, 'cssUrlLoader.mjs'));
9158
+ urlRule.use(CHAIN_ID.USE.CSS_URL).loader(node_path.join(LOADER_PATH, 'cssUrlLoader.mjs'));
9216
9159
  let inlineRule = cssRule.oneOf(CHAIN_ID.ONE_OF.CSS_INLINE).resourceQuery(INLINE_QUERY_REGEX);
9217
9160
  cssRule.oneOf(CHAIN_ID.ONE_OF.CSS_RAW).type('asset/source').resourceQuery(RAW_QUERY_REGEX);
9218
9161
  let mainRule = cssRule.oneOf(CHAIN_ID.ONE_OF.CSS_MAIN), emitCss = config.output.emitCss ?? 'web' === target;
@@ -9221,15 +9164,15 @@ try {
9221
9164
  initial: {},
9222
9165
  config: config.tools.styleLoader
9223
9166
  });
9224
- mainRule.use(CHAIN_ID.USE.STYLE).loader(join(COMPILED_PATH, 'style-loader', 'index.js')).options(styleLoaderOptions);
9167
+ mainRule.use(CHAIN_ID.USE.STYLE).loader(getCompiledPath('style-loader')).options(styleLoaderOptions);
9225
9168
  } else mainRule.use(CHAIN_ID.USE.MINI_CSS_EXTRACT).loader(core_rspack.CssExtractRspackPlugin.loader).options(config.tools.cssExtract.loaderOptions);
9226
- else mainRule.use(CHAIN_ID.USE.IGNORE_CSS).loader(node_path.join(dirname, 'ignoreCssLoader.mjs'));
9169
+ else mainRule.use(CHAIN_ID.USE.IGNORE_CSS).loader(node_path.join(LOADER_PATH, 'ignoreCssLoader.mjs'));
9227
9170
  let importLoaders = {
9228
9171
  normal: 0,
9229
9172
  inline: 0
9230
9173
  }, updateRules = async (callback, options = {})=>{
9231
9174
  options.skipMain || await callback(mainRule, 'main'), await callback(inlineRule, 'inline'), await callback(urlRule, 'url');
9232
- }, cssLoaderPath = join(COMPILED_PATH, 'css-loader', 'index.js');
9175
+ }, cssLoaderPath = getCompiledPath('css-loader');
9233
9176
  if (await updateRules((rule)=>{
9234
9177
  rule.use(CHAIN_ID.USE.CSS).loader(cssLoaderPath);
9235
9178
  }), !1 !== config.tools.lightningcssLoader) {
@@ -9253,7 +9196,7 @@ try {
9253
9196
  });
9254
9197
  if ('function' == typeof postcssLoaderOptions.postcssOptions || postcssLoaderOptions.postcssOptions?.plugins?.length) {
9255
9198
  emitCss && importLoaders.normal++, importLoaders.inline++;
9256
- let postcssLoaderPath = join(COMPILED_PATH, 'postcss-loader', 'index.js');
9199
+ let postcssLoaderPath = getCompiledPath('postcss-loader');
9257
9200
  await updateRules((rule)=>{
9258
9201
  rule.use(CHAIN_ID.USE.POSTCSS).loader(postcssLoaderPath).options(postcssLoaderOptions);
9259
9202
  }, {
@@ -9366,7 +9309,7 @@ try {
9366
9309
  api.modifyBundlerChain({
9367
9310
  order: 'pre',
9368
9311
  handler: (chain, { CHAIN_ID })=>{
9369
- chain.module.rule(CHAIN_ID.RULE.JS).oneOf(CHAIN_ID.ONE_OF.JS_WORKER).resourceQuery(WORKER_QUERY_REGEX).type("javascript/auto").use(CHAIN_ID.USE.WORKER_QUERY).loader(node_path.join(dirname, 'workerLoader.mjs'));
9312
+ chain.module.rule(CHAIN_ID.RULE.JS).oneOf(CHAIN_ID.ONE_OF.JS_WORKER).resourceQuery(WORKER_QUERY_REGEX).type("javascript/auto").use(CHAIN_ID.USE.WORKER_QUERY).loader(node_path.join(LOADER_PATH, 'workerLoader.mjs'));
9370
9313
  }
9371
9314
  });
9372
9315
  }
@@ -10067,10 +10010,15 @@ let canReadExport = (module)=>null !== module && ('object' == typeof module || '
10067
10010
  if ('default' === exportName) return canReadExport(configModule) && 'default' in configModule ? configModule.default : configModule;
10068
10011
  if (canReadExport(configModule) && Object.hasOwn(configModule, exportName)) return configModule[exportName];
10069
10012
  throw Error(`Cannot find export ${exportName} in config file: ${configPath}`);
10070
- }, loadWithJiti = async (configPath, exportName, fresh)=>{
10013
+ }, cachedImport = (importer)=>{
10014
+ let promise;
10015
+ return ()=>promise ??= importer().catch((error)=>{
10016
+ throw promise = void 0, error;
10017
+ });
10018
+ }, getJiti = cachedImport(()=>import("../compiled/jiti/lib/jiti.mjs")), loadWithJiti = async (configPath, exportName, fresh)=>{
10071
10019
  let createJiti;
10072
10020
  try {
10073
- ({ createJiti } = await import("../compiled/jiti/lib/jiti.mjs"));
10021
+ ({ createJiti } = await getJiti());
10074
10022
  } catch (error) {
10075
10023
  throw Error('The "jiti" package is required to load this config. Install it with your package manager.', {
10076
10024
  cause: error
@@ -10096,13 +10044,13 @@ let canReadExport = (module)=>null !== module && ('object' == typeof module || '
10096
10044
  function getConfigMeta(config) {
10097
10045
  if (null !== config && 'object' == typeof config && Object.hasOwn(config, CONFIG_META)) return config[CONFIG_META];
10098
10046
  }
10099
- let JS_CONFIG_REGEXP = /\.(?:js|mjs|cjs)$/, loadWithNative = async (configPath, fresh)=>{
10047
+ let getFreshImport = cachedImport(()=>import("./freshImport.js")), JS_CONFIG_REGEXP = /\.(?:js|mjs|cjs)$/, loadWithNative = async (configPath, fresh)=>{
10100
10048
  let configFileURL = pathToFileURL(configPath).href;
10101
10049
  if (!fresh) return {
10102
10050
  configModule: await import(configFileURL),
10103
10051
  dependencies: []
10104
10052
  };
10105
- let { freshImport } = await import("./freshImport.js"), freshImportResult = await freshImport(configFileURL);
10053
+ let { freshImport } = await getFreshImport(), freshImportResult = await freshImport(configFileURL);
10106
10054
  return freshImportResult ? {
10107
10055
  configModule: freshImportResult.result,
10108
10056
  dependencies: freshImportResult.dependencies.sort()
@@ -10257,7 +10205,7 @@ let applyServerOptions = (command)=>{
10257
10205
  };
10258
10206
  function setupCommands(argv) {
10259
10207
  let cli = ((name = "")=>new CAC(name))('rsbuild');
10260
- cli.version("2.2.9"), cli.option('--base <base>', 'Set the base path of the server').option('-c, --config <config>', 'Set the configuration file (relative or absolute path)').option('--config-loader <loader>', 'Set the config file loader (auto | jiti | native)', {
10208
+ cli.version("2.2.11"), cli.option('--base <base>', 'Set the base path of the server').option('-c, --config <config>', 'Set the configuration file (relative or absolute path)').option('--config-loader <loader>', 'Set the config file loader (auto | jiti | native)', {
10261
10209
  default: 'auto'
10262
10210
  }).option('--dist-path <dir>', 'Set the root directory of output files').option('--source-map', 'Enable source map').option('--env-dir <dir>', 'Set the directory for loading `.env` files').option('--env-mode <mode>', 'Set the env mode to load the `.env.[mode]` file').option('--environment <name>', 'Set the environment name(s) to build', {
10263
10211
  type: [
@@ -10322,7 +10270,7 @@ function setupCommands(argv) {
10322
10270
  }
10323
10271
  function showGreeting() {
10324
10272
  let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
10325
- src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.2.9\n`);
10273
+ src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.2.11\n`);
10326
10274
  }
10327
10275
  function setupLogLevel(argv) {
10328
10276
  if (argv.length <= 3) return;
@@ -10344,5 +10292,5 @@ function runCLI({ argv = process.argv } = {}) {
10344
10292
  src_logger.error('Failed to start Rsbuild CLI.'), src_logger.error(err), process.exit(1);
10345
10293
  }
10346
10294
  }
10347
- let src_version = "2.2.9";
10348
- export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, core_rspack as rspack, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig_loadConfig as loadConfig, loadEnv, logger_createLogger as createLogger, mergeRsbuildConfig, mrmime_lookup, runCLI, src_logger as logger, src_version as version };
10295
+ let src_version = "2.2.11";
10296
+ export { core_rspack as rspack, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig_loadConfig as loadConfig, loadEnv, logger_createLogger as createLogger, mergeRsbuildConfig, mrmime_lookup, runCLI, src_logger as logger, src_version as version };