@rsbuild/core 2.2.11 → 2.2.12

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.
@@ -1,8 +1,8 @@
1
1
  (() => {
2
2
  var __webpack_modules__ = {
3
- 793: (module, __unused_webpack_exports, __nccwpck_require__) => {
3
+ 419: (module, __unused_webpack_exports, __nccwpck_require__) => {
4
4
  "use strict";
5
- const { HtmlWebpackChildCompiler } = __nccwpck_require__(82);
5
+ const { HtmlWebpackChildCompiler } = __nccwpck_require__(536);
6
6
  const compilerMap = new WeakMap();
7
7
  class CachedChildCompilation {
8
8
  constructor(compiler) {
@@ -307,7 +307,7 @@
307
307
  }
308
308
  module.exports = { CachedChildCompilation };
309
309
  },
310
- 82: (module) => {
310
+ 536: (module) => {
311
311
  "use strict";
312
312
  class HtmlWebpackChildCompiler {
313
313
  compilationPromise;
@@ -476,7 +476,7 @@
476
476
  }
477
477
  module.exports = { HtmlWebpackChildCompiler };
478
478
  },
479
- 474: (module) => {
479
+ 488: (module) => {
480
480
  "use strict";
481
481
  function none(chunks) {
482
482
  return chunks;
@@ -492,7 +492,7 @@
492
492
  }
493
493
  module.exports = { auto: none, manual, none };
494
494
  },
495
- 621: (module) => {
495
+ 239: (module) => {
496
496
  "use strict";
497
497
  module.exports = function (err) {
498
498
  return {
@@ -516,7 +516,7 @@
516
516
  };
517
517
  };
518
518
  },
519
- 116: (module, __unused_webpack_exports, __nccwpck_require__) => {
519
+ 86: (module, __unused_webpack_exports, __nccwpck_require__) => {
520
520
  "use strict";
521
521
  const { AsyncSeriesWaterfallHook } = __nccwpck_require__(176);
522
522
  const htmlWebpackPluginHooksMap = new WeakMap();
@@ -542,7 +542,7 @@
542
542
  }
543
543
  module.exports = { getHtmlRspackPluginHooks };
544
544
  },
545
- 265: (module) => {
545
+ 539: (module) => {
546
546
  const voidTags = [
547
547
  "area",
548
548
  "base",
@@ -610,19 +610,19 @@
610
610
  htmlTagObjectToString,
611
611
  };
612
612
  },
613
- 52: (module, __unused_webpack_exports, __nccwpck_require__) => {
613
+ 202: (module, __unused_webpack_exports, __nccwpck_require__) => {
614
614
  "use strict";
615
615
  const promisify = __nccwpck_require__(23).promisify;
616
616
  const vm = __nccwpck_require__(154);
617
617
  const fs = __nccwpck_require__(896);
618
618
  const path = __nccwpck_require__(928);
619
- const { CachedChildCompilation } = __nccwpck_require__(793);
619
+ const { CachedChildCompilation } = __nccwpck_require__(419);
620
620
  const { createHtmlTagObject, htmlTagObjectToString, HtmlTagArray } =
621
- __nccwpck_require__(265);
622
- const prettyError = __nccwpck_require__(621);
623
- const chunkSorter = __nccwpck_require__(474);
621
+ __nccwpck_require__(539);
622
+ const prettyError = __nccwpck_require__(239);
623
+ const chunkSorter = __nccwpck_require__(488);
624
624
  const getHtmlRspackPluginHooks =
625
- __nccwpck_require__(116).getHtmlRspackPluginHooks;
625
+ __nccwpck_require__(86).getHtmlRspackPluginHooks;
626
626
  const WITH_PLACEHOLDER = "function __with_placeholder__";
627
627
  class HtmlRspackPlugin {
628
628
  constructor(userOptions = {}) {
@@ -2395,6 +2395,6 @@
2395
2395
  }
2396
2396
  if (typeof __nccwpck_require__ !== "undefined")
2397
2397
  __nccwpck_require__.ab = __dirname + "/";
2398
- var __webpack_exports__ = __nccwpck_require__(52);
2398
+ var __webpack_exports__ = __nccwpck_require__(202);
2399
2399
  module.exports = __webpack_exports__;
2400
2400
  })();
File without changes
@@ -1,15 +1,15 @@
1
1
  (() => {
2
2
  "use strict";
3
3
  var __webpack_modules__ = {
4
- 951: (module, __unused_webpack_exports, __nccwpck_require__) => {
5
- module.exports = __nccwpck_require__(265)["default"];
4
+ 760: (module, __unused_webpack_exports, __nccwpck_require__) => {
5
+ module.exports = __nccwpck_require__(286)["default"];
6
6
  },
7
- 265: (__unused_webpack_module, exports, __nccwpck_require__) => {
7
+ 286: (__unused_webpack_module, exports, __nccwpck_require__) => {
8
8
  var __webpack_unused_export__;
9
9
  __webpack_unused_export__ = { value: true };
10
10
  exports["default"] = loader;
11
- var _nodePath = _interopRequireDefault(__nccwpck_require__(760));
12
- var _utils = __nccwpck_require__(284);
11
+ var _nodePath = _interopRequireDefault(__nccwpck_require__(379));
12
+ var _utils = __nccwpck_require__(327);
13
13
  function _interopRequireDefault(e) {
14
14
  return e && e.__esModule ? e : { default: e };
15
15
  }
@@ -179,7 +179,7 @@
179
179
  callback(null, result.css, map, { ast });
180
180
  }
181
181
  },
182
- 284: (module, exports, __nccwpck_require__) => {
182
+ 327: (module, exports, __nccwpck_require__) => {
183
183
  module = __nccwpck_require__.nmd(module);
184
184
  Object.defineProperty(exports, "__esModule", { value: true });
185
185
  exports.exec = exec;
@@ -192,7 +192,7 @@
192
192
  exports.reportError = reportError;
193
193
  exports.warningFactory = warningFactory;
194
194
  var _nodeModule = _interopRequireDefault(__nccwpck_require__(995));
195
- var _nodePath = _interopRequireDefault(__nccwpck_require__(760));
195
+ var _nodePath = _interopRequireDefault(__nccwpck_require__(379));
196
196
  var _nodeUrl = _interopRequireDefault(__nccwpck_require__(136));
197
197
  var _cosmiconfig = {};
198
198
  function _interopRequireDefault(e) {
@@ -675,7 +675,7 @@
675
675
  995: (module) => {
676
676
  module.exports = require("node:module");
677
677
  },
678
- 760: (module) => {
678
+ 379: (module) => {
679
679
  module.exports = require("node:path");
680
680
  },
681
681
  136: (module) => {
@@ -716,6 +716,6 @@
716
716
  })();
717
717
  if (typeof __nccwpck_require__ !== "undefined")
718
718
  __nccwpck_require__.ab = __dirname + "/";
719
- var __webpack_exports__ = __nccwpck_require__(951);
719
+ var __webpack_exports__ = __nccwpck_require__(760);
720
720
  module.exports = __webpack_exports__;
721
721
  })();
@@ -261,6 +261,8 @@ declare namespace WebSocket {
261
261
  allowSynchronousEvents?: boolean | undefined;
262
262
  autoPong?: boolean | undefined;
263
263
  maxPayload?: number | undefined;
264
+ maxBufferedChunks?: number | undefined;
265
+ maxFragments?: number | undefined;
264
266
  skipUTF8Validation?: boolean | undefined;
265
267
  createConnection?: typeof createConnection | undefined;
266
268
  finishRequest?: FinishRequestCallback | undefined;
@@ -344,6 +346,8 @@ declare namespace WebSocket {
344
346
  clientTracking?: boolean | undefined;
345
347
  perMessageDeflate?: boolean | PerMessageDeflateOptions | undefined;
346
348
  maxPayload?: number | undefined;
349
+ maxBufferedChunks?: number | undefined;
350
+ maxFragments?: number | undefined;
347
351
  skipUTF8Validation?: boolean | undefined;
348
352
  WebSocket?: U | undefined;
349
353
  }
@@ -1 +1 @@
1
- {"name":"ws","version":"8.18.1","license":"MIT","types":"index.d.ts","type":"commonjs"}
1
+ {"name":"ws","version":"8.18.2","license":"MIT","types":"index.d.ts","type":"commonjs"}
@@ -1,17 +1,22 @@
1
1
  import node_path from "node:path";
2
2
  import { relativeWithin } from "./1.js";
3
3
  import { isCSSModules } from "./c.js";
4
- let HASH_PLACEHOLDER_REGEX = /\[(?:[^:\]]+:)?(?:chunkhash|contenthash|hash|fullhash)(?::[^\]]+)?]/i, getRelativePath = (root, resourcePath)=>{
4
+ let HASH_PLACEHOLDER_REGEX = /\[(?:[^:\]]+:)?(?:chunkhash|contenthash|hash|fullhash)(?::[^\]]+)?]/i, BASE_URI = 'rsbuild-css-url://', ABSOLUTE_PUBLIC_PATH = `${BASE_URI}/public-path/`, AUTO_PUBLIC_PATH = '__rsbuild_css_url_auto_public_path__', SINGLE_DOT_PATH_SEGMENT = '__rsbuild_css_url_single_dot__', getPublicPathForExtract = (publicPath)=>/^[a-zA-Z][a-zA-Z\d+\-.]*?:/.test(publicPath) ? publicPath : `${ABSOLUTE_PUBLIC_PATH}${publicPath.replaceAll('.', SINGLE_DOT_PATH_SEGMENT)}`, getRelativePath = (root, resourcePath)=>{
5
5
  let relativePath = relativeWithin(root, resourcePath);
6
6
  if (relativePath) return relativePath.replace(/\\/g, '/');
7
7
  }, pitch = async function(remainingRequest) {
8
8
  let root, resourcePath, nameSource, hash, options = this.getOptions();
9
9
  if (isCSSModules(options.modules, this)) throw Error('[rsbuild:css] CSS Modules do not support the ?url query. Use ?inline to import the compiled CSS content as a string.');
10
- let content = ((moduleExports)=>{
10
+ let { publicPath } = this._compilation.outputOptions;
11
+ 'auto' === publicPath && (publicPath = AUTO_PUBLIC_PATH);
12
+ let publicPathForExtract = 'function' == typeof publicPath ? (pathData, assetInfo)=>getPublicPathForExtract(publicPath(pathData, assetInfo)) : 'string' == typeof publicPath ? getPublicPathForExtract(publicPath) : publicPath, content = ((moduleExports)=>{
11
13
  let content = moduleExports && 'object' == typeof moduleExports && 'default' in moduleExports ? moduleExports.default : moduleExports;
12
14
  if ('string' != typeof content) throw Error('[rsbuild:css] Expected CSS ?url imports to export a string.');
13
15
  return content;
14
- })(await this.importModule(`!!${remainingRequest}`)), ext = node_path.extname(this.resourcePath), sourceFilename = node_path.relative(this.rootContext, this.resourcePath).replace(/\\/g, '/'), name = (root = this.rootContext, resourcePath = this.resourcePath, nameSource = getRelativePath(node_path.join(root, 'src'), resourcePath) ?? getRelativePath(root, resourcePath) ?? node_path.basename(resourcePath), ext ? nameSource.slice(0, -ext.length) : nameSource), contentHash = ((hash = this.utils.createHash(this._compilation.outputOptions.hashFunction)).update(Buffer.from(content)), hash.digest(this._compilation.outputOptions.hashDigest || 'hex')), pathData = {
16
+ })(await this.importModule(`!!${remainingRequest}`, {
17
+ publicPath: publicPathForExtract,
18
+ baseUri: `${BASE_URI}/`
19
+ })).replaceAll(ABSOLUTE_PUBLIC_PATH, '').replaceAll(SINGLE_DOT_PATH_SEGMENT, '.'), ext = node_path.extname(this.resourcePath), sourceFilename = node_path.relative(this.rootContext, this.resourcePath).replace(/\\/g, '/'), name = (root = this.rootContext, resourcePath = this.resourcePath, nameSource = getRelativePath(node_path.join(root, 'src'), resourcePath) ?? getRelativePath(root, resourcePath) ?? node_path.basename(resourcePath), ext ? nameSource.slice(0, -ext.length) : nameSource), contentHash = ((hash = this.utils.createHash(this._compilation.outputOptions.hashFunction)).update(Buffer.from(content)), hash.digest(this._compilation.outputOptions.hashDigest || 'hex')), pathData = {
15
20
  contentHash,
16
21
  chunk: {
17
22
  name,
@@ -22,10 +27,15 @@ let HASH_PLACEHOLDER_REGEX = /\[(?:[^:\]]+:)?(?:chunkhash|contenthash|hash|fullh
22
27
  }
23
28
  }, assetInfo = {
24
29
  sourceFilename
25
- }, filenameTemplate = 'function' == typeof options.filename ? options.filename(pathData, assetInfo) : options.filename, { path: filename, info } = this._compilation.getAssetPathWithInfo(filenameTemplate, pathData);
26
- return this.emitFile(filename, content, void 0, {
30
+ }, filenameTemplate = 'function' == typeof options.filename ? options.filename(pathData, assetInfo) : options.filename, { path: filename, info } = this._compilation.getAssetPathWithInfo(filenameTemplate, pathData), css = content;
31
+ if (publicPath === AUTO_PUBLIC_PATH) {
32
+ let undoPath = node_path.posix.relative(node_path.posix.dirname(filename), '.');
33
+ css = content.replaceAll(AUTO_PUBLIC_PATH, undoPath ? `${undoPath}/` : '');
34
+ }
35
+ return this.emitFile(filename, css, void 0, {
27
36
  ...info,
28
37
  ...assetInfo,
38
+ minimized: options.minimized,
29
39
  immutable: info.immutable || HASH_PLACEHOLDER_REGEX.test(filenameTemplate)
30
40
  }), `export default import.meta.rspackPublicPath + ${JSON.stringify(filename)};`;
31
41
  };
@@ -3,6 +3,7 @@ import type { CSSLoaderOptions } from '../types/index.js';
3
3
  type CSSUrlLoaderOptions = {
4
4
  filename: string | ((pathData: PathData, assetInfo?: AssetInfo) => string);
5
5
  modules: CSSLoaderOptions['modules'];
6
+ minimized: boolean;
6
7
  };
7
8
  declare const cssUrlLoader: LoaderDefinitionFunction<CSSUrlLoaderOptions>;
8
9
  export declare const pitch: PitchLoaderDefinitionFunction<CSSUrlLoaderOptions>;
package/dist/m.js CHANGED
@@ -2,7 +2,7 @@
2
2
  let runtimeProcessArgs, runtimeInfo, swcHelpersPath, pluginHelper_htmlPlugin;
3
3
  import { rspackRequire, moduleFactories, compatGetDefaultExport, createFakeNamespaceObject } from "./rslib-runtime.js";
4
4
  import { rspack as core_rspack } from "@rspack/core";
5
- import node_util, { promisify, stripVTControlCharacters } from "node:util";
5
+ import node_util, { format as external_node_util_format, promisify, stripVTControlCharacters } from "node:util";
6
6
  import node_path, { dirname, isAbsolute as external_node_path_isAbsolute, join, posix, relative, resolve as external_node_path_resolve, sep } from "node:path";
7
7
  import { builtinModules, createRequire, createRequire as __rspack_createRequire } from "node:module";
8
8
  import node_fs, { existsSync } from "node:fs";
@@ -12,7 +12,7 @@ import { URL as external_node_url_URL, pathToFileURL, fileURLToPath as __rspack_
12
12
  import { isPromise, isRegExp } from "node:util/types";
13
13
  import { readFile } from "node:fs/promises";
14
14
  import node_zlib, { constants as external_node_zlib_constants } from "node:zlib";
15
- import { once } from "node:events";
15
+ import { once as external_node_events_once } from "node:events";
16
16
  import { ALL_INTERFACES_IPV4, IMAGE_EXTENSIONS, ASSETS_DIST_DIR, FONT_DIST_DIR, AUDIO_EXTENSIONS, ensureAbsolutePath, NODE_MODULES_REGEX, FONT_EXTENSIONS, HMR_SOCKET_PATH, WASM_DIST_DIR, VIDEO_EXTENSIONS, BROWSER_LOG_PREFIX, toPosixPath, TRACK_EXTENSIONS, IMAGE_DIST_DIR, RSBUILD_OUTPUTS_PATH, DEFAULT_STACK_TRACE, LOADER_PATH, ASSET_EXTENSIONS, SVG_DIST_DIR, isWindows, COMPILED_PATH, WORKER_QUERY_REGEX, TS_CONFIG_FILE, dedupeNestedPaths, CSS_REGEX, relativeWithin, LAZY_COMPILATION_IDENTIFIER, DEFAULT_BROWSERSLIST, JS_REGEX, MEDIA_DIST_DIR, SCRIPT_REGEX, DEFAULT_WEB_BROWSERSLIST, getCompiledPath, normalizeRuleConditionPath, getPathnameFromUrl, toRelativePath, isDeno, CSS_DIST_DIR, INLINE_QUERY_REGEX, STATIC_PATH, RAW_QUERY_REGEX, PLUGIN_SWC_NAME, CLIENT_PATH, getCommonParentPath, LOCALHOST, JS_DIST_DIR, URL_QUERY_REGEX } from "./1.js";
17
17
  import { cachedImport as cachedImport_cachedImport, getTinyglobby } from "./r.js";
18
18
  var superClass, superClass1, __rspack_import_meta_filename__ = __rspack_fileURLToPath(import.meta.url);
@@ -2373,12 +2373,19 @@ function createEnvironmentAsyncHook() {
2373
2373
  }
2374
2374
  };
2375
2375
  }
2376
+ let SKIP_CALLBACK = Symbol('skip callback');
2376
2377
  function createAsyncHook() {
2377
- let preGroup = [], postGroup = [], defaultGroup = [];
2378
+ let preGroup = [], postGroup = [], defaultGroup = [], register = (cb, once)=>{
2379
+ let { handler, order } = isFunction(cb) ? {
2380
+ handler: cb
2381
+ } : cb, group = defaultGroup;
2382
+ if ('pre' === order ? group = preGroup : 'post' === order && (group = postGroup), !once) return void group.push(handler);
2383
+ let called = !1, onceCallback = (...args)=>called ? SKIP_CALLBACK : (called = !0, group.splice(group.indexOf(onceCallback), 1), handler(...args));
2384
+ group.push(onceCallback);
2385
+ };
2378
2386
  return {
2379
- tap: (cb)=>{
2380
- isFunction(cb) ? defaultGroup.push(cb) : 'pre' === cb.order ? preGroup.push(cb.handler) : 'post' === cb.order ? postGroup.push(cb.handler) : defaultGroup.push(cb.handler);
2381
- },
2387
+ tap: (cb)=>register(cb, !1),
2388
+ tapOnce: (cb)=>register(cb, !0),
2382
2389
  callChain: async (...params)=>{
2383
2390
  for (let callback of [
2384
2391
  ...preGroup,
@@ -2386,7 +2393,7 @@ function createAsyncHook() {
2386
2393
  ...postGroup
2387
2394
  ]){
2388
2395
  let result = await callback(...params);
2389
- void 0 !== result && (params[0] = result);
2396
+ result !== SKIP_CALLBACK && void 0 !== result && (params[0] = result);
2390
2397
  }
2391
2398
  return params;
2392
2399
  },
@@ -2398,7 +2405,7 @@ function createAsyncHook() {
2398
2405
  ], results = [];
2399
2406
  for (let callback of callbacks){
2400
2407
  let result = await callback(...params);
2401
- results.push(result);
2408
+ result !== SKIP_CALLBACK && results.push(result);
2402
2409
  }
2403
2410
  return results;
2404
2411
  }
@@ -3291,7 +3298,7 @@ function createPublicContext(context) {
3291
3298
  async function createContext(options, userConfig, logger, loadConfigResult) {
3292
3299
  let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = join(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, hooks = initHooks();
3293
3300
  return {
3294
- version: "2.2.11",
3301
+ version: "2.2.12",
3295
3302
  rootPath,
3296
3303
  configFile: loadConfigResult?.filePath ?? userConfig._privateMeta?.configFilePath,
3297
3304
  configFileDependencies: loadConfigResult?.dependencies ?? userConfig._privateMeta?.configFileDependencies ?? [],
@@ -5119,8 +5126,6 @@ function pluginExternals() {
5119
5126
  ...autoExternalRules
5120
5127
  ] : autoExternalRules : externals;
5121
5128
  mergedExternals && chain.externals(mergedExternals);
5122
- }), api.onBeforeCreateCompiler(({ bundlerConfigs })=>{
5123
- for (let config of bundlerConfigs)(Array.isArray(config.target) ? config.target.includes('webworker') : 'webworker' === config.target) && !config.output?.module && config.externals && delete config.externals;
5124
5129
  });
5125
5130
  }
5126
5131
  };
@@ -5143,19 +5148,19 @@ function getCompression(compressed) {
5143
5148
  totalKey: 'totalGzipSize'
5144
5149
  };
5145
5150
  }
5146
- async function calcCompressedSize(input, type, level) {
5147
- return (await new Promise((resolve, reject)=>{
5148
- let callback = (err, result)=>{
5149
- err ? reject(err) : resolve(result);
5150
- };
5151
- 'brotli' === type ? node_zlib.brotliCompress(input, {
5151
+ function calcCompressedSize(input, type, level) {
5152
+ return new Promise((resolve, reject)=>{
5153
+ let stream = 'brotli' === type ? node_zlib.createBrotliCompress({
5152
5154
  params: {
5153
5155
  [node_zlib.constants.BROTLI_PARAM_QUALITY]: level
5154
5156
  }
5155
- }, callback) : node_zlib.gzip(input, {
5157
+ }) : node_zlib.createGzip({
5156
5158
  level
5157
- }, callback);
5158
- })).length;
5159
+ }), size = 0;
5160
+ stream.on('data', (chunk)=>{
5161
+ size += chunk.length;
5162
+ }), stream.on('error', reject), stream.on('end', ()=>resolve(size)), stream.end(input);
5163
+ });
5159
5164
  }
5160
5165
  function getSnapshotPath(dir, snapshotHash) {
5161
5166
  return snapshotHash ? node_path.join(dir, `rsbuild/file-sizes-${snapshotHash}.json`) : node_path.join(dir, 'rsbuild/file-sizes.json');
@@ -6000,7 +6005,7 @@ function doesChunkBelongToHtml({ chunk, htmlPluginData }) {
6000
6005
  let { options } = htmlPluginData.plugin;
6001
6006
  return recursiveChunkEntryNames(chunk).some((chunkName)=>isChunksFiltered(chunkName, options?.chunks, options?.excludeChunks));
6002
6007
  }
6003
- let getManifestPlugin = cachedImport_cachedImport(()=>import("./manifest-plugin.js").then(rspackRequire.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/rspack-manifest-plugin/5.2.2/12a6328c2e9bf08e26b58fdf2ee8c0ecfe31cb73b1db951f7711492f8c9e3b25/node_modules/rspack-manifest-plugin/dist/index.js"))), isCSSPath = (filePath)=>filePath.endsWith('.css');
6008
+ let getManifestPlugin = cachedImport_cachedImport(()=>import("./manifest-plugin.js").then(rspackRequire.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/rspack-manifest-plugin/5.2.2/c829036b5a98f872a31c12f9fca915a8b3b1d943468219bdea4197081cf13ac8/node_modules/rspack-manifest-plugin/dist/index.js"))), isCSSPath = (filePath)=>filePath.endsWith('.css');
6004
6009
  function normalizeManifestObjectConfig(manifest) {
6005
6010
  let defaultOptions = {
6006
6011
  prefix: !0,
@@ -6769,6 +6774,10 @@ function createAssetsMiddleware(context, ready, outputFileSystem) {
6769
6774
  }
6770
6775
  -2 === parsedRanges ? logger.error("[rsbuild:middleware] A malformed 'Range' header was provided. A regular response will be sent for this request.") : parsedRanges.length > 1 && logger.error("[rsbuild:middleware] A 'Range' header with multiple ranges was provided. Multiple ranges are not supported, so a regular response will be sent for this request."), -2 !== parsedRanges && 1 === parsedRanges.length && (res.statusCode = 206, res.setHeader('Content-Range', getValueContentRangeHeader('bytes', size, parsedRanges[0])), [offset, len] = getOffsetAndLenFromRange(parsedRanges[0]));
6771
6776
  }
6777
+ if ('HEAD' === req.method) {
6778
+ res.setHeader('Content-Length', len), 404 === res.statusCode && (res.statusCode = 200), res.end();
6779
+ return;
6780
+ }
6772
6781
  let [start, end] = calcStartAndEnd(offset, len);
6773
6782
  try {
6774
6783
  readStream = createReadStream(filename, outputFileSystem, start, end);
@@ -6776,10 +6785,7 @@ function createAssetsMiddleware(context, ready, outputFileSystem) {
6776
6785
  await goNext();
6777
6786
  return;
6778
6787
  }
6779
- if (res.setHeader('Content-Length', len), 'HEAD' === req.method) {
6780
- 404 === res.statusCode && (res.statusCode = 200), res.end();
6781
- return;
6782
- }
6788
+ res.setHeader('Content-Length', len);
6783
6789
  let cleanup = ()=>{
6784
6790
  destroyStream(readStream, !0);
6785
6791
  };
@@ -6797,38 +6803,41 @@ function createAssetsMiddleware(context, ready, outputFileSystem) {
6797
6803
  });
6798
6804
  };
6799
6805
  }
6800
- async function setupOutputFileSystem(writeToDisk, compilers) {
6801
- if (!0 !== writeToDisk) {
6806
+ async function setupOutputFileSystem(writeAllToDisk, compilers) {
6807
+ if (!writeAllToDisk) {
6802
6808
  let { createMemoryFileSystem } = await import("./memfs.js"), outputFileSystem = createMemoryFileSystem();
6803
6809
  for (let compiler of compilers)compiler.outputFileSystem = outputFileSystem;
6804
6810
  }
6805
6811
  let compiler = compilers.find((compiler)=>!!compiler.outputFileSystem);
6806
6812
  return compiler?.outputFileSystem ?? node_fs;
6807
6813
  }
6808
- function setupWriteToDisk(compilers, writeToDisk, logger) {
6809
- for (let compiler of compilers)compiler.hooks.emit.tap('DevMiddleware', ()=>{
6810
- compiler.__hasRsbuildAssetEmittedCallback || (compiler.hooks.assetEmitted.tapAsync('DevMiddleware', (_file, info, callback)=>{
6811
- if (compiler.outputFileSystem === node_fs) return void callback();
6812
- let { targetPath, content, compilation } = info;
6813
- if (!('function' != typeof writeToDisk || writeToDisk(targetPath, compilation.name))) return void callback();
6814
- let dir = node_path.dirname(targetPath), name = compiler.options.name ? `Child "${compiler.options.name}": ` : '';
6815
- node_fs.mkdir(dir, {
6816
- recursive: !0
6817
- }, (mkdirError)=>{
6818
- if (mkdirError) {
6819
- logger.error(`[rsbuild:middleware] ${name}Unable to write "${dir}" directory to disk:\n${mkdirError.message}`), callback(mkdirError);
6820
- return;
6821
- }
6822
- node_fs.writeFile(targetPath, content, (writeFileError)=>{
6823
- if (writeFileError) {
6824
- logger.error(`[rsbuild:middleware] ${name}Unable to write "${targetPath}" asset to disk:\n${writeFileError.message}`), callback(writeFileError);
6814
+ function setupWriteToDisk(compilers, writeToDiskList, logger) {
6815
+ for (let [index, compiler] of compilers.entries()){
6816
+ let writeToDisk = writeToDiskList[index];
6817
+ writeToDisk && compiler.hooks.emit.tap('DevMiddleware', ()=>{
6818
+ compiler.__hasRsbuildAssetEmittedCallback || (compiler.hooks.assetEmitted.tapAsync('DevMiddleware', (_file, info, callback)=>{
6819
+ if (compiler.outputFileSystem === node_fs) return void callback();
6820
+ let { targetPath } = info;
6821
+ if ('function' == typeof writeToDisk && !writeToDisk(targetPath)) return void callback();
6822
+ let { content } = info, dir = node_path.dirname(targetPath), name = compiler.options.name ? `Child "${compiler.options.name}": ` : '';
6823
+ node_fs.mkdir(dir, {
6824
+ recursive: !0
6825
+ }, (mkdirError)=>{
6826
+ if (mkdirError) {
6827
+ logger.error(`[rsbuild:middleware] ${name}Unable to write "${dir}" directory to disk:\n${mkdirError.message}`), callback(mkdirError);
6825
6828
  return;
6826
6829
  }
6827
- callback();
6830
+ node_fs.writeFile(targetPath, content, (writeFileError)=>{
6831
+ if (writeFileError) {
6832
+ logger.error(`[rsbuild:middleware] ${name}Unable to write "${targetPath}" asset to disk:\n${writeFileError.message}`), callback(writeFileError);
6833
+ return;
6834
+ }
6835
+ callback();
6836
+ });
6828
6837
  });
6829
- });
6830
- }), compiler.__hasRsbuildAssetEmittedCallback = !0);
6831
- });
6838
+ }), compiler.__hasRsbuildAssetEmittedCallback = !0);
6839
+ });
6840
+ }
6832
6841
  }
6833
6842
  let noop = ()=>{}, normalizeLiveReload = (liveReload)=>'boolean' == typeof liveReload ? {
6834
6843
  enabled: liveReload,
@@ -6867,8 +6876,7 @@ init(
6867
6876
  }).apply(compiler);
6868
6877
  }
6869
6878
  let assets_middleware_assetsMiddleware = async ({ config, compiler, context, socketServer, resolvedPort })=>{
6870
- var config1;
6871
- let watching, writeToDiskValues, { logger } = context, resolvedHost = await resolveHostname(config.server.host), { environments, environmentList } = context;
6879
+ let watching, { logger } = context, resolvedHost = await resolveHostname(config.server.host), { environmentList } = context;
6872
6880
  applyToCompiler(compiler, (compiler, index)=>{
6873
6881
  let environment = environmentList[index];
6874
6882
  if (!environment) return;
@@ -6932,14 +6940,11 @@ let assets_middleware_assetsMiddleware = async ({ config, compiler, context, soc
6932
6940
  'done' === context.buildState.status && flushCallbacks();
6933
6941
  });
6934
6942
  });
6935
- let writeToDisk = (config1 = config.dev, 1 === new Set(writeToDiskValues = environmentList.map((env)=>env.config.dev.writeToDisk)).size ? writeToDiskValues[0] : (filePath, name)=>{
6936
- let { writeToDisk } = config1;
6937
- return name && environments[name] && (writeToDisk = environments[name].config.dev.writeToDisk ?? writeToDisk), 'function' == typeof writeToDisk ? writeToDisk(filePath) : writeToDisk;
6938
- });
6939
- writeToDisk && setupWriteToDisk(compilers, writeToDisk, logger);
6943
+ let writeToDiskList = environmentList.map((environment)=>environment.config.dev.writeToDisk);
6944
+ writeToDiskList.some(Boolean) && setupWriteToDisk(compilers, writeToDiskList, logger);
6940
6945
  let instance = createAssetsMiddleware(context, (callback)=>{
6941
6946
  'done' === context.buildState.status || 'failed' === context.buildState.status ? callback() : callbacks.push(callback);
6942
- }, await setupOutputFileSystem(writeToDisk, compilers));
6947
+ }, await setupOutputFileSystem(writeToDiskList.every((writeToDisk)=>!0 === writeToDisk), compilers));
6943
6948
  return instance.watch = ()=>{
6944
6949
  if (compiler.watching) watching = compiler.watching;
6945
6950
  else {
@@ -7505,14 +7510,17 @@ function gzipMiddleware_gzipMiddleware({ filter, level = node_zlib.constants.Z_B
7505
7510
  if (!CONTENT_TYPE_REGEX.test(contentTypeValue) || 'text/event-stream' === contentTypeValue.split(';', 1)[0].trim().toLowerCase()) return !1;
7506
7511
  let size = res.getHeader('Content-Length');
7507
7512
  return void 0 === size || Number(size) > 1024;
7508
- })(res)) for (let listener of (res.setHeader('Content-Encoding', 'gzip'), res.removeHeader('Content-Length'), (gzip = node_zlib.createGzip({
7509
- level
7510
- })).on('data', (chunk)=>{
7511
- write(chunk) || gzip.pause();
7512
- }), on('drain', ()=>gzip.resume()), gzip.on('end', ()=>{
7513
- end();
7514
- }), listeners))gzip.on(...listener);
7515
- else for (let listener of listeners)on.apply(res, listener);
7513
+ })(res)) {
7514
+ let contentLength = Number(res.getHeader('Content-Length'));
7515
+ for (let listener of (res.setHeader('Content-Encoding', 'gzip'), res.removeHeader('Content-Length'), (gzip = node_zlib.createGzip({
7516
+ level,
7517
+ chunkSize: contentLength > 524288 ? 65536 : void 0
7518
+ })).on('data', (chunk)=>{
7519
+ write(chunk) || gzip.pause();
7520
+ }), on('drain', ()=>gzip.resume()), on('close', ()=>gzip.destroy()), gzip.on('end', ()=>{
7521
+ end();
7522
+ }), listeners))gzip.on(...listener);
7523
+ } else for (let listener of listeners)on.apply(res, listener);
7516
7524
  let statusCode = writeHeadStatus ?? res.statusCode;
7517
7525
  void 0 !== writeHeadMessage ? writeHead(statusCode, writeHeadMessage) : writeHead(statusCode);
7518
7526
  };
@@ -7617,7 +7625,17 @@ let faviconFallbackMiddleware = (req, res, next)=>{
7617
7625
  resolve(!!stats?.isFile());
7618
7626
  });
7619
7627
  }), isFileExistsInDistPaths = async (distPaths, filename, outputFileSystem)=>{
7620
- for (let distPath of distPaths)if (await middlewares_isFileExists(node_path.join(distPath, filename), outputFileSystem)) return !0;
7628
+ let decodedFilename;
7629
+ try {
7630
+ decodedFilename = decodeURIComponent(filename);
7631
+ } catch {
7632
+ return !1;
7633
+ }
7634
+ if (decodedFilename.includes('\0') || UP_PATH_REGEXP.test(decodedFilename) && UP_PATH_REGEXP.test(node_path.normalize(`./${decodedFilename}`))) return !1;
7635
+ for (let distPath of distPaths){
7636
+ let filePath = node_path.join(distPath, decodedFilename);
7637
+ if (await middlewares_isFileExists(filePath, outputFileSystem)) return !0;
7638
+ }
7621
7639
  return !1;
7622
7640
  }, maybeHTMLRequest = (req)=>{
7623
7641
  if (!req.url || !req.headers || 'GET' !== req.method && 'HEAD' !== req.method) return !1;
@@ -7675,14 +7693,14 @@ function formatProxyOptions(proxyOptions, logger) {
7675
7693
  let logPrefix = color.dim('[http-proxy-middleware]: '), defaultOptions = {
7676
7694
  changeOrigin: !0,
7677
7695
  logger: {
7678
- info (msg) {
7679
- logger.debug(logPrefix + msg);
7696
+ info (msg, ...args) {
7697
+ logger.debug(logPrefix + external_node_util_format(msg, ...args));
7680
7698
  },
7681
- warn: (msg)=>{
7682
- logger.warn(logPrefix + msg);
7699
+ warn: (msg, ...args)=>{
7700
+ logger.warn(logPrefix + external_node_util_format(msg, ...args));
7683
7701
  },
7684
- error: (msg)=>{
7685
- logger.error(logPrefix + msg);
7702
+ error: (msg, ...args)=>{
7703
+ logger.error(logPrefix + external_node_util_format(msg, ...args));
7686
7704
  }
7687
7705
  }
7688
7706
  };
@@ -8291,7 +8309,7 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8291
8309
  customShortcuts: shortcutsOptions.custom,
8292
8310
  logger
8293
8311
  });
8294
- context.hooks.onCloseDevServer.tap(cleanup);
8312
+ context.hooks.onCloseDevServer.tapOnce(cleanup);
8295
8313
  }
8296
8314
  !getPortSilently && portTip && logger.info(portTip);
8297
8315
  }, cacheableLoadBundle = createCacheableFunction(loadBundle), cacheableTransformedHtml = createCacheableFunction((_stats, entryName, utils)=>((entryName, utils)=>{
@@ -8350,12 +8368,12 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8350
8368
  listen: async ()=>{
8351
8369
  if (!httpServer) throw Error(`${color.dim('[rsbuild:server]')} Can not listen dev server as ${color.yellow('server.middlewareMode')} is enabled.`);
8352
8370
  let serverTerminator = getServerTerminator(httpServer);
8353
- logger.debug('listen dev server'), context.hooks.onCloseDevServer.tap(serverTerminator);
8371
+ logger.debug('listen dev server'), context.hooks.onCloseDevServer.tapOnce(serverTerminator);
8354
8372
  try {
8355
8373
  return httpServer.listen({
8356
8374
  host,
8357
8375
  port
8358
- }), await once(httpServer, 'listening'), middlewares.use(optionsFallbackMiddleware), middlewares.use(notFoundMiddleware), devServer.connectWebSocket({
8376
+ }), await external_node_events_once(httpServer, 'listening'), middlewares.use(optionsFallbackMiddleware), middlewares.use(notFoundMiddleware), devServer.connectWebSocket({
8359
8377
  server: httpServer
8360
8378
  }), logger.debug('listen dev server done'), await devServer.afterListen(), {
8361
8379
  port,
@@ -8395,7 +8413,7 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8395
8413
  })).filter((item)=>'function' == typeof item),
8396
8414
  ...setupPostCallbacks
8397
8415
  ];
8398
- return runCompile ? context.hooks.onBeforeCreateCompiler.tap(beforeCreateCompiler) : await beforeCreateCompiler(), state.buildManager = runCompile ? await startCompile() : void 0, state.fileWatcher = await setupWatchFiles({
8416
+ return runCompile ? context.hooks.onBeforeCreateCompiler.tapOnce(beforeCreateCompiler) : await beforeCreateCompiler(), state.buildManager = runCompile ? await startCompile() : void 0, state.fileWatcher = await setupWatchFiles({
8399
8417
  config,
8400
8418
  buildManager: state.buildManager,
8401
8419
  root: context.rootPath
@@ -8487,7 +8505,7 @@ async function startPreviewServer(context, config, { getPortSilently } = {}) {
8487
8505
  if (httpServer.listen({
8488
8506
  host,
8489
8507
  port
8490
- }), await once(httpServer, 'listening'), await context.hooks.onAfterStartPreviewServer.callBatch({
8508
+ }), await external_node_events_once(httpServer, 'listening'), await context.hooks.onAfterStartPreviewServer.callBatch({
8491
8509
  port,
8492
8510
  routes,
8493
8511
  environments: context.environments
@@ -9173,17 +9191,36 @@ try {
9173
9191
  }, updateRules = async (callback, options = {})=>{
9174
9192
  options.skipMain || await callback(mainRule, 'main'), await callback(inlineRule, 'inline'), await callback(urlRule, 'url');
9175
9193
  }, cssLoaderPath = getCompiledPath('css-loader');
9176
- if (await updateRules((rule)=>{
9194
+ await updateRules((rule)=>{
9177
9195
  rule.use(CHAIN_ID.USE.CSS).loader(cssLoaderPath);
9178
- }), !1 !== config.tools.lightningcssLoader) {
9196
+ });
9197
+ let cssUrlMinimized = !1;
9198
+ if (!1 !== config.tools.lightningcssLoader) {
9179
9199
  emitCss && importLoaders.normal++, importLoaders.inline++;
9180
- let minifyCss = parseMinifyOptions(config).minifyCss, { browserslist } = environment;
9200
+ let { minifyCss, cssOptions } = parseMinifyOptions(config), { browserslist } = environment;
9181
9201
  if ('node' === target) {
9182
9202
  let webEnvironment = Object.values(environments).find((env)=>'web' === env.config.output.target);
9183
- webEnvironment && (browserslist = webEnvironment.browserslist, minifyCss = parseMinifyOptions(webEnvironment.config).minifyCss);
9203
+ if (webEnvironment) {
9204
+ browserslist = webEnvironment.browserslist;
9205
+ let webMinifyOptions = parseMinifyOptions(webEnvironment.config);
9206
+ minifyCss = webMinifyOptions.minifyCss, cssOptions ??= webMinifyOptions.cssOptions;
9207
+ }
9184
9208
  }
9209
+ let cssUrlMinimizerOptions = minifyCss ? ((cssOptions)=>{
9210
+ let options = helpers_castArray(cssOptions), { minimizerOptions, test, include, exclude } = options[0] ?? {};
9211
+ return !(options.length > 1 || [
9212
+ test,
9213
+ include,
9214
+ exclude
9215
+ ].some((value)=>void 0 !== value)) && (minimizerOptions ?? {});
9216
+ })(cssOptions) : {};
9185
9217
  await updateRules(async (rule, type)=>{
9186
9218
  let minify = ('inline' === type || 'url' === type || config.output.injectStyles) && minifyCss, lightningcssOptions = await getLightningCSSLoaderOptions(config, browserslist, minify);
9219
+ if ('url' === type && !0 === lightningcssOptions.minify && !1 !== cssUrlMinimizerOptions) {
9220
+ var loaderOptions;
9221
+ let options;
9222
+ loaderOptions = lightningcssOptions, options = cjs_0_default()(loaderOptions, cssUrlMinimizerOptions), isPlainObject(cssUrlMinimizerOptions.targets) && (options.targets = cssUrlMinimizerOptions.targets), lightningcssOptions = options, cssUrlMinimized = !0;
9223
+ }
9187
9224
  rule.use(CHAIN_ID.USE.LIGHTNINGCSS).loader('builtin:lightningcss-loader').options(lightningcssOptions);
9188
9225
  }, {
9189
9226
  skipMain: !emitCss
@@ -9225,7 +9262,8 @@ try {
9225
9262
  let cssUrlFilename = getFilename(config, 'css', isProd), cssUrlPath = config.output.distPath.css;
9226
9263
  urlRule.use(CHAIN_ID.USE.CSS_URL).options({
9227
9264
  filename: 'function' == typeof cssUrlFilename ? (pathData, assetInfo)=>posix.join(cssUrlPath, cssUrlFilename(pathData, assetInfo)) : posix.join(cssUrlPath, cssUrlFilename),
9228
- modules: cssLoaderOptions.modules
9265
+ modules: cssLoaderOptions.modules,
9266
+ minimized: cssUrlMinimized
9229
9267
  });
9230
9268
  let isStringExport = 'string' === cssLoaderOptions.exportType;
9231
9269
  if (isStringExport && mainRule.uses.has(CHAIN_ID.USE.MINI_CSS_EXTRACT) && mainRule.uses.delete(CHAIN_ID.USE.MINI_CSS_EXTRACT), emitCss && !config.output.injectStyles && !isStringExport) {
@@ -10205,7 +10243,7 @@ let applyServerOptions = (command)=>{
10205
10243
  };
10206
10244
  function setupCommands(argv) {
10207
10245
  let cli = ((name = "")=>new CAC(name))('rsbuild');
10208
- cli.version("2.2.11"), cli.option('--base <base>', 'Set the base path of the server').option('-c, --config <config>', 'Set the configuration file (relative or absolute path)').option('--config-loader <loader>', 'Set the config file loader (auto | jiti | native)', {
10246
+ cli.version("2.2.12"), cli.option('--base <base>', 'Set the base path of the server').option('-c, --config <config>', 'Set the configuration file (relative or absolute path)').option('--config-loader <loader>', 'Set the config file loader (auto | jiti | native)', {
10209
10247
  default: 'auto'
10210
10248
  }).option('--dist-path <dir>', 'Set the root directory of output files').option('--source-map', 'Enable source map').option('--env-dir <dir>', 'Set the directory for loading `.env` files').option('--env-mode <mode>', 'Set the env mode to load the `.env.[mode]` file').option('--environment <name>', 'Set the environment name(s) to build', {
10211
10249
  type: [
@@ -10270,7 +10308,7 @@ function setupCommands(argv) {
10270
10308
  }
10271
10309
  function showGreeting() {
10272
10310
  let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
10273
- src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.2.11\n`);
10311
+ src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.2.12\n`);
10274
10312
  }
10275
10313
  function setupLogLevel(argv) {
10276
10314
  if (argv.length <= 3) return;
@@ -10292,5 +10330,5 @@ function runCLI({ argv = process.argv } = {}) {
10292
10330
  src_logger.error('Failed to start Rsbuild CLI.'), src_logger.error(err), process.exit(1);
10293
10331
  }
10294
10332
  }
10295
- let src_version = "2.2.11";
10333
+ let src_version = "2.2.12";
10296
10334
  export { core_rspack as rspack, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig_loadConfig as loadConfig, loadEnv, logger_createLogger as createLogger, mergeRsbuildConfig, mrmime_lookup, runCLI, src_logger as logger, src_version as version };