@ohos-ports/rsbuild-core 2.2.13-beta.0 → 2.3.3-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +7 -9
  2. package/compiled/@rstackjs/load-config/index.d.ts +10 -1
  3. package/compiled/@rstackjs/load-config/package.json +1 -1
  4. package/compiled/chokidar/index.d.ts +448 -161
  5. package/compiled/chokidar/package.json +1 -1
  6. package/compiled/css-loader/index.js +2 -2
  7. package/compiled/html-rspack-plugin/index.js +14 -14
  8. package/compiled/http-proxy-middleware/index.d.ts +10 -10
  9. package/compiled/http-proxy-middleware/package.json +1 -1
  10. package/compiled/jiti/dist/babel.cjs +1 -1
  11. package/compiled/postcss/index.js +1 -1
  12. package/compiled/postcss/lib/declaration.d.ts +2 -2
  13. package/compiled/postcss/package.json +1 -1
  14. package/compiled/postcss-loader/index.js +6 -6
  15. package/compiled/rspack-chain/package.json +1 -1
  16. package/compiled/rspack-chain/types/index.d.ts +1 -0
  17. package/dist/1.js +1 -0
  18. package/dist/chokidar.js +1 -1
  19. package/dist/client/hmr.js +26 -8
  20. package/dist/client/overlay.js +6 -5
  21. package/dist/defaultConfig.d.ts +7 -2
  22. package/dist/helpers/compilation.d.ts +2 -0
  23. package/dist/helpers/stats.d.ts +1 -0
  24. package/dist/helpers/workspace.d.ts +1 -0
  25. package/dist/hooks.d.ts +2 -1
  26. package/dist/http-proxy-middleware.js +4 -4
  27. package/dist/index.d.ts +1 -1
  28. package/dist/m.js +1515 -1387
  29. package/dist/m.js.LICENSE.txt +0 -13
  30. package/dist/manifest-plugin.js +1 -1
  31. package/dist/memfs.js +1 -1
  32. package/dist/open.js +2 -2
  33. package/dist/server/assets-middleware/getFileFromUrl.d.ts +3 -1
  34. package/dist/server/assets-middleware/index.d.ts +2 -1
  35. package/dist/server/assets-middleware/middleware.d.ts +4 -6
  36. package/dist/server/assets-middleware/setupMemoryFileSystemCleanup.d.ts +3 -0
  37. package/dist/server/devMiddlewares.d.ts +1 -1
  38. package/dist/server/helper.d.ts +5 -2
  39. package/dist/server/socketServer.d.ts +18 -2
  40. package/dist/server/watchFiles.d.ts +3 -1
  41. package/dist/sirv.js +3 -2
  42. package/dist/transformLoader.mjs +10 -10
  43. package/dist/transformRawLoader.mjs +2 -2
  44. package/dist/types/config.d.ts +17 -4
  45. package/dist/types/hooks.d.ts +1 -0
  46. package/dist/types/plugin.d.ts +26 -4
  47. package/dist/types/rsbuild.d.ts +1 -1
  48. package/dist/workerLoader.mjs +3 -3
  49. package/dist/ws.js +2 -2
  50. package/package.json +5 -5
package/dist/m.js CHANGED
@@ -1,11 +1,11 @@
1
1
  /*! LICENSE: m.js.LICENSE.txt */
2
- let runtimeProcessArgs, runtimeInfo, swcHelpersPath, pluginHelper_htmlPlugin;
2
+ let 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
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
- import { builtinModules, createRequire, createRequire as __rspack_createRequire } from "node:module";
8
- import node_fs, { existsSync } from "node:fs";
7
+ import { createRequire, isBuiltin, createRequire as __rspack_createRequire } from "node:module";
8
+ import node_fs, { existsSync, readFileSync } from "node:fs";
9
9
  import node_os, { constants } from "node:os";
10
10
  import node_process from "node:process";
11
11
  import { URL as external_node_url_URL, pathToFileURL, fileURLToPath as __rspack_fileURLToPath } from "node:url";
@@ -13,6 +13,7 @@ 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
15
  import { once as external_node_events_once } from "node:events";
16
+ import { finished } from "node:stream";
16
17
  import { isIP } from "node:net";
17
18
  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";
18
19
  import { cachedImport as cachedImport_cachedImport, getTinyglobby } from "./r.js";
@@ -121,39 +122,6 @@ moduleFactories.add({
121
122
  }
122
123
  module.exports.f = expand;
123
124
  },
124
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/ee-first/1.1.1/7d7aff2abffb03f454b885edc2f03bd078376c8cde75af0c324753fee26268de/node_modules/ee-first/index.js" (module) {
125
- function listener(event, done) {
126
- return function onevent(arg1) {
127
- for(var args = Array(arguments.length), i = 0; i < args.length; i++)args[i] = arguments[i];
128
- done('error' === event ? arg1 : null, this, event, args);
129
- };
130
- }
131
- module.exports = function first(stuff, done) {
132
- if (!Array.isArray(stuff)) throw TypeError('arg must be an array of [ee, events...] arrays');
133
- for(var cleanups = [], i = 0; i < stuff.length; i++){
134
- var arr = stuff[i];
135
- if (!Array.isArray(arr) || arr.length < 2) throw TypeError('each array member must be [ee, events...]');
136
- for(var ee = arr[0], j = 1; j < arr.length; j++){
137
- var event = arr[j], fn = listener(event, callback);
138
- ee.on(event, fn), cleanups.push({
139
- ee: ee,
140
- event: event,
141
- fn: fn
142
- });
143
- }
144
- }
145
- function callback() {
146
- cleanup(), done.apply(null, arguments);
147
- }
148
- function cleanup() {
149
- for(var x, i = 0; i < cleanups.length; i++)(x = cleanups[i]).ee.removeListener(x.event, x.fn);
150
- }
151
- function thunk(fn) {
152
- done = fn;
153
- }
154
- return thunk.cancel = cleanup, thunk;
155
- };
156
- },
157
125
  "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/lilconfig/3.1.3/8e9a79516bf61f8427342cef50cdad2cdc2572f42288ba8053b88eadfdc0ebef/node_modules/lilconfig/src/index.js" (module) {
158
126
  let path = __rspack_createRequire_require("path"), fs = __rspack_createRequire_require("fs"), os = __rspack_createRequire_require("os"), url = __rspack_createRequire_require("url"), fsReadFileAsync = fs.promises.readFile;
159
127
  function getDefaultSearchPlaces(name, sync) {
@@ -239,7 +207,7 @@ moduleFactories.add({
239
207
  if ('function' != typeof loader) throw Error('loader is not a function');
240
208
  }
241
209
  module.exports.lilconfig = function lilconfig(name, options) {
242
- let { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, cache } = getOptions(name, options ?? {}, !1), searchCache = new Map(), loadCache = new Map(), emplace = (c, filepath, res)=>(cache && c.set(filepath, res), res);
210
+ let { ignoreEmptySearchPlaces, loaders, packageProp, searchPlaces, stopDir, transform, cache } = getOptions(name, options ?? {}, !1), searchCache = new Map(), loadCache = new Map(), emplace = (0, (c, filepath, res)=>(cache && c.set(filepath, res), res));
243
211
  return {
244
212
  async search (searchFrom = process.cwd()) {
245
213
  let result = {
@@ -324,74 +292,8 @@ moduleFactories.add({
324
292
  };
325
293
  };
326
294
  },
327
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/on-finished/2.4.1/cf4b90e733493a0ce70ba421a5b37153ad39360f9513e36b25d2e49f57047a9b/node_modules/on-finished/index.js" (module) {
328
- module.exports = onFinished, module.exports.isFinished = isFinished;
329
- var asyncHooks = tryRequireAsyncHooks(), first = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/ee-first/1.1.1/7d7aff2abffb03f454b885edc2f03bd078376c8cde75af0c324753fee26268de/node_modules/ee-first/index.js"), defer = 'function' == typeof setImmediate ? setImmediate : function(fn) {
330
- process.nextTick(fn.bind.apply(fn, arguments));
331
- };
332
- function onFinished(msg, listener) {
333
- return !1 !== isFinished(msg) ? defer(listener, null, msg) : attachListener(msg, wrap(listener)), msg;
334
- }
335
- function isFinished(msg) {
336
- var socket = msg.socket;
337
- return 'boolean' == typeof msg.finished ? !!(msg.finished || socket && !socket.writable) : 'boolean' == typeof msg.complete ? !!(msg.upgrade || !socket || !socket.readable || msg.complete && !msg.readable) : void 0;
338
- }
339
- function attachFinishedListener(msg, callback) {
340
- var eeMsg, eeSocket, finished = !1;
341
- function onFinish(error) {
342
- eeMsg.cancel(), eeSocket.cancel(), finished = !0, callback(error);
343
- }
344
- function onSocket(socket) {
345
- msg.removeListener('socket', onSocket), finished || eeMsg === eeSocket && (eeSocket = first([
346
- [
347
- socket,
348
- 'error',
349
- 'close'
350
- ]
351
- ], onFinish));
352
- }
353
- (eeMsg = eeSocket = first([
354
- [
355
- msg,
356
- 'end',
357
- 'finish'
358
- ]
359
- ], onFinish), msg.socket) ? onSocket(msg.socket) : (msg.on('socket', onSocket), void 0 === msg.socket && patchAssignSocket(msg, onSocket));
360
- }
361
- function attachListener(msg, listener) {
362
- var attached = msg.__onFinished;
363
- attached && attached.queue || (attached = msg.__onFinished = createListener(msg), attachFinishedListener(msg, attached)), attached.queue.push(listener);
364
- }
365
- function createListener(msg) {
366
- function listener(err) {
367
- if (msg.__onFinished === listener && (msg.__onFinished = null), listener.queue) {
368
- var queue = listener.queue;
369
- listener.queue = null;
370
- for(var i = 0; i < queue.length; i++)queue[i](err, msg);
371
- }
372
- }
373
- return listener.queue = [], listener;
374
- }
375
- function patchAssignSocket(res, callback) {
376
- var assignSocket = res.assignSocket;
377
- 'function' == typeof assignSocket && (res.assignSocket = function _assignSocket(socket) {
378
- assignSocket.call(this, socket), callback(socket);
379
- });
380
- }
381
- function tryRequireAsyncHooks() {
382
- try {
383
- return rspackRequire("async_hooks");
384
- } catch (e) {
385
- return {};
386
- }
387
- }
388
- function wrap(fn) {
389
- var res;
390
- return (asyncHooks.AsyncResource && (res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn')), res && res.runInAsyncScope) ? res.runInAsyncScope.bind(res, fn, null) : fn;
391
- }
392
- },
393
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/baf07bf9099810ce2e0c00768f056c90b47d57b154f4b8912460449b9922899a/node_modules/postcss-load-config/src/index.js" (module) {
394
- 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/baf07bf9099810ce2e0c00768f056c90b47d57b154f4b8912460449b9922899a/node_modules/postcss-load-config/src/options.js"), loadPlugins = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/baf07bf9099810ce2e0c00768f056c90b47d57b154f4b8912460449b9922899a/node_modules/postcss-load-config/src/plugins.js"), req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/baf07bf9099810ce2e0c00768f056c90b47d57b154f4b8912460449b9922899a/node_modules/postcss-load-config/src/req.js");
295
+ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/0c96146f27b5be84aebd61df108bee07abfdc2dd46aa3cb0cd89aa03287d40cd/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/0c96146f27b5be84aebd61df108bee07abfdc2dd46aa3cb0cd89aa03287d40cd/node_modules/postcss-load-config/src/options.js"), loadPlugins = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/0c96146f27b5be84aebd61df108bee07abfdc2dd46aa3cb0cd89aa03287d40cd/node_modules/postcss-load-config/src/plugins.js"), req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/0c96146f27b5be84aebd61df108bee07abfdc2dd46aa3cb0cd89aa03287d40cd/node_modules/postcss-load-config/src/req.js");
395
297
  async function processResult(ctx, result) {
396
298
  let obj, file = result.filepath || '', projectConfig = ((obj = result.config) && obj.__esModule ? obj : {
397
299
  default: obj
@@ -464,8 +366,8 @@ moduleFactories.add({
464
366
  });
465
367
  };
466
368
  },
467
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/baf07bf9099810ce2e0c00768f056c90b47d57b154f4b8912460449b9922899a/node_modules/postcss-load-config/src/options.js" (module) {
468
- let req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/baf07bf9099810ce2e0c00768f056c90b47d57b154f4b8912460449b9922899a/node_modules/postcss-load-config/src/req.js");
369
+ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/0c96146f27b5be84aebd61df108bee07abfdc2dd46aa3cb0cd89aa03287d40cd/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/0c96146f27b5be84aebd61df108bee07abfdc2dd46aa3cb0cd89aa03287d40cd/node_modules/postcss-load-config/src/req.js");
469
371
  module.exports = async function options(config, file) {
470
372
  if (config.parser && 'string' == typeof config.parser) try {
471
373
  config.parser = await req(config.parser, file);
@@ -485,8 +387,8 @@ moduleFactories.add({
485
387
  return config;
486
388
  };
487
389
  },
488
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/baf07bf9099810ce2e0c00768f056c90b47d57b154f4b8912460449b9922899a/node_modules/postcss-load-config/src/plugins.js" (module) {
489
- let req = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/baf07bf9099810ce2e0c00768f056c90b47d57b154f4b8912460449b9922899a/node_modules/postcss-load-config/src/req.js");
390
+ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/0c96146f27b5be84aebd61df108bee07abfdc2dd46aa3cb0cd89aa03287d40cd/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/0c96146f27b5be84aebd61df108bee07abfdc2dd46aa3cb0cd89aa03287d40cd/node_modules/postcss-load-config/src/req.js");
490
392
  async function load(plugin, options, file) {
491
393
  try {
492
394
  if (null == options || 0 === Object.keys(options).length) return await req(plugin, file);
@@ -502,7 +404,7 @@ moduleFactories.add({
502
404
  }), list;
503
405
  };
504
406
  },
505
- "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/baf07bf9099810ce2e0c00768f056c90b47d57b154f4b8912460449b9922899a/node_modules/postcss-load-config/src/req.js" (module) {
407
+ "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/0c96146f27b5be84aebd61df108bee07abfdc2dd46aa3cb0cd89aa03287d40cd/node_modules/postcss-load-config/src/req.js" (module) {
506
408
  let tsx, jiti, { createRequire } = __rspack_createRequire_require("node:module"), { pathToFileURL } = __rspack_createRequire_require("node:url"), TS_EXT_RE = /\.[mc]?ts$/, importError = [];
507
409
  module.exports = async function req(name, rootFile = __rspack_import_meta_filename__) {
508
410
  let url = createRequire(rootFile).resolve(name);
@@ -531,9 +433,6 @@ moduleFactories.add({
531
433
  throw Error(`'tsx' or 'jiti' is required for the TypeScript configuration files. Make sure it is installed\nError: ${importError.map((error)=>error.message).join('\n')}`);
532
434
  };
533
435
  },
534
- async_hooks (module) {
535
- module.exports = __rspack_createRequire_require("async_hooks");
536
- },
537
436
  process (module) {
538
437
  module.exports = __rspack_createRequire_require("process");
539
438
  },
@@ -758,7 +657,7 @@ function setDotProp(obj, keys, val) {
758
657
  }
759
658
  }
760
659
  function setByType(obj, transforms) {
761
- for (let [key, transform] of Object.entries(transforms))transform.shouldTransform && (obj[key] = [
660
+ for (let [key, transform] of Object.entries(transforms))transform.shouldTransform && key in obj && (obj[key] = [
762
661
  obj[key]
763
662
  ].flat(), "function" == typeof transform.transformFunction && (obj[key] = obj[key].map(transform.transformFunction)));
764
663
  }
@@ -791,8 +690,11 @@ var CACError = class extends Error {
791
690
  };
792
691
  if ("u" > typeof process) {
793
692
  let runtimeName;
794
- runtimeName = "u" > typeof Deno && "string" == typeof Deno.version?.deno ? "deno" : "u" > typeof Bun && "string" == typeof Bun.version ? "bun" : "node", runtimeInfo = `${process.platform}-${process.arch} ${runtimeName}-${process.version}`, runtimeProcessArgs = process.argv;
693
+ runtimeName = "u" > typeof Deno && "string" == typeof Deno.version?.deno ? "deno" : "u" > typeof Bun && "string" == typeof Bun.version ? "bun" : "node", runtimeInfo = `${process.platform}-${process.arch} ${runtimeName}-${process.version}`;
795
694
  } else runtimeInfo = "u" < typeof navigator ? "unknown" : `${navigator.platform} ${navigator.userAgent}`;
695
+ function getRuntimeProcessArgs() {
696
+ return "u" < typeof process ? void 0 : process.argv;
697
+ }
796
698
  var Command = class {
797
699
  rawName;
798
700
  description;
@@ -965,6 +867,7 @@ var Command = class {
965
867
  }
966
868
  parse(argv, { run = !0 } = {}) {
967
869
  if (!argv) {
870
+ let runtimeProcessArgs = getRuntimeProcessArgs();
968
871
  if (!runtimeProcessArgs) throw Error("No argv provided and runtime process argv is not available.");
969
872
  argv = runtimeProcessArgs;
970
873
  }
@@ -1038,16 +941,16 @@ var Command = class {
1038
941
  arg.variadic ? actionArgs.push(args.slice(index)) : actionArgs.push(args[index]);
1039
942
  }), actionArgs.push(options), command.commandAction.apply(this, actionArgs);
1040
943
  }
1041
- }, __webpack_modules__ = {}, __webpack_module_cache__ = {};
944
+ }, dist_webpack_modules_ = {}, dist_webpack_module_cache_ = {};
1042
945
  function dist_webpack_require_(moduleId) {
1043
- var cachedModule = __webpack_module_cache__[moduleId];
946
+ var cachedModule = dist_webpack_module_cache_[moduleId];
1044
947
  if (void 0 !== cachedModule) return cachedModule.exports;
1045
- var module = __webpack_module_cache__[moduleId] = {
948
+ var module = dist_webpack_module_cache_[moduleId] = {
1046
949
  exports: {}
1047
950
  };
1048
- return __webpack_modules__[moduleId](module, module.exports, dist_webpack_require_), module.exports;
951
+ return dist_webpack_modules_[moduleId](module, module.exports, dist_webpack_require_), module.exports;
1049
952
  }
1050
- dist_webpack_require_.m = __webpack_modules__, dist_webpack_require_.add = function(modules) {
953
+ dist_webpack_require_.m = dist_webpack_modules_, dist_webpack_require_.add = function(modules) {
1051
954
  Object.assign(dist_webpack_require_.m, modules);
1052
955
  }, dist_webpack_require_.add({
1053
956
  "./node_modules/.pnpm/deepmerge@4.3.1/node_modules/deepmerge/dist/cjs.js" (module) {
@@ -1267,7 +1170,7 @@ dist_webpack_require_.m = __webpack_modules__, dist_webpack_require_.add = funct
1267
1170
  exports.A = void 0;
1268
1171
  let stringify_1 = __webpack_require__("./node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/stringify.js"), quote_1 = __webpack_require__("./node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/quote.js"), ROOT_SENTINEL = Symbol("root");
1269
1172
  function replacerToString(replacer) {
1270
- return replacer ? (value, space, next, key)=>replacer(value, space, (value)=>stringify_1.toString(value, space, next, key), key) : stringify_1.toString;
1173
+ return replacer ? (0, (value, space, next, key)=>replacer(value, space, (value)=>stringify_1.toString(value, space, next, key), key)) : stringify_1.toString;
1271
1174
  }
1272
1175
  exports.A = function stringify(value, replacer, indent, options = {}) {
1273
1176
  let space = "string" == typeof indent ? indent : " ".repeat(indent || 0), path = [], stack = new Set(), tracking = new Map(), unpack = new Map(), valueCount = 0, { maxDepth = 100, references = !1, skipUndefinedProperties = !1, maxValues = 100000 } = options, valueToString = replacerToString(replacer), onNext = (value, key)=>{
@@ -2090,11 +1993,15 @@ class RspackChain extends ChainedMap {
2090
1993
  ]);
2091
1994
  }
2092
1995
  }
2093
- let vendors_require = createRequire(import.meta.url);
2094
- var cjs_0_default = compatGetDefaultExport(rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/deepmerge/4.3.1/56471899410038644780b3527c5076e78d3f57091a0da3ac0daf6d994929353d/node_modules/deepmerge/dist/cjs.js"));
1996
+ let vendors_require = createRequire(import.meta.url), cjs_0 = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/deepmerge/4.3.1/56471899410038644780b3527c5076e78d3f57091a0da3ac0daf6d994929353d/node_modules/deepmerge/dist/cjs.js");
1997
+ var cjs_0_default = compatGetDefaultExport(cjs_0);
2095
1998
  let setNodeEnv = (env)=>{
2096
1999
  process.env.NODE_ENV = env;
2097
- }, isCI = ()=>!!process.env.CI && 'false' !== process.env.CI, isFunction = (func)=>'function' == typeof func, isObject = (obj)=>'[object Object]' === Object.prototype.toString.call(obj), objectPrototype = Object.prototype, helpers_getProto = Object.getPrototypeOf, isPlainObject = (obj)=>null !== obj && 'object' == typeof obj && helpers_getProto(obj) === objectPrototype, helpers_castArray = (arr)=>void 0 === arr ? [] : Array.isArray(arr) ? arr : [
2000
+ }, isCI = ()=>!!process.env.CI && 'false' !== process.env.CI, isFunction = (func)=>'function' == typeof func, isObject = (obj)=>'[object Object]' === Object.prototype.toString.call(obj), objectPrototype = Object.prototype, helpers_getProto = Object.getPrototypeOf, isPlainObject = (obj)=>{
2001
+ if (null === obj || 'object' != typeof obj) return !1;
2002
+ let proto = helpers_getProto(obj);
2003
+ return null === proto || proto === objectPrototype || null === helpers_getProto(proto);
2004
+ }, helpers_castArray = (arr)=>void 0 === arr ? [] : Array.isArray(arr) ? arr : [
2098
2005
  arr
2099
2006
  ], cloneDeep = (value)=>null == value ? value : cjs_0_default()({}, value, {
2100
2007
  isMergeableObject: isPlainObject
@@ -2172,11 +2079,8 @@ function resolveFileName(stats, logger) {
2172
2079
  let file = stats.file || stats.moduleName;
2173
2080
  if (file) return removeLoaderChainDelimiter(file, logger);
2174
2081
  if (stats.moduleIdentifier) {
2175
- let matched = stats.moduleIdentifier.match(/(?:!|^)([^!]+)$/);
2176
- if (matched) {
2177
- let fileName = matched.pop();
2178
- if (fileName) return removeLoaderChainDelimiter(fileName, logger);
2179
- }
2082
+ let fileName = stats.moduleIdentifier.slice(stats.moduleIdentifier.lastIndexOf('!') + 1);
2083
+ if (fileName) return removeLoaderChainDelimiter(fileName, logger);
2180
2084
  }
2181
2085
  return '';
2182
2086
  }
@@ -2188,12 +2092,12 @@ function formatModuleTrace(stats, errorFile, root, level, logger) {
2188
2092
  let formatted = removeLoaderChainDelimiter(errorFile, logger);
2189
2093
  moduleNames[0] !== formatted && moduleNames.unshift(formatted);
2190
2094
  }
2191
- let trace = moduleNames.slice().reverse().map((name)=>formatDiagnosticPath(name, root));
2095
+ let trace = moduleNames.toReversed();
2192
2096
  return trace.length > 4 && !isVerbose(logger) && (trace = [
2193
2097
  ...trace.slice(0, 2),
2194
2098
  `... (${trace.length - 2 - 2} hidden)`,
2195
2099
  ...trace.slice(trace.length - 2)
2196
- ]), color.dim(`Import traces (entry → ${level}):\n ${trace.join('\n ')} ${color.bold(color.red('×'))}`);
2100
+ ]), color.dim(`Import traces (entry → ${level}):\n ${trace.map((name)=>formatDiagnosticPath(name, root)).join('\n ')} ${color.bold(color.red('×'))}`);
2197
2101
  }
2198
2102
  function hintUnknownFiles(message) {
2199
2103
  let hint = 'You may need an appropriate loader to handle this file type.';
@@ -2202,37 +2106,45 @@ function hintUnknownFiles(message) {
2202
2106
  for (let plugin of [
2203
2107
  {
2204
2108
  test: /File: .+\.s(c|a)ss/,
2205
- hint: createPluginHint('sass', 'Sass')
2109
+ name: 'sass',
2110
+ keyword: 'Sass'
2206
2111
  },
2207
2112
  {
2208
2113
  test: /File: .+\.less/,
2209
- hint: createPluginHint('less', 'Less')
2114
+ name: 'less',
2115
+ keyword: 'Less'
2210
2116
  },
2211
2117
  {
2212
2118
  test: /File: .+\.styl(us)?/,
2213
- hint: createPluginHint('stylus', 'Stylus')
2119
+ name: 'stylus',
2120
+ keyword: 'Stylus'
2214
2121
  },
2215
2122
  {
2216
2123
  test: /File: .+\.vue?/,
2217
- hint: createPluginHint('vue', 'Vue')
2124
+ name: 'vue',
2125
+ keyword: 'Vue'
2218
2126
  },
2219
2127
  {
2220
2128
  test: /File: .+\.svelte?/,
2221
- hint: createPluginHint('svelte', 'Svelte')
2129
+ name: 'svelte',
2130
+ keyword: 'Svelte'
2222
2131
  },
2223
2132
  {
2224
2133
  test: /File: .+\.mdx/,
2225
- hint: createPluginHint('mdx', 'MDX')
2134
+ name: 'mdx',
2135
+ keyword: 'MDX'
2226
2136
  },
2227
2137
  {
2228
2138
  test: /File: .+\.toml/,
2229
- hint: createPluginHint('toml', 'TOML')
2139
+ name: 'toml',
2140
+ keyword: 'TOML'
2230
2141
  },
2231
2142
  {
2232
2143
  test: /File: .+\.yaml/,
2233
- hint: createPluginHint('yaml', 'YAML')
2144
+ name: 'yaml',
2145
+ keyword: 'YAML'
2234
2146
  }
2235
- ])if (plugin.test.test(message)) return message.replace(hint, plugin.hint);
2147
+ ])if (plugin.test.test(message)) return message.replace(hint, createPluginHint(plugin.name, plugin.keyword));
2236
2148
  return message;
2237
2149
  }
2238
2150
  function formatStatsError(stats, root, level = 'error', logger) {
@@ -2240,11 +2152,11 @@ function formatStatsError(stats, root, level = 'error', logger) {
2240
2152
  if (!fileName) return '';
2241
2153
  let DATA_URI_PREFIX = "data:text/javascript,";
2242
2154
  if (fileName.startsWith(DATA_URI_PREFIX)) {
2243
- let snippet = fileName.replace(DATA_URI_PREFIX, '');
2155
+ let snippet = fileName.slice(DATA_URI_PREFIX.length);
2244
2156
  return snippet.length > 30 && (snippet = `${snippet.slice(0, 30)}...`), `File: ${color.cyan('data-uri virtual module')} ${color.dim(`(${snippet})`)}\n`;
2245
2157
  }
2246
2158
  let prefix = root + sep;
2247
- 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`;
2159
+ return (fileName = fileName.startsWith(prefix) ? `.${sep}${fileName.slice(prefix.length)}` : 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`;
2248
2160
  })(fileName, stats, root)}${stats.message}`, verbose = isVerbose(logger);
2249
2161
  if (verbose && (stats.details && (message += `\nDetails: ${stats.details}\n`), stats.stack && (message += `\n${stats.stack}`)), 'error' === level || isVerbose(logger)) {
2250
2162
  let moduleTrace = formatModuleTrace(stats, fileName, root, level, logger);
@@ -2271,7 +2183,7 @@ function formatStatsError(stats, root, level = 'error', logger) {
2271
2183
  let matchArray = stripVTControlCharacters(message).match(/Can't resolve '(\w+)'/);
2272
2184
  if (!matchArray) return message;
2273
2185
  let moduleName = matchArray[1];
2274
- return moduleName && builtinModules.includes(moduleName) ? getTips(moduleName) : message;
2186
+ return moduleName && isBuiltin(moduleName) ? getTips(moduleName) : message;
2275
2187
  })(message = hintUnknownFiles(message)))).split('\n');
2276
2188
  return (message = (lines = lines.filter((line, index, arr)=>0 === index || '' !== line.trim() || line.trim() !== arr[index - 1].trim())).join('\n')).trim();
2277
2189
  }
@@ -2311,6 +2223,20 @@ function getRsbuildStats(statsInstance, compiler, logger, action) {
2311
2223
  let statsOptions = getStatsOptions(compiler, logger, action);
2312
2224
  return statsInstance.toJson(statsOptions);
2313
2225
  }
2226
+ function getEarlyStats(stats) {
2227
+ let entrypoints = Object.create(null);
2228
+ for (let [name, entrypoint] of stats.compilation.entrypoints){
2229
+ let chunks = [];
2230
+ for (let { id } of entrypoint.chunks)null != id && chunks.push(id);
2231
+ entrypoints[name] = {
2232
+ chunks
2233
+ };
2234
+ }
2235
+ return {
2236
+ hash: stats.hash ?? void 0,
2237
+ entrypoints
2238
+ };
2239
+ }
2314
2240
  function formatStats(stats, hasErrors, root, logger) {
2315
2241
  if (hasErrors) return {
2316
2242
  message: formatErrorMessage(getStatsErrors(stats).map((item)=>formatStatsError(item, root, 'error', logger))),
@@ -2326,7 +2252,11 @@ function formatStats(stats, hasErrors, root, logger) {
2326
2252
  }
2327
2253
  return {};
2328
2254
  }
2329
- let removeLoaderChainDelimiter = (moduleId, logger)=>isVerbose(logger) ? moduleId : moduleId.split('!=!')[0];
2255
+ let removeLoaderChainDelimiter = (moduleId, logger)=>{
2256
+ if (isVerbose(logger)) return moduleId;
2257
+ let index = moduleId.indexOf('!=!');
2258
+ return -1 === index ? moduleId : moduleId.slice(0, index);
2259
+ };
2330
2260
  function createEnvironmentAsyncHook() {
2331
2261
  let preGroup = [], postGroup = [], defaultGroup = [], tapEnvironment = ({ environment, handler: cb })=>{
2332
2262
  isFunction(cb) ? defaultGroup.push({
@@ -2425,6 +2355,7 @@ function initHooks() {
2425
2355
  onBeforeDevCompile: createAsyncHook(),
2426
2356
  onAfterDevCompile: createAsyncHook(),
2427
2357
  onCloseDevServer: createAsyncHook(),
2358
+ onClosePreviewServer: createAsyncHook(),
2428
2359
  onAfterStartDevServer: createAsyncHook(),
2429
2360
  onBeforeStartDevServer: createAsyncHook(),
2430
2361
  onAfterStartPreviewServer: createAsyncHook(),
@@ -2461,19 +2392,20 @@ let onBeforeCompile = ({ compiler, beforeCompile, beforeEnvironmentCompile, isWa
2461
2392
  if (compiler_isMultiCompiler(compiler)) {
2462
2393
  let { compilers } = compiler, compilerStats = [], doneCompilers = 0;
2463
2394
  for(let index = 0; index < compilers.length; index++){
2464
- let compiler = compilers[index], compilerIndex = index, compilerDone = !1;
2395
+ let compiler = compilers[index], compilerDone = !1, generation = 0, compilationGeneration = 0;
2465
2396
  compiler.hooks.done.tapPromise('rsbuild:done', async (stats)=>{
2466
- !compilerDone && (compilerDone = !0, doneCompilers++), compilerStats[compilerIndex] = stats;
2467
- let lastCompilerDone = doneCompilers === compilers.length;
2468
- await onEnvironmentDone(index, stats), lastCompilerDone && await onDone(new MultiStatsCtor(compilerStats));
2397
+ let currentGeneration = compilationGeneration;
2398
+ await onEnvironmentDone(index, stats), currentGeneration === generation && (!compilerDone && (compilerDone = !0, doneCompilers++), compilerStats[index] = stats, doneCompilers === compilers.length && await onDone(new MultiStatsCtor(compilerStats)));
2469
2399
  });
2470
2400
  let resetDoneState = ()=>{
2471
- compilerDone && (compilerDone = !1, doneCompilers--);
2401
+ generation++, compilerDone && (compilerDone = !1, doneCompilers--);
2472
2402
  };
2473
2403
  compiler.hooks.invalid.tap('rsbuild:done', resetDoneState), compiler.hooks.watchRun.tap({
2474
2404
  name: 'rsbuild:done',
2475
2405
  stage: -1 / 0
2476
- }, resetDoneState);
2406
+ }, ()=>{
2407
+ resetDoneState(), compilationGeneration = generation;
2408
+ });
2477
2409
  }
2478
2410
  } else compiler.hooks.done.tapPromise('rsbuild:done', async (stats)=>{
2479
2411
  await onEnvironmentDone(0, stats), await onDone(stats);
@@ -2495,8 +2427,14 @@ class BrowserslistError extends Error {
2495
2427
  let isFileCache = {};
2496
2428
  function isFile(file) {
2497
2429
  if (file in isFileCache) return isFileCache[file];
2498
- let result = node_fs.existsSync(file) && node_fs.statSync(file).isFile();
2499
- return isFileCache[file] = result, result;
2430
+ try {
2431
+ let result = node_fs.existsSync(file) && node_fs.statSync(file).isFile();
2432
+ return isFileCache[file] = result, result;
2433
+ } catch (error) {
2434
+ let { code } = error;
2435
+ if ('ENOENT' === code || 'EACCES' === code || 'ERR_ACCESS_DENIED' === code) return !1;
2436
+ throw error;
2437
+ }
2500
2438
  }
2501
2439
  function dist_check(section) {
2502
2440
  let FORMAT = 'Browserslist config should be a string or an array of strings with browser queries';
@@ -2510,7 +2448,7 @@ function parsePackage(file) {
2510
2448
  let list = config.browserslist;
2511
2449
  for(let i in Array.isArray(list) && (list = {
2512
2450
  defaults: list
2513
- }), 'string' == typeof list && (list = parseConfig(list)), list)dist_check(list[i]);
2451
+ }), 'string' == typeof list && (list = parseConfig(list)), list)dist_check(list[i]), 'string' == typeof list[i] && (list[i] = parseConfig(list[i]).defaults);
2514
2452
  return list;
2515
2453
  }
2516
2454
  let IS_SECTION = /^\s*\[(.+)]\s*$/;
@@ -2604,7 +2542,7 @@ async function pathExists(path) {
2604
2542
  async function isFileExists(file) {
2605
2543
  return node_fs.promises.access(file, node_fs.constants.F_OK).then(()=>!0).catch(()=>!1);
2606
2544
  }
2607
- async function fileExistsByCompilation({ inputFileSystem }, filePath) {
2545
+ function fileExistsByCompilation({ inputFileSystem }, filePath) {
2608
2546
  return new Promise((resolve)=>{
2609
2547
  inputFileSystem ? inputFileSystem.stat(filePath, (err, stats)=>{
2610
2548
  err ? resolve(!1) : resolve(!!stats?.isFile());
@@ -2659,11 +2597,12 @@ let OVERRIDE_PATHS = new Set([
2659
2597
  'customLogger'
2660
2598
  ]), merge = (x, y, path = '')=>{
2661
2599
  if (((key)=>{
2600
+ let realKey = key;
2662
2601
  if (key.startsWith('environments.')) {
2663
- let realKey = key.split('.').slice(2).join('.');
2664
- return OVERRIDE_PATHS.has(realKey);
2602
+ let index = key.indexOf('.', 13);
2603
+ realKey = -1 === index ? '' : key.slice(index + 1);
2665
2604
  }
2666
- return OVERRIDE_PATHS.has(key) || key.startsWith('output.filename.');
2605
+ return OVERRIDE_PATHS.has(realKey) || realKey.startsWith('output.filename.');
2667
2606
  })(path)) return y ?? x;
2668
2607
  if (void 0 === x) return isPlainObject(y) ? cloneDeep(y) : y;
2669
2608
  if (void 0 === y) return isPlainObject(x) ? cloneDeep(x) : x;
@@ -2684,14 +2623,22 @@ let OVERRIDE_PATHS = new Set([
2684
2623
  y
2685
2624
  ];
2686
2625
  if (!isPlainObject(x) || !isPlainObject(y)) return y;
2687
- let merged = {};
2688
- for (let key of new Set([
2689
- ...Object.keys(x),
2690
- ...Object.keys(y)
2691
- ])){
2626
+ let merged = {}, xKeys = Object.keys(x), yKeys = Object.keys(y), xKeySet = xKeys.length > 8 && yKeys.length > 8 ? new Set(xKeys) : void 0;
2627
+ for (let key of xKeys){
2692
2628
  let childPath = path ? `${path}.${key}` : key;
2693
2629
  merged[key] = merge(x[key], y[key], childPath);
2694
2630
  }
2631
+ for (let key of yKeys)if (!(xKeySet ? xKeySet.has(key) : xKeys.includes(key))) {
2632
+ let childPath = path ? `${path}.${key}` : key;
2633
+ merged[key] = merge(x[key], y[key], childPath);
2634
+ }
2635
+ for (let source of [
2636
+ x,
2637
+ y
2638
+ ])for (let key of Object.getOwnPropertySymbols(source))if (Object.prototype.propertyIsEnumerable.call(source, key)) {
2639
+ let value = source[key];
2640
+ void 0 !== value && (merged[key] = value);
2641
+ }
2695
2642
  return merged;
2696
2643
  }, normalizeConfigStructure = (config)=>{
2697
2644
  let { dev, output } = config, normalizedConfig = {
@@ -2864,16 +2811,28 @@ function getDefaultEntry(root) {
2864
2811
  index: entryFile
2865
2812
  } : {};
2866
2813
  }
2867
- let withDefaultConfig = async (rootPath, userConfig)=>{
2868
- let config = mergeRsbuildConfig(createDefaultConfig(), userConfig);
2869
- if (config.root ||= rootPath, config.source ||= {}, config.server?.base && (userConfig.dev?.assetPrefix === void 0 && (config.dev ||= {}, config.dev.assetPrefix = config.server.base), userConfig.output?.assetPrefix === void 0 && (config.output ||= {}, config.output.assetPrefix = config.server.base)), userConfig.dev?.client?.logLevel === void 0 && (config.dev ||= {}, config.dev.client ||= {}, config.dev.client.logLevel = config.logLevel), config.dev?.lazyCompilation === void 0 && (config.dev ||= {}, config.dev.lazyCompilation = {
2870
- imports: !0,
2871
- entries: !1
2872
- }), !config.source.tsconfigPath) {
2873
- let tsconfigPath = join(rootPath, TS_CONFIG_FILE);
2874
- await isFileExists(tsconfigPath) && (config.source.tsconfigPath = tsconfigPath);
2875
- }
2876
- return config;
2814
+ let normalizePublicDirs = (rootPath, publicDir)=>{
2815
+ if (!1 === publicDir) return [];
2816
+ let defaultConfig = {
2817
+ name: join(rootPath, 'public'),
2818
+ copyOnBuild: 'auto',
2819
+ watch: !1,
2820
+ ignore: []
2821
+ };
2822
+ if (void 0 === publicDir) return [
2823
+ defaultConfig
2824
+ ];
2825
+ let mergeWithDefault = (options)=>{
2826
+ if ('' === options.name) throw Error('[rsbuild:config] `publicDir.name` cannot be empty string.');
2827
+ let merged = {
2828
+ ...defaultConfig,
2829
+ ...options
2830
+ };
2831
+ return external_node_path_isAbsolute(merged.name) || (merged.name = join(rootPath, merged.name)), merged;
2832
+ };
2833
+ return Array.isArray(publicDir) ? publicDir.map((options)=>mergeWithDefault(options)) : [
2834
+ mergeWithDefault(publicDir)
2835
+ ];
2877
2836
  }, restartPorts = new WeakMap(), exitHook_callbacks = new Set(), isCalled = !1, isRegistered = !1;
2878
2837
  function exit(exitCode, type) {
2879
2838
  if (!isCalled) {
@@ -2929,7 +2888,11 @@ let isEnvironmentMatch = (pluginEnvironment, specifiedEnvironment)=>pluginEnviro
2929
2888
  function createPluginManager(logger) {
2930
2889
  let plugins = [];
2931
2890
  return {
2932
- getPlugins: (options = {})=>plugins.filter((plugin)=>isEnvironmentMatch(plugin.environment, options.environment)).map(({ instance })=>instance),
2891
+ getPlugins: (options = {})=>{
2892
+ let result = [];
2893
+ for (let plugin of plugins)isEnvironmentMatch(plugin.environment, options.environment) && result.push(plugin.instance);
2894
+ return result;
2895
+ },
2933
2896
  getAllPluginsWithMeta: ()=>plugins,
2934
2897
  addPlugins: (newPlugins, options)=>{
2935
2898
  let { before, environment } = options || {};
@@ -2958,11 +2921,6 @@ async function initPlugins({ context, pluginManager }) {
2958
2921
  let plugins = pluginManager.getAllPluginsWithMeta();
2959
2922
  plugins = ((plugins)=>{
2960
2923
  let allLines = [], pluginNames = new Set(plugins.map((item)=>item.instance.name));
2961
- function getPlugin(name) {
2962
- let targets = plugins.filter((item)=>item.instance.name === name);
2963
- if (!targets.length) throw Error(`${color.dim('[rsbuild:plugin]')} Plugin "${color.yellow(name)}" not existed`);
2964
- return targets;
2965
- }
2966
2924
  for (let plugin of plugins){
2967
2925
  if (plugin.instance.pre) for (let pre of plugin.instance.pre)pre && pluginNames.has(pre) && allLines.push([
2968
2926
  pre,
@@ -2973,10 +2931,23 @@ async function initPlugins({ context, pluginManager }) {
2973
2931
  post
2974
2932
  ]);
2975
2933
  }
2976
- let endPoints = new Set(allLines.map((line)=>line[1])), zeroEndPoints = plugins.filter((item)=>!endPoints.has(item.instance.name)), sortedPoint = [], sortedPluginNames = new Set();
2977
- for(; zeroEndPoints.length;){
2978
- let { name } = zeroEndPoints[0].instance, pluginInstances = getPlugin(name);
2979
- sortedPoint.push(...pluginInstances), sortedPluginNames.add(name), endPoints = new Set((allLines = allLines.filter((line)=>line[0] !== name)).map((line)=>line[1])), zeroEndPoints = plugins.filter((item)=>!sortedPluginNames.has(item.instance.name) && !endPoints.has(item.instance.name));
2934
+ if (0 === allLines.length && pluginNames.size === plugins.length) return plugins.slice();
2935
+ let pluginsByName = new Map();
2936
+ for (let plugin of plugins){
2937
+ let { name } = plugin.instance, group = pluginsByName.get(name);
2938
+ group ? group.push(plugin) : pluginsByName.set(name, [
2939
+ plugin
2940
+ ]);
2941
+ }
2942
+ function getPlugin(name) {
2943
+ let targets = pluginsByName.get(name) ?? [];
2944
+ if (!targets.length) throw Error(`${color.dim('[rsbuild:plugin]')} Plugin "${color.yellow(name)}" not existed`);
2945
+ return targets;
2946
+ }
2947
+ let endPoints = new Set(allLines.map((line)=>line[1])), zeroEndPoint = plugins.find((item)=>!endPoints.has(item.instance.name)), sortedPoint = [], sortedPluginNames = new Set();
2948
+ for(; zeroEndPoint;){
2949
+ let { name } = zeroEndPoint.instance, pluginInstances = getPlugin(name);
2950
+ sortedPoint.push(...pluginInstances), sortedPluginNames.add(name), endPoints = new Set((allLines = allLines.filter((line)=>line[0] !== name)).map((line)=>line[1])), zeroEndPoint = plugins.find((item)=>!sortedPluginNames.has(item.instance.name) && !endPoints.has(item.instance.name));
2980
2951
  }
2981
2952
  if (allLines.length) {
2982
2953
  let restInRingPoints = {};
@@ -3089,7 +3060,7 @@ function initPluginAPI({ context, pluginManager }) {
3089
3060
  }, GLOBAL_EXPOSED_KEY = Symbol('global-exposed'), exposed = new Map(), expose = (id, api, options)=>{
3090
3061
  let exposedAPIs = exposed.get(id) ?? new Map(), key = options?.environment ?? GLOBAL_EXPOSED_KEY;
3091
3062
  exposedAPIs.set(key, api), exposed.set(id, exposedAPIs);
3092
- }, transformId = 0, transformer = {}, processAssetsFns = [], resolveFns = [];
3063
+ }, transformId = 0, transformer = {}, preTransformIds = new Set(), processAssetsFns = [], resolveFns = [];
3093
3064
  hooks.modifyBundlerChain.tap((chain, { target, environment })=>{
3094
3065
  let pluginName = 'RsbuildCorePlugin';
3095
3066
  chain.plugin(pluginName).use(class {
@@ -3133,39 +3104,43 @@ function initPluginAPI({ context, pluginManager }) {
3133
3104
  context: publicContext,
3134
3105
  expose,
3135
3106
  logger: context.logger,
3136
- transform: (descriptor, handler)=>{
3107
+ transform: (0, (descriptor, handler)=>{
3137
3108
  let id = `rsbuild-transform-${transformId++}`;
3138
- transformer[id] = handler, hooks.modifyBundlerChain.tapEnvironment({
3109
+ transformer[id] = handler, void 0 !== descriptor.as && 'pre' === descriptor.order && preTransformIds.add(id), hooks.modifyBundlerChain.tapEnvironment({
3139
3110
  environment: environment,
3140
3111
  handler: (chain, { target, environment: environmentContext })=>{
3141
3112
  if (descriptor.targets && !descriptor.targets.includes(target) || descriptor.environments && !descriptor.environments.includes(environmentContext.name)) return;
3142
3113
  let rule = chain.module.rule(id);
3143
- descriptor.test && rule.test(descriptor.test), descriptor.resourceQuery && rule.resourceQuery(descriptor.resourceQuery), descriptor.layer && rule.layer(descriptor.layer), descriptor.issuerLayer && rule.issuerLayer(descriptor.issuerLayer), descriptor.issuer && rule.issuer(descriptor.issuer), descriptor.with && rule.with(descriptor.with), descriptor.mimetype && rule.mimetype(descriptor.mimetype), descriptor.order && 'default' !== descriptor.order ? rule.enforce(descriptor.order) : descriptor.enforce && rule.enforce(descriptor.enforce);
3144
- let loaderPath = join(LOADER_PATH, descriptor.raw ? 'transformRawLoader.mjs' : 'transformLoader.mjs');
3145
- rule.use(id).loader(loaderPath).options({
3114
+ if (preTransformIds.has(id)) {
3115
+ let firstRuleName = chain.module.rules.order().order.find((name)=>!preTransformIds.has(name));
3116
+ firstRuleName && rule.before(firstRuleName);
3117
+ }
3118
+ void 0 !== descriptor.as && rule.set('as', descriptor.as), descriptor.test && rule.test(descriptor.test), descriptor.resourceQuery && rule.resourceQuery(descriptor.resourceQuery), descriptor.layer && rule.layer(descriptor.layer), descriptor.issuerLayer && rule.issuerLayer(descriptor.issuerLayer), descriptor.issuer && rule.issuer(descriptor.issuer), descriptor.with && rule.with(descriptor.with), descriptor.mimetype && rule.mimetype(descriptor.mimetype), descriptor.order && 'default' !== descriptor.order ? rule.enforce(descriptor.order) : descriptor.enforce && rule.enforce(descriptor.enforce);
3119
+ let loaderName = descriptor.raw ? 'transformRawLoader.mjs' : 'transformLoader.mjs', loaderPath = join(LOADER_PATH, loaderName), use = rule.use(id).loader(loaderPath).options({
3146
3120
  id,
3147
3121
  getEnvironment: ()=>environmentContext
3148
3122
  });
3123
+ void 0 !== descriptor.codeFilter && use.set('codeFilter', descriptor.codeFilter);
3149
3124
  }
3150
3125
  });
3151
- },
3152
- useExposed: (id)=>{
3126
+ }),
3127
+ useExposed: (0, (id)=>{
3153
3128
  let exposedAPIs = exposed.get(id);
3154
3129
  if (exposedAPIs) return void 0 !== environment && exposedAPIs.has(environment) ? exposedAPIs.get(environment) : exposedAPIs.get(GLOBAL_EXPOSED_KEY);
3155
- },
3156
- processAssets: (descriptor, handler)=>{
3130
+ }),
3131
+ processAssets: (0, (descriptor, handler)=>{
3157
3132
  processAssetsFns.push({
3158
3133
  environment: environment,
3159
3134
  descriptor,
3160
3135
  handler
3161
3136
  });
3162
- },
3163
- resolve: (handler)=>{
3137
+ }),
3138
+ resolve: (0, (handler)=>{
3164
3139
  resolveFns.push({
3165
3140
  environment: environment,
3166
3141
  handler
3167
3142
  });
3168
- },
3143
+ }),
3169
3144
  getRsbuildConfig,
3170
3145
  getNormalizedConfig,
3171
3146
  isPluginExists: pluginManager.isPluginExists,
@@ -3175,6 +3150,7 @@ function initPluginAPI({ context, pluginManager }) {
3175
3150
  onCloseBuild: hooks.onCloseBuild.tap,
3176
3151
  onBeforeBuild: hooks.onBeforeBuild.tap,
3177
3152
  onCloseDevServer: hooks.onCloseDevServer.tap,
3153
+ onClosePreviewServer: hooks.onClosePreviewServer.tap,
3178
3154
  onBeforeDevCompile: hooks.onBeforeDevCompile.tap,
3179
3155
  onAfterDevCompile: hooks.onAfterDevCompile.tap,
3180
3156
  onDevCompileDone: hooks.onAfterDevCompile.tap,
@@ -3230,7 +3206,8 @@ function initPluginAPI({ context, pluginManager }) {
3230
3206
  });
3231
3207
  }
3232
3208
  function getAbsoluteDistPath(cwd, config) {
3233
- return ensureAbsolutePath(cwd, config.output?.distPath?.root ?? "dist");
3209
+ let dirRoot = config.output?.distPath?.root ?? "dist";
3210
+ return ensureAbsolutePath(cwd, dirRoot);
3234
3211
  }
3235
3212
  let browsersListCache = new Map();
3236
3213
  function getBrowserslist(path) {
@@ -3301,9 +3278,19 @@ function createPublicContext(context) {
3301
3278
  });
3302
3279
  }
3303
3280
  async function createContext(options, userConfig, logger, loadConfigResult) {
3304
- 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();
3281
+ let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await (async (rootPath, userConfig)=>{
3282
+ let config = mergeRsbuildConfig(createDefaultConfig(), userConfig);
3283
+ if (config.root ||= rootPath, config.source ||= {}, config.server?.base && (userConfig.dev?.assetPrefix === void 0 && (config.dev ||= {}, config.dev.assetPrefix = config.server.base), userConfig.output?.assetPrefix === void 0 && (config.output ||= {}, config.output.assetPrefix = config.server.base)), userConfig.dev?.client?.logLevel === void 0 && (config.dev ||= {}, config.dev.client ||= {}, config.dev.client.logLevel = config.logLevel), config.dev?.lazyCompilation === void 0 && (config.dev ||= {}, config.dev.lazyCompilation = {
3284
+ imports: !0,
3285
+ entries: !1
3286
+ }), !config.source.tsconfigPath) {
3287
+ let tsconfigPath = join(rootPath, TS_CONFIG_FILE);
3288
+ await isFileExists(tsconfigPath) && (config.source.tsconfigPath = tsconfigPath);
3289
+ }
3290
+ return config;
3291
+ })(rootPath, userConfig), cachePath = join(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0, hooks = initHooks();
3305
3292
  return {
3306
- version: "2.2.13",
3293
+ version: "2.3.3",
3307
3294
  rootPath,
3308
3295
  configFile: loadConfigResult?.filePath ?? userConfig._privateMeta?.configFilePath,
3309
3296
  configFileDependencies: loadConfigResult?.dependencies ?? userConfig._privateMeta?.configFileDependencies ?? [],
@@ -3391,7 +3378,7 @@ async function emitConfigFiles({ bundlerConfigs, environmentConfigs, extraConfig
3391
3378
  };
3392
3379
  }),
3393
3380
  ...bundlerConfigs.map(({ name, content })=>{
3394
- let outputFilePath = join(outputPath, `rspack.config.${name}.mjs`);
3381
+ let outputFile = `rspack.config.${name}.mjs`, outputFilePath = join(outputPath, outputFile);
3395
3382
  return node_fs.existsSync(outputFilePath) && (outputFilePath = outputFilePath.replace(/\.mjs$/, `.${Date.now()}.mjs`)), {
3396
3383
  path: outputFilePath,
3397
3384
  label: `Rspack Config (${name})`,
@@ -3736,11 +3723,12 @@ function getConfigUtils(getCurrentConfig, chainUtils) {
3736
3723
  };
3737
3724
  }
3738
3725
  function getChainUtils(target, environment, environments) {
3726
+ let nodeEnv = process.env.NODE_ENV || '';
3739
3727
  return {
3740
3728
  rspack: core_rspack,
3741
3729
  environment,
3742
3730
  environments,
3743
- env: process.env.NODE_ENV || '',
3731
+ env: nodeEnv,
3744
3732
  target,
3745
3733
  isDev: 'development' === environment.config.mode,
3746
3734
  isProd: 'production' === environment.config.mode,
@@ -3809,29 +3797,7 @@ async function initRsbuildConfig({ context, pluginManager }) {
3809
3797
  context,
3810
3798
  pluginManager
3811
3799
  }), await modifyRsbuildConfig(context);
3812
- let normalizedBaseConfig = (config = context.config, rootPath = context.rootPath, config.server ||= {}, config.server.host = 'string' == typeof (host = config.server.host) ? host : !0 === host ? ALL_INTERFACES_IPV4 : LOCALHOST, config.server.publicDir = ((rootPath, publicDir)=>{
3813
- if (!1 === publicDir) return [];
3814
- let defaultConfig = {
3815
- name: join(rootPath, 'public'),
3816
- copyOnBuild: 'auto',
3817
- watch: !1,
3818
- ignore: []
3819
- };
3820
- if (void 0 === publicDir) return [
3821
- defaultConfig
3822
- ];
3823
- let mergeWithDefault = (options)=>{
3824
- if ('' === options.name) throw Error('[rsbuild:config] `publicDir.name` cannot be empty string.');
3825
- let merged = {
3826
- ...defaultConfig,
3827
- ...options
3828
- };
3829
- return external_node_path_isAbsolute(merged.name) || (merged.name = join(rootPath, merged.name)), merged;
3830
- };
3831
- return Array.isArray(publicDir) ? publicDir.map((options)=>mergeWithDefault(options)) : [
3832
- mergeWithDefault(publicDir)
3833
- ];
3834
- })(rootPath, config.server.publicDir), (defaultConfig = createDefaultConfig()).mode = (()=>{
3800
+ let normalizedBaseConfig = (config = context.config, rootPath = context.rootPath, config.server ||= {}, config.server.host = 'string' == typeof (host = config.server.host) ? host : !0 === host ? ALL_INTERFACES_IPV4 : LOCALHOST, config.server.publicDir = normalizePublicDirs(rootPath, config.server.publicDir), (defaultConfig = createDefaultConfig()).mode = (()=>{
3835
3801
  if (config.mode) return config.mode;
3836
3802
  let nodeEnv = process.env.NODE_ENV || '';
3837
3803
  return 'production' === nodeEnv || 'development' === nodeEnv ? nodeEnv : 'none';
@@ -3859,13 +3825,19 @@ async function initRsbuildConfig({ context, pluginManager }) {
3859
3825
  };
3860
3826
  })(normalizedBaseConfig, context.rootPath, context.specifiedEnvironments), tsconfigPaths = new Set();
3861
3827
  for (let [name, config] of Object.entries(mergedEnvironments)){
3862
- let environmentConfig = await modifyEnvironmentConfig(context, config, name), normalizedEnvironmentConfig = {
3828
+ let environmentConfig = await modifyEnvironmentConfig(context, config, name), publicDir = environmentConfig.server?.publicDir, normalizedEnvironmentConfig = {
3863
3829
  ...environmentConfig,
3864
3830
  dev: {
3865
3831
  ...normalizedBaseConfig.dev,
3866
3832
  ...environmentConfig.dev
3867
3833
  },
3868
- server: normalizedBaseConfig.server
3834
+ server: {
3835
+ ...normalizedBaseConfig.server,
3836
+ ...pick(environmentConfig.server ?? {}, [
3837
+ 'serveAssets'
3838
+ ]),
3839
+ publicDir: void 0 === publicDir ? normalizedBaseConfig.server.publicDir : normalizePublicDirs(context.rootPath, publicDir)
3840
+ }
3869
3841
  }, { tsconfigPath } = normalizedEnvironmentConfig.source;
3870
3842
  if (tsconfigPath) {
3871
3843
  let absoluteTsconfigPath = ensureAbsolutePath(context.rootPath, tsconfigPath);
@@ -3932,14 +3904,14 @@ function cutPath(originalFilePath, root) {
3932
3904
  return parts.length > 3 ? parts.slice(-3).join(sep) : parts.join(sep);
3933
3905
  }
3934
3906
  function isLikelyFile(filePath) {
3935
- return (filePath.split(sep).pop() || '').includes('.');
3907
+ return filePath.slice(filePath.lastIndexOf(sep) + 1).includes('.');
3936
3908
  }
3937
3909
  function formatFileList(paths, rootPath) {
3938
3910
  let files = paths.filter(isLikelyFile);
3939
3911
  0 === files.length && paths.length > 0 && (files = [
3940
3912
  paths[0]
3941
3913
  ]);
3942
- let fileInfo = files.slice(0, 1).map((file)=>cutPath(file, rootPath)).join(', ');
3914
+ let fileInfo = files.length ? cutPath(files[0], rootPath) : '';
3943
3915
  return files.length > 1 ? `${fileInfo} and ${files.length - 1} more` : fileInfo;
3944
3916
  }
3945
3917
  function printBuildLog(compiler, context, lazyModules) {
@@ -3965,9 +3937,9 @@ async function createCompiler_createCompiler(options) {
3965
3937
  bundlerConfigs: rspackConfigs,
3966
3938
  environments: context.environments
3967
3939
  }), (version = core_rspack.rspackVersion).includes('-canary') && (version = version.split('-canary')[0]), !(!(version && /^[\d.]+$/.test(version)) || ((version1, version2)=>{
3968
- let parts1 = version1.split('.').map(Number), parts2 = version2.split('.').map(Number), len = Math.max(parts1.length, parts2.length);
3940
+ let parts1 = version1.split('.'), parts2 = version2.split('.'), len = Math.max(parts1.length, parts2.length);
3969
3941
  for(let i = 0; i < len; i++){
3970
- let item1 = parts1[i] ?? 0, item2 = parts2[i] ?? 0;
3942
+ let item1 = Number(parts1[i] ?? 0), item2 = Number(parts2[i] ?? 0);
3971
3943
  if (item1 > item2) return 1;
3972
3944
  if (item1 < item2) return -1;
3973
3945
  }
@@ -4044,31 +4016,10 @@ async function createCompiler_createCompiler(options) {
4044
4016
  let { message, level } = formatStats(stats, hasErrors, options.context.rootPath, logger);
4045
4017
  'error' === level && logger.error(message), 'warning' === level && logger.warn(message), isMultiCompiler || printTime(0, hasErrors), isCompiling = !1;
4046
4018
  }), 'dev' === context.action && (({ context, compiler, bundlerConfigs, MultiStatsCtor })=>{
4047
- let isFirstCompile = !0, { environmentList } = context, onDone = async (stats)=>{
4048
- let promise = context.hooks.onAfterDevCompile.callBatch({
4049
- isFirstCompile,
4050
- stats,
4051
- environments: context.environments
4052
- });
4053
- isFirstCompile = !1, await promise;
4054
- }, onEnvironmentDone = async (index, stats)=>{
4055
- let environment = environmentList[index], time = context.buildState.time[environment.name] ?? 0;
4056
- await context.hooks.onAfterEnvironmentCompile.callBatch({
4057
- environment: environment.name,
4058
- args: [
4059
- {
4060
- isFirstCompile,
4061
- stats,
4062
- environment,
4063
- isWatch: !0,
4064
- time
4065
- }
4066
- ]
4067
- });
4068
- };
4019
+ let isFirstCompile = !0, { environmentList } = context;
4069
4020
  onBeforeCompile({
4070
4021
  compiler,
4071
- beforeEnvironmentCompile: async (buildIndex)=>{
4022
+ beforeEnvironmentCompile: (buildIndex)=>{
4072
4023
  let environment = environmentList[buildIndex];
4073
4024
  return context.hooks.onBeforeEnvironmentCompile.callBatch({
4074
4025
  environment: environment.name,
@@ -4082,7 +4033,7 @@ async function createCompiler_createCompiler(options) {
4082
4033
  ]
4083
4034
  });
4084
4035
  },
4085
- beforeCompile: async ()=>context.hooks.onBeforeDevCompile.callBatch({
4036
+ beforeCompile: ()=>context.hooks.onBeforeDevCompile.callBatch({
4086
4037
  bundlerConfigs,
4087
4038
  environments: context.environments,
4088
4039
  isFirstCompile,
@@ -4091,8 +4042,29 @@ async function createCompiler_createCompiler(options) {
4091
4042
  isWatch: !0
4092
4043
  }), onCompileDone({
4093
4044
  compiler,
4094
- onDone,
4095
- onEnvironmentDone,
4045
+ onDone: async (stats)=>{
4046
+ let promise = context.hooks.onAfterDevCompile.callBatch({
4047
+ isFirstCompile,
4048
+ stats,
4049
+ environments: context.environments
4050
+ });
4051
+ isFirstCompile = !1, await promise;
4052
+ },
4053
+ onEnvironmentDone: async (index, stats)=>{
4054
+ let environment = environmentList[index], time = context.buildState.time[environment.name] ?? 0;
4055
+ await context.hooks.onAfterEnvironmentCompile.callBatch({
4056
+ environment: environment.name,
4057
+ args: [
4058
+ {
4059
+ isFirstCompile,
4060
+ stats,
4061
+ environment,
4062
+ isWatch: !0,
4063
+ time
4064
+ }
4065
+ ]
4066
+ });
4067
+ },
4096
4068
  MultiStatsCtor
4097
4069
  });
4098
4070
  })({
@@ -4108,70 +4080,277 @@ async function createCompiler_createCompiler(options) {
4108
4080
  rspackConfigs
4109
4081
  };
4110
4082
  }
4111
- let getChokidar = cachedImport_cachedImport(()=>import("./chokidar.js").then((m)=>m.chokidar_namespaceObject)), DEFAULT_WATCH_FILE_EVENTS = [
4112
- 'add',
4113
- 'change',
4114
- 'unlink'
4115
- ];
4116
- async function setupWatchFiles(options) {
4117
- let { config, root, buildManager } = options, { hmr, liveReload } = config.dev;
4118
- if (!hmr && !liveReload || !buildManager) return;
4119
- let closeDevFilesWatcher = await watchDevFiles(config.dev, buildManager, root), serverFilesWatcher = await watchServerFiles(config.server, buildManager, root);
4120
- return {
4121
- async close () {
4122
- await Promise.all([
4123
- closeDevFilesWatcher?.(),
4124
- serverFilesWatcher?.close()
4125
- ]);
4083
+ let normalizeUrl = (url)=>url.replace(/([^:]\/)\/+/g, '$1'), formatPrefix = (input)=>{
4084
+ let prefix = input;
4085
+ if (prefix?.startsWith('./') && (prefix = prefix.replace('./', '')), !prefix) return '/';
4086
+ let hasLeadingSlash = prefix.startsWith('/'), hasTailSlash = prefix.endsWith('/');
4087
+ return `${hasLeadingSlash ? '' : '/'}${prefix}${hasTailSlash ? '' : '/'}`;
4088
+ }, joinUrlPath = (basePath, pathname)=>'' === basePath ? pathname : '' === pathname ? basePath : addTrailingSlash(basePath) + pathname.replace(/^\/+/, ''), getMoreEntriesMessage = (moreEntries, cliShortcutsEnabled)=>cliShortcutsEnabled ? ` ${color.dim(`... ${moreEntries} more entries, press `)}${color.bold('u + enter')}${color.dim(' to show all')}\n` : ` ${color.dim(`... ${moreEntries} more entries, set `)}${color.bold('server.printUrls.maxRoutes')}${color.dim(' to show more')}\n`, isUrlPathUnderBase = (pathname, base)=>{
4089
+ let basePath = removeTailingSlash(base);
4090
+ return '' === basePath || pathname === basePath || pathname.startsWith(`${basePath}/`);
4091
+ }, removeBasePath = (url, base)=>{
4092
+ let basePath = removeTailingSlash(base);
4093
+ if ('' === basePath || !url.startsWith(basePath)) return url;
4094
+ let nextChar = url[basePath.length];
4095
+ return void 0 === nextChar ? '/' : '/' === nextChar ? url.slice(basePath.length) : '?' === nextChar || '#' === nextChar ? `/${url.slice(basePath.length)}` : url;
4096
+ }, isServingAssets = (config)=>config.server.serveAssets ?? isWebTarget(config.output.target), getRoutes = (context)=>{
4097
+ let environmentWithHtml = context.environmentList.filter((item)=>isServingAssets(item.config) && Object.keys(item.htmlPaths).length > 0);
4098
+ if (0 === environmentWithHtml.length) return [];
4099
+ let commonDistPath = getCommonParentPath(environmentWithHtml.map((item)=>item.distPath));
4100
+ return environmentWithHtml.reduce((prev, environmentContext)=>{
4101
+ let { distPath, config } = environmentContext, distPrefix = relative(commonDistPath, distPath).split(sep).join('/'), routes = formatRoutes(environmentContext.htmlPaths, context.normalizedConfig.server.base, posix.join(distPrefix, config.output.distPath.html), config.html.outputStructure);
4102
+ return prev.concat(routes);
4103
+ }, []);
4104
+ }, formatRoutes = (entry, base, distPathPrefix, outputStructure)=>{
4105
+ let prefix = joinUrlPath(base, formatPrefix(distPathPrefix)), entryNames = Object.keys(entry), index = entryNames.indexOf('index');
4106
+ return index > 0 && (entryNames.splice(index, 1), entryNames.unshift('index')), entryNames.map((entryName)=>({
4107
+ entryName,
4108
+ pathname: prefix + ('index' === entryName && 'nested' !== outputStructure ? '' : entryName)
4109
+ }));
4110
+ }, formatName = (name)=>name ? `(${name.length > 20 ? `${name.slice(0, 19)}…` : name})` : name;
4111
+ function getURLMessages(urls, routes, { maxRoutes = 10, showAllRoutes, cliShortcutsEnabled }) {
4112
+ let prevName, routeLimit = showAllRoutes ? 1 / 0 : void 0 === maxRoutes ? 10 : 1 / 0 === maxRoutes ? maxRoutes : Math.max(0, Math.floor(maxRoutes)), printableRoutes = 0 === routeLimit ? [] : routes.slice(0, routeLimit), moreEntries = routeLimit > 0 ? routes.length - printableRoutes.length : 0, nameCount = 0;
4113
+ for (let { name } of urls)if (name && ++nameCount > 1) break;
4114
+ let showNames = nameCount > 1;
4115
+ if (routes.length <= 1 || 0 === printableRoutes.length) {
4116
+ let pathname = printableRoutes[0]?.pathname ?? '', items = urls.map(({ label, name, url })=>({
4117
+ label,
4118
+ name: showNames ? formatName(name) : void 0,
4119
+ url: normalizeUrl(`${url}${pathname}`)
4120
+ })), labelWidth = Math.max(10, ...items.map((item)=>item.label.trimEnd().length + 2)), urlWidth = Math.max(0, ...items.map((item)=>item.name ? item.url.length : 0)), message = items.map(({ label, name, url })=>{
4121
+ let prefix = `➜ ${color.dim(label.trimEnd().padEnd(labelWidth))}`, suffix = name ? `${' '.repeat(urlWidth - url.length + 2)}${color.dim(name)}` : '';
4122
+ return ` ${prefix}${color.cyan(url)}${suffix}\n`;
4123
+ }).join('');
4124
+ return moreEntries > 0 && (message += getMoreEntriesMessage(moreEntries, cliShortcutsEnabled)), message;
4125
+ }
4126
+ let message = '', prevLabel = '', entryWidth = Math.max(...printableRoutes.map((route)=>route.entryName.length));
4127
+ return urls.forEach(({ label, name, url }, index)=>{
4128
+ let shortName = showNames ? formatName(name) : void 0;
4129
+ if (prevLabel !== label || prevName !== shortName) {
4130
+ index > 0 && (message += '\n');
4131
+ let title = shortName ? `${label.trimEnd().slice(0, -1)} ${color.dim(shortName)}:` : label;
4132
+ message += ` ➜ ${title}\n`, prevLabel = label, prevName = shortName;
4126
4133
  }
4127
- };
4134
+ for (let { entryName, pathname } of printableRoutes)message += ` ${color.dim('-')} ${color.dim(entryName.padEnd(entryWidth + 4))}${color.cyan(normalizeUrl(`${url}${pathname}`))}\n`;
4135
+ }), moreEntries > 0 && (message += getMoreEntriesMessage(moreEntries, cliShortcutsEnabled)), message;
4128
4136
  }
4129
- async function watchDevFiles(devConfig, buildManager, root) {
4130
- let { watchFiles } = devConfig;
4131
- if (!watchFiles) return;
4132
- let watchers = [];
4133
- for (let { paths, events, options, type } of helpers_castArray(watchFiles)){
4134
- let watchOptions = prepareWatchOptions(paths, options, type, events), watcher = await startWatchFiles(watchOptions, buildManager, root);
4135
- watcher && watchers.push(watcher);
4137
+ function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls, fallbackPathname, showAllRoutes, cliShortcutsEnabled, originalConfig, logger }) {
4138
+ if (!1 === printUrls) return null;
4139
+ let urls = originalUrls, useCustomUrl = isFunction(printUrls);
4140
+ if (useCustomUrl) {
4141
+ let newUrls = printUrls({
4142
+ urls: urls.map((item)=>item.url),
4143
+ port,
4144
+ routes,
4145
+ protocol
4146
+ });
4147
+ if (!newUrls) return null;
4148
+ if (!Array.isArray(newUrls)) throw Error(`${color.dim('[rsbuild:config]')} "server.printUrls" must return an array, but got ${typeof newUrls}.`);
4149
+ urls = newUrls.map((u)=>{
4150
+ let { url, label } = 'string' == typeof u ? {
4151
+ url: u
4152
+ } : u;
4153
+ return {
4154
+ url,
4155
+ label: label ?? getUrlLabel(url)
4156
+ };
4157
+ });
4136
4158
  }
4137
- return async ()=>{
4138
- for (let watcher of watchers)await watcher.close();
4139
- };
4140
- }
4141
- function watchServerFiles({ publicDir }, buildManager, root) {
4142
- if (!publicDir.length) return;
4143
- let watchPaths = publicDir.filter((item)=>item.watch).map((item)=>item.name);
4144
- if (watchPaths.length) return startWatchFiles(prepareWatchOptions(watchPaths), buildManager, root);
4159
+ if (0 === urls.length) return null;
4160
+ let printableRoutes = 0 !== routes.length || useCustomUrl || void 0 === fallbackPathname ? routes : [
4161
+ {
4162
+ entryName: 'index',
4163
+ pathname: formatPrefix(fallbackPathname)
4164
+ }
4165
+ ];
4166
+ if (0 === printableRoutes.length && !useCustomUrl) return null;
4167
+ let printUrlsOptions = printUrls && 'object' == typeof printUrls ? printUrls : {}, message = getURLMessages(urls, printableRoutes, {
4168
+ maxRoutes: useCustomUrl ? 1 / 0 : printUrlsOptions.maxRoutes,
4169
+ showAllRoutes,
4170
+ cliShortcutsEnabled
4171
+ });
4172
+ return originalConfig && originalConfig.server?.host === void 0 && (message += ` ➜ ${color.dim('Network:')} ${color.dim('use')} ${color.bold('--host')} ${color.dim('to expose')}\n`), !0 === cliShortcutsEnabled && message.endsWith('\n') && (message = message.slice(0, -1)), logger.log(message), message;
4145
4173
  }
4146
- function prepareWatchOptions(paths, options = {}, type, events) {
4174
+ let resolvePort = async (config, lastPort)=>{
4175
+ let { host, port: originalPort, strictPort } = config.server, preferredPort = 0 === originalPort ? lastPort : void 0, port = await (async ({ host, port, strictPort, tryLimits = 20 })=>{
4176
+ 'string' == typeof port && (port = Number.parseInt(port, 10)), strictPort && (tryLimits = 1);
4177
+ let { createServer } = await import("node:net"), original = port, found = !1, attempts = 0;
4178
+ for(; !found && attempts <= tryLimits;)try {
4179
+ await new Promise((resolve, reject)=>{
4180
+ let server = createServer();
4181
+ server.unref(), server.on('error', reject), server.listen({
4182
+ port,
4183
+ host
4184
+ }, ()=>{
4185
+ if (0 === port) {
4186
+ let address = server.address();
4187
+ address && 'string' != typeof address && (port = address.port);
4188
+ }
4189
+ found = !0, server.close(resolve);
4190
+ });
4191
+ });
4192
+ } catch (e) {
4193
+ if (!(e instanceof Error) || !('code' in e) || 'EADDRINUSE' !== e.code) throw e;
4194
+ port++, attempts++;
4195
+ }
4196
+ if (!found) throw Error(`${color.dim('[rsbuild:server]')} Failed to find an available port after ${tryLimits + 1} attempts, starting from ${color.yellow(original)}.`);
4197
+ if (0 !== original && port !== original && strictPort) throw Error(`${color.dim('[rsbuild:server]')} Port ${color.yellow(original)} is occupied, please choose another one.`);
4198
+ return port;
4199
+ })({
4200
+ host,
4201
+ port: preferredPort ?? originalPort,
4202
+ strictPort: void 0 === preferredPort && strictPort
4203
+ }), portTip = 0 !== originalPort && port !== originalPort ? `port ${originalPort} is in use, ${color.yellow(`using port ${port}.`)}` : void 0;
4147
4204
  return {
4148
- paths: 'string' == typeof paths ? [
4149
- paths
4150
- ] : paths,
4151
- events,
4152
- options,
4153
- type
4205
+ port,
4206
+ portTip
4154
4207
  };
4155
- }
4156
- let GLOB_REGEX = /[*?{}[\]()!+|]/;
4157
- async function createChokidar(pathOrGlobs, root, options) {
4158
- let { default: chokidar } = await getChokidar(), watchFiles = new Set(), globPatterns = pathOrGlobs.filter((pathOrGlob)=>!!GLOB_REGEX.test(pathOrGlob) || (watchFiles.add(pathOrGlob), !1));
4159
- if (globPatterns.length) {
4160
- let { glob } = await getTinyglobby();
4161
- for (let file of (await glob(globPatterns, {
4162
- cwd: root,
4163
- absolute: !0
4164
- })))watchFiles.add(file);
4208
+ }, WILDCARD_HOSTS = new Set([
4209
+ ALL_INTERFACES_IPV4,
4210
+ '::',
4211
+ '0000:0000:0000:0000:0000:0000:0000:0000'
4212
+ ]), LOOPBACK_HOSTS = new Set([
4213
+ LOCALHOST,
4214
+ '127.0.0.1',
4215
+ '::1',
4216
+ '0000:0000:0000:0000:0000:0000:0000:0001'
4217
+ ]), isLoopbackHost = (host)=>LOOPBACK_HOSTS.has(host), getHostInUrl = async (host)=>{
4218
+ if (host === ALL_INTERFACES_IPV4 || host === LOCALHOST) return LOCALHOST;
4219
+ let { isIPv6 } = await import("node:net");
4220
+ return isIPv6(host) ? '::' === host ? '[::1]' : `[${host}]` : host;
4221
+ }, concatUrl = ({ host, port, protocol })=>`${protocol}://${host}:${port}`, LOCAL_LABEL = 'Local: ', NETWORK_LABEL = 'Network: ', getUrlLabel = (url)=>{
4222
+ try {
4223
+ let { hostname } = new URL(url);
4224
+ return isLoopbackHost(hostname) ? LOCAL_LABEL : NETWORK_LABEL;
4225
+ } catch {
4226
+ return NETWORK_LABEL;
4165
4227
  }
4166
- return chokidar.watch(Array.from(watchFiles), options);
4167
- }
4168
- async function startWatchFiles({ paths, events, options, type = 'reload-page' }, buildManager, root) {
4169
- if ('reload-page' !== type || events?.length === 0) return;
4170
- let watcher = await createChokidar(paths, root, {
4171
- ignoreInitial: !0,
4172
- ...options
4173
- }), reloadPage = ()=>{
4174
- buildManager.socketServer.sendMessage({
4228
+ }, getAddressUrls = async ({ protocol, port, host })=>{
4229
+ if (host && !WILDCARD_HOSTS.has(host)) {
4230
+ let url = concatUrl({
4231
+ port,
4232
+ host: await getHostInUrl(host),
4233
+ protocol
4234
+ });
4235
+ return [
4236
+ {
4237
+ label: isLoopbackHost(host) ? LOCAL_LABEL : NETWORK_LABEL,
4238
+ url
4239
+ }
4240
+ ];
4241
+ }
4242
+ let urls = [], seen = new Set(), hasLocal = !1;
4243
+ for (let [name, infos] of Object.entries(node_os.networkInterfaces()))for (let info of infos ?? []){
4244
+ let family = info.family;
4245
+ !('IPv4' !== family && 4 !== family || seen.has(info.address)) && (seen.add(info.address), isLoopbackHost(info.address) || info.internal ? hasLocal || (urls.push({
4246
+ label: LOCAL_LABEL,
4247
+ url: concatUrl({
4248
+ host: LOCALHOST,
4249
+ port,
4250
+ protocol
4251
+ })
4252
+ }), hasLocal = !0) : urls.push({
4253
+ label: NETWORK_LABEL,
4254
+ name,
4255
+ url: concatUrl({
4256
+ host: info.address,
4257
+ port,
4258
+ protocol
4259
+ })
4260
+ }));
4261
+ }
4262
+ return urls;
4263
+ };
4264
+ function getServerTerminator(server) {
4265
+ let listened = !1, pendingSockets = new Set(), onConnection = (socket)=>{
4266
+ pendingSockets.add(socket), socket.on('close', ()=>{
4267
+ pendingSockets.delete(socket);
4268
+ });
4269
+ };
4270
+ return server.on('connection', onConnection), server.on('secureConnection', onConnection), server.once('listening', ()=>{
4271
+ listened = !0;
4272
+ }), ()=>new Promise((resolve, reject)=>{
4273
+ for (let socket of pendingSockets)socket.destroy();
4274
+ listened ? server.close((err)=>{
4275
+ err ? reject(err) : resolve();
4276
+ }) : resolve();
4277
+ });
4278
+ }
4279
+ function escapeHtml(text) {
4280
+ return text ? text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;') : '';
4281
+ }
4282
+ let getPublicDirPaths = (config, watchOnly = !1)=>{
4283
+ let paths = new Set();
4284
+ for (let { server } of Object.values(config.environments))for (let { name, watch } of server.publicDir)(!watchOnly || watch) && paths.add(name);
4285
+ return [
4286
+ ...paths
4287
+ ];
4288
+ }, getChokidar = cachedImport_cachedImport(()=>import("./chokidar.js").then((m)=>m.chokidar_namespaceObject)), DEFAULT_WATCH_FILE_EVENTS = [
4289
+ 'add',
4290
+ 'change',
4291
+ 'unlink'
4292
+ ];
4293
+ async function setupWatchFiles(options) {
4294
+ let { config, root, logger, buildManager } = options, { hmr, liveReload } = config.dev;
4295
+ if (!hmr && !liveReload || !buildManager) return;
4296
+ let closeDevFilesWatcher = await watchDevFiles(config.dev, buildManager, root, logger), serverFilesWatcher = await watchServerFiles(config, buildManager, root, logger);
4297
+ return {
4298
+ async close () {
4299
+ await Promise.all([
4300
+ closeDevFilesWatcher?.(),
4301
+ serverFilesWatcher?.close()
4302
+ ]);
4303
+ }
4304
+ };
4305
+ }
4306
+ async function watchDevFiles(devConfig, buildManager, root, logger) {
4307
+ let { watchFiles } = devConfig;
4308
+ if (!watchFiles) return;
4309
+ let watchers = [];
4310
+ for (let { paths, events, options, type } of helpers_castArray(watchFiles)){
4311
+ let watchOptions = prepareWatchOptions(paths, options, type, events), watcher = await startWatchFiles(watchOptions, buildManager, root, logger);
4312
+ watcher && watchers.push(watcher);
4313
+ }
4314
+ return async ()=>{
4315
+ for (let watcher of watchers)await watcher.close();
4316
+ };
4317
+ }
4318
+ function watchServerFiles(config, buildManager, root, logger) {
4319
+ let watchPaths = getPublicDirPaths(config, !0);
4320
+ if (watchPaths.length) return startWatchFiles(prepareWatchOptions(watchPaths), buildManager, root, logger);
4321
+ }
4322
+ function prepareWatchOptions(paths, options = {}, type, events) {
4323
+ return {
4324
+ paths: 'string' == typeof paths ? [
4325
+ paths
4326
+ ] : paths,
4327
+ events,
4328
+ options,
4329
+ type
4330
+ };
4331
+ }
4332
+ let GLOB_REGEX = /[*?{}[\]()!+|]/;
4333
+ async function createChokidar(pathOrGlobs, root, options, logger) {
4334
+ let { default: chokidar } = await getChokidar(), watchFiles = new Set(), globPatterns = pathOrGlobs.filter((pathOrGlob)=>!!GLOB_REGEX.test(pathOrGlob) || (watchFiles.add(pathOrGlob), !1));
4335
+ if (globPatterns.length) {
4336
+ let { glob } = await getTinyglobby();
4337
+ for (let file of (await glob(globPatterns, {
4338
+ cwd: root,
4339
+ absolute: !0
4340
+ })))watchFiles.add(file);
4341
+ }
4342
+ let watcher = chokidar.watch(Array.from(watchFiles), options);
4343
+ return watcher.on('error', (error)=>{
4344
+ logger.error('File watcher error:', error);
4345
+ }), watcher;
4346
+ }
4347
+ async function startWatchFiles({ paths, events, options, type = 'reload-page' }, buildManager, root, logger) {
4348
+ if ('reload-page' !== type || events?.length === 0) return;
4349
+ let watcher = await createChokidar(paths, root, {
4350
+ ignoreInitial: !0,
4351
+ ...options
4352
+ }, logger), reloadPage = ()=>{
4353
+ buildManager.socketServer.sendMessage({
4175
4354
  type: 'full-reload'
4176
4355
  });
4177
4356
  };
@@ -4234,7 +4413,7 @@ function watchFilesForRestart({ watchFiles, context, restartContext }) {
4234
4413
  ignoreInitial: !0,
4235
4414
  ignorePermissionErrors: !0,
4236
4415
  ...options
4237
- }), cwd = options?.cwd ?? root;
4416
+ }, logger), cwd = options?.cwd ?? root;
4238
4417
  for (let event of events ? new Set(events) : DEFAULT_WATCH_FILE_EVENTS)watcher.on(event, (filePath)=>onWatchEvent(event, filePath, cwd));
4239
4418
  return watcher;
4240
4419
  } catch (error) {
@@ -4245,100 +4424,7 @@ function watchFilesForRestart({ watchFiles, context, restartContext }) {
4245
4424
  close
4246
4425
  };
4247
4426
  }
4248
- let RSPACK_BUILD_ERROR = 'Rspack build failed.', build_build = async (initOptions, buildOptions = {})=>{
4249
- let stats, closeCompiler, closingPromise, unregisterRestart, restartWatcher, { watch } = buildOptions, { context } = initOptions, { logger } = context, { compiler, rspackConfigs } = await createCompiler_createCompiler(initOptions);
4250
- if ((({ context, isWatch, compiler, rspackConfigs, MultiStatsCtor })=>{
4251
- let isFirstCompile = !0, { environmentList } = context, onDone = async (stats)=>{
4252
- let shouldLogWatching = isWatch && isFirstCompile, promise = context.hooks.onAfterBuild.callBatch({
4253
- isFirstCompile,
4254
- stats,
4255
- environments: context.environments,
4256
- isWatch
4257
- });
4258
- isFirstCompile = !1, await promise, shouldLogWatching && context.logger.info('watching for changes...');
4259
- }, onEnvironmentDone = async (index, stats)=>{
4260
- let environment = environmentList[index], time = context.buildState.time[environment.name] ?? 0;
4261
- await context.hooks.onAfterEnvironmentCompile.callBatch({
4262
- environment: environment.name,
4263
- args: [
4264
- {
4265
- isFirstCompile,
4266
- stats,
4267
- environment,
4268
- isWatch,
4269
- time
4270
- }
4271
- ]
4272
- });
4273
- };
4274
- onBeforeCompile({
4275
- compiler,
4276
- beforeCompile: async ()=>context.hooks.onBeforeBuild.callBatch({
4277
- bundlerConfigs: rspackConfigs,
4278
- environments: context.environments,
4279
- isWatch,
4280
- isFirstCompile
4281
- }),
4282
- beforeEnvironmentCompile: async (buildIndex)=>{
4283
- let environment = environmentList[buildIndex];
4284
- return context.hooks.onBeforeEnvironmentCompile.callBatch({
4285
- environment: environment.name,
4286
- args: [
4287
- {
4288
- bundlerConfig: rspackConfigs[buildIndex],
4289
- environment,
4290
- isWatch,
4291
- isFirstCompile
4292
- }
4293
- ]
4294
- });
4295
- },
4296
- isWatch
4297
- }), onCompileDone({
4298
- compiler,
4299
- onDone,
4300
- onEnvironmentDone,
4301
- MultiStatsCtor
4302
- });
4303
- })({
4304
- context,
4305
- rspackConfigs,
4306
- compiler,
4307
- isWatch: !!watch,
4308
- MultiStatsCtor: core_rspack.MultiStats
4309
- }), watch) {
4310
- let watchOptions = rspackConfigs.map((options)=>options.watchOptions || {});
4311
- compiler.watch(watchOptions.length > 1 ? watchOptions : watchOptions[0] || {}, (err)=>{
4312
- err && logger.error(err);
4313
- }), closeCompiler = ()=>new Promise((resolve)=>{
4314
- compiler.close(()=>{
4315
- resolve();
4316
- });
4317
- });
4318
- } else stats = await new Promise((resolve, reject)=>{
4319
- compiler.run((err, stats)=>{
4320
- compiler.close((closeErr)=>{
4321
- closeErr && logger.error('Failed to close compiler: ', closeErr), err ? reject(err) : context.buildState.hasErrors ? reject(Error(RSPACK_BUILD_ERROR)) : resolve(stats);
4322
- });
4323
- });
4324
- });
4325
- let closeBuild = ()=>closingPromise ||= (async ()=>{
4326
- unregisterRestart?.(), unregisterRestart = void 0, await context.hooks.onCloseBuild.callBatch(), await closeCompiler?.();
4327
- })();
4328
- return watch && (unregisterRestart = context.restartManager.registerCleanup(closeBuild), restartWatcher = watchFilesForRestart({
4329
- watchFiles: context.normalizedConfig.dev.watchFiles,
4330
- context,
4331
- restartContext: {
4332
- action: 'build',
4333
- options: buildOptions
4334
- }
4335
- })), {
4336
- stats,
4337
- close: async ()=>{
4338
- await restartWatcher?.close(), await closeBuild();
4339
- }
4340
- };
4341
- }, main = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/dotenv-expand/13.0.0/1d3d360f4c41ed89366b79ec2c361d16e6aee7ab6c47163ea4f3718f7f78cc4c/node_modules/dotenv-expand/lib/main.js"), DOTENV_LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
4427
+ let RSPACK_BUILD_ERROR = 'Rspack build failed.', main = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/dotenv-expand/13.0.0/1d3d360f4c41ed89366b79ec2c361d16e6aee7ab6c47163ea4f3718f7f78cc4c/node_modules/dotenv-expand/lib/main.js"), DOTENV_LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
4342
4428
  function loadEnv_parse(src) {
4343
4429
  let match, obj = {}, lines = src.toString();
4344
4430
  for(lines = lines.replace(/\r\n?/gm, '\n'); null != (match = DOTENV_LINE.exec(lines));){
@@ -4370,8 +4456,8 @@ function loadEnv({ cwd = process.cwd(), mode = process.env.NODE_ENV || '', prefi
4370
4456
  });
4371
4457
  let publicVars = {}, rawPublicVars = {};
4372
4458
  for (let key of Object.keys(processEnv))if (prefixes.some((prefix)=>key.startsWith(prefix))) {
4373
- let val = processEnv[key];
4374
- publicVars[`import.meta.env.${key}`] = JSON.stringify(val), publicVars[`process.env.${key}`] = JSON.stringify(val), rawPublicVars[key] = val;
4459
+ let val = processEnv[key], serialized = JSON.stringify(val);
4460
+ publicVars[`import.meta.env.${key}`] = serialized, publicVars[`process.env.${key}`] = serialized, rawPublicVars[key] = val;
4375
4461
  }
4376
4462
  let cleaned = !1;
4377
4463
  return {
@@ -4890,7 +4976,25 @@ let normalizeCleanDistPath = (userOptions)=>{
4890
4976
  ...defaultOptions,
4891
4977
  ...userOptions
4892
4978
  };
4893
- }, getConsolePureFuncs = (methods)=>methods.map((method)=>`console.${method}`), ALL_CONSOLE_PURE_FUNCS = getConsolePureFuncs([
4979
+ };
4980
+ function findWorkspaceRoot(root) {
4981
+ let packageRoot, current = root;
4982
+ for(;;){
4983
+ if (isFileSync(join(current, 'pnpm-workspace.yaml')) || isFileSync(join(current, 'lerna.json'))) return current;
4984
+ let packageJson = join(current, 'package.json');
4985
+ if (isFileSync(packageJson)) {
4986
+ packageRoot ??= current;
4987
+ try {
4988
+ let pkg = JSON.parse(readFileSync(packageJson, 'utf8'));
4989
+ if (pkg?.workspaces) return current;
4990
+ } catch {}
4991
+ }
4992
+ let parent = dirname(current);
4993
+ if (parent === current) return packageRoot ?? root;
4994
+ current = parent;
4995
+ }
4996
+ }
4997
+ let getConsolePureFuncs = (methods)=>methods.map((method)=>`console.${method}`), ALL_CONSOLE_PURE_FUNCS = getConsolePureFuncs([
4894
4998
  'assert',
4895
4999
  'clear',
4896
5000
  'count',
@@ -4950,8 +5054,9 @@ function parseMinifyOptions(config) {
4950
5054
  cssOptions: minify.cssOptions
4951
5055
  };
4952
5056
  }
4953
- var postcss_load_config_src_default = compatGetDefaultExport(rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/baf07bf9099810ce2e0c00768f056c90b47d57b154f4b8912460449b9922899a/node_modules/postcss-load-config/src/index.js"));
4954
- async function getLightningCSSLoaderOptions(config, targets, minify) {
5057
+ let postcss_load_config_src = rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/postcss-load-config/6.0.1/0c96146f27b5be84aebd61df108bee07abfdc2dd46aa3cb0cd89aa03287d40cd/node_modules/postcss-load-config/src/index.js");
5058
+ var postcss_load_config_src_default = compatGetDefaultExport(postcss_load_config_src);
5059
+ function getLightningCSSLoaderOptions(config, targets, minify) {
4955
5060
  let userOptions = 'object' == typeof config.tools.lightningcssLoader ? config.tools.lightningcssLoader : {}, initialOptions = {
4956
5061
  targets,
4957
5062
  errorRecovery: !0
@@ -4973,81 +5078,14 @@ let clonePostCSSConfig = (config)=>({
4973
5078
  async function loadUserPostcssrc(root, postcssrcCache) {
4974
5079
  let cached = postcssrcCache.get(root);
4975
5080
  if (cached) return clonePostCSSConfig(await cached);
4976
- let promise = postcss_load_config_src_default()({}, root).catch((err)=>{
5081
+ let promise = postcss_load_config_src_default()({}, root, {
5082
+ stopDir: findWorkspaceRoot(root)
5083
+ }).catch((err)=>{
4977
5084
  if (err.message?.includes('No PostCSS Config found')) return {};
4978
5085
  throw err;
4979
5086
  });
4980
5087
  return postcssrcCache.set(root, promise), promise.then((config)=>(postcssrcCache.set(root, config), clonePostCSSConfig(config)));
4981
5088
  }
4982
- let getPostcssLoaderOptions = async ({ config, root, postcssrcCache })=>{
4983
- let extraPlugins = [], userOptions = await loadUserPostcssrc(root, postcssrcCache);
4984
- userOptions.plugins ||= [];
4985
- let defaultOptions = {
4986
- implementation: getCompiledPath('postcss'),
4987
- postcssOptions: userOptions,
4988
- sourceMap: getCSSSourceMap(config)
4989
- }, finalOptions = await reduceConfigsWithContext({
4990
- initial: defaultOptions,
4991
- config: config.tools.postcss,
4992
- ctx: {
4993
- addPlugins (plugins, options = {}) {
4994
- let { order = 'post' } = options, list = helpers_castArray(plugins);
4995
- 'pre' === order ? extraPlugins.unshift(...list) : extraPlugins.push(...list);
4996
- }
4997
- }
4998
- });
4999
- finalOptions.postcssOptions ||= {};
5000
- 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;
5001
- if ('function' == typeof postcssOptions) {
5002
- let postcssOptionsWrapper = (loaderContext)=>{
5003
- let options = postcssOptions(loaderContext);
5004
- if ('object' != typeof options || null === options) throw Error(`${color.dim('[rsbuild:css]')} \`postcssOptions\` function must return a PostCSSOptions object, got ${color.yellow(typeof options)}.`);
5005
- return updatePostcssOptions({
5006
- ...userOptions,
5007
- ...options,
5008
- plugins: [
5009
- ...userOptions.plugins || [],
5010
- ...options.plugins || []
5011
- ]
5012
- });
5013
- };
5014
- return postcssOptionsWrapper.config = !1, {
5015
- ...finalOptions,
5016
- postcssOptions: postcssOptionsWrapper
5017
- };
5018
- }
5019
- return finalOptions.postcssOptions = updatePostcssOptions(postcssOptions), finalOptions;
5020
- }, getCSSLoaderOptions = async ({ config, localIdentName, emitCss })=>{
5021
- let { cssModules } = config.output, defaultOptions = {
5022
- modules: {
5023
- ...cssModules,
5024
- localIdentName
5025
- },
5026
- sourceMap: getCSSSourceMap(config)
5027
- };
5028
- return ((options, exportOnlyLocals)=>{
5029
- if (options.modules && exportOnlyLocals) {
5030
- let { modules } = options;
5031
- return modules = !0 === modules ? {
5032
- exportOnlyLocals: !0
5033
- } : 'string' == typeof modules ? {
5034
- mode: modules,
5035
- exportOnlyLocals: !0
5036
- } : {
5037
- ...modules,
5038
- exportOnlyLocals: !0
5039
- }, {
5040
- ...options,
5041
- modules
5042
- };
5043
- }
5044
- return options;
5045
- })(await reduceConfigs({
5046
- initial: defaultOptions,
5047
- config: config.tools.cssLoader,
5048
- mergeFn: cjs_0_default()
5049
- }), !emitCss);
5050
- };
5051
5089
  function checkProcessEnvSecurity(define, logger) {
5052
5090
  let value = define['process.env'];
5053
5091
  if (!value) return;
@@ -5060,13 +5098,7 @@ function checkProcessEnvSecurity(define, logger) {
5060
5098
  check(JSON.parse(value));
5061
5099
  } catch {}
5062
5100
  }
5063
- let readPackageJsonByPath = async (pkgJsonPath)=>{
5064
- if (await isFileExists(pkgJsonPath)) try {
5065
- return JSON.parse(await readFile(pkgJsonPath, 'utf8'));
5066
- } catch {
5067
- return;
5068
- }
5069
- }, dependencyTypes = [
5101
+ let dependencyTypes = [
5070
5102
  'dependencies',
5071
5103
  'peerDependencies',
5072
5104
  'devDependencies',
@@ -5083,18 +5115,6 @@ let readPackageJsonByPath = async (pkgJsonPath)=>{
5083
5115
  ...!0 === autoExternal ? {} : autoExternal
5084
5116
  };
5085
5117
  return dependencyTypes.some((type)=>externalOptions[type]) ? externalOptions : void 0;
5086
- }, readPackageJsonList = async (paths, cache)=>{
5087
- var packageJsonList = (await Promise.all(paths.map(async (path)=>(cache.has(path) || cache.set(path, await readPackageJsonByPath(path)), cache.get(path))))).filter((pkgJson)=>!!pkgJson);
5088
- return packageJsonList.length ? dependencyTypes.reduce((merged, type)=>{
5089
- for (let pkgJson of packageJsonList){
5090
- let deps = pkgJson[type];
5091
- isPlainObject(deps) && (merged[type] = {
5092
- ...merged[type],
5093
- ...deps
5094
- });
5095
- }
5096
- return merged;
5097
- }, {}) : void 0;
5098
5118
  };
5099
5119
  function pluginExternals() {
5100
5120
  return {
@@ -5105,7 +5125,25 @@ function pluginExternals() {
5105
5125
  let pkgJson, { autoExternal, externals } = environment.config.output, externalOptions = resolveAutoExternalOptions(autoExternal);
5106
5126
  if (externalOptions) {
5107
5127
  let rootPath, packageJsonPaths = (rootPath = api.context.rootPath, helpers_castArray(externalOptions.packageJson ?? 'package.json').map((path)=>external_node_path_resolve(rootPath, path)));
5108
- pkgJson = await readPackageJsonList(packageJsonPaths, packageJsonCache);
5128
+ pkgJson = await (async (paths, cache)=>{
5129
+ var packageJsonList = (await Promise.all(paths.map(async (path)=>(cache.has(path) || cache.set(path, await (async (pkgJsonPath)=>{
5130
+ if (await isFileExists(pkgJsonPath)) try {
5131
+ return JSON.parse(await readFile(pkgJsonPath, 'utf8'));
5132
+ } catch {
5133
+ return;
5134
+ }
5135
+ })(path)), cache.get(path))))).filter((pkgJson)=>!!pkgJson);
5136
+ return packageJsonList.length ? dependencyTypes.reduce((merged, type)=>{
5137
+ for (let pkgJson of packageJsonList){
5138
+ let deps = pkgJson[type];
5139
+ isPlainObject(deps) && (merged[type] = {
5140
+ ...merged[type],
5141
+ ...deps
5142
+ });
5143
+ }
5144
+ return merged;
5145
+ }, {}) : void 0;
5146
+ })(packageJsonPaths, packageJsonCache);
5109
5147
  }
5110
5148
  !externalOptions || pkgJson || hasWarnedReadPackageJsonFailed || (api.logger.warn('The `output.autoExternal` configuration will not be applied because reading package.json failed.'), hasWarnedReadPackageJsonFailed = !0);
5111
5149
  let autoExternalRules = ((options)=>{
@@ -5135,10 +5173,16 @@ function pluginExternals() {
5135
5173
  }
5136
5174
  };
5137
5175
  }
5176
+ function getAssetNames(compilation) {
5177
+ return compilation.__internal__getAssetFilenames();
5178
+ }
5138
5179
  function createAssetProcessor() {
5139
5180
  let failure, active = 0, waiting = [];
5140
5181
  return async (names, processAsset)=>{
5141
- let cursor = 0, consume = async ()=>{
5182
+ let cursor = 0;
5183
+ if (await Promise.all(Array.from({
5184
+ length: Math.min(16, names.length)
5185
+ }, async ()=>{
5142
5186
  for(; cursor < names.length && !failure;){
5143
5187
  let index = cursor++;
5144
5188
  active >= 16 ? await new Promise((resolve)=>waiting.push(resolve)) : active++;
@@ -5154,10 +5198,7 @@ function createAssetProcessor() {
5154
5198
  next ? next() : active--;
5155
5199
  }
5156
5200
  }
5157
- };
5158
- if (await Promise.all(Array.from({
5159
- length: Math.min(16, names.length)
5160
- }, consume)), failure) throw failure.error;
5201
+ })), failure) throw failure.error;
5161
5202
  };
5162
5203
  }
5163
5204
  function getCompression(compressed) {
@@ -5221,7 +5262,7 @@ let EXCLUDE_ASSET_REGEX = /\.(?:map|LICENSE\.txt|d\.(?:ts|mts|cts))$/, isSignifi
5221
5262
  label: (diff > 0 ? color.red : color.green)(label),
5222
5263
  length: label.length
5223
5264
  };
5224
- }, getAssetColor = (size)=>size > 300000 ? color.red : size > 100000 ? color.yellow : (input)=>input;
5265
+ }, getAssetColor = (size)=>size > 300000 ? color.red : size > 100000 ? color.yellow : (0, (input)=>input);
5225
5266
  function getHeader(maxFileLength, maxSizeLength, fileHeader, compressionHeader) {
5226
5267
  let lengths = [
5227
5268
  maxFileLength,
@@ -5242,8 +5283,8 @@ let calcFileSize = (len)=>{
5242
5283
  return `${val.toFixed(val < 1 ? 2 : 1)} kB`;
5243
5284
  }, COMPRESSIBLE_REGEX = /\.(?:js|mjs|cjs|jsx|ts|tsx|mts|cts|css|html|json|svg|txt|xml|xhtml|wasm|manifest|md)$/i;
5244
5285
  async function getFileSizes(options, compilation, processAssets) {
5245
- if (!1 === options.detail && !1 === options.total) return [];
5246
- let { exclude, include } = options, compression = getCompression(options.compressed), fileSizes = [], compilationAssets = compilation.assets, names = Object.getOwnPropertyNames(compilationAssets);
5286
+ if ((!1 === options.detail || 0 === options.detail) && !1 === options.total) return [];
5287
+ let { exclude, include } = options, compression = getCompression(options.compressed), fileSizes = [], compilationAssets = compilation.assets, names = getAssetNames(compilation);
5247
5288
  return await processAssets(names, async (assetName, index)=>{
5248
5289
  let queryIndex, filePath = -1 === (queryIndex = assetName.indexOf('?')) ? assetName : assetName.slice(0, queryIndex);
5249
5290
  if (!exclude && EXCLUDE_ASSET_REGEX.test(filePath)) return;
@@ -5264,7 +5305,7 @@ async function getFileSizes(options, compilation, processAssets) {
5264
5305
  }), fileSizes.filter(Boolean);
5265
5306
  }
5266
5307
  function printFileSizes(options, fileSizes, rootPath, distPath, environmentName, previousSizes, saveSnapshot) {
5267
- 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;
5308
+ let logs = [], compression = getCompression(options.compressed), prev = previousSizes?.[environmentName], detailLimit = 'number' == typeof options.detail ? Math.max(0, Math.floor(options.detail)) : 1 / 0, showDetail = !1 !== options.detail && detailLimit > 0, showDiff = !1 !== options.diff && null !== previousSizes, prevType = prev?.compressionType ?? (!!prev?.totalGzipSize && 'gzip'), showCompressedDiff = showDiff && prevType === compression.type, showTotal = !1 !== options.total;
5268
5309
  if (!showTotal && !showDetail) return {
5269
5310
  logs
5270
5311
  };
@@ -5360,16 +5401,17 @@ function printFileSizes(options, fileSizes, rootPath, distPath, environmentName,
5360
5401
  totalBrotliSize: options.compressed && 'brotli' === compression.type ? totalCompressedSize : void 0
5361
5402
  }) : null;
5362
5403
  if (showDetail) {
5363
- let maxFileLength = Math.max(showTotal ? totalSizeTitle.length : 0, fileHeader.length), maxSizeLength = totalSizeLabelLength, hasCompressedSize = !1;
5364
- for (let asset of assets)asset.filenameLength > maxFileLength && (maxFileLength = asset.filenameLength), asset.sizeLabelLength > maxSizeLength && (maxSizeLength = asset.sizeLabelLength), null !== asset.compressedSize && (hasCompressedSize = !0);
5365
- let showCompressedHeader = !!(options.compressed && hasCompressedSize);
5366
- for (let asset of (logs.push(getHeader(maxFileLength, maxSizeLength, fileHeader, showCompressedHeader && compression.header)), assets)){
5404
+ let displayedAssets = assets.slice(Math.max(0, assets.length - detailLimit)), maxFileLength = Math.max(showTotal ? totalSizeTitle.length : 0, fileHeader.length), maxSizeLength = totalSizeLabelLength;
5405
+ for (let asset of displayedAssets)asset.filenameLength > maxFileLength && (maxFileLength = asset.filenameLength), asset.sizeLabelLength > maxSizeLength && (maxSizeLength = asset.sizeLabelLength);
5406
+ let showCompressedHeader = !!(options.compressed && (showTotal ? assets : displayedAssets).some((asset)=>null !== asset.compressedSize));
5407
+ for (let asset of (logs.push(getHeader(maxFileLength, maxSizeLength, fileHeader, showCompressedHeader && compression.header)), displayedAssets)){
5367
5408
  let { sizeLabel, filenameLabel } = asset, { sizeLabelLength, compressedSizeLabel, filenameLength } = asset;
5368
5409
  sizeLabelLength < maxSizeLength && (sizeLabel += ' '.repeat(maxSizeLength - sizeLabelLength)), filenameLength < maxFileLength && (filenameLabel += ' '.repeat(maxFileLength - filenameLength));
5369
5410
  let log = `${filenameLabel} ${sizeLabel}`;
5370
5411
  compressedSizeLabel && (log += ` ${compressedSizeLabel}`), logs.push(log);
5371
5412
  }
5372
- if (showTotal) {
5413
+ let hiddenCount = assets.length - displayedAssets.length;
5414
+ if (hiddenCount > 0 && logs.push(color.dim(`... ${hiddenCount} more ${1 === hiddenCount ? 'file' : 'files'} not shown`)), showTotal) {
5373
5415
  logs.push('');
5374
5416
  let customTotal = getCustomTotal();
5375
5417
  if (customTotal) logs.push(customTotal);
@@ -5480,42 +5522,7 @@ class RsbuildHtmlPlugin {
5480
5522
  this.name = 'RsbuildHtmlPlugin', this.getExtraData = getExtraData, this.getHTMLPlugin = getHTMLPlugin;
5481
5523
  }
5482
5524
  apply(compiler) {
5483
- let emitFavicon = async ({ compilation, favicon, faviconDistPath, logger })=>{
5484
- let fileContent, name = node_path.basename(favicon), outputFilename = node_path.posix.join(faviconDistPath, name);
5485
- if (outputFilename in compilation.assets) return outputFilename;
5486
- let inputFs = compilation.inputFileSystem;
5487
- if (!inputFs) return addCompilationError(compilation, `${color.dim('[rsbuild:html]')} Failed to read the favicon file as ${color.yellow('compilation.inputFileSystem')} is not available.`), null;
5488
- let inputFilename = node_path.isAbsolute(favicon) ? favicon : node_path.join(compilation.compiler.context, favicon);
5489
- try {
5490
- fileContent = await readFileAsync(inputFs, inputFilename);
5491
- } catch (error) {
5492
- return logger.debug('read favicon error:', error), addCompilationError(compilation, `${color.dim('[rsbuild:html]')} Failed to read the favicon file at ${color.yellow(inputFilename)}.`), null;
5493
- }
5494
- let source = new core_rspack.sources.RawSource(fileContent, !1);
5495
- return compilation.emitAsset(outputFilename, source), outputFilename;
5496
- }, addFavicon = async ({ headTags, favicon, faviconDistPath, compilation, publicPath, logger })=>{
5497
- let href = favicon;
5498
- if (!isURL(favicon)) {
5499
- let name = await emitFavicon({
5500
- compilation,
5501
- favicon,
5502
- faviconDistPath,
5503
- logger
5504
- });
5505
- if (null === name) return;
5506
- href = ensureAssetPrefix(name, publicPath);
5507
- }
5508
- let tag = {
5509
- tagName: 'link',
5510
- voidTag: !0,
5511
- attributes: {
5512
- rel: 'icon',
5513
- href
5514
- },
5515
- meta: {}
5516
- };
5517
- href.endsWith('.svg') && (tag.attributes.type = 'image/svg+xml'), headTags.unshift(tag);
5518
- }, getExtraDataByPlugin = (plugin)=>{
5525
+ let getExtraDataByPlugin = (plugin)=>{
5519
5526
  if (!plugin.options) return;
5520
5527
  let entryName = plugin.options[entryNameSymbol];
5521
5528
  if (entryName) return this.getExtraData(entryName);
@@ -5534,7 +5541,42 @@ class RsbuildHtmlPlugin {
5534
5541
  voidTag: !1,
5535
5542
  meta: {}
5536
5543
  });
5537
- })(headTags, data.plugin.options?.title), favicon && await addFavicon({
5544
+ })(headTags, data.plugin.options?.title), favicon && await (async ({ headTags, favicon, faviconDistPath, compilation, publicPath, logger })=>{
5545
+ let href = favicon;
5546
+ if (!isURL(favicon)) {
5547
+ let name = await (async ({ compilation, favicon, faviconDistPath, logger })=>{
5548
+ let fileContent, name = node_path.basename(favicon), outputFilename = node_path.posix.join(faviconDistPath, name);
5549
+ if (outputFilename in compilation.assets) return outputFilename;
5550
+ let inputFs = compilation.inputFileSystem;
5551
+ if (!inputFs) return addCompilationError(compilation, `${color.dim('[rsbuild:html]')} Failed to read the favicon file as ${color.yellow('compilation.inputFileSystem')} is not available.`), null;
5552
+ let inputFilename = node_path.isAbsolute(favicon) ? favicon : node_path.join(compilation.compiler.context, favicon);
5553
+ try {
5554
+ fileContent = await readFileAsync(inputFs, inputFilename);
5555
+ } catch (error) {
5556
+ return logger.debug('read favicon error:', error), addCompilationError(compilation, `${color.dim('[rsbuild:html]')} Failed to read the favicon file at ${color.yellow(inputFilename)}.`), null;
5557
+ }
5558
+ let source = new core_rspack.sources.RawSource(fileContent, !1);
5559
+ return compilation.emitAsset(outputFilename, source), outputFilename;
5560
+ })({
5561
+ compilation,
5562
+ favicon,
5563
+ faviconDistPath,
5564
+ logger
5565
+ });
5566
+ if (null === name) return;
5567
+ href = ensureAssetPrefix(name, publicPath);
5568
+ }
5569
+ let tag = {
5570
+ tagName: 'link',
5571
+ voidTag: !0,
5572
+ attributes: {
5573
+ rel: 'icon',
5574
+ href
5575
+ },
5576
+ meta: {}
5577
+ };
5578
+ href.endsWith('.svg') && (tag.attributes.type = 'image/svg+xml'), headTags.unshift(tag);
5579
+ })({
5538
5580
  headTags,
5539
5581
  favicon,
5540
5582
  faviconDistPath,
@@ -5691,10 +5733,10 @@ async function getMetaTags(entryName, config, templateContent) {
5691
5733
  entryName
5692
5734
  }
5693
5735
  });
5694
- return templateContent && metaTags.charset && /<meta[^>]+charset=["'][^>]*>/i.test(templateContent) && delete metaTags.charset, metaTags;
5736
+ return templateContent && metaTags.charset && /<meta\b(?:[^>"']|"[^"]*"|'[^']*')*?\scharset\s*=/i.test(templateContent) && delete metaTags.charset, metaTags;
5695
5737
  }
5696
5738
  function getTemplateParameters(entryName, config, assetPrefix) {
5697
- return async (compilation, assets, assetTags, pluginOptions)=>{
5739
+ return (compilation, assets, assetTags, pluginOptions)=>{
5698
5740
  let { mountId, templateParameters } = config.html, rspackConfig = compilation.options;
5699
5741
  return reduceConfigsWithContext({
5700
5742
  initial: {
@@ -5737,10 +5779,12 @@ function updateSourceMappingURL({ source, compilation, publicPath, type, config
5737
5779
  }
5738
5780
  function getMatchedAsset(name, assets, tests) {
5739
5781
  let asset;
5740
- if (tests.some((test)=>isFunction(test) ? !!(asset ??= assets[name]) && test({
5782
+ for (let test of tests)if (isFunction(test)) {
5783
+ if ((asset ??= assets[name]) && test({
5741
5784
  name,
5742
5785
  size: asset.size()
5743
- }) : test.exec(name))) return asset ?? assets[name];
5786
+ })) return asset;
5787
+ } else if (test.test(name)) return asset ?? assets[name];
5744
5788
  }
5745
5789
  function getInlineTests(config) {
5746
5790
  let isProd = 'production' === config.mode, { inlineStyles, inlineScripts } = config.output, scriptTests = [], styleTests = [];
@@ -5749,205 +5793,6 @@ function getInlineTests(config) {
5749
5793
  styleTests
5750
5794
  };
5751
5795
  }
5752
- let normalizeUrl = (url)=>url.replace(/([^:]\/)\/+/g, '$1'), formatPrefix = (input)=>{
5753
- let prefix = input;
5754
- if (prefix?.startsWith('./') && (prefix = prefix.replace('./', '')), !prefix) return '/';
5755
- let hasLeadingSlash = prefix.startsWith('/'), hasTailSlash = prefix.endsWith('/');
5756
- return `${hasLeadingSlash ? '' : '/'}${prefix}${hasTailSlash ? '' : '/'}`;
5757
- }, joinUrlPath = (basePath, pathname)=>'' === basePath ? pathname : '' === pathname ? basePath : addTrailingSlash(basePath) + pathname.replace(/^\/+/, ''), getMoreEntriesMessage = (moreEntries, cliShortcutsEnabled)=>cliShortcutsEnabled ? ` ${color.dim(`... ${moreEntries} more entries, press `)}${color.bold('u + enter')}${color.dim(' to show all')}\n` : ` ${color.dim(`... ${moreEntries} more entries, set `)}${color.bold('server.printUrls.maxRoutes')}${color.dim(' to show more')}\n`, isUrlPathUnderBase = (pathname, base)=>{
5758
- let basePath = removeTailingSlash(base);
5759
- return '' === basePath || pathname === basePath || pathname.startsWith(`${basePath}/`);
5760
- }, removeBasePath = (url, base)=>{
5761
- let basePath = removeTailingSlash(base);
5762
- if ('' === basePath || !url.startsWith(basePath)) return url;
5763
- let nextChar = url[basePath.length];
5764
- return void 0 === nextChar ? '/' : '/' === nextChar ? url.slice(basePath.length) : '?' === nextChar || '#' === nextChar ? `/${url.slice(basePath.length)}` : url;
5765
- }, getRoutes = (context)=>{
5766
- let environmentWithHtml = context.environmentList.filter((item)=>Object.keys(item.htmlPaths).length > 0);
5767
- if (0 === environmentWithHtml.length) return [];
5768
- let commonDistPath = getCommonParentPath(environmentWithHtml.map((item)=>item.distPath));
5769
- return environmentWithHtml.reduce((prev, environmentContext)=>{
5770
- let { distPath, config } = environmentContext, distPrefix = relative(commonDistPath, distPath).split(sep).join('/'), routes = formatRoutes(environmentContext.htmlPaths, context.normalizedConfig.server.base, posix.join(distPrefix, config.output.distPath.html), config.html.outputStructure);
5771
- return prev.concat(...routes);
5772
- }, []);
5773
- }, formatRoutes = (entry, base, distPathPrefix, outputStructure)=>{
5774
- let prefix = joinUrlPath(base, formatPrefix(distPathPrefix));
5775
- return Object.keys(entry).map((entryName)=>({
5776
- entryName,
5777
- pathname: prefix + ('index' === entryName && 'nested' !== outputStructure ? '' : entryName)
5778
- })).sort((a)=>'index' === a.entryName ? -1 : 1);
5779
- }, formatName = (name)=>name ? `(${name.length > 20 ? `${name.slice(0, 19)}…` : name})` : name;
5780
- function getURLMessages(urls, routes, { maxRoutes = 10, showAllRoutes, cliShortcutsEnabled }) {
5781
- let prevName, routeLimit = showAllRoutes ? 1 / 0 : void 0 === maxRoutes ? 10 : 1 / 0 === maxRoutes ? maxRoutes : Math.max(0, Math.floor(maxRoutes)), printableRoutes = 0 === routeLimit ? [] : routes.slice(0, routeLimit), moreEntries = routeLimit > 0 ? routes.length - printableRoutes.length : 0, nameCount = 0;
5782
- for (let { name } of urls)if (name && ++nameCount > 1) break;
5783
- let showNames = nameCount > 1;
5784
- if (routes.length <= 1 || 0 === printableRoutes.length) {
5785
- let pathname = printableRoutes[0]?.pathname ?? '', items = urls.map(({ label, name, url })=>({
5786
- label,
5787
- name: showNames ? formatName(name) : void 0,
5788
- url: normalizeUrl(`${url}${pathname}`)
5789
- })), labelWidth = Math.max(10, ...items.map((item)=>item.label.trimEnd().length + 2)), urlWidth = Math.max(0, ...items.map((item)=>item.name ? item.url.length : 0)), message = items.map(({ label, name, url })=>{
5790
- let prefix = `➜ ${color.dim(label.trimEnd().padEnd(labelWidth))}`, suffix = name ? `${' '.repeat(urlWidth - url.length + 2)}${color.dim(name)}` : '';
5791
- return ` ${prefix}${color.cyan(url)}${suffix}\n`;
5792
- }).join('');
5793
- return moreEntries > 0 && (message += getMoreEntriesMessage(moreEntries, cliShortcutsEnabled)), message;
5794
- }
5795
- let message = '', prevLabel = '', entryWidth = Math.max(...printableRoutes.map((route)=>route.entryName.length));
5796
- return urls.forEach(({ label, name, url }, index)=>{
5797
- let shortName = showNames ? formatName(name) : void 0;
5798
- if (prevLabel !== label || prevName !== shortName) {
5799
- index > 0 && (message += '\n');
5800
- let title = shortName ? `${label.trimEnd().slice(0, -1)} ${color.dim(shortName)}:` : label;
5801
- message += ` ➜ ${title}\n`, prevLabel = label, prevName = shortName;
5802
- }
5803
- for (let { entryName, pathname } of printableRoutes)message += ` ${color.dim('-')} ${color.dim(entryName.padEnd(entryWidth + 4))}${color.cyan(normalizeUrl(`${url}${pathname}`))}\n`;
5804
- }), moreEntries > 0 && (message += getMoreEntriesMessage(moreEntries, cliShortcutsEnabled)), message;
5805
- }
5806
- function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls, fallbackPathname, showAllRoutes, cliShortcutsEnabled, originalConfig, logger }) {
5807
- if (!1 === printUrls) return null;
5808
- let urls = originalUrls, useCustomUrl = isFunction(printUrls);
5809
- if (useCustomUrl) {
5810
- let newUrls = printUrls({
5811
- urls: urls.map((item)=>item.url),
5812
- port,
5813
- routes,
5814
- protocol
5815
- });
5816
- if (!newUrls) return null;
5817
- if (!Array.isArray(newUrls)) throw Error(`${color.dim('[rsbuild:config]')} "server.printUrls" must return an array, but got ${typeof newUrls}.`);
5818
- urls = newUrls.map((u)=>{
5819
- let { url, label } = 'string' == typeof u ? {
5820
- url: u
5821
- } : u;
5822
- return {
5823
- url,
5824
- label: label ?? getUrlLabel(url)
5825
- };
5826
- });
5827
- }
5828
- if (0 === urls.length) return null;
5829
- let printableRoutes = 0 !== routes.length || useCustomUrl || void 0 === fallbackPathname ? routes : [
5830
- {
5831
- entryName: 'index',
5832
- pathname: formatPrefix(fallbackPathname)
5833
- }
5834
- ];
5835
- if (0 === printableRoutes.length && !useCustomUrl) return null;
5836
- let printUrlsOptions = printUrls && 'object' == typeof printUrls ? printUrls : {}, message = getURLMessages(urls, printableRoutes, {
5837
- maxRoutes: useCustomUrl ? 1 / 0 : printUrlsOptions.maxRoutes,
5838
- showAllRoutes,
5839
- cliShortcutsEnabled
5840
- });
5841
- return originalConfig && originalConfig.server?.host === void 0 && (message += ` ➜ ${color.dim('Network:')} ${color.dim('use')} ${color.bold('--host')} ${color.dim('to expose')}\n`), !0 === cliShortcutsEnabled && message.endsWith('\n') && (message = message.slice(0, -1)), logger.log(message), message;
5842
- }
5843
- let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
5844
- 'string' == typeof port && (port = Number.parseInt(port, 10)), strictPort && (tryLimits = 1);
5845
- let { createServer } = await import("node:net"), original = port, found = !1, attempts = 0;
5846
- for(; !found && attempts <= tryLimits;)try {
5847
- await new Promise((resolve, reject)=>{
5848
- let server = createServer();
5849
- server.unref(), server.on('error', reject), server.listen({
5850
- port,
5851
- host
5852
- }, ()=>{
5853
- if (0 === port) {
5854
- let address = server.address();
5855
- address && 'string' != typeof address && (port = address.port);
5856
- }
5857
- found = !0, server.close(resolve);
5858
- });
5859
- });
5860
- } catch (e) {
5861
- if (!(e instanceof Error) || !('code' in e) || 'EADDRINUSE' !== e.code) throw e;
5862
- port++, attempts++;
5863
- }
5864
- if (!found) throw Error(`${color.dim('[rsbuild:server]')} Failed to find an available port after ${tryLimits + 1} attempts, starting from ${color.yellow(original)}.`);
5865
- if (0 !== original && port !== original && strictPort) throw Error(`${color.dim('[rsbuild:server]')} Port ${color.yellow(original)} is occupied, please choose another one.`);
5866
- return port;
5867
- }, resolvePort = async (config, lastPort)=>{
5868
- let { host, port: originalPort, strictPort } = config.server, preferredPort = 0 === originalPort ? lastPort : void 0, port = await getPort({
5869
- host,
5870
- port: preferredPort ?? originalPort,
5871
- strictPort: void 0 === preferredPort && strictPort
5872
- }), portTip = 0 !== originalPort && port !== originalPort ? `port ${originalPort} is in use, ${color.yellow(`using port ${port}.`)}` : void 0;
5873
- return {
5874
- port,
5875
- portTip
5876
- };
5877
- }, WILDCARD_HOSTS = new Set([
5878
- ALL_INTERFACES_IPV4,
5879
- '::',
5880
- '0000:0000:0000:0000:0000:0000:0000:0000'
5881
- ]), LOOPBACK_HOSTS = new Set([
5882
- LOCALHOST,
5883
- '127.0.0.1',
5884
- '::1',
5885
- '0000:0000:0000:0000:0000:0000:0000:0001'
5886
- ]), isLoopbackHost = (host)=>LOOPBACK_HOSTS.has(host), getHostInUrl = async (host)=>{
5887
- if (host === ALL_INTERFACES_IPV4 || host === LOCALHOST) return LOCALHOST;
5888
- let { isIPv6 } = await import("node:net");
5889
- return isIPv6(host) ? '::' === host ? '[::1]' : `[${host}]` : host;
5890
- }, concatUrl = ({ host, port, protocol })=>`${protocol}://${host}:${port}`, LOCAL_LABEL = 'Local: ', NETWORK_LABEL = 'Network: ', getUrlLabel = (url)=>{
5891
- try {
5892
- let { hostname } = new URL(url);
5893
- return isLoopbackHost(hostname) ? LOCAL_LABEL : NETWORK_LABEL;
5894
- } catch {
5895
- return NETWORK_LABEL;
5896
- }
5897
- }, getAddressUrls = async ({ protocol, port, host })=>{
5898
- if (host && host !== ALL_INTERFACES_IPV4) {
5899
- let url = concatUrl({
5900
- port,
5901
- host: await getHostInUrl(host),
5902
- protocol
5903
- });
5904
- return [
5905
- {
5906
- label: isLoopbackHost(host) ? LOCAL_LABEL : NETWORK_LABEL,
5907
- url
5908
- }
5909
- ];
5910
- }
5911
- let urls = [], seen = new Set(), hasLocal = !1;
5912
- for (let [name, infos] of Object.entries(node_os.networkInterfaces()))for (let info of infos ?? []){
5913
- let family = info.family;
5914
- !('IPv4' !== family && 4 !== family || seen.has(info.address)) && (seen.add(info.address), isLoopbackHost(info.address) || info.internal ? hasLocal || (urls.push({
5915
- label: LOCAL_LABEL,
5916
- url: concatUrl({
5917
- host: LOCALHOST,
5918
- port,
5919
- protocol
5920
- })
5921
- }), hasLocal = !0) : urls.push({
5922
- label: NETWORK_LABEL,
5923
- name,
5924
- url: concatUrl({
5925
- host: info.address,
5926
- port,
5927
- protocol
5928
- })
5929
- }));
5930
- }
5931
- return urls;
5932
- };
5933
- function getServerTerminator(server) {
5934
- let listened = !1, pendingSockets = new Set(), onConnection = (socket)=>{
5935
- pendingSockets.add(socket), socket.on('close', ()=>{
5936
- pendingSockets.delete(socket);
5937
- });
5938
- };
5939
- return server.on('connection', onConnection), server.on('secureConnection', onConnection), server.once('listening', ()=>{
5940
- listened = !0;
5941
- }), ()=>new Promise((resolve, reject)=>{
5942
- for (let socket of pendingSockets)socket.destroy();
5943
- listened ? server.close((err)=>{
5944
- err ? reject(err) : resolve();
5945
- }) : resolve();
5946
- });
5947
- }
5948
- function escapeHtml(text) {
5949
- return text ? text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;') : '';
5950
- }
5951
5796
  let supportedChromiumBrowsers = [
5952
5797
  'Google Chrome Canary',
5953
5798
  'Google Chrome Dev',
@@ -5962,14 +5807,14 @@ let supportedChromiumBrowsers = [
5962
5807
  async function openBrowser(url, logger) {
5963
5808
  let browser = process.env.BROWSER, browserArgs = process.env.BROWSER_ARGS;
5964
5809
  if ('darwin' === process.platform && (!browser || !browserArgs) && (!browser || supportedChromiumBrowsers.includes(mapChromiumBrowserName(browser)))) {
5965
- let { execFile } = await import("node:child_process"), execFileAsync = promisify(execFile), getDefaultBrowserForAppleScript = async ()=>{
5966
- let { stdout: ps } = await execFileAsync('ps', [
5967
- 'cax'
5968
- ]);
5969
- return supportedChromiumBrowsers.find((b)=>ps.includes(b));
5970
- };
5810
+ let { execFile } = await import("node:child_process"), execFileAsync = promisify(execFile);
5971
5811
  try {
5972
- let chromiumBrowser = browser ? mapChromiumBrowserName(browser) : await getDefaultBrowserForAppleScript();
5812
+ let chromiumBrowser = browser ? mapChromiumBrowserName(browser) : await (async ()=>{
5813
+ let { stdout: ps } = await execFileAsync('ps', [
5814
+ 'cax'
5815
+ ]);
5816
+ return supportedChromiumBrowsers.find((b)=>ps.includes(b));
5817
+ })();
5973
5818
  if (chromiumBrowser) return await execFileAsync("osascript", [
5974
5819
  "openChrome.applescript",
5975
5820
  encodeURI(url),
@@ -6037,18 +5882,22 @@ let getServerUrlFromClientConfig = async (config, context)=>{
6037
5882
  let protocol = client.protocol ? `${'wss' === client.protocol ? 'https' : 'http'}:` : '', hostname = await getHostInUrl(client.host || devServer.hostname), port = client.port && '<port>' !== client.port ? client.port : devServer.port;
6038
5883
  return `${protocol}//${hostname}:${port}`;
6039
5884
  };
6040
- function recursiveChunkGroup(chunkGroup, visited = new Set()) {
6041
- if (visited.has(chunkGroup)) return [];
5885
+ function recursiveChunkGroup(chunkGroup, visited, names) {
5886
+ if (visited.has(chunkGroup)) return;
6042
5887
  visited.add(chunkGroup);
6043
5888
  let parents = chunkGroup.getParents();
6044
- return parents.length ? parents.flatMap((chunkParent)=>recursiveChunkGroup(chunkParent, visited)) : [
6045
- chunkGroup.name
6046
- ];
5889
+ if (!parents.length) {
5890
+ let { name } = chunkGroup;
5891
+ name && names.add(name);
5892
+ return;
5893
+ }
5894
+ for (let parent of parents)recursiveChunkGroup(parent, visited, names);
6047
5895
  }
6048
5896
  function recursiveChunkEntryNames(chunk) {
6049
- let [...chunkGroups] = chunk.groupsIterable;
5897
+ let names = new Set(), visited = new Set();
5898
+ for (let chunkGroup of chunk.groupsIterable)recursiveChunkGroup(chunkGroup, visited, names);
6050
5899
  return [
6051
- ...new Set(chunkGroups.flatMap((chunkGroup)=>recursiveChunkGroup(chunkGroup)).filter((name)=>!!name))
5900
+ ...names
6052
5901
  ];
6053
5902
  }
6054
5903
  function isChunksFiltered(chunkName, includeChunks, excludeChunks) {
@@ -6058,7 +5907,7 @@ function doesChunkBelongToHtml({ chunk, htmlPluginData }) {
6058
5907
  let { options } = htmlPluginData.plugin;
6059
5908
  return recursiveChunkEntryNames(chunk).some((chunkName)=>isChunksFiltered(chunkName, options?.chunks, options?.excludeChunks));
6060
5909
  }
6061
- 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/cbeeb1bf16831c5d12121244c2e0e825d7a61324a587214ca9e44e464c6b1496/node_modules/rspack-manifest-plugin/dist/index.js"))), isCSSPath = (filePath)=>filePath.endsWith('.css');
5910
+ 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/17497e64d22a6c2a8eb2700029cf278579ead3c64963d770513f8f60bb2e2fa4/node_modules/rspack-manifest-plugin/dist/index.js"))), isCSSPath = (filePath)=>filePath.endsWith('.css');
6062
5911
  function normalizeManifestObjectConfig(manifest) {
6063
5912
  let defaultOptions = {
6064
5913
  prefix: !0,
@@ -6098,13 +5947,13 @@ function pluginModuleFederation() {
6098
5947
  }
6099
5948
  };
6100
5949
  }
6101
- function getPublicPath({ isDev, config, context }) {
5950
+ async function getPublicPath({ isDev, config, context }) {
6102
5951
  let { dev, output, server } = config, publicPath = "/";
6103
5952
  if (isDev) {
6104
5953
  if ('string' == typeof dev.assetPrefix) publicPath = dev.assetPrefix;
6105
5954
  else if (dev.assetPrefix) {
6106
- let protocol = context.devServer?.https ? 'https' : 'http', hostname = context.devServer?.hostname || LOCALHOST;
6107
- publicPath = hostname === ALL_INTERFACES_IPV4 ? `${protocol}://localhost:<port>/` : `${protocol}://${hostname}:<port>/`, server.base && '/' !== server.base && (publicPath = urlJoin(publicPath, server.base));
5955
+ let protocol = context.devServer?.https ? 'https' : 'http', host = context.devServer?.hostname || LOCALHOST, hostname = WILDCARD_HOSTS.has(host) ? LOCALHOST : await getHostInUrl(host);
5956
+ publicPath = `${protocol}://${hostname}:<port>/`, server.base && '/' !== server.base && (publicPath = urlJoin(publicPath, server.base));
6108
5957
  }
6109
5958
  } else 'string' == typeof output.assetPrefix && (publicPath = output.assetPrefix);
6110
5959
  let defaultPort = server.port ?? 3000;
@@ -6160,7 +6009,7 @@ function extractChunks(compilation, includeType) {
6160
6009
  ];
6161
6010
  return void 0 === includeType || 'async-chunks' === includeType ? chunks.filter(isAsyncChunk) : 'initial' === includeType ? chunks.filter((chunk)=>!isAsyncChunk(chunk)) : 'all-chunks' === includeType ? chunks : 'all-assets' === includeType ? [
6162
6011
  {
6163
- files: Object.keys(compilation.assets).filter((file)=>!LICENSE_ASSET_REGEX.test(file))
6012
+ files: getAssetNames(compilation).filter((file)=>!LICENSE_ASSET_REGEX.test(file))
6164
6013
  }
6165
6014
  ] : chunks;
6166
6015
  }
@@ -6203,6 +6052,7 @@ function generateLinks(options, type, compilation, data, HTMLCount, isDev) {
6203
6052
  chunk.auxiliaryFiles ?? []
6204
6053
  ])for (let file of files)isDev && file.endsWith('.hot-update.js') || file.endsWith('.map') || uniqueFiles.add(file);
6205
6054
  let sortedFilteredFiles = ((files, include, exclude)=>{
6055
+ if (!include && !exclude) return files;
6206
6056
  let includeRegExp = [], excludeRegExp = [], includeFn = [], excludeFn = [];
6207
6057
  if (include) for (let item of helpers_castArray(include))'string' == typeof item ? includeRegExp.push(new RegExp(item)) : isFunction(item) ? includeFn.push(item) : includeRegExp.push(item);
6208
6058
  if (exclude) for (let item of helpers_castArray(exclude))'string' == typeof item ? excludeRegExp.push(new RegExp(item)) : isFunction(item) ? excludeFn.push(item) : excludeRegExp.push(item);
@@ -6301,6 +6151,38 @@ async function applyProfile(root, filterValue, traceLayer, traceOutput) {
6301
6151
  let filter = resolveLayer(filterValue);
6302
6152
  return isTerminalTraceOutput(traceOutput) || await ensureFileDir(traceOutput), await core_rspack.experiments.globalTrace.register(filter, traceLayer, traceOutput), traceOutput;
6303
6153
  }
6154
+ let copyPublicDir = async (publicDir, distPaths, ignore)=>{
6155
+ let shouldCopy;
6156
+ if (ignore?.length) {
6157
+ let { globSync } = await getTinyglobby(), ignoredSet = new Set(globSync(ignore, {
6158
+ cwd: publicDir,
6159
+ absolute: !1,
6160
+ dot: !0,
6161
+ onlyFiles: !1
6162
+ }).map((item)=>item.replace(/\\/g, '/').replace(/\/$/, '')));
6163
+ shouldCopy = (source)=>{
6164
+ let relativePath = node_path.relative(publicDir, source);
6165
+ if (!relativePath) return !0;
6166
+ let normalizedPath = relativePath.replace(/\\/g, '/');
6167
+ return !ignoredSet.has(normalizedPath);
6168
+ };
6169
+ }
6170
+ try {
6171
+ await Promise.all(distPaths.map(async (distPath)=>{
6172
+ isDeno && node_fs.existsSync(distPath) && await node_fs.promises.rm(distPath, {
6173
+ recursive: !0,
6174
+ force: !0
6175
+ }), await node_fs.promises.cp(publicDir, distPath, {
6176
+ recursive: !0,
6177
+ dereference: !0,
6178
+ mode: node_fs.constants.COPYFILE_FICLONE,
6179
+ filter: shouldCopy
6180
+ });
6181
+ }));
6182
+ } catch (err) {
6183
+ throw err instanceof Error && (err.message = `Failed to copy public directory '${color.yellow(publicDir)}' to output directory. To disable public directory copying, set \`${color.cyan('server.publicDir: false')}\` in your config.\n${err.message}`), err;
6184
+ }
6185
+ };
6304
6186
  function getForceSplittingGroups(forceSplitting, strategy) {
6305
6187
  let cacheGroups = {};
6306
6188
  for (let [key, regexp] of Array.isArray(forceSplitting) ? forceSplitting.map((regexp, index)=>[
@@ -6583,7 +6465,11 @@ async function getFileFromUrl(url, outputFileSystem, context) {
6583
6465
  for (let [index, distPath] of distPaths.entries()){
6584
6466
  let prefix = publicPathnames[index];
6585
6467
  if (prefix && '/' !== prefix && isUrlPathUnderBase(pathname, prefix)) {
6586
- let candidatePath = node_path.join(distPath, pathname.slice(prefix.length));
6468
+ let relativePathname = pathname.slice(prefix.length);
6469
+ if (hasUpPath && UP_PATH_REGEXP.test(node_path.normalize(`./${relativePathname}`))) return {
6470
+ errorCode: 403
6471
+ };
6472
+ let candidatePath = node_path.join(distPath, relativePathname);
6587
6473
  if (hasUpPath) {
6588
6474
  let relativePath = node_path.relative(distPath, candidatePath);
6589
6475
  if (UP_PATH_REGEXP.test(relativePath)) return {
@@ -6636,7 +6522,6 @@ function parseTokenList(str) {
6636
6522
  }
6637
6523
  return start !== end && list.push(str.substring(start, end)), list;
6638
6524
  }
6639
- var on_finished_default = compatGetDefaultExport(rspackRequire("../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/on-finished/2.4.1/cf4b90e733493a0ce70ba421a5b37153ad39360f9513e36b25d2e49f57047a9b/node_modules/on-finished/index.js"));
6640
6525
  function getEtag(stat) {
6641
6526
  let mtime = stat.mtime.getTime().toString(16), size = stat.size.toString(16);
6642
6527
  return `W/"${size}-${mtime}"`;
@@ -6654,7 +6539,7 @@ function getContentType(str) {
6654
6539
  }
6655
6540
  let BYTES_RANGE_REGEXP = /^ *bytes/i;
6656
6541
  function getValueContentRangeHeader(type, size, range) {
6657
- return `${type} ${range ? `${range.start}-${range.end}` : '*'}:${size}`.replace(':', '/');
6542
+ return `${type} ${range ? `${range.start}-${range.end}` : '*'}/${size}`;
6658
6543
  }
6659
6544
  function parseHttpDate(date) {
6660
6545
  let timestamp = date && Date.parse(date);
@@ -6744,12 +6629,7 @@ function destroyStream(stream, suppress) {
6744
6629
  'number' == typeof fd && this.close();
6745
6630
  }), 'function' == typeof stream.addListener && suppress && (stream.removeAllListeners('error'), stream.addListener('error', ()=>{}));
6746
6631
  }
6747
- let getRangeParser = cachedImport_cachedImport(()=>import("./range-parser.js").then(createFakeNamespaceObject.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/range-parser/1.3.0/d49e5dcb9d0e39475844e240fad8cd1db6a58f4144f7ede43d9755e2fce5babc/node_modules/range-parser/index.js", 23))), parseRangeHeaders = async (value)=>{
6748
- let { default: rangeParser } = await getRangeParser(), [len, rangeHeader] = value.split('|');
6749
- return rangeParser(Number(len), rangeHeader, {
6750
- combine: !0
6751
- });
6752
- };
6632
+ let getRangeParser = cachedImport_cachedImport(()=>import("./range-parser.js").then(createFakeNamespaceObject.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/range-parser/1.3.0/d49e5dcb9d0e39475844e240fad8cd1db6a58f4144f7ede43d9755e2fce5babc/node_modules/range-parser/index.js", 23)));
6753
6633
  function sendError(res, code) {
6754
6634
  let content = {
6755
6635
  400: 'Bad Request',
@@ -6774,22 +6654,21 @@ function sendError(res, code) {
6774
6654
  let byteLength = Buffer.byteLength(document);
6775
6655
  res.setHeader('Content-Length', byteLength), res.end(document);
6776
6656
  }
6777
- let filterWebEnvironments = (environmentList)=>environmentList.filter((environment)=>isWebTarget(environment.config.output.target));
6778
- function createAssetsMiddleware(context, ready, outputFileSystem) {
6779
- let { logger } = context, webEnvironments = filterWebEnvironments(context.environmentList), assetContext = {
6657
+ function createAssetsMiddleware(context, { waitForAssets, waitForBuild }, outputFileSystem) {
6658
+ let { logger } = context, servedEnvironments = context.environmentList.filter((environment)=>isServingAssets(environment.config)), assetContext = {
6780
6659
  ...context,
6781
- environmentList: webEnvironments,
6782
- publicPathnames: webEnvironments.map((environment)=>context.publicPathnames[environment.index])
6660
+ environmentList: servedEnvironments,
6661
+ publicPathnames: servedEnvironments.map((environment)=>context.publicPathnames[environment.index])
6783
6662
  };
6784
6663
  return async function assetsMiddleware(req, res, next) {
6785
- async function goNext() {
6664
+ function goNext() {
6786
6665
  return new Promise((resolve)=>{
6787
- ready(()=>{
6666
+ waitForBuild(()=>{
6788
6667
  next(), resolve();
6789
6668
  });
6790
6669
  });
6791
6670
  }
6792
- req.method && 'GET' !== req.method && 'HEAD' !== req.method ? await goNext() : ready(async function processRequest() {
6671
+ req.method && 'GET' !== req.method && 'HEAD' !== req.method ? await goNext() : waitForAssets(async function processRequest() {
6793
6672
  let readStream;
6794
6673
  if (!req.url) return void await goNext();
6795
6674
  let resolved = await getFileFromUrl(req.url, outputFileSystem, assetContext);
@@ -6820,7 +6699,12 @@ function createAssetsMiddleware(context, ready, outputFileSystem) {
6820
6699
  }
6821
6700
  }
6822
6701
  if (rangeHeader) {
6823
- let parsedRanges = await parseRangeHeaders(`${size}|${rangeHeader}`);
6702
+ let parsedRanges = await (async (value)=>{
6703
+ let { default: rangeParser } = await getRangeParser(), [len, rangeHeader] = value.split('|');
6704
+ return rangeParser(Number(len), rangeHeader, {
6705
+ combine: !0
6706
+ });
6707
+ })(`${size}|${rangeHeader}`);
6824
6708
  if (isRangeFresh(req.headers, res) || (parsedRanges = []), -1 === parsedRanges) {
6825
6709
  logger.error("[rsbuild:middleware] Unsatisfiable range for 'Range' header."), res.setHeader('Content-Range', getValueContentRangeHeader('bytes', size)), sendError(res, 416);
6826
6710
  return;
@@ -6852,14 +6736,36 @@ function createAssetsMiddleware(context, ready, outputFileSystem) {
6852
6736
  default:
6853
6737
  sendError(res, 500);
6854
6738
  }
6855
- }), readStream.pipe(res), on_finished_default()(res, cleanup);
6739
+ }), readStream.pipe(res), finished(res, cleanup);
6856
6740
  });
6857
6741
  };
6858
6742
  }
6743
+ function setupMemoryFileSystemCleanup(fileSystem, compilers) {
6744
+ if (compilers.some((compiler)=>compiler.options.output.clean)) return;
6745
+ let lastSeenByCompiler = compilers.map(()=>new Map());
6746
+ for (let [index, compiler] of compilers.entries()){
6747
+ let lastHash, lastSeen = lastSeenByCompiler[index], generation = 0;
6748
+ compiler.hooks.afterEmit.tap('rsbuild:clean-memory-filesystem', (compilation)=>{
6749
+ if (compilation.errors.length) return;
6750
+ compilation.hash !== lastHash && (generation++, lastHash = compilation.hash);
6751
+ let outputPath = compilation.getPath(compiler.outputPath);
6752
+ for (let name of getAssetNames(compilation)){
6753
+ let queryIndex = name.indexOf('?'), filename = -1 === queryIndex ? name : name.slice(0, queryIndex), filePath = join(outputPath, filename);
6754
+ lastSeen.set(filePath, generation);
6755
+ }
6756
+ for (let [filePath, seen] of lastSeen)if (!(seen >= generation - 1) && (lastSeen.delete(filePath), !lastSeenByCompiler.some((assets)=>assets.has(filePath)))) try {
6757
+ fileSystem.unlinkSync(filePath);
6758
+ } catch (error) {
6759
+ if ('ENOENT' !== error.code) throw error;
6760
+ }
6761
+ });
6762
+ }
6763
+ }
6859
6764
  async function setupOutputFileSystem(writeAllToDisk, compilers) {
6860
6765
  if (!writeAllToDisk) {
6861
6766
  let { createMemoryFileSystem } = await import("./memfs.js"), outputFileSystem = createMemoryFileSystem();
6862
6767
  for (let compiler of compilers)compiler.outputFileSystem = outputFileSystem;
6768
+ setupMemoryFileSystemCleanup(outputFileSystem, compilers);
6863
6769
  }
6864
6770
  let compiler = compilers.find((compiler)=>!!compiler.outputFileSystem);
6865
6771
  return compiler?.outputFileSystem ?? node_fs;
@@ -6928,88 +6834,6 @@ init(
6928
6834
  name: void 0
6929
6835
  }).apply(compiler);
6930
6836
  }
6931
- let assets_middleware_assetsMiddleware = async ({ config, compiler, context, socketServer, resolvedPort })=>{
6932
- let watching, { logger } = context, resolvedHost = await resolveHostname(config.server.host), { environmentList } = context;
6933
- applyToCompiler(compiler, (compiler, index)=>{
6934
- let environment = environmentList[index];
6935
- if (!environment) return;
6936
- let token = environment.webSocketToken;
6937
- token && (applyHMREntry({
6938
- token,
6939
- config: environment.config,
6940
- compiler,
6941
- resolvedHost,
6942
- resolvedPort
6943
- }), (({ context, compiler, token, socketServer, liveReload })=>{
6944
- if (((compiler)=>{
6945
- let { target } = compiler.options;
6946
- return !!target && (Array.isArray(target) ? target.includes('node') : 'node' === target);
6947
- })(compiler)) return;
6948
- let errorsCount = null, warningsCount = null;
6949
- compiler.hooks.invalid.tap('rsbuild-dev-server', (fileName)=>{
6950
- errorsCount = null, warningsCount = null, 'string' == typeof fileName && fileName.endsWith('.html') && normalizeLiveReload(liveReload).html && socketServer.sendMessage({
6951
- type: 'full-reload'
6952
- }, token);
6953
- }), compiler.hooks.done.tap('rsbuild-dev-server', (stats)=>{
6954
- let { errors, warnings } = stats.compilation;
6955
- if (errors.length === errorsCount && warnings.length === warningsCount) return;
6956
- let isRecalled = null !== errorsCount || null !== warningsCount;
6957
- if (errorsCount = errors.length, warningsCount = warnings.length, isRecalled) {
6958
- let tsErrors = errors.filter(isTsError), tsWarnings = warnings.filter(isTsError);
6959
- if (!tsErrors.length && !tsWarnings.length) return;
6960
- let { stats: statsJson } = context.buildState, handleTsIssues = (issues, type, sendFn)=>{
6961
- let statsIssues = issues.map((item)=>pick(item, [
6962
- 'message',
6963
- 'file'
6964
- ]));
6965
- statsJson && (statsJson[type] = statsJson[type] ? [
6966
- ...statsJson[type],
6967
- ...statsIssues
6968
- ] : statsIssues), sendFn(statsIssues, token);
6969
- };
6970
- if (tsErrors.length > 0) return void handleTsIssues(tsErrors, 'errors', (issues, token)=>{
6971
- socketServer.sendError(issues, token);
6972
- });
6973
- if (tsWarnings.length > 0) return void handleTsIssues(tsWarnings, 'warnings', (issues, token)=>{
6974
- socketServer.sendWarning(issues, token);
6975
- });
6976
- }
6977
- });
6978
- })({
6979
- context,
6980
- compiler,
6981
- socketServer,
6982
- token,
6983
- liveReload: environment.config.dev.liveReload
6984
- }));
6985
- });
6986
- let compilers = compiler_isMultiCompiler(compiler) ? compiler.compilers : [
6987
- compiler
6988
- ], callbacks = [], flushCallbacks = ()=>{
6989
- for (let callback of callbacks.splice(0))callback();
6990
- };
6991
- compiler.hooks.done.tap('rsbuild-dev-middleware', ()=>{
6992
- process.nextTick(()=>{
6993
- 'done' === context.buildState.status && flushCallbacks();
6994
- });
6995
- });
6996
- let writeToDiskList = environmentList.map((environment)=>environment.config.dev.writeToDisk);
6997
- writeToDiskList.some(Boolean) && setupWriteToDisk(compilers, writeToDiskList, logger);
6998
- let instance = createAssetsMiddleware(context, (callback)=>{
6999
- 'done' === context.buildState.status || 'failed' === context.buildState.status ? callback() : callbacks.push(callback);
7000
- }, await setupOutputFileSystem(writeToDiskList.every((writeToDisk)=>!0 === writeToDisk), compilers));
7001
- return instance.watch = ()=>{
7002
- if (compiler.watching) watching = compiler.watching;
7003
- else {
7004
- let watchOptions = compilers.length > 1 ? compilers.map(({ options })=>options.watchOptions || {}) : compilers[0].options.watchOptions || {};
7005
- watching = compiler.watch(watchOptions, (error)=>{
7006
- error && (context.buildState.status = 'failed', context.buildState.hasErrors = !0, process.nextTick(flushCallbacks), error.message?.includes('× Error:') && (error.message = error.message.replace('× Error:', '').trim()), logger.error(error));
7007
- });
7008
- }
7009
- }, instance.close = (callback = noop)=>{
7010
- watching?.close(callback);
7011
- }, instance;
7012
- };
7013
6837
  var UNKNOWN_FUNCTION = '<unknown>';
7014
6838
  function stack_trace_parser_esm_parse(stackString) {
7015
6839
  return stackString.split('\n').reduce(function(stack, line) {
@@ -7101,16 +6925,6 @@ let getTraceMapping = cachedImport_cachedImport(()=>import("./trace-mapping.js")
7101
6925
  } catch (error) {
7102
6926
  error instanceof Error && context.logger.debug('failed to map source map position:', error);
7103
6927
  }
7104
- }, resolveOriginalLocation = async (stackFrames, fs, context, cache)=>{
7105
- let frame = stackFrames.find((frame)=>null !== frame.file && null !== frame.column && null !== frame.lineNumber && SCRIPT_REGEX.test(frame.file));
7106
- if (!frame) return;
7107
- let parsedFrame = await parseFrame(frame, fs, context, cache);
7108
- if (!parsedFrame) return;
7109
- let { sourceMapPath, originalPosition } = parsedFrame;
7110
- return {
7111
- frame,
7112
- location: formatOriginalLocation(sourceMapPath, originalPosition, context)
7113
- };
7114
6928
  }, formatOriginalLocation = (sourceMapPath, originalMapping, context)=>{
7115
6929
  let { source, line, column } = originalMapping;
7116
6930
  if (!source) return;
@@ -7123,39 +6937,23 @@ let getTraceMapping = cachedImport_cachedImport(()=>import("./trace-mapping.js")
7123
6937
  }, formatFrameLocation = (frame)=>{
7124
6938
  let { file, lineNumber, column } = frame;
7125
6939
  if (file) return null !== lineNumber ? null !== column ? `${file}:${lineNumber}:${column}` : `${file}:${lineNumber}` : file;
7126
- }, formatFullStack = async (stackFrames, context, fs, cache)=>{
7127
- let formattedFrames = [];
7128
- for (let frame of stackFrames){
7129
- let location, parsedFrame = await parseFrame(frame, fs, context, cache), { methodName } = frame, parts = [];
7130
- isValidMethodName(methodName) && parts.push(methodName);
7131
- let parsed = !1;
7132
- if (parsedFrame) {
7133
- let { sourceMapPath, originalPosition } = parsedFrame, originalLocation = formatOriginalLocation(sourceMapPath, originalPosition, context);
7134
- originalLocation && (location = originalLocation, parts.push(originalLocation), parsed = !0);
7135
- }
7136
- if (!parsed && isVerbose(context.logger)) {
7137
- let frameString = formatFrameLocation(frame);
7138
- frameString && (location = frameString, parts.push(frameString));
7139
- }
7140
- let [first, second] = parts;
7141
- if (first) {
7142
- let isRspackRuntime = isRspackRuntimeStack(methodName) || isRspackRuntimeStack(location);
7143
- formattedFrames.push({
7144
- text: second ? `\n at ${first} (${second})` : `\n at ${first}`,
7145
- isRspackRuntime,
7146
- hasLocation: void 0 !== location
7147
- });
7148
- }
7149
- }
7150
- let shouldFilterRspackRuntime = formattedFrames.some((frame)=>!frame.isRspackRuntime && frame.hasLocation);
7151
- return formattedFrames.filter((frame)=>!(shouldFilterRspackRuntime && frame.isRspackRuntime)).map((frame)=>frame.text).join('');
7152
6940
  }, formatBrowserErrorLog = async (message, context, fs, stackTrace, stackFrames, cache)=>{
7153
6941
  var log;
7154
6942
  let log1 = color.red(message);
7155
6943
  if (stackFrames?.length) switch(stackTrace){
7156
6944
  case 'summary':
7157
6945
  {
7158
- let resolved = await resolveOriginalLocation(stackFrames, fs, context, cache);
6946
+ let resolved = await (async (stackFrames, fs, context, cache)=>{
6947
+ let frame = stackFrames.find((frame)=>null !== frame.file && null !== frame.column && null !== frame.lineNumber && SCRIPT_REGEX.test(frame.file));
6948
+ if (!frame) return;
6949
+ let parsedFrame = await parseFrame(frame, fs, context, cache);
6950
+ if (!parsedFrame) return;
6951
+ let { sourceMapPath, originalPosition } = parsedFrame;
6952
+ return {
6953
+ frame,
6954
+ location: formatOriginalLocation(sourceMapPath, originalPosition, context)
6955
+ };
6956
+ })(stackFrames, fs, context, cache);
7159
6957
  if (!resolved) break;
7160
6958
  let { frame, location } = resolved, { methodName } = frame, suffix = '';
7161
6959
  isValidMethodName(methodName) && (suffix += ` at ${methodName}`), location && (suffix += ` (${location})`), log1 += suffix ? color.dim(suffix) : '';
@@ -7163,7 +6961,33 @@ let getTraceMapping = cachedImport_cachedImport(()=>import("./trace-mapping.js")
7163
6961
  }
7164
6962
  case 'full':
7165
6963
  {
7166
- let fullStack = await formatFullStack(stackFrames, context, fs, cache);
6964
+ let fullStack = await (async (stackFrames, context, fs, cache)=>{
6965
+ let formattedFrames = [];
6966
+ for (let frame of stackFrames){
6967
+ let location, parsedFrame = await parseFrame(frame, fs, context, cache), { methodName } = frame, parts = [];
6968
+ isValidMethodName(methodName) && parts.push(methodName);
6969
+ let parsed = !1;
6970
+ if (parsedFrame) {
6971
+ let { sourceMapPath, originalPosition } = parsedFrame, originalLocation = formatOriginalLocation(sourceMapPath, originalPosition, context);
6972
+ originalLocation && (location = originalLocation, parts.push(originalLocation), parsed = !0);
6973
+ }
6974
+ if (!parsed && isVerbose(context.logger)) {
6975
+ let frameString = formatFrameLocation(frame);
6976
+ frameString && (location = frameString, parts.push(frameString));
6977
+ }
6978
+ let [first, second] = parts;
6979
+ if (first) {
6980
+ let isRspackRuntime = isRspackRuntimeStack(methodName) || isRspackRuntimeStack(location);
6981
+ formattedFrames.push({
6982
+ text: second ? `\n at ${first} (${second})` : `\n at ${first}`,
6983
+ isRspackRuntime,
6984
+ hasLocation: void 0 !== location
6985
+ });
6986
+ }
6987
+ }
6988
+ let shouldFilterRspackRuntime = formattedFrames.some((frame)=>!frame.isRspackRuntime && frame.hasLocation);
6989
+ return formattedFrames.filter((frame)=>!(shouldFilterRspackRuntime && frame.isRspackRuntime)).map((frame)=>frame.text).join('');
6990
+ })(stackFrames, context, fs, cache);
7167
6991
  fullStack && (log1 += fullStack);
7168
6992
  }
7169
6993
  }
@@ -7199,12 +7023,12 @@ let closeCode = [
7199
7023
  49
7200
7024
  ];
7201
7025
  function ansiHTML(text) {
7202
- let ansiCodes = [], ret = text.replace(/\x1B\[([0-9;]+)m/g, (_match, sequences)=>{
7026
+ let openSpans = 0, ret = text.replace(/\x1B\[([0-9;]+)m/g, (_match, sequences)=>{
7203
7027
  let style = '';
7204
7028
  for (let seq of sequences.split(';'))styles[seq] && (style += `${styles[seq]};`);
7205
- return style ? (ansiCodes.push(sequences), `<span style="${style}">`) : closeCode.includes(Number(sequences)) && ansiCodes.length > 0 ? (ansiCodes.pop(), '</span>') : '';
7029
+ return style ? (openSpans++, `<span style="${style}">`) : closeCode.includes(Number(sequences)) && openSpans > 0 ? (openSpans--, '</span>') : '';
7206
7030
  });
7207
- return ansiCodes.length > 0 && (ret += Array(ansiCodes.length + 1).join('</span>')), ret;
7031
+ return openSpans > 0 && (ret += '</span>'.repeat(openSpans)), ret;
7208
7032
  }
7209
7033
  function formatDisplayPath(filePath, isAbsolute, root) {
7210
7034
  if (NODE_MODULES_REGEX.test(filePath)) for (let needle of [
@@ -7250,6 +7074,7 @@ class SocketServer {
7250
7074
  getOutputFileSystem;
7251
7075
  reportedBrowserLogs = new Set();
7252
7076
  currentHash = new Map();
7077
+ environmentStats = new Map();
7253
7078
  onSocketConnect;
7254
7079
  constructor(context, options, getOutputFileSystem, onSocketConnect){
7255
7080
  this.context = context, this.options = options, this.getOutputFileSystem = getOutputFileSystem, this.onSocketConnect = onSocketConnect;
@@ -7257,7 +7082,7 @@ class SocketServer {
7257
7082
  upgrade = (req, socket, head)=>{
7258
7083
  if (!this.wsServer.shouldHandle(req)) return;
7259
7084
  let query = parseQueryString(req);
7260
- this.context.environmentList.map(({ webSocketToken })=>webSocketToken).includes(query.token) ? this.wsServer.handleUpgrade(req, socket, head, (connection)=>{
7085
+ this.context.environmentList.some(({ webSocketToken })=>webSocketToken === query.token) ? this.wsServer.handleUpgrade(req, socket, head, (connection)=>{
7261
7086
  this.wsServer.emit('connection', connection, req);
7262
7087
  }) : socket.destroy();
7263
7088
  };
@@ -7281,8 +7106,16 @@ class SocketServer {
7281
7106
  this.onConnect(socket, query.token);
7282
7107
  });
7283
7108
  }
7109
+ onEnvironmentDone(token, getStats) {
7110
+ 'done' !== this.context.buildState.status && this.socketsMap.has(token) && (this.environmentStats.set(token, getStats()), this.sendStats({
7111
+ token
7112
+ }));
7113
+ }
7114
+ clearEnvironmentStats(token) {
7115
+ this.environmentStats.delete(token);
7116
+ }
7284
7117
  onBuildDone() {
7285
- if (this.reportedBrowserLogs.clear(), this.ensureInitialChunks(), this.socketsMap.size) for (let token of this.socketsMap.keys())this.sendStats({
7118
+ if (this.environmentStats.clear(), this.reportedBrowserLogs.clear(), this.ensureInitialChunks(), this.socketsMap.size) for (let token of this.socketsMap.keys())this.sendStats({
7286
7119
  token
7287
7120
  });
7288
7121
  }
@@ -7326,7 +7159,7 @@ class SocketServer {
7326
7159
  for (let sockets of this.socketsMap.values())sockets.forEach((socket)=>{
7327
7160
  socket.close();
7328
7161
  });
7329
- return this.socketsMap.clear(), this.initialChunksMap.clear(), this.reportedBrowserLogs.clear(), new Promise((resolve, reject)=>{
7162
+ return this.socketsMap.clear(), this.initialChunksMap.clear(), this.environmentStats.clear(), this.currentHash.clear(), this.reportedBrowserLogs.clear(), new Promise((resolve, reject)=>{
7330
7163
  this.wsServer.close((err)=>{
7331
7164
  err ? reject(err) : resolve();
7332
7165
  });
@@ -7381,11 +7214,12 @@ class SocketServer {
7381
7214
  }
7382
7215
  getInitialChunks(stats) {
7383
7216
  let initialChunks = new Set(), { entrypoints } = stats;
7384
- if (!entrypoints) return initialChunks;
7217
+ if (!entrypoints) return;
7385
7218
  let entryNames = Object.keys(entrypoints);
7386
7219
  for(let entryIndex = 0; entryIndex < entryNames.length; entryIndex++){
7387
7220
  let chunks = entrypoints[entryNames[entryIndex]]?.chunks;
7388
- if (Array.isArray(chunks)) for(let index = 0; index < chunks.length; index++){
7221
+ if (!Array.isArray(chunks)) return;
7222
+ for(let index = 0; index < chunks.length; index++){
7389
7223
  let chunkName = chunks[index];
7390
7224
  void 0 !== chunkName && initialChunks.add('string' == typeof chunkName ? chunkName : String(chunkName));
7391
7225
  }
@@ -7396,10 +7230,19 @@ class SocketServer {
7396
7230
  for (let { webSocketToken } of this.context.environmentList){
7397
7231
  if (this.initialChunksMap.has(webSocketToken)) continue;
7398
7232
  let result = this.getStats(webSocketToken);
7399
- result && this.initialChunksMap.set(webSocketToken, this.getInitialChunks(result.stats));
7233
+ if (result) {
7234
+ let initialChunks = this.getInitialChunks(result.stats);
7235
+ initialChunks && this.initialChunksMap.set(webSocketToken, initialChunks);
7236
+ }
7400
7237
  }
7401
7238
  }
7402
7239
  getStats(token) {
7240
+ let environmentStats = this.environmentStats.get(token);
7241
+ if (environmentStats) return {
7242
+ stats: environmentStats,
7243
+ errors: getStatsErrors(environmentStats),
7244
+ warnings: getStatsWarnings(environmentStats)
7245
+ };
7403
7246
  let { stats } = this.context.buildState, environment = this.getEnvironmentByToken(token);
7404
7247
  if (!stats || !environment) return;
7405
7248
  let currentStats = stats;
@@ -7416,10 +7259,17 @@ class SocketServer {
7416
7259
  sendStats({ force = !1, token }) {
7417
7260
  let result = this.getStats(token);
7418
7261
  if (!result) return null;
7419
- let { stats, errors, warnings } = result, newInitialChunks = this.getInitialChunks(stats), initialChunks = this.initialChunksMap.get(token), shouldReload = stats.entrypoints && initialChunks && !isEqualSet(initialChunks, newInitialChunks);
7420
- if (this.initialChunksMap.set(token, newInitialChunks), shouldReload) return void this.sendMessage({
7262
+ let { stats, errors, warnings } = result, newInitialChunks = this.getInitialChunks(stats), initialChunks = this.initialChunksMap.get(token), shouldReload = newInitialChunks && initialChunks && !isEqualSet(initialChunks, newInitialChunks);
7263
+ if (newInitialChunks && this.initialChunksMap.set(token, newInitialChunks), shouldReload) return void this.sendMessage({
7421
7264
  type: 'full-reload'
7422
7265
  }, token);
7266
+ if (this.environmentStats.has(token)) {
7267
+ stats.hash && (this.currentHash.set(token, stats.hash), this.sendMessage({
7268
+ type: 'early-update',
7269
+ data: stats.hash
7270
+ }, token));
7271
+ return;
7272
+ }
7423
7273
  if (stats.hash) {
7424
7274
  let prevHash = this.currentHash.get(token);
7425
7275
  if (this.currentHash.set(token, stats.hash), !force && 0 === errors.length && 0 === warnings.length && prevHash === stats.hash) return void this.sendMessage({
@@ -7470,7 +7320,110 @@ class BuildManager {
7470
7320
  }
7471
7321
  readFileSync = (fileName)=>'readFileSync' in this.outputFileSystem ? this.outputFileSystem.readFileSync(fileName, 'utf-8') : node_fs.readFileSync(fileName, 'utf-8');
7472
7322
  async setupCompilationMiddleware() {
7473
- let { config, context } = this, middleware = await assets_middleware_assetsMiddleware({
7323
+ let { config, context } = this, middleware = await (async ({ config, compiler, context, socketServer, resolvedPort })=>{
7324
+ let watching, allCompilers, webCompilers, earlyWebUpdates, { logger } = context, resolvedHost = await resolveHostname(config.server.host), { environmentList } = context, { allCompilers: allCompilers1, webCompilers: webCompilers1, earlyWebUpdates: earlyWebUpdates1 } = (earlyWebUpdates = (webCompilers = (allCompilers = compiler_isMultiCompiler(compiler) ? compiler.compilers : [
7325
+ compiler
7326
+ ]).filter((_, index)=>isWebTarget(environmentList[index].config.output.target))).length > 0 && webCompilers.length < allCompilers.length, {
7327
+ allCompilers,
7328
+ webCompilers,
7329
+ earlyWebUpdates
7330
+ }), canServeWebAssetsEarly = earlyWebUpdates1 && !environmentList.some((environment)=>isServingAssets(environment.config) && !isWebTarget(environment.config.output.target));
7331
+ applyToCompiler(compiler, (compiler, index)=>{
7332
+ let environment = environmentList[index];
7333
+ if (!environment) return;
7334
+ let token = environment.webSocketToken;
7335
+ !token || (applyHMREntry({
7336
+ token,
7337
+ config: environment.config,
7338
+ compiler,
7339
+ resolvedHost,
7340
+ resolvedPort
7341
+ }), isWebTarget(environment.config.output.target) && (({ context, compiler, token, socketServer, liveReload, earlyWebUpdates })=>{
7342
+ let errorsCount = null, warningsCount = null, reset = ()=>{
7343
+ errorsCount = null, warningsCount = null, socketServer.clearEnvironmentStats(token);
7344
+ };
7345
+ compiler.hooks.watchRun.tap('rsbuild-dev-server', reset), compiler.hooks.invalid.tap('rsbuild-dev-server', (fileName)=>{
7346
+ reset(), 'string' == typeof fileName && fileName.endsWith('.html') && normalizeLiveReload(liveReload).html && socketServer.sendMessage({
7347
+ type: 'full-reload'
7348
+ }, token);
7349
+ }), compiler.hooks.done.tap('rsbuild-dev-server', (stats)=>{
7350
+ let { errors, warnings } = stats.compilation;
7351
+ if (errors.length === errorsCount && warnings.length === warningsCount) return;
7352
+ null === errorsCount && null === warningsCount && earlyWebUpdates && !stats.hasErrors() && socketServer.onEnvironmentDone(token, ()=>getEarlyStats(stats));
7353
+ let isRecalled = null !== errorsCount || null !== warningsCount;
7354
+ if (errorsCount = errors.length, warningsCount = warnings.length, isRecalled) {
7355
+ let tsErrors = errors.filter(isTsError), tsWarnings = warnings.filter(isTsError);
7356
+ if (!tsErrors.length && !tsWarnings.length) return;
7357
+ let { stats: statsJson } = context.buildState, handleTsIssues = (issues, type, sendFn)=>{
7358
+ let statsIssues = issues.map((item)=>pick(item, [
7359
+ 'message',
7360
+ 'file'
7361
+ ]));
7362
+ statsJson && (statsJson[type] = statsJson[type] ? [
7363
+ ...statsJson[type],
7364
+ ...statsIssues
7365
+ ] : statsIssues), sendFn(statsIssues, token);
7366
+ };
7367
+ if (tsErrors.length > 0) return void handleTsIssues(tsErrors, 'errors', (issues, token)=>{
7368
+ socketServer.sendError(issues, token);
7369
+ });
7370
+ if (tsWarnings.length > 0) return void handleTsIssues(tsWarnings, 'warnings', (issues, token)=>{
7371
+ socketServer.sendWarning(issues, token);
7372
+ });
7373
+ }
7374
+ });
7375
+ })({
7376
+ context,
7377
+ compiler,
7378
+ socketServer,
7379
+ token,
7380
+ liveReload: environment.config.dev.liveReload,
7381
+ earlyWebUpdates: earlyWebUpdates1
7382
+ }));
7383
+ });
7384
+ let assetCallbacks = [], buildCallbacks = [], flushCallbacks = (callbacks)=>{
7385
+ for (let callback of callbacks.splice(0))callback();
7386
+ }, flushAllCallbacks = ()=>{
7387
+ flushCallbacks(assetCallbacks), flushCallbacks(buildCallbacks);
7388
+ };
7389
+ compiler.hooks.done.tap('rsbuild-dev-middleware', ()=>{
7390
+ process.nextTick(()=>{
7391
+ 'done' === context.buildState.status && flushAllCallbacks();
7392
+ });
7393
+ });
7394
+ let compiledWebCompilers = new Set(), isWebReady = ()=>canServeWebAssetsEarly && compiledWebCompilers.size === webCompilers1.length;
7395
+ if (canServeWebAssetsEarly) for (let item of webCompilers1){
7396
+ let reset = ()=>{
7397
+ compiledWebCompilers.delete(item);
7398
+ };
7399
+ item.hooks.invalid.tap('rsbuild-dev-middleware', reset), item.hooks.watchRun.tap('rsbuild-dev-middleware', reset), item.hooks.done.tap('rsbuild-dev-middleware', (stats)=>{
7400
+ !stats.hasErrors() && (compiledWebCompilers.add(item), isWebReady() && process.nextTick(()=>{
7401
+ isWebReady() && flushCallbacks(assetCallbacks);
7402
+ }));
7403
+ });
7404
+ }
7405
+ let writeToDiskList = environmentList.map((environment)=>environment.config.dev.writeToDisk);
7406
+ writeToDiskList.some(Boolean) && setupWriteToDisk(allCompilers1, writeToDiskList, logger);
7407
+ let outputFileSystem = await setupOutputFileSystem(writeToDiskList.every((writeToDisk)=>!0 === writeToDisk), allCompilers1), isBuildReady = ()=>'done' === context.buildState.status || 'failed' === context.buildState.status, instance = createAssetsMiddleware(context, {
7408
+ waitForAssets: (callback)=>{
7409
+ isBuildReady() || isWebReady() ? callback() : assetCallbacks.push(callback);
7410
+ },
7411
+ waitForBuild: (callback)=>{
7412
+ isBuildReady() ? callback() : buildCallbacks.push(callback);
7413
+ }
7414
+ }, outputFileSystem);
7415
+ return instance.watch = ()=>{
7416
+ if (compiler.watching) watching = compiler.watching;
7417
+ else {
7418
+ let watchOptions = allCompilers1.length > 1 ? allCompilers1.map(({ options })=>options.watchOptions || {}) : allCompilers1[0].options.watchOptions || {};
7419
+ watching = compiler.watch(watchOptions, (error)=>{
7420
+ error && (context.buildState.status = 'failed', context.buildState.hasErrors = !0, process.nextTick(flushAllCallbacks), error.message?.includes('× Error:') && (error.message = error.message.replace('× Error:', '').trim()), logger.error(error));
7421
+ });
7422
+ }
7423
+ }, instance.close = (callback = noop)=>{
7424
+ watching?.close(callback);
7425
+ }, instance;
7426
+ })({
7474
7427
  config,
7475
7428
  context,
7476
7429
  compiler: this.compiler,
@@ -7556,11 +7509,12 @@ function gzipMiddleware_gzipMiddleware({ filter, level = node_zlib.constants.Z_B
7556
7509
  let start = ()=>{
7557
7510
  if (started) return;
7558
7511
  if (started = !0, ((res)=>{
7512
+ let index;
7559
7513
  if (res.getHeader('Content-Encoding')) return !1;
7560
7514
  let contentType = res.getHeader('Content-Type');
7561
7515
  if (!contentType) return !1;
7562
7516
  let contentTypeValue = String(contentType);
7563
- if (!CONTENT_TYPE_REGEX.test(contentTypeValue) || 'text/event-stream' === contentTypeValue.split(';', 1)[0].trim().toLowerCase()) return !1;
7517
+ if (!CONTENT_TYPE_REGEX.test(contentTypeValue) || 'text/event-stream' === (-1 === (index = contentTypeValue.indexOf(';')) ? contentTypeValue : contentTypeValue.slice(0, index)).trim().toLowerCase()) return !1;
7564
7518
  let size = res.getHeader('Content-Length');
7565
7519
  return void 0 === size || Number(size) > 1024;
7566
7520
  })(res)) {
@@ -7661,8 +7615,8 @@ let faviconFallbackMiddleware = (req, res, next)=>{
7661
7615
  '/favicon.ico' === req.url ? (res.statusCode = 204, res.end()) : next();
7662
7616
  }, getRequestLoggerMiddleware = (logger)=>(req, res, next)=>{
7663
7617
  let _startAt = process.hrtime();
7664
- on_finished_default()(res, ()=>{
7665
- let method = req.method, url = req.originalUrl || req.url, status = Number(res.statusCode), statusColor = status >= 500 ? color.red : status >= 400 ? color.yellow : status >= 300 ? color.cyan : status >= 200 ? color.green : (res)=>res, endAt = process.hrtime(), totalTime = (endAt[0] - _startAt[0]) * 1e3 + (endAt[1] - _startAt[1]) * 1e-6;
7618
+ finished(res, ()=>{
7619
+ let method = req.method, url = req.originalUrl || req.url, status = Number(res.statusCode), statusColor = status >= 500 ? color.red : status >= 400 ? color.yellow : status >= 300 ? color.cyan : status >= 200 ? color.green : (0, (res)=>res), endAt = process.hrtime(), totalTime = (endAt[0] - _startAt[0]) * 1e3 + (endAt[1] - _startAt[1]) * 1e-6;
7666
7620
  logger.debug(`${statusColor(status)} ${method} ${url} ${color.dim(`${totalTime.toFixed(3)} ms`)}`);
7667
7621
  }), next();
7668
7622
  }, notFoundMiddleware = (_req, res, _next)=>{
@@ -7673,7 +7627,7 @@ let faviconFallbackMiddleware = (req, res, next)=>{
7673
7627
  return;
7674
7628
  }
7675
7629
  next();
7676
- }, middlewares_isFileExists = async (filePath, outputFileSystem)=>new Promise((resolve)=>{
7630
+ }, middlewares_isFileExists = (filePath, outputFileSystem)=>new Promise((resolve)=>{
7677
7631
  outputFileSystem.stat(filePath, (_error, stats)=>{
7678
7632
  resolve(!!stats?.isFile());
7679
7633
  });
@@ -7787,175 +7741,16 @@ async function createProxyMiddleware(proxyOptions, logger) {
7787
7741
  }
7788
7742
  };
7789
7743
  }
7790
- let applyDefaultMiddlewares = async ({ config, buildManager, context, devServer, middlewares, postCallbacks })=>{
7791
- let launchEditorHandlerPromise, upgradeEvents = [], { server } = config, { logger } = context;
7792
- if (server.cors) {
7793
- let { default: corsMiddleware } = await import("./cors.js").then(createFakeNamespaceObject.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/cors/2.8.6/abeeebb4dd5e2293f01aa9f4c01ff28ab19103cfa7a845442d515e16cf051f35/node_modules/cors/lib/index.js", 23));
7794
- middlewares.use(corsMiddleware('boolean' == typeof server.cors ? {} : server.cors));
7795
- }
7796
- let { headers } = server;
7797
- if (headers && middlewares.use((_req, res, next)=>{
7798
- for (let [key, value] of Object.entries(headers))res.setHeader(key, value);
7799
- next();
7800
- }), server.proxy) {
7801
- let { middlewares: proxyMiddlewares, upgrade } = await createProxyMiddleware(server.proxy, logger);
7802
- for (let middleware of (upgradeEvents.push(upgrade), proxyMiddlewares))middlewares.use(middleware);
7803
- }
7804
- let { compress } = server;
7805
- if (compress && middlewares.use(gzipMiddleware_gzipMiddleware('object' == typeof compress ? compress : void 0)), 'dev' === context.action && buildManager) {
7806
- let { compiler } = buildManager;
7807
- (compiler_isMultiCompiler(compiler) ? compiler.compilers.some((childCompiler)=>childCompiler.options.lazyCompilation) : compiler.options.lazyCompilation) && middlewares.use(core_rspack.lazyCompilationMiddleware(compiler));
7808
- }
7809
- if (server.base && '/' !== server.base && middlewares.use(getBaseUrlMiddleware({
7810
- base: server.base
7811
- })), middlewares.use('/__open-in-editor', async (req, res, next)=>{
7812
- try {
7813
- (await (launchEditorHandlerPromise ??= (async ()=>{
7814
- let { default: launchEditorMiddleware } = await import("./launch-editor-middleware.js").then(createFakeNamespaceObject.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/launch-editor-middleware/2.14.2/46c81dbb0ad4cd8f776539a7cfaa5ea6144007363b919f05970ca6624282dcce/node_modules/launch-editor-middleware/index.js", 23));
7815
- return launchEditorMiddleware();
7816
- })()))(req, res, next);
7817
- } catch (err) {
7818
- next(err);
7819
- }
7820
- }), middlewares.use((({ environments, logger })=>async function viewingServedFilesMiddleware(req, res, next) {
7821
- if ('/rsbuild-dev-server' !== req.url.replace(postfixRE, '')) return void next();
7822
- res.writeHead(200, {
7823
- 'Content-Type': 'text/html; charset=utf-8'
7824
- }), res.write(`<!DOCTYPE html>
7825
- <html>
7826
- <head>
7827
- <meta charset="utf-8"/>
7828
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
7829
- <style>
7830
- body {
7831
- margin: 0;
7832
- color: #f6f7f9;
7833
- padding: 32px 40px;
7834
- line-height: 1.8;
7835
- min-height: 100vh;
7836
- background-image: linear-gradient(#020917, #101725);
7837
- font-family: ui-sans-serif,system-ui,sans-serif;
7838
- }
7839
- h1, h2 {
7840
- font-weight: 500;
7841
- }
7842
- h1 {
7843
- margin: 0;
7844
- font-size: 36px;
7845
- }
7846
- h2 {
7847
- font-size: 20px;
7848
- margin: 24px 0 16px;
7849
- }
7850
- ul {
7851
- margin: 0;
7852
- padding-left: 16px;
7853
- }
7854
- a {
7855
- color: #58c4dc;
7856
- text-decoration: none;
7857
- }
7858
- a:hover {
7859
- text-decoration: underline;
7860
- }
7861
- </style>
7862
- </head>
7863
- <body>
7864
- <h1>Assets Report</h1>
7865
- </body>
7866
- </html>`);
7867
- try {
7868
- for(let key in environments){
7869
- res.write(`<h2>Environment: ${key}</h2>`);
7870
- let list = [], environment = environments[key], stats = await environment.getStats(), assets = Object.keys(stats.compilation.assets);
7871
- for (let asset of (res.write('<ul>'), assets))list.push(`<li><a target="_blank" href="${asset}">${asset}</a></li>`);
7872
- res.write(list?.join('')), res.write('</ul>');
7873
- }
7874
- res.end('</body></html>');
7875
- } catch (err) {
7876
- logger.error(err), res.writeHead(500), res.end('Failed to list the files');
7877
- }
7878
- })({
7879
- environments: devServer.environments,
7880
- logger
7881
- })), buildManager && (middlewares.use(buildManager.assetsMiddleware), upgradeEvents.push(buildManager.socketServer.upgrade), middlewares.use(function hotUpdateJsonFallbackMiddleware(req, res, next) {
7882
- let url = req.url;
7883
- if (!url || 'OPTIONS' === req.method) return void next();
7884
- let queryIndex = url.indexOf('?'), end = -1 === queryIndex ? url.length : queryIndex;
7885
- url.endsWith('.hot-update.json', end) || url.endsWith('.hot-update.json.mjs', end) ? notFoundMiddleware(req, res, next) : next();
7886
- })), buildManager && middlewares.use(getHtmlCompletionMiddleware({
7887
- assetsMiddleware: buildManager.assetsMiddleware,
7888
- distPaths: [
7889
- context.distPath
7890
- ],
7891
- outputFileSystem: buildManager.outputFileSystem
7892
- })), server.publicDir.length) {
7893
- let { default: sirv } = await import("./sirv.js");
7894
- for (let { name } of server.publicDir){
7895
- let sirvMiddleware = sirv(name, {
7896
- etag: !0,
7897
- dev: !0
7898
- });
7899
- middlewares.use(function publicDirMiddleware(req, res, next) {
7900
- sirvMiddleware(req, res, next);
7901
- });
7902
- }
7903
- }
7904
- for (let callback of postCallbacks)await callback();
7905
- return server.historyApiFallback && (middlewares.use(historyApiFallback_historyApiFallbackMiddleware(logger, !0 === server.historyApiFallback ? {} : server.historyApiFallback)), buildManager?.assetsMiddleware && middlewares.use(buildManager.assetsMiddleware)), buildManager && server.htmlFallback && middlewares.use(getHtmlFallbackMiddleware({
7906
- assetsMiddleware: buildManager.assetsMiddleware,
7907
- distPaths: [
7908
- context.distPath
7909
- ],
7910
- logger,
7911
- outputFileSystem: buildManager.outputFileSystem
7912
- })), middlewares.use(faviconFallbackMiddleware), {
7913
- onUpgrade: (...args)=>{
7914
- for (let cb of upgradeEvents)cb(...args);
7915
- }
7916
- };
7917
- }, getDevMiddlewares = async (options)=>{
7918
- let { buildManager, context, devServer } = options, { middlewares } = devServer, { logger } = context;
7919
- isVerbose(logger) && middlewares.use(getRequestLoggerMiddleware(logger));
7920
- let { before, after } = ((config, devServer, logger)=>{
7921
- let setupMiddlewares = config.dev.setupMiddlewares ? helpers_castArray(config.dev.setupMiddlewares) : [];
7922
- setupMiddlewares.length && logger.warn('[rsbuild] `dev.setupMiddlewares` is deprecated, use `server.setup` instead');
7923
- let serverOptions = pick(devServer, [
7924
- 'sockWrite',
7925
- 'environments'
7926
- ]), before = [], after = [];
7927
- for (let handler of setupMiddlewares)handler({
7928
- unshift: (...handlers)=>before.unshift(...handlers),
7929
- push: (...handlers)=>after.push(...handlers)
7930
- }, serverOptions);
7931
- return {
7932
- before,
7933
- after
7934
- };
7935
- })(options.config, options.devServer, logger);
7936
- for (let middleware of before)middlewares.use(middleware);
7937
- let { onUpgrade } = await applyDefaultMiddlewares({
7938
- ...options,
7939
- middlewares
7940
- });
7941
- for (let middleware of after)middlewares.use(middleware);
7942
- return {
7943
- close: async ()=>{
7944
- await buildManager?.close();
7945
- },
7946
- onUpgrade
7947
- };
7948
- }, isModuleNamespaceObject = (moduleExports)=>'[object Module]' === Object.prototype.toString.call(moduleExports), asModule = async (vm, moduleExports, context, unlinked)=>{
7744
+ let isModuleNamespaceObject = (moduleExports)=>'[object Module]' === Object.prototype.toString.call(moduleExports), asModule = async (vm, moduleExports, context, unlinked)=>{
7949
7745
  let { Module, SyntheticModule } = vm;
7950
7746
  if (moduleExports instanceof Module) return moduleExports;
7951
7747
  let normalizedModuleExports = null !== moduleExports && ('object' == typeof moduleExports || 'function' == typeof moduleExports) ? moduleExports : {
7952
7748
  default: moduleExports
7953
7749
  }, exports = [
7954
- ...new Set([
7955
- 'default',
7956
- ...Object.keys(normalizedModuleExports)
7957
- ])
7958
- ], syntheticModule = new SyntheticModule(exports, ()=>{
7750
+ 'default'
7751
+ ];
7752
+ for (let name of Object.keys(normalizedModuleExports))'default' !== name && exports.push(name);
7753
+ let syntheticModule = new SyntheticModule(exports, ()=>{
7959
7754
  for (let name of exports)if ('default' === name) {
7960
7755
  let defaultExport = isModuleNamespaceObject(normalizedModuleExports) && 'default' in normalizedModuleExports ? normalizedModuleExports.default : moduleExports;
7961
7756
  syntheticModule.setExport(name, defaultExport);
@@ -7980,7 +7775,14 @@ class BasicRunner {
7980
7775
  }
7981
7776
  getRequire() {
7982
7777
  let entryRequire = this.requirers.get('entry');
7983
- return (currentDirectory, modulePath, context = {})=>entryRequire(currentDirectory, Array.isArray(modulePath) ? modulePath : modulePath.split('?')[0], context);
7778
+ return (currentDirectory, modulePath, context = {})=>{
7779
+ let p = modulePath;
7780
+ if ('string' == typeof modulePath) {
7781
+ let index = modulePath.indexOf('?');
7782
+ -1 !== index && (p = modulePath.slice(0, index));
7783
+ }
7784
+ return entryRequire(currentDirectory, p, context);
7785
+ };
7984
7786
  }
7985
7787
  getFile(modulePath, currentDirectory) {
7986
7788
  if (Array.isArray(modulePath)) return {
@@ -8147,10 +7949,7 @@ class BasicRunnerFactory {
8147
7949
  return new EsmRunner(runnerOptions);
8148
7950
  }
8149
7951
  }
8150
- let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>{
8151
- let runner = new BasicRunnerFactory(bundlePath).create(runnerFactoryOptions);
8152
- return await runner.run(bundlePath);
8153
- }, loadBundleStatsCache = new WeakMap(), loadBundle = async (stats, entryName, utils)=>{
7952
+ let loadBundleStatsCache = new WeakMap(), loadBundle = async (stats, entryName, utils)=>{
8154
7953
  let loadBundleStats = loadBundleStatsCache.get(stats);
8155
7954
  loadBundleStats || (loadBundleStats = {
8156
7955
  ...stats.toJson({
@@ -8174,7 +7973,10 @@ let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>{
8174
7973
  for (let chunk of (outputFilePaths = new Set(), chunks || []))for (let file of chunk.files)outputFilePaths.add(join(outputPath, file));
8175
7974
  loadBundleStats.outputFilePaths = outputFilePaths;
8176
7975
  }
8177
- return await runner_run({
7976
+ return await (async ({ bundlePath, ...runnerFactoryOptions })=>{
7977
+ let runner = new BasicRunnerFactory(bundlePath).create(runnerFactoryOptions);
7978
+ return await runner.run(bundlePath);
7979
+ })({
8178
7980
  bundlePath: files[0],
8179
7981
  dist: outputPath,
8180
7982
  compilerOptions: stats.compilation.options,
@@ -8302,51 +8104,7 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8302
8104
  let currentStats = stats[index];
8303
8105
  return currentStats || waiters[index].promise;
8304
8106
  }
8305
- }), hotConnectCallbacks = new Map(), startCompile = async ()=>{
8306
- let compiler = await createCompiler();
8307
- if (!compiler) throw Error(`${color.dim('[rsbuild:server]')} Failed to get compiler instance.`);
8308
- context.publicPathnames = getPublicPathnames(compiler_isMultiCompiler(compiler) ? compiler.compilers.map(getPublicPathFromCompiler) : [
8309
- getPublicPathFromCompiler(compiler)
8310
- ], config.server.base);
8311
- let hookOptions = {
8312
- name: 'rsbuild:environment-api',
8313
- stage: -10000
8314
- };
8315
- compiler_isMultiCompiler(compiler) ? compiler.compilers.forEach((compiler, index)=>{
8316
- compiler.hooks.watchRun.tap(hookOptions, ()=>{
8317
- compileState.reset(index);
8318
- }), compiler.hooks.done.tap(hookOptions, (stats)=>{
8319
- compileState.done(index, stats);
8320
- });
8321
- }) : (compiler.hooks.watchRun.tap(hookOptions, ()=>{
8322
- compileState.reset(0);
8323
- }), compiler.hooks.done.tap(hookOptions, (stats)=>{
8324
- compileState.done(0, stats);
8325
- }));
8326
- let buildManager = new BuildManager({
8327
- context,
8328
- config,
8329
- compiler,
8330
- resolvedPort: port,
8331
- onSocketConnect: (socket, token)=>{
8332
- let callbacks = hotConnectCallbacks?.get(token);
8333
- if (!callbacks?.size) return;
8334
- let client = {
8335
- send: createHotSend(socket)
8336
- };
8337
- for (let callback of [
8338
- ...callbacks
8339
- ])try {
8340
- Promise.resolve(callback(client)).catch((error)=>{
8341
- logger.error(error);
8342
- });
8343
- } catch (error) {
8344
- logger.error(error);
8345
- }
8346
- }
8347
- });
8348
- return await buildManager.init(), buildManager;
8349
- }, protocol = isHttps ? 'https' : 'http', urls = await getAddressUrls({
8107
+ }), hotConnectCallbacks = new Map(), protocol = isHttps ? 'https' : 'http', urls = await getAddressUrls({
8350
8108
  protocol,
8351
8109
  port,
8352
8110
  host
@@ -8478,44 +8236,247 @@ async function devServer_createDevServer(options, createCompiler, config, devSer
8478
8236
  urls: urls.map((item)=>item.url),
8479
8237
  server: devServer
8480
8238
  };
8481
- } catch (error) {
8482
- try {
8483
- await closeServer();
8484
- } catch (closeError) {
8485
- logger.error('Failed to close dev server after startup error.'), logger.error(closeError);
8239
+ } catch (error) {
8240
+ try {
8241
+ await closeServer();
8242
+ } catch (closeError) {
8243
+ logger.error('Failed to close dev server after startup error.'), logger.error(closeError);
8244
+ }
8245
+ throw error;
8246
+ }
8247
+ },
8248
+ afterListen: async ()=>{
8249
+ await context.hooks.onAfterStartDevServer.callBatch({
8250
+ port,
8251
+ routes,
8252
+ environments: context.environments
8253
+ });
8254
+ },
8255
+ connectWebSocket: ({ server })=>{
8256
+ state.devMiddlewares && webSocketServers && !webSocketServers.has(server) && (server.on('upgrade', state.devMiddlewares.onUpgrade), webSocketServers.add(server));
8257
+ },
8258
+ close: closeServer,
8259
+ printUrls,
8260
+ open: openPage
8261
+ }, setupPostCallbacks = await applyServerSetup(config.server.setup, {
8262
+ action: 'dev',
8263
+ server: devServer,
8264
+ environments: context.environments
8265
+ }), postCallbacks = [
8266
+ ...(await context.hooks.onBeforeStartDevServer.callBatch({
8267
+ server: devServer,
8268
+ environments: context.environments
8269
+ })).filter((item)=>'function' == typeof item),
8270
+ ...setupPostCallbacks
8271
+ ];
8272
+ return runCompile ? context.hooks.onBeforeCreateCompiler.tapOnce(beforeCreateCompiler) : await beforeCreateCompiler(), state.buildManager = runCompile ? await (async ()=>{
8273
+ let compiler = await createCompiler();
8274
+ if (!compiler) throw Error(`${color.dim('[rsbuild:server]')} Failed to get compiler instance.`);
8275
+ context.publicPathnames = getPublicPathnames(compiler_isMultiCompiler(compiler) ? compiler.compilers.map(getPublicPathFromCompiler) : [
8276
+ getPublicPathFromCompiler(compiler)
8277
+ ], config.server.base);
8278
+ let hookOptions = {
8279
+ name: 'rsbuild:environment-api',
8280
+ stage: -10000
8281
+ };
8282
+ compiler_isMultiCompiler(compiler) ? compiler.compilers.forEach((compiler, index)=>{
8283
+ compiler.hooks.watchRun.tap(hookOptions, ()=>{
8284
+ compileState.reset(index);
8285
+ }), compiler.hooks.done.tap(hookOptions, (stats)=>{
8286
+ compileState.done(index, stats);
8287
+ });
8288
+ }) : (compiler.hooks.watchRun.tap(hookOptions, ()=>{
8289
+ compileState.reset(0);
8290
+ }), compiler.hooks.done.tap(hookOptions, (stats)=>{
8291
+ compileState.done(0, stats);
8292
+ }));
8293
+ let buildManager = new BuildManager({
8294
+ context,
8295
+ config,
8296
+ compiler,
8297
+ resolvedPort: port,
8298
+ onSocketConnect: (socket, token)=>{
8299
+ let callbacks = hotConnectCallbacks?.get(token);
8300
+ if (!callbacks?.size) return;
8301
+ let client = {
8302
+ send: createHotSend(socket)
8303
+ };
8304
+ for (let callback of [
8305
+ ...callbacks
8306
+ ])try {
8307
+ Promise.resolve(callback(client)).catch((error)=>{
8308
+ logger.error(error);
8309
+ });
8310
+ } catch (error) {
8311
+ logger.error(error);
8486
8312
  }
8487
- throw error;
8488
8313
  }
8489
- },
8490
- afterListen: async ()=>{
8491
- await context.hooks.onAfterStartDevServer.callBatch({
8492
- port,
8493
- routes,
8494
- environments: context.environments
8495
- });
8496
- },
8497
- connectWebSocket: ({ server })=>{
8498
- state.devMiddlewares && webSocketServers && !webSocketServers.has(server) && (server.on('upgrade', state.devMiddlewares.onUpgrade), webSocketServers.add(server));
8499
- },
8500
- close: closeServer,
8501
- printUrls,
8502
- open: openPage
8503
- }, setupPostCallbacks = await applyServerSetup(config.server.setup, {
8504
- action: 'dev',
8505
- server: devServer,
8506
- environments: context.environments
8507
- }), postCallbacks = [
8508
- ...(await context.hooks.onBeforeStartDevServer.callBatch({
8509
- server: devServer,
8510
- environments: context.environments
8511
- })).filter((item)=>'function' == typeof item),
8512
- ...setupPostCallbacks
8513
- ];
8514
- return runCompile ? context.hooks.onBeforeCreateCompiler.tapOnce(beforeCreateCompiler) : await beforeCreateCompiler(), state.buildManager = runCompile ? await startCompile() : void 0, state.fileWatcher = await setupWatchFiles({
8314
+ });
8315
+ return await buildManager.init(), buildManager;
8316
+ })() : void 0, state.fileWatcher = await setupWatchFiles({
8515
8317
  config,
8318
+ logger,
8516
8319
  buildManager: state.buildManager,
8517
8320
  root: context.rootPath
8518
- }), state.devMiddlewares = await getDevMiddlewares({
8321
+ }), state.devMiddlewares = await (async (options)=>{
8322
+ let { buildManager, context, devServer } = options, { middlewares } = devServer, { logger } = context;
8323
+ isVerbose(logger) && middlewares.use(getRequestLoggerMiddleware(logger));
8324
+ let { before, after } = ((config, devServer, logger)=>{
8325
+ let setupMiddlewares = config.dev.setupMiddlewares ? helpers_castArray(config.dev.setupMiddlewares) : [];
8326
+ setupMiddlewares.length && logger.warn('[rsbuild] `dev.setupMiddlewares` is deprecated, use `server.setup` instead');
8327
+ let serverOptions = pick(devServer, [
8328
+ 'sockWrite',
8329
+ 'environments'
8330
+ ]), before = [], after = [];
8331
+ for (let handler of setupMiddlewares)handler({
8332
+ unshift: (...handlers)=>before.unshift(...handlers),
8333
+ push: (...handlers)=>after.push(...handlers)
8334
+ }, serverOptions);
8335
+ return {
8336
+ before,
8337
+ after
8338
+ };
8339
+ })(options.config, options.devServer, logger);
8340
+ for (let middleware of before)middlewares.use(middleware);
8341
+ let { onUpgrade } = await (async ({ config, buildManager, context, devServer, middlewares, postCallbacks })=>{
8342
+ let launchEditorHandlerPromise, upgradeEvents = [], { server } = config, { logger } = context, servedEnvironments = context.environmentList.filter((environment)=>isServingAssets(environment.config)), distPaths = [
8343
+ ...new Set(servedEnvironments.map((environment)=>environment.distPath))
8344
+ ];
8345
+ if (server.cors) {
8346
+ let { default: corsMiddleware } = await import("./cors.js").then(createFakeNamespaceObject.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/cors/2.8.6/abeeebb4dd5e2293f01aa9f4c01ff28ab19103cfa7a845442d515e16cf051f35/node_modules/cors/lib/index.js", 23));
8347
+ middlewares.use(corsMiddleware('boolean' == typeof server.cors ? {} : server.cors));
8348
+ }
8349
+ let { headers } = server;
8350
+ if (headers && middlewares.use((_req, res, next)=>{
8351
+ for (let [key, value] of Object.entries(headers))res.setHeader(key, value);
8352
+ next();
8353
+ }), server.proxy) {
8354
+ let { middlewares: proxyMiddlewares, upgrade } = await createProxyMiddleware(server.proxy, logger);
8355
+ for (let middleware of (upgradeEvents.push(upgrade), proxyMiddlewares))middlewares.use(middleware);
8356
+ }
8357
+ let { compress } = server;
8358
+ if (compress && middlewares.use(gzipMiddleware_gzipMiddleware('object' == typeof compress ? compress : void 0)), 'dev' === context.action && buildManager) {
8359
+ let { compiler } = buildManager;
8360
+ (compiler_isMultiCompiler(compiler) ? compiler.compilers.some((childCompiler)=>childCompiler.options.lazyCompilation) : compiler.options.lazyCompilation) && middlewares.use(core_rspack.lazyCompilationMiddleware(compiler));
8361
+ }
8362
+ server.base && '/' !== server.base && middlewares.use(getBaseUrlMiddleware({
8363
+ base: server.base
8364
+ })), middlewares.use('/__open-in-editor', async (req, res, next)=>{
8365
+ try {
8366
+ (await (launchEditorHandlerPromise ??= (async ()=>{
8367
+ let { default: launchEditorMiddleware } = await import("./launch-editor-middleware.js").then(createFakeNamespaceObject.bind(rspackRequire, "../../../../../setup-pnpm/node_modules/.bin/store/v11/links/@/launch-editor-middleware/2.14.2/46c81dbb0ad4cd8f776539a7cfaa5ea6144007363b919f05970ca6624282dcce/node_modules/launch-editor-middleware/index.js", 23));
8368
+ return launchEditorMiddleware();
8369
+ })()))(req, res, next);
8370
+ } catch (err) {
8371
+ next(err);
8372
+ }
8373
+ }), middlewares.use((({ environments, logger })=>async function viewingServedFilesMiddleware(req, res, next) {
8374
+ if ('/rsbuild-dev-server' !== req.url.replace(postfixRE, '')) return void next();
8375
+ res.writeHead(200, {
8376
+ 'Content-Type': 'text/html; charset=utf-8'
8377
+ }), res.write(`<!DOCTYPE html>
8378
+ <html>
8379
+ <head>
8380
+ <meta charset="utf-8"/>
8381
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
8382
+ <style>
8383
+ body {
8384
+ margin: 0;
8385
+ color: #f6f7f9;
8386
+ padding: 32px 40px;
8387
+ line-height: 1.8;
8388
+ min-height: 100vh;
8389
+ background-image: linear-gradient(#020917, #101725);
8390
+ font-family: ui-sans-serif,system-ui,sans-serif;
8391
+ }
8392
+ h1, h2 {
8393
+ font-weight: 500;
8394
+ }
8395
+ h1 {
8396
+ margin: 0;
8397
+ font-size: 36px;
8398
+ }
8399
+ h2 {
8400
+ font-size: 20px;
8401
+ margin: 24px 0 16px;
8402
+ }
8403
+ ul {
8404
+ margin: 0;
8405
+ padding-left: 16px;
8406
+ }
8407
+ a {
8408
+ color: #58c4dc;
8409
+ text-decoration: none;
8410
+ }
8411
+ a:hover {
8412
+ text-decoration: underline;
8413
+ }
8414
+ </style>
8415
+ </head>
8416
+ <body>
8417
+ <h1>Assets Report</h1>
8418
+ </body>
8419
+ </html>`);
8420
+ try {
8421
+ for(let key in environments){
8422
+ res.write(`<h2>Environment: ${key}</h2>`);
8423
+ let list = [], environment = environments[key], stats = await environment.getStats(), assets = getAssetNames(stats.compilation);
8424
+ for (let asset of (res.write('<ul>'), assets))list.push(`<li><a target="_blank" href="${asset}">${asset}</a></li>`);
8425
+ res.write(list?.join('')), res.write('</ul>');
8426
+ }
8427
+ res.end('</body></html>');
8428
+ } catch (err) {
8429
+ logger.error(err), res.writeHead(500), res.end('Failed to list the files');
8430
+ }
8431
+ })({
8432
+ environments: pick(devServer.environments, servedEnvironments.map((environment)=>environment.name)),
8433
+ logger
8434
+ })), buildManager && (middlewares.use(buildManager.assetsMiddleware), upgradeEvents.push(buildManager.socketServer.upgrade), middlewares.use(function hotUpdateJsonFallbackMiddleware(req, res, next) {
8435
+ let url = req.url;
8436
+ if (!url || 'OPTIONS' === req.method) return void next();
8437
+ let queryIndex = url.indexOf('?'), end = -1 === queryIndex ? url.length : queryIndex;
8438
+ url.endsWith('.hot-update.json', end) || url.endsWith('.hot-update.json.mjs', end) ? notFoundMiddleware(req, res, next) : next();
8439
+ })), buildManager && middlewares.use(getHtmlCompletionMiddleware({
8440
+ assetsMiddleware: buildManager.assetsMiddleware,
8441
+ distPaths,
8442
+ outputFileSystem: buildManager.outputFileSystem
8443
+ }));
8444
+ let publicDirPaths = getPublicDirPaths(config);
8445
+ if (publicDirPaths.length) {
8446
+ let { default: sirv } = await import("./sirv.js");
8447
+ for (let name of publicDirPaths){
8448
+ let sirvMiddleware = sirv(name, {
8449
+ etag: !0,
8450
+ dev: !0
8451
+ });
8452
+ middlewares.use(function publicDirMiddleware(req, res, next) {
8453
+ req.method && 'GET' !== req.method && 'HEAD' !== req.method ? next() : sirvMiddleware(req, res, next);
8454
+ });
8455
+ }
8456
+ }
8457
+ for (let callback of postCallbacks)await callback();
8458
+ return server.historyApiFallback && (middlewares.use(historyApiFallback_historyApiFallbackMiddleware(logger, !0 === server.historyApiFallback ? {} : server.historyApiFallback)), buildManager?.assetsMiddleware && middlewares.use(buildManager.assetsMiddleware)), buildManager && server.htmlFallback && middlewares.use(getHtmlFallbackMiddleware({
8459
+ assetsMiddleware: buildManager.assetsMiddleware,
8460
+ distPaths,
8461
+ logger,
8462
+ outputFileSystem: buildManager.outputFileSystem
8463
+ })), middlewares.use(faviconFallbackMiddleware), {
8464
+ onUpgrade: (...args)=>{
8465
+ for (let cb of upgradeEvents)cb(...args);
8466
+ }
8467
+ };
8468
+ })({
8469
+ ...options,
8470
+ middlewares
8471
+ });
8472
+ for (let middleware of after)middlewares.use(middleware);
8473
+ return {
8474
+ close: async ()=>{
8475
+ await buildManager?.close();
8476
+ },
8477
+ onUpgrade
8478
+ };
8479
+ })({
8519
8480
  buildManager: state.buildManager,
8520
8481
  config,
8521
8482
  devServer,
@@ -8543,7 +8504,7 @@ async function startPreviewServer(context, config, { getPortSilently } = {}) {
8543
8504
  serverConfig,
8544
8505
  middlewares
8545
8506
  }), cleanupGracefulShutdown = setupGracefulShutdown(), serverTerminator = getServerTerminator(httpServer), closingPromise = null, closeServer = async ()=>(closingPromise || (closingPromise = (async ()=>{
8546
- removeCleanup(closeServer), cleanupGracefulShutdown(), cleanupCliShortcuts?.(), await serverTerminator();
8507
+ removeCleanup(closeServer), cleanupGracefulShutdown(), cleanupCliShortcuts?.(), await serverTerminator(), await context.hooks.onClosePreviewServer.callBatch();
8547
8508
  })()), closingPromise), printUrls = (options)=>printServerURLs({
8548
8509
  urls,
8549
8510
  port,
@@ -8577,9 +8538,14 @@ async function startPreviewServer(context, config, { getPortSilently } = {}) {
8577
8538
  server: previewServer,
8578
8539
  environments: context.environments
8579
8540
  });
8580
- let webEnvironments = filterWebEnvironments(context.environmentList), assetsMiddleware = createAssetsMiddleware(context, (callback)=>callback(), node_fs), htmlMiddlewareOptions = {
8541
+ let servedEnvironments = context.environmentList.filter((environment)=>isServingAssets(environment.config)), assetsMiddleware = createAssetsMiddleware(context, {
8542
+ waitForAssets: (callback)=>callback(),
8543
+ waitForBuild: (callback)=>callback()
8544
+ }, node_fs), htmlMiddlewareOptions = {
8581
8545
  assetsMiddleware,
8582
- distPaths: webEnvironments.map((environment)=>environment.distPath),
8546
+ distPaths: [
8547
+ ...new Set(servedEnvironments.map((environment)=>environment.distPath))
8548
+ ],
8583
8549
  outputFileSystem: node_fs
8584
8550
  };
8585
8551
  if (isVerbose(logger) && middlewares.use(getRequestLoggerMiddleware(logger)), cors) {
@@ -8690,11 +8656,7 @@ function applyDefaultPlugins(pluginManager, context) {
8690
8656
  name: 'rsbuild:source-map',
8691
8657
  setup (api) {
8692
8658
  let normalizeExtractOptions = (extract = {})=>{
8693
- let hasLegacyJs = 'js' in extract, hasFlatFields = [
8694
- 'test',
8695
- 'include',
8696
- 'exclude'
8697
- ].some((key)=>void 0 !== extract[key]);
8659
+ let hasLegacyJs = 'js' in extract, hasFlatFields = void 0 !== extract.test || void 0 !== extract.include || void 0 !== extract.exclude;
8698
8660
  if (!1 === extract.js) return !1;
8699
8661
  if (hasLegacyJs && !hasFlatFields) {
8700
8662
  var target;
@@ -8759,11 +8721,14 @@ function applyDefaultPlugins(pluginManager, context) {
8759
8721
  api.modifyBundlerChain(async (chain, { environment, env })=>{
8760
8722
  let { config } = environment, { buildCache = !1 } = config.performance;
8761
8723
  if (!1 === buildCache) return;
8762
- cacheEnabled = !0;
8763
- let { context } = api, cacheConfig = 'boolean' == typeof buildCache ? {} : buildCache, cacheDirectory = getCacheDirectory(cacheConfig, context), buildDependencies = await getBuildDependencies(context, environment, cacheConfig.buildDependencies), cacheVersion = Array.isArray(cacheConfig.cacheDigest) && cacheConfig.cacheDigest.length ? `${environment.name}-${env}-${await helpers_hash(JSON.stringify(cacheConfig.cacheDigest))}` : `${environment.name}-${env}`;
8724
+ 'new' === process.env.RSBUILD_E2E_CACHE && chain.experiments({
8725
+ ...chain.get('experiments'),
8726
+ newCache: !0
8727
+ }), cacheEnabled = !0;
8728
+ 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.3-${environment.name}-${env}`;
8764
8729
  chain.cache({
8765
8730
  type: 'persistent',
8766
- version: cacheVersion,
8731
+ version: useDigest ? `${cacheVersion}-${await helpers_hash(JSON.stringify(cacheConfig.cacheDigest))}` : cacheVersion,
8767
8732
  storage: {
8768
8733
  type: 'filesystem',
8769
8734
  directory: cacheDirectory
@@ -8802,9 +8767,9 @@ function applyDefaultPlugins(pluginManager, context) {
8802
8767
  {
8803
8768
  name: 'rsbuild:output',
8804
8769
  setup (api) {
8805
- api.modifyBundlerChain((chain, { CHAIN_ID, isDev, isProd, isServer, environment, rspack, target })=>{
8770
+ api.modifyBundlerChain(async (chain, { CHAIN_ID, isDev, isProd, isServer, environment, rspack, target })=>{
8806
8771
  var jsAsync;
8807
- let { distPath, config } = environment, publicPath = getPublicPath({
8772
+ let { distPath, config } = environment, publicPath = await getPublicPath({
8808
8773
  config,
8809
8774
  isDev,
8810
8775
  context: api.context
@@ -9002,7 +8967,7 @@ function applyDefaultPlugins(pluginManager, context) {
9002
8967
  {
9003
8968
  name: 'rsbuild:html',
9004
8969
  setup (api) {
9005
- let defaultFavicon;
8970
+ let defaultFaviconCache = new Map();
9006
8971
  api.modifyBundlerChain(async (chain, { HtmlPlugin, CHAIN_ID, environment })=>{
9007
8972
  let { config, htmlPaths } = environment;
9008
8973
  if (0 === Object.keys(htmlPaths).length) return;
@@ -9034,17 +8999,18 @@ function applyDefaultPlugins(pluginManager, context) {
9034
8999
  };
9035
9000
  })(environment.config);
9036
9001
  tagConfig && (extraData.tagConfig = tagConfig), pluginOptions.title = await getTitle(entryName, config);
9037
- let favicon = await getFavicon(entryName, config) || (()=>{
9038
- if (defaultFavicon) return defaultFavicon;
9039
- let { publicDir } = api.getNormalizedConfig().server, extensions = [
9002
+ let favicon = await getFavicon(entryName, config) || ((config)=>{
9003
+ let { publicDir } = config.server, extensions = [
9040
9004
  'ico',
9041
9005
  'png',
9042
9006
  'svg'
9043
- ], publicDirs = Array.from(new Set(publicDir.map(({ name })=>name))), faviconPaths = [];
9007
+ ], publicDirs = Array.from(new Set(publicDir.map(({ name })=>name))), key = JSON.stringify(publicDirs), defaultFavicon = defaultFaviconCache.get(key);
9008
+ if (defaultFavicon) return defaultFavicon;
9009
+ let faviconPaths = [];
9044
9010
  for (let publicDir of publicDirs)for (let ext of extensions)faviconPaths.push(node_path.join(publicDir, `favicon.${ext}`));
9045
9011
  let faviconPath = findExists(faviconPaths);
9046
- return faviconPath && (defaultFavicon = faviconPath), defaultFavicon;
9047
- })();
9012
+ if (faviconPath) return defaultFaviconCache.set(key, faviconPath), faviconPath;
9013
+ })(config);
9048
9014
  favicon && (extraData.favicon = favicon);
9049
9015
  let finalOptions = await reduceConfigsWithContext({
9050
9016
  initial: pluginOptions,
@@ -9245,7 +9211,13 @@ try {
9245
9211
  name: 'rsbuild:define',
9246
9212
  setup (api) {
9247
9213
  api.modifyBundlerChain((chain, { CHAIN_ID, rspack, environment })=>{
9248
- let { config } = environment, baseUrl = JSON.stringify(config.server.base), assetPrefix = JSON.stringify(getPublicPathFromChain(chain, !1)), mergedDefine = {
9214
+ let { config } = environment, baseUrl = JSON.stringify(config.server.base), assetPrefix = JSON.stringify(getPublicPathFromChain(chain, !1)), envPrefix = 'import.meta.env.', userEnv = Object.create(null);
9215
+ for (let [key, value] of Object.entries(config.source.define)){
9216
+ if (!key.startsWith(envPrefix)) continue;
9217
+ let name = key.slice(envPrefix.length);
9218
+ '' === name || name.includes('.') || (userEnv[name] = value);
9219
+ }
9220
+ let mergedDefine = {
9249
9221
  ...{
9250
9222
  'import.meta.env': {
9251
9223
  MODE: JSON.stringify(config.mode),
@@ -9253,7 +9225,8 @@ try {
9253
9225
  PROD: 'production' === config.mode,
9254
9226
  SSR: 'node' === config.output.target,
9255
9227
  BASE_URL: baseUrl,
9256
- ASSET_PREFIX: assetPrefix
9228
+ ASSET_PREFIX: assetPrefix,
9229
+ ...userEnv
9257
9230
  },
9258
9231
  'process.env.BASE_URL': baseUrl,
9259
9232
  'process.env.ASSET_PREFIX': assetPrefix
@@ -9333,7 +9306,45 @@ try {
9333
9306
  skipMain: !emitCss
9334
9307
  });
9335
9308
  }
9336
- let postcssLoaderOptions = await getPostcssLoaderOptions({
9309
+ let postcssLoaderOptions = await (async ({ config, root, postcssrcCache })=>{
9310
+ let extraPlugins = [], userOptions = await loadUserPostcssrc(root, postcssrcCache);
9311
+ userOptions.plugins ||= [];
9312
+ let defaultOptions = {
9313
+ implementation: getCompiledPath('postcss'),
9314
+ postcssOptions: userOptions,
9315
+ sourceMap: getCSSSourceMap(config)
9316
+ }, finalOptions = await reduceConfigsWithContext({
9317
+ initial: defaultOptions,
9318
+ config: config.tools.postcss,
9319
+ ctx: {
9320
+ addPlugins (plugins, options = {}) {
9321
+ let { order = 'post' } = options, list = helpers_castArray(plugins);
9322
+ 'pre' === order ? extraPlugins.unshift(...list) : extraPlugins.push(...list);
9323
+ }
9324
+ }
9325
+ });
9326
+ finalOptions.postcssOptions ||= {};
9327
+ 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;
9328
+ if ('function' == typeof postcssOptions) {
9329
+ let postcssOptionsWrapper = (loaderContext)=>{
9330
+ let options = postcssOptions(loaderContext);
9331
+ if ('object' != typeof options || null === options) throw Error(`${color.dim('[rsbuild:css]')} \`postcssOptions\` function must return a PostCSSOptions object, got ${color.yellow(typeof options)}.`);
9332
+ return updatePostcssOptions({
9333
+ ...userOptions,
9334
+ ...options,
9335
+ plugins: [
9336
+ ...userOptions.plugins || [],
9337
+ ...options.plugins || []
9338
+ ]
9339
+ });
9340
+ };
9341
+ return postcssOptionsWrapper.config = !1, {
9342
+ ...finalOptions,
9343
+ postcssOptions: postcssOptionsWrapper
9344
+ };
9345
+ }
9346
+ return finalOptions.postcssOptions = updatePostcssOptions(postcssOptions), finalOptions;
9347
+ })({
9337
9348
  config,
9338
9349
  root: api.context.rootPath,
9339
9350
  postcssrcCache
@@ -9347,7 +9358,37 @@ try {
9347
9358
  skipMain: !emitCss
9348
9359
  });
9349
9360
  }
9350
- let localIdentName = config.output.cssModules.localIdentName || (isProd ? '[local]-[hash:base64:6]' : '[path][name]__[local]-[hash:base64:6]'), cssLoaderOptions = await getCSSLoaderOptions({
9361
+ let localIdentName = config.output.cssModules.localIdentName || (isProd ? '[local]-[hash:base64:6]' : '[path][name]__[local]-[hash:base64:6]'), cssLoaderOptions = await (async ({ config, localIdentName, emitCss })=>{
9362
+ let { cssModules } = config.output, defaultOptions = {
9363
+ modules: {
9364
+ ...cssModules,
9365
+ localIdentName
9366
+ },
9367
+ sourceMap: getCSSSourceMap(config)
9368
+ };
9369
+ return ((options, exportOnlyLocals)=>{
9370
+ if (options.modules && exportOnlyLocals) {
9371
+ let { modules } = options;
9372
+ return modules = !0 === modules ? {
9373
+ exportOnlyLocals: !0
9374
+ } : 'string' == typeof modules ? {
9375
+ mode: modules,
9376
+ exportOnlyLocals: !0
9377
+ } : {
9378
+ ...modules,
9379
+ exportOnlyLocals: !0
9380
+ }, {
9381
+ ...options,
9382
+ modules
9383
+ };
9384
+ }
9385
+ return options;
9386
+ })(await reduceConfigs({
9387
+ initial: defaultOptions,
9388
+ config: config.tools.cssLoader,
9389
+ mergeFn: cjs_0_default()
9390
+ }), !emitCss);
9391
+ })({
9351
9392
  config,
9352
9393
  localIdentName,
9353
9394
  emitCss
@@ -9674,7 +9715,7 @@ try {
9674
9715
  return;
9675
9716
  }
9676
9717
  }
9677
- api.logger.warn(`\`process.env.RSDOCTOR\` enabled, please install ${color.bold(color.yellow('@rsdoctor/rspack-plugin'))} package.`);
9718
+ api.logger.warn(`\`process.env.RSDOCTOR\` enabled, please install ${color.bold(color.yellow('@rsdoctor/core@latest'))} package.`);
9678
9719
  });
9679
9720
  }
9680
9721
  },
@@ -9700,10 +9741,8 @@ try {
9700
9741
  bodyTags
9701
9742
  };
9702
9743
  }), api.modifyBundlerChain((chain, { CHAIN_ID, environment, isDev })=>{
9703
- let { config, htmlPaths } = environment;
9704
- if (0 === Object.keys(htmlPaths).length) return;
9705
- let { performance: { preload, prefetch } } = config;
9706
- if (!preload && !prefetch) return;
9744
+ let { config, htmlPaths } = environment, { performance: { preload, prefetch } } = config;
9745
+ if (!preload && !prefetch || 0 === Object.keys(htmlPaths).length) return;
9707
9746
  let HTMLCount = chain.entryPoints.values().length, excludes = ((config)=>{
9708
9747
  let { scriptTests, styleTests } = getInlineTests(config);
9709
9748
  return [
@@ -9751,39 +9790,22 @@ try {
9751
9790
  }
9752
9791
  };
9753
9792
  api.onAfterStartDevServer(onStartServer), api.onAfterStartPreviewServer(onStartServer), api.onBeforeBuild(async ({ isFirstCompile, environments })=>{
9754
- if (isFirstCompile) for (let { name: publicDir, copyOnBuild, ignore } of api.getNormalizedConfig().server.publicDir){
9755
- let shouldCopy;
9793
+ if (!isFirstCompile) return;
9794
+ let groups = new Map();
9795
+ for (let environment of Object.values(environments)){
9796
+ let key = JSON.stringify(environment.config.server.publicDir.map(({ name, copyOnBuild, ignore })=>[
9797
+ name,
9798
+ copyOnBuild,
9799
+ ignore
9800
+ ])), group = groups.get(key);
9801
+ group ? group.push(environment) : groups.set(key, [
9802
+ environment
9803
+ ]);
9804
+ }
9805
+ for (let group of groups.values())for (let { name: publicDir, copyOnBuild, ignore } of group[0].config.server.publicDir){
9756
9806
  if (!1 === copyOnBuild || !node_fs.existsSync(publicDir)) continue;
9757
- let distPaths = dedupeNestedPaths(Object.values(environments).filter(({ config })=>!0 === copyOnBuild || 'auto' === copyOnBuild && 'node' !== config.output.target).map(({ distPath })=>distPath));
9758
- if (ignore?.length) {
9759
- let { globSync } = await getTinyglobby(), ignoredSet = new Set(globSync(ignore, {
9760
- cwd: publicDir,
9761
- absolute: !1,
9762
- dot: !0,
9763
- onlyFiles: !1
9764
- }).map((item)=>item.replace(/\\/g, '/').replace(/\/$/, '')));
9765
- shouldCopy = (source)=>{
9766
- let relativePath = node_path.relative(publicDir, source);
9767
- if (!relativePath) return !0;
9768
- let normalizedPath = relativePath.replace(/\\/g, '/');
9769
- return !ignoredSet.has(normalizedPath);
9770
- };
9771
- }
9772
- try {
9773
- await Promise.all(distPaths.map(async (distPath)=>{
9774
- isDeno && node_fs.existsSync(distPath) && await node_fs.promises.rm(distPath, {
9775
- recursive: !0,
9776
- force: !0
9777
- }), await node_fs.promises.cp(publicDir, distPath, {
9778
- recursive: !0,
9779
- dereference: !0,
9780
- mode: node_fs.constants.COPYFILE_FICLONE,
9781
- filter: shouldCopy
9782
- });
9783
- }));
9784
- } catch (err) {
9785
- throw err instanceof Error && (err.message = `Failed to copy public directory '${color.yellow(publicDir)}' to output directory. To disable public directory copying, set \`${color.cyan('server.publicDir: false')}\` in your config.\n${err.message}`), err;
9786
- }
9807
+ let distPaths = dedupeNestedPaths(group.filter(({ config })=>!0 === copyOnBuild || 'node' !== config.output.target).map(({ distPath })=>distPath));
9808
+ 0 !== distPaths.length && await copyPublicDir(publicDir, distPaths, ignore);
9787
9809
  }
9788
9810
  });
9789
9811
  }
@@ -9801,7 +9823,7 @@ try {
9801
9823
  fileName: manifestOptions.filename,
9802
9824
  filter,
9803
9825
  writeToFileEmit: isDev && !0 !== writeToDisk,
9804
- generate: (_seed, files, entries, { compilation })=>{
9826
+ generate: (0, (_seed, files, entries, { compilation })=>{
9805
9827
  let chunkEntries = new Map(), filePathByName = new Map(), licenseMap = new Map(), publicPath = getPublicPathFromCompiler(compilation), integrity = {}, allFiles = files.map((file)=>{
9806
9828
  if (filePathByName.has(file.name) || filePathByName.set(file.name, file.path), file.integrity && (integrity[file.path] = file.integrity), file.chunk) for (let entryName of recursiveChunkEntryNames(file.chunk)){
9807
9829
  let chunkFiles = chunkEntries.get(entryName);
@@ -9857,7 +9879,7 @@ try {
9857
9879
  throw Error(`${color.dim('[rsbuild:manifest]')} \`manifest.generate\` function must return a valid manifest object.`);
9858
9880
  }
9859
9881
  return environment.manifest = manifestData, manifestData;
9860
- }
9882
+ })
9861
9883
  };
9862
9884
  manifestOptions.prefix || (pluginOptions.publicPath = ''), chain.plugin(CHAIN_ID.PLUGIN.MANIFEST).use(RspackManifestPlugin, [
9863
9885
  pluginOptions
@@ -9961,11 +9983,15 @@ try {
9961
9983
  }), api.modifyHTMLTags({
9962
9984
  order: 'post',
9963
9985
  handler: ({ headTags, bodyTags }, { environment })=>{
9964
- let { config } = environment, { nonce } = config.security, allTags = [
9986
+ let { config } = environment, { nonce } = config.security;
9987
+ if (!nonce) return {
9988
+ headTags,
9989
+ bodyTags
9990
+ };
9991
+ for (let tag of [
9965
9992
  ...headTags,
9966
9993
  ...bodyTags
9967
- ];
9968
- if (nonce) for (let tag of allTags)isNonceTag(tag) && (tag.attrs ??= {}, tag.attrs.nonce = nonce);
9994
+ ])isNonceTag(tag) && (tag.attrs ??= {}, tag.attrs.nonce = nonce);
9969
9995
  return {
9970
9996
  headTags,
9971
9997
  bodyTags
@@ -10002,6 +10028,14 @@ async function createRsbuild(options = {}) {
10002
10028
  ...'boolean' == typeof options.loadEnv ? {} : options.loadEnv
10003
10029
  }) : null, configOrFactory = options.config ?? options.rsbuildConfig, config = isFunction(configOrFactory) ? await configOrFactory() : configOrFactory;
10004
10030
  isLoadConfigResult(config) && (loadConfigResult = config, config = config.content), config ||= {};
10031
+ let e2eCache = process.env.RSBUILD_E2E_CACHE;
10032
+ ('new' === e2eCache || 'legacy' === e2eCache) && config.performance?.buildCache === void 0 && (config = {
10033
+ ...config,
10034
+ performance: {
10035
+ ...config.performance,
10036
+ buildCache: !0
10037
+ }
10038
+ });
10005
10039
  let logger = config.customLogger ?? logger_createLogger({
10006
10040
  ...src_logger.options,
10007
10041
  level: src_logger.level
@@ -10023,82 +10057,175 @@ async function createRsbuild(options = {}) {
10023
10057
  context,
10024
10058
  pluginManager,
10025
10059
  rsbuildOptions: resolvedOptions
10026
- })).compiler), preview = async (options = {})=>{
10027
- context.action = 'preview', process.env.NODE_ENV || setNodeEnv('production');
10028
- let config = await initRsbuildConfig({
10029
- context,
10030
- pluginManager
10031
- }), { distPath } = context, { checkDistDir = !0 } = options;
10032
- if (checkDistDir) {
10033
- if (!existsSync(distPath)) throw Error(`${color.dim('[rsbuild:preview]')} The output directory ${color.yellow(distPath)} does not exist, please build the project before previewing.`);
10034
- if (isEmptyDir(distPath)) throw Error(`${color.dim('[rsbuild:preview]')} The output directory ${color.yellow(distPath)} is empty, please build the project before previewing.`);
10035
- }
10036
- return startPreviewServer(context, config, options);
10037
- }, build = async (options = {})=>(context.action = 'build', process.env.NODE_ENV || setNodeEnv('production'), build_build({
10038
- context,
10039
- pluginManager,
10040
- rsbuildOptions: resolvedOptions
10041
- }, {
10042
- ...options
10043
- })), startDevServer = async (options = {})=>{
10044
- context.action = 'dev', process.env.NODE_ENV || setNodeEnv('development');
10045
- let config = await initRsbuildConfig({
10046
- context,
10047
- pluginManager
10048
- });
10049
- return (await devServer_createDevServer({
10050
- context,
10051
- pluginManager,
10052
- rsbuildOptions: resolvedOptions
10053
- }, createCompiler, config, options)).listen();
10054
- }, createDevServer = async (options)=>{
10055
- context.action = 'dev', process.env.NODE_ENV || setNodeEnv('development');
10056
- let config = await initRsbuildConfig({
10057
- context,
10058
- pluginManager
10059
- });
10060
- return devServer_createDevServer({
10061
- context,
10062
- pluginManager,
10063
- rsbuildOptions: resolvedOptions
10064
- }, createCompiler, config, options);
10065
- }, initAction = (mode = config.mode)=>{
10060
+ })).compiler), initAction = (mode = config.mode)=>{
10066
10061
  context.action || (context.action = 'development' === mode ? 'dev' : 'build');
10067
- }, inspectConfig = async (inspectOptions = {})=>{
10068
- inspectOptions.mode ? setNodeEnv(inspectOptions.mode) : process.env.NODE_ENV || setNodeEnv('development'), initAction(config.mode ?? (process.env.NODE_ENV || ''));
10069
- let { rspackConfigs } = await initConfigs_initConfigs({
10070
- context,
10071
- pluginManager,
10072
- rsbuildOptions: resolvedOptions
10073
- });
10074
- return inspectConfig_inspectConfig({
10075
- context,
10076
- pluginManager,
10077
- rsbuildOptions: resolvedOptions,
10078
- inspectOptions,
10079
- bundlerConfigs: rspackConfigs
10080
- });
10081
- }, initConfigs = async (options)=>{
10082
- if (context.action && options?.action && context.action !== options.action) throw Error(`\
10083
- [rsbuild] initConfigs() can only be called with the same action type.
10084
- - Expected: ${context.action}
10085
- - Actual: ${options?.action}`);
10086
- options?.action && (context.action = options.action);
10087
- let { rspackConfigs } = await initConfigs_initConfigs({
10088
- context,
10089
- pluginManager,
10090
- rsbuildOptions: resolvedOptions
10091
- });
10092
- return rspackConfigs;
10093
10062
  }, rsbuild = {
10094
10063
  logger: context.logger,
10095
- build,
10096
- preview,
10097
- startDevServer,
10064
+ build: async (options = {})=>(context.action = 'build', process.env.NODE_ENV || setNodeEnv('production'), (async (initOptions, buildOptions = {})=>{
10065
+ let stats, closeCompiler, closingPromise, unregisterRestart, restartWatcher, { watch } = buildOptions, { context } = initOptions, { logger } = context, { compiler, rspackConfigs } = await createCompiler_createCompiler(initOptions);
10066
+ if ((({ context, isWatch, compiler, rspackConfigs, MultiStatsCtor })=>{
10067
+ let isFirstCompile = !0, { environmentList } = context;
10068
+ onBeforeCompile({
10069
+ compiler,
10070
+ beforeCompile: ()=>context.hooks.onBeforeBuild.callBatch({
10071
+ bundlerConfigs: rspackConfigs,
10072
+ environments: context.environments,
10073
+ isWatch,
10074
+ isFirstCompile
10075
+ }),
10076
+ beforeEnvironmentCompile: (buildIndex)=>{
10077
+ let environment = environmentList[buildIndex];
10078
+ return context.hooks.onBeforeEnvironmentCompile.callBatch({
10079
+ environment: environment.name,
10080
+ args: [
10081
+ {
10082
+ bundlerConfig: rspackConfigs[buildIndex],
10083
+ environment,
10084
+ isWatch,
10085
+ isFirstCompile
10086
+ }
10087
+ ]
10088
+ });
10089
+ },
10090
+ isWatch
10091
+ }), onCompileDone({
10092
+ compiler,
10093
+ onDone: async (stats)=>{
10094
+ let shouldLogWatching = isWatch && isFirstCompile, promise = context.hooks.onAfterBuild.callBatch({
10095
+ isFirstCompile,
10096
+ stats,
10097
+ environments: context.environments,
10098
+ isWatch
10099
+ });
10100
+ isFirstCompile = !1, await promise, shouldLogWatching && context.logger.info('watching for changes...');
10101
+ },
10102
+ onEnvironmentDone: async (index, stats)=>{
10103
+ let environment = environmentList[index], time = context.buildState.time[environment.name] ?? 0;
10104
+ await context.hooks.onAfterEnvironmentCompile.callBatch({
10105
+ environment: environment.name,
10106
+ args: [
10107
+ {
10108
+ isFirstCompile,
10109
+ stats,
10110
+ environment,
10111
+ isWatch,
10112
+ time
10113
+ }
10114
+ ]
10115
+ });
10116
+ },
10117
+ MultiStatsCtor
10118
+ });
10119
+ })({
10120
+ context,
10121
+ rspackConfigs,
10122
+ compiler,
10123
+ isWatch: !!watch,
10124
+ MultiStatsCtor: core_rspack.MultiStats
10125
+ }), watch) {
10126
+ let watchOptions = rspackConfigs.map((options)=>options.watchOptions || {});
10127
+ compiler.watch(watchOptions.length > 1 ? watchOptions : watchOptions[0] || {}, (err)=>{
10128
+ err && logger.error(err);
10129
+ }), closeCompiler = ()=>new Promise((resolve)=>{
10130
+ compiler.close(()=>{
10131
+ resolve();
10132
+ });
10133
+ });
10134
+ } else stats = await new Promise((resolve, reject)=>{
10135
+ compiler.run((err, stats)=>{
10136
+ compiler.close((closeErr)=>{
10137
+ closeErr && logger.error('Failed to close compiler: ', closeErr), err ? reject(err) : context.buildState.hasErrors ? reject(Error(RSPACK_BUILD_ERROR)) : resolve(stats);
10138
+ });
10139
+ });
10140
+ });
10141
+ let closeBuild = ()=>closingPromise ||= (async ()=>{
10142
+ unregisterRestart?.(), unregisterRestart = void 0, await context.hooks.onCloseBuild.callBatch(), await closeCompiler?.();
10143
+ })();
10144
+ return watch && (unregisterRestart = context.restartManager.registerCleanup(closeBuild), restartWatcher = watchFilesForRestart({
10145
+ watchFiles: context.normalizedConfig.dev.watchFiles,
10146
+ context,
10147
+ restartContext: {
10148
+ action: 'build',
10149
+ options: buildOptions
10150
+ }
10151
+ })), {
10152
+ stats,
10153
+ close: async ()=>{
10154
+ await restartWatcher?.close(), await closeBuild();
10155
+ }
10156
+ };
10157
+ })({
10158
+ context,
10159
+ pluginManager,
10160
+ rsbuildOptions: resolvedOptions
10161
+ }, {
10162
+ ...options
10163
+ })),
10164
+ preview: async (options = {})=>{
10165
+ context.action = 'preview', process.env.NODE_ENV || setNodeEnv('production');
10166
+ let config = await initRsbuildConfig({
10167
+ context,
10168
+ pluginManager
10169
+ }), { distPath } = context, { checkDistDir = !0 } = options;
10170
+ if (checkDistDir) {
10171
+ if (!existsSync(distPath)) throw Error(`${color.dim('[rsbuild:preview]')} The output directory ${color.yellow(distPath)} does not exist, please build the project before previewing.`);
10172
+ if (isEmptyDir(distPath)) throw Error(`${color.dim('[rsbuild:preview]')} The output directory ${color.yellow(distPath)} is empty, please build the project before previewing.`);
10173
+ }
10174
+ return startPreviewServer(context, config, options);
10175
+ },
10176
+ startDevServer: async (options = {})=>{
10177
+ context.action = 'dev', process.env.NODE_ENV || setNodeEnv('development');
10178
+ let config = await initRsbuildConfig({
10179
+ context,
10180
+ pluginManager
10181
+ });
10182
+ return (await devServer_createDevServer({
10183
+ context,
10184
+ pluginManager,
10185
+ rsbuildOptions: resolvedOptions
10186
+ }, createCompiler, config, options)).listen();
10187
+ },
10098
10188
  createCompiler,
10099
- createDevServer,
10100
- inspectConfig,
10101
- initConfigs,
10189
+ createDevServer: async (options)=>{
10190
+ context.action = 'dev', process.env.NODE_ENV || setNodeEnv('development');
10191
+ let config = await initRsbuildConfig({
10192
+ context,
10193
+ pluginManager
10194
+ });
10195
+ return devServer_createDevServer({
10196
+ context,
10197
+ pluginManager,
10198
+ rsbuildOptions: resolvedOptions
10199
+ }, createCompiler, config, options);
10200
+ },
10201
+ inspectConfig: async (inspectOptions = {})=>{
10202
+ inspectOptions.mode ? setNodeEnv(inspectOptions.mode) : process.env.NODE_ENV || setNodeEnv('development'), initAction(config.mode ?? (process.env.NODE_ENV || ''));
10203
+ let { rspackConfigs } = await initConfigs_initConfigs({
10204
+ context,
10205
+ pluginManager,
10206
+ rsbuildOptions: resolvedOptions
10207
+ });
10208
+ return inspectConfig_inspectConfig({
10209
+ context,
10210
+ pluginManager,
10211
+ rsbuildOptions: resolvedOptions,
10212
+ inspectOptions,
10213
+ bundlerConfigs: rspackConfigs
10214
+ });
10215
+ },
10216
+ initConfigs: async (options)=>{
10217
+ if (context.action && options?.action && context.action !== options.action) throw Error(`\
10218
+ [rsbuild] initConfigs() can only be called with the same action type.
10219
+ - Expected: ${context.action}
10220
+ - Actual: ${options?.action}`);
10221
+ options?.action && (context.action = options.action);
10222
+ let { rspackConfigs } = await initConfigs_initConfigs({
10223
+ context,
10224
+ pluginManager,
10225
+ rsbuildOptions: resolvedOptions
10226
+ });
10227
+ return rspackConfigs;
10228
+ },
10102
10229
  ...pick(pluginManager, [
10103
10230
  'addPlugins',
10104
10231
  'getPlugins',
@@ -10126,6 +10253,7 @@ async function createRsbuild(options = {}) {
10126
10253
  'onBeforeStartPreviewServer',
10127
10254
  'onCloseBuild',
10128
10255
  'onCloseDevServer',
10256
+ 'onClosePreviewServer',
10129
10257
  'onDevCompileDone',
10130
10258
  'onExit',
10131
10259
  'onRestart'
@@ -10160,50 +10288,11 @@ let canReadExport = (module)=>null !== module && ('object' == typeof module || '
10160
10288
  return ()=>promise ??= importer().catch((error)=>{
10161
10289
  throw promise = void 0, error;
10162
10290
  });
10163
- }, getJiti = cachedImport(()=>import("../compiled/jiti/lib/jiti.mjs")), loadWithJiti = async (configPath, exportName, fresh)=>{
10164
- let createJiti;
10165
- try {
10166
- ({ createJiti } = await getJiti());
10167
- } catch (error) {
10168
- throw Error('The "jiti" package is required to load this config. Install it with your package manager.', {
10169
- cause: error
10170
- });
10171
- }
10172
- let jiti = createJiti(configPath, {
10173
- moduleCache: !fresh,
10174
- interopDefault: !0,
10175
- nativeModules: [
10176
- "typescript"
10177
- ]
10178
- });
10179
- return 'default' === exportName ? {
10180
- configExport: await jiti.import(configPath, {
10181
- default: !0
10182
- }),
10183
- dependencies: []
10184
- } : {
10185
- configExport: getConfigExport(await jiti.import(configPath), exportName, configPath),
10186
- dependencies: []
10187
- };
10188
- }, CONFIG_META = Symbol.for('@rstackjs/load-config/meta');
10291
+ }, getJiti = cachedImport(()=>import("../compiled/jiti/lib/jiti.mjs")), CONFIG_META = Symbol.for('@rstackjs/load-config/meta');
10189
10292
  function getConfigMeta(config) {
10190
10293
  if (null !== config && 'object' == typeof config && Object.hasOwn(config, CONFIG_META)) return config[CONFIG_META];
10191
10294
  }
10192
- let getFreshImport = cachedImport(()=>import("./freshImport.js")), JS_CONFIG_REGEXP = /\.(?:js|mjs|cjs)$/, loadWithNative = async (configPath, fresh)=>{
10193
- let configFileURL = pathToFileURL(configPath).href;
10194
- if (!fresh) return {
10195
- configModule: await import(configFileURL),
10196
- dependencies: []
10197
- };
10198
- let { freshImport } = await getFreshImport(), freshImportResult = await freshImport(configFileURL);
10199
- return freshImportResult ? {
10200
- configModule: freshImportResult.result,
10201
- dependencies: freshImportResult.dependencies.sort()
10202
- } : {
10203
- configModule: await import(`${configFileURL}?t=${Date.now()}`),
10204
- dependencies: []
10205
- };
10206
- };
10295
+ let getFreshImport = cachedImport(()=>import("./freshImport.js")), JS_CONFIG_REGEXP = /\.(?:js|mjs|cjs)$/;
10207
10296
  async function dist_loadConfig({ cwd = process.cwd(), path, configFileNames = [], loader = 'auto', exportName = 'default', configParams = [], fresh = !1 } = {}) {
10208
10297
  let loadedConfig, content;
10209
10298
  if (!path && 0 === configFileNames.length) throw Error('Either `path` or at least one `configFileNames` entry must be provided.');
@@ -10227,7 +10316,21 @@ async function dist_loadConfig({ cwd = process.cwd(), path, configFileNames = []
10227
10316
  if ('native' === loader || 'auto' === loader && (process.features.typescript || process.versions.bun || process.versions.deno) || JS_CONFIG_REGEXP.test(configPath)) {
10228
10317
  let result;
10229
10318
  try {
10230
- result = await loadWithNative(configPath, fresh);
10319
+ result = await (async (configPath, fresh)=>{
10320
+ let configFileURL = pathToFileURL(configPath).href;
10321
+ if (!fresh) return {
10322
+ configModule: await import(configFileURL),
10323
+ dependencies: []
10324
+ };
10325
+ let { freshImport } = await getFreshImport(), freshImportResult = await freshImport(configFileURL);
10326
+ return freshImportResult ? {
10327
+ configModule: freshImportResult.result,
10328
+ dependencies: freshImportResult.dependencies.sort()
10329
+ } : {
10330
+ configModule: await import(`${configFileURL}?t=${Date.now()}`),
10331
+ dependencies: []
10332
+ };
10333
+ })(configPath, fresh);
10231
10334
  } catch (err) {
10232
10335
  if ('native' === loader) throw err;
10233
10336
  }
@@ -10236,7 +10339,32 @@ async function dist_loadConfig({ cwd = process.cwd(), path, configFileNames = []
10236
10339
  dependencies: result.dependencies
10237
10340
  });
10238
10341
  }
10239
- loadedConfig || (loadedConfig = await loadWithJiti(configPath, exportName, fresh));
10342
+ loadedConfig || (loadedConfig = await (async (configPath, exportName, fresh)=>{
10343
+ let createJiti;
10344
+ try {
10345
+ ({ createJiti } = await getJiti());
10346
+ } catch (error) {
10347
+ throw Error('The "jiti" package is required to load this config. Install it with your package manager.', {
10348
+ cause: error
10349
+ });
10350
+ }
10351
+ let jiti = createJiti(configPath, {
10352
+ moduleCache: !fresh,
10353
+ interopDefault: !0,
10354
+ nativeModules: [
10355
+ "typescript"
10356
+ ]
10357
+ });
10358
+ return 'default' === exportName ? {
10359
+ configExport: await jiti.import(configPath, {
10360
+ default: !0
10361
+ }),
10362
+ dependencies: []
10363
+ } : {
10364
+ configExport: getConfigExport(await jiti.import(configPath), exportName, configPath),
10365
+ dependencies: []
10366
+ };
10367
+ })(configPath, exportName, fresh));
10240
10368
  let { configExport, dependencies } = loadedConfig;
10241
10369
  if ('function' == typeof configExport) {
10242
10370
  let result = await configExport(...configParams);
@@ -10295,30 +10423,6 @@ let cliState = {
10295
10423
  options: {}
10296
10424
  }, initCliAction = (command, options)=>{
10297
10425
  process.env.NODE_ENV || (process.env.NODE_ENV = 'build' === command || 'preview' === command ? 'production' : 'development'), options.environment?.some((env)=>env.includes(',')) && (options.environment = options.environment.flatMap((env)=>env.split(','))), cliState.command = command, cliState.options = options;
10298
- }, init_loadConfig = async (root)=>{
10299
- let { options, command } = cliState, result = await loadConfig_loadConfig({
10300
- cwd: root,
10301
- path: options.config,
10302
- envMode: options.envMode,
10303
- loader: options.configLoader,
10304
- command
10305
- }), { content: config } = result;
10306
- if (config.dev ||= {}, config.source ||= {}, config.server ||= {}, options.base && (config.server.base = options.base), options.root && (config.root = root), options.mode && (config.mode = options.mode), options.logLevel && (config.logLevel = options.logLevel), options.open && !config.server?.open && (config.server.open = options.open), void 0 !== options.host && (config.server.host = options.host), void 0 !== options.port && (config.server.port = options.port), void 0 !== options.strictPort && (config.server.strictPort = options.strictPort), void 0 !== options.distPath) {
10307
- config.output ||= {};
10308
- let { distPath } = config.output;
10309
- config.output.distPath = distPath && 'object' == typeof distPath ? {
10310
- ...distPath,
10311
- root: options.distPath
10312
- } : {
10313
- root: options.distPath
10314
- };
10315
- }
10316
- if (void 0 !== options.sourceMap) {
10317
- let sourceMap = options.sourceMap;
10318
- if ('boolean' != typeof sourceMap) throw Error('The "--source-map" option only accepts a boolean value.');
10319
- config.output ||= {}, config.output.sourceMap = sourceMap;
10320
- }
10321
- return void 0 === config.dev.cliShortcuts && (config.dev.cliShortcuts = !0), result;
10322
10426
  }, init_restart = async (context)=>{
10323
10427
  let rsbuild = await init_init({
10324
10428
  isRestart: !0
@@ -10331,7 +10435,31 @@ async function init_init({ isRestart } = {}) {
10331
10435
  var envDir;
10332
10436
  let cwd = process.cwd(), root = options.root ? ensureAbsolutePath(cwd, options.root) : cwd, rsbuild = await createRsbuild({
10333
10437
  cwd: root,
10334
- config: ()=>init_loadConfig(root),
10438
+ config: ()=>(async (root)=>{
10439
+ let { options, command } = cliState, result = await loadConfig_loadConfig({
10440
+ cwd: root,
10441
+ path: options.config,
10442
+ envMode: options.envMode,
10443
+ loader: options.configLoader,
10444
+ command
10445
+ }), { content: config } = result;
10446
+ if (config.dev ||= {}, config.source ||= {}, config.server ||= {}, options.base && (config.server.base = options.base), options.root && (config.root = root), options.mode && (config.mode = options.mode), options.logLevel && (config.logLevel = options.logLevel), options.open && !config.server?.open && (config.server.open = options.open), void 0 !== options.host && (config.server.host = options.host), void 0 !== options.port && (config.server.port = options.port), void 0 !== options.strictPort && (config.server.strictPort = options.strictPort), void 0 !== options.distPath) {
10447
+ config.output ||= {};
10448
+ let { distPath } = config.output;
10449
+ config.output.distPath = distPath && 'object' == typeof distPath ? {
10450
+ ...distPath,
10451
+ root: options.distPath
10452
+ } : {
10453
+ root: options.distPath
10454
+ };
10455
+ }
10456
+ if (void 0 !== options.sourceMap) {
10457
+ let sourceMap = options.sourceMap;
10458
+ if ('boolean' != typeof sourceMap) throw Error('The "--source-map" option only accepts a boolean value.');
10459
+ config.output ||= {}, config.output.sourceMap = sourceMap;
10460
+ }
10461
+ return void 0 === config.dev.cliShortcuts && (config.dev.cliShortcuts = !0), result;
10462
+ })(root),
10335
10463
  environment: options.environment,
10336
10464
  loadEnv: !1 !== options.env && {
10337
10465
  cwd: (envDir = options.envDir) ? node_path.isAbsolute(envDir) ? envDir : node_path.join(root, envDir) : root,
@@ -10350,7 +10478,7 @@ let applyServerOptions = (command)=>{
10350
10478
  };
10351
10479
  function setupCommands(argv) {
10352
10480
  let cli = ((name = "")=>new CAC(name))('rsbuild');
10353
- cli.version("2.2.13"), 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)', {
10481
+ cli.version("2.3.3"), cli.option('--base <base>', 'Set the base path of the server').option('-c, --config <config>', 'Set the configuration file (relative or absolute path)').option('--config-loader <loader>', 'Set the config file loader (auto | jiti | native)', {
10354
10482
  default: 'auto'
10355
10483
  }).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', {
10356
10484
  type: [
@@ -10415,7 +10543,7 @@ function setupCommands(argv) {
10415
10543
  }
10416
10544
  function showGreeting() {
10417
10545
  let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
10418
- src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.2.13\n`);
10546
+ src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.3.3\n`);
10419
10547
  }
10420
10548
  function setupLogLevel(argv) {
10421
10549
  if (argv.length <= 3) return;
@@ -10437,5 +10565,5 @@ function runCLI({ argv = process.argv } = {}) {
10437
10565
  src_logger.error('Failed to start Rsbuild CLI.'), src_logger.error(err), process.exit(1);
10438
10566
  }
10439
10567
  }
10440
- let src_version = "2.2.13";
10568
+ let src_version = "2.3.3";
10441
10569
  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 };