@rsbuild/core 2.2.4 → 2.2.6

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/626.js CHANGED
@@ -2280,6 +2280,9 @@ let compiler_isMultiCompiler = (compiler)=>'compilers' in compiler && Array.isAr
2280
2280
  }, addCompilationError = (compilation, message)=>{
2281
2281
  compilation.errors.push(new core_rspack.WebpackError(message));
2282
2282
  };
2283
+ function formatDiagnosticPath(filePath, root) {
2284
+ return /^(\.\.[\\/]){4}/.test(filePath) ? external_node_path_resolve(root, filePath) : filePath;
2285
+ }
2283
2286
  function resolveFileName(stats, logger) {
2284
2287
  let file = stats.file || stats.moduleName;
2285
2288
  if (file) return removeLoaderChainDelimiter(file, logger);
@@ -2292,7 +2295,7 @@ function resolveFileName(stats, logger) {
2292
2295
  }
2293
2296
  return '';
2294
2297
  }
2295
- function formatModuleTrace(stats, errorFile, level, logger) {
2298
+ function formatModuleTrace(stats, errorFile, root, level, logger) {
2296
2299
  if (!stats.moduleTrace) return;
2297
2300
  let moduleNames = stats.moduleTrace.map((trace)=>trace.originName && removeLoaderChainDelimiter(trace.originName, logger)).filter((trace)=>trace && !trace.startsWith(LAZY_COMPILATION_IDENTIFIER));
2298
2301
  if (!moduleNames.length) return;
@@ -2300,7 +2303,7 @@ function formatModuleTrace(stats, errorFile, level, logger) {
2300
2303
  let formatted = removeLoaderChainDelimiter(errorFile, logger);
2301
2304
  moduleNames[0] !== formatted && moduleNames.unshift(formatted);
2302
2305
  }
2303
- let trace = moduleNames.slice().reverse();
2306
+ let trace = moduleNames.slice().reverse().map((name)=>formatDiagnosticPath(name, root));
2304
2307
  return trace.length > 4 && !isVerbose(logger) && (trace = [
2305
2308
  ...trace.slice(0, 2),
2306
2309
  `... (${trace.length - 2 - 2} hidden)`,
@@ -2356,10 +2359,10 @@ function formatStatsError(stats, root, level = 'error', logger) {
2356
2359
  return snippet.length > 30 && (snippet = `${snippet.slice(0, 30)}...`), `File: ${color.cyan('data-uri virtual module')} ${color.dim(`(${snippet})`)}\n`;
2357
2360
  }
2358
2361
  let prefix = root + sep;
2359
- return (fileName.startsWith(prefix) && (fileName = fileName.replace(prefix, `.${sep}`)), /:\d+:\d+/.test(fileName)) ? `File: ${color.cyan(fileName)}\n` : stats.loc ? `File: ${color.cyan(`${fileName}:${stats.loc}`)}\n` : `File: ${color.cyan(`${fileName}:1:1`)}\n`;
2362
+ return (fileName = fileName.startsWith(prefix) ? fileName.replace(prefix, `.${sep}`) : formatDiagnosticPath(fileName, root), /:\d+:\d+/.test(fileName)) ? `File: ${color.cyan(fileName)}\n` : stats.loc ? `File: ${color.cyan(`${fileName}:${stats.loc}`)}\n` : `File: ${color.cyan(`${fileName}:1:1`)}\n`;
2360
2363
  })(fileName, stats, root)}${stats.message}`, verbose = isVerbose(logger);
2361
2364
  if (verbose && (stats.details && (message += `\nDetails: ${stats.details}\n`), stats.stack && (message += `\n${stats.stack}`)), 'error' === level || isVerbose(logger)) {
2362
- let moduleTrace = formatModuleTrace(stats, fileName, level, logger);
2365
+ let moduleTrace = formatModuleTrace(stats, fileName, root, level, logger);
2363
2366
  moduleTrace && (message += moduleTrace);
2364
2367
  }
2365
2368
  let innerError = '-- inner error --';
@@ -3425,7 +3428,7 @@ function createPublicContext(context) {
3425
3428
  async function createContext(options, userConfig, logger, loadConfigResult) {
3426
3429
  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();
3427
3430
  return {
3428
- version: "2.2.4",
3431
+ version: "2.2.6",
3429
3432
  rootPath,
3430
3433
  configFile: loadConfigResult?.filePath ?? userConfig._privateMeta?.configFilePath,
3431
3434
  configFileDependencies: loadConfigResult?.dependencies ?? userConfig._privateMeta?.configFileDependencies ?? [],
@@ -4094,7 +4097,7 @@ async function createCompiler_createCompiler(options) {
4094
4097
  if (item1 < item2) return -1;
4095
4098
  }
4096
4099
  return 0;
4097
- })(version, '2.0.0') >= 0)) throw Error(`${color.dim('[rsbuild]')} The current Rspack version does not meet the requirements, the minimum supported version of Rspack is ${color.green("2.0.0")}`);
4100
+ })(version, '2.2.3') >= 0)) throw Error(`${color.dim('[rsbuild]')} The current Rspack version does not meet the requirements, the minimum supported version of Rspack is ${color.green("2.2.3")}`);
4098
4101
  let isMultiCompiler = rspackConfigs.length > 1, compiler = isMultiCompiler ? core_rspack(rspackConfigs) : core_rspack(rspackConfigs[0]);
4099
4102
  'true' === process.env.RSPACK_UNSAFE_FAST_DROP && (compiler.unsafeFastDrop = !0);
4100
4103
  let isVersionLogged = !1, isCompiling = !1, hasFatalError = !1, compilers = isMultiCompiler ? compiler.compilers : [
@@ -5261,11 +5264,36 @@ function pluginExternals() {
5261
5264
  }
5262
5265
  };
5263
5266
  }
5264
- async function gzipSize(input) {
5267
+ function getCompression(compressed) {
5268
+ let { type = 'gzip', level = 6 } = 'object' == typeof compressed ? compressed : {};
5269
+ return 'brotli' === type ? {
5270
+ type,
5271
+ level,
5272
+ header: 'Br',
5273
+ label: 'brotli',
5274
+ sizeKey: 'brotliSize',
5275
+ totalKey: 'totalBrotliSize'
5276
+ } : {
5277
+ type,
5278
+ level,
5279
+ header: 'Gzip',
5280
+ label: 'gzipped',
5281
+ sizeKey: 'gzippedSize',
5282
+ totalKey: 'totalGzipSize'
5283
+ };
5284
+ }
5285
+ async function calcCompressedSize(input, type, level) {
5265
5286
  return (await new Promise((resolve, reject)=>{
5266
- node_zlib.gzip(input, (err, result)=>{
5287
+ let callback = (err, result)=>{
5267
5288
  err ? reject(err) : resolve(result);
5268
- });
5289
+ };
5290
+ 'brotli' === type ? node_zlib.brotliCompress(input, {
5291
+ params: {
5292
+ [node_zlib.constants.BROTLI_PARAM_QUALITY]: level
5293
+ }
5294
+ }, callback) : node_zlib.gzip(input, {
5295
+ level
5296
+ }, callback);
5269
5297
  })).length;
5270
5298
  }
5271
5299
  function getSnapshotPath(dir, snapshotHash) {
@@ -5298,7 +5326,7 @@ let EXCLUDE_ASSET_REGEX = /\.(?:map|LICENSE\.txt|d\.(?:ts|mts|cts))$/, isSignifi
5298
5326
  length: label.length
5299
5327
  };
5300
5328
  }, getAssetColor = (size)=>size > 300000 ? color.red : size > 100000 ? color.yellow : (input)=>input;
5301
- function getHeader(maxFileLength, maxSizeLength, fileHeader, showGzipHeader) {
5329
+ function getHeader(maxFileLength, maxSizeLength, fileHeader, compressionHeader) {
5302
5330
  let lengths = [
5303
5331
  maxFileLength,
5304
5332
  maxSizeLength
@@ -5306,7 +5334,7 @@ function getHeader(maxFileLength, maxSizeLength, fileHeader, showGzipHeader) {
5306
5334
  fileHeader,
5307
5335
  'Size'
5308
5336
  ];
5309
- showGzipHeader && rowTypes.push('Gzip');
5337
+ compressionHeader && rowTypes.push(compressionHeader);
5310
5338
  let headerRow = rowTypes.reduce((prev, cur, index)=>{
5311
5339
  let length = lengths[index], curLabel = cur;
5312
5340
  return length && (curLabel = cur.length < length ? cur + ' '.repeat(length - cur.length) : cur), `${prev + curLabel} `;
@@ -5321,30 +5349,31 @@ let calcFileSize = (len)=>{
5321
5349
  return -1 === queryIndex ? assetName : assetName.slice(0, queryIndex);
5322
5350
  };
5323
5351
  async function printFileSizes(options, stats, rootPath, distPath, environmentName, previousSizes, saveSnapshot) {
5324
- let logs = [], showDetail = !1 !== options.detail, showDiff = !1 !== options.diff && null !== previousSizes, showTotal = !1 !== options.total;
5352
+ let logs = [], compression = getCompression(options.compressed), prev = previousSizes?.[environmentName], showDetail = !1 !== options.detail, showDiff = !1 !== options.diff && null !== previousSizes, prevType = prev?.compressionType ?? (!!prev?.totalGzipSize && 'gzip'), showCompressedDiff = showDiff && prevType === compression.type, showTotal = !1 !== options.total;
5325
5353
  if (!showTotal && !showDetail) return {
5326
5354
  logs
5327
5355
  };
5328
5356
  let relativeDistPath = node_path.relative(rootPath, distPath), rootFolderLabel = `${relativeDistPath || '.'}${node_path.sep}`, snapshot = saveSnapshot ? {
5329
5357
  files: {},
5330
5358
  totalSize: 0,
5331
- totalGzipSize: 0
5332
- } : null, formatAsset = (filePath, size, gzippedSize)=>{
5359
+ totalGzipSize: 0,
5360
+ compressionType: !!options.compressed && compression.type
5361
+ } : null, formatAsset = (filePath, size, compressedSize)=>{
5333
5362
  let normalizedPath = '';
5334
5363
  (snapshot || showDiff) && (normalizedPath = normalizeFilePath(filePath), snapshot && (snapshot.files[normalizedPath] = {
5335
5364
  size,
5336
- gzippedSize: gzippedSize ?? void 0
5365
+ [compression.sizeKey]: compressedSize ?? void 0
5337
5366
  }));
5338
- let sizeLabel = calcFileSize(size), sizeLabelLength = sizeLabel.length, gzipSizeLabel = gzippedSize ? getAssetColor(gzippedSize)(calcFileSize(gzippedSize)) : null;
5367
+ let sizeLabel = calcFileSize(size), sizeLabelLength = sizeLabel.length, compressedSizeLabel = compressedSize ? getAssetColor(compressedSize)(calcFileSize(compressedSize)) : null;
5339
5368
  if (showDiff) {
5340
- let sizeData = previousSizes[environmentName]?.files[normalizedPath], sizeDiff = size - (sizeData?.size ?? 0);
5369
+ let sizeData = prev?.files[normalizedPath], sizeDiff = size - (sizeData?.size ?? 0);
5341
5370
  if (isSignificantDiff(sizeDiff)) {
5342
5371
  let { label, length } = formatDiff(sizeDiff);
5343
5372
  sizeLabel += ` ${label}`, sizeLabelLength += length + 1;
5344
5373
  }
5345
- if (null !== gzippedSize) {
5346
- let gzipDiff = gzippedSize - (sizeData?.gzippedSize ?? 0);
5347
- isSignificantDiff(gzipDiff) && (gzipSizeLabel += ` ${formatDiff(gzipDiff).label}`);
5374
+ if (null !== compressedSize && showCompressedDiff) {
5375
+ let compressedDiff = compressedSize - (sizeData?.[compression.sizeKey] ?? 0);
5376
+ isSignificantDiff(compressedDiff) && (compressedSizeLabel += ` ${formatDiff(compressedDiff).label}`);
5348
5377
  }
5349
5378
  }
5350
5379
  let separatorIndex = filePath.lastIndexOf('/'), folderLabel = -1 === separatorIndex ? rootFolderLabel : `${node_path.join(relativeDistPath, filePath.slice(0, separatorIndex))}${node_path.sep}`, filename = -1 === separatorIndex ? filePath : filePath.slice(separatorIndex + 1);
@@ -5355,8 +5384,8 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
5355
5384
  size,
5356
5385
  sizeLabel,
5357
5386
  sizeLabelLength,
5358
- gzippedSize,
5359
- gzipSizeLabel
5387
+ compressedSize,
5388
+ compressedSizeLabel
5360
5389
  };
5361
5390
  }, getAssets = async ()=>{
5362
5391
  let { exclude, include } = options, formattedAssets = [], compilationAssets = stats.compilation.assets;
@@ -5371,7 +5400,7 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
5371
5400
  };
5372
5401
  if (exclude?.(publicAsset) || include && !include(publicAsset)) continue;
5373
5402
  }
5374
- void 0 === content ? formattedAssets.push(formatAsset(filePath, size, null)) : formattedAssets.push(gzipSize(content).then((gzippedSize)=>formatAsset(filePath, size, gzippedSize)));
5403
+ void 0 === content ? formattedAssets.push(formatAsset(filePath, size, null)) : formattedAssets.push(calcCompressedSize(content, compression.type, compression.level).then((compressedSize)=>formatAsset(filePath, size, compressedSize)));
5375
5404
  }
5376
5405
  return (await Promise.all(formattedAssets)).sort((a, b)=>a.size - b.size);
5377
5406
  }, assets = await getAssets();
@@ -5379,15 +5408,15 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
5379
5408
  logs
5380
5409
  };
5381
5410
  logs.push(''), showDetail && 1 === assets.length && (showTotal = !1);
5382
- let { totalSize, totalGzipSize } = ((assets, compressed)=>{
5383
- let totalSize = 0, totalGzipSize = 0;
5384
- for (let { size, gzippedSize } of assets)totalSize += size, compressed && (totalGzipSize += gzippedSize ?? size);
5411
+ let { totalSize, totalCompressedSize } = ((assets, compressed)=>{
5412
+ let totalSize = 0, totalCompressedSize = 0;
5413
+ for (let { size, compressedSize } of assets)totalSize += size, compressed && (totalCompressedSize += compressedSize ?? size);
5385
5414
  return {
5386
5415
  totalSize,
5387
- totalGzipSize
5416
+ totalCompressedSize
5388
5417
  };
5389
- })(assets, options.compressed);
5390
- snapshot && (snapshot.totalSize = totalSize, snapshot.totalGzipSize = totalGzipSize);
5418
+ })(assets, !!options.compressed);
5419
+ snapshot && (snapshot.totalSize = totalSize, options.compressed && (snapshot[compression.totalKey] = totalCompressedSize));
5391
5420
  let fileHeader = showDetail ? `File (${environmentName})` : '', { totalSizeTitle, totalSizeLabel, totalSizeLabelLength } = (()=>{
5392
5421
  if (!showTotal) return {
5393
5422
  totalSizeTitle: '',
@@ -5396,7 +5425,7 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
5396
5425
  };
5397
5426
  let totalSizeTitle = showDetail ? 'Total:' : `Total size (${environmentName}):`, totalSizeLabel = calcFileSize(totalSize), totalSizeLabelLength = totalSizeLabel.length;
5398
5427
  if (showDiff) {
5399
- let totalSizeDiff = totalSize - (previousSizes[environmentName]?.totalSize ?? 0);
5428
+ let totalSizeDiff = totalSize - (prev?.totalSize ?? 0);
5400
5429
  if (isSignificantDiff(totalSizeDiff)) {
5401
5430
  let { label, length } = formatDiff(totalSizeDiff);
5402
5431
  totalSizeLabel += ` ${label}`, totalSizeLabelLength += length + 1;
@@ -5407,7 +5436,11 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
5407
5436
  totalSizeLabel,
5408
5437
  totalSizeLabelLength
5409
5438
  };
5410
- })(), getCustomTotal = ()=>'function' == typeof options.total ? options.total({
5439
+ })(), getCompressedTotalDiff = ()=>{
5440
+ if (!showCompressedDiff) return '';
5441
+ let diff = totalCompressedSize - (prev?.[compression.totalKey] ?? 0);
5442
+ return isSignificantDiff(diff) ? ` ${formatDiff(diff).label}` : '';
5443
+ }, getCustomTotal = ()=>'function' == typeof options.total ? options.total({
5411
5444
  environmentName,
5412
5445
  distPath: relativeDistPath,
5413
5446
  assets: assets.map((asset)=>({
@@ -5415,17 +5448,18 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
5415
5448
  size: asset.size
5416
5449
  })),
5417
5450
  totalSize,
5418
- totalGzipSize
5451
+ totalGzipSize: 'gzip' === compression.type ? totalCompressedSize : 0,
5452
+ totalBrotliSize: options.compressed && 'brotli' === compression.type ? totalCompressedSize : void 0
5419
5453
  }) : null;
5420
5454
  if (showDetail) {
5421
- let maxFileLength = Math.max(showTotal ? totalSizeTitle.length : 0, fileHeader.length), maxSizeLength = totalSizeLabelLength, hasGzipSize = !1;
5422
- for (let asset of assets)asset.filenameLength > maxFileLength && (maxFileLength = asset.filenameLength), asset.sizeLabelLength > maxSizeLength && (maxSizeLength = asset.sizeLabelLength), null !== asset.gzippedSize && (hasGzipSize = !0);
5423
- let showGzipHeader = !!(options.compressed && hasGzipSize);
5424
- for (let asset of (logs.push(getHeader(maxFileLength, maxSizeLength, fileHeader, showGzipHeader)), assets)){
5425
- let { sizeLabel, filenameLabel } = asset, { sizeLabelLength, gzipSizeLabel, filenameLength } = asset;
5455
+ let maxFileLength = Math.max(showTotal ? totalSizeTitle.length : 0, fileHeader.length), maxSizeLength = totalSizeLabelLength, hasCompressedSize = !1;
5456
+ for (let asset of assets)asset.filenameLength > maxFileLength && (maxFileLength = asset.filenameLength), asset.sizeLabelLength > maxSizeLength && (maxSizeLength = asset.sizeLabelLength), null !== asset.compressedSize && (hasCompressedSize = !0);
5457
+ let showCompressedHeader = !!(options.compressed && hasCompressedSize);
5458
+ for (let asset of (logs.push(getHeader(maxFileLength, maxSizeLength, fileHeader, showCompressedHeader && compression.header)), assets)){
5459
+ let { sizeLabel, filenameLabel } = asset, { sizeLabelLength, compressedSizeLabel, filenameLength } = asset;
5426
5460
  sizeLabelLength < maxSizeLength && (sizeLabel += ' '.repeat(maxSizeLength - sizeLabelLength)), filenameLength < maxFileLength && (filenameLabel += ' '.repeat(maxFileLength - filenameLength));
5427
5461
  let log = `${filenameLabel} ${sizeLabel}`;
5428
- gzipSizeLabel && (log += ` ${gzipSizeLabel}`), logs.push(log);
5462
+ compressedSizeLabel && (log += ` ${compressedSizeLabel}`), logs.push(log);
5429
5463
  }
5430
5464
  if (showTotal) {
5431
5465
  logs.push('');
@@ -5434,11 +5468,8 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
5434
5468
  else {
5435
5469
  let log = '';
5436
5470
  if (log += ' '.repeat(maxFileLength - totalSizeTitle.length), log += color.magenta(totalSizeTitle), log += ` ${totalSizeLabel}`, options.compressed) {
5437
- let colorFn = getAssetColor(totalGzipSize / assets.length);
5438
- if (log += ' '.repeat(maxSizeLength - totalSizeLabelLength), log += ` ${colorFn(calcFileSize(totalGzipSize))}`, showDiff) {
5439
- let totalGzipSizeDiff = totalGzipSize - (previousSizes[environmentName]?.totalGzipSize ?? 0);
5440
- isSignificantDiff(totalGzipSizeDiff) && (log += ` ${formatDiff(totalGzipSizeDiff).label}`);
5441
- }
5471
+ let colorFn = getAssetColor(totalCompressedSize / assets.length);
5472
+ log += ' '.repeat(maxSizeLength - totalSizeLabelLength), log += ` ${colorFn(calcFileSize(totalCompressedSize))}${getCompressedTotalDiff()}`;
5442
5473
  }
5443
5474
  logs.push(log);
5444
5475
  }
@@ -5448,7 +5479,7 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
5448
5479
  if (customTotal) logs.push(customTotal);
5449
5480
  else {
5450
5481
  let log = `${color.magenta(totalSizeTitle)} ${totalSizeLabel}`;
5451
- options.compressed && (log += color.green(` (${calcFileSize(totalGzipSize)} gzipped)`)), logs.push(log);
5482
+ options.compressed && (log += color.green(` (${calcFileSize(totalCompressedSize)}${getCompressedTotalDiff()} ${compression.label})`)), logs.push(log);
5452
5483
  }
5453
5484
  }
5454
5485
  return logs.push(''), {
@@ -5456,7 +5487,7 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
5456
5487
  snapshot
5457
5488
  };
5458
5489
  }
5459
- let entryNameSymbol = Symbol('entryName'), VOID_TAGS = [
5490
+ let isNonceTag = (tag)=>"script" === tag.tag || 'style' === tag.tag || 'link' === tag.tag && tag.attrs?.rel === 'preload' && tag.attrs?.as === "script", entryNameSymbol = Symbol('entryName'), VOID_TAGS = [
5460
5491
  'area',
5461
5492
  'base',
5462
5493
  'br',
@@ -5487,7 +5518,26 @@ let entryNameSymbol = Symbol('entryName'), VOID_TAGS = [
5487
5518
  }, getTagPriority = (tag, tagConfig)=>{
5488
5519
  let priority = tag.head ?? HEAD_TAGS.includes(tag.tag) ? -2 : 2, append = tag.append ?? tagConfig.append;
5489
5520
  return 'boolean' == typeof append && (priority += append ? 1 : -1), priority;
5490
- }, sortTags = (tags, tagConfig)=>tags.sort((tag1, tag2)=>getTagPriority(tag1, tagConfig) - getTagPriority(tag2, tagConfig)), formatBasicTag = (tag)=>({
5521
+ }, sortTags = (tags, tagConfig)=>tags.sort((tag1, tag2)=>getTagPriority(tag1, tagConfig) - getTagPriority(tag2, tagConfig)), moveImportMaps = (tags)=>{
5522
+ let importMaps;
5523
+ if (!tags.some((tag)=>{
5524
+ let type = tag.attributes.type;
5525
+ return 'string' == typeof type && 9 === type.length && 'importmap' === type.toLowerCase() && "script" === tag.tagName.toLowerCase();
5526
+ })) return tags;
5527
+ let firstModuleIndex = -1;
5528
+ for(let index = 0; index < tags.length; index++){
5529
+ let tag = tags[index], name = tag.tagName.toLowerCase(), type = tag.attributes.type, scriptType = "script" === name && 'string' == typeof type ? type.toLowerCase() : '';
5530
+ if (-1 === firstModuleIndex) {
5531
+ let rel = tag.attributes.rel;
5532
+ ('module' === scriptType || 'link' === name && 'string' == typeof rel && rel.toLowerCase().split(/[\t\n\f\r ]+/).includes('modulepreload')) && (firstModuleIndex = index);
5533
+ } else if ('importmap' === scriptType) {
5534
+ (importMaps ??= []).push(tag);
5535
+ continue;
5536
+ }
5537
+ importMaps && (tags[index - importMaps.length] = tag);
5538
+ }
5539
+ return importMaps && (tags.length -= importMaps.length, tags.splice(firstModuleIndex, 0, ...importMaps)), tags;
5540
+ }, formatBasicTag = (tag)=>({
5491
5541
  tag: tag.tagName,
5492
5542
  attrs: tag.attributes,
5493
5543
  children: tag.innerHTML,
@@ -5592,7 +5642,7 @@ class RsbuildHtmlPlugin {
5592
5642
  return Object.assign(data, {
5593
5643
  headTags: modified.headTags.map(fromBasicTag),
5594
5644
  bodyTags: modified.bodyTags.map(fromBasicTag)
5595
- }), tagConfig && ((data, tagConfig, compilationHash, entryName)=>{
5645
+ }), tagConfig && ((data, tagConfig, compilationHash, entryName, nonce)=>{
5596
5646
  if (!tagConfig.tags?.length) return;
5597
5647
  let fromInjectTags = (tags)=>{
5598
5648
  let ret = [];
@@ -5624,12 +5674,19 @@ class RsbuildHtmlPlugin {
5624
5674
  entryName,
5625
5675
  outputName: data.outputName,
5626
5676
  publicPath: data.publicPath
5627
- }, shouldSort = !1;
5628
- for (let item of tagConfig.tags)isFunction(item) ? (shouldSort && (tags = sortTags(tags, tagConfig)), tags = item(tags, context) || tags) : tags.push(item), shouldSort = !0;
5677
+ }, shouldSort = !1, withNonce = (tag)=>(nonce && isNonceTag(tag) && tag.attrs?.nonce === void 0 && (tag.attrs ??= {}, tag.attrs.nonce = nonce), tag);
5678
+ for (let item of tagConfig.tags){
5679
+ if (isFunction(item)) {
5680
+ shouldSort && (tags = sortTags(tags, tagConfig));
5681
+ let existingTags = nonce ? new Set(tags) : void 0;
5682
+ if (tags = item(tags, context) || tags, existingTags) for (let tag of tags)existingTags.has(tag) || withNonce(tag);
5683
+ } else tags.push(withNonce(item));
5684
+ shouldSort = !0;
5685
+ }
5629
5686
  shouldSort && (tags = sortTags(tags, tagConfig));
5630
5687
  let [headTags, bodyTags] = partition(tags, (tag)=>tag.head ?? HEAD_TAGS.includes(tag.tag));
5631
5688
  return data.headTags = fromInjectTags(headTags), data.bodyTags = fromInjectTags(bodyTags);
5632
- })(data, tagConfig, compilation.hash ?? '', entryName), data;
5689
+ })(data, tagConfig, compilation.hash ?? '', entryName, environment.config.security.nonce), data.headTags = moveImportMaps(data.headTags), data.bodyTags = moveImportMaps(data.bodyTags), data;
5633
5690
  }), hooks.beforeEmit.tapPromise(this.name, async (data)=>{
5634
5691
  let extraData = getExtraDataByPlugin(data.plugin);
5635
5692
  if (!extraData) return data;
@@ -6881,7 +6938,7 @@ function createAssetsMiddleware(context, ready, outputFileSystem) {
6881
6938
  }
6882
6939
  async function setupOutputFileSystem(writeToDisk, compilers) {
6883
6940
  if (!0 !== writeToDisk) {
6884
- let { createFsFromVolume, Volume } = await import("./memfs.js").then(createFakeNamespaceObject.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/memfs/4.71.0/717d01ef4d84cedabdf3b728d1862a444e82bbbcc379d834c8006e341a87f7d9/node_modules/memfs/lib/index.js", 23)), outputFileSystem = createFsFromVolume(new Volume());
6941
+ let { createFsFromVolume, Volume } = await import("./memfs.js").then(createFakeNamespaceObject.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/memfs/4.76.0/faf1dbc5150aad7a40813fed85f89f32005245b4653e078bb6e3431e6d0c023c/node_modules/memfs/lib/index.js", 23)), outputFileSystem = createFsFromVolume(new Volume());
6885
6942
  for (let compiler of compilers)compiler.outputFileSystem = outputFileSystem;
6886
6943
  }
6887
6944
  let compiler = compilers.find((compiler)=>!!compiler.outputFileSystem);
@@ -8556,7 +8613,7 @@ function applyDefaultPlugins(pluginManager, context) {
8556
8613
  {
8557
8614
  name: 'rsbuild:basic',
8558
8615
  setup (api) {
8559
- api.modifyBundlerChain((chain, { isDev, target, rspack, environment, CHAIN_ID })=>{
8616
+ api.modifyBundlerChain((chain, { isDev, isProd, target, rspack, environment, CHAIN_ID })=>{
8560
8617
  let { config } = environment;
8561
8618
  chain.name(environment.name), chain.context(api.context.rootPath), chain.mode(environment.config.mode), chain.infrastructureLogging({
8562
8619
  level: 'error'
@@ -8569,7 +8626,7 @@ function applyDefaultPlugins(pluginManager, context) {
8569
8626
  javascript: {
8570
8627
  typeReexportsPresence: 'tolerant'
8571
8628
  }
8572
- }), isDev && config.dev.hmr && 'web' === target && chain.plugin(CHAIN_ID.PLUGIN.HMR).use(rspack.HotModuleReplacementPlugin);
8629
+ }), isProd && chain.optimization.chunkIds('compact-hashed').moduleIds('compact-hashed'), isDev && config.dev.hmr && 'web' === target && chain.plugin(CHAIN_ID.PLUGIN.HMR).use(rspack.HotModuleReplacementPlugin);
8573
8630
  });
8574
8631
  }
8575
8632
  },
@@ -9537,32 +9594,38 @@ try {
9537
9594
  name: 'rsbuild:rsdoctor',
9538
9595
  setup (api) {
9539
9596
  api.onBeforeCreateCompiler(async ({ bundlerConfigs })=>{
9540
- let packagePath, module;
9541
9597
  if ('true' !== process.env.RSDOCTOR) return;
9542
9598
  let pluginName = 'RsdoctorRspackPlugin', isRsdoctorPlugin = (plugin)=>plugin?.isRsdoctorPlugin === !0 || plugin?.constructor?.name === pluginName;
9543
9599
  for (let config of bundlerConfigs)if (config.plugins?.some((plugin)=>isRsdoctorPlugin(plugin))) return;
9544
- let packageName = '@rsdoctor/rspack-plugin';
9545
- try {
9546
- packagePath = vendors_require.resolve(packageName, {
9547
- paths: [
9548
- api.context.rootPath
9549
- ]
9550
- });
9551
- } catch {
9552
- api.logger.warn(`\`process.env.RSDOCTOR\` enabled, please install ${color.bold(color.yellow(packageName))} package.`);
9553
- return;
9554
- }
9555
- try {
9556
- let moduleURL = isWindows ? pathToFileURL(packagePath).href : packagePath;
9557
- module = await import(moduleURL);
9558
- } catch {
9559
- api.logger.error(`\`process.env.RSDOCTOR\` enabled, but failed to load ${color.bold(color.yellow(packageName))} module.`);
9560
- return;
9561
- }
9562
- if (module && module[pluginName]) {
9563
- for (let config of bundlerConfigs)config.plugins ||= [], config.plugins.push(new module[pluginName]());
9564
- api.logger.info(`${color.bold(color.yellow(packageName))} enabled.`);
9600
+ for (let packageName of [
9601
+ '@rsdoctor/core',
9602
+ '@rsdoctor/rspack-plugin'
9603
+ ]){
9604
+ let packagePath, module;
9605
+ try {
9606
+ packagePath = vendors_require.resolve(packageName, {
9607
+ paths: [
9608
+ api.context.rootPath
9609
+ ]
9610
+ });
9611
+ } catch {
9612
+ continue;
9613
+ }
9614
+ try {
9615
+ let moduleURL = isWindows ? pathToFileURL(packagePath).href : packagePath;
9616
+ module = await import(moduleURL);
9617
+ } catch {
9618
+ api.logger.error(`\`process.env.RSDOCTOR\` enabled, but failed to load ${color.bold(color.yellow(packageName))} module.`);
9619
+ return;
9620
+ }
9621
+ let RsdoctorPlugin = module[pluginName];
9622
+ if ('function' == typeof RsdoctorPlugin) {
9623
+ for (let config of bundlerConfigs)config.plugins ||= [], config.plugins.push(new RsdoctorPlugin());
9624
+ api.logger.info(`${color.bold(color.yellow(packageName))} enabled.`);
9625
+ return;
9626
+ }
9565
9627
  }
9628
+ api.logger.warn(`\`process.env.RSDOCTOR\` enabled, please install ${color.bold(color.yellow('@rsdoctor/rspack-plugin'))} package.`);
9566
9629
  });
9567
9630
  }
9568
9631
  },
@@ -9683,7 +9746,7 @@ try {
9683
9746
  api.modifyBundlerChain(async (chain, { CHAIN_ID, environment, isDev })=>{
9684
9747
  let { output: { manifest }, dev: { writeToDisk } } = environment.config;
9685
9748
  if (!1 === manifest) return;
9686
- let manifestOptions = normalizeManifestObjectConfig(manifest), { RspackManifestPlugin } = await import("./manifest-plugin.js").then(rspackRequire.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/rspack-manifest-plugin/5.2.2/0e24beaf1b234a114f5305075e91a7e73b51041985d9a6da39afa17869758a5c/node_modules/rspack-manifest-plugin/dist/index.js")), { htmlPaths } = environment, filter = manifestOptions.filter ?? ((file)=>!file.name.endsWith('.LICENSE.txt'));
9749
+ let manifestOptions = normalizeManifestObjectConfig(manifest), { RspackManifestPlugin } = await import("./manifest-plugin.js").then(rspackRequire.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/rspack-manifest-plugin/5.2.2/9919f482fd00d27c94e8e9f65edbae4f86987a8c95774cc077aa085a1cd380ae/node_modules/rspack-manifest-plugin/dist/index.js")), { htmlPaths } = environment, filter = manifestOptions.filter ?? ((file)=>!file.name.endsWith('.LICENSE.txt'));
9687
9750
  manifestFilenames.set(environment.name, manifestOptions.filename);
9688
9751
  let pluginOptions = {
9689
9752
  fileName: manifestOptions.filename,
@@ -9853,7 +9916,7 @@ try {
9853
9916
  ...headTags,
9854
9917
  ...bodyTags
9855
9918
  ];
9856
- if (nonce) for (let tag of allTags)("script" === tag.tag || 'style' === tag.tag || 'link' === tag.tag && tag.attrs?.rel === 'preload' && tag.attrs?.as === "script") && (tag.attrs ??= {}, tag.attrs.nonce = nonce);
9919
+ if (nonce) for (let tag of allTags)isNonceTag(tag) && (tag.attrs ??= {}, tag.attrs.nonce = nonce);
9857
9920
  return {
9858
9921
  headTags,
9859
9922
  bodyTags
@@ -10068,7 +10131,11 @@ let canReadExport = (module)=>null !== module && ('object' == typeof module || '
10068
10131
  configExport: getConfigExport(await jiti.import(configPath), exportName, configPath),
10069
10132
  dependencies: []
10070
10133
  };
10071
- }, JS_CONFIG_REGEXP = /\.(?:js|mjs|cjs)$/, loadWithNative = async (configPath, fresh)=>{
10134
+ }, CONFIG_META = Symbol.for('@rstackjs/load-config/meta');
10135
+ function getConfigMeta(config) {
10136
+ if (null !== config && 'object' == typeof config && Object.hasOwn(config, CONFIG_META)) return config[CONFIG_META];
10137
+ }
10138
+ let JS_CONFIG_REGEXP = /\.(?:js|mjs|cjs)$/, loadWithNative = async (configPath, fresh)=>{
10072
10139
  let configFileURL = pathToFileURL(configPath).href;
10073
10140
  if (!fresh) return {
10074
10141
  configModule: await import(configFileURL),
@@ -10084,7 +10151,7 @@ let canReadExport = (module)=>null !== module && ('object' == typeof module || '
10084
10151
  };
10085
10152
  };
10086
10153
  async function dist_loadConfig({ cwd = process.cwd(), path, configFileNames = [], loader = 'auto', exportName = 'default', configParams = [], fresh = !1 } = {}) {
10087
- let loadedConfig;
10154
+ let loadedConfig, content;
10088
10155
  if (!path && 0 === configFileNames.length) throw Error('Either `path` or at least one `configFileNames` entry must be provided.');
10089
10156
  let configPath = ((root, customConfig, configFileNames = [])=>{
10090
10157
  if (customConfig) {
@@ -10120,17 +10187,20 @@ async function dist_loadConfig({ cwd = process.cwd(), path, configFileNames = []
10120
10187
  if ('function' == typeof configExport) {
10121
10188
  let result = await configExport(...configParams);
10122
10189
  if (void 0 === result) throw Error('The config function must return a config object.');
10123
- return {
10124
- content: result,
10125
- filePath: configPath,
10126
- dependencies
10127
- };
10128
- }
10129
- return {
10130
- content: configExport,
10190
+ content = result;
10191
+ } else content = configExport;
10192
+ let meta = getConfigMeta(content), result = {
10193
+ content,
10131
10194
  filePath: configPath,
10132
10195
  dependencies
10133
10196
  };
10197
+ return meta && (result.filePath = meta.filePath, result.dependencies = [
10198
+ ...new Set([
10199
+ ...meta.dependencies ?? [],
10200
+ configPath,
10201
+ ...dependencies
10202
+ ])
10203
+ ]), result;
10134
10204
  }
10135
10205
  function defineConfig(config) {
10136
10206
  return config;
@@ -10226,7 +10296,7 @@ let applyServerOptions = (command)=>{
10226
10296
  };
10227
10297
  function setupCommands(argv) {
10228
10298
  let cli = ((name = "")=>new CAC(name))('rsbuild');
10229
- cli.version("2.2.4"), 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)', {
10299
+ cli.version("2.2.6"), 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)', {
10230
10300
  default: 'auto'
10231
10301
  }).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', {
10232
10302
  type: [
@@ -10291,7 +10361,7 @@ function setupCommands(argv) {
10291
10361
  }
10292
10362
  function showGreeting() {
10293
10363
  let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
10294
- src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.2.4\n`);
10364
+ src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.2.6\n`);
10295
10365
  }
10296
10366
  function setupLogLevel(argv) {
10297
10367
  if (argv.length <= 3) return;
@@ -10313,5 +10383,5 @@ function runCLI({ argv = process.argv } = {}) {
10313
10383
  src_logger.error('Failed to start Rsbuild CLI.'), src_logger.error(err), process.exit(1);
10314
10384
  }
10315
10385
  }
10316
- let src_version = "2.2.4";
10386
+ let src_version = "2.2.6";
10317
10387
  export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, core_rspack as rspack, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig_loadConfig as loadConfig, loadEnv, logger_createLogger as createLogger, mergeRsbuildConfig, mrmime_lookup, runCLI, src_logger as logger, src_version as version };