@rsbuild/core 1.5.12 → 1.5.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/compiled/@jridgewell/remapping/index.js +5 -848
  2. package/compiled/@jridgewell/trace-mapping/index.d.ts +194 -0
  3. package/compiled/@jridgewell/trace-mapping/index.js +1408 -0
  4. package/compiled/@jridgewell/trace-mapping/license +19 -0
  5. package/compiled/@jridgewell/trace-mapping/package.json +1 -0
  6. package/compiled/css-loader/index.js +22 -22
  7. package/compiled/html-rspack-plugin/index.js +14 -14
  8. package/compiled/launch-editor-middleware/index.js +3 -3
  9. package/compiled/memfs/index.d.ts +6 -1
  10. package/compiled/memfs/index.js +662 -636
  11. package/compiled/memfs/package.json +1 -1
  12. package/compiled/postcss/index.js +4 -4
  13. package/compiled/postcss-loader/index.js +6 -6
  14. package/compiled/rspack-manifest-plugin/index.js +4 -4
  15. package/dist/client/hmr.js +58 -19
  16. package/dist/index.cjs +426 -373
  17. package/dist/index.js +420 -369
  18. package/dist-types/configChain.d.ts +0 -4
  19. package/dist-types/server/assets-middleware/getFileFromUrl.d.ts +9 -0
  20. package/dist-types/server/assets-middleware/index.d.ts +48 -0
  21. package/dist-types/server/assets-middleware/middleware.d.ts +3 -0
  22. package/dist-types/server/assets-middleware/setupOutputFileSystem.d.ts +4 -0
  23. package/dist-types/server/assets-middleware/setupWriteToDisk.d.ts +15 -0
  24. package/dist-types/server/browserLogs.d.ts +7 -0
  25. package/dist-types/server/{compilationManager.d.ts → buildManager.d.ts} +11 -11
  26. package/dist-types/server/devMiddlewares.d.ts +2 -2
  27. package/dist-types/server/devServer.d.ts +3 -3
  28. package/dist-types/server/middlewares.d.ts +3 -3
  29. package/dist-types/server/socketServer.d.ts +22 -11
  30. package/dist-types/server/watchFiles.d.ts +2 -2
  31. package/dist-types/types/config.d.ts +13 -6
  32. package/dist-types/types/context.d.ts +14 -4
  33. package/dist-types/types/plugin.d.ts +1 -1
  34. package/dist-types/types/rsbuild.d.ts +8 -1
  35. package/package.json +5 -3
  36. package/dist-types/dev-middleware/index.d.ts +0 -53
  37. package/dist-types/dev-middleware/middleware.d.ts +0 -3
  38. package/dist-types/dev-middleware/utils/getFilenameFromUrl.d.ts +0 -7
  39. package/dist-types/dev-middleware/utils/getPaths.d.ts +0 -7
  40. package/dist-types/dev-middleware/utils/ready.d.ts +0 -2
  41. package/dist-types/dev-middleware/utils/setupHooks.d.ts +0 -3
  42. package/dist-types/dev-middleware/utils/setupOutputFileSystem.d.ts +0 -3
  43. package/dist-types/dev-middleware/utils/setupWriteToDisk.d.ts +0 -7
  44. package/dist-types/server/compilationMiddleware.d.ts +0 -36
  45. /package/dist-types/{dev-middleware/utils → server/assets-middleware}/escapeHtml.d.ts +0 -0
  46. /package/dist-types/{dev-middleware/utils → server/assets-middleware}/memorize.d.ts +0 -0
  47. /package/dist-types/{dev-middleware/utils → server/assets-middleware}/parseTokenList.d.ts +0 -0
package/dist/index.js CHANGED
@@ -2444,6 +2444,8 @@ function formatMessage(stats, verbose) {
2444
2444
  let message;
2445
2445
  if ('object' == typeof stats) {
2446
2446
  let fileName = function(stats) {
2447
+ let file = stats.file || stats.moduleName;
2448
+ if (file) return formatFileName(file);
2447
2449
  if (stats.moduleIdentifier) {
2448
2450
  let matched = stats.moduleIdentifier.match(/(?:!|^)([^!]+)$/);
2449
2451
  if (matched) {
@@ -2451,8 +2453,7 @@ function formatMessage(stats, verbose) {
2451
2453
  if (fileName) return formatFileName(fileName);
2452
2454
  }
2453
2455
  }
2454
- let file = stats.file || stats.moduleName;
2455
- return file ? formatFileName(file) : '';
2456
+ return '';
2456
2457
  }(stats), mainMessage = stats.message, details = verbose && stats.details ? `\nDetails: ${stats.details}\n` : '', stack = verbose && stats.stack ? `\n${stats.stack}` : '', moduleTrace = function(stats) {
2457
2458
  let traceStr = '';
2458
2459
  if (stats.moduleTrace) for (let trace of stats.moduleTrace)trace.originName && (traceStr += `\n @ ${trace.originName}`);
@@ -3332,6 +3333,7 @@ let configCache = {}, OVERRIDE_PATHS = [
3332
3333
  dev: {
3333
3334
  hmr: !0,
3334
3335
  liveReload: !0,
3336
+ browserLogs: !0,
3335
3337
  watchFiles: [],
3336
3338
  assetPrefix: DEFAULT_ASSET_PREFIX,
3337
3339
  writeToDisk: !1,
@@ -3677,7 +3679,7 @@ async function updateEnvironmentContext(context, configs) {
3677
3679
  async function createContext(options, userConfig) {
3678
3680
  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';
3679
3681
  return {
3680
- version: "1.5.12",
3682
+ version: "1.5.13",
3681
3683
  rootPath,
3682
3684
  distPath: '',
3683
3685
  cachePath,
@@ -3713,7 +3715,11 @@ async function createContext(options, userConfig) {
3713
3715
  ...rsbuildConfig
3714
3716
  },
3715
3717
  originalConfig: userConfig,
3716
- specifiedEnvironments
3718
+ specifiedEnvironments,
3719
+ buildState: {
3720
+ status: 'idle',
3721
+ hasErrors: !1
3722
+ }
3717
3723
  };
3718
3724
  }
3719
3725
  let normalizePluginObject = (plugin)=>{
@@ -3892,7 +3898,6 @@ let configChain_CHAIN_ID = {
3892
3898
  STYLUS_RAW: 'stylus-raw',
3893
3899
  STYLUS_INLINE: 'stylus-inline',
3894
3900
  SVG: 'svg',
3895
- PUG: 'pug',
3896
3901
  VUE: 'vue',
3897
3902
  WASM: 'wasm',
3898
3903
  SVELTE: 'svelte'
@@ -3912,7 +3917,6 @@ let configChain_CHAIN_ID = {
3912
3917
  LESS: 'less',
3913
3918
  STYLUS: 'stylus',
3914
3919
  URL: 'url',
3915
- PUG: 'pug',
3916
3920
  VUE: 'vue',
3917
3921
  SWC: 'swc',
3918
3922
  SVGR: 'svgr',
@@ -4043,6 +4047,7 @@ let allowedEnvironmentDevKeys = [
4043
4047
  'hmr',
4044
4048
  'client',
4045
4049
  'liveReload',
4050
+ 'browserLogs',
4046
4051
  'writeToDisk',
4047
4052
  'assetPrefix',
4048
4053
  'progressBar',
@@ -4215,7 +4220,7 @@ function formatFileList(paths, rootPath) {
4215
4220
  async function createCompiler_createCompiler(options) {
4216
4221
  let version;
4217
4222
  logger.debug('creating compiler');
4218
- let { context } = options, { rspackConfigs } = await initConfigs(options);
4223
+ let HOOK_NAME = 'rsbuild:compiler', { context } = options, { rspackConfigs } = await initConfigs(options);
4219
4224
  if (await context.hooks.onBeforeCreateCompiler.callBatch({
4220
4225
  bundlerConfigs: rspackConfigs,
4221
4226
  environments: context.environments
@@ -4231,7 +4236,7 @@ async function createCompiler_createCompiler(options) {
4231
4236
  let isMultiCompiler = rspackConfigs.length > 1, compiler = isMultiCompiler ? rspack_rspack(rspackConfigs) : rspack_rspack(rspackConfigs[0]), isVersionLogged = !1, isCompiling = !1, logRspackVersion = ()=>{
4232
4237
  isVersionLogged || (logger.debug(`using Rspack v${rspack_rspack.rspackVersion}`), isVersionLogged = !0);
4233
4238
  }, lazyModules = new Set();
4234
- return compiler.hooks.infrastructureLog.tap('rsbuild:compiling', (name, _, args)=>{
4239
+ return compiler.hooks.infrastructureLog.tap(HOOK_NAME, (name, _, args)=>{
4235
4240
  let log = args[0];
4236
4241
  if ('LazyCompilation' === name && 'string' == typeof log && log.startsWith('lazy-compilation-proxy')) {
4237
4242
  let resource = log.split(' ')[0];
@@ -4242,8 +4247,10 @@ async function createCompiler_createCompiler(options) {
4242
4247
  lazyModules.add(relativePath);
4243
4248
  }
4244
4249
  }
4245
- }), compiler.hooks.watchRun.tap('rsbuild:compiling', (compiler)=>{
4246
- logRspackVersion(), isCompiling || function(compiler, context, lazyModules) {
4250
+ }), compiler.hooks.run.tap(HOOK_NAME, ()=>{
4251
+ context.buildState.status = 'building';
4252
+ }), compiler.hooks.watchRun.tap(HOOK_NAME, (compiler)=>{
4253
+ context.buildState.status = 'building', logRspackVersion(), isCompiling || function(compiler, context, lazyModules) {
4247
4254
  let { modifiedFiles } = compiler, changedFiles = modifiedFiles?.size ? Array.from(modifiedFiles) : lazyModules.size ? Array.from(lazyModules) : null;
4248
4255
  if (changedFiles?.length) {
4249
4256
  let fileInfo = formatFileList(changedFiles, context.rootPath);
@@ -4258,28 +4265,30 @@ async function createCompiler_createCompiler(options) {
4258
4265
  }
4259
4266
  logger.start('build started...');
4260
4267
  }(compiler, context, lazyModules), lazyModules.size && lazyModules.clear(), isCompiling = !0;
4261
- }), 'build' === context.action && (isMultiCompiler ? compiler.compilers[0] : compiler).hooks.run.tap('rsbuild:run', ()=>{
4268
+ }), compiler.hooks.invalid.tap(HOOK_NAME, ()=>{
4269
+ context.buildState.status = 'idle', context.buildState.hasErrors = !1;
4270
+ }), 'build' === context.action && (isMultiCompiler ? compiler.compilers[0] : compiler).hooks.run.tap(HOOK_NAME, ()=>{
4262
4271
  logger.info('build started...'), logRspackVersion();
4263
- }), compiler.hooks.done.tap('rsbuild:done', (stats)=>{
4264
- ((stats)=>{
4265
- let statsOptions = getStatsOptions(compiler), statsJson = stats.toJson({
4266
- children: !0,
4267
- moduleTrace: !0,
4268
- timings: !0,
4269
- preset: 'errors-warnings',
4270
- ...statsOptions
4271
- }), printTime = (c, index)=>{
4272
- if (c.time) {
4273
- let time = prettyTime(c.time / 1000), { name } = rspackConfigs[index], suffix = name && isMultiCompiler ? picocolors.dim(` (${name})`) : '';
4274
- logger.ready(`built in ${time}${suffix}`);
4275
- }
4276
- }, hasErrors = stats.hasErrors();
4277
- hasErrors || (isMultiCompiler && statsJson.children?.length ? statsJson.children.forEach((c, index)=>{
4278
- printTime(c, index);
4279
- }) : printTime(statsJson, 0));
4280
- let { message, level } = formatStats(statsJson, hasErrors);
4281
- 'error' === level && logger.error(message), 'warning' === level && logger.warn(message), isCompiling = !1;
4282
- })(stats);
4272
+ }), compiler.hooks.done.tap(HOOK_NAME, (stats)=>{
4273
+ let hasErrors = stats.hasErrors();
4274
+ context.buildState.hasErrors = hasErrors, context.buildState.status = 'done';
4275
+ let statsOptions = getStatsOptions(compiler), statsJson = stats.toJson({
4276
+ children: !0,
4277
+ moduleTrace: !0,
4278
+ timings: !0,
4279
+ preset: 'errors-warnings',
4280
+ ...statsOptions
4281
+ }), printTime = (c, index)=>{
4282
+ if (c.time) {
4283
+ let time = prettyTime(c.time / 1000), { name } = rspackConfigs[index], suffix = name && isMultiCompiler ? picocolors.dim(` (${name})`) : '';
4284
+ logger.ready(`built in ${time}${suffix}`);
4285
+ }
4286
+ };
4287
+ hasErrors || (isMultiCompiler && statsJson.children?.length ? statsJson.children.forEach((c, index)=>{
4288
+ printTime(c, index);
4289
+ }) : printTime(statsJson, 0));
4290
+ let { message, level } = formatStats(statsJson, hasErrors);
4291
+ 'error' === level && logger.error(message), 'warning' === level && logger.warn(message), isCompiling = !1;
4283
4292
  }), 'dev' === context.action && registerDevHook({
4284
4293
  context,
4285
4294
  compiler,
@@ -5691,72 +5700,73 @@ let MODULE_PATH_REGEX = /.*[\\/]node_modules[\\/](?!\.pnpm[\\/])(?:(@[^\\/]+)[\\
5691
5700
  }
5692
5701
  };
5693
5702
  }
5694
- }, swc_require = (0, external_node_module_.createRequire)(import.meta.url), builtinSwcLoaderName = 'builtin:swc-loader', isCliShortcutsEnabled = (config)=>config.dev.cliShortcuts && isTTY('stdin');
5695
- async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls, restartServer, customShortcuts }) {
5696
- let shortcuts = [
5697
- {
5698
- key: 'c',
5699
- description: `${picocolors.bold('c + enter')} ${picocolors.dim('clear console')}`,
5700
- action: ()=>{
5701
- console.clear();
5703
+ }, swc_require = (0, external_node_module_.createRequire)(import.meta.url), builtinSwcLoaderName = 'builtin:swc-loader';
5704
+ async function getLocalhostResolvedAddress() {
5705
+ let { promises: dns } = await import("node:dns"), [defaultLookup, explicitLookup] = await Promise.all([
5706
+ dns.lookup('localhost'),
5707
+ dns.lookup('localhost', {
5708
+ verbatim: !0
5709
+ })
5710
+ ]);
5711
+ return defaultLookup.family === explicitLookup.family && defaultLookup.address === explicitLookup.address ? void 0 : defaultLookup.address;
5712
+ }
5713
+ async function resolveHostname(host = 'localhost') {
5714
+ if ('localhost' === host) {
5715
+ let resolvedAddress = await getLocalhostResolvedAddress();
5716
+ if (resolvedAddress) return resolvedAddress;
5717
+ }
5718
+ return void 0 === host || new Set([
5719
+ '0.0.0.0',
5720
+ '::',
5721
+ '0000:0000:0000:0000:0000:0000:0000:0000'
5722
+ ]).has(host) ? 'localhost' : host;
5723
+ }
5724
+ var on_finished = __webpack_require__("../../node_modules/.pnpm/on-finished@2.4.1/node_modules/on-finished/index.js"), on_finished_default = __webpack_require__.n(on_finished), range_parser = __webpack_require__("../../node_modules/.pnpm/range-parser@1.2.1/node_modules/range-parser/index.js"), range_parser_default = __webpack_require__.n(range_parser);
5725
+ let matchHtmlRegExp = /["'&<>]/, UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
5726
+ function getFileFromUrl(url, outputFileSystem, environments) {
5727
+ let pathname;
5728
+ try {
5729
+ let urlObject = new URL(url, 'http://localhost');
5730
+ urlObject.pathname && (pathname = external_node_querystring_unescape(urlObject.pathname));
5731
+ } catch {
5732
+ return;
5733
+ }
5734
+ if (pathname) {
5735
+ if (pathname.includes('\0')) return {
5736
+ errorCode: 400
5737
+ };
5738
+ if (UP_PATH_REGEXP.test(external_node_path_.default.normalize(`./${pathname}`))) return {
5739
+ errorCode: 403
5740
+ };
5741
+ for (let distPath of new Set(Object.values(environments).map((env)=>env.distPath))){
5742
+ let fsStats, filename = external_node_path_.default.join(distPath, pathname);
5743
+ try {
5744
+ fsStats = outputFileSystem.statSync?.(filename);
5745
+ } catch {
5746
+ continue;
5702
5747
  }
5703
- },
5704
- {
5705
- key: 'o',
5706
- description: `${picocolors.bold('o + enter')} ${picocolors.dim('open in browser')}`,
5707
- action: openPage
5708
- },
5709
- {
5710
- key: 'q',
5711
- description: `${picocolors.bold('q + enter')} ${picocolors.dim('quit process')}`,
5712
- action: async ()=>{
5713
- try {
5714
- await closeServer();
5715
- } finally{
5716
- process.exit(0);
5748
+ if (fsStats) {
5749
+ if (fsStats.isFile()) return {
5750
+ filename,
5751
+ fsStats
5752
+ };
5753
+ if (fsStats.isDirectory()) {
5754
+ filename = external_node_path_.default.join(filename, 'index.html');
5755
+ try {
5756
+ fsStats = outputFileSystem.statSync?.(filename);
5757
+ } catch {
5758
+ continue;
5759
+ }
5760
+ if (!fsStats) continue;
5761
+ if (fsStats.isFile()) return {
5762
+ filename,
5763
+ fsStats
5764
+ };
5717
5765
  }
5718
5766
  }
5719
- },
5720
- restartServer ? {
5721
- key: 'r',
5722
- description: `${picocolors.bold('r + enter')} ${picocolors.dim('restart server')}`,
5723
- action: restartServer
5724
- } : null,
5725
- {
5726
- key: 'u',
5727
- description: `${picocolors.bold('u + enter')} ${picocolors.dim('show urls')}`,
5728
- action: printUrls
5729
- }
5730
- ].filter(Boolean);
5731
- if (customShortcuts && !Array.isArray(shortcuts = customShortcuts(shortcuts))) throw Error(`${picocolors.dim('[rsbuild:config]')} ${picocolors.yellow('dev.cliShortcuts')} option must return an array of shortcuts.`);
5732
- help && logger.log(!0 === help ? ` ➜ ${picocolors.dim('press')} ${picocolors.bold('h + enter')} ${picocolors.dim('to show shortcuts')}\n` : ` ➜ ${help}\n`);
5733
- let { createInterface } = await import("node:readline"), rl = createInterface({
5734
- input: process.stdin
5735
- });
5736
- return rl.on('line', (input)=>{
5737
- if ('h' === input) {
5738
- let message = `\n ${picocolors.bold(picocolors.blue('Shortcuts:'))}\n`;
5739
- for (let shortcut of shortcuts)message += ` ${shortcut.description}\n`;
5740
- logger.log(message);
5741
5767
  }
5742
- for (let shortcut of shortcuts)if (input === shortcut.key) return void shortcut.action();
5743
- }), ()=>{
5744
- rl.close();
5745
- };
5746
- }
5747
- var on_finished = __webpack_require__("../../node_modules/.pnpm/on-finished@2.4.1/node_modules/on-finished/index.js"), on_finished_default = __webpack_require__.n(on_finished), range_parser = __webpack_require__("../../node_modules/.pnpm/range-parser@1.2.1/node_modules/range-parser/index.js"), range_parser_default = __webpack_require__.n(range_parser);
5748
- let matchHtmlRegExp = /["'&<>]/;
5749
- function memorize(fn, { cache = new Map() } = {}, callback) {
5750
- return (...arguments_)=>{
5751
- let [key] = arguments_, cacheItem = cache.get(key);
5752
- if (cacheItem) return cacheItem.data;
5753
- let result = fn.apply(void 0, arguments_);
5754
- return callback && (result = callback(result)), cache.set(key, {
5755
- data: result
5756
- }), result;
5757
- };
5768
+ }
5758
5769
  }
5759
- let memoizedParse = memorize(external_node_url_.parse, void 0, (value)=>(value.pathname && (value.pathname = external_node_querystring_unescape(value.pathname)), value)), UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
5760
5770
  function parseTokenList(str) {
5761
5771
  let end = 0, start = 0, list = [];
5762
5772
  for(let i = 0, len = str.length; i < len; i++)switch(str.charCodeAt(i)){
@@ -5771,9 +5781,6 @@ function parseTokenList(str) {
5771
5781
  }
5772
5782
  return start !== end && list.push(str.substring(start, end)), list;
5773
5783
  }
5774
- function ready(context, callback) {
5775
- context.state ? callback(context.stats) : context.callbacks.push(callback);
5776
- }
5777
5784
  async function getContentType(str) {
5778
5785
  let { lookup } = await import("../compiled/mrmime/index.js"), mime = lookup(str);
5779
5786
  return !!mime && ((mime.startsWith('text/') || 'application/json' === mime || 'application/manifest+json' === mime) && (mime += '; charset=utf-8'), mime);
@@ -5792,57 +5799,113 @@ let CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/, statuses =
5792
5799
  404: 'Not Found',
5793
5800
  416: 'Range Not Satisfiable',
5794
5801
  500: 'Internal Server Error'
5795
- }, parseRangeHeaders = memorize((value)=>{
5802
+ }, parseRangeHeaders = function(fn, { cache = new Map() } = {}, callback) {
5803
+ return (...arguments_)=>{
5804
+ let [key] = arguments_, cacheItem = cache.get(key);
5805
+ if (cacheItem) return cacheItem.data;
5806
+ let result = fn.apply(void 0, arguments_);
5807
+ return cache.set(key, {
5808
+ data: result
5809
+ }), result;
5810
+ };
5811
+ }((value)=>{
5796
5812
  let [len, rangeHeader] = value.split('|');
5797
5813
  return range_parser_default()(Number(len), rangeHeader, {
5798
5814
  combine: !0
5799
5815
  });
5800
- });
5801
- async function setupOutputFileSystem(options, compilers) {
5802
- if (!0 !== options.writeToDisk) {
5816
+ }), acceptedMethods = [
5817
+ 'GET',
5818
+ 'HEAD'
5819
+ ];
5820
+ async function setupOutputFileSystem(writeToDisk, compilers) {
5821
+ if (!0 !== writeToDisk) {
5803
5822
  let { createFsFromVolume, Volume } = await import("../compiled/memfs/index.js"), outputFileSystem = createFsFromVolume(new Volume());
5804
5823
  for (let compiler of compilers)compiler.outputFileSystem = outputFileSystem;
5805
5824
  }
5806
5825
  return compilers[0].outputFileSystem;
5807
5826
  }
5808
- let noop = ()=>{};
5809
- async function devMiddleware(compiler, options = {}) {
5827
+ let noop = ()=>{}, assets_middleware_require = (0, external_node_module_.createRequire)(import.meta.url), assetsMiddleware = async ({ config, compiler, context, socketServer, resolvedPort })=>{
5828
+ var config1, ready;
5829
+ let watching, writeToDiskValues, resolvedHost = await resolveHostname(config.server.host), { environments } = context;
5830
+ applyToCompiler(compiler, (compiler, index)=>{
5831
+ let environment = Object.values(environments).find((env)=>env.index === index);
5832
+ if (!environment) return;
5833
+ let token = environment.webSocketToken;
5834
+ token && (!function({ config, compiler, token, resolvedHost, resolvedPort }) {
5835
+ var devConfig;
5836
+ let clientPaths;
5837
+ if (!((compiler)=>{
5838
+ let { target } = compiler.options;
5839
+ return !!target && (Array.isArray(target) ? target.includes('web') : 'web' === target);
5840
+ })(compiler)) return;
5841
+ let clientPaths1 = (devConfig = config.dev, clientPaths = [], (devConfig.hmr || devConfig.liveReload) && (hmrClientPath || (hmrClientPath = assets_middleware_require.resolve('@rsbuild/core/client/hmr')), clientPaths.push(hmrClientPath), devConfig.client?.overlay && (overlayClientPath || (overlayClientPath = assets_middleware_require.resolve('@rsbuild/core/client/overlay')), clientPaths.push(overlayClientPath))), clientPaths);
5842
+ if (!clientPaths1.length) return;
5843
+ let clientConfig = {
5844
+ ...config.dev.client
5845
+ };
5846
+ for (let clientPath of ('<port>' === clientConfig.port && (clientConfig.port = resolvedPort), new compiler.webpack.DefinePlugin({
5847
+ RSBUILD_WEB_SOCKET_TOKEN: JSON.stringify(token),
5848
+ RSBUILD_CLIENT_CONFIG: JSON.stringify(clientConfig),
5849
+ RSBUILD_SERVER_HOST: JSON.stringify(resolvedHost),
5850
+ RSBUILD_SERVER_PORT: JSON.stringify(resolvedPort),
5851
+ RSBUILD_DEV_LIVE_RELOAD: config.dev.liveReload,
5852
+ RSBUILD_DEV_BROWSER_LOGS: config.dev.browserLogs
5853
+ }).apply(compiler), clientPaths1))new compiler.webpack.EntryPlugin(compiler.context, clientPath, {
5854
+ name: void 0
5855
+ }).apply(compiler);
5856
+ }({
5857
+ token,
5858
+ config: environment.config,
5859
+ compiler,
5860
+ resolvedHost,
5861
+ resolvedPort
5862
+ }), (({ compiler, token, socketServer })=>{
5863
+ ((compiler)=>{
5864
+ let { target } = compiler.options;
5865
+ return !!target && (Array.isArray(target) ? target.includes('node') : 'node' === target);
5866
+ })(compiler) || (compiler.hooks.invalid.tap('rsbuild-dev-server', (fileName)=>{
5867
+ if ('string' == typeof fileName && fileName.endsWith('.html')) return void socketServer.sockWrite({
5868
+ type: 'static-changed'
5869
+ }, token);
5870
+ }), compiler.hooks.done.tap('rsbuild-dev-server', (stats)=>{
5871
+ socketServer.onBuildDone(stats, token);
5872
+ }));
5873
+ })({
5874
+ compiler,
5875
+ socketServer,
5876
+ token
5877
+ }));
5878
+ });
5810
5879
  let compilers = helpers_isMultiCompiler(compiler) ? compiler.compilers : [
5811
5880
  compiler
5812
- ], context = {
5813
- state: !1,
5814
- stats: void 0,
5815
- callbacks: [],
5816
- options,
5817
- compilers
5818
- };
5819
- function invalid() {
5820
- context.state = !1, context.stats = void 0;
5821
- }
5822
- compiler.hooks.watchRun.tap('rsbuild-dev-middleware', invalid), compiler.hooks.invalid.tap('rsbuild-dev-middleware', invalid), compiler.hooks.done.tap('rsbuild-dev-middleware', function(stats) {
5823
- context.state = !0, context.stats = stats, process.nextTick(()=>{
5824
- let { state, callbacks } = context;
5825
- state && (context.callbacks = [], callbacks.forEach((callback)=>{
5826
- callback(stats);
5827
- }));
5881
+ ], callbacks = [];
5882
+ compiler.hooks.done.tap('rsbuild-dev-middleware', ()=>{
5883
+ process.nextTick(()=>{
5884
+ 'done' === context.buildState.status && (callbacks.forEach((callback)=>{
5885
+ callback();
5886
+ }), callbacks.length = 0);
5828
5887
  });
5829
- }), options.writeToDisk && function(context) {
5830
- let { compilers } = context;
5888
+ });
5889
+ let writeToDisk = (config1 = config.dev, 1 === new Set(writeToDiskValues = Object.values(environments).map((env)=>env.config.dev.writeToDisk)).size ? writeToDiskValues[0] : (filePath, name)=>{
5890
+ let { writeToDisk } = config1;
5891
+ return name && environments[name] && (writeToDisk = environments[name].config.dev.writeToDisk ?? writeToDisk), 'function' == typeof writeToDisk ? writeToDisk(filePath) : writeToDisk;
5892
+ });
5893
+ writeToDisk && function(compilers, writeToDisk) {
5831
5894
  for (let compiler of compilers)compiler.hooks.emit.tap('DevMiddleware', ()=>{
5832
5895
  compiler.__hasRsbuildAssetEmittedCallback || (compiler.hooks.assetEmitted.tapAsync('DevMiddleware', (_file, info, callback)=>{
5833
- let { targetPath, content, compilation } = info, { writeToDisk: filter } = context.options;
5834
- if (!(!filter || 'function' != typeof filter || filter(targetPath, compilation.name))) return void callback();
5896
+ let { targetPath, content, compilation } = info;
5897
+ if (!(!writeToDisk || 'function' != typeof writeToDisk || writeToDisk(targetPath, compilation.name))) return void callback();
5835
5898
  let dir = external_node_path_.default.dirname(targetPath), name = compiler.options.name ? `Child "${compiler.options.name}": ` : '';
5836
5899
  node_fs.mkdir(dir, {
5837
5900
  recursive: !0
5838
5901
  }, (mkdirError)=>{
5839
5902
  if (mkdirError) {
5840
- logger.error(`[rsbuild-dev-middleware] ${name}Unable to write "${dir}" directory to disk:\n${mkdirError.message}`), callback(mkdirError);
5903
+ logger.error(`[rsbuild:middleware] ${name}Unable to write "${dir}" directory to disk:\n${mkdirError.message}`), callback(mkdirError);
5841
5904
  return;
5842
5905
  }
5843
5906
  node_fs.writeFile(targetPath, content, (writeFileError)=>{
5844
5907
  if (writeFileError) {
5845
- logger.error(`[rsbuild-dev-middleware] ${name}Unable to write "${targetPath}" asset to disk:\n${writeFileError.message}`), callback(writeFileError);
5908
+ logger.error(`[rsbuild:middleware] ${name}Unable to write "${targetPath}" asset to disk:\n${writeFileError.message}`), callback(writeFileError);
5846
5909
  return;
5847
5910
  }
5848
5911
  callback();
@@ -5850,21 +5913,19 @@ async function devMiddleware(compiler, options = {}) {
5850
5913
  });
5851
5914
  }), compiler.__hasRsbuildAssetEmittedCallback = !0);
5852
5915
  });
5853
- }(context), context.outputFileSystem = await setupOutputFileSystem(options, compilers);
5854
- let instance = async function(req, res, next) {
5916
+ }(compilers, writeToDisk);
5917
+ let outputFileSystem = await setupOutputFileSystem(writeToDisk, compilers), instance = (ready = (callback)=>{
5918
+ 'done' === context.buildState.status ? callback() : callbacks.push(callback);
5919
+ }, async function(req, res, next) {
5920
+ let { environments } = context;
5855
5921
  async function goNext() {
5856
5922
  return new Promise((resolve)=>{
5857
- ready(context, ()=>{
5858
- res.locals = res.locals || {}, res.locals.webpack = {
5859
- devMiddleware: context
5860
- }, next(), resolve();
5923
+ ready(()=>{
5924
+ next(), resolve();
5861
5925
  });
5862
5926
  });
5863
5927
  }
5864
- if (req.method && ![
5865
- 'GET',
5866
- 'HEAD'
5867
- ].includes(req.method)) return void await goNext();
5928
+ if (req.method && !acceptedMethods.includes(req.method)) return void await goNext();
5868
5929
  function sendError(status, options) {
5869
5930
  let content = statuses[status] || String(status), document = Buffer.from(`<!DOCTYPE html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<title>Error</title>\n</head>\n<body>\n<pre>${function(input) {
5870
5931
  let htmlEntity, match = matchHtmlRegExp.exec(input);
@@ -5906,76 +5967,17 @@ async function devMiddleware(compiler, options = {}) {
5906
5967
  let byteLength = Buffer.byteLength(document);
5907
5968
  res.setHeader('Content-Length', byteLength), res.end(document);
5908
5969
  }
5909
- async function processRequest() {
5910
- var stat, range, offset, outputFileSystem;
5911
- let bufferOrStream, byteLength, end, extra = {}, filename = function(context, url, extra = {}) {
5912
- let foundFilename, urlObject, paths = function(context) {
5913
- let { stats, options } = context, childStats = stats.stats ? stats.stats : [
5914
- stats
5915
- ], publicPaths = [];
5916
- for (let { compilation } of childStats){
5917
- let outputPath = compilation.getPath(compilation.outputOptions.path || ''), publicPath = options.publicPath ? compilation.getPath(options.publicPath) : compilation.outputOptions.publicPath ? compilation.getPath(compilation.outputOptions.publicPath) : '';
5918
- publicPaths.push({
5919
- outputPath,
5920
- publicPath
5921
- });
5922
- }
5923
- return publicPaths;
5924
- }(context);
5925
- try {
5926
- urlObject = memoizedParse(url, !1, !0);
5927
- } catch (_ignoreError) {
5928
- return;
5929
- }
5930
- for (let { publicPath, outputPath } of paths){
5931
- let filename, publicPathObject;
5932
- try {
5933
- publicPathObject = memoizedParse('auto' !== publicPath && publicPath ? publicPath : '/', !1, !0);
5934
- } catch (_ignoreError) {
5935
- continue;
5936
- }
5937
- let { pathname } = urlObject, { pathname: publicPathPathname } = publicPathObject;
5938
- if (pathname?.startsWith(publicPathPathname)) {
5939
- if (pathname.includes('\u0000')) {
5940
- extra.errorCode = 400;
5941
- return;
5942
- }
5943
- if (UP_PATH_REGEXP.test(external_node_path_.normalize(`./${pathname}`))) {
5944
- extra.errorCode = 403;
5945
- return;
5946
- }
5947
- filename = external_node_path_.join(outputPath, pathname.slice(publicPathPathname.length));
5948
- try {
5949
- extra.stats = context.outputFileSystem.statSync(filename);
5950
- } catch (_ignoreError) {
5951
- continue;
5952
- }
5953
- if (extra.stats.isFile()) {
5954
- foundFilename = filename;
5955
- break;
5956
- }
5957
- if (extra.stats.isDirectory()) {
5958
- filename = external_node_path_.join(filename, 'index.html');
5959
- try {
5960
- extra.stats = context.outputFileSystem.statSync(filename);
5961
- } catch (__ignoreError) {
5962
- continue;
5963
- }
5964
- if (extra.stats.isFile()) {
5965
- foundFilename = filename;
5966
- break;
5967
- }
5968
- }
5969
- }
5970
- }
5971
- return foundFilename;
5972
- }(context, req.url, extra);
5973
- if (extra.errorCode) {
5974
- 403 === extra.errorCode && logger.error(`[rsbuild-dev-middleware] Malicious path "${filename}".`), sendError(extra.errorCode);
5970
+ ready(async function() {
5971
+ var range, offset;
5972
+ let bufferOrStream, byteLength, end;
5973
+ if (!req.url) return void await goNext();
5974
+ let resolved = getFileFromUrl(req.url, outputFileSystem, environments);
5975
+ if (!resolved) return void await goNext();
5976
+ if ('errorCode' in resolved) {
5977
+ 403 === resolved.errorCode && logger.error(`[rsbuild:middleware] Malicious path "${req.url}".`), sendError(resolved.errorCode);
5975
5978
  return;
5976
5979
  }
5977
- if (!filename) return void await goNext();
5978
- let { size } = extra.stats, len = size, offset1 = 0;
5980
+ let { fsStats, filename } = resolved, { size } = fsStats, len = size, offset1 = 0;
5979
5981
  if (!res.getHeader('Content-Type')) {
5980
5982
  let contentType = await getContentType(filename);
5981
5983
  contentType && res.setHeader('Content-Type', contentType);
@@ -5985,8 +5987,8 @@ async function devMiddleware(compiler, options = {}) {
5985
5987
  let rage = req.headers.range;
5986
5988
  if (rage && BYTES_RANGE_REGEXP.test(rage)) return rage;
5987
5989
  }();
5988
- if (!res.getHeader('ETag') && extra.stats) {
5989
- let mtime, size, hash = (mtime = (stat = extra.stats).mtime.getTime().toString(16), size = stat.size.toString(16), `W/"${size}-${mtime}"`);
5990
+ if (!res.getHeader('ETag') && fsStats) {
5991
+ let mtime, size, hash = (mtime = fsStats.mtime.getTime().toString(16), size = fsStats.size.toString(16), `W/"${size}-${mtime}"`);
5990
5992
  res.setHeader('ETag', hash);
5991
5993
  }
5992
5994
  if (req.headers['if-match'] || req.headers['if-unmodified-since'] || req.headers['if-none-match'] || req.headers['if-modified-since']) {
@@ -6049,14 +6051,14 @@ async function devMiddleware(compiler, options = {}) {
6049
6051
  let lastModified = res.getHeader('Last-Modified');
6050
6052
  return !lastModified || parseHttpDate(lastModified) <= parseHttpDate(ifRange);
6051
6053
  }() && (parsedRanges = []), -1 === parsedRanges) {
6052
- logger.error("[rsbuild-dev-middleware] Unsatisfiable range for 'Range' header."), res.setHeader('Content-Range', getValueContentRangeHeader('bytes', size)), sendError(416, {
6054
+ logger.error("[rsbuild:middleware] Unsatisfiable range for 'Range' header."), res.setHeader('Content-Range', getValueContentRangeHeader('bytes', size)), sendError(416, {
6053
6055
  headers: {
6054
6056
  'Content-Range': res.getHeader('Content-Range')
6055
6057
  }
6056
6058
  });
6057
6059
  return;
6058
6060
  }
6059
- (-2 === parsedRanges ? logger.error("[rsbuild-dev-middleware] A malformed 'Range' header was provided. A regular response will be sent for this request.") : parsedRanges.length > 1 && logger.error("[rsbuild-dev-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])), [offset1, len] = [
6061
+ (-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])), [offset1, len] = [
6060
6062
  (range = parsedRanges[0]).start,
6061
6063
  range.end - range.start + 1
6062
6064
  ]);
@@ -6066,14 +6068,14 @@ async function devMiddleware(compiler, options = {}) {
6066
6068
  end
6067
6069
  ]);
6068
6070
  try {
6069
- ({ bufferOrStream, byteLength } = (outputFileSystem = context.outputFileSystem, {
6071
+ ({ bufferOrStream, byteLength } = {
6070
6072
  bufferOrStream: outputFileSystem.createReadStream(filename, {
6071
6073
  start: start,
6072
6074
  end: end1
6073
6075
  }),
6074
6076
  byteLength: 0 === end1 ? 0 : end1 - start + 1
6075
- }));
6076
- } catch (_ignoreError) {
6077
+ });
6078
+ } catch {
6077
6079
  await goNext();
6078
6080
  return;
6079
6081
  }
@@ -6099,106 +6101,101 @@ async function devMiddleware(compiler, options = {}) {
6099
6101
  sendError(500);
6100
6102
  }
6101
6103
  }), bufferOrStream.pipe(res), on_finished_default()(res, cleanup);
6102
- }
6103
- ready(context, processRequest);
6104
- };
6104
+ });
6105
+ });
6105
6106
  return instance.watch = ()=>{
6106
- if (compiler.watching) context.watching = compiler.watching;
6107
+ if (compiler.watching) watching = compiler.watching;
6107
6108
  else {
6108
- let errorHandler = (error)=>{
6109
+ let watchOptions = compilers.length > 1 ? compilers.map(({ options })=>options.watchOptions || {}) : compilers[0].options.watchOptions || {};
6110
+ watching = compiler.watch(watchOptions, (error)=>{
6109
6111
  error && (error.message?.includes('× Error:') && (error.message = error.message.replace('× Error:', '').trim()), logger.error(error));
6110
- };
6111
- if (compilers.length > 1) {
6112
- let watchOptions = compilers.map((childCompiler)=>childCompiler.options.watchOptions || {});
6113
- context.watching = compiler.watch(watchOptions, errorHandler);
6114
- } else {
6115
- let watchOptions = compilers[0].options.watchOptions || {};
6116
- context.watching = compiler.watch(watchOptions, errorHandler);
6117
- }
6112
+ });
6118
6113
  }
6119
6114
  }, instance.close = (callback = noop)=>{
6120
- context.watching?.close(callback);
6115
+ watching?.close(callback);
6121
6116
  }, instance;
6117
+ };
6118
+ var UNKNOWN_FUNCTION = '<unknown>', chromeRe = /^\s*at (.*?) ?\(((?:file|https?|blob|chrome-extension|native|eval|webpack|rsc|<anonymous>|\/|[a-z]:\\|\\\\).*?)(?::(\d+))?(?::(\d+))?\)?\s*$/i, chromeEvalRe = /\((\S*)(?::(\d+))(?::(\d+))\)/, winjsRe = /^\s*at (?:((?:\[object object\])?.+) )?\(?((?:file|ms-appx|https?|webpack|rsc|blob):.*?):(\d+)(?::(\d+))?\)?\s*$/i, geckoRe = /^\s*(.*?)(?:\((.*?)\))?(?:^|@)((?:file|https?|blob|chrome|webpack|rsc|resource|\[native).*?|[^@]*bundle)(?::(\d+))?(?::(\d+))?\s*$/i, geckoEvalRe = /(\S+) line (\d+)(?: > eval line \d+)* > eval/i, javaScriptCoreRe = /^\s*(?:([^@]*)(?:\((.*?)\))?@)?(\S.*?):(\d+)(?::(\d+))?\s*$/i, nodeRe = /^\s*at (?:((?:\[object object\])?[^\\/]+(?: \[as \S+\])?) )?\(?(.*?):(\d+)(?::(\d+))?\)?\s*$/i;
6119
+ async function mapSourceMapPosition(rawSourceMap, line, column) {
6120
+ let { default: { TraceMap, originalPositionFor } } = await import("../compiled/@jridgewell/trace-mapping/index.js");
6121
+ return originalPositionFor(new TraceMap(rawSourceMap), {
6122
+ line,
6123
+ column
6124
+ });
6122
6125
  }
6123
- async function getLocalhostResolvedAddress() {
6124
- let { promises: dns } = await import("node:dns"), [defaultLookup, explicitLookup] = await Promise.all([
6125
- dns.lookup('localhost'),
6126
- dns.lookup('localhost', {
6127
- verbatim: !0
6128
- })
6129
- ]);
6130
- return defaultLookup.family === explicitLookup.family && defaultLookup.address === explicitLookup.address ? void 0 : defaultLookup.address;
6131
- }
6132
- async function resolveHostname(host = 'localhost') {
6133
- if ('localhost' === host) {
6134
- let resolvedAddress = await getLocalhostResolvedAddress();
6135
- if (resolvedAddress) return resolvedAddress;
6136
- }
6137
- return void 0 === host || new Set([
6138
- '0.0.0.0',
6139
- '::',
6140
- '0000:0000:0000:0000:0000:0000:0000:0000'
6141
- ]).has(host) ? 'localhost' : host;
6142
- }
6143
- let compilationMiddleware_require = (0, external_node_module_.createRequire)(import.meta.url), getCompilationMiddleware = async ({ config, compiler, callbacks, environments, resolvedPort })=>{
6144
- var config1;
6145
- let writeToDiskValues, resolvedHost = await resolveHostname(config.server.host);
6146
- return applyToCompiler(compiler, (compiler, index)=>{
6147
- let environment = Object.values(environments).find((env)=>env.index === index);
6148
- if (!environment) return;
6149
- let token = environment.webSocketToken;
6150
- token && (!function({ config, compiler, token, resolvedHost, resolvedPort }) {
6151
- var devConfig;
6152
- let clientPaths;
6153
- if (!((compiler)=>{
6154
- let { target } = compiler.options;
6155
- return !!target && (Array.isArray(target) ? target.includes('web') : 'web' === target);
6156
- })(compiler)) return;
6157
- let clientPaths1 = (devConfig = config.dev, clientPaths = [], (devConfig.hmr || devConfig.liveReload) && (hmrClientPath || (hmrClientPath = compilationMiddleware_require.resolve('@rsbuild/core/client/hmr')), clientPaths.push(hmrClientPath), devConfig.client?.overlay && (overlayClientPath || (overlayClientPath = compilationMiddleware_require.resolve('@rsbuild/core/client/overlay')), clientPaths.push(overlayClientPath))), clientPaths);
6158
- if (!clientPaths1.length) return;
6159
- let clientConfig = {
6160
- ...config.dev.client
6126
+ let resolveSourceLocation = async (stack, fs, environments)=>{
6127
+ let parsed = stack.split('\n').reduce(function(stack, line) {
6128
+ var line1, parts, line2, parts1, line3, parts2, parseResult = function(line) {
6129
+ var parts = chromeRe.exec(line);
6130
+ if (!parts) return null;
6131
+ var isNative = parts[2] && 0 === parts[2].indexOf('native'), isEval = parts[2] && 0 === parts[2].indexOf('eval'), submatch = chromeEvalRe.exec(parts[2]);
6132
+ return isEval && null != submatch && (parts[2] = submatch[1], parts[3] = submatch[2], parts[4] = submatch[3]), {
6133
+ file: isNative ? null : parts[2],
6134
+ methodName: parts[1] || UNKNOWN_FUNCTION,
6135
+ arguments: isNative ? [
6136
+ parts[2]
6137
+ ] : [],
6138
+ lineNumber: parts[3] ? +parts[3] : null,
6139
+ column: parts[4] ? +parts[4] : null
6161
6140
  };
6162
- for (let clientPath of ('<port>' === clientConfig.port && (clientConfig.port = resolvedPort), new compiler.webpack.DefinePlugin({
6163
- RSBUILD_WEB_SOCKET_TOKEN: JSON.stringify(token),
6164
- RSBUILD_CLIENT_CONFIG: JSON.stringify(clientConfig),
6165
- RSBUILD_SERVER_HOST: JSON.stringify(resolvedHost),
6166
- RSBUILD_SERVER_PORT: JSON.stringify(resolvedPort),
6167
- RSBUILD_DEV_LIVE_RELOAD: config.dev.liveReload
6168
- }).apply(compiler), clientPaths1))new compiler.webpack.EntryPlugin(compiler.context, clientPath, {
6169
- name: void 0
6170
- }).apply(compiler);
6171
- }({
6172
- token,
6173
- config: environment.config,
6174
- compiler,
6175
- resolvedHost,
6176
- resolvedPort
6177
- }), (({ compiler, token, callbacks: { onDone, onInvalid } })=>{
6178
- if (((compiler)=>{
6179
- let { target } = compiler.options;
6180
- return !!target && (Array.isArray(target) ? target.includes('node') : 'node' === target);
6181
- })(compiler)) return;
6182
- let { compile, invalid, done } = compiler.hooks;
6183
- compile.tap('rsbuild-dev-server', ()=>{
6184
- onInvalid(token);
6185
- }), invalid.tap('rsbuild-dev-server', (fileName)=>{
6186
- onInvalid(token, fileName);
6187
- }), done.tap('rsbuild-dev-server', (stats)=>{
6188
- onDone(token, stats);
6189
- });
6190
- })({
6191
- compiler,
6192
- callbacks,
6193
- token
6194
- }));
6195
- }), devMiddleware(compiler, {
6196
- publicPath: '/',
6197
- writeToDisk: (config1 = config.dev, 1 === new Set(writeToDiskValues = Object.values(environments).map((env)=>env.config.dev.writeToDisk)).size ? writeToDiskValues[0] : (filePath, name)=>{
6198
- let { writeToDisk } = config1;
6199
- return name && environments[name] && (writeToDisk = environments[name].config.dev.writeToDisk ?? writeToDisk), 'function' == typeof writeToDisk ? writeToDisk(filePath) : writeToDisk;
6200
- })
6201
- });
6141
+ }(line) || (line1 = line, (parts = winjsRe.exec(line1)) ? {
6142
+ file: parts[2],
6143
+ methodName: parts[1] || UNKNOWN_FUNCTION,
6144
+ arguments: [],
6145
+ lineNumber: +parts[3],
6146
+ column: parts[4] ? +parts[4] : null
6147
+ } : null) || function(line) {
6148
+ var parts = geckoRe.exec(line);
6149
+ if (!parts) return null;
6150
+ var isEval = parts[3] && parts[3].indexOf(' > eval') > -1, submatch = geckoEvalRe.exec(parts[3]);
6151
+ return isEval && null != submatch && (parts[3] = submatch[1], parts[4] = submatch[2], parts[5] = null), {
6152
+ file: parts[3],
6153
+ methodName: parts[1] || UNKNOWN_FUNCTION,
6154
+ arguments: parts[2] ? parts[2].split(',') : [],
6155
+ lineNumber: parts[4] ? +parts[4] : null,
6156
+ column: parts[5] ? +parts[5] : null
6157
+ };
6158
+ }(line) || (line2 = line, (parts1 = nodeRe.exec(line2)) ? {
6159
+ file: parts1[2],
6160
+ methodName: parts1[1] || UNKNOWN_FUNCTION,
6161
+ arguments: [],
6162
+ lineNumber: +parts1[3],
6163
+ column: parts1[4] ? +parts1[4] : null
6164
+ } : null) || (line3 = line, (parts2 = javaScriptCoreRe.exec(line3)) ? {
6165
+ file: parts2[3],
6166
+ methodName: parts2[1] || UNKNOWN_FUNCTION,
6167
+ arguments: [],
6168
+ lineNumber: +parts2[4],
6169
+ column: parts2[5] ? +parts2[5] : null
6170
+ } : null);
6171
+ return parseResult && stack.push(parseResult), stack;
6172
+ }, []);
6173
+ if (!parsed.length) return;
6174
+ let frame = parsed.find((frame)=>null !== frame.file && null !== frame.column && null !== frame.lineNumber && SCRIPT_REGEX.test(frame.file));
6175
+ if (!frame) return;
6176
+ let { file, column, lineNumber } = frame, sourceMapInfo = getFileFromUrl(`${file}.map`, fs, environments);
6177
+ if (!sourceMapInfo || 'errorCode' in sourceMapInfo) return;
6178
+ let readFile = external_node_util_promisify(fs.readFile);
6179
+ try {
6180
+ let sourceMap = await readFile(sourceMapInfo.filename);
6181
+ if (sourceMap) return await mapSourceMapPosition(sourceMap.toString(), lineNumber, column);
6182
+ } catch (error) {
6183
+ error instanceof Error && logger.debug(`failed to map source map position: ${error.message}`);
6184
+ }
6185
+ }, formatErrorLocation = async (stack, context, fs)=>{
6186
+ let parsed = await resolveSourceLocation(stack, fs, context.environments);
6187
+ if (!parsed) return;
6188
+ let { source, line, column } = parsed;
6189
+ if (!source) return;
6190
+ let rawLocation = external_node_path_.default.relative(context.rootPath, source);
6191
+ return null !== line && (rawLocation += null === column ? `:${line}` : `:${line}:${column}`), rawLocation;
6192
+ }, formatBrowserErrorLog = async (message, context, fs)=>{
6193
+ let log = `${picocolors.cyan('[browser]')} ${picocolors.red(message.message)}`;
6194
+ if (message.stack) {
6195
+ let rawLocation = await formatErrorLocation(message.stack, context, fs);
6196
+ rawLocation && (log += picocolors.dim(` (${rawLocation})`));
6197
+ }
6198
+ return log;
6202
6199
  }, styles = {
6203
6200
  1: 'font-weight:bold',
6204
6201
  2: 'opacity:0.5',
@@ -6236,17 +6233,19 @@ class SocketServer {
6236
6233
  wsServer;
6237
6234
  socketsMap = new Map();
6238
6235
  options;
6236
+ context;
6239
6237
  stats;
6240
6238
  initialChunks;
6241
6239
  heartbeatTimer = null;
6242
- environments;
6243
- constructor(options, environments){
6244
- this.options = options, this.stats = {}, this.initialChunks = {}, this.environments = environments;
6240
+ getOutputFileSystem;
6241
+ reportedBrowserLogs = new Set();
6242
+ constructor(context, options, getOutputFileSystem){
6243
+ this.options = options, this.stats = {}, this.initialChunks = {}, this.context = context, this.getOutputFileSystem = getOutputFileSystem;
6245
6244
  }
6246
6245
  upgrade = (req, socket, head)=>{
6247
6246
  if (!this.wsServer.shouldHandle(req)) return;
6248
6247
  let query = parseQueryString(req);
6249
- Object.values(this.environments).map((env)=>env.webSocketToken).includes(query.token) ? this.wsServer.handleUpgrade(req, socket, head, (connection)=>{
6248
+ Object.values(this.context.environments).map((env)=>env.webSocketToken).includes(query.token) ? this.wsServer.handleUpgrade(req, socket, head, (connection)=>{
6250
6249
  this.wsServer.emit('connection', connection, req);
6251
6250
  }) : socket.destroy();
6252
6251
  };
@@ -6270,8 +6269,8 @@ class SocketServer {
6270
6269
  this.onConnect(socket, query.token);
6271
6270
  });
6272
6271
  }
6273
- updateStats(stats, token) {
6274
- this.stats[token] = stats, this.socketsMap.size && this.sendStats({
6272
+ onBuildDone(stats, token) {
6273
+ this.stats[token] = stats, this.reportedBrowserLogs.clear(), this.socketsMap.size && this.sendStats({
6275
6274
  token
6276
6275
  });
6277
6276
  }
@@ -6289,7 +6288,7 @@ class SocketServer {
6289
6288
  for (let sockets of this.socketsMap.values())sockets.forEach((socket)=>{
6290
6289
  socket.close();
6291
6290
  });
6292
- return this.stats = {}, this.initialChunks = {}, this.socketsMap.clear(), new Promise((resolve, reject)=>{
6291
+ return this.stats = {}, this.initialChunks = {}, this.socketsMap.clear(), this.reportedBrowserLogs.clear(), new Promise((resolve, reject)=>{
6293
6292
  this.wsServer.close((err)=>{
6294
6293
  err ? reject(err) : resolve();
6295
6294
  });
@@ -6298,6 +6297,14 @@ class SocketServer {
6298
6297
  onConnect(socket, token) {
6299
6298
  socket.isAlive = !0, socket.on('pong', ()=>{
6300
6299
  socket.isAlive = !0;
6300
+ }), socket.on('message', async (data)=>{
6301
+ try {
6302
+ let message = JSON.parse('string' == typeof data ? data : data.toString());
6303
+ if ('client-error' === message.type && 'rspack' === this.context.bundlerType && !this.context.buildState.hasErrors) {
6304
+ let log = await formatBrowserErrorLog(message, this.context, this.getOutputFileSystem());
6305
+ this.reportedBrowserLogs.has(log) || (this.reportedBrowserLogs.add(log), logger.error(log));
6306
+ }
6307
+ } catch {}
6301
6308
  });
6302
6309
  let sockets = this.socketsMap.get(token);
6303
6310
  sockets || (sockets = new Set(), this.socketsMap.set(token, sockets)), sockets.add(socket), socket.on('close', ()=>{
@@ -6529,17 +6536,17 @@ class SocketServer {
6529
6536
  socket.readyState === socket.OPEN && socket.send(message);
6530
6537
  }
6531
6538
  }
6532
- class CompilationManager {
6539
+ class BuildManager {
6533
6540
  middleware;
6534
6541
  outputFileSystem;
6535
- config;
6542
+ socketServer;
6536
6543
  compiler;
6537
- environments;
6544
+ config;
6538
6545
  publicPaths;
6539
- socketServer;
6540
6546
  resolvedPort;
6541
- constructor({ config, compiler, publicPaths, resolvedPort, environments }){
6542
- this.config = config, this.compiler = compiler, this.environments = environments, this.publicPaths = publicPaths, this.resolvedPort = resolvedPort, this.outputFileSystem = node_fs, this.socketServer = new SocketServer(config.dev, environments);
6547
+ context;
6548
+ constructor({ config, context, compiler, publicPaths, resolvedPort }){
6549
+ this.config = config, this.context = context, this.compiler = compiler, this.publicPaths = publicPaths, this.resolvedPort = resolvedPort, this.outputFileSystem = node_fs, this.socketServer = new SocketServer(context, config.dev, ()=>this.outputFileSystem);
6543
6550
  }
6544
6551
  async init() {
6545
6552
  await this.setupCompilationMiddleware(), await this.socketServer.prepare();
@@ -6562,20 +6569,11 @@ class CompilationManager {
6562
6569
  }
6563
6570
  readFileSync = (fileName)=>'readFileSync' in this.outputFileSystem ? this.outputFileSystem.readFileSync(fileName, 'utf-8') : node_fs.readFileSync(fileName, 'utf-8');
6564
6571
  async setupCompilationMiddleware() {
6565
- let { config, publicPaths, environments } = this, middleware = await getCompilationMiddleware({
6572
+ let { config, context, publicPaths } = this, middleware = await assetsMiddleware({
6566
6573
  config,
6574
+ context,
6567
6575
  compiler: this.compiler,
6568
- callbacks: {
6569
- onInvalid: (token, fileName)=>{
6570
- if ('string' == typeof fileName && fileName.endsWith('.html')) return void this.socketServer.sockWrite({
6571
- type: 'static-changed'
6572
- }, token);
6573
- },
6574
- onDone: (token, stats)=>{
6575
- this.socketServer.updateStats(stats, token);
6576
- }
6577
- },
6578
- environments,
6576
+ socketServer: this.socketServer,
6579
6577
  resolvedPort: this.resolvedPort
6580
6578
  }), { base } = config.server, assetPrefixes = publicPaths.map(getPathnameFromUrl).map((prefix)=>base && '/' !== base ? stripBase(prefix, base) : prefix), wrapper = (req, res, next)=>{
6581
6579
  let { url } = req, assetPrefix = url && assetPrefixes.find((prefix)=>url.startsWith(prefix));
@@ -6586,6 +6584,59 @@ class CompilationManager {
6586
6584
  wrapper.close = middleware.close, wrapper.watch = middleware.watch, this.middleware = wrapper;
6587
6585
  }
6588
6586
  }
6587
+ let isCliShortcutsEnabled = (config)=>config.dev.cliShortcuts && isTTY('stdin');
6588
+ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls, restartServer, customShortcuts }) {
6589
+ let shortcuts = [
6590
+ {
6591
+ key: 'c',
6592
+ description: `${picocolors.bold('c + enter')} ${picocolors.dim('clear console')}`,
6593
+ action: ()=>{
6594
+ console.clear();
6595
+ }
6596
+ },
6597
+ {
6598
+ key: 'o',
6599
+ description: `${picocolors.bold('o + enter')} ${picocolors.dim('open in browser')}`,
6600
+ action: openPage
6601
+ },
6602
+ {
6603
+ key: 'q',
6604
+ description: `${picocolors.bold('q + enter')} ${picocolors.dim('quit process')}`,
6605
+ action: async ()=>{
6606
+ try {
6607
+ await closeServer();
6608
+ } finally{
6609
+ process.exit(0);
6610
+ }
6611
+ }
6612
+ },
6613
+ restartServer ? {
6614
+ key: 'r',
6615
+ description: `${picocolors.bold('r + enter')} ${picocolors.dim('restart server')}`,
6616
+ action: restartServer
6617
+ } : null,
6618
+ {
6619
+ key: 'u',
6620
+ description: `${picocolors.bold('u + enter')} ${picocolors.dim('show urls')}`,
6621
+ action: printUrls
6622
+ }
6623
+ ].filter(Boolean);
6624
+ if (customShortcuts && !Array.isArray(shortcuts = customShortcuts(shortcuts))) throw Error(`${picocolors.dim('[rsbuild:config]')} ${picocolors.yellow('dev.cliShortcuts')} option must return an array of shortcuts.`);
6625
+ help && logger.log(!0 === help ? ` ➜ ${picocolors.dim('press')} ${picocolors.bold('h + enter')} ${picocolors.dim('to show shortcuts')}\n` : ` ➜ ${help}\n`);
6626
+ let { createInterface } = await import("node:readline"), rl = createInterface({
6627
+ input: process.stdin
6628
+ });
6629
+ return rl.on('line', (input)=>{
6630
+ if ('h' === input) {
6631
+ let message = `\n ${picocolors.bold(picocolors.blue('Shortcuts:'))}\n`;
6632
+ for (let shortcut of shortcuts)message += ` ${shortcut.description}\n`;
6633
+ logger.log(message);
6634
+ }
6635
+ for (let shortcut of shortcuts)if (input === shortcut.key) return void shortcut.action();
6636
+ }), ()=>{
6637
+ rl.close();
6638
+ };
6639
+ }
6589
6640
  let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xml/i, gzipMiddleware = ({ filter, level = node_zlib.constants.Z_BEST_SPEED } = {})=>(req, res, next)=>{
6590
6641
  let gzip, writeHeadStatus;
6591
6642
  if (filter && !filter(req, res)) return void next();
@@ -6752,7 +6803,7 @@ let faviconFallbackMiddleware = (req, res, next)=>{
6752
6803
  for (let middleware of proxyMiddlewares)'function' == typeof middleware.upgrade && middleware.upgrade(req, socket, head);
6753
6804
  }
6754
6805
  };
6755
- }, applyDefaultMiddlewares = async ({ config, compilationManager, context, devServerAPI, middlewares, pwd, postCallbacks })=>{
6806
+ }, applyDefaultMiddlewares = async ({ config, buildManager, context, devServerAPI, middlewares, pwd, postCallbacks })=>{
6756
6807
  let upgradeEvents = [], { server } = config;
6757
6808
  if (server.cors) {
6758
6809
  let { default: corsMiddleware } = await import("../compiled/cors/index.js");
@@ -6767,8 +6818,8 @@ let faviconFallbackMiddleware = (req, res, next)=>{
6767
6818
  for (let middleware of (upgradeEvents.push(upgrade), proxyMiddlewares))middlewares.push(middleware);
6768
6819
  }
6769
6820
  let { compress } = server;
6770
- if (compress && middlewares.push(gzipMiddleware('object' == typeof compress ? compress : void 0)), 'dev' === context.action && 'rspack' === context.bundlerType && compilationManager) {
6771
- let { compiler } = compilationManager;
6821
+ if (compress && middlewares.push(gzipMiddleware('object' == typeof compress ? compress : void 0)), 'dev' === context.action && 'rspack' === context.bundlerType && buildManager) {
6822
+ let { compiler } = buildManager;
6772
6823
  (helpers_isMultiCompiler(compiler) ? compiler.compilers.some((childCompiler)=>childCompiler.options.experiments?.lazyCompilation || childCompiler.options.lazyCompilation) : compiler.options.experiments?.lazyCompilation || compiler.options.lazyCompilation) && middlewares.push(rspack_rspack.experiments.lazyCompilationMiddleware(compiler));
6773
6824
  }
6774
6825
  server.base && '/' !== server.base && middlewares.push(getBaseMiddleware({
@@ -6838,25 +6889,25 @@ let faviconFallbackMiddleware = (req, res, next)=>{
6838
6889
  }
6839
6890
  })({
6840
6891
  environments: devServerAPI.environments
6841
- })), compilationManager && (middlewares.push(compilationManager.middleware), upgradeEvents.push(compilationManager.socketServer.upgrade), middlewares.push((req, res, next)=>{
6892
+ })), buildManager && (middlewares.push(buildManager.middleware), upgradeEvents.push(buildManager.socketServer.upgrade), middlewares.push((req, res, next)=>{
6842
6893
  req.url?.endsWith('.hot-update.json') && 'OPTIONS' !== req.method ? (res.statusCode = 404, res.end()) : next();
6843
- })), compilationManager && middlewares.push((({ distPath, compilationManager })=>async (req, res, next)=>{
6894
+ })), buildManager && middlewares.push((({ distPath, buildManager })=>async (req, res, next)=>{
6844
6895
  if (!maybeHTMLRequest(req)) return void next();
6845
6896
  let pathname = req.url.replace(postfixRE, ''), rewrite = (newUrl)=>{
6846
- req.url = newUrl, compilationManager.middleware(req, res, (...args)=>{
6897
+ req.url = newUrl, buildManager.middleware(req, res, (...args)=>{
6847
6898
  next(...args);
6848
6899
  });
6849
6900
  };
6850
6901
  if (pathname.endsWith('/')) {
6851
6902
  let newUrl = `${pathname}index.html`, filePath = external_node_path_.default.join(distPath, newUrl);
6852
- if (await middlewares_isFileExists(filePath, compilationManager.outputFileSystem)) return void rewrite(newUrl);
6903
+ if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) return void rewrite(newUrl);
6853
6904
  } else if (!external_node_path_.default.extname(pathname)) {
6854
6905
  let newUrl = `${pathname}.html`, filePath = external_node_path_.default.join(distPath, newUrl);
6855
- if (await middlewares_isFileExists(filePath, compilationManager.outputFileSystem)) return void rewrite(newUrl);
6906
+ if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) return void rewrite(newUrl);
6856
6907
  }
6857
6908
  next();
6858
6909
  })({
6859
- compilationManager,
6910
+ buildManager,
6860
6911
  distPath: context.distPath
6861
6912
  })), normalizePublicDirs(server?.publicDir))){
6862
6913
  let { default: sirv } = await import("../compiled/sirv/index.js"), { name } = publicDir, assetMiddleware = sirv((0, external_node_path_.isAbsolute)(name) ? name : (0, external_node_path_.join)(pwd, name), {
@@ -6866,28 +6917,28 @@ let faviconFallbackMiddleware = (req, res, next)=>{
6866
6917
  middlewares.push(assetMiddleware);
6867
6918
  }
6868
6919
  for (let callback of postCallbacks)callback();
6869
- return compilationManager && middlewares.push((({ htmlFallback, distPath, compilationManager })=>async (req, res, next)=>{
6920
+ return buildManager && middlewares.push((({ htmlFallback, distPath, buildManager })=>async (req, res, next)=>{
6870
6921
  if (!maybeHTMLRequest(req) || '/favicon.ico' === req.url || 'index' !== htmlFallback) return void next();
6871
6922
  let filePath = external_node_path_.default.join(distPath, 'index.html');
6872
- if (await middlewares_isFileExists(filePath, compilationManager.outputFileSystem)) {
6923
+ if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) {
6873
6924
  let newUrl = '/index.html';
6874
- 'verbose' === logger.level && logger.debug(` ${req.method} ${req.url} ${picocolors.yellow('fallback to')} ${newUrl}`), req.url = newUrl, compilationManager.middleware(req, res, (...args)=>{
6925
+ 'verbose' === logger.level && logger.debug(` ${req.method} ${req.url} ${picocolors.yellow('fallback to')} ${newUrl}`), req.url = newUrl, buildManager.middleware(req, res, (...args)=>{
6875
6926
  next(...args);
6876
6927
  });
6877
6928
  return;
6878
6929
  }
6879
6930
  next();
6880
6931
  })({
6881
- compilationManager,
6932
+ buildManager,
6882
6933
  distPath: context.distPath,
6883
6934
  htmlFallback: server.htmlFallback
6884
- })), server.historyApiFallback && (middlewares.push(historyApiFallbackMiddleware(!0 === server.historyApiFallback ? {} : server.historyApiFallback)), compilationManager?.middleware && middlewares.push(compilationManager.middleware)), middlewares.push(faviconFallbackMiddleware), {
6935
+ })), server.historyApiFallback && (middlewares.push(historyApiFallbackMiddleware(!0 === server.historyApiFallback ? {} : server.historyApiFallback)), buildManager?.middleware && middlewares.push(buildManager.middleware)), middlewares.push(faviconFallbackMiddleware), {
6885
6936
  onUpgrade: (...args)=>{
6886
6937
  for (let cb of upgradeEvents)cb(...args);
6887
6938
  }
6888
6939
  };
6889
6940
  }, getDevMiddlewares = async (options)=>{
6890
- let middlewares = [], { compilationManager } = options;
6941
+ let middlewares = [], { buildManager } = options;
6891
6942
  'verbose' === logger.level && middlewares.push(getRequestLoggerMiddleware());
6892
6943
  let { before, after } = ((config, devServerAPI)=>{
6893
6944
  let setupMiddlewares = config.dev.setupMiddlewares || [], serverOptions = pick(devServerAPI, [
@@ -6910,7 +6961,7 @@ let faviconFallbackMiddleware = (req, res, next)=>{
6910
6961
  });
6911
6962
  return middlewares.push(...after), {
6912
6963
  close: async ()=>{
6913
- await compilationManager?.close();
6964
+ await buildManager?.close();
6914
6965
  },
6915
6966
  onUpgrade,
6916
6967
  middlewares
@@ -7186,14 +7237,14 @@ let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>{
7186
7237
  return createServer(middlewares);
7187
7238
  };
7188
7239
  async function setupWatchFiles(options) {
7189
- let { config, root, compilationManager } = options, { hmr, liveReload } = config.dev;
7190
- if (!hmr && !liveReload || !compilationManager) return;
7191
- let closeDevFilesWatcher = await watchDevFiles(config.dev, compilationManager, root), serverFilesWatcher = await function(serverConfig, compilationManager, root) {
7240
+ let { config, root, buildManager } = options, { hmr, liveReload } = config.dev;
7241
+ if (!hmr && !liveReload || !buildManager) return;
7242
+ let closeDevFilesWatcher = await watchDevFiles(config.dev, buildManager, root), serverFilesWatcher = await function(serverConfig, buildManager, root) {
7192
7243
  let publicDirs = normalizePublicDirs(serverConfig.publicDir);
7193
7244
  if (!publicDirs.length) return;
7194
7245
  let watchPaths = publicDirs.filter((item)=>item.watch).map((item)=>item.name);
7195
- if (watchPaths.length) return startWatchFiles(prepareWatchOptions(watchPaths), compilationManager, root);
7196
- }(config.server, compilationManager, root);
7246
+ if (watchPaths.length) return startWatchFiles(prepareWatchOptions(watchPaths), buildManager, root);
7247
+ }(config.server, buildManager, root);
7197
7248
  return {
7198
7249
  async close () {
7199
7250
  await Promise.all([
@@ -7203,12 +7254,12 @@ async function setupWatchFiles(options) {
7203
7254
  }
7204
7255
  };
7205
7256
  }
7206
- async function watchDevFiles(devConfig, compilationManager, root) {
7257
+ async function watchDevFiles(devConfig, buildManager, root) {
7207
7258
  let { watchFiles } = devConfig;
7208
7259
  if (!watchFiles) return;
7209
7260
  let watchers = [];
7210
7261
  for (let { paths, options, type } of helpers_castArray(watchFiles)){
7211
- let watchOptions = prepareWatchOptions(paths, options, type), watcher = await startWatchFiles(watchOptions, compilationManager, root);
7262
+ let watchOptions = prepareWatchOptions(paths, options, type), watcher = await startWatchFiles(watchOptions, buildManager, root);
7212
7263
  watcher && watchers.push(watcher);
7213
7264
  }
7214
7265
  return async ()=>{
@@ -7236,11 +7287,11 @@ async function createChokidar(pathOrGlobs, root, options) {
7236
7287
  }
7237
7288
  return chokidar.watch(Array.from(watchFiles), options);
7238
7289
  }
7239
- async function startWatchFiles({ paths, options, type = 'reload-page' }, compilationManager, root) {
7290
+ async function startWatchFiles({ paths, options, type = 'reload-page' }, buildManager, root) {
7240
7291
  if ('reload-page' !== type) return;
7241
7292
  let watcher = await createChokidar(paths, root, options);
7242
7293
  return watcher.on('change', ()=>{
7243
- compilationManager.socketServer.sockWrite({
7294
+ buildManager.socketServer.sockWrite({
7244
7295
  type: 'static-changed'
7245
7296
  });
7246
7297
  }), watcher;
@@ -7274,14 +7325,14 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
7274
7325
  });
7275
7326
  let publicPaths = helpers_isMultiCompiler(compiler) ? compiler.compilers.map(getPublicPathFromCompiler) : [
7276
7327
  getPublicPathFromCompiler(compiler)
7277
- ], compilationManager = new CompilationManager({
7328
+ ], buildManager = new BuildManager({
7329
+ context,
7278
7330
  config,
7279
7331
  compiler,
7280
7332
  publicPaths: publicPaths,
7281
- resolvedPort: port,
7282
- environments: context.environments
7333
+ resolvedPort: port
7283
7334
  });
7284
- return await compilationManager.init(), compilationManager;
7335
+ return await buildManager.init(), buildManager;
7285
7336
  }, protocol = https ? 'https' : 'http', urls = await getAddressUrls({
7286
7337
  protocol,
7287
7338
  port,
@@ -7330,21 +7381,21 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
7330
7381
  name,
7331
7382
  {
7332
7383
  getStats: async ()=>{
7333
- if (!compilationManager) throw Error(`${picocolors.dim('[rsbuild:server]')} Can not call ${picocolors.yellow('getStats')} when ${picocolors.yellow('runCompile')} is false`);
7384
+ if (!buildManager) throw Error(`${picocolors.dim('[rsbuild:server]')} Can not call ${picocolors.yellow('getStats')} when ${picocolors.yellow('runCompile')} is false`);
7334
7385
  return await waitLastCompileDone, lastStats[environment.index];
7335
7386
  },
7336
7387
  context: environment,
7337
7388
  loadBundle: async (entryName)=>{
7338
- if (!compilationManager) throw Error(`${picocolors.dim('[rsbuild:server]')} Can not call ${picocolors.yellow('loadBundle')} when ${picocolors.yellow('runCompile')} is false`);
7389
+ if (!buildManager) throw Error(`${picocolors.dim('[rsbuild:server]')} Can not call ${picocolors.yellow('loadBundle')} when ${picocolors.yellow('runCompile')} is false`);
7339
7390
  return await waitLastCompileDone, cacheableLoadBundle(lastStats[environment.index], entryName, {
7340
- readFileSync: compilationManager.readFileSync,
7391
+ readFileSync: buildManager.readFileSync,
7341
7392
  environment
7342
7393
  });
7343
7394
  },
7344
7395
  getTransformedHtml: async (entryName)=>{
7345
- if (!compilationManager) throw Error(`${picocolors.dim('[rsbuild:server]')} Can not call ${picocolors.yellow('getTransformedHtml')} when ${picocolors.yellow('runCompile')} is false`);
7396
+ if (!buildManager) throw Error(`${picocolors.dim('[rsbuild:server]')} Can not call ${picocolors.yellow('getTransformedHtml')} when ${picocolors.yellow('runCompile')} is false`);
7346
7397
  return await waitLastCompileDone, cacheableTransformedHtml(lastStats[environment.index], entryName, {
7347
- readFileSync: compilationManager.readFileSync,
7398
+ readFileSync: buildManager.readFileSync,
7348
7399
  environment
7349
7400
  });
7350
7401
  }
@@ -7357,7 +7408,7 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
7357
7408
  middlewares,
7358
7409
  environments: environmentAPI,
7359
7410
  httpServer,
7360
- sockWrite: (type, data)=>compilationManager?.socketServer.sockWrite({
7411
+ sockWrite: (type, data)=>buildManager?.socketServer.sockWrite({
7361
7412
  type,
7362
7413
  data
7363
7414
  }),
@@ -7398,20 +7449,20 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
7398
7449
  environments: context.environments
7399
7450
  })).filter((item)=>'function' == typeof item);
7400
7451
  runCompile ? context.hooks.onBeforeCreateCompiler.tap(beforeCreateCompiler) : await beforeCreateCompiler();
7401
- let compilationManager = runCompile ? await startCompile() : void 0;
7452
+ let buildManager = runCompile ? await startCompile() : void 0;
7402
7453
  for (let item of (fileWatcher = await setupWatchFiles({
7403
7454
  config,
7404
- compilationManager,
7455
+ buildManager,
7405
7456
  root
7406
7457
  }), (devMiddlewares = await getDevMiddlewares({
7407
7458
  pwd: root,
7408
- compilationManager,
7459
+ buildManager,
7409
7460
  config,
7410
7461
  devServerAPI,
7411
7462
  context,
7412
7463
  postCallbacks
7413
7464
  })).middlewares))Array.isArray(item) ? middlewares.use(...item) : middlewares.use(item);
7414
- return compilationManager?.watch(), logger.debug('create dev server done'), devServerAPI;
7465
+ return buildManager?.watch(), logger.debug('create dev server done'), devServerAPI;
7415
7466
  }
7416
7467
  let rspackProvider = ({ context, pluginManager, rsbuildOptions })=>{
7417
7468
  let createCompiler = async ()=>(await createCompiler_createCompiler({
@@ -7607,7 +7658,7 @@ async function createRsbuild(options = {}) {
7607
7658
  let plugins, envs = options.loadEnv ? loadEnv({
7608
7659
  cwd: options.cwd,
7609
7660
  ...'boolean' == typeof options.loadEnv ? {} : options.loadEnv
7610
- }) : null, config = isFunction(options.rsbuildConfig) ? await options.rsbuildConfig() : options.rsbuildConfig || {};
7661
+ }) : null, configOrFactory = options.config ?? options.rsbuildConfig, config = isFunction(configOrFactory) ? await configOrFactory() : configOrFactory || {};
7611
7662
  config.logLevel && !isDebug() && (logger.level = config.logLevel), function(config, envs) {
7612
7663
  if (null !== envs && (config.source ||= {}, config.source.define = {
7613
7664
  ...envs.publicVars,
@@ -9561,7 +9612,7 @@ async function init_init({ cliOptions, isRestart, isBuildWatch = !1 }) {
9561
9612
  var envDir;
9562
9613
  let cwd = process.cwd(), root = commonOpts.root ? ensureAbsolutePath(cwd, commonOpts.root) : cwd, rsbuild = await createRsbuild({
9563
9614
  cwd: root,
9564
- rsbuildConfig: ()=>init_loadConfig(root),
9615
+ config: ()=>init_loadConfig(root),
9565
9616
  environment: commonOpts.environment,
9566
9617
  loadEnv: !1 !== commonOpts.env && {
9567
9618
  cwd: (envDir = commonOpts.envDir) ? external_node_path_.default.isAbsolute(envDir) ? envDir : external_node_path_.default.join(root, envDir) : root,
@@ -9662,11 +9713,11 @@ function runCLI() {
9662
9713
  }
9663
9714
  !function() {
9664
9715
  let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
9665
- logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v1.5.12\n`);
9716
+ logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v1.5.13\n`);
9666
9717
  }();
9667
9718
  try {
9668
9719
  let cli, devDescription, devCommand, buildCommand, previewCommand, inspectCommand;
9669
- (cli = ((name = "")=>new CAC(name))('rsbuild')).version("1.5.12"), cli.option('--base <base>', 'Set the base path of the server').option('-c, --config <config>', 'Set the configuration file (relative or absolute path)').option('--config-loader <loader>', 'Set the config file loader (auto | jiti | native)', {
9720
+ (cli = ((name = "")=>new CAC(name))('rsbuild')).version("1.5.13"), cli.option('--base <base>', 'Set the base path of the server').option('-c, --config <config>', 'Set the configuration file (relative or absolute path)').option('--config-loader <loader>', 'Set the config file loader (auto | jiti | native)', {
9670
9721
  default: 'jiti'
9671
9722
  }).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', {
9672
9723
  type: [
@@ -9723,5 +9774,5 @@ function runCLI() {
9723
9774
  logger.error('Failed to start Rsbuild CLI.'), logger.error(err);
9724
9775
  }
9725
9776
  }
9726
- let src_version = "1.5.12";
9777
+ let src_version = "1.5.13";
9727
9778
  export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig_loadConfig as loadConfig, loadEnv, logger, mergeRsbuildConfig, rspack_rspack as rspack, runCLI, src_version as version };