@rsbuild/core 2.3.4 → 2.3.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/m.js CHANGED
@@ -292,8 +292,8 @@ moduleFactories.add({
292
292
  };
293
293
  };
294
294
  },
295
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/b7f5a594bf00404e4e776a1083b3a0cfef602f460cf7e11269b23855d34ff149/node_modules/postcss-load-config/src/index.js" (module) {
296
- let yaml, { resolve } = __rspack_createRequire_require("node:path"), config = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/lilconfig/3.1.3/8e9a79516bf61f8427342cef50cdad2cdc2572f42288ba8053b88eadfdc0ebef/node_modules/lilconfig/src/index.js"), loadOptions = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/b7f5a594bf00404e4e776a1083b3a0cfef602f460cf7e11269b23855d34ff149/node_modules/postcss-load-config/src/options.js"), loadPlugins = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/b7f5a594bf00404e4e776a1083b3a0cfef602f460cf7e11269b23855d34ff149/node_modules/postcss-load-config/src/plugins.js"), req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/b7f5a594bf00404e4e776a1083b3a0cfef602f460cf7e11269b23855d34ff149/node_modules/postcss-load-config/src/req.js");
295
+ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/9e609fb6c52072bc6facf6e92463c7ae61177cd218a9d63536247c93a5b51966/node_modules/postcss-load-config/src/index.js" (module) {
296
+ let yaml, { resolve } = __rspack_createRequire_require("node:path"), config = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/lilconfig/3.1.3/8e9a79516bf61f8427342cef50cdad2cdc2572f42288ba8053b88eadfdc0ebef/node_modules/lilconfig/src/index.js"), loadOptions = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/9e609fb6c52072bc6facf6e92463c7ae61177cd218a9d63536247c93a5b51966/node_modules/postcss-load-config/src/options.js"), loadPlugins = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/9e609fb6c52072bc6facf6e92463c7ae61177cd218a9d63536247c93a5b51966/node_modules/postcss-load-config/src/plugins.js"), req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/9e609fb6c52072bc6facf6e92463c7ae61177cd218a9d63536247c93a5b51966/node_modules/postcss-load-config/src/req.js");
297
297
  async function processResult(ctx, result) {
298
298
  let obj, file = result.filepath || '', projectConfig = ((obj = result.config) && obj.__esModule ? obj : {
299
299
  default: obj
@@ -366,8 +366,8 @@ moduleFactories.add({
366
366
  });
367
367
  };
368
368
  },
369
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/b7f5a594bf00404e4e776a1083b3a0cfef602f460cf7e11269b23855d34ff149/node_modules/postcss-load-config/src/options.js" (module) {
370
- let req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/b7f5a594bf00404e4e776a1083b3a0cfef602f460cf7e11269b23855d34ff149/node_modules/postcss-load-config/src/req.js");
369
+ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/9e609fb6c52072bc6facf6e92463c7ae61177cd218a9d63536247c93a5b51966/node_modules/postcss-load-config/src/options.js" (module) {
370
+ let req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/9e609fb6c52072bc6facf6e92463c7ae61177cd218a9d63536247c93a5b51966/node_modules/postcss-load-config/src/req.js");
371
371
  module.exports = async function options(config, file) {
372
372
  if (config.parser && 'string' == typeof config.parser) try {
373
373
  config.parser = await req(config.parser, file);
@@ -387,8 +387,8 @@ moduleFactories.add({
387
387
  return config;
388
388
  };
389
389
  },
390
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/b7f5a594bf00404e4e776a1083b3a0cfef602f460cf7e11269b23855d34ff149/node_modules/postcss-load-config/src/plugins.js" (module) {
391
- let req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/b7f5a594bf00404e4e776a1083b3a0cfef602f460cf7e11269b23855d34ff149/node_modules/postcss-load-config/src/req.js");
390
+ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/9e609fb6c52072bc6facf6e92463c7ae61177cd218a9d63536247c93a5b51966/node_modules/postcss-load-config/src/plugins.js" (module) {
391
+ let req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/9e609fb6c52072bc6facf6e92463c7ae61177cd218a9d63536247c93a5b51966/node_modules/postcss-load-config/src/req.js");
392
392
  async function load(plugin, options, file) {
393
393
  try {
394
394
  if (null == options || 0 === Object.keys(options).length) return await req(plugin, file);
@@ -404,7 +404,7 @@ moduleFactories.add({
404
404
  }), list;
405
405
  };
406
406
  },
407
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/b7f5a594bf00404e4e776a1083b3a0cfef602f460cf7e11269b23855d34ff149/node_modules/postcss-load-config/src/req.js" (module) {
407
+ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/9e609fb6c52072bc6facf6e92463c7ae61177cd218a9d63536247c93a5b51966/node_modules/postcss-load-config/src/req.js" (module) {
408
408
  let tsx, jiti, { createRequire } = __rspack_createRequire_require("node:module"), { pathToFileURL } = __rspack_createRequire_require("node:url"), TS_EXT_RE = /\.[mc]?ts$/, importError = [];
409
409
  module.exports = async function req(name, rootFile = __rspack_import_meta_filename__) {
410
410
  let url = createRequire(rootFile).resolve(name);
@@ -1474,7 +1474,38 @@ let ChainedMap = createMap(createChainable(Object)), ChainedValueMap = (superCla
1474
1474
  when(condition, whenTruthy = Function.prototype, whenFalsy = Function.prototype) {
1475
1475
  return condition ? whenTruthy(this) : whenFalsy(this), this;
1476
1476
  }
1477
- }), childMaps = [
1477
+ });
1478
+ function cloneValue(value, context) {
1479
+ if (null === value || 'object' != typeof value) return value;
1480
+ let seen = context.seen ??= new WeakMap();
1481
+ if (seen.has(value)) return seen.get(value);
1482
+ if (value instanceof RegExp) {
1483
+ let cloned = new RegExp(value.source, value.flags);
1484
+ return cloned.lastIndex = value.lastIndex, seen.set(value, cloned), cloned;
1485
+ }
1486
+ let prototype = Object.getPrototypeOf(value);
1487
+ if (!Array.isArray(value) && prototype !== Object.prototype && null !== prototype) return value;
1488
+ let cloned = Array.isArray(value) ? Array(value.length) : Object.create(prototype);
1489
+ for (let key of (seen.set(value, cloned), Object.keys(value))){
1490
+ let clonedValue = cloneValue(value[key], context);
1491
+ '__proto__' === key ? Object.defineProperty(cloned, key, {
1492
+ value: clonedValue,
1493
+ enumerable: !0,
1494
+ configurable: !0,
1495
+ writable: !0
1496
+ }) : cloned[key] = clonedValue;
1497
+ }
1498
+ return cloned;
1499
+ }
1500
+ function cloneMap(source, context, cloned = new Map()) {
1501
+ for (let [key, value] of (cloned.clear(), source))cloned.set(key, cloneValue(value, context));
1502
+ return cloned;
1503
+ }
1504
+ function cloneSet(source, context, cloned = new Set()) {
1505
+ for (let value of (cloned.clear(), source))cloned.add(cloneValue(value, context));
1506
+ return cloned;
1507
+ }
1508
+ let childMaps = [
1478
1509
  'alias',
1479
1510
  'fallback',
1480
1511
  'byDependency',
@@ -1491,7 +1522,8 @@ let ChainedMap = createMap(createChainable(Object)), ChainedValueMap = (superCla
1491
1522
  'restrictions',
1492
1523
  'roots',
1493
1524
  'modules'
1494
- ], Resolve = class extends ChainedMap {
1525
+ ];
1526
+ class Resolve extends ChainedMap {
1495
1527
  constructor(parent){
1496
1528
  super(parent), childMaps.forEach((key)=>{
1497
1529
  this[key] = new ChainedMap(this);
@@ -1530,7 +1562,14 @@ let ChainedMap = createMap(createChainable(Object)), ChainedValueMap = (superCla
1530
1562
  ...omissions
1531
1563
  ]);
1532
1564
  }
1533
- }, ResolveLoader = class extends Resolve {
1565
+ }
1566
+ function cloneResolve(source, parent, context) {
1567
+ let cloned = new Resolve(parent);
1568
+ for (let key of (cloneMap(source.store, context, cloned.store), childMaps))cloneMap(source[key].store, context, cloned[key].store);
1569
+ for (let key of childSets)cloneSet(source[key].store, context, cloned[key].store);
1570
+ return cloned;
1571
+ }
1572
+ let ResolveLoader = class extends Resolve {
1534
1573
  constructor(parent){
1535
1574
  super(parent), this.modules = new ChainedSet(this), this.moduleExtensions = new ChainedSet(this), this.packageMains = new ChainedSet(this);
1536
1575
  }
@@ -1710,6 +1749,9 @@ let ChainedMap = createMap(createChainable(Object)), ChainedValueMap = (superCla
1710
1749
  tap(f) {
1711
1750
  return this.options(f(this.get('options'))), this;
1712
1751
  }
1752
+ cloneFrom(source) {
1753
+ return source === this || (this.store = cloneMap(source.store, {})), this;
1754
+ }
1713
1755
  merge(obj, omit = []) {
1714
1756
  return !omit.includes('loader') && 'loader' in obj && this.loader(obj.loader), !omit.includes('options') && 'options' in obj && this.options(cjs(this.store.get('options') || {}, obj.options)), super.merge(obj, [
1715
1757
  ...omit,
@@ -1786,6 +1828,26 @@ let Rule = Orderable(class extends ChainedMap {
1786
1828
  post() {
1787
1829
  return this.enforce('post');
1788
1830
  }
1831
+ cloneFrom(source) {
1832
+ return source === this ? this : this.#cloneFrom(source, {});
1833
+ }
1834
+ #cloneFrom(source, context) {
1835
+ let children = {};
1836
+ for (let key of [
1837
+ 'uses',
1838
+ 'rules',
1839
+ 'oneOfs'
1840
+ ]){
1841
+ let entries = new Map();
1842
+ for (let [name, child] of source[key].store){
1843
+ let cloned;
1844
+ 'uses' === key ? (cloned = new Use(this, name), cloneMap(child.store, context, cloned.store)) : (cloned = new Rule(this, name, 'rules' === key ? 'rule' : 'oneOf')).#cloneFrom(child, context), cloned.__before = child.__before, cloned.__after = child.__after, entries.set(name, cloned);
1845
+ }
1846
+ children[key] = entries;
1847
+ }
1848
+ let resolve = source.#resolve ? cloneResolve(source.#resolve, this, context) : void 0;
1849
+ return cloneMap(source.store, context, this.store), cloneSet(source.include.store, context, this.include.store), cloneSet(source.exclude.store, context, this.exclude.store), this.uses.store = children.uses, this.rules.store = children.rules, this.oneOfs.store = children.oneOfs, this.#resolve = resolve, this;
1850
+ }
1789
1851
  toConfig() {
1790
1852
  let config = this.clean(Object.assign(this.entries() || {}, {
1791
1853
  include: this.include.values(),
@@ -2019,9 +2081,9 @@ let setNodeEnv = (env)=>{
2019
2081
  arr
2020
2082
  ], cloneDeep = (value)=>null == value ? value : cjs_0_default()({}, value, {
2021
2083
  isMergeableObject: isPlainObject
2022
- }), DEFAULT_FILENAME_HASH = 'contenthash:10';
2023
- function getFilename(config, type, isProd, isServer) {
2024
- let { filename, filenameHash } = config.output, hashConfig = 'boolean' == typeof filenameHash ? {
2084
+ }), normalizeCopyOptions = (copy)=>Array.isArray(copy) ? {
2085
+ patterns: copy
2086
+ } : copy, DEFAULT_FILENAME_HASH = 'contenthash:10', normalizeFilenameHash = (filenameHash)=>'boolean' == typeof filenameHash ? {
2025
2087
  enable: filenameHash,
2026
2088
  format: DEFAULT_FILENAME_HASH
2027
2089
  } : 'string' == typeof filenameHash ? {
@@ -2030,24 +2092,29 @@ function getFilename(config, type, isProd, isServer) {
2030
2092
  } : {
2031
2093
  enable: filenameHash.enable ?? !0,
2032
2094
  format: filenameHash.format ?? DEFAULT_FILENAME_HASH
2033
- }, hashTemplate = `[${hashConfig.format}]`, getHash = ()=>!1 !== hashConfig.enable ? `.${hashTemplate}` : '', getJsCssHash = (flag)=>'always' === hashConfig.enable || !0 === hashConfig.enable && flag ? `.${hashTemplate}` : '';
2095
+ };
2096
+ function getFilename(config, type, isProd, isServer) {
2097
+ let { filename, filenameHash } = config.output, getHash = (useHash)=>{
2098
+ let { enable, format } = normalizeFilenameHash(filenameHash);
2099
+ return 'always' === enable || enable && useHash ? `.[${format}]` : '';
2100
+ };
2034
2101
  switch(type){
2035
2102
  case 'js':
2036
- return filename.js ?? `[name]${getJsCssHash(isProd && !isServer)}.js`;
2103
+ return filename.js ?? `[name]${getHash(isProd && !isServer)}.js`;
2037
2104
  case 'css':
2038
- return filename.css ?? `[name]${getJsCssHash(isProd)}.css`;
2105
+ return filename.css ?? `[name]${getHash(isProd)}.css`;
2039
2106
  case 'svg':
2040
- return filename.svg ?? `[name]${getHash()}.svg`;
2107
+ return filename.svg ?? `[name]${getHash(!0)}.svg`;
2041
2108
  case 'font':
2042
- return filename.font ?? `[name]${getHash()}[ext]`;
2109
+ return filename.font ?? `[name]${getHash(!0)}[ext]`;
2043
2110
  case 'image':
2044
- return filename.image ?? `[name]${getHash()}[ext]`;
2111
+ return filename.image ?? `[name]${getHash(!0)}[ext]`;
2045
2112
  case 'media':
2046
- return filename.media ?? `[name]${getHash()}[ext]`;
2113
+ return filename.media ?? `[name]${getHash(!0)}[ext]`;
2047
2114
  case 'assets':
2048
- return filename.assets ?? `[name]${getHash()}[ext]`;
2115
+ return filename.assets ?? `[name]${getHash(!0)}[ext]`;
2049
2116
  case 'wasm':
2050
- return filename.wasm ?? `${hashTemplate}.module.wasm`;
2117
+ return filename.wasm ?? `[${normalizeFilenameHash(filenameHash).format}].module.wasm`;
2051
2118
  case 'html':
2052
2119
  if (filename.html) return filename.html;
2053
2120
  return 'flat' === config.html.outputStructure ? '[name].html' : '[name]/index.html';
@@ -2179,7 +2246,7 @@ function formatStatsError(stats, root, level = 'error', logger) {
2179
2246
  let innerError = '-- inner error --';
2180
2247
  !verbose && message.includes(innerError) && (message = message.split(innerError)[0]);
2181
2248
  let lines = (message = ((message)=>{
2182
- if (!message.includes('produce different content for the same output file') && !message.includes('Multiple assets emit different content to the same filename')) return message;
2249
+ if (!message.includes('produce different content for the same output file')) return message;
2183
2250
  let extraMessage = `You may need to adjust ${color.yellow('output.filename')} configuration to prevent name conflicts. (See ${color.yellow('https://rsbuild.rs/config/output/filename')})`;
2184
2251
  return `${message}\n${extraMessage}`;
2185
2252
  })(message = ((message)=>{
@@ -2592,6 +2659,7 @@ let OVERRIDE_PATHS = new Set([
2592
2659
  'output.inlineScripts',
2593
2660
  'output.inlineStyles',
2594
2661
  'output.cssModules.auto',
2662
+ 'output.cssModules.mode',
2595
2663
  'output.manifest.filter',
2596
2664
  'output.manifest.generate',
2597
2665
  'output.overrideBrowserslist',
@@ -2600,11 +2668,14 @@ let OVERRIDE_PATHS = new Set([
2600
2668
  'performance.printFileSize.total',
2601
2669
  'server.open',
2602
2670
  'server.compress.filter',
2671
+ 'server.cors.origin',
2603
2672
  'server.printUrls',
2604
2673
  'resolve.extensions',
2605
2674
  'resolve.conditionNames',
2606
2675
  'resolve.mainFields',
2676
+ 'splitChunks.chunks',
2607
2677
  'dev.writeToDisk',
2678
+ 'dev.cliShortcuts.custom',
2608
2679
  'dev.client.overlay.errors',
2609
2680
  'dev.client.overlay.runtime',
2610
2681
  'provider',
@@ -2655,20 +2726,37 @@ let OVERRIDE_PATHS = new Set([
2655
2726
  }
2656
2727
  return merged;
2657
2728
  }, normalizeConfigStructure = (config)=>{
2658
- let { dev, output } = config, normalizedConfig = {
2729
+ let { dev, output, environments } = config, normalizedConfig = {
2659
2730
  ...config
2660
2731
  };
2661
- return output && (Array.isArray((output = {
2662
- ...output
2663
- }).copy) && (output.copy = {
2664
- patterns: output.copy
2665
- }), 'string' == typeof output.distPath && (output.distPath = {
2666
- root: output.distPath
2667
- }), normalizedConfig.output = output), dev && ((dev = {
2732
+ if (output) {
2733
+ (output = {
2734
+ ...output
2735
+ }).copy && (output.copy = normalizeCopyOptions(output.copy)), 'string' == typeof output.distPath && (output.distPath = {
2736
+ root: output.distPath
2737
+ }), 'string' == typeof output.filenameHash && (output.filenameHash = normalizeFilenameHash(output.filenameHash)), 'string' == typeof output.manifest && (output.manifest = {
2738
+ filename: output.manifest
2739
+ });
2740
+ let { dataUriLimit } = output;
2741
+ 'number' == typeof dataUriLimit && (output.dataUriLimit = {
2742
+ svg: dataUriLimit,
2743
+ font: dataUriLimit,
2744
+ image: dataUriLimit,
2745
+ media: dataUriLimit,
2746
+ assets: dataUriLimit
2747
+ }), normalizedConfig.output = output;
2748
+ }
2749
+ if (dev && ((dev = {
2668
2750
  ...dev
2669
2751
  }).watchFiles && !Array.isArray(dev.watchFiles) && (dev.watchFiles = [
2670
2752
  dev.watchFiles
2671
- ]), normalizedConfig.dev = dev), normalizedConfig;
2753
+ ]), normalizedConfig.dev = dev), environments) {
2754
+ for (let [name, environment] of Object.entries(environments = {
2755
+ ...environments
2756
+ }))environment && (environments[name] = normalizeConfigStructure(environment));
2757
+ normalizedConfig.environments = environments;
2758
+ }
2759
+ return normalizedConfig;
2672
2760
  }, mergeRsbuildConfig = (...originalConfigs)=>{
2673
2761
  let configs = originalConfigs.filter((config)=>void 0 !== config).map(normalizeConfigStructure);
2674
2762
  return 2 === configs.length ? merge(configs[0], configs[1]) : 0 === configs.length ? {} : configs.reduce((result, config)=>merge(result, config), {});
@@ -2761,13 +2849,7 @@ let OVERRIDE_PATHS = new Set([
2761
2849
  filename: {},
2762
2850
  charset: 'utf8',
2763
2851
  polyfill: 'off',
2764
- dataUriLimit: {
2765
- svg: 4096,
2766
- font: 4096,
2767
- image: 4096,
2768
- media: 4096,
2769
- assets: 4096
2770
- },
2852
+ dataUriLimit: 4096,
2771
2853
  legalComments: 'linked',
2772
2854
  injectStyles: !1,
2773
2855
  manifest: !1,
@@ -3303,7 +3385,7 @@ async function createContext(options, userConfig, logger, loadConfigResult) {
3303
3385
  return config;
3304
3386
  })(rootPath, userConfig), cachePath = join(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, hooks = initHooks();
3305
3387
  return {
3306
- version: "2.3.4",
3388
+ version: "2.3.6",
3307
3389
  rootPath,
3308
3390
  configFile: loadConfigResult?.filePath ?? userConfig._privateMeta?.configFilePath,
3309
3391
  configFileDependencies: loadConfigResult?.dependencies ?? userConfig._privateMeta?.configFileDependencies ?? [],
@@ -4954,6 +5036,108 @@ function getRegExpForExts(exts) {
4954
5036
  let matcher = normalizedExts.join('|');
4955
5037
  return RegExp(1 === normalizedExts.length ? `\\.${matcher}$` : `\\.(?:${matcher})$`, 'i');
4956
5038
  }
5039
+ function findWorkspaceRoot(root) {
5040
+ let packageRoot, current = root;
5041
+ for(;;){
5042
+ if (isFileSync(join(current, 'pnpm-workspace.yaml')) || isFileSync(join(current, 'lerna.json'))) return current;
5043
+ let packageJson = join(current, 'package.json');
5044
+ if (isFileSync(packageJson)) {
5045
+ packageRoot ??= current;
5046
+ try {
5047
+ let pkg = JSON.parse(readFileSync(packageJson, 'utf8'));
5048
+ if (pkg?.workspaces) return current;
5049
+ } catch {}
5050
+ }
5051
+ let parent = dirname(current);
5052
+ if (parent === current) return packageRoot ?? root;
5053
+ current = parent;
5054
+ }
5055
+ }
5056
+ let postcss_load_config_src = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/9e609fb6c52072bc6facf6e92463c7ae61177cd218a9d63536247c93a5b51966/node_modules/postcss-load-config/src/index.js");
5057
+ var postcss_load_config_src_default = compatGetDefaultExport(postcss_load_config_src);
5058
+ let getCSSOutputFilename = (distPath, filename)=>'function' == typeof filename ? (...args)=>posix.join(distPath, filename(...args)) : posix.join(distPath, filename), getCSSChunkFilename = ({ css, cssAsync }, filename)=>getCSSOutputFilename(cssAsync ?? (css ? `${css}/async` : 'async'), filename);
5059
+ function getLightningCSSLoaderOptions(config, targets, minify) {
5060
+ let userOptions = 'object' == typeof config.tools.lightningcssLoader ? config.tools.lightningcssLoader : {}, initialOptions = {
5061
+ targets,
5062
+ errorRecovery: !0
5063
+ };
5064
+ return minify && (initialOptions.minify = !0), reduceConfigs({
5065
+ initial: initialOptions,
5066
+ config: userOptions
5067
+ });
5068
+ }
5069
+ let clonePostCSSConfig = (config)=>({
5070
+ ...config,
5071
+ plugins: config.plugins ? [
5072
+ ...config.plugins
5073
+ ] : void 0
5074
+ }), getCSSSourceMap = (config)=>{
5075
+ let { sourceMap } = config.output;
5076
+ return 'boolean' == typeof sourceMap ? sourceMap : sourceMap.css;
5077
+ };
5078
+ async function loadUserPostcssrc(root, postcssrcCache) {
5079
+ let cached = postcssrcCache.get(root);
5080
+ if (cached) return clonePostCSSConfig(await cached);
5081
+ let promise = postcss_load_config_src_default()({}, root, {
5082
+ stopDir: findWorkspaceRoot(root)
5083
+ }).catch((err)=>{
5084
+ if (err.message?.includes('No PostCSS Config found')) return {};
5085
+ throw err;
5086
+ });
5087
+ return postcssrcCache.set(root, promise), promise.then((config)=>(postcssrcCache.set(root, config), clonePostCSSConfig(config)));
5088
+ }
5089
+ function createPostCSSTransform(root) {
5090
+ let postcssrcCache = new Map();
5091
+ return async ({ environment, CHAIN_ID }, ...rules)=>{
5092
+ let options = await (async ({ config, root, postcssrcCache })=>{
5093
+ let extraPlugins = [], userOptions = await loadUserPostcssrc(root, postcssrcCache);
5094
+ userOptions.plugins ||= [];
5095
+ let defaultOptions = {
5096
+ implementation: getCompiledPath('postcss'),
5097
+ postcssOptions: userOptions,
5098
+ sourceMap: getCSSSourceMap(config)
5099
+ }, finalOptions = await reduceConfigsWithContext({
5100
+ initial: defaultOptions,
5101
+ config: config.tools.postcss,
5102
+ ctx: {
5103
+ addPlugins (plugins, options = {}) {
5104
+ let { order = 'post' } = options, list = helpers_castArray(plugins);
5105
+ 'pre' === order ? extraPlugins.unshift(...list) : extraPlugins.push(...list);
5106
+ }
5107
+ }
5108
+ });
5109
+ finalOptions.postcssOptions ||= {};
5110
+ let updatePostcssOptions = (options)=>(options.plugins ||= [], extraPlugins.length && options.plugins.push(...extraPlugins), options.plugins = options.plugins.map((plugin)=>'function' == typeof plugin && 'postcss' in plugin && plugin.postcss ? plugin() : plugin), options.config = !1, options), { postcssOptions } = finalOptions;
5111
+ if ('function' == typeof postcssOptions) {
5112
+ let postcssOptionsWrapper = (loaderContext)=>{
5113
+ let options = postcssOptions(loaderContext);
5114
+ if ('object' != typeof options || null === options) throw Error(`${color.dim('[rsbuild:css]')} \`postcssOptions\` function must return a PostCSSOptions object, got ${color.yellow(typeof options)}.`);
5115
+ return updatePostcssOptions({
5116
+ ...userOptions,
5117
+ ...options,
5118
+ plugins: [
5119
+ ...userOptions.plugins || [],
5120
+ ...options.plugins || []
5121
+ ]
5122
+ });
5123
+ };
5124
+ return postcssOptionsWrapper.config = !1, {
5125
+ ...finalOptions,
5126
+ postcssOptions: postcssOptionsWrapper
5127
+ };
5128
+ }
5129
+ return finalOptions.postcssOptions = updatePostcssOptions(postcssOptions), finalOptions;
5130
+ })({
5131
+ config: environment.config,
5132
+ root,
5133
+ postcssrcCache
5134
+ });
5135
+ if ('function' != typeof options.postcssOptions && !options.postcssOptions?.plugins?.length) return !1;
5136
+ let loader = getCompiledPath('postcss-loader');
5137
+ for (let rule of rules)rule?.use(CHAIN_ID.USE.POSTCSS).loader(loader).options(options);
5138
+ return !0;
5139
+ };
5140
+ }
4957
5141
  function getCacheDirectory({ cacheDirectory }, context) {
4958
5142
  return cacheDirectory ? external_node_path_isAbsolute(cacheDirectory) ? cacheDirectory : join(context.rootPath, cacheDirectory) : join(context.cachePath, 'rspack');
4959
5143
  }
@@ -4992,25 +5176,7 @@ let normalizeCleanDistPath = (userOptions)=>{
4992
5176
  ...defaultOptions,
4993
5177
  ...userOptions
4994
5178
  };
4995
- };
4996
- function findWorkspaceRoot(root) {
4997
- let packageRoot, current = root;
4998
- for(;;){
4999
- if (isFileSync(join(current, 'pnpm-workspace.yaml')) || isFileSync(join(current, 'lerna.json'))) return current;
5000
- let packageJson = join(current, 'package.json');
5001
- if (isFileSync(packageJson)) {
5002
- packageRoot ??= current;
5003
- try {
5004
- let pkg = JSON.parse(readFileSync(packageJson, 'utf8'));
5005
- if (pkg?.workspaces) return current;
5006
- } catch {}
5007
- }
5008
- let parent = dirname(current);
5009
- if (parent === current) return packageRoot ?? root;
5010
- current = parent;
5011
- }
5012
- }
5013
- let getConsolePureFuncs = (methods)=>methods.map((method)=>`console.${method}`), ALL_CONSOLE_PURE_FUNCS = getConsolePureFuncs([
5179
+ }, getConsolePureFuncs = (methods)=>methods.map((method)=>`console.${method}`), ALL_CONSOLE_PURE_FUNCS = getConsolePureFuncs([
5014
5180
  'assert',
5015
5181
  'clear',
5016
5182
  'count',
@@ -5070,38 +5236,6 @@ function parseMinifyOptions(config) {
5070
5236
  cssOptions: minify.cssOptions
5071
5237
  };
5072
5238
  }
5073
- let postcss_load_config_src = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/b7f5a594bf00404e4e776a1083b3a0cfef602f460cf7e11269b23855d34ff149/node_modules/postcss-load-config/src/index.js");
5074
- var postcss_load_config_src_default = compatGetDefaultExport(postcss_load_config_src);
5075
- function getLightningCSSLoaderOptions(config, targets, minify) {
5076
- let userOptions = 'object' == typeof config.tools.lightningcssLoader ? config.tools.lightningcssLoader : {}, initialOptions = {
5077
- targets,
5078
- errorRecovery: !0
5079
- };
5080
- return minify && (initialOptions.minify = !0), reduceConfigs({
5081
- initial: initialOptions,
5082
- config: userOptions
5083
- });
5084
- }
5085
- let clonePostCSSConfig = (config)=>({
5086
- ...config,
5087
- plugins: config.plugins ? [
5088
- ...config.plugins
5089
- ] : void 0
5090
- }), getCSSSourceMap = (config)=>{
5091
- let { sourceMap } = config.output;
5092
- return 'boolean' == typeof sourceMap ? sourceMap : sourceMap.css;
5093
- };
5094
- async function loadUserPostcssrc(root, postcssrcCache) {
5095
- let cached = postcssrcCache.get(root);
5096
- if (cached) return clonePostCSSConfig(await cached);
5097
- let promise = postcss_load_config_src_default()({}, root, {
5098
- stopDir: findWorkspaceRoot(root)
5099
- }).catch((err)=>{
5100
- if (err.message?.includes('No PostCSS Config found')) return {};
5101
- throw err;
5102
- });
5103
- return postcssrcCache.set(root, promise), promise.then((config)=>(postcssrcCache.set(root, config), clonePostCSSConfig(config)));
5104
- }
5105
5239
  function checkProcessEnvSecurity(define, logger) {
5106
5240
  let value = define['process.env'];
5107
5241
  if (!value) return;
@@ -5923,7 +6057,7 @@ function doesChunkBelongToHtml({ chunk, htmlPluginData }) {
5923
6057
  let { options } = htmlPluginData.plugin;
5924
6058
  return recursiveChunkEntryNames(chunk).some((chunkName)=>isChunksFiltered(chunkName, options?.chunks, options?.excludeChunks));
5925
6059
  }
5926
- let getManifestPlugin = cachedImport_cachedImport(()=>import("./manifest-plugin.js").then(()=>rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/rspack-manifest-plugin/5.2.2/a5aff6a67a64dc2cd6fba2fe392c361454bba759c9980bb6bfe1a6686c72e73b/node_modules/rspack-manifest-plugin/dist/index.js"))), isCSSPath = (filePath)=>filePath.endsWith('.css');
6060
+ let getManifestPlugin = cachedImport_cachedImport(()=>import("./manifest-plugin.js").then(()=>rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/rspack-manifest-plugin/5.2.2/b54c3f7e531ab4051357d2e4e706e67fa438667b770e5dc3518ad8bd544f3dc3/node_modules/rspack-manifest-plugin/dist/index.js"))), isCSSPath = (filePath)=>filePath.endsWith('.css');
5927
6061
  function normalizeManifestObjectConfig(manifest) {
5928
6062
  let defaultOptions = {
5929
6063
  prefix: !0,
@@ -6359,7 +6493,6 @@ function getSplitChunksByPreset(config, preset) {
6359
6493
  throw Error(`[rsbuild] Unknown splitChunks preset: ${String(preset)}`);
6360
6494
  }
6361
6495
  }
6362
- let builtinSwcLoaderName = 'builtin:swc-loader';
6363
6496
  function applyScriptCondition({ rule, isDev, config, rsbuildTarget }) {
6364
6497
  for (let condition of (rule.include.add({
6365
6498
  not: NODE_MODULES_REGEX
@@ -6761,16 +6894,20 @@ function setupMemoryFileSystemCleanup(fileSystem, compilers) {
6761
6894
  if (compilers.some((compiler)=>compiler.options.output.clean)) return;
6762
6895
  let lastSeenByCompiler = compilers.map(()=>new Map());
6763
6896
  for (let [index, compiler] of compilers.entries()){
6764
- let lastHash, lastSeen = lastSeenByCompiler[index], generation = 0;
6897
+ let lastHash, lastSeen = lastSeenByCompiler[index], expiresAt = new Map(), generation = 0;
6765
6898
  compiler.hooks.afterEmit.tap('rsbuild:clean-memory-filesystem', (compilation)=>{
6766
6899
  if (compilation.errors.length) return;
6767
- compilation.hash !== lastHash && (generation++, lastHash = compilation.hash);
6900
+ let now = performance.now();
6901
+ for (let [retiredGeneration, deadline] of (compilation.hash !== lastHash && (generation > 0 && expiresAt.set(generation, now + 30000), generation++, lastHash = compilation.hash), expiresAt)){
6902
+ if (deadline > now) break;
6903
+ expiresAt.delete(retiredGeneration);
6904
+ }
6768
6905
  let outputPath = compilation.getPath(compiler.outputPath);
6769
6906
  for (let name of getAssetNames(compilation)){
6770
6907
  let queryIndex = name.indexOf('?'), filename = -1 === queryIndex ? name : name.slice(0, queryIndex), filePath = join(outputPath, filename);
6771
6908
  lastSeen.set(filePath, generation);
6772
6909
  }
6773
- for (let [filePath, seen] of lastSeen)if (!(seen >= generation - 1) && (lastSeen.delete(filePath), !lastSeenByCompiler.some((assets)=>assets.has(filePath)))) try {
6910
+ for (let [filePath, seen] of lastSeen)if (!(seen >= generation - 1 || expiresAt.has(seen)) && (lastSeen.delete(filePath), !lastSeenByCompiler.some((assets)=>assets.has(filePath)))) try {
6774
6911
  fileSystem.unlinkSync(filePath);
6775
6912
  } catch (error) {
6776
6913
  if ('ENOENT' !== error.code) throw error;
@@ -7098,11 +7235,11 @@ class SocketServer {
7098
7235
  this.context = context, this.options = options, this.getOutputFileSystem = getOutputFileSystem, this.onSocketConnect = onSocketConnect, this.onSocketCustomMessage = onSocketCustomMessage;
7099
7236
  }
7100
7237
  upgrade = (req, socket, head)=>{
7101
- if (!this.wsServer.shouldHandle(req)) return;
7238
+ if (!this.wsServer.shouldHandle(req)) return !1;
7102
7239
  let query = parseQueryString(req);
7103
- this.context.environmentList.some(({ webSocketToken })=>webSocketToken === query.token) ? this.wsServer.handleUpgrade(req, socket, head, (connection)=>{
7240
+ return this.context.environmentList.some(({ webSocketToken })=>webSocketToken === query.token) ? this.wsServer.handleUpgrade(req, socket, head, (connection)=>{
7104
7241
  this.wsServer.emit('connection', connection, req);
7105
- }) : socket.destroy();
7242
+ }) : socket.destroy(), !0;
7106
7243
  };
7107
7244
  checkSockets = ()=>{
7108
7245
  for (let socket of this.wsServer.clients)socket.isAlive ? (socket.isAlive = !1, socket.ping(()=>{})) : socket.terminate();
@@ -7517,7 +7654,15 @@ let createDeferred = ()=>{
7517
7654
  return deferred.promise = new Promise((resolve)=>{
7518
7655
  deferred.resolve = resolve;
7519
7656
  }), deferred;
7520
- }, ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xml/i;
7657
+ }, ENCODING_REGEX = /\bgzip\b/, TEXT_LIKE_MIME_TYPE = /text|javascript|\/json|xml|\+(?:json|yaml)$/, COMPRESSIBLE_ASSET_TYPES = new Set([
7658
+ 'application/toml',
7659
+ 'application/wasm',
7660
+ 'application/yaml',
7661
+ 'font/collection',
7662
+ 'font/otf',
7663
+ 'font/ttf',
7664
+ 'image/bmp'
7665
+ ]);
7521
7666
  function gzipMiddleware_gzipMiddleware({ filter, level = node_zlib.constants.Z_BEST_SPEED } = {}) {
7522
7667
  return function gzipMiddleware(req, res, next) {
7523
7668
  let gzip, writeHeadStatus, writeHeadMessage;
@@ -7531,12 +7676,13 @@ function gzipMiddleware_gzipMiddleware({ filter, level = node_zlib.constants.Z_B
7531
7676
  let start = ()=>{
7532
7677
  if (started) return;
7533
7678
  if (started = !0, ((res)=>{
7679
+ var contentType;
7534
7680
  let index;
7535
7681
  if (res.getHeader('Content-Encoding')) return !1;
7536
- let contentType = res.getHeader('Content-Type');
7537
- if (!contentType) return !1;
7538
- let contentTypeValue = String(contentType);
7539
- if (!CONTENT_TYPE_REGEX.test(contentTypeValue) || 'text/event-stream' === (-1 === (index = contentTypeValue.indexOf(';')) ? contentTypeValue : contentTypeValue.slice(0, index)).trim().toLowerCase()) return !1;
7682
+ let contentType1 = res.getHeader('Content-Type');
7683
+ if (!contentType1) return !1;
7684
+ let mimeType = (-1 === (index = (contentType = String(contentType1)).indexOf(';')) ? contentType : contentType.slice(0, index)).trim().toLowerCase();
7685
+ if ('text/event-stream' === mimeType || !TEXT_LIKE_MIME_TYPE.test(mimeType) && !COMPRESSIBLE_ASSET_TYPES.has(mimeType)) return !1;
7540
7686
  let size = res.getHeader('Content-Length');
7541
7687
  return void 0 === size || Number(size) > 1024;
7542
7688
  })(res)) {
@@ -8378,7 +8524,7 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8378
8524
  })(options.config, options.devServer, logger);
8379
8525
  for (let middleware of before)middlewares.use(middleware);
8380
8526
  let { onUpgrade } = await (async ({ config, buildManager, context, devServer, middlewares, postCallbacks })=>{
8381
- let launchEditorHandlerPromise, upgradeEvents = [], { server } = config, { logger } = context, servedEnvironments = context.environmentList.filter((environment)=>isServingAssets(environment.config)), distPaths = [
8527
+ let proxyUpgrade, launchEditorHandlerPromise, { server } = config, { logger } = context, servedEnvironments = context.environmentList.filter((environment)=>isServingAssets(environment.config)), distPaths = [
8382
8528
  ...new Set(servedEnvironments.map((environment)=>environment.distPath))
8383
8529
  ];
8384
8530
  if (server.cors) {
@@ -8391,7 +8537,7 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8391
8537
  next();
8392
8538
  }), server.proxy) {
8393
8539
  let { middlewares: proxyMiddlewares, upgrade } = await createProxyMiddleware(server.proxy, logger);
8394
- for (let middleware of (upgradeEvents.push(upgrade), proxyMiddlewares))middlewares.use(middleware);
8540
+ for (let middleware of (proxyUpgrade = upgrade, proxyMiddlewares))middlewares.use(middleware);
8395
8541
  }
8396
8542
  let { compress } = server;
8397
8543
  if (compress && middlewares.use(gzipMiddleware_gzipMiddleware('object' == typeof compress ? compress : void 0)), 'dev' === context.action && buildManager) {
@@ -8470,7 +8616,7 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8470
8616
  })({
8471
8617
  environments: pick(devServer.environments, servedEnvironments.map((environment)=>environment.name)),
8472
8618
  logger
8473
- })), buildManager && (middlewares.use(buildManager.assetsMiddleware), upgradeEvents.push(buildManager.socketServer.upgrade), middlewares.use(function hotUpdateJsonFallbackMiddleware(req, res, next) {
8619
+ })), buildManager && (middlewares.use(buildManager.assetsMiddleware), middlewares.use(function hotUpdateJsonFallbackMiddleware(req, res, next) {
8474
8620
  let url = req.url;
8475
8621
  if (!url || 'OPTIONS' === req.method) return void next();
8476
8622
  let queryIndex = url.indexOf('?'), end = -1 === queryIndex ? url.length : queryIndex;
@@ -8501,7 +8647,7 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8501
8647
  outputFileSystem: buildManager.outputFileSystem
8502
8648
  })), middlewares.use(faviconFallbackMiddleware), {
8503
8649
  onUpgrade: (...args)=>{
8504
- for (let cb of upgradeEvents)cb(...args);
8650
+ buildManager?.socketServer.upgrade(...args) || proxyUpgrade?.(...args);
8505
8651
  }
8506
8652
  };
8507
8653
  })({
@@ -8764,7 +8910,7 @@ function applyDefaultPlugins(pluginManager, context) {
8764
8910
  ...chain.get('experiments'),
8765
8911
  newCache: !0
8766
8912
  }), cacheEnabled = !0;
8767
- let { context } = api, cacheConfig = 'boolean' == typeof buildCache ? {} : buildCache, cacheDirectory = getCacheDirectory(cacheConfig, context), buildDependencies = await getBuildDependencies(context, environment, cacheConfig.buildDependencies), useDigest = Array.isArray(cacheConfig.cacheDigest) && cacheConfig.cacheDigest.length, cacheVersion = `rsbuild-2.3.4-${environment.name}-${env}`;
8913
+ let { context } = api, cacheConfig = 'boolean' == typeof buildCache ? {} : buildCache, cacheDirectory = getCacheDirectory(cacheConfig, context), buildDependencies = await getBuildDependencies(context, environment, cacheConfig.buildDependencies), useDigest = Array.isArray(cacheConfig.cacheDigest) && cacheConfig.cacheDigest.length, cacheVersion = `rsbuild-2.3.6-${environment.name}-${env}`;
8768
8914
  chain.cache({
8769
8915
  type: 'persistent',
8770
8916
  version: useDigest ? `${cacheVersion}-${await helpers_hash(JSON.stringify(cacheConfig.cacheDigest))}` : cacheVersion,
@@ -8825,18 +8971,15 @@ function applyDefaultPlugins(pluginManager, context) {
8825
8971
  }
8826
8972
  });
8827
8973
  let isESM = config.output.module;
8828
- if (isServer && chain.output.merge({
8974
+ isServer && chain.output.merge({
8829
8975
  library: {
8830
8976
  type: isESM ? 'module' : 'commonjs2'
8831
8977
  }
8832
- }), isESM && (chain.node.set('__dirname', !1).set('__filename', !1), chain.output.module(!0).chunkFormat('module').chunkLoading('import').workerChunkLoading('import')), config.output.copy) {
8833
- let { copy } = config.output, options = Array.isArray(copy) ? {
8834
- patterns: copy
8835
- } : copy;
8836
- chain.plugin(CHAIN_ID.PLUGIN.COPY).use(rspack.CopyRspackPlugin, [
8837
- options
8838
- ]);
8839
- }
8978
+ }), isESM && (chain.node.set('__dirname', !1).set('__filename', !1), chain.output.module(!0).chunkFormat('module').chunkLoading('import').workerChunkLoading('import'));
8979
+ let { copy } = config.output;
8980
+ copy && chain.plugin(CHAIN_ID.PLUGIN.COPY).use(rspack.CopyRspackPlugin, [
8981
+ normalizeCopyOptions(copy)
8982
+ ]);
8840
8983
  });
8841
8984
  }
8842
8985
  },
@@ -9281,11 +9424,49 @@ try {
9281
9424
  {
9282
9425
  name: 'rsbuild:css',
9283
9426
  setup (api) {
9284
- let postcssrcCache = new Map();
9427
+ let applyPostCSS = createPostCSSTransform(api.context.rootPath);
9428
+ async function applyCSSTransforms(utils, mainRule, inlineRule, urlRule) {
9429
+ let { environment, environments, target, CHAIN_ID } = utils, { config } = environment, cssUrlMinimized = !1, useLightningCSS = !1 !== config.tools.lightningcssLoader;
9430
+ if (useLightningCSS) {
9431
+ let { minifyCss, cssOptions } = parseMinifyOptions(config), { browserslist } = environment;
9432
+ if ('node' === target) {
9433
+ let webEnvironment = Object.values(environments).find((env)=>'web' === env.config.output.target);
9434
+ if (webEnvironment) {
9435
+ browserslist = webEnvironment.browserslist;
9436
+ let webMinifyOptions = parseMinifyOptions(webEnvironment.config);
9437
+ minifyCss = webMinifyOptions.minifyCss, cssOptions ??= webMinifyOptions.cssOptions;
9438
+ }
9439
+ }
9440
+ let cssUrlMinimizerOptions = minifyCss ? ((cssOptions)=>{
9441
+ let options = helpers_castArray(cssOptions), { minimizerOptions, test, include, exclude } = options[0] ?? {};
9442
+ return !(options.length > 1 || [
9443
+ test,
9444
+ include,
9445
+ exclude
9446
+ ].some((value)=>void 0 !== value)) && (minimizerOptions ?? {});
9447
+ })(cssOptions) : {}, addLightningCSS = async (rule, type)=>{
9448
+ let minify = ('inline' === type || 'url' === type || config.output.injectStyles) && minifyCss, lightningcssOptions = await getLightningCSSLoaderOptions(config, browserslist, minify);
9449
+ if ('url' === type && !0 === lightningcssOptions.minify && !1 !== cssUrlMinimizerOptions) {
9450
+ var loaderOptions;
9451
+ let options;
9452
+ loaderOptions = lightningcssOptions, options = cjs_0_default()(loaderOptions, cssUrlMinimizerOptions), isPlainObject(cssUrlMinimizerOptions.targets) && (options.targets = cssUrlMinimizerOptions.targets), lightningcssOptions = options, cssUrlMinimized = !0;
9453
+ }
9454
+ rule.use(CHAIN_ID.USE.LIGHTNINGCSS).loader('builtin:lightningcss-loader').options(lightningcssOptions);
9455
+ };
9456
+ mainRule && await addLightningCSS(mainRule, 'main'), await addLightningCSS(inlineRule, 'inline'), await addLightningCSS(urlRule, 'url');
9457
+ }
9458
+ return {
9459
+ useLightningCSS,
9460
+ usePostCSS: await applyPostCSS(utils, mainRule, inlineRule, urlRule),
9461
+ cssUrlMinimized
9462
+ };
9463
+ }
9285
9464
  api.modifyBundlerChain({
9286
9465
  order: 'pre',
9287
- handler: async (chain, { target, isProd, CHAIN_ID, environment, environments })=>{
9288
- let cssRule = chain.module.rule(CHAIN_ID.RULE.CSS), { config } = environment;
9466
+ handler: async (chain, utils)=>{
9467
+ let { target, isProd, CHAIN_ID, environment } = utils, { config } = environment;
9468
+ if (config.css) return;
9469
+ let cssRule = chain.module.rule(CHAIN_ID.RULE.CSS);
9289
9470
  cssRule.test(CSS_REGEX).dependency({
9290
9471
  not: 'url'
9291
9472
  }), cssRule.oneOf(CHAIN_ID.ONE_OF.CSS_TEXT).with({
@@ -9304,100 +9485,9 @@ try {
9304
9485
  mainRule.use(CHAIN_ID.USE.STYLE).loader(getCompiledPath('style-loader')).options(styleLoaderOptions);
9305
9486
  } else mainRule.use(CHAIN_ID.USE.MINI_CSS_EXTRACT).loader(core_rspack.CssExtractRspackPlugin.loader).options(config.tools.cssExtract.loaderOptions);
9306
9487
  else mainRule.use(CHAIN_ID.USE.IGNORE_CSS).loader(node_path.join(LOADER_PATH, 'ignoreCssLoader.mjs'));
9307
- let importLoaders = {
9308
- normal: 0,
9309
- inline: 0
9310
- }, updateRules = async (callback, options = {})=>{
9311
- options.skipMain || await callback(mainRule, 'main'), await callback(inlineRule, 'inline'), await callback(urlRule, 'url');
9312
- }, cssLoaderPath = getCompiledPath('css-loader');
9313
- await updateRules((rule)=>{
9314
- rule.use(CHAIN_ID.USE.CSS).loader(cssLoaderPath);
9315
- });
9316
- let cssUrlMinimized = !1;
9317
- if (!1 !== config.tools.lightningcssLoader) {
9318
- emitCss && importLoaders.normal++, importLoaders.inline++;
9319
- let { minifyCss, cssOptions } = parseMinifyOptions(config), { browserslist } = environment;
9320
- if ('node' === target) {
9321
- let webEnvironment = Object.values(environments).find((env)=>'web' === env.config.output.target);
9322
- if (webEnvironment) {
9323
- browserslist = webEnvironment.browserslist;
9324
- let webMinifyOptions = parseMinifyOptions(webEnvironment.config);
9325
- minifyCss = webMinifyOptions.minifyCss, cssOptions ??= webMinifyOptions.cssOptions;
9326
- }
9327
- }
9328
- let cssUrlMinimizerOptions = minifyCss ? ((cssOptions)=>{
9329
- let options = helpers_castArray(cssOptions), { minimizerOptions, test, include, exclude } = options[0] ?? {};
9330
- return !(options.length > 1 || [
9331
- test,
9332
- include,
9333
- exclude
9334
- ].some((value)=>void 0 !== value)) && (minimizerOptions ?? {});
9335
- })(cssOptions) : {};
9336
- await updateRules(async (rule, type)=>{
9337
- let minify = ('inline' === type || 'url' === type || config.output.injectStyles) && minifyCss, lightningcssOptions = await getLightningCSSLoaderOptions(config, browserslist, minify);
9338
- if ('url' === type && !0 === lightningcssOptions.minify && !1 !== cssUrlMinimizerOptions) {
9339
- var loaderOptions;
9340
- let options;
9341
- loaderOptions = lightningcssOptions, options = cjs_0_default()(loaderOptions, cssUrlMinimizerOptions), isPlainObject(cssUrlMinimizerOptions.targets) && (options.targets = cssUrlMinimizerOptions.targets), lightningcssOptions = options, cssUrlMinimized = !0;
9342
- }
9343
- rule.use(CHAIN_ID.USE.LIGHTNINGCSS).loader('builtin:lightningcss-loader').options(lightningcssOptions);
9344
- }, {
9345
- skipMain: !emitCss
9346
- });
9347
- }
9348
- let postcssLoaderOptions = await (async ({ config, root, postcssrcCache })=>{
9349
- let extraPlugins = [], userOptions = await loadUserPostcssrc(root, postcssrcCache);
9350
- userOptions.plugins ||= [];
9351
- let defaultOptions = {
9352
- implementation: getCompiledPath('postcss'),
9353
- postcssOptions: userOptions,
9354
- sourceMap: getCSSSourceMap(config)
9355
- }, finalOptions = await reduceConfigsWithContext({
9356
- initial: defaultOptions,
9357
- config: config.tools.postcss,
9358
- ctx: {
9359
- addPlugins (plugins, options = {}) {
9360
- let { order = 'post' } = options, list = helpers_castArray(plugins);
9361
- 'pre' === order ? extraPlugins.unshift(...list) : extraPlugins.push(...list);
9362
- }
9363
- }
9364
- });
9365
- finalOptions.postcssOptions ||= {};
9366
- let updatePostcssOptions = (options)=>(options.plugins ||= [], extraPlugins.length && options.plugins.push(...extraPlugins), options.plugins = options.plugins.map((plugin)=>'function' == typeof plugin && 'postcss' in plugin && plugin.postcss ? plugin() : plugin), options.config = !1, options), { postcssOptions } = finalOptions;
9367
- if ('function' == typeof postcssOptions) {
9368
- let postcssOptionsWrapper = (loaderContext)=>{
9369
- let options = postcssOptions(loaderContext);
9370
- if ('object' != typeof options || null === options) throw Error(`${color.dim('[rsbuild:css]')} \`postcssOptions\` function must return a PostCSSOptions object, got ${color.yellow(typeof options)}.`);
9371
- return updatePostcssOptions({
9372
- ...userOptions,
9373
- ...options,
9374
- plugins: [
9375
- ...userOptions.plugins || [],
9376
- ...options.plugins || []
9377
- ]
9378
- });
9379
- };
9380
- return postcssOptionsWrapper.config = !1, {
9381
- ...finalOptions,
9382
- postcssOptions: postcssOptionsWrapper
9383
- };
9384
- }
9385
- return finalOptions.postcssOptions = updatePostcssOptions(postcssOptions), finalOptions;
9386
- })({
9387
- config,
9388
- root: api.context.rootPath,
9389
- postcssrcCache
9390
- });
9391
- if ('function' == typeof postcssLoaderOptions.postcssOptions || postcssLoaderOptions.postcssOptions?.plugins?.length) {
9392
- emitCss && importLoaders.normal++, importLoaders.inline++;
9393
- let postcssLoaderPath = getCompiledPath('postcss-loader');
9394
- await updateRules((rule)=>{
9395
- rule.use(CHAIN_ID.USE.POSTCSS).loader(postcssLoaderPath).options(postcssLoaderOptions);
9396
- }, {
9397
- skipMain: !emitCss
9398
- });
9399
- }
9400
- let localIdentName = config.output.cssModules.localIdentName || (isProd ? '[local]-[hash:base64:6]' : '[path][name]__[local]-[hash:base64:6]'), cssLoaderOptions = await (async ({ config, localIdentName, emitCss })=>{
9488
+ let cssLoaderPath = getCompiledPath('css-loader');
9489
+ mainRule.use(CHAIN_ID.USE.CSS).loader(cssLoaderPath), inlineRule.use(CHAIN_ID.USE.CSS).loader(cssLoaderPath), urlRule.use(CHAIN_ID.USE.CSS).loader(cssLoaderPath);
9490
+ let { useLightningCSS, usePostCSS, cssUrlMinimized } = await applyCSSTransforms(utils, emitCss ? mainRule : void 0, inlineRule, urlRule), importLoaders = Number(useLightningCSS) + Number(usePostCSS), localIdentName = config.output.cssModules.localIdentName || (isProd ? '[local]-[hash:base64:6]' : '[path][name]__[local]-[hash:base64:6]'), cssLoaderOptions = await (async ({ config, localIdentName, emitCss })=>{
9401
9491
  let { cssModules } = config.output, defaultOptions = {
9402
9492
  modules: {
9403
9493
  ...cssModules,
@@ -9431,44 +9521,60 @@ try {
9431
9521
  config,
9432
9522
  localIdentName,
9433
9523
  emitCss
9434
- });
9435
- await updateRules((rule, type)=>{
9524
+ }), configureCSSLoader = (rule, type)=>{
9436
9525
  let finalOptions = 'inline' === type || 'url' === type ? {
9437
9526
  ...cssLoaderOptions,
9438
9527
  exportType: 'string',
9439
9528
  modules: !1,
9440
- importLoaders: importLoaders.inline
9529
+ importLoaders
9441
9530
  } : {
9442
9531
  ...cssLoaderOptions,
9443
- importLoaders: importLoaders.normal
9532
+ importLoaders: emitCss ? importLoaders : 0
9444
9533
  };
9445
9534
  emitCss || 'main' !== type || rule.use(CHAIN_ID.USE.IGNORE_CSS).options({
9446
9535
  modules: finalOptions.modules
9447
9536
  }), rule.use(CHAIN_ID.USE.CSS).options(finalOptions), 'url' !== type && rule.sideEffects(!0), rule.resolve.preferRelative(!0);
9448
- });
9449
- let cssUrlFilename = getFilename(config, 'css', isProd), cssUrlPath = config.output.distPath.css;
9537
+ };
9538
+ configureCSSLoader(mainRule, 'main'), configureCSSLoader(inlineRule, 'inline'), configureCSSLoader(urlRule, 'url');
9539
+ let { distPath } = config.output, cssFilename = getFilename(config, 'css', isProd), filename = getCSSOutputFilename(distPath.css, cssFilename);
9450
9540
  urlRule.use(CHAIN_ID.USE.CSS_URL).options({
9451
- filename: 'function' == typeof cssUrlFilename ? (pathData, assetInfo)=>posix.join(cssUrlPath, cssUrlFilename(pathData, assetInfo)) : posix.join(cssUrlPath, cssUrlFilename),
9541
+ filename,
9452
9542
  modules: cssLoaderOptions.modules,
9453
9543
  minimized: cssUrlMinimized
9454
9544
  });
9455
9545
  let isStringExport = 'string' === cssLoaderOptions.exportType;
9456
- 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) {
9457
- let extractPluginOptions = config.tools.cssExtract.pluginOptions, cssPath = config.output.distPath.css, cssFilename = getFilename(config, 'css', isProd), isCssFilenameFn = 'function' == typeof cssFilename, cssAsyncPath = config.output.distPath.cssAsync ?? (cssPath ? `${cssPath}/async` : 'async');
9458
- chain.plugin(CHAIN_ID.PLUGIN.MINI_CSS_EXTRACT).use(core_rspack.CssExtractRspackPlugin, [
9459
- {
9460
- filename: isCssFilenameFn ? (...args)=>{
9461
- let name = cssFilename(...args);
9462
- return posix.join(cssPath, name);
9463
- } : posix.join(cssPath, cssFilename),
9464
- chunkFilename: isCssFilenameFn ? (...args)=>{
9465
- let name = cssFilename(...args);
9466
- return posix.join(cssAsyncPath, name);
9467
- } : posix.join(cssAsyncPath, cssFilename),
9468
- ...extractPluginOptions
9469
- }
9470
- ]);
9471
- }
9546
+ isStringExport && mainRule.uses.has(CHAIN_ID.USE.MINI_CSS_EXTRACT) && mainRule.uses.delete(CHAIN_ID.USE.MINI_CSS_EXTRACT), !emitCss || config.output.injectStyles || isStringExport || chain.plugin(CHAIN_ID.PLUGIN.MINI_CSS_EXTRACT).use(core_rspack.CssExtractRspackPlugin, [
9547
+ {
9548
+ filename,
9549
+ chunkFilename: getCSSChunkFilename(distPath, cssFilename),
9550
+ ...config.tools.cssExtract.pluginOptions
9551
+ }
9552
+ ]);
9553
+ }
9554
+ });
9555
+ }
9556
+ },
9557
+ {
9558
+ name: 'rsbuild:builtin-css',
9559
+ setup (api) {
9560
+ let applyPostCSS = createPostCSSTransform(api.context.rootPath);
9561
+ api.modifyBundlerChain({
9562
+ order: 'pre',
9563
+ handler: async (chain, utils)=>{
9564
+ let { environment, CHAIN_ID, isProd } = utils, { config, browserslist } = environment;
9565
+ if (!config.css) return;
9566
+ let cssRule = chain.module.rule(CHAIN_ID.RULE.CSS);
9567
+ cssRule.test(CSS_REGEX).dependency({
9568
+ not: 'url'
9569
+ }), cssRule.oneOf(CHAIN_ID.ONE_OF.CSS_TEXT).with({
9570
+ type: 'text'
9571
+ }).type('asset/source'), cssRule.oneOf(CHAIN_ID.ONE_OF.CSS_RAW).resourceQuery(RAW_QUERY_REGEX).type('asset/source');
9572
+ let mainRule = cssRule.oneOf(CHAIN_ID.ONE_OF.CSS_MAIN);
9573
+ if (mainRule.type('css/auto').sideEffects(!0).resolve.preferRelative(!0), !1 !== config.tools.lightningcssLoader && mainRule.use(CHAIN_ID.USE.LIGHTNINGCSS).loader('builtin:lightningcss-loader').options(await getLightningCSSLoaderOptions(config, browserslist, !1)), await applyPostCSS(utils, mainRule), 'object' == typeof config.css && 'style' === config.css.exportType) return void mainRule.parser({
9574
+ exportType: 'style'
9575
+ });
9576
+ let { distPath } = config.output, cssFilename = getFilename(config, 'css', isProd);
9577
+ chain.output.set('cssFilename', getCSSOutputFilename(distPath.css, cssFilename)).set('cssChunkFilename', getCSSChunkFilename(distPath, cssFilename));
9472
9578
  }
9473
9579
  });
9474
9580
  }
@@ -9585,7 +9691,7 @@ try {
9585
9691
  config: config.tools.swc,
9586
9692
  mergeFn: cjs_0_default()
9587
9693
  });
9588
- mergedConfig.jsc?.target !== void 0 && mergedConfig.env?.targets !== void 0 && 1 === Object.keys(mergedConfig.env).length && delete mergedConfig.env, mainRule.use(CHAIN_ID.USE.SWC).loader(builtinSwcLoaderName).options(mergedConfig), dataUriRule.resolve.set('fullySpecified', !1).end().use(CHAIN_ID.USE.SWC).loader(builtinSwcLoaderName).options(cloneDeep(mergedConfig));
9694
+ mergedConfig.jsc?.target !== void 0 && mergedConfig.env?.targets !== void 0 && 1 === Object.keys(mergedConfig.env).length && delete mergedConfig.env, mainRule.use(CHAIN_ID.USE.SWC).loader('builtin:swc-loader').options(mergedConfig), dataUriRule.resolve.set('fullySpecified', !1).end().use(CHAIN_ID.USE.SWC).cloneFrom(mainRule.use(CHAIN_ID.USE.SWC));
9589
9695
  }
9590
9696
  });
9591
9697
  }
@@ -10517,7 +10623,7 @@ let applyServerOptions = (command)=>{
10517
10623
  };
10518
10624
  function setupCommands(argv) {
10519
10625
  let cli = ((name = "")=>new CAC(name))('rsbuild');
10520
- cli.version("2.3.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)', {
10626
+ cli.version("2.3.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)', {
10521
10627
  default: 'auto'
10522
10628
  }).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', {
10523
10629
  type: [
@@ -10582,7 +10688,7 @@ function setupCommands(argv) {
10582
10688
  }
10583
10689
  function showGreeting() {
10584
10690
  let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
10585
- src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.3.4\n`);
10691
+ src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.3.6\n`);
10586
10692
  }
10587
10693
  function setupLogLevel(argv) {
10588
10694
  if (argv.length <= 3) return;
@@ -10604,5 +10710,5 @@ function runCLI({ argv = process.argv } = {}) {
10604
10710
  src_logger.error('Failed to start Rsbuild CLI.'), src_logger.error(err), process.exit(1);
10605
10711
  }
10606
10712
  }
10607
- let src_version = "2.3.4";
10713
+ let src_version = "2.3.6";
10608
10714
  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 };