@rsbuild/core 1.4.2 → 1.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ import picocolors from "../compiled/picocolors/index.js";
8
8
  import node_fs, { existsSync } from "node:fs";
9
9
  import { EventEmitter } from "events";
10
10
  import { createRequire } from "node:module";
11
- import node_os, { constants } from "node:os";
11
+ import node_os, { constants as external_node_os_constants } from "node:os";
12
12
  import node_process from "node:process";
13
13
  import rspack_chain from "../compiled/rspack-chain/index.js";
14
14
  import { isPromise, isRegExp } from "node:util/types";
@@ -777,7 +777,7 @@ let constants_filename = fileURLToPath(import.meta.url), constants_dirname = dir
777
777
  node: [
778
778
  'node >= 16'
779
779
  ]
780
- }, HTML_REGEX = /\.html$/, JS_REGEX = /\.(?:js|mjs|cjs|jsx)$/, SCRIPT_REGEX = /\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts)$/, CSS_REGEX = /\.css$/, NODE_MODULES_REGEX = /[\\/]node_modules[\\/]/, PLUGIN_SWC_NAME = 'rsbuild:swc', PLUGIN_CSS_NAME = 'rsbuild:css', FONT_EXTENSIONS = [
780
+ }, HTML_REGEX = /\.html$/, JS_REGEX = /\.(?:js|mjs|cjs|jsx)$/, SCRIPT_REGEX = /\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts)$/, CSS_REGEX = /\.css$/, RAW_QUERY_REGEX = /^\?raw$/, INLINE_QUERY_REGEX = /^\?inline$/, NODE_MODULES_REGEX = /[\\/]node_modules[\\/]/, PLUGIN_SWC_NAME = 'rsbuild:swc', PLUGIN_CSS_NAME = 'rsbuild:css', FONT_EXTENSIONS = [
781
781
  'woff',
782
782
  'woff2',
783
783
  'eot',
@@ -2040,7 +2040,7 @@ let getEnvironmentHTMLPaths = (entry, config)=>'web' !== config.output.target ||
2040
2040
  }, {});
2041
2041
  async function updateEnvironmentContext(context, configs) {
2042
2042
  for (let [index, [name, config]] of (context.environments ||= {}, Object.entries(configs).entries())){
2043
- let browserslist = await getBrowserslistByEnvironment(context.rootPath, config), { entry = {}, tsconfigPath } = config.source, htmlPaths = getEnvironmentHTMLPaths(entry, config), environmentContext = {
2043
+ let browserslist = await getBrowserslistByEnvironment(context.rootPath, config), { entry = {}, tsconfigPath } = config.source, htmlPaths = getEnvironmentHTMLPaths(entry, config), webSocketToken = 'dev' === context.action ? await helpers_hash(context.rootPath + name) : '', environmentContext = {
2044
2044
  index,
2045
2045
  name,
2046
2046
  distPath: function(cwd, config) {
@@ -2051,7 +2051,8 @@ async function updateEnvironmentContext(context, configs) {
2051
2051
  browserslist,
2052
2052
  htmlPaths,
2053
2053
  tsconfigPath,
2054
- config
2054
+ config,
2055
+ webSocketToken
2055
2056
  };
2056
2057
  context.environments[name] = new Proxy(environmentContext, {
2057
2058
  get: (target, prop)=>target[prop],
@@ -2062,7 +2063,7 @@ async function updateEnvironmentContext(context, configs) {
2062
2063
  async function createContext(options, userConfig) {
2063
2064
  let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = join(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, bundlerType = userConfig.provider ? 'webpack' : 'rspack';
2064
2065
  return {
2065
- version: "1.4.2",
2066
+ version: "1.4.4",
2066
2067
  rootPath,
2067
2068
  distPath: '',
2068
2069
  cachePath,
@@ -2751,7 +2752,7 @@ let chainStaticAssetRule = ({ emit, rule, maxSize, filename, assetType })=>{
2751
2752
  let generatorOptions = {
2752
2753
  filename
2753
2754
  };
2754
- !1 === emit && (generatorOptions.emit = !1), rule.oneOf(`${assetType}-asset-url`).type('asset/resource').resourceQuery(/(__inline=false|url)/).set('generator', generatorOptions), rule.oneOf(`${assetType}-asset-inline`).type('asset/inline').resourceQuery(/inline/), rule.oneOf(`${assetType}-asset-raw`).type('asset/source').resourceQuery(/raw/), rule.oneOf(`${assetType}-asset`).type('asset').parser({
2755
+ !1 === emit && (generatorOptions.emit = !1), rule.oneOf(`${assetType}-asset-url`).type('asset/resource').resourceQuery(/^\?(__inline=false|url)$/).set('generator', generatorOptions), rule.oneOf(`${assetType}-asset-inline`).type('asset/inline').resourceQuery(INLINE_QUERY_REGEX), rule.oneOf(`${assetType}-asset-raw`).type('asset/source').resourceQuery(RAW_QUERY_REGEX), rule.oneOf(`${assetType}-asset`).type('asset').parser({
2755
2756
  dataUrlCondition: {
2756
2757
  maxSize
2757
2758
  }
@@ -3685,9 +3686,6 @@ let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
3685
3686
  })
3686
3687
  });
3687
3688
  return addressUrls;
3688
- }, COMPILATION_ID_REGEX = /[^a-zA-Z0-9_-]/g, getCompilationId = (compiler)=>{
3689
- let uniqueName = compiler.options.output.uniqueName ?? '';
3690
- return `${compiler.name ?? ''}_${uniqueName.replace(COMPILATION_ID_REGEX, '_')}`;
3691
3689
  };
3692
3690
  function getServerTerminator(server) {
3693
3691
  let listened = !1, pendingSockets = new Set(), onConnection = (socket)=>{
@@ -3751,6 +3749,7 @@ async function openBrowser(url) {
3751
3749
  }
3752
3750
  let openedURLs = [], replacePortPlaceholder = (url, port)=>url.replace(/<port>/g, String(port));
3753
3751
  async function server_open_open({ https, port, routes, config, clearCache }) {
3752
+ if ('true' === process.env.CSB) return;
3754
3753
  let { targets, before } = ((config)=>{
3755
3754
  let { open } = config.server;
3756
3755
  return 'boolean' == typeof open ? {
@@ -4154,13 +4153,15 @@ async function getResolvedClientConfig(clientConfig, serverConfig) {
4154
4153
  }
4155
4154
  let getCompilationMiddleware = async (compiler, options)=>{
4156
4155
  let { default: rsbuildDevMiddleware } = await import("../compiled/rsbuild-dev-middleware/index.js"), { clientPaths, callbacks, devConfig, serverConfig } = options, resolvedClientConfig = await getResolvedClientConfig(devConfig.client, serverConfig);
4157
- return applyToCompiler(compiler, (compiler)=>{
4158
- clientPaths && function({ compiler, clientPaths, devConfig, resolvedClientConfig }) {
4156
+ return applyToCompiler(compiler, (compiler, index)=>{
4157
+ var _Object_values_find;
4158
+ let token = null == (_Object_values_find = Object.values(options.environments).find((env)=>env.index === index)) ? void 0 : _Object_values_find.webSocketToken;
4159
+ token && (clientPaths && function({ compiler, clientPaths, devConfig, resolvedClientConfig, token }) {
4159
4160
  if (((compiler)=>{
4160
4161
  let { target } = compiler.options;
4161
4162
  return !!target && (Array.isArray(target) ? target.includes('web') : 'web' === target);
4162
4163
  })(compiler)) for (let clientPath of (new compiler.webpack.DefinePlugin({
4163
- RSBUILD_COMPILATION_NAME: JSON.stringify(getCompilationId(compiler)),
4164
+ RSBUILD_WEB_SOCKET_TOKEN: JSON.stringify(token),
4164
4165
  RSBUILD_CLIENT_CONFIG: JSON.stringify(devConfig.client),
4165
4166
  RSBUILD_RESOLVED_CLIENT_CONFIG: JSON.stringify(resolvedClientConfig),
4166
4167
  RSBUILD_DEV_LIVE_RELOAD: devConfig.liveReload
@@ -4171,19 +4172,26 @@ let getCompilationMiddleware = async (compiler, options)=>{
4171
4172
  compiler,
4172
4173
  clientPaths,
4173
4174
  devConfig,
4174
- resolvedClientConfig
4175
- }), ((compiler, { onDone, onInvalid })=>{
4175
+ resolvedClientConfig,
4176
+ token
4177
+ }), (({ compiler, token, callbacks: { onDone, onInvalid } })=>{
4176
4178
  if (((compiler)=>{
4177
4179
  let { target } = compiler.options;
4178
4180
  return !!target && (Array.isArray(target) ? target.includes('node') : 'node' === target);
4179
4181
  })(compiler)) return;
4180
4182
  let { compile, invalid, done } = compiler.hooks;
4181
4183
  compile.tap('rsbuild-dev-server', ()=>{
4182
- onInvalid(getCompilationId(compiler));
4184
+ onInvalid(token);
4183
4185
  }), invalid.tap('rsbuild-dev-server', (fileName)=>{
4184
- onInvalid(getCompilationId(compiler), fileName);
4185
- }), done.tap('rsbuild-dev-server', onDone);
4186
- })(compiler, callbacks);
4186
+ onInvalid(token, fileName);
4187
+ }), done.tap('rsbuild-dev-server', (stats)=>{
4188
+ onDone(token, stats);
4189
+ });
4190
+ })({
4191
+ compiler,
4192
+ callbacks,
4193
+ token
4194
+ }));
4187
4195
  }), rsbuildDevMiddleware(compiler, {
4188
4196
  etag: 'weak',
4189
4197
  publicPath: '/',
@@ -4229,6 +4237,10 @@ function socketServer_define_property(obj, key, value) {
4229
4237
  writable: !0
4230
4238
  }) : obj[key] = value, obj;
4231
4239
  }
4240
+ let parseQueryString = (req)=>{
4241
+ let queryStr = req.url ? req.url.split('?')[1] : '';
4242
+ return queryStr ? Object.fromEntries(new URLSearchParams(queryStr)) : {};
4243
+ };
4232
4244
  class SocketServer {
4233
4245
  clearHeartbeatTimer() {
4234
4246
  this.heartbeatTimer && (clearTimeout(this.heartbeatTimer), this.heartbeatTimer = null);
@@ -4243,51 +4255,44 @@ class SocketServer {
4243
4255
  }), this.wsServer.on('error', (err)=>{
4244
4256
  logger.error(err);
4245
4257
  }), this.heartbeatTimer = setTimeout(this.checkSockets, 30000).unref(), this.wsServer.on('connection', (socket, req)=>{
4246
- let queryStr = req.url ? req.url.split('?')[1] : '';
4247
- this.onConnect(socket, queryStr ? Object.fromEntries(new URLSearchParams(queryStr)) : {});
4258
+ let query = parseQueryString(req);
4259
+ this.onConnect(socket, query.token);
4248
4260
  });
4249
4261
  }
4250
- updateStats(stats) {
4251
- let compilationId = getCompilationId(stats.compilation);
4252
- this.stats[compilationId] = stats, this.sockets.length && this.sendStats({
4253
- compilationId
4262
+ updateStats(stats, token) {
4263
+ this.stats[token] = stats, this.sockets.size && this.sendStats({
4264
+ token
4254
4265
  });
4255
4266
  }
4256
- sockWrite({ type, compilationId, data }) {
4257
- for (let socket of this.sockets)this.send(socket, JSON.stringify({
4258
- type,
4259
- data,
4260
- compilationId
4261
- }));
4267
+ sockWrite(message, token) {
4268
+ let messageStr = JSON.stringify(message);
4269
+ if (token) {
4270
+ let socket = this.sockets.get(token);
4271
+ socket && this.send(socket, messageStr);
4272
+ } else for (let socket of this.sockets.values())this.send(socket, messageStr);
4262
4273
  }
4263
- singleWrite(socket, { type, data, compilationId }) {
4264
- this.send(socket, JSON.stringify({
4265
- type,
4266
- data,
4267
- compilationId
4268
- }));
4274
+ singleWrite(socket, message) {
4275
+ this.send(socket, JSON.stringify(message));
4269
4276
  }
4270
4277
  async close() {
4271
4278
  for (let socket of (this.clearHeartbeatTimer(), this.wsServer.removeAllListeners(), this.wsServer.clients))socket.terminate();
4272
- for (let socket of this.sockets)socket.close();
4273
- return this.stats = {}, this.initialChunks = {}, this.sockets.length = 0, new Promise((resolve, reject)=>{
4279
+ for (let socket of this.sockets.values())socket.close();
4280
+ return this.stats = {}, this.initialChunks = {}, this.sockets.clear(), new Promise((resolve, reject)=>{
4274
4281
  this.wsServer.close((err)=>{
4275
4282
  err ? reject(err) : resolve();
4276
4283
  });
4277
4284
  });
4278
4285
  }
4279
- onConnect(socket, params) {
4286
+ onConnect(socket, token) {
4280
4287
  socket.isAlive = !0, socket.on('pong', ()=>{
4281
4288
  socket.isAlive = !0;
4282
- }), this.sockets.push(socket), socket.on('close', ()=>{
4283
- let index = this.sockets.indexOf(socket);
4284
- index >= 0 && this.sockets.splice(index, 1);
4289
+ }), this.sockets.set(token, socket), socket.on('close', ()=>{
4290
+ this.sockets.delete(token);
4285
4291
  }), (this.options.hmr || this.options.liveReload) && this.singleWrite(socket, {
4286
- type: 'hot',
4287
- compilationId: params.compilationId
4292
+ type: 'hot'
4288
4293
  }), this.stats && this.sendStats({
4289
4294
  force: !0,
4290
- compilationId: params.compilationId
4295
+ token
4291
4296
  });
4292
4297
  }
4293
4298
  getStats(name) {
@@ -4312,37 +4317,33 @@ class SocketServer {
4312
4317
  root: curStats.compilation.compiler.options.context
4313
4318
  } : null;
4314
4319
  }
4315
- sendStats({ force = !1, compilationId }) {
4316
- let result = this.getStats(compilationId);
4320
+ sendStats({ force = !1, token }) {
4321
+ let result = this.getStats(token);
4317
4322
  if (!result) return null;
4318
4323
  let { statsJson, root } = result, newInitialChunks = new Set();
4319
4324
  if (statsJson.entrypoints) for (let entrypoint of Object.values(statsJson.entrypoints)){
4320
4325
  let chunks = entrypoint.chunks;
4321
4326
  if (Array.isArray(chunks)) for (let chunkName of chunks)chunkName && newInitialChunks.add(String(chunkName));
4322
4327
  }
4323
- let initialChunks = this.initialChunks[compilationId], shouldReload = !!statsJson.entrypoints && !!initialChunks && !(initialChunks.size === newInitialChunks.size && [
4328
+ let initialChunks = this.initialChunks[token], shouldReload = !!statsJson.entrypoints && !!initialChunks && !(initialChunks.size === newInitialChunks.size && [
4324
4329
  ...initialChunks
4325
4330
  ].every((value)=>newInitialChunks.has(value)));
4326
- if (this.initialChunks[compilationId] = newInitialChunks, shouldReload) return this.sockWrite({
4327
- type: 'static-changed',
4328
- compilationId
4329
- });
4331
+ if (this.initialChunks[token] = newInitialChunks, shouldReload) return this.sockWrite({
4332
+ type: 'static-changed'
4333
+ }, token);
4330
4334
  if (!force && statsJson && !statsJson.errorsCount && statsJson.assets && statsJson.assets.every((asset)=>!asset.emitted)) return this.sockWrite({
4331
- type: 'ok',
4332
- compilationId
4333
- });
4335
+ type: 'ok'
4336
+ }, token);
4334
4337
  if (this.sockWrite({
4335
4338
  type: 'hash',
4336
- compilationId,
4337
4339
  data: statsJson.hash
4338
- }), statsJson.errorsCount) {
4340
+ }, token), statsJson.errorsCount) {
4339
4341
  let { errors: formattedErrors } = formatStatsMessages({
4340
4342
  errors: getAllStatsErrors(statsJson),
4341
4343
  warnings: []
4342
4344
  });
4343
4345
  return this.sockWrite({
4344
4346
  type: 'errors',
4345
- compilationId,
4346
4347
  data: {
4347
4348
  text: formattedErrors,
4348
4349
  html: function(errors, root) {
@@ -4500,7 +4501,7 @@ class SocketServer {
4500
4501
  `;
4501
4502
  }(formattedErrors, root)
4502
4503
  }
4503
- });
4504
+ }, token);
4504
4505
  }
4505
4506
  if (statsJson.warningsCount) {
4506
4507
  let { warnings: formattedWarnings } = formatStatsMessages({
@@ -4509,29 +4510,30 @@ class SocketServer {
4509
4510
  });
4510
4511
  return this.sockWrite({
4511
4512
  type: 'warnings',
4512
- compilationId,
4513
4513
  data: {
4514
4514
  text: formattedWarnings
4515
4515
  }
4516
- });
4516
+ }, token);
4517
4517
  }
4518
4518
  return this.sockWrite({
4519
- type: 'ok',
4520
- compilationId
4521
- });
4519
+ type: 'ok'
4520
+ }, token);
4522
4521
  }
4523
4522
  send(connection, message) {
4524
4523
  1 === connection.readyState && connection.send(message);
4525
4524
  }
4526
- constructor(options){
4527
- socketServer_define_property(this, "wsServer", void 0), socketServer_define_property(this, "sockets", []), socketServer_define_property(this, "options", void 0), socketServer_define_property(this, "stats", void 0), socketServer_define_property(this, "initialChunks", void 0), socketServer_define_property(this, "heartbeatTimer", null), socketServer_define_property(this, "upgrade", (req, sock, head)=>{
4528
- this.wsServer.shouldHandle(req) && this.wsServer.handleUpgrade(req, sock, head, (connection)=>{
4525
+ constructor(options, environments){
4526
+ socketServer_define_property(this, "wsServer", void 0), socketServer_define_property(this, "sockets", new Map()), socketServer_define_property(this, "options", void 0), socketServer_define_property(this, "stats", void 0), socketServer_define_property(this, "initialChunks", void 0), socketServer_define_property(this, "heartbeatTimer", null), socketServer_define_property(this, "environments", void 0), socketServer_define_property(this, "upgrade", (req, socket, head)=>{
4527
+ if (!this.wsServer.shouldHandle(req)) return;
4528
+ let query = parseQueryString(req);
4529
+ if (!Object.values(this.environments).map((env)=>env.webSocketToken).includes(query.token)) return void socket.destroy();
4530
+ this.wsServer.handleUpgrade(req, socket, head, (connection)=>{
4529
4531
  this.wsServer.emit('connection', connection, req);
4530
4532
  });
4531
4533
  }), socketServer_define_property(this, "checkSockets", ()=>{
4532
4534
  for (let socket of this.wsServer.clients)socket.isAlive ? (socket.isAlive = !1, socket.ping(()=>{})) : socket.terminate();
4533
4535
  null !== this.heartbeatTimer && (this.heartbeatTimer = setTimeout(this.checkSockets, 30000).unref());
4534
- }), this.options = options, this.stats = {}, this.initialChunks = {};
4536
+ }), this.options = options, this.stats = {}, this.initialChunks = {}, this.environments = environments;
4535
4537
  }
4536
4538
  }
4537
4539
  function compilationManager_define_property(obj, key, value) {
@@ -4564,29 +4566,28 @@ class CompilationManager {
4564
4566
  });
4565
4567
  }
4566
4568
  async setupCompilationMiddleware() {
4567
- let { devConfig, serverConfig, publicPaths } = this, clientPaths = function(devConfig) {
4569
+ let { devConfig, serverConfig, publicPaths, environments } = this, clientPaths = function(devConfig) {
4568
4570
  var _devConfig_client;
4569
4571
  let clientPaths = [];
4570
4572
  return (devConfig.hmr || devConfig.liveReload) && (clientPaths.push(compilationManager_require.resolve('@rsbuild/core/client/hmr')), (null == (_devConfig_client = devConfig.client) ? void 0 : _devConfig_client.overlay) && clientPaths.push(`${compilationManager_require.resolve('@rsbuild/core/client/overlay')}`)), clientPaths;
4571
4573
  }(devConfig), middleware = await getCompilationMiddleware(this.compiler, {
4572
4574
  callbacks: {
4573
- onInvalid: (compilationId, fileName)=>{
4575
+ onInvalid: (token, fileName)=>{
4574
4576
  if ('string' == typeof fileName && HTML_REGEX.test(fileName)) return void this.socketServer.sockWrite({
4575
- type: 'static-changed',
4576
- compilationId
4577
- });
4577
+ type: 'static-changed'
4578
+ }, token);
4578
4579
  this.socketServer.sockWrite({
4579
- type: 'invalid',
4580
- compilationId
4581
- });
4580
+ type: 'invalid'
4581
+ }, token);
4582
4582
  },
4583
- onDone: (stats)=>{
4584
- this.socketServer.updateStats(stats);
4583
+ onDone: (token, stats)=>{
4584
+ this.socketServer.updateStats(stats, token);
4585
4585
  }
4586
4586
  },
4587
4587
  clientPaths,
4588
4588
  devConfig,
4589
- serverConfig
4589
+ serverConfig,
4590
+ environments
4590
4591
  }), { base } = serverConfig, assetPrefixes = publicPaths.map(getPathnameFromUrl).map((prefix)=>base && '/' !== base ? stripBase(prefix, base) : prefix), wrapper = async (req, res, next)=>{
4591
4592
  let { url } = req, assetPrefix = url && assetPrefixes.find((prefix)=>url.startsWith(prefix));
4592
4593
  assetPrefix && '/' !== assetPrefix ? (req.url = url.slice(assetPrefix.length - 1), middleware(req, res, (...args)=>{
@@ -4596,7 +4597,7 @@ class CompilationManager {
4596
4597
  wrapper.close = middleware.close, wrapper.watch = middleware.watch, this.middleware = wrapper;
4597
4598
  }
4598
4599
  constructor({ dev, server, compiler, publicPaths, environments }){
4599
- compilationManager_define_property(this, "middleware", void 0), compilationManager_define_property(this, "outputFileSystem", void 0), compilationManager_define_property(this, "devConfig", void 0), compilationManager_define_property(this, "serverConfig", void 0), compilationManager_define_property(this, "compiler", void 0), compilationManager_define_property(this, "publicPaths", void 0), compilationManager_define_property(this, "socketServer", void 0), compilationManager_define_property(this, "readFileSync", (fileName)=>'readFileSync' in this.outputFileSystem ? this.outputFileSystem.readFileSync(fileName, 'utf-8') : node_fs.readFileSync(fileName, 'utf-8')), this.devConfig = ((config, environments)=>{
4600
+ compilationManager_define_property(this, "middleware", void 0), compilationManager_define_property(this, "outputFileSystem", void 0), compilationManager_define_property(this, "devConfig", void 0), compilationManager_define_property(this, "serverConfig", void 0), compilationManager_define_property(this, "compiler", void 0), compilationManager_define_property(this, "environments", void 0), compilationManager_define_property(this, "publicPaths", void 0), compilationManager_define_property(this, "socketServer", void 0), compilationManager_define_property(this, "readFileSync", (fileName)=>'readFileSync' in this.outputFileSystem ? this.outputFileSystem.readFileSync(fileName, 'utf-8') : node_fs.readFileSync(fileName, 'utf-8')), this.devConfig = ((config, environments)=>{
4600
4601
  let writeToDiskValues = Object.values(environments).map((env)=>env.config.dev.writeToDisk);
4601
4602
  return 1 === new Set(writeToDiskValues).size ? {
4602
4603
  ...config,
@@ -4608,11 +4609,13 @@ class CompilationManager {
4608
4609
  return compilationName && environments[compilationName] && (writeToDisk = environments[compilationName].config.dev.writeToDisk ?? writeToDisk), 'function' == typeof writeToDisk ? writeToDisk(filePath) : writeToDisk;
4609
4610
  }
4610
4611
  };
4611
- })(dev, environments), this.serverConfig = server, this.compiler = compiler, this.publicPaths = publicPaths, this.outputFileSystem = node_fs, this.socketServer = new SocketServer(dev);
4612
+ })(dev, environments), this.serverConfig = server, this.compiler = compiler, this.environments = environments, this.publicPaths = publicPaths, this.outputFileSystem = node_fs, this.socketServer = new SocketServer(dev, environments);
4612
4613
  }
4613
4614
  }
4614
- let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xml/i, gzipMiddleware = ({ level = node_zlib.constants.Z_BEST_SPEED } = {})=>(req, res, next)=>{
4615
- let gzip, writeHeadStatus, accept = req.headers['accept-encoding'], encoding = 'string' == typeof accept && ENCODING_REGEX.test(accept);
4615
+ 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)=>{
4616
+ let gzip, writeHeadStatus;
4617
+ if (filter && !1 === filter(req, res)) return void next();
4618
+ let accept = req.headers['accept-encoding'], encoding = 'string' == typeof accept && ENCODING_REGEX.test(accept);
4616
4619
  if ('HEAD' === req.method || !encoding) return void next();
4617
4620
  let started = !1, { end, write, on, writeHead } = res, listeners = [], start = ()=>{
4618
4621
  if (!started) {
@@ -4736,7 +4739,8 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
4736
4739
  let { middlewares: proxyMiddlewares, upgrade } = await createProxyMiddleware(server.proxy);
4737
4740
  for (let middleware of (upgradeEvents.push(upgrade), proxyMiddlewares))middlewares.push(middleware);
4738
4741
  }
4739
- if (server.compress && middlewares.push(gzipMiddleware()), 'dev' === context.action && 'rspack' === context.bundlerType && compilationManager) {
4742
+ let { compress } = server;
4743
+ if (compress && middlewares.push(gzipMiddleware('object' == typeof compress ? compress : void 0)), 'dev' === context.action && 'rspack' === context.bundlerType && compilationManager) {
4740
4744
  var _compiler_options_experiments;
4741
4745
  let { compiler } = compilationManager;
4742
4746
  (helpers_isMultiCompiler(compiler) ? compiler.compilers.some((childCompiler)=>{
@@ -5154,7 +5158,7 @@ let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>new BasicRunne
5154
5158
  }, shutdownRefCount = 0, setupGracefulShutdown = ()=>{
5155
5159
  shutdownRefCount++;
5156
5160
  let onSigterm = ()=>{
5157
- handleTermination(constants.signals.SIGTERM + 128);
5161
+ handleTermination(external_node_os_constants.signals.SIGTERM + 128);
5158
5162
  };
5159
5163
  process.once('SIGTERM', onSigterm);
5160
5164
  let isCI = 'true' === process.env.CI, onStdinEnd = ()=>{
@@ -5487,9 +5491,14 @@ class RsbuildProdServer {
5487
5491
  for (let middleware of middlewares)this.middlewares.use(middleware);
5488
5492
  this.app.on('upgrade', upgrade);
5489
5493
  }
5490
- if (compress && this.middlewares.use(gzipMiddleware({
5491
- level: 6
5492
- })), base && '/' !== base && this.middlewares.use(getBaseMiddleware({
5494
+ if (compress) {
5495
+ let { constants } = await import("node:zlib");
5496
+ this.middlewares.use(gzipMiddleware({
5497
+ level: constants.Z_DEFAULT_COMPRESSION,
5498
+ ...'object' == typeof compress ? compress : void 0
5499
+ }));
5500
+ }
5501
+ if (base && '/' !== base && this.middlewares.use(getBaseMiddleware({
5493
5502
  base
5494
5503
  })), await this.applyStaticAssetMiddleware(), historyApiFallback) {
5495
5504
  let { default: connectHistoryApiFallback } = await import("../compiled/connect-history-api-fallback/index.js"), historyApiFallbackMiddleware = connectHistoryApiFallback(!0 === historyApiFallback ? {} : historyApiFallback);
@@ -6275,8 +6284,11 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
6275
6284
  rule.test(CSS_REGEX).type("javascript/auto").dependency({
6276
6285
  not: 'url'
6277
6286
  }).resourceQuery({
6278
- not: /raw|inline/
6279
- }), inlineRule.test(CSS_REGEX).type("javascript/auto").resourceQuery(/inline/), chain.module.rule(CHAIN_ID.RULE.CSS_RAW).test(CSS_REGEX).type('asset/source').resourceQuery(/raw/);
6287
+ not: [
6288
+ RAW_QUERY_REGEX,
6289
+ INLINE_QUERY_REGEX
6290
+ ]
6291
+ }), inlineRule.test(CSS_REGEX).type("javascript/auto").resourceQuery(INLINE_QUERY_REGEX), chain.module.rule(CHAIN_ID.RULE.CSS_RAW).test(CSS_REGEX).type('asset/source').resourceQuery(RAW_QUERY_REGEX);
6280
6292
  let emitCss = config.output.emitCss ?? 'web' === target;
6281
6293
  if (emitCss) if (config.output.injectStyles) {
6282
6294
  let styleLoaderOptions = reduceConfigs({
@@ -6458,9 +6470,9 @@ throw new Error('Failed to load Node.js addon: "${name}"\\n' + error);
6458
6470
  let { config, browserslist } = environment, cacheRoot = node_path.join(api.context.cachePath, '.swc'), rule = chain.module.rule(CHAIN_ID.RULE.JS).test(SCRIPT_REGEX).type("javascript/auto").dependency({
6459
6471
  not: 'url'
6460
6472
  }).resourceQuery({
6461
- not: /raw/
6473
+ not: RAW_QUERY_REGEX
6462
6474
  });
6463
- chain.module.rule(CHAIN_ID.RULE.JS_RAW).test(SCRIPT_REGEX).type('asset/source').resourceQuery(/raw/);
6475
+ chain.module.rule(CHAIN_ID.RULE.JS_RAW).test(SCRIPT_REGEX).type('asset/source').resourceQuery(RAW_QUERY_REGEX);
6464
6476
  let dataUriRule = chain.module.rule(CHAIN_ID.RULE.JS_DATA_URI).mimetype({
6465
6477
  or: [
6466
6478
  "text/javascript",
@@ -7253,9 +7265,9 @@ async function createRsbuild(options = {}) {
7253
7265
  exitCode
7254
7266
  });
7255
7267
  }, exitHook_callbacks.add(onExit), isRegistered || (isRegistered = !0, node_process.on('SIGINT', ()=>{
7256
- exit(constants.signals.SIGINT + 128, 'SIGINT');
7268
+ exit(external_node_os_constants.signals.SIGINT + 128, 'SIGINT');
7257
7269
  }), node_process.once('SIGTERM', ()=>{
7258
- exit(constants.signals.SIGTERM + 128, 'SIGTERM');
7270
+ exit(external_node_os_constants.signals.SIGTERM + 128, 'SIGTERM');
7259
7271
  }), node_process.once('exit', (exitCode)=>{
7260
7272
  exit(exitCode, 'exit');
7261
7273
  })), onExitListened = !0;
@@ -7633,11 +7645,11 @@ async function runCLI() {
7633
7645
  ].includes(level) && (logger.level = level);
7634
7646
  }
7635
7647
  let { npm_execpath } = process.env;
7636
- (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && logger.log(), logger.greet(` Rsbuild v1.4.2\n`);
7648
+ (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) && logger.log(), logger.greet(` Rsbuild v1.4.4\n`);
7637
7649
  try {
7638
7650
  !function() {
7639
7651
  let cli = ((name = "")=>new CAC(name))('rsbuild');
7640
- cli.help(), cli.version("1.4.2"), cli.option('--base <base>', 'specify the base path of the server').option('-c, --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--config-loader <loader>', 'specify the loader to load the config file, can be `jiti` or `native`', {
7652
+ cli.help(), cli.version("1.4.4"), cli.option('--base <base>', 'specify the base path of the server').option('-c, --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--config-loader <loader>', 'specify the loader to load the config file, can be `jiti` or `native`', {
7641
7653
  default: 'jiti'
7642
7654
  }).option('-r, --root <root>', 'specify the project root directory, can be an absolute path or a path relative to cwd').option('-m, --mode <mode>', 'specify the build mode, can be `development`, `production` or `none`').option('--log-level <level>', 'specify the log level, can be `info`, `warn`, `error` or `silent`').option('--env-mode <mode>', 'specify the env mode to load the `.env.[mode]` file').option('--environment <name>', 'specify the name of environment to build', {
7643
7655
  type: [
@@ -7695,5 +7707,5 @@ async function runCLI() {
7695
7707
  logger.error('Failed to start Rsbuild CLI.'), logger.error(err);
7696
7708
  }
7697
7709
  }
7698
- let src_version = "1.4.2";
7710
+ let src_version = "1.4.4";
7699
7711
  export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig_loadConfig as loadConfig, loadEnv, logger, mergeRsbuildConfig, rspack, runCLI, src_version as version };
@@ -28,6 +28,8 @@ export declare const HTML_REGEX: RegExp;
28
28
  export declare const JS_REGEX: RegExp;
29
29
  export declare const SCRIPT_REGEX: RegExp;
30
30
  export declare const CSS_REGEX: RegExp;
31
+ export declare const RAW_QUERY_REGEX: RegExp;
32
+ export declare const INLINE_QUERY_REGEX: RegExp;
31
33
  export declare const NODE_MODULES_REGEX: RegExp;
32
34
  export declare const PLUGIN_SWC_NAME = "rsbuild:swc";
33
35
  export declare const PLUGIN_CSS_NAME = "rsbuild:css";
@@ -19,4 +19,4 @@ export { type Logger, logger } from './logger';
19
19
  export { mergeRsbuildConfig } from './mergeConfig';
20
20
  export type { RsbuildDevServer } from './server/devServer';
21
21
  export type { StartServerResult } from './server/helper';
22
- export type { AliasStrategy, AppIcon, AppIconItem, Build, BuildOptions, BundlerPluginInstance, Charset, CleanDistPath, CleanDistPathObject, ClientConfig, CliShortcut, ConfigChain, ConfigChainWithContext, ConsoleType, CreateCompiler, CreateRsbuildOptions, CrossOrigin, CSSLoaderOptions, CSSModules, CSSModulesLocalsConvention, DataUriLimit, Decorators, DevConfig, DistPathConfig, EnvironmentConfig, EnvironmentContext, FilenameConfig, HistoryApiFallbackContext, HistoryApiFallbackOptions, HtmlBasicTag, HtmlConfig, HtmlFallback, HtmlRspackPlugin, HtmlTagContext, HtmlTagDescriptor, HtmlTagHandler, InlineChunkConfig, InlineChunkTest, InlineChunkTestFunction, InspectConfigOptions, InspectConfigResult, InternalContext, LegalComments, LogLevel, ManifestConfig, ManifestData, ManifestObjectConfig, MergedEnvironmentConfig, MetaAttrs, MetaOptions, Minify, ModifyBundlerChainFn, ModifyBundlerChainUtils, ModifyChainUtils, ModifyEnvironmentConfigFn, ModifyEnvironmentConfigUtils, ModifyHTMLContext, ModifyHTMLFn, ModifyHTMLTagsContext, ModifyHTMLTagsFn, ModifyRsbuildConfigFn, ModifyRsbuildConfigUtils, ModifyRspackConfigFn, ModifyRspackConfigUtils, ModifyWebpackChainFn, ModifyWebpackChainUtils, ModifyWebpackConfigFn, ModifyWebpackConfigUtils, ModuleFederationConfig, NormalizedConfig, NormalizedDevConfig, NormalizedEnvironmentConfig, NormalizedHtmlConfig, NormalizedModuleFederationConfig, NormalizedOutputConfig, NormalizedPerformanceConfig, NormalizedSecurityConfig, NormalizedServerConfig, NormalizedSourceConfig, NormalizedToolsConfig, OnAfterBuildFn, OnAfterCreateCompilerFn, OnAfterEnvironmentCompileFn, OnAfterStartDevServerFn, OnAfterStartProdServerFn, OnBeforeBuildFn, OnBeforeCreateCompilerFn, OnBeforeEnvironmentCompileFn, OnBeforeStartDevServerFn, OnBeforeStartProdServerFn, OnCloseBuildFn, OnCloseDevServerFn, OnDevCompileDoneFn, OnExitFn, OutputConfig, OutputStructure, PerformanceConfig, PluginManager, Polyfill, PostCSSLoaderOptions, PostCSSOptions, PostCSSPlugin, PreconnectOption, PreviewOptions, PrintUrls, ProcessAssetsDescriptor, ProcessAssetsHandler, ProcessAssetsHook, ProgressBarConfig, ProxyBypass, ProxyConfig, ProxyFilter, ProxyOptions, PublicDir, PublicDirOptions, RequestHandler, ResolvedCreateRsbuildOptions, ResolveHandler, ResolveHook, ResourceHintsIncludeType, RsbuildConfig, RsbuildContext, RsbuildEntry, RsbuildEntryDescription, RsbuildInstance, RsbuildMode, RsbuildPlugin, RsbuildPluginAPI, RsbuildPlugins, RsbuildProvider, RsbuildProviderHelpers, RsbuildTarget, RspackChain, RspackRule, ScriptInject, ScriptLoading, SecurityConfig, ServerConfig, SetupMiddlewaresContext, SetupMiddlewaresFn, SourceConfig, SourceMap, SplitChunks, SriAlgorithm, SriOptions, StartDevServerOptions, StyleLoaderOptions, ToolsConfig, TransformContext, TransformDescriptor, TransformHandler, TransformHook, TransformImport, WatchFiles, } from './types';
22
+ export type { AliasStrategy, AppIcon, AppIconItem, Build, BuildOptions, BundlerPluginInstance, Charset, CleanDistPath, CleanDistPathObject, ClientConfig, CliShortcut, CompressOptions, ConfigChain, ConfigChainWithContext, ConsoleType, CreateCompiler, CreateRsbuildOptions, CrossOrigin, CSSLoaderOptions, CSSModules, CSSModulesLocalsConvention, DataUriLimit, Decorators, DevConfig, DistPathConfig, EnvironmentConfig, EnvironmentContext, FilenameConfig, HistoryApiFallbackContext, HistoryApiFallbackOptions, HtmlBasicTag, HtmlConfig, HtmlFallback, HtmlRspackPlugin, HtmlTagContext, HtmlTagDescriptor, HtmlTagHandler, InlineChunkConfig, InlineChunkTest, InlineChunkTestFunction, InspectConfigOptions, InspectConfigResult, InternalContext, LegalComments, LogLevel, ManifestConfig, ManifestData, ManifestObjectConfig, MergedEnvironmentConfig, MetaAttrs, MetaOptions, Minify, ModifyBundlerChainFn, ModifyBundlerChainUtils, ModifyChainUtils, ModifyEnvironmentConfigFn, ModifyEnvironmentConfigUtils, ModifyHTMLContext, ModifyHTMLFn, ModifyHTMLTagsContext, ModifyHTMLTagsFn, ModifyRsbuildConfigFn, ModifyRsbuildConfigUtils, ModifyRspackConfigFn, ModifyRspackConfigUtils, ModifyWebpackChainFn, ModifyWebpackChainUtils, ModifyWebpackConfigFn, ModifyWebpackConfigUtils, ModuleFederationConfig, NormalizedConfig, NormalizedDevConfig, NormalizedEnvironmentConfig, NormalizedHtmlConfig, NormalizedModuleFederationConfig, NormalizedOutputConfig, NormalizedPerformanceConfig, NormalizedSecurityConfig, NormalizedServerConfig, NormalizedSourceConfig, NormalizedToolsConfig, OnAfterBuildFn, OnAfterCreateCompilerFn, OnAfterEnvironmentCompileFn, OnAfterStartDevServerFn, OnAfterStartProdServerFn, OnBeforeBuildFn, OnBeforeCreateCompilerFn, OnBeforeEnvironmentCompileFn, OnBeforeStartDevServerFn, OnBeforeStartProdServerFn, OnCloseBuildFn, OnCloseDevServerFn, OnDevCompileDoneFn, OnExitFn, OutputConfig, OutputStructure, PerformanceConfig, PluginManager, Polyfill, PostCSSLoaderOptions, PostCSSOptions, PostCSSPlugin, PreconnectOption, PreviewOptions, PrintUrls, ProcessAssetsDescriptor, ProcessAssetsHandler, ProcessAssetsHook, ProgressBarConfig, ProxyBypass, ProxyConfig, ProxyFilter, ProxyOptions, PublicDir, PublicDirOptions, RequestHandler, ResolvedCreateRsbuildOptions, ResolveHandler, ResolveHook, ResourceHintsIncludeType, RsbuildConfig, RsbuildContext, RsbuildEntry, RsbuildEntryDescription, RsbuildInstance, RsbuildMode, RsbuildPlugin, RsbuildPluginAPI, RsbuildPlugins, RsbuildProvider, RsbuildProviderHelpers, RsbuildTarget, RspackChain, RspackRule, ScriptInject, ScriptLoading, SecurityConfig, ServerConfig, SetupMiddlewaresContext, SetupMiddlewaresFn, SourceConfig, SourceMap, SplitChunks, SriAlgorithm, SriOptions, StartDevServerOptions, StyleLoaderOptions, ToolsConfig, TransformContext, TransformDescriptor, TransformHandler, TransformHook, TransformImport, WatchFiles, } from './types';
@@ -1,11 +1,11 @@
1
- import type { EnvironmentContext, DevConfig as OriginDevConfig, Rspack, ServerConfig } from '../types';
1
+ import type { EnvironmentContext, NormalizedDevConfig, NormalizedServerConfig, Rspack } from '../types';
2
2
  import { type CompilationMiddleware } from './compilationMiddleware';
3
3
  import { SocketServer } from './socketServer';
4
4
  type Options = {
5
5
  publicPaths: string[];
6
6
  environments: Record<string, EnvironmentContext>;
7
- dev: OriginDevConfig;
8
- server: ServerConfig;
7
+ dev: NormalizedDevConfig;
8
+ server: NormalizedServerConfig;
9
9
  compiler: Rspack.Compiler | Rspack.MultiCompiler;
10
10
  };
11
11
  /**
@@ -19,6 +19,7 @@ export declare class CompilationManager {
19
19
  private devConfig;
20
20
  private serverConfig;
21
21
  compiler: Rspack.Compiler | Rspack.MultiCompiler;
22
+ private environments;
22
23
  private publicPaths;
23
24
  socketServer: SocketServer;
24
25
  constructor({ dev, server, compiler, publicPaths, environments }: Options);
@@ -1,16 +1,20 @@
1
1
  import type { IncomingMessage, ServerResponse } from 'node:http';
2
- import type { Compiler, MultiCompiler } from '@rspack/core';
3
- import type { DevConfig, NextFunction, ServerConfig } from '../types';
2
+ import type { Compiler, MultiCompiler, Stats } from '@rspack/core';
3
+ import type { DevConfig, EnvironmentContext, NextFunction, ServerConfig } from '../types';
4
4
  export declare const isClientCompiler: (compiler: {
5
5
  options: {
6
6
  target?: Compiler["options"]["target"];
7
7
  };
8
8
  }) => boolean;
9
- type ServerCallbacks = {
10
- onInvalid: (compilationId?: string, fileName?: string | null) => void;
11
- onDone: (stats: any) => void;
9
+ export type ServerCallbacks = {
10
+ onInvalid: (token: string, fileName?: string | null) => void;
11
+ onDone: (token: string, stats: Stats) => void;
12
12
  };
13
- export declare const setupServerHooks: (compiler: Compiler, { onDone, onInvalid }: ServerCallbacks) => void;
13
+ export declare const setupServerHooks: ({ compiler, token, callbacks: { onDone, onInvalid }, }: {
14
+ compiler: Compiler;
15
+ token: string;
16
+ callbacks: ServerCallbacks;
17
+ }) => void;
14
18
  type Middleware = (req: IncomingMessage, res: ServerResponse, next: NextFunction) => Promise<void>;
15
19
  export type CompilationMiddlewareOptions = {
16
20
  /**
@@ -23,6 +27,7 @@ export type CompilationMiddlewareOptions = {
23
27
  callbacks: ServerCallbacks;
24
28
  devConfig: DevConfig;
25
29
  serverConfig: ServerConfig;
30
+ environments: Record<string, EnvironmentContext>;
26
31
  };
27
32
  export type CompilationMiddleware = Middleware & {
28
33
  close: (callback: (err: Error | null | undefined) => void) => any;
@@ -1,4 +1,2 @@
1
- import type { RequestHandler } from '../types';
2
- export declare const gzipMiddleware: ({ level, }?: {
3
- level?: number;
4
- }) => RequestHandler;
1
+ import type { CompressOptions, RequestHandler } from '../types';
2
+ export declare const gzipMiddleware: ({ filter, level, }?: CompressOptions) => RequestHandler;
@@ -1,7 +1,7 @@
1
1
  import type { IncomingMessage, Server } from 'node:http';
2
2
  import type { Http2SecureServer } from 'node:http2';
3
3
  import type { Socket } from 'node:net';
4
- import type { InternalContext, NormalizedConfig, OutputStructure, PrintUrls, Routes, RsbuildEntry, Rspack } from '../types';
4
+ import type { InternalContext, NormalizedConfig, OutputStructure, PrintUrls, Routes, RsbuildEntry } from '../types';
5
5
  /**
6
6
  * It used to subscribe http upgrade event
7
7
  */
@@ -71,7 +71,6 @@ export declare const getAddressUrls: ({ protocol, port, host, }: {
71
71
  port: number;
72
72
  host?: string;
73
73
  }) => Promise<AddressUrl[]>;
74
- export declare const getCompilationId: (compiler: Rspack.Compiler | Rspack.Compilation) => string;
75
74
  export declare function getServerTerminator(server: Server | Http2SecureServer): () => Promise<void>;
76
75
  /**
77
76
  * Escape HTML characters
@@ -1,10 +1,9 @@
1
1
  import type { IncomingMessage } from 'node:http';
2
2
  import type { Socket } from 'node:net';
3
- import type { DevConfig, Rspack } from '../types';
3
+ import type { DevConfig, EnvironmentContext, Rspack } from '../types';
4
4
  import type { SockWriteType } from './devServer';
5
5
  interface SocketMessage {
6
6
  type: SockWriteType;
7
- compilationId?: string;
8
7
  data?: Record<string, any> | string | boolean;
9
8
  }
10
9
  export declare class SocketServer {
@@ -14,13 +13,20 @@ export declare class SocketServer {
14
13
  private stats;
15
14
  private initialChunks;
16
15
  private heartbeatTimer;
17
- constructor(options: DevConfig);
18
- upgrade: (req: IncomingMessage, sock: Socket, head: any) => void;
16
+ private environments;
17
+ constructor(options: DevConfig, environments: Record<string, EnvironmentContext>);
18
+ upgrade: (req: IncomingMessage, socket: Socket, head: Buffer) => void;
19
19
  private checkSockets;
20
20
  private clearHeartbeatTimer;
21
21
  prepare(): Promise<void>;
22
- updateStats(stats: Rspack.Stats): void;
23
- sockWrite({ type, compilationId, data }: SocketMessage): void;
22
+ updateStats(stats: Rspack.Stats, token: string): void;
23
+ /**
24
+ * Write message to each socket
25
+ * @param message - The message to send
26
+ * @param token - The token of the socket to send the message to,
27
+ * if not provided, the message will be sent to all sockets
28
+ */
29
+ sockWrite(message: SocketMessage, token?: string): void;
24
30
  private singleWrite;
25
31
  close(): Promise<void>;
26
32
  private onConnect;