@rsbuild/core 2.0.0-beta.3 → 2.0.0-beta.5

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 (40) hide show
  1. package/compiled/css-loader/index.js +2 -2
  2. package/compiled/css-loader/package.json +1 -1
  3. package/compiled/html-rspack-plugin/index.js +14 -14
  4. package/compiled/jiti/LICENSE +21 -0
  5. package/compiled/jiti/README.md +243 -0
  6. package/compiled/jiti/dist/babel.cjs +46699 -0
  7. package/compiled/jiti/dist/jiti.cjs +4842 -0
  8. package/compiled/jiti/lib/jiti-cli.mjs +19 -0
  9. package/compiled/jiti/lib/jiti-hooks.mjs +89 -0
  10. package/compiled/jiti/lib/jiti-native.mjs +76 -0
  11. package/compiled/jiti/lib/jiti-register.d.mts +1 -0
  12. package/compiled/jiti/lib/jiti-register.mjs +2 -0
  13. package/compiled/jiti/lib/jiti.cjs +24 -0
  14. package/compiled/jiti/lib/jiti.d.cts +8 -0
  15. package/compiled/jiti/lib/jiti.d.mts +8 -0
  16. package/compiled/jiti/lib/jiti.mjs +23 -0
  17. package/compiled/jiti/lib/types.d.ts +363 -0
  18. package/compiled/jiti/package.json +133 -0
  19. package/compiled/postcss-loader/index.js +10 -9
  20. package/compiled/postcss-loader/package.json +1 -1
  21. package/dist/131.js +192 -202
  22. package/dist/launch-editor-middleware.js +16 -11
  23. package/dist/manifest-plugin.js +5 -5
  24. package/dist-types/hooks.d.ts +3 -3
  25. package/dist-types/index.d.ts +3 -2
  26. package/dist-types/server/cliShortcuts.d.ts +1 -0
  27. package/dist-types/server/devMiddlewares.d.ts +4 -6
  28. package/dist-types/server/devServer.d.ts +8 -42
  29. package/dist-types/server/helper.d.ts +47 -15
  30. package/dist-types/server/middlewares.d.ts +1 -2
  31. package/dist-types/server/open.d.ts +2 -2
  32. package/dist-types/server/previewServer.d.ts +4 -0
  33. package/dist-types/server/serverSetup.d.ts +2 -0
  34. package/dist-types/server/socketServer.d.ts +1 -0
  35. package/dist-types/types/config.d.ts +50 -1
  36. package/dist-types/types/hooks.d.ts +13 -3
  37. package/dist-types/types/plugin.d.ts +5 -5
  38. package/dist-types/types/rsbuild.d.ts +4 -4
  39. package/package.json +9 -9
  40. package/dist-types/server/prodServer.d.ts +0 -24
package/dist/131.js CHANGED
@@ -904,7 +904,7 @@ __webpack_require__.add({
904
904
  return loaded && '__esModule' in loaded ? loaded.default : loaded;
905
905
  }
906
906
  if (void 0 === jiti) try {
907
- jiti = (await import("jiti")).default;
907
+ jiti = (await import("../compiled/jiti/lib/jiti.mjs")).default;
908
908
  } catch (error) {
909
909
  importError.push(error);
910
910
  }
@@ -2270,7 +2270,7 @@ async function helpers_hash(data) {
2270
2270
  }
2271
2271
  let compiler_isMultiCompiler = (compiler)=>'compilers' in compiler && Array.isArray(compiler.compilers), getPublicPathFromCompiler = (compiler)=>{
2272
2272
  let { publicPath } = compiler.options.output;
2273
- return 'string' == typeof publicPath ? 'auto' === publicPath ? '' : publicPath.endsWith('/') ? publicPath : `${publicPath}/` : DEFAULT_ASSET_PREFIX;
2273
+ return 'string' == typeof publicPath ? 'auto' === publicPath || '' === publicPath ? '' : publicPath.endsWith('/') ? publicPath : `${publicPath}/` : DEFAULT_ASSET_PREFIX;
2274
2274
  }, applyToCompiler = (compiler, apply)=>{
2275
2275
  compiler_isMultiCompiler(compiler) ? compiler.compilers.forEach(apply) : apply(compiler, 0);
2276
2276
  }, addCompilationError = (compilation, message)=>{
@@ -2527,8 +2527,8 @@ function initHooks() {
2527
2527
  onCloseDevServer: createAsyncHook(),
2528
2528
  onAfterStartDevServer: createAsyncHook(),
2529
2529
  onBeforeStartDevServer: createAsyncHook(),
2530
- onAfterStartProdServer: createAsyncHook(),
2531
- onBeforeStartProdServer: createAsyncHook(),
2530
+ onAfterStartPreviewServer: createAsyncHook(),
2531
+ onBeforeStartPreviewServer: createAsyncHook(),
2532
2532
  onAfterCreateCompiler: createAsyncHook(),
2533
2533
  onBeforeCreateCompiler: createAsyncHook(),
2534
2534
  modifyHTML: createEnvironmentAsyncHook(),
@@ -3004,7 +3004,7 @@ function exitHook(onExit) {
3004
3004
  let external_node_url_ = __webpack_require__("node:url"), addTrailingSlash = (s)=>s.endsWith('/') ? s : `${s}/`, isURL = (str)=>str.startsWith('http') || str.startsWith('//'), urlJoin = (base, path)=>{
3005
3005
  let [urlProtocol, baseUrl] = base.split('://');
3006
3006
  return `${urlProtocol}://${external_node_path_.posix.join(baseUrl, path)}`;
3007
- }, ensureAssetPrefix = (url, assetPrefix = DEFAULT_ASSET_PREFIX)=>url.startsWith('//') || external_node_url_.URL.canParse(url) || 'auto' === assetPrefix || 'function' == typeof assetPrefix ? url : assetPrefix.startsWith('http') ? urlJoin(assetPrefix, url) : assetPrefix.startsWith('//') ? urlJoin(`https:${assetPrefix}`, url).replace('https:', '') : external_node_path_.posix.join(assetPrefix, url), formatPublicPath = (publicPath, withSlash = !0)=>'auto' === publicPath ? publicPath : withSlash ? addTrailingSlash(publicPath) : publicPath.replace(/\/+$/, ''), getPublicPathFromChain = (chain, withSlash = !0)=>{
3007
+ }, ensureAssetPrefix = (url, assetPrefix = DEFAULT_ASSET_PREFIX)=>url.startsWith('//') || external_node_url_.URL.canParse(url) || 'auto' === assetPrefix || 'function' == typeof assetPrefix ? url : assetPrefix.startsWith('http') ? urlJoin(assetPrefix, url) : assetPrefix.startsWith('//') ? urlJoin(`https:${assetPrefix}`, url).replace('https:', '') : external_node_path_.posix.join(assetPrefix, url), formatPublicPath = (publicPath, withSlash = !0)=>'auto' === publicPath || '' === publicPath ? publicPath : withSlash ? addTrailingSlash(publicPath) : publicPath.replace(/\/+$/, ''), getPublicPathFromChain = (chain, withSlash = !0)=>{
3008
3008
  let publicPath = chain.output.get('publicPath');
3009
3009
  return 'string' == typeof publicPath ? formatPublicPath(publicPath, withSlash) : formatPublicPath(DEFAULT_ASSET_PREFIX, withSlash);
3010
3010
  };
@@ -3282,8 +3282,8 @@ function initPluginAPI({ context, pluginManager }) {
3282
3282
  onAfterStartDevServer: hooks.onAfterStartDevServer.tap,
3283
3283
  onBeforeCreateCompiler: hooks.onBeforeCreateCompiler.tap,
3284
3284
  onBeforeStartDevServer: hooks.onBeforeStartDevServer.tap,
3285
- onAfterStartProdServer: hooks.onAfterStartProdServer.tap,
3286
- onBeforeStartProdServer: hooks.onBeforeStartProdServer.tap,
3285
+ onAfterStartPreviewServer: hooks.onAfterStartPreviewServer.tap,
3286
+ onBeforeStartPreviewServer: hooks.onBeforeStartPreviewServer.tap,
3287
3287
  modifyRsbuildConfig: hooks.modifyRsbuildConfig.tap,
3288
3288
  modifyHTML: (handler)=>{
3289
3289
  hooks.modifyHTML.tapEnvironment({
@@ -3399,7 +3399,7 @@ function createPublicContext(context) {
3399
3399
  async function createContext(options, userConfig) {
3400
3400
  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;
3401
3401
  return {
3402
- version: "2.0.0-beta.3",
3402
+ version: "2.0.0-beta.5",
3403
3403
  rootPath,
3404
3404
  distPath: '',
3405
3405
  cachePath,
@@ -4964,16 +4964,14 @@ let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
4964
4964
  if (!found) throw Error(`${color.dim('[rsbuild:server]')} Failed to find an available port after ${tryLimits + 1} attempts, starting from ${color.yellow(original)}.`);
4965
4965
  if (port !== original && strictPort) throw Error(`${color.dim('[rsbuild:server]')} Port ${color.yellow(original)} is occupied, please choose another one.`);
4966
4966
  return port;
4967
- }, getServerConfig = async ({ config })=>{
4967
+ }, resolvePort = async (config)=>{
4968
4968
  let { host, port: originalPort, strictPort } = config.server, port = await getPort({
4969
4969
  host,
4970
4970
  port: originalPort,
4971
4971
  strictPort
4972
- }), https = !!config.server.https, portTip = port !== originalPort ? `port ${originalPort} is in use, ${color.yellow(`using port ${port}.`)}` : void 0;
4972
+ }), portTip = port !== originalPort ? `port ${originalPort} is in use, ${color.yellow(`using port ${port}.`)}` : void 0;
4973
4973
  return {
4974
4974
  port,
4975
- host,
4976
- https,
4977
4975
  portTip
4978
4976
  };
4979
4977
  }, isLoopbackHost = (host)=>new Set([
@@ -4992,7 +4990,7 @@ let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
4992
4990
  } catch {
4993
4991
  return NETWORK_LABEL;
4994
4992
  }
4995
- }, getAddressUrls = async ({ protocol = 'http', port, host })=>{
4993
+ }, getAddressUrls = async ({ protocol, port, host })=>{
4996
4994
  if (host && host !== ALL_INTERFACES_IPV4) {
4997
4995
  let url = concatUrl({
4998
4996
  port,
@@ -5106,7 +5104,7 @@ function resolveUrl(str, base) {
5106
5104
  throw Error(`${color.dim('[rsbuild:open]')} Invalid input: ${color.yellow(str)} is not a valid URL or pathname`);
5107
5105
  }
5108
5106
  }
5109
- async function open_open({ https, port, routes, config, clearCache }) {
5107
+ async function open_open({ port, routes, config, protocol, clearCache }) {
5110
5108
  if ('true' === process.env.CSB) return;
5111
5109
  let { targets, before } = ((config)=>{
5112
5110
  let { open } = config.server;
@@ -5124,7 +5122,7 @@ async function open_open({ https, port, routes, config, clearCache }) {
5124
5122
  };
5125
5123
  })(config);
5126
5124
  clearCache && (openedURLs = []);
5127
- let urls = [], host = await getHostInUrl(config.server.host), baseUrl = `${https ? 'https' : 'http'}://${host}:${port}`;
5125
+ let urls = [], host = await getHostInUrl(config.server.host), baseUrl = `${protocol}://${host}:${port}`;
5128
5126
  for (let url of (targets.length ? urls.push(...targets.map((target)=>resolveUrl(replacePortPlaceholder(target, port), baseUrl))) : routes.length ? urls.push(`${baseUrl}${routes[0].pathname}`) : urls.push(baseUrl), before && await before(), urls))openedURLs.includes(url) || (openBrowser(url), openedURLs.push(url));
5129
5127
  }
5130
5128
  function recursiveChunkGroup(chunkGroup, visited = new Set()) {
@@ -6375,9 +6373,11 @@ class SocketServer {
6375
6373
  socket.isAlive = !0;
6376
6374
  }), socket.on('message', async (data)=>{
6377
6375
  try {
6378
- let payload = JSON.parse('string' == typeof data ? data : data.toString()), { context } = this, config = context.normalizedConfig;
6379
- if (!config) return;
6380
- let { browserLogs, client } = config.dev;
6376
+ let payload = JSON.parse('string' == typeof data ? data : data.toString()), { context } = this;
6377
+ if (!context.normalizedConfig) return;
6378
+ let environment = this.getEnvironmentByToken(token);
6379
+ if (!environment) return;
6380
+ let { browserLogs, client } = environment.config.dev;
6381
6381
  if ('client-error' === payload.type && !context.buildState.hasErrors && browserLogs) {
6382
6382
  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);
6383
6383
  if (this.reportedBrowserLogs.has(log) || (this.reportedBrowserLogs.add(log), src_logger.error(`${color.cyan('[browser]')} ${log}`)), 'object' == typeof client.overlay && client.overlay.runtime) {
@@ -6402,8 +6402,11 @@ class SocketServer {
6402
6402
  token
6403
6403
  });
6404
6404
  }
6405
+ getEnvironmentByToken(token) {
6406
+ return this.context.environmentList.find(({ webSocketToken })=>webSocketToken === token);
6407
+ }
6405
6408
  getStats(token) {
6406
- let { stats } = this.context.buildState, environment = this.context.environmentList.find(({ webSocketToken })=>webSocketToken === token);
6409
+ let { stats } = this.context.buildState, environment = this.getEnvironmentByToken(token);
6407
6410
  if (!stats || !environment) return;
6408
6411
  let currentStats = stats;
6409
6412
  if (stats.children) {
@@ -6531,7 +6534,7 @@ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls,
6531
6534
  input: process.stdin
6532
6535
  });
6533
6536
  return rl.on('line', (input)=>{
6534
- if ('h' === input) {
6537
+ if ('h' === (input = input.trim().toLowerCase())) {
6535
6538
  let message = `\n ${color.bold(color.blue('Shortcuts:'))}\n`;
6536
6539
  for (let shortcut of shortcuts)message += ` ${shortcut.description}\n`;
6537
6540
  src_logger.log(message);
@@ -6590,7 +6593,7 @@ function historyApiFallback_historyApiFallbackMiddleware(options = {}) {
6590
6593
  src_logger.debug('Not rewriting', req.method, req.url, 'because the client did not send an HTTP accept header.'), next();
6591
6594
  return;
6592
6595
  }
6593
- if (0 === headers.accept.indexOf('application/json')) {
6596
+ if (headers.accept.startsWith('application/json')) {
6594
6597
  src_logger.debug('Not rewriting', req.method, req.url, 'because the client prefers JSON.'), next();
6595
6598
  return;
6596
6599
  }
@@ -6608,11 +6611,11 @@ function historyApiFallback_historyApiFallbackMiddleware(options = {}) {
6608
6611
  let match = parsedUrl.pathname?.match(rewrite.from);
6609
6612
  if (!match) continue;
6610
6613
  let rule = rewrite.to;
6611
- '/' !== (rewriteTarget = 'string' == typeof rule ? rule : rule({
6614
+ (rewriteTarget = 'string' == typeof rule ? rule : rule({
6612
6615
  parsedUrl,
6613
6616
  match,
6614
6617
  request: req
6615
- })).charAt(0) && src_logger.debug('We recommend using an absolute path for the rewrite target.', 'Received a non-absolute rewrite target', rewriteTarget, 'for URL', req.url), src_logger.debug('Rewriting', req.method, req.url, 'to', rewriteTarget), req.url = rewriteTarget, next();
6618
+ })).startsWith('/') || src_logger.debug('We recommend using an absolute path for the rewrite target.', 'Received a non-absolute rewrite target', rewriteTarget, 'for URL', req.url), src_logger.debug('Rewriting', req.method, req.url, 'to', rewriteTarget), req.url = rewriteTarget, next();
6616
6619
  return;
6617
6620
  }
6618
6621
  let { pathname } = parsedUrl;
@@ -6723,33 +6726,30 @@ async function createProxyMiddleware(proxyOptions) {
6723
6726
  }
6724
6727
  };
6725
6728
  }
6726
- let applyDefaultMiddlewares = async ({ config, buildManager, context, devServerAPI, middlewares, postCallbacks })=>{
6729
+ let applyDefaultMiddlewares = async ({ config, buildManager, context, devServer, middlewares, postCallbacks })=>{
6727
6730
  let upgradeEvents = [], { server } = config;
6728
6731
  if (server.cors) {
6729
6732
  let { default: corsMiddleware } = await import("./cors.js").then(__webpack_require__.t.bind(__webpack_require__, "../../node_modules/.pnpm/cors@2.8.6/node_modules/cors/lib/index.js", 23));
6730
- middlewares.push(corsMiddleware('boolean' == typeof server.cors ? {} : server.cors));
6733
+ middlewares.use(corsMiddleware('boolean' == typeof server.cors ? {} : server.cors));
6731
6734
  }
6732
6735
  let { headers } = server;
6733
- if (headers && middlewares.push((_req, res, next)=>{
6736
+ if (headers && middlewares.use((_req, res, next)=>{
6734
6737
  for (let [key, value] of Object.entries(headers))res.setHeader(key, value);
6735
6738
  next();
6736
6739
  }), server.proxy) {
6737
6740
  let { middlewares: proxyMiddlewares, upgrade } = await createProxyMiddleware(server.proxy);
6738
- for (let middleware of (upgradeEvents.push(upgrade), proxyMiddlewares))middlewares.push(middleware);
6741
+ for (let middleware of (upgradeEvents.push(upgrade), proxyMiddlewares))middlewares.use(middleware);
6739
6742
  }
6740
6743
  let { compress } = server;
6741
- if (compress && middlewares.push(gzipMiddleware_gzipMiddleware('object' == typeof compress ? compress : void 0)), 'dev' === context.action && buildManager) {
6744
+ if (compress && middlewares.use(gzipMiddleware_gzipMiddleware('object' == typeof compress ? compress : void 0)), 'dev' === context.action && buildManager) {
6742
6745
  let { compiler } = buildManager;
6743
- (compiler_isMultiCompiler(compiler) ? compiler.compilers.some((childCompiler)=>childCompiler.options.lazyCompilation) : compiler.options.lazyCompilation) && middlewares.push(core_rspack.lazyCompilationMiddleware(compiler));
6746
+ (compiler_isMultiCompiler(compiler) ? compiler.compilers.some((childCompiler)=>childCompiler.options.lazyCompilation) : compiler.options.lazyCompilation) && middlewares.use(core_rspack.lazyCompilationMiddleware(compiler));
6744
6747
  }
6745
- server.base && '/' !== server.base && middlewares.push(getBaseUrlMiddleware({
6748
+ server.base && '/' !== server.base && middlewares.use(getBaseUrlMiddleware({
6746
6749
  base: server.base
6747
6750
  }));
6748
- let { default: launchEditorMiddleware } = await import("./launch-editor-middleware.js").then(__webpack_require__.t.bind(__webpack_require__, "../../node_modules/.pnpm/launch-editor-middleware@2.12.0/node_modules/launch-editor-middleware/index.js", 23));
6749
- if (middlewares.push([
6750
- '/__open-in-editor',
6751
- launchEditorMiddleware()
6752
- ]), middlewares.push((({ environments })=>async function viewingServedFilesMiddleware(req, res, next) {
6751
+ let { default: launchEditorMiddleware } = await import("./launch-editor-middleware.js").then(__webpack_require__.t.bind(__webpack_require__, "../../node_modules/.pnpm/launch-editor-middleware@2.13.0/node_modules/launch-editor-middleware/index.js", 23));
6752
+ if (middlewares.use('/__open-in-editor', launchEditorMiddleware()), middlewares.use((({ environments })=>async function viewingServedFilesMiddleware(req, res, next) {
6753
6753
  if ('/rsbuild-dev-server' !== req.url.replace(postfixRE, '')) return void next();
6754
6754
  res.writeHead(200, {
6755
6755
  'Content-Type': 'text/html; charset=utf-8'
@@ -6808,10 +6808,10 @@ let applyDefaultMiddlewares = async ({ config, buildManager, context, devServerA
6808
6808
  src_logger.error(err), res.writeHead(500), res.end('Failed to list the files');
6809
6809
  }
6810
6810
  })({
6811
- environments: devServerAPI.environments
6812
- })), buildManager && (middlewares.push(buildManager.assetsMiddleware), upgradeEvents.push(buildManager.socketServer.upgrade), middlewares.push(function hotUpdateJsonFallbackMiddleware(req, res, next) {
6811
+ environments: devServer.environments
6812
+ })), buildManager && (middlewares.use(buildManager.assetsMiddleware), upgradeEvents.push(buildManager.socketServer.upgrade), middlewares.use(function hotUpdateJsonFallbackMiddleware(req, res, next) {
6813
6813
  req.url?.endsWith('.hot-update.json') && 'OPTIONS' !== req.method ? notFoundMiddleware(req, res, next) : next();
6814
- })), buildManager && middlewares.push((({ distPath, buildManager })=>async function htmlCompletionMiddleware(req, res, next) {
6814
+ })), buildManager && middlewares.use((({ distPath, buildManager })=>async function htmlCompletionMiddleware(req, res, next) {
6815
6815
  if (!maybeHTMLRequest(req)) return void next();
6816
6816
  let pathname = req.url.replace(postfixRE, ''), rewrite = (newUrl)=>{
6817
6817
  req.url = newUrl, buildManager.assetsMiddleware(req, res, (...args)=>{
@@ -6838,14 +6838,14 @@ let applyDefaultMiddlewares = async ({ config, buildManager, context, devServerA
6838
6838
  etag: !0,
6839
6839
  dev: !0
6840
6840
  });
6841
- middlewares.push(function publicDirMiddleware(req, res, next) {
6841
+ middlewares.use(function publicDirMiddleware(req, res, next) {
6842
6842
  sirvMiddleware(req, res, next);
6843
6843
  });
6844
6844
  }
6845
6845
  }
6846
- for (let callback of postCallbacks)callback();
6847
- return server.historyApiFallback && (middlewares.push(historyApiFallback_historyApiFallbackMiddleware(!0 === server.historyApiFallback ? {} : server.historyApiFallback)), buildManager?.assetsMiddleware && middlewares.push(buildManager.assetsMiddleware)), buildManager && middlewares.push((({ htmlFallback, distPath, buildManager })=>async function htmlFallbackMiddleware(req, res, next) {
6848
- if (!maybeHTMLRequest(req) || '/favicon.ico' === req.url || 'index' !== htmlFallback) return void next();
6846
+ for (let callback of postCallbacks)await callback();
6847
+ return server.historyApiFallback && (middlewares.use(historyApiFallback_historyApiFallbackMiddleware(!0 === server.historyApiFallback ? {} : server.historyApiFallback)), buildManager?.assetsMiddleware && middlewares.use(buildManager.assetsMiddleware)), buildManager && server.htmlFallback && middlewares.use((({ distPath, buildManager })=>async function htmlFallbackMiddleware(req, res, next) {
6848
+ if (!maybeHTMLRequest(req) || '/favicon.ico' === req.url) return void next();
6849
6849
  let filePath = external_node_path_.default.join(distPath, 'index.html');
6850
6850
  if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) {
6851
6851
  let newUrl = '/index.html';
@@ -6857,22 +6857,23 @@ let applyDefaultMiddlewares = async ({ config, buildManager, context, devServerA
6857
6857
  next();
6858
6858
  })({
6859
6859
  buildManager,
6860
- distPath: context.distPath,
6861
- htmlFallback: server.htmlFallback
6862
- })), middlewares.push(faviconFallbackMiddleware), {
6860
+ distPath: context.distPath
6861
+ })), middlewares.use(faviconFallbackMiddleware), {
6863
6862
  onUpgrade: (...args)=>{
6864
6863
  for (let cb of upgradeEvents)cb(...args);
6865
6864
  }
6866
6865
  };
6867
6866
  }, getDevMiddlewares = async (options)=>{
6868
- let middlewares = [], { buildManager } = options;
6869
- isVerbose() && middlewares.push(getRequestLoggerMiddleware());
6870
- let { before, after } = ((config, devServerAPI)=>{
6871
- let setupMiddlewares = config.dev.setupMiddlewares || [], serverOptions = pick(devServerAPI, [
6867
+ let { buildManager, devServer } = options, { middlewares } = devServer;
6868
+ isVerbose() && middlewares.use(getRequestLoggerMiddleware());
6869
+ let { before, after } = ((config, devServer)=>{
6870
+ let setupMiddlewares = config.dev.setupMiddlewares ? helpers_castArray(config.dev.setupMiddlewares) : [];
6871
+ setupMiddlewares.length && src_logger.warn('[rsbuild] `dev.setupMiddlewares` is deprecated, use `server.setup` instead');
6872
+ let serverOptions = pick(devServer, [
6872
6873
  'sockWrite',
6873
6874
  'environments'
6874
6875
  ]), before = [], after = [];
6875
- for (let handler of helpers_castArray(setupMiddlewares))handler({
6876
+ for (let handler of setupMiddlewares)handler({
6876
6877
  unshift: (...handlers)=>before.unshift(...handlers),
6877
6878
  push: (...handlers)=>after.push(...handlers)
6878
6879
  }, serverOptions);
@@ -6880,18 +6881,18 @@ let applyDefaultMiddlewares = async ({ config, buildManager, context, devServerA
6880
6881
  before,
6881
6882
  after
6882
6883
  };
6883
- })(options.config, options.devServerAPI);
6884
- middlewares.push(...before);
6884
+ })(options.config, options.devServer);
6885
+ for (let middleware of before)middlewares.use(middleware);
6885
6886
  let { onUpgrade } = await applyDefaultMiddlewares({
6886
6887
  ...options,
6887
6888
  middlewares
6888
6889
  });
6889
- return middlewares.push(...after), {
6890
+ for (let middleware of after)middlewares.use(middleware);
6891
+ return {
6890
6892
  close: async ()=>{
6891
6893
  await buildManager?.close();
6892
6894
  },
6893
- onUpgrade,
6894
- middlewares
6895
+ onUpgrade
6895
6896
  };
6896
6897
  }, asModule = async (something, context, unlinked)=>{
6897
6898
  let { Module, SyntheticModule } = await import("node:vm");
@@ -7162,6 +7163,14 @@ let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>{
7162
7163
  let { createServer } = await import("node:http");
7163
7164
  return createServer(middlewares);
7164
7165
  };
7166
+ async function applyServerSetup(setup, context) {
7167
+ let postCallbacks = [];
7168
+ for (let handler of helpers_castArray(setup || [])){
7169
+ let postCallback = await handler(context);
7170
+ 'function' == typeof postCallback && postCallbacks.push(postCallback);
7171
+ }
7172
+ return postCallbacks;
7173
+ }
7165
7174
  async function setupWatchFiles(options) {
7166
7175
  let { config, root, buildManager } = options, { hmr, liveReload } = config.dev;
7167
7176
  if (!hmr && !liveReload || !buildManager) return;
@@ -7227,15 +7236,13 @@ async function startWatchFiles({ paths, options, type = 'reload-page' }, buildMa
7227
7236
  }), watcher;
7228
7237
  }
7229
7238
  async function devServer_createDevServer(options, createCompiler, config, { getPortSilently, runCompile = !0 } = {}) {
7230
- let lastStats, fileWatcher, devMiddlewares;
7239
+ let lastStats, fileWatcher, devMiddlewares, buildManager;
7231
7240
  src_logger.debug('create dev server');
7232
- let { port, host, https, portTip } = await getServerConfig({
7233
- config
7234
- }), { middlewareMode } = config.server, { context } = options, routes = getRoutes(context), root = context.rootPath;
7241
+ let { port, portTip } = await resolvePort(config), { middlewareMode, host } = config.server, isHttps = !!config.server.https, { context } = options, routes = getRoutes(context);
7235
7242
  context.devServer = {
7236
7243
  hostname: host,
7237
7244
  port,
7238
- https
7245
+ https: isHttps
7239
7246
  };
7240
7247
  let waitLastCompileDoneResolve = null, waitLastCompileDone = new Promise((resolve)=>{
7241
7248
  waitLastCompileDoneResolve = resolve;
@@ -7263,7 +7270,7 @@ async function devServer_createDevServer(options, createCompiler, config, { getP
7263
7270
  resolvedPort: port
7264
7271
  });
7265
7272
  return await buildManager.init(), buildManager;
7266
- }, protocol = https ? 'https' : 'http', urls = await getAddressUrls({
7273
+ }, protocol = isHttps ? 'https' : 'http', urls = await getAddressUrls({
7267
7274
  protocol,
7268
7275
  port,
7269
7276
  host
@@ -7276,10 +7283,10 @@ async function devServer_createDevServer(options, createCompiler, config, { getP
7276
7283
  trailingLineBreak: !cliShortcutsEnabled,
7277
7284
  originalConfig: context.originalConfig
7278
7285
  }), openPage = async ()=>open_open({
7279
- https,
7280
7286
  port,
7281
7287
  routes,
7282
7288
  config,
7289
+ protocol,
7283
7290
  clearCache: !0
7284
7291
  }), cleanupGracefulShutdown = middlewareMode ? null : setupGracefulShutdown(), closingPromise = null, closeServer = async ()=>(closingPromise || (closingPromise = (async ()=>{
7285
7292
  removeCleanup(closeServer), cleanupGracefulShutdown?.(), await context.hooks.onCloseDevServer.callBatch(), await Promise.all([
@@ -7335,7 +7342,7 @@ async function devServer_createDevServer(options, createCompiler, config, { getP
7335
7342
  let { default: connect } = await import("./connect.js").then(__webpack_require__.t.bind(__webpack_require__, "../../node_modules/.pnpm/connect@3.7.0_supports-color@10.2.2/node_modules/connect/index.js", 23)), middlewares = connect(), httpServer = middlewareMode ? null : await createHttpServer({
7336
7343
  serverConfig: config.server,
7337
7344
  middlewares
7338
- }), devServerAPI = {
7345
+ }), devServer = {
7339
7346
  port,
7340
7347
  middlewares,
7341
7348
  environments: environmentAPI,
@@ -7353,12 +7360,10 @@ async function devServer_createDevServer(options, createCompiler, config, { getP
7353
7360
  port
7354
7361
  }, async (err)=>{
7355
7362
  if (err) throw err;
7356
- middlewares.use(optionsFallbackMiddleware), middlewares.use(notFoundMiddleware), devMiddlewares && httpServer.on('upgrade', devMiddlewares.onUpgrade), src_logger.debug('listen dev server done'), await devServerAPI.afterListen(), onBeforeRestartServer(devServerAPI.close), resolve({
7363
+ middlewares.use(optionsFallbackMiddleware), middlewares.use(notFoundMiddleware), devMiddlewares && httpServer.on('upgrade', devMiddlewares.onUpgrade), src_logger.debug('listen dev server done'), await devServer.afterListen(), onBeforeRestartServer(devServer.close), resolve({
7357
7364
  port,
7358
7365
  urls: urls.map((item)=>item.url),
7359
- server: {
7360
- close: devServerAPI.close
7361
- }
7366
+ server: devServer
7362
7367
  });
7363
7368
  });
7364
7369
  });
@@ -7376,134 +7381,119 @@ async function devServer_createDevServer(options, createCompiler, config, { getP
7376
7381
  close: closeServer,
7377
7382
  printUrls,
7378
7383
  open: openPage
7379
- }, postCallbacks = (await context.hooks.onBeforeStartDevServer.callBatch({
7380
- server: devServerAPI,
7384
+ }, setupPostCallbacks = await applyServerSetup(config.server.setup, {
7385
+ action: 'dev',
7386
+ server: devServer,
7381
7387
  environments: context.environments
7382
- })).filter((item)=>'function' == typeof item);
7383
- runCompile ? context.hooks.onBeforeCreateCompiler.tap(beforeCreateCompiler) : await beforeCreateCompiler();
7384
- let buildManager = runCompile ? await startCompile() : void 0;
7385
- for (let item of (fileWatcher = await setupWatchFiles({
7388
+ }), postCallbacks = [
7389
+ ...(await context.hooks.onBeforeStartDevServer.callBatch({
7390
+ server: devServer,
7391
+ environments: context.environments
7392
+ })).filter((item)=>'function' == typeof item),
7393
+ ...setupPostCallbacks
7394
+ ];
7395
+ return runCompile ? context.hooks.onBeforeCreateCompiler.tap(beforeCreateCompiler) : await beforeCreateCompiler(), buildManager = runCompile ? await startCompile() : void 0, fileWatcher = await setupWatchFiles({
7386
7396
  config,
7387
7397
  buildManager,
7388
- root
7389
- }), (devMiddlewares = await getDevMiddlewares({
7398
+ root: context.rootPath
7399
+ }), devMiddlewares = await getDevMiddlewares({
7390
7400
  buildManager,
7391
7401
  config,
7392
- devServerAPI,
7402
+ devServer,
7393
7403
  context,
7394
7404
  postCallbacks
7395
- })).middlewares))Array.isArray(item) ? middlewares.use(...item) : middlewares.use(item);
7396
- return buildManager?.watch(), src_logger.debug('create dev server done'), devServerAPI;
7405
+ }), buildManager?.watch(), src_logger.debug('create dev server done'), devServer;
7397
7406
  }
7398
- class RsbuildProdServer {
7399
- app;
7400
- options;
7401
- middlewares;
7402
- constructor(options, middlewares){
7403
- this.options = options, this.middlewares = middlewares;
7404
- }
7405
- async onInit(app) {
7406
- this.app = app, await this.applyDefaultMiddlewares();
7407
- }
7408
- async applyDefaultMiddlewares() {
7409
- let { headers, proxy, historyApiFallback, compress, base, cors } = this.options.serverConfig;
7410
- if (isVerbose() && this.middlewares.use(getRequestLoggerMiddleware()), cors) {
7411
- let { default: corsMiddleware } = await import("./cors.js").then(__webpack_require__.t.bind(__webpack_require__, "../../node_modules/.pnpm/cors@2.8.6/node_modules/cors/lib/index.js", 23));
7412
- this.middlewares.use(corsMiddleware('boolean' == typeof cors ? {} : cors));
7413
- }
7414
- if (headers && this.middlewares.use((_req, res, next)=>{
7415
- for (let [key, value] of Object.entries(headers))res.setHeader(key, value);
7416
- next();
7417
- }), proxy) {
7418
- let { middlewares, upgrade } = await createProxyMiddleware(proxy);
7419
- for (let middleware of middlewares)this.middlewares.use(middleware);
7420
- this.app.on('upgrade', upgrade);
7421
- }
7422
- if (compress) {
7423
- let { constants } = await import("node:zlib");
7424
- this.middlewares.use(gzipMiddleware_gzipMiddleware({
7425
- level: constants.Z_DEFAULT_COMPRESSION,
7426
- ...'object' == typeof compress ? compress : void 0
7427
- }));
7428
- }
7429
- base && '/' !== base && this.middlewares.use(getBaseUrlMiddleware({
7430
- base
7431
- })), await this.applyStaticAssetMiddleware(), historyApiFallback && (this.middlewares.use(historyApiFallback_historyApiFallbackMiddleware(!0 === historyApiFallback ? {} : historyApiFallback)), await this.applyStaticAssetMiddleware()), this.middlewares.use(faviconFallbackMiddleware), this.middlewares.use(optionsFallbackMiddleware), this.middlewares.use(notFoundMiddleware);
7432
- }
7433
- async applyStaticAssetMiddleware() {
7434
- let { output: { path, assetPrefixes }, serverConfig: { htmlFallback } } = this.options, { default: sirv } = await import("./sirv.js").then((mod)=>({
7407
+ async function startPreviewServer(context, config, { getPortSilently } = {}) {
7408
+ let { default: connect } = await import("./connect.js").then(__webpack_require__.t.bind(__webpack_require__, "../../node_modules/.pnpm/connect@3.7.0_supports-color@10.2.2/node_modules/connect/index.js", 23)), middlewares = connect(), { port, portTip } = await resolvePort(config), serverConfig = config.server, { host, headers, proxy, historyApiFallback, compress, base, cors } = serverConfig, protocol = serverConfig.https ? 'https' : 'http', routes = getRoutes(context), urls = await getAddressUrls({
7409
+ protocol,
7410
+ port,
7411
+ host
7412
+ }), cliShortcutsEnabled = isCliShortcutsEnabled(config), httpServer = await createHttpServer({
7413
+ serverConfig,
7414
+ middlewares
7415
+ }), cleanupGracefulShutdown = setupGracefulShutdown(), serverTerminator = getServerTerminator(httpServer), closingPromise = null, closeServer = async ()=>(closingPromise || (closingPromise = (async ()=>{
7416
+ removeCleanup(closeServer), cleanupGracefulShutdown(), await serverTerminator();
7417
+ })()), closingPromise), printUrls = ()=>printServerURLs({
7418
+ urls,
7419
+ port,
7420
+ routes,
7421
+ protocol,
7422
+ printUrls: serverConfig.printUrls,
7423
+ trailingLineBreak: !cliShortcutsEnabled,
7424
+ originalConfig: context.originalConfig
7425
+ }), openPage = async ()=>open_open({
7426
+ port,
7427
+ routes,
7428
+ config,
7429
+ protocol,
7430
+ clearCache: !0
7431
+ }), previewServer = {
7432
+ httpServer,
7433
+ port,
7434
+ middlewares,
7435
+ close: closeServer,
7436
+ printUrls,
7437
+ open: openPage
7438
+ }, postSetupCallbacks = await applyServerSetup(serverConfig.setup, {
7439
+ action: 'preview',
7440
+ server: previewServer,
7441
+ environments: context.environments
7442
+ });
7443
+ await context.hooks.onBeforeStartPreviewServer.callBatch({
7444
+ server: previewServer,
7445
+ environments: context.environments
7446
+ });
7447
+ let applyStaticAssetMiddleware = async ()=>{
7448
+ let { default: sirv } = await import("./sirv.js").then((mod)=>({
7435
7449
  default: mod.build
7436
- })), assetsMiddleware = sirv(path, {
7450
+ })), assetsMiddleware = sirv(context.distPath, {
7437
7451
  etag: !0,
7438
7452
  dev: !0,
7439
7453
  ignores: [
7440
7454
  'favicon.ico'
7441
7455
  ],
7442
- single: 'index' === htmlFallback
7443
- });
7444
- this.middlewares.use(function staticAssetMiddleware(req, res, next) {
7445
- let url = req.url, assetPrefix = url && assetPrefixes.find((prefix)=>url.startsWith(prefix));
7456
+ single: 'index' === serverConfig.htmlFallback
7457
+ }), assetPrefixes = context.environmentList.map((e)=>getPathnameFromUrl(e.config.output.assetPrefix));
7458
+ middlewares.use(function staticAssetMiddleware(req, res, next) {
7459
+ let { url } = req, assetPrefix = url && assetPrefixes.find((prefix)=>url.startsWith(prefix));
7446
7460
  assetPrefix && url?.startsWith(assetPrefix) ? (req.url = url.slice(assetPrefix.length), assetsMiddleware(req, res, (...args)=>{
7447
7461
  req.url = url, next(...args);
7448
7462
  })) : assetsMiddleware(req, res, next);
7449
7463
  });
7464
+ };
7465
+ if (isVerbose() && middlewares.use(getRequestLoggerMiddleware()), cors) {
7466
+ let { default: corsMiddleware } = await import("./cors.js").then(__webpack_require__.t.bind(__webpack_require__, "../../node_modules/.pnpm/cors@2.8.6/node_modules/cors/lib/index.js", 23));
7467
+ middlewares.use(corsMiddleware('boolean' == typeof cors ? {} : cors));
7450
7468
  }
7451
- async close() {}
7452
- }
7453
- async function startProdServer(context, config, { getPortSilently } = {}) {
7454
- let { port, host, https, portTip } = await getServerConfig({
7455
- config
7456
- }), { default: connect } = await import("./connect.js").then(__webpack_require__.t.bind(__webpack_require__, "../../node_modules/.pnpm/connect@3.7.0_supports-color@10.2.2/node_modules/connect/index.js", 23)), middlewares = connect(), serverConfig = config.server, server = new RsbuildProdServer({
7457
- pwd: context.rootPath,
7458
- output: {
7459
- path: context.distPath,
7460
- assetPrefixes: context.environmentList.map((e)=>getPathnameFromUrl(e.config.output.assetPrefix))
7461
- },
7462
- serverConfig
7463
- }, middlewares);
7464
- await context.hooks.onBeforeStartProdServer.callBatch();
7465
- let httpServer = await createHttpServer({
7466
- serverConfig,
7467
- middlewares: server.middlewares
7468
- }), serverTerminator = getServerTerminator(httpServer);
7469
- return await server.onInit(httpServer), new Promise((resolve)=>{
7469
+ if (headers && middlewares.use((_req, res, next)=>{
7470
+ for (let [key, value] of Object.entries(headers))res.setHeader(key, value);
7471
+ next();
7472
+ }), proxy) {
7473
+ let { middlewares: proxyMiddlewares, upgrade } = await createProxyMiddleware(proxy);
7474
+ for (let middleware of proxyMiddlewares)middlewares.use(middleware);
7475
+ httpServer.on('upgrade', upgrade);
7476
+ }
7477
+ if (compress) {
7478
+ let { constants } = await import("node:zlib");
7479
+ middlewares.use(gzipMiddleware_gzipMiddleware({
7480
+ level: constants.Z_DEFAULT_COMPRESSION,
7481
+ ...'object' == typeof compress ? compress : void 0
7482
+ }));
7483
+ }
7484
+ for (let callback of (base && '/' !== base && middlewares.use(getBaseUrlMiddleware({
7485
+ base
7486
+ })), await applyStaticAssetMiddleware(), historyApiFallback && (middlewares.use(historyApiFallback_historyApiFallbackMiddleware(!0 === historyApiFallback ? {} : historyApiFallback)), await applyStaticAssetMiddleware()), postSetupCallbacks))await callback();
7487
+ return middlewares.use(faviconFallbackMiddleware), middlewares.use(optionsFallbackMiddleware), middlewares.use(notFoundMiddleware), new Promise((resolve)=>{
7470
7488
  httpServer.listen({
7471
7489
  host,
7472
7490
  port
7473
7491
  }, async ()=>{
7474
- let routes = getRoutes(context);
7475
- await context.hooks.onAfterStartProdServer.callBatch({
7492
+ if (await context.hooks.onAfterStartPreviewServer.callBatch({
7476
7493
  port,
7477
7494
  routes,
7478
7495
  environments: context.environments
7479
- });
7480
- let protocol = https ? 'https' : 'http', urls = await getAddressUrls({
7481
- protocol,
7482
- port,
7483
- host
7484
- }), cliShortcutsEnabled = isCliShortcutsEnabled(config), cleanupGracefulShutdown = setupGracefulShutdown(), closingPromise = null, closeServer = async ()=>(closingPromise || (closingPromise = (async ()=>{
7485
- removeCleanup(closeServer), cleanupGracefulShutdown(), await Promise.all([
7486
- server.close(),
7487
- serverTerminator()
7488
- ]);
7489
- })()), closingPromise);
7490
- registerCleanup(closeServer);
7491
- let printUrls = ()=>printServerURLs({
7492
- urls,
7493
- port,
7494
- routes,
7495
- protocol,
7496
- printUrls: serverConfig.printUrls,
7497
- trailingLineBreak: !cliShortcutsEnabled,
7498
- originalConfig: context.originalConfig
7499
- }), openPage = async ()=>open_open({
7500
- https,
7501
- port,
7502
- routes,
7503
- config,
7504
- clearCache: !0
7505
- });
7506
- if (printUrls(), cliShortcutsEnabled) {
7496
+ }), registerCleanup(closeServer), printUrls(), cliShortcutsEnabled) {
7507
7497
  let shortcutsOptions = 'boolean' == typeof config.dev.cliShortcuts ? {} : config.dev.cliShortcuts;
7508
7498
  await setupCliShortcuts({
7509
7499
  openPage,
@@ -7516,9 +7506,7 @@ async function startProdServer(context, config, { getPortSilently } = {}) {
7516
7506
  !getPortSilently && portTip && src_logger.info(portTip), resolve({
7517
7507
  port,
7518
7508
  urls: urls.map((item)=>item.url),
7519
- server: {
7520
- close: closeServer
7521
- }
7509
+ server: previewServer
7522
7510
  });
7523
7511
  });
7524
7512
  });
@@ -7535,14 +7523,10 @@ function applyDefaultPlugins(pluginManager, context) {
7535
7523
  }), chain.watchOptions({
7536
7524
  aggregateTimeout: 0
7537
7525
  }), chain.performance.hints(!1), chain.module.parser.merge({
7538
- javascript: {
7539
- exportsPresence: 'error'
7540
- }
7541
- }), isDev && config.dev.hmr && 'web' === target && chain.plugin(CHAIN_ID.PLUGIN.HMR).use(rspack.HotModuleReplacementPlugin), chain.module.parser.merge({
7542
7526
  javascript: {
7543
7527
  typeReexportsPresence: 'tolerant'
7544
7528
  }
7545
- });
7529
+ }), isDev && config.dev.hmr && 'web' === target && chain.plugin(CHAIN_ID.PLUGIN.HMR).use(rspack.HotModuleReplacementPlugin);
7546
7530
  });
7547
7531
  }
7548
7532
  },
@@ -7759,7 +7743,13 @@ function applyDefaultPlugins(pluginManager, context) {
7759
7743
  path: targetPath
7760
7744
  };
7761
7745
  })()
7762
- ].filter((pathInfo)=>!!pathInfo))await emptyDir(pathInfo.path, pathInfo.keep);
7746
+ ].filter((pathInfo)=>!!pathInfo)){
7747
+ if ('/' === pathInfo.path) {
7748
+ let prefix = color.dim('[rsbuild:cleanOutput]');
7749
+ throw Error(`${prefix} Refusing to clean output at ${color.cyan(`"${pathInfo.path}"`)}. Update ${color.yellow('`output.distPath.root`')} or set ${color.yellow('`output.cleanDistPath`')} to false.`);
7750
+ }
7751
+ await emptyDir(pathInfo.path, pathInfo.keep);
7752
+ }
7763
7753
  };
7764
7754
  api.onBeforeBuild(async ({ isFirstCompile, environments })=>{
7765
7755
  isFirstCompile && await cleanAll({
@@ -7910,7 +7900,7 @@ function applyDefaultPlugins(pluginManager, context) {
7910
7900
  }
7911
7901
  },
7912
7902
  {
7913
- name: 'rsbuild:app-icon',
7903
+ name: 'rsbuild:appIcon',
7914
7904
  setup (api) {
7915
7905
  let htmlTagsMap = new Map(), iconFormatMap = new Map();
7916
7906
  api.processAssets({
@@ -7947,16 +7937,16 @@ function applyDefaultPlugins(pluginManager, context) {
7947
7937
  })(icon, distDir, publicPath, lookup)), tags = [];
7948
7938
  for (let icon of icons){
7949
7939
  if ('web-app-manifest' === icon.target && !appIcon.name) {
7950
- addCompilationError(compilation, `${color.dim('[rsbuild:app-icon]')} ${color.yellow('"appIcon.name"')} is required when ${color.yellow('"target"')} is ${color.yellow('"web-app-manifest"')}.`);
7940
+ addCompilationError(compilation, `${color.dim('[rsbuild:appIcon]')} ${color.yellow('"appIcon.name"')} is required when ${color.yellow('"target"')} is ${color.yellow('"web-app-manifest"')}.`);
7951
7941
  continue;
7952
7942
  }
7953
7943
  if (!icon.isURL) {
7954
7944
  if (!compilation.inputFileSystem) {
7955
- addCompilationError(compilation, `${color.dim('[rsbuild:app-icon]')} Failed to read the icon file as ${color.yellow('"compilation.inputFileSystem"')} is not available.`);
7945
+ addCompilationError(compilation, `${color.dim('[rsbuild:appIcon]')} Failed to read the icon file as ${color.yellow('"compilation.inputFileSystem"')} is not available.`);
7956
7946
  continue;
7957
7947
  }
7958
7948
  if (!await fileExistsByCompilation(compilation, icon.absolutePath)) {
7959
- addCompilationError(compilation, `${color.dim('[rsbuild:app-icon]')} Failed to find the icon file at ${color.yellow(icon.absolutePath)}.`);
7949
+ addCompilationError(compilation, `${color.dim('[rsbuild:appIcon]')} Failed to find the icon file at ${color.yellow(icon.absolutePath)}.`);
7960
7950
  continue;
7961
7951
  }
7962
7952
  let source = await readFileAsync(compilation.inputFileSystem, icon.absolutePath);
@@ -8013,10 +8003,7 @@ function applyDefaultPlugins(pluginManager, context) {
8013
8003
  setup (api) {
8014
8004
  api.modifyBundlerChain((chain, { CHAIN_ID, environment, isProd })=>{
8015
8005
  let { config } = environment, distPath = config.output.distPath.wasm, filename = external_node_path_.posix.join(distPath, getFilename(config, 'wasm', isProd));
8016
- chain.experiments({
8017
- ...chain.get('experiments'),
8018
- asyncWebAssembly: !0
8019
- }), chain.output.webassemblyModuleFilename(filename), chain.module.rule(CHAIN_ID.RULE.WASM).test(/\.wasm$/).dependency('url').type('asset/resource').set('generator', {
8006
+ chain.output.webassemblyModuleFilename(filename), chain.module.rule(CHAIN_ID.RULE.WASM).test(/\.wasm$/).dependency('url').type('asset/resource').set('generator', {
8020
8007
  filename
8021
8008
  });
8022
8009
  });
@@ -8033,7 +8020,7 @@ function applyDefaultPlugins(pluginManager, context) {
8033
8020
  raw: !0
8034
8021
  }, ({ code, emitFile, resourcePath })=>{
8035
8022
  let name, filename = (name = resourcePath && external_node_path_.default.parse(resourcePath).name) ? `${name}.node` : null;
8036
- if (null === filename) throw Error(`${color.dim('[rsbuild:node-addons]')} Failed to load Node.js addon: ${color.yellow(resourcePath)}`);
8023
+ if (null === filename) throw Error(`${color.dim('[rsbuild:nodeAddons]')} Failed to load Node.js addon: ${color.yellow(resourcePath)}`);
8037
8024
  emitFile(filename, code);
8038
8025
  let config = api.getNormalizedConfig(), handleErrorSnippet = `throw new Error('Failed to load Node.js addon: "${filename}"', {
8039
8026
  cause: error,
@@ -8535,14 +8522,17 @@ try {
8535
8522
  setup (api) {
8536
8523
  let onStartServer = ({ port, routes })=>{
8537
8524
  let config = api.getNormalizedConfig();
8538
- config.server.open && open_open({
8539
- https: api.context.devServer?.https,
8540
- port,
8541
- routes,
8542
- config
8543
- });
8525
+ if (config.server.open) {
8526
+ let protocol = config.server.https ? 'https' : 'http';
8527
+ open_open({
8528
+ port,
8529
+ routes,
8530
+ config,
8531
+ protocol
8532
+ });
8533
+ }
8544
8534
  };
8545
- api.onAfterStartDevServer(onStartServer), api.onAfterStartProdServer(onStartServer), api.onBeforeBuild(async ({ isFirstCompile, environments })=>{
8535
+ api.onAfterStartDevServer(onStartServer), api.onAfterStartPreviewServer(onStartServer), api.onBeforeBuild(async ({ isFirstCompile, environments })=>{
8546
8536
  if (isFirstCompile) for (let { name: publicDir, copyOnBuild, ignore } of api.getNormalizedConfig().server.publicDir){
8547
8537
  let shouldCopy;
8548
8538
  if (!1 === copyOnBuild || !external_node_fs_.default.existsSync(publicDir)) continue;
@@ -8589,7 +8579,7 @@ try {
8589
8579
  api.modifyBundlerChain(async (chain, { CHAIN_ID, environment, isDev })=>{
8590
8580
  let { output: { manifest }, dev: { writeToDisk } } = environment.config;
8591
8581
  if (!1 === manifest) return;
8592
- let manifestOptions = normalizeManifestObjectConfig(manifest), { RspackManifestPlugin } = await import("./manifest-plugin.js").then(__webpack_require__.bind(__webpack_require__, "../../node_modules/.pnpm/rspack-manifest-plugin@5.2.1_@rspack+core@2.0.0-beta.0_@module-federation+runtime-tools@0.24.0_@swc+helpers@0.5.18_/node_modules/rspack-manifest-plugin/dist/index.js")), { htmlPaths } = environment, filter = manifestOptions.filter ?? ((file)=>!file.name.endsWith('.LICENSE.txt'));
8582
+ let manifestOptions = normalizeManifestObjectConfig(manifest), { RspackManifestPlugin } = await import("./manifest-plugin.js").then(__webpack_require__.bind(__webpack_require__, "../../node_modules/.pnpm/rspack-manifest-plugin@5.2.1_@rspack+core@2.0.0-beta.2_@module-federation+runtime-tools@2.0.1_@swc+helpers@0.5.19_/node_modules/rspack-manifest-plugin/dist/index.js")), { htmlPaths } = environment, filter = manifestOptions.filter ?? ((file)=>!file.name.endsWith('.LICENSE.txt'));
8593
8583
  manifestFilenames.set(environment.name, manifestOptions.filename);
8594
8584
  let pluginOptions = {
8595
8585
  fileName: manifestOptions.filename,
@@ -8824,7 +8814,7 @@ async function createRsbuild(options = {}) {
8824
8814
  if (!(0, external_node_fs_.existsSync)(distPath)) throw Error(`${color.dim('[rsbuild:preview]')} The output directory ${color.yellow(distPath)} does not exist, please build the project before previewing.`);
8825
8815
  if (isEmptyDir(distPath)) throw Error(`${color.dim('[rsbuild:preview]')} The output directory ${color.yellow(distPath)} is empty, please build the project before previewing.`);
8826
8816
  }
8827
- return startProdServer(context, config, options);
8817
+ return startPreviewServer(context, config, options);
8828
8818
  },
8829
8819
  startDevServer: async (options)=>{
8830
8820
  context.action = 'dev', process.env.NODE_ENV || setNodeEnv('development');
@@ -8886,13 +8876,13 @@ async function createRsbuild(options = {}) {
8886
8876
  'onAfterDevCompile',
8887
8877
  'onAfterEnvironmentCompile',
8888
8878
  'onAfterStartDevServer',
8889
- 'onAfterStartProdServer',
8879
+ 'onAfterStartPreviewServer',
8890
8880
  'onBeforeBuild',
8891
8881
  'onBeforeCreateCompiler',
8892
8882
  'onBeforeDevCompile',
8893
8883
  'onBeforeEnvironmentCompile',
8894
8884
  'onBeforeStartDevServer',
8895
- 'onBeforeStartProdServer',
8885
+ 'onBeforeStartPreviewServer',
8896
8886
  'onCloseBuild',
8897
8887
  'onCloseDevServer',
8898
8888
  'onDevCompileDone',
@@ -8957,7 +8947,7 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
8957
8947
  src_logger.debug(`${errorMessage}, fallback to jiti.`), src_logger.debug(err);
8958
8948
  }
8959
8949
  if (void 0 === configExport) try {
8960
- let { createJiti } = await import("jiti"), jiti = createJiti(import.meta.filename, {
8950
+ let { createJiti } = await import("../compiled/jiti/lib/jiti.mjs"), jiti = createJiti(import.meta.filename, {
8961
8951
  moduleCache: !1,
8962
8952
  interopDefault: !0,
8963
8953
  nativeModules: [
@@ -9094,7 +9084,7 @@ let applyServerOptions = (command)=>{
9094
9084
  };
9095
9085
  function setupCommands() {
9096
9086
  let cli = ((name = "")=>new CAC(name))('rsbuild');
9097
- cli.version("2.0.0-beta.3"), 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)', {
9087
+ cli.version("2.0.0-beta.5"), 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)', {
9098
9088
  default: 'auto'
9099
9089
  }).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', {
9100
9090
  type: [
@@ -9163,7 +9153,7 @@ function initNodeEnv() {
9163
9153
  }
9164
9154
  function showGreeting() {
9165
9155
  let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
9166
- src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.0.0-beta.3\n`);
9156
+ src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.0.0-beta.5\n`);
9167
9157
  }
9168
9158
  function setupLogLevel() {
9169
9159
  let logLevelIndex = process.argv.findIndex((item)=>'--log-level' === item || '--logLevel' === item);
@@ -9184,5 +9174,5 @@ function runCLI() {
9184
9174
  src_logger.error('Failed to start Rsbuild CLI.'), src_logger.error(err), process.exit(1);
9185
9175
  }
9186
9176
  }
9187
- let src_version = "2.0.0-beta.3";
9177
+ let src_version = "2.0.0-beta.5";
9188
9178
  export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, core_rspack as rspack, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, external_node_util_promisify, loadConfig_loadConfig as loadConfig, loadEnv, mergeRsbuildConfig, runCLI, src_logger as logger, src_version as version };