@rsbuild/core 2.1.6 → 2.1.8

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 (162) hide show
  1. package/compiled/cors/index.d.ts +1 -1
  2. package/compiled/css-loader/index.js +2 -2
  3. package/compiled/html-rspack-plugin/index.d.ts +1 -1
  4. package/compiled/html-rspack-plugin/index.js +14 -14
  5. package/compiled/postcss/index.js +1 -1
  6. package/compiled/postcss/lib/postcss.d.ts +4 -1
  7. package/compiled/postcss/package.json +1 -1
  8. package/compiled/postcss-loader/index.js +6 -6
  9. package/compiled/rslog/index.d.ts +7 -0
  10. package/compiled/rslog/package.json +1 -1
  11. package/dist/{711.js → 626.js} +336 -252
  12. package/dist/build.d.ts +4 -0
  13. package/dist/chokidar.js +1 -1046
  14. package/{dist-types → dist}/cli/commands.d.ts +2 -2
  15. package/{dist-types → dist}/cli/init.d.ts +3 -4
  16. package/dist/client/hmr.js +1 -1
  17. package/dist/client/overlay.js +1 -1
  18. package/{dist-types → dist}/configChain.d.ts +2 -2
  19. package/dist/connect-next.js +1 -876
  20. package/dist/cors.js +1 -1
  21. package/{dist-types → dist}/createCompiler.d.ts +2 -2
  22. package/{dist-types → dist}/createContext.d.ts +4 -3
  23. package/{dist-types → dist}/createRsbuild.d.ts +1 -1
  24. package/{dist-types → dist}/defaultConfig.d.ts +1 -1
  25. package/{dist-types → dist}/helpers/compiler.d.ts +1 -1
  26. package/{dist-types → dist}/helpers/css.d.ts +1 -1
  27. package/{dist-types → dist}/helpers/format.d.ts +1 -1
  28. package/{dist-types → dist}/helpers/fs.d.ts +2 -2
  29. package/{dist-types → dist}/helpers/index.d.ts +4 -4
  30. package/{dist-types → dist}/helpers/overlayConfig.d.ts +1 -1
  31. package/{dist-types → dist}/helpers/path.d.ts +1 -1
  32. package/dist/helpers/restartManager.d.ts +13 -0
  33. package/{dist-types → dist}/helpers/stats.d.ts +2 -2
  34. package/{dist-types → dist}/helpers/url.d.ts +2 -2
  35. package/{dist-types → dist}/helpers/vendors.d.ts +1 -1
  36. package/{dist-types → dist}/hooks.d.ts +2 -1
  37. package/dist/http-proxy-middleware.js +5 -3010
  38. package/{dist-types → dist}/index.d.ts +14 -14
  39. package/dist/index.js +1 -1
  40. package/{dist-types → dist}/initConfigs.d.ts +1 -1
  41. package/{dist-types → dist}/initPlugins.d.ts +2 -2
  42. package/{dist-types → dist}/inspectConfig.d.ts +2 -2
  43. package/dist/launch-editor-middleware.js +1 -544
  44. package/{dist-types → dist}/loadConfig.d.ts +6 -6
  45. package/{dist-types → dist}/loader/cssUrlLoader.d.ts +1 -1
  46. package/{dist-types → dist}/loader/ignoreCssLoader.d.ts +1 -1
  47. package/{dist-types → dist}/loader/transformLoader.d.ts +1 -1
  48. package/{dist-types → dist}/loader/transformRawLoader.d.ts +1 -1
  49. package/{dist-types → dist}/logger.d.ts +1 -1
  50. package/dist/manifest-plugin.js +1 -692
  51. package/dist/memfs.js +1 -5695
  52. package/{dist-types → dist}/mergeConfig.d.ts +1 -1
  53. package/dist/open.js +2 -439
  54. package/{dist-types → dist}/pluginHelper.d.ts +1 -1
  55. package/{dist-types → dist}/pluginManager.d.ts +2 -2
  56. package/{dist-types → dist}/plugins/appIcon.d.ts +1 -1
  57. package/{dist-types → dist}/plugins/asset.d.ts +1 -1
  58. package/{dist-types → dist}/plugins/basic.d.ts +1 -1
  59. package/dist/plugins/cache.d.ts +2 -0
  60. package/{dist-types → dist}/plugins/cleanOutput.d.ts +1 -1
  61. package/{dist-types → dist}/plugins/css.d.ts +1 -1
  62. package/{dist-types → dist}/plugins/define.d.ts +1 -1
  63. package/dist/plugins/entry.d.ts +2 -0
  64. package/{dist-types → dist}/plugins/externals.d.ts +2 -2
  65. package/{dist-types → dist}/plugins/fileSize.d.ts +1 -1
  66. package/{dist-types → dist}/plugins/html.d.ts +1 -1
  67. package/{dist-types → dist}/plugins/inlineChunk.d.ts +1 -1
  68. package/{dist-types → dist}/plugins/lazyCompilation.d.ts +1 -1
  69. package/{dist-types → dist}/plugins/manifest.d.ts +1 -1
  70. package/{dist-types → dist}/plugins/minimize.d.ts +3 -3
  71. package/{dist-types → dist}/plugins/moduleFederation.d.ts +1 -1
  72. package/{dist-types → dist}/plugins/nodeAddons.d.ts +1 -1
  73. package/dist/plugins/nonce.d.ts +2 -0
  74. package/{dist-types → dist}/plugins/output.d.ts +1 -1
  75. package/{dist-types → dist}/plugins/progress.d.ts +1 -1
  76. package/{dist-types → dist}/plugins/resolve.d.ts +1 -1
  77. package/{dist-types → dist}/plugins/resourceHints.d.ts +1 -1
  78. package/{dist-types → dist}/plugins/rsdoctor.d.ts +1 -1
  79. package/{dist-types → dist}/plugins/rspackProfile.d.ts +1 -1
  80. package/{dist-types → dist}/plugins/server.d.ts +1 -1
  81. package/{dist-types → dist}/plugins/sourceMap.d.ts +1 -1
  82. package/{dist-types → dist}/plugins/splitChunks.d.ts +1 -1
  83. package/dist/plugins/sri.d.ts +2 -0
  84. package/{dist-types → dist}/plugins/swc.d.ts +1 -1
  85. package/{dist-types → dist}/plugins/target.d.ts +1 -1
  86. package/dist/plugins/wasm.d.ts +2 -0
  87. package/{dist-types → dist}/plugins/worker.d.ts +1 -1
  88. package/dist/range-parser.js +1 -1
  89. package/dist/restart.d.ts +15 -0
  90. package/{dist-types → dist}/rspack-plugins/RsbuildHtmlPlugin.d.ts +1 -1
  91. package/{dist-types → dist}/rspack-plugins/resource-hints/HtmlResourceHintsPlugin.d.ts +1 -1
  92. package/{dist-types → dist}/rspack-plugins/resource-hints/doesChunkBelongToHtml.d.ts +1 -1
  93. package/{dist-types → dist}/rspack-plugins/resource-hints/extractChunks.d.ts +1 -1
  94. package/{dist-types → dist}/rspackConfig.d.ts +1 -1
  95. package/{dist-types → dist}/server/assets-middleware/getFileFromUrl.d.ts +1 -1
  96. package/{dist-types → dist}/server/assets-middleware/index.d.ts +2 -2
  97. package/{dist-types → dist}/server/assets-middleware/middleware.d.ts +1 -1
  98. package/{dist-types → dist}/server/assets-middleware/setupOutputFileSystem.d.ts +1 -1
  99. package/{dist-types → dist}/server/assets-middleware/setupWriteToDisk.d.ts +2 -2
  100. package/{dist-types → dist}/server/browserLogs.d.ts +1 -1
  101. package/{dist-types → dist}/server/buildManager.d.ts +3 -3
  102. package/{dist-types → dist}/server/cliShortcuts.d.ts +2 -2
  103. package/{dist-types → dist}/server/devMiddlewares.d.ts +4 -4
  104. package/{dist-types → dist}/server/devServer.d.ts +4 -4
  105. package/{dist-types → dist}/server/environment.d.ts +1 -1
  106. package/{dist-types → dist}/server/gzipMiddleware.d.ts +1 -1
  107. package/{dist-types → dist}/server/helper.d.ts +4 -4
  108. package/{dist-types → dist}/server/historyApiFallback.d.ts +2 -2
  109. package/{dist-types → dist}/server/httpServer.d.ts +1 -1
  110. package/{dist-types → dist}/server/middlewares.d.ts +2 -2
  111. package/{dist-types → dist}/server/open.d.ts +2 -2
  112. package/{dist-types → dist}/server/previewServer.d.ts +2 -2
  113. package/{dist-types → dist}/server/proxy.d.ts +3 -3
  114. package/{dist-types → dist}/server/runner/basic.d.ts +1 -1
  115. package/{dist-types → dist}/server/runner/cjs.d.ts +2 -2
  116. package/{dist-types → dist}/server/runner/esm.d.ts +2 -2
  117. package/{dist-types → dist}/server/runner/index.d.ts +1 -1
  118. package/{dist-types → dist}/server/serverSetup.d.ts +1 -1
  119. package/{dist-types → dist}/server/socketServer.d.ts +1 -1
  120. package/{dist-types → dist}/server/watchFiles.d.ts +4 -3
  121. package/dist/sirv.js +1 -1
  122. package/dist/tinyglobby.js +1 -1670
  123. package/{dist-types → dist}/types/config.d.ts +36 -19
  124. package/{dist-types → dist}/types/context.d.ts +11 -7
  125. package/{dist-types → dist}/types/hooks.d.ts +36 -9
  126. package/dist/types/index.d.ts +8 -0
  127. package/{dist-types → dist}/types/plugin.d.ts +10 -7
  128. package/{dist-types → dist}/types/rsbuild.d.ts +21 -14
  129. package/{dist-types → dist}/types/rspack.d.ts +2 -2
  130. package/{dist-types → dist}/types/thirdParty.d.ts +5 -5
  131. package/dist/ws.js +2 -1528
  132. package/package.json +11 -12
  133. package/dist-types/build.d.ts +0 -4
  134. package/dist-types/package.json +0 -1
  135. package/dist-types/plugins/cache.d.ts +0 -2
  136. package/dist-types/plugins/entry.d.ts +0 -2
  137. package/dist-types/plugins/nonce.d.ts +0 -2
  138. package/dist-types/plugins/sri.d.ts +0 -2
  139. package/dist-types/plugins/wasm.d.ts +0 -2
  140. package/dist-types/restart.d.ts +0 -19
  141. package/dist-types/types/index.d.ts +0 -8
  142. /package/dist/{711.js.LICENSE.txt → 626.js.LICENSE.txt} +0 -0
  143. /package/{dist-types → dist}/cli/index.d.ts +0 -0
  144. /package/dist/client/{307.js → 307~0.js} +0 -0
  145. /package/{dist-types → dist}/constants.d.ts +0 -0
  146. /package/{dist-types → dist}/helpers/exitHook.d.ts +0 -0
  147. /package/{dist-types → dist}/helpers/packageJson.d.ts +0 -0
  148. /package/{dist-types → dist}/helpers/version.d.ts +0 -0
  149. /package/{dist-types → dist}/loadEnv.d.ts +0 -0
  150. /package/{dist-types → dist}/loader/workerLoader.d.ts +0 -0
  151. /package/dist/{1~rslib-runtime.js → rslib-runtime.js} +0 -0
  152. /package/{dist-types → dist}/rspack-plugins/resource-hints/getResourceType.d.ts +0 -0
  153. /package/{dist-types → dist}/server/ansiHTML.d.ts +0 -0
  154. /package/{dist-types → dist}/server/assets-middleware/parseTokenList.d.ts +0 -0
  155. /package/{dist-types → dist}/server/compileState.d.ts +0 -0
  156. /package/{dist-types → dist}/server/gracefulShutdown.d.ts +0 -0
  157. /package/{dist-types → dist}/server/hmrFallback.d.ts +0 -0
  158. /package/{dist-types → dist}/server/overlay.d.ts +0 -0
  159. /package/{dist-types → dist}/server/publicPathnames.d.ts +0 -0
  160. /package/{dist-types → dist}/server/runner/asModule.d.ts +0 -0
  161. /package/{dist-types → dist}/server/runner/type.d.ts +0 -0
  162. /package/{dist-types → dist}/types/utils.d.ts +0 -0
@@ -1,4 +1,4 @@
1
- /*! LICENSE: 711.js.LICENSE.txt */
1
+ /*! LICENSE: 626.js.LICENSE.txt */
2
2
  let runtimeProcessArgs, runtimeInfo, swcHelpersPath, pluginHelper_htmlPlugin;
3
3
  import { rspack as core_rspack } from "@rspack/core";
4
4
  import node_util, { stripVTControlCharacters } from "node:util";
@@ -11,7 +11,7 @@ import { URL as external_node_url_URL, pathToFileURL, fileURLToPath as __rspack_
11
11
  import { isPromise, isRegExp } from "node:util/types";
12
12
  import { readFile } from "node:fs/promises";
13
13
  import node_zlib from "node:zlib";
14
- import { __webpack_require__ } from "./1~rslib-runtime.js";
14
+ import { __webpack_require__ } from "./rslib-runtime.js";
15
15
  var superClass, superClass1, __rspack_import_meta_filename__ = __rspack_fileURLToPath(import.meta.url);
16
16
  let __rspack_createRequire_require = __rspack_createRequire(import.meta.url);
17
17
  __webpack_require__.add({
@@ -151,7 +151,7 @@ __webpack_require__.add({
151
151
  };
152
152
  },
153
153
  "../../node_modules/.pnpm/lilconfig@3.1.3/node_modules/lilconfig/src/index.js" (module, __unused_rspack_exports, __webpack_require__) {
154
- let path = __webpack_require__("path?aeb1"), fs = __webpack_require__("fs?8b28"), os = __webpack_require__("os"), url = __webpack_require__("url?b918"), fsReadFileAsync = fs.promises.readFile;
154
+ let path = __webpack_require__("path?37f5"), fs = __webpack_require__("fs?cdbd"), os = __webpack_require__("os"), url = __webpack_require__("url?5f07"), fsReadFileAsync = fs.promises.readFile;
155
155
  function getDefaultSearchPlaces(name, sync) {
156
156
  return [
157
157
  'package.json',
@@ -386,8 +386,8 @@ __webpack_require__.add({
386
386
  return (asyncHooks.AsyncResource && (res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn')), res && res.runInAsyncScope) ? res.runInAsyncScope.bind(res, fn, null) : fn;
387
387
  }
388
388
  },
389
- "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17/node_modules/postcss-load-config/src/index.js" (module, __unused_rspack_exports, __webpack_require__) {
390
- let yaml, { resolve } = __webpack_require__("node:path?435f"), config = __webpack_require__("../../node_modules/.pnpm/lilconfig@3.1.3/node_modules/lilconfig/src/index.js"), loadOptions = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17/node_modules/postcss-load-config/src/options.js"), loadPlugins = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17/node_modules/postcss-load-config/src/plugins.js"), req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17/node_modules/postcss-load-config/src/req.js");
389
+ "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.19/node_modules/postcss-load-config/src/index.js" (module, __unused_rspack_exports, __webpack_require__) {
390
+ let yaml, { resolve } = __webpack_require__("node:path?815c"), config = __webpack_require__("../../node_modules/.pnpm/lilconfig@3.1.3/node_modules/lilconfig/src/index.js"), loadOptions = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.19/node_modules/postcss-load-config/src/options.js"), loadPlugins = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.19/node_modules/postcss-load-config/src/plugins.js"), req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.19/node_modules/postcss-load-config/src/req.js");
391
391
  async function processResult(ctx, result) {
392
392
  let obj, file = result.filepath || '', projectConfig = ((obj = result.config) && obj.__esModule ? obj : {
393
393
  default: obj
@@ -460,8 +460,8 @@ __webpack_require__.add({
460
460
  });
461
461
  };
462
462
  },
463
- "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17/node_modules/postcss-load-config/src/options.js" (module, __unused_rspack_exports, __webpack_require__) {
464
- let req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17/node_modules/postcss-load-config/src/req.js");
463
+ "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.19/node_modules/postcss-load-config/src/options.js" (module, __unused_rspack_exports, __webpack_require__) {
464
+ let req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.19/node_modules/postcss-load-config/src/req.js");
465
465
  module.exports = async function options(config, file) {
466
466
  if (config.parser && 'string' == typeof config.parser) try {
467
467
  config.parser = await req(config.parser, file);
@@ -481,8 +481,8 @@ __webpack_require__.add({
481
481
  return config;
482
482
  };
483
483
  },
484
- "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17/node_modules/postcss-load-config/src/plugins.js" (module, __unused_rspack_exports, __webpack_require__) {
485
- let req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17/node_modules/postcss-load-config/src/req.js");
484
+ "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.19/node_modules/postcss-load-config/src/plugins.js" (module, __unused_rspack_exports, __webpack_require__) {
485
+ let req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.19/node_modules/postcss-load-config/src/req.js");
486
486
  async function load(plugin, options, file) {
487
487
  try {
488
488
  if (null == options || 0 === Object.keys(options).length) return await req(plugin, file);
@@ -498,8 +498,8 @@ __webpack_require__.add({
498
498
  }), list;
499
499
  };
500
500
  },
501
- "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17/node_modules/postcss-load-config/src/req.js" (module, __unused_rspack_exports, __webpack_require__) {
502
- let tsx, jiti, { createRequire } = __webpack_require__("node:module?1bcb"), { pathToFileURL } = __webpack_require__("node:url?b4ec"), TS_EXT_RE = /\.[mc]?ts$/, importError = [];
501
+ "../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.19/node_modules/postcss-load-config/src/req.js" (module, __unused_rspack_exports, __webpack_require__) {
502
+ let tsx, jiti, { createRequire } = __webpack_require__("node:module?f56b"), { pathToFileURL } = __webpack_require__("node:url?5295"), TS_EXT_RE = /\.[mc]?ts$/, importError = [];
503
503
  module.exports = async function req(name, rootFile = __rspack_import_meta_filename__) {
504
504
  let url = createRequire(rootFile).resolve(name);
505
505
  try {
@@ -539,7 +539,7 @@ __webpack_require__.add({
539
539
  crypto (module) {
540
540
  module.exports = __rspack_createRequire_require("crypto");
541
541
  },
542
- "fs?8b28" (module) {
542
+ "fs?cdbd" (module) {
543
543
  module.exports = __rspack_createRequire_require("fs");
544
544
  },
545
545
  http (module) {
@@ -551,31 +551,31 @@ __webpack_require__.add({
551
551
  net (module) {
552
552
  module.exports = __rspack_createRequire_require("net");
553
553
  },
554
- "node:buffer?1cd0" (module) {
554
+ "node:buffer?4a79" (module) {
555
555
  module.exports = __rspack_createRequire_require("node:buffer");
556
556
  },
557
- "node:events?3ec9" (module) {
557
+ events (module) {
558
558
  module.exports = __rspack_createRequire_require("node:events");
559
559
  },
560
- "node:fs?9592" (module) {
560
+ "node:fs?31c0" (module) {
561
561
  module.exports = __rspack_createRequire_require("node:fs");
562
562
  },
563
- "node:module?1bcb" (module) {
563
+ "node:module?f56b" (module) {
564
564
  module.exports = __rspack_createRequire_require("node:module");
565
565
  },
566
- "node:path?435f" (module) {
566
+ "node:path?815c" (module) {
567
567
  module.exports = __rspack_createRequire_require("node:path");
568
568
  },
569
- "node:stream?3c93" (module) {
569
+ "node:stream?be04" (module) {
570
570
  module.exports = __rspack_createRequire_require("node:stream");
571
571
  },
572
- "node:url?b4ec" (module) {
572
+ "node:url?5295" (module) {
573
573
  module.exports = __rspack_createRequire_require("node:url");
574
574
  },
575
575
  os (module) {
576
576
  module.exports = __rspack_createRequire_require("os");
577
577
  },
578
- "path?aeb1" (module) {
578
+ "path?37f5" (module) {
579
579
  module.exports = __rspack_createRequire_require("path");
580
580
  },
581
581
  process (module) {
@@ -584,13 +584,16 @@ __webpack_require__.add({
584
584
  stream (module) {
585
585
  module.exports = __rspack_createRequire_require("stream");
586
586
  },
587
+ "supports-color" (module) {
588
+ module.exports = __rspack_createRequire_require("supports-color");
589
+ },
587
590
  tls (module) {
588
591
  module.exports = __rspack_createRequire_require("tls");
589
592
  },
590
593
  tty (module) {
591
594
  module.exports = __rspack_createRequire_require("tty");
592
595
  },
593
- "url?b918" (module) {
596
+ "url?5f07" (module) {
594
597
  module.exports = __rspack_createRequire_require("url");
595
598
  },
596
599
  util (module) {
@@ -598,12 +601,6 @@ __webpack_require__.add({
598
601
  },
599
602
  zlib (module) {
600
603
  module.exports = __rspack_createRequire_require("zlib");
601
- },
602
- events (module) {
603
- module.exports = __rspack_createRequire_require("node:events");
604
- },
605
- "supports-color" (module) {
606
- module.exports = __rspack_createRequire_require("supports-color");
607
604
  }
608
605
  }), function checkNodeVersion() {
609
606
  let { versions } = process;
@@ -650,24 +647,31 @@ let createStyler = (style)=>(text)=>node_util.styleText(style, String(text)), co
650
647
  level: 'info'
651
648
  },
652
649
  debug: createLogType('debug', 'verbose', color.magenta)
653
- }, errorStackRegExp = /at [^\r\n]{0,200}(?::\d+:\d+[\s)]*|\(<anonymous>\)|\(index\s\d+\))$/, normalizeErrorMessage = (err)=>{
650
+ }, ANSI_REGEXP = RegExp("\x1b\\[[0-9;]*m", 'g'), errorStackRegExp = /at [^\r\n]{0,200}(?::\d+:\d+[\s)]*|\(<anonymous>\)|\(index\s\d+\))$/, isErrorStackMessage = (message)=>{
651
+ let stripped = message.replace(ANSI_REGEXP, '');
652
+ return errorStackRegExp.test(stripped);
653
+ }, normalizeErrorMessage = (err)=>{
654
654
  if (err.stack) {
655
655
  let [rawName, ...rest] = err.stack.split('\n'), name = rawName.startsWith('Error: ') ? rawName.slice(7) : rawName;
656
656
  return `${name}\n${color.gray(rest.join('\n'))}`;
657
657
  }
658
658
  return err.message;
659
659
  }, createLogger = (options = {})=>{
660
- let { level = 'info', prefix, console: console1 = globalThis.console } = options, maxLevel = level, log = (type, message, ...args)=>{
660
+ let { level = 'info', prefix, console: console1 = globalThis.console, alignMultiline } = options, maxLevel = level, log = (type, message, ...args)=>{
661
661
  let logType = LOG_TYPES[type], { level } = logType;
662
662
  if (LOG_LEVEL[level] > LOG_LEVEL[maxLevel]) return;
663
663
  if (null == message) return console1.log();
664
- let label = 'label' in logType ? logType.label : '', text = '';
665
- if (message instanceof Error) {
664
+ let label = 'label' in logType ? logType.label : '', header = label ? prefix ? `${label} ${prefix}` : label : prefix, text = '', isErrorObject = message instanceof Error;
665
+ if (isErrorObject) {
666
666
  text += normalizeErrorMessage(message);
667
667
  let { cause } = message;
668
668
  cause && (text += color.yellow('\n [cause]: '), text += cause instanceof Error ? normalizeErrorMessage(cause) : String(cause));
669
- } else text = 'error' === level && 'string' == typeof message ? message.split('\n').map((line)=>errorStackRegExp.test(line) ? color.gray(line) : line).join('\n') : `${message}`;
670
- prefix && (text = `${prefix} ${text}`), console1['error' === level || 'warn' === level ? level : 'log'](label ? `${label} ${text}` : text, ...args);
669
+ } else text = 'error' === level && 'string' == typeof message ? message.split('\n').map((line)=>isErrorStackMessage(line) ? color.gray(line) : line).join('\n') : `${message}`;
670
+ if (alignMultiline && header && !isErrorObject && text.includes('\n')) {
671
+ let indent = ' '.repeat(header.replace(ANSI_REGEXP, '').length + 1), skipStack = 'error' === level;
672
+ text = text.split('\n').map((line, i)=>0 === i || '' === line || skipStack && isErrorStackMessage(line) ? line : indent + line).join('\n');
673
+ }
674
+ console1['error' === level || 'warn' === level ? level : 'log'](header ? `${header} ${text}` : text, ...args);
671
675
  }, logger = {
672
676
  greet: (message)=>log('log', supportsTrueColor ? `\x1b[1;38;2;132;225;199m${message}\x1b[39;22m` : color.bold(color.cyan(message)))
673
677
  };
@@ -2501,6 +2505,7 @@ function createAsyncHook() {
2501
2505
  function initHooks() {
2502
2506
  return {
2503
2507
  onExit: createAsyncHook(),
2508
+ onRestart: createAsyncHook(),
2504
2509
  onCloseBuild: createAsyncHook(),
2505
2510
  onAfterBuild: createAsyncHook(),
2506
2511
  onBeforeBuild: createAsyncHook(),
@@ -3269,6 +3274,7 @@ function initPluginAPI({ context, pluginManager }) {
3269
3274
  getNormalizedConfig,
3270
3275
  isPluginExists: pluginManager.isPluginExists,
3271
3276
  onExit,
3277
+ onRestart: hooks.onRestart.tap,
3272
3278
  onAfterBuild: hooks.onAfterBuild.tap,
3273
3279
  onCloseBuild: hooks.onCloseBuild.tap,
3274
3280
  onBeforeBuild: hooks.onBeforeBuild.tap,
@@ -3383,6 +3389,8 @@ function createPublicContext(context) {
3383
3389
  'action',
3384
3390
  'version',
3385
3391
  'rootPath',
3392
+ 'configFile',
3393
+ 'configFileDependencies',
3386
3394
  'distPath',
3387
3395
  'devServer',
3388
3396
  'cachePath',
@@ -3396,11 +3404,13 @@ function createPublicContext(context) {
3396
3404
  set: (target, prop)=>(target.logger.error(`Context is readonly, you can not assign to the "context.${prop}" prop.`), !0)
3397
3405
  });
3398
3406
  }
3399
- async function createContext(options, userConfig, logger) {
3400
- 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;
3407
+ async function createContext(options, userConfig, logger, loadConfigResult) {
3408
+ 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();
3401
3409
  return {
3402
- version: "2.1.6",
3410
+ version: "2.1.8",
3403
3411
  rootPath,
3412
+ configFile: loadConfigResult?.filePath ?? userConfig._privateMeta?.configFilePath,
3413
+ configFileDependencies: loadConfigResult?.dependencies ?? userConfig._privateMeta?.configFileDependencies ?? [],
3404
3414
  distPath: '',
3405
3415
  cachePath,
3406
3416
  logger,
@@ -3409,7 +3419,38 @@ async function createContext(options, userConfig, logger) {
3409
3419
  environments: {},
3410
3420
  environmentList: [],
3411
3421
  publicPathnames: [],
3412
- hooks: initHooks(),
3422
+ hooks,
3423
+ restartManager: (({ onRestart, restart })=>{
3424
+ let cleanups = new Set();
3425
+ return {
3426
+ canRestart: !!restart,
3427
+ registerCleanup: (cleanup)=>(cleanups.add(cleanup), ()=>{
3428
+ cleanups.delete(cleanup);
3429
+ }),
3430
+ async requestRestart (context) {
3431
+ let firstError;
3432
+ if (!restart) return await onRestart(context), !1;
3433
+ let currentCleanups = cleanups;
3434
+ cleanups = new Set();
3435
+ let hasError = !1;
3436
+ try {
3437
+ await onRestart(context);
3438
+ } catch (error) {
3439
+ hasError = !0, firstError = error;
3440
+ }
3441
+ for (let cleanup of currentCleanups)try {
3442
+ await cleanup();
3443
+ } catch (error) {
3444
+ hasError || (hasError = !0, firstError = error);
3445
+ }
3446
+ if (hasError) throw firstError;
3447
+ return restart(context);
3448
+ }
3449
+ };
3450
+ })({
3451
+ onRestart: hooks.onRestart.callBatch,
3452
+ restart: options.restart
3453
+ }),
3413
3454
  config: {
3414
3455
  ...rsbuildConfig
3415
3456
  },
@@ -3926,7 +3967,7 @@ async function initRsbuildConfig({ context, pluginManager }) {
3926
3967
  }
3927
3968
  return tsconfigPaths.size && 'prefer-tsconfig' === normalizedBaseConfig.resolve.aliasStrategy && normalizedBaseConfig.dev.watchFiles.push({
3928
3969
  paths: Array.from(tsconfigPaths),
3929
- type: 'reload-server'
3970
+ type: 'restart'
3930
3971
  }), context.normalizedConfig = {
3931
3972
  ...normalizedBaseConfig,
3932
3973
  environments
@@ -4143,8 +4184,145 @@ async function createCompiler_createCompiler(options) {
4143
4184
  rspackConfigs
4144
4185
  };
4145
4186
  }
4146
- let RSPACK_BUILD_ERROR = 'Rspack build failed.', build_build = async (initOptions, { watch } = {})=>{
4147
- let { context } = initOptions, { logger } = context, { compiler, rspackConfigs } = await createCompiler_createCompiler(initOptions);
4187
+ let DEFAULT_WATCH_FILE_EVENTS = [
4188
+ 'add',
4189
+ 'change',
4190
+ 'unlink'
4191
+ ];
4192
+ async function setupWatchFiles(options) {
4193
+ let { config, root, buildManager } = options, { hmr, liveReload } = config.dev;
4194
+ if (!hmr && !liveReload || !buildManager) return;
4195
+ let closeDevFilesWatcher = await watchDevFiles(config.dev, buildManager, root), serverFilesWatcher = await watchServerFiles(config.server, buildManager, root);
4196
+ return {
4197
+ async close () {
4198
+ await Promise.all([
4199
+ closeDevFilesWatcher?.(),
4200
+ serverFilesWatcher?.close()
4201
+ ]);
4202
+ }
4203
+ };
4204
+ }
4205
+ async function watchDevFiles(devConfig, buildManager, root) {
4206
+ let { watchFiles } = devConfig;
4207
+ if (!watchFiles) return;
4208
+ let watchers = [];
4209
+ for (let { paths, events, options, type } of helpers_castArray(watchFiles)){
4210
+ let watchOptions = prepareWatchOptions(paths, options, type, events), watcher = await startWatchFiles(watchOptions, buildManager, root);
4211
+ watcher && watchers.push(watcher);
4212
+ }
4213
+ return async ()=>{
4214
+ for (let watcher of watchers)await watcher.close();
4215
+ };
4216
+ }
4217
+ function watchServerFiles({ publicDir }, buildManager, root) {
4218
+ if (!publicDir.length) return;
4219
+ let watchPaths = publicDir.filter((item)=>item.watch).map((item)=>item.name);
4220
+ if (watchPaths.length) return startWatchFiles(prepareWatchOptions(watchPaths), buildManager, root);
4221
+ }
4222
+ function prepareWatchOptions(paths, options = {}, type, events) {
4223
+ return {
4224
+ paths: 'string' == typeof paths ? [
4225
+ paths
4226
+ ] : paths,
4227
+ events,
4228
+ options,
4229
+ type
4230
+ };
4231
+ }
4232
+ let GLOB_REGEX = /[*?{}[\]()!+|]/;
4233
+ async function createChokidar(pathOrGlobs, root, options) {
4234
+ let { default: chokidar } = await import("./chokidar.js"), watchFiles = new Set(), globPatterns = pathOrGlobs.filter((pathOrGlob)=>!!GLOB_REGEX.test(pathOrGlob) || (watchFiles.add(pathOrGlob), !1));
4235
+ if (globPatterns.length) {
4236
+ let { glob } = await import("./tinyglobby.js");
4237
+ for (let file of (await glob(globPatterns, {
4238
+ cwd: root,
4239
+ absolute: !0
4240
+ })))watchFiles.add(file);
4241
+ }
4242
+ return chokidar.watch(Array.from(watchFiles), options);
4243
+ }
4244
+ async function startWatchFiles({ paths, events, options, type = 'reload-page' }, buildManager, root) {
4245
+ if ('reload-page' !== type || events?.length === 0) return;
4246
+ let watcher = await createChokidar(paths, root, {
4247
+ ignoreInitial: !0,
4248
+ ...options
4249
+ }), reloadPage = ()=>{
4250
+ buildManager.socketServer.sendMessage({
4251
+ type: 'full-reload'
4252
+ });
4253
+ };
4254
+ for (let event of events ? new Set(events) : DEFAULT_WATCH_FILE_EVENTS)watcher.on(event, reloadPage);
4255
+ return watcher;
4256
+ }
4257
+ let requestRestart = ({ clear = !0, logger, restartContext, restartManager })=>{
4258
+ let { action, filePath } = restartContext;
4259
+ if (restartManager.canRestart) {
4260
+ clear && isTTY() && !process.env.DEBUG && process.stdout.write('\x1B[H\x1B[2J');
4261
+ let id = 'dev' === action ? 'server' : 'build';
4262
+ if (filePath) {
4263
+ let filename = node_path.basename(filePath);
4264
+ logger.info(`restarting ${id} as ${color.yellow(filename)} changed\n`);
4265
+ } else logger.info(`restarting ${id}...\n`);
4266
+ }
4267
+ return restartManager.requestRestart(restartContext);
4268
+ };
4269
+ function watchFilesForRestart({ watchFiles, context, restartContext }) {
4270
+ let closePromise, defaultFiles = context.configFile ? [
4271
+ context.configFile,
4272
+ ...context.configFileDependencies
4273
+ ] : [];
4274
+ if (!watchFiles.length && !defaultFiles.length) return;
4275
+ let watchGroups = [];
4276
+ for (let { paths, events, options, type } of watchFiles){
4277
+ if ('restart' !== type && 'reload-server' !== type || events?.length === 0) continue;
4278
+ let files = helpers_castArray(paths);
4279
+ files.length && (options || events ? watchGroups.push({
4280
+ files,
4281
+ events,
4282
+ options
4283
+ }) : defaultFiles.push(...files));
4284
+ }
4285
+ if (defaultFiles.length && watchGroups.push({
4286
+ files: defaultFiles
4287
+ }), !watchGroups.length) return;
4288
+ let { logger, restartManager, rootPath: root } = context, restarting = !1, onWatchEvent = async (event, filePath, cwd)=>{
4289
+ if (restarting || closePromise) return;
4290
+ restarting = !0;
4291
+ let absoluteFilePath = node_path.resolve(cwd, filePath);
4292
+ try {
4293
+ await requestRestart({
4294
+ restartContext: {
4295
+ ...restartContext,
4296
+ event,
4297
+ filePath: absoluteFilePath
4298
+ },
4299
+ logger,
4300
+ restartManager
4301
+ }) ? await close() : restartManager.canRestart && logger.error('build' === restartContext.action ? 'Restart build failed.' : 'Restart server failed.');
4302
+ } catch (error) {
4303
+ logger.error(error);
4304
+ } finally{
4305
+ restarting = !1;
4306
+ }
4307
+ }, watchersPromise = Promise.all(watchGroups.map(async ({ files, events, options })=>{
4308
+ try {
4309
+ let watcher = await createChokidar(files, root, {
4310
+ ignoreInitial: !0,
4311
+ ignorePermissionErrors: !0,
4312
+ ...options
4313
+ }), cwd = options?.cwd ?? root;
4314
+ for (let event of events ? new Set(events) : DEFAULT_WATCH_FILE_EVENTS)watcher.on(event, (filePath)=>onWatchEvent(event, filePath, cwd));
4315
+ return watcher;
4316
+ } catch (error) {
4317
+ logger.error(error);
4318
+ }
4319
+ })), close = ()=>(closePromise || (closePromise = watchersPromise.then((watchers)=>Promise.all(watchers.map((watcher)=>watcher?.close()))).then(()=>{})), closePromise);
4320
+ return {
4321
+ close
4322
+ };
4323
+ }
4324
+ let RSPACK_BUILD_ERROR = 'Rspack build failed.', build_build = async (initOptions, buildOptions = {})=>{
4325
+ let stats, closeCompiler, closingPromise, unregisterRestart, restartWatcher, { watch } = buildOptions, { context } = initOptions, { logger } = context, { compiler, rspackConfigs } = await createCompiler_createCompiler(initOptions);
4148
4326
  if ((({ context, isWatch, compiler, rspackConfigs, MultiStatsCtor })=>{
4149
4327
  let isFirstCompile = !0, { environmentList } = context, onDone = async (stats)=>{
4150
4328
  let promise = context.hooks.onAfterBuild.callBatch({
@@ -4206,28 +4384,35 @@ let RSPACK_BUILD_ERROR = 'Rspack build failed.', build_build = async (initOption
4206
4384
  MultiStatsCtor: core_rspack.MultiStats
4207
4385
  }), watch) {
4208
4386
  let watchOptions = rspackConfigs.map((options)=>options.watchOptions || {});
4209
- return compiler.watch(watchOptions.length > 1 ? watchOptions : watchOptions[0] || {}, (err)=>{
4387
+ compiler.watch(watchOptions.length > 1 ? watchOptions : watchOptions[0] || {}, (err)=>{
4210
4388
  err && logger.error(err);
4211
- }), {
4212
- close: ()=>new Promise((resolve)=>{
4213
- compiler.close(()=>{
4214
- resolve();
4215
- });
4216
- })
4217
- };
4218
- }
4219
- let { stats } = await new Promise((resolve, reject)=>{
4389
+ }), closeCompiler = ()=>new Promise((resolve)=>{
4390
+ compiler.close(()=>{
4391
+ resolve();
4392
+ });
4393
+ });
4394
+ } else stats = await new Promise((resolve, reject)=>{
4220
4395
  compiler.run((err, stats)=>{
4221
4396
  compiler.close((closeErr)=>{
4222
- closeErr && logger.error('Failed to close compiler: ', closeErr), err ? reject(err) : context.buildState.hasErrors ? reject(Error(RSPACK_BUILD_ERROR)) : resolve({
4223
- stats
4224
- });
4397
+ closeErr && logger.error('Failed to close compiler: ', closeErr), err ? reject(err) : context.buildState.hasErrors ? reject(Error(RSPACK_BUILD_ERROR)) : resolve(stats);
4225
4398
  });
4226
4399
  });
4227
4400
  });
4228
- return {
4401
+ let closeBuild = ()=>closingPromise ||= (async ()=>{
4402
+ unregisterRestart?.(), unregisterRestart = void 0, await context.hooks.onCloseBuild.callBatch(), await closeCompiler?.();
4403
+ })();
4404
+ return watch && (unregisterRestart = context.restartManager.registerCleanup(closeBuild), restartWatcher = watchFilesForRestart({
4405
+ watchFiles: context.normalizedConfig.dev.watchFiles,
4406
+ context,
4407
+ restartContext: {
4408
+ action: 'build',
4409
+ options: buildOptions
4410
+ }
4411
+ })), {
4229
4412
  stats,
4230
- close: async ()=>{}
4413
+ close: async ()=>{
4414
+ await restartWatcher?.close(), await closeBuild();
4415
+ }
4231
4416
  };
4232
4417
  }, main = __webpack_require__("../../node_modules/.pnpm/dotenv-expand@13.0.0_patch_hash=5ff37847fa487be2db4e4f14c2b21937f4e51cc7a43deea4506d4aaf3fa6149c/node_modules/dotenv-expand/lib/main.js"), DOTENV_LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;
4233
4418
  function loadEnv_parse(src) {
@@ -4746,7 +4931,7 @@ function getRegExpForExts(exts) {
4746
4931
  function getCacheDirectory({ cacheDirectory }, context) {
4747
4932
  return cacheDirectory ? external_node_path_isAbsolute(cacheDirectory) ? cacheDirectory : join(context.rootPath, cacheDirectory) : join(context.cachePath, 'rspack');
4748
4933
  }
4749
- async function getBuildDependencies(context, config, environmentContext, additionalDependencies) {
4934
+ async function getBuildDependencies(context, environmentContext, additionalDependencies) {
4750
4935
  let rootPackageJson = join(context.rootPath, 'package.json'), browserslistConfig = join(context.rootPath, '.browserslistrc'), buildDependencies = {};
4751
4936
  await isFileExists(rootPackageJson) && (buildDependencies.packageJson = [
4752
4937
  rootPackageJson
@@ -4754,8 +4939,9 @@ async function getBuildDependencies(context, config, environmentContext, additio
4754
4939
  let { tsconfigPath } = environmentContext;
4755
4940
  tsconfigPath && (buildDependencies.tsconfig = [
4756
4941
  tsconfigPath
4757
- ]), config._privateMeta?.configFilePath && (buildDependencies.rsbuildConfig = [
4758
- config._privateMeta.configFilePath
4942
+ ]), context.configFile && (buildDependencies.rsbuildConfig = [
4943
+ context.configFile,
4944
+ ...context.configFileDependencies
4759
4945
  ]), await isFileExists(browserslistConfig) && (buildDependencies.browserslistrc = [
4760
4946
  browserslistConfig
4761
4947
  ]);
@@ -4843,7 +5029,7 @@ function parseMinifyOptions(config) {
4843
5029
  cssOptions: minify.cssOptions
4844
5030
  };
4845
5031
  }
4846
- let postcss_load_config_src = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.17/node_modules/postcss-load-config/src/index.js");
5032
+ let postcss_load_config_src = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.7.0_postcss@8.5.19/node_modules/postcss-load-config/src/index.js");
4847
5033
  var postcss_load_config_src_default = __webpack_require__.n(postcss_load_config_src);
4848
5034
  async function getLightningCSSLoaderOptions(config, targets, minify) {
4849
5035
  let userOptions = 'object' == typeof config.tools.lightningcssLoader ? config.tools.lightningcssLoader : {}, initialOptions = {
@@ -5095,7 +5281,7 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
5095
5281
  if (!showTotal && !showDetail) return {
5096
5282
  logs
5097
5283
  };
5098
- let relativeDistPath = node_path.relative(rootPath, distPath), snapshot = saveSnapshot ? {
5284
+ let relativeDistPath = node_path.relative(rootPath, distPath), rootFolderLabel = `${relativeDistPath || '.'}${node_path.sep}`, snapshot = saveSnapshot ? {
5099
5285
  files: {},
5100
5286
  totalSize: 0,
5101
5287
  totalGzipSize: 0
@@ -5117,7 +5303,7 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
5117
5303
  isSignificantDiff(gzipDiff) && (gzipSizeLabel += ` ${formatDiff(gzipDiff).label}`);
5118
5304
  }
5119
5305
  }
5120
- let separatorIndex = filePath.lastIndexOf('/'), folderLabel = (-1 === separatorIndex ? node_path.join(relativeDistPath, '.') : node_path.join(relativeDistPath, filePath.slice(0, separatorIndex))) + node_path.sep, filename = -1 === separatorIndex ? filePath : filePath.slice(separatorIndex + 1);
5306
+ let separatorIndex = filePath.lastIndexOf('/'), folderLabel = -1 === separatorIndex ? rootFolderLabel : `${node_path.join(relativeDistPath, filePath.slice(0, separatorIndex))}${node_path.sep}`, filename = -1 === separatorIndex ? filePath : filePath.slice(separatorIndex + 1);
5121
5307
  return {
5122
5308
  filePath,
5123
5309
  filenameLabel: color.dim(folderLabel) + (JS_REGEX.test(filename) ? color.cyan(filename) : filename.endsWith('.css') ? color.yellow(filename) : filename.endsWith('.html') ? color.green(filename) : color.magenta(filename)),
@@ -5806,6 +5992,8 @@ async function open_open({ port, routes, config, protocol, clearCache, logger })
5806
5992
  for (let url of (targets.length ? urls.push(...targets.map((target)=>resolveUrl(replacePortPlaceholder(target, port), baseUrl))) : routes.length ? urls.push(`${baseUrl}${routes[0].pathname}`) : urls.push(baseUrl), before && await before(), urls))openedURLs.includes(url) || (openBrowser(url, logger), openedURLs.push(url));
5807
5993
  }
5808
5994
  let getServerUrlFromClientConfig = async (config, context)=>{
5995
+ let { assetPrefix } = config.dev;
5996
+ if (!(!0 === assetPrefix || 'string' == typeof assetPrefix && isURL(assetPrefix))) return;
5809
5997
  let { devServer } = context;
5810
5998
  if (!devServer) return;
5811
5999
  let { client } = config.dev, hasClientHost = !!client.host, hasClientPort = void 0 !== client.port && '' !== client.port;
@@ -7953,69 +8141,14 @@ async function applyServerSetup(setup, context) {
7953
8141
  }
7954
8142
  return postCallbacks;
7955
8143
  }
7956
- async function setupWatchFiles(options) {
7957
- let { config, root, buildManager } = options, { hmr, liveReload } = config.dev;
7958
- if (!hmr && !liveReload || !buildManager) return;
7959
- let closeDevFilesWatcher = await watchDevFiles(config.dev, buildManager, root), serverFilesWatcher = await watchServerFiles(config.server, buildManager, root);
7960
- return {
7961
- async close () {
7962
- await Promise.all([
7963
- closeDevFilesWatcher?.(),
7964
- serverFilesWatcher?.close()
7965
- ]);
7966
- }
7967
- };
7968
- }
7969
- async function watchDevFiles(devConfig, buildManager, root) {
7970
- let { watchFiles } = devConfig;
7971
- if (!watchFiles) return;
7972
- let watchers = [];
7973
- for (let { paths, options, type } of helpers_castArray(watchFiles)){
7974
- let watchOptions = prepareWatchOptions(paths, options, type), watcher = await startWatchFiles(watchOptions, buildManager, root);
7975
- watcher && watchers.push(watcher);
7976
- }
7977
- return async ()=>{
7978
- for (let watcher of watchers)await watcher.close();
7979
- };
7980
- }
7981
- function watchServerFiles({ publicDir }, buildManager, root) {
7982
- if (!publicDir.length) return;
7983
- let watchPaths = publicDir.filter((item)=>item.watch).map((item)=>item.name);
7984
- if (watchPaths.length) return startWatchFiles(prepareWatchOptions(watchPaths), buildManager, root);
7985
- }
7986
- function prepareWatchOptions(paths, options = {}, type) {
7987
- return {
7988
- paths: 'string' == typeof paths ? [
7989
- paths
7990
- ] : paths,
7991
- options,
7992
- type
7993
- };
7994
- }
7995
- let GLOB_REGEX = /[*?{}[\]()!+|]/;
7996
- async function createChokidar(pathOrGlobs, root, options) {
7997
- let { default: chokidar } = await import("./chokidar.js"), watchFiles = new Set(), globPatterns = pathOrGlobs.filter((pathOrGlob)=>!!GLOB_REGEX.test(pathOrGlob) || (watchFiles.add(pathOrGlob), !1));
7998
- if (globPatterns.length) {
7999
- let { glob } = await import("./tinyglobby.js");
8000
- for (let file of (await glob(globPatterns, {
8001
- cwd: root,
8002
- absolute: !0
8003
- })))watchFiles.add(file);
8004
- }
8005
- return chokidar.watch(Array.from(watchFiles), options);
8006
- }
8007
- async function startWatchFiles({ paths, options, type = 'reload-page' }, buildManager, root) {
8008
- if ('reload-page' !== type) return;
8009
- let watcher = await createChokidar(paths, root, options);
8010
- return watcher.on('change', ()=>{
8011
- buildManager.socketServer.sendMessage({
8012
- type: 'full-reload'
8013
- });
8014
- }), watcher;
8015
- }
8016
- async function devServer_createDevServer(options, createCompiler, config, { getPortSilently, runCompile = !0 } = {}) {
8144
+ async function devServer_createDevServer(options, createCompiler, config, devServerOptions = {}) {
8017
8145
  var environmentCount;
8018
- let stats, waiters, { context } = options, { logger } = context;
8146
+ let closingPromise, unregisterRestart, stats, waiters, { getPortSilently, runCompile = !0 } = devServerOptions, restartContext = {
8147
+ action: 'dev',
8148
+ options: pick(devServerOptions, [
8149
+ 'getPortSilently'
8150
+ ])
8151
+ }, { context } = options, { logger } = context;
8019
8152
  logger.debug('create dev server');
8020
8153
  let { port, portTip } = await resolvePort(config), { middlewareMode, host } = config.server, isHttps = !!config.server.https, routes = getRoutes(context), fallbackPathname = 0 === routes.length && context.environmentList.some((item)=>'web' === item.config.output.target) ? config.server.base : void 0;
8021
8154
  context.devServer = {
@@ -8086,12 +8219,22 @@ async function devServer_createDevServer(options, createCompiler, config, { getP
8086
8219
  protocol,
8087
8220
  clearCache: !0,
8088
8221
  logger
8089
- }), state = {}, cleanupGracefulShutdown = middlewareMode ? null : setupGracefulShutdown(), closingPromise = null, closeServer = async ()=>(closingPromise || (closingPromise = (async ()=>{
8222
+ }), state = {}, cleanupGracefulShutdown = middlewareMode ? null : setupGracefulShutdown(), closeServerResources = ()=>(closingPromise || (unregisterRestart?.(), unregisterRestart = void 0, closingPromise = (async ()=>{
8090
8223
  removeCleanup(closeServer), cleanupGracefulShutdown?.(), await context.hooks.onCloseDevServer.callBatch(), await Promise.all([
8091
8224
  state.devMiddlewares?.close(),
8092
8225
  state.fileWatcher?.close()
8093
8226
  ]);
8094
- })()), closingPromise);
8227
+ })()), closingPromise), closeServer = async ()=>{
8228
+ await state.restartWatcher?.close(), await closeServerResources();
8229
+ }, restartServer = async ()=>{
8230
+ let restarted = await requestRestart({
8231
+ restartContext,
8232
+ clear: !1,
8233
+ logger,
8234
+ restartManager: context.restartManager
8235
+ });
8236
+ return restarted && await state.restartWatcher?.close(), restarted;
8237
+ };
8095
8238
  middlewareMode || registerCleanup(closeServer);
8096
8239
  let beforeCreateCompiler = async ()=>{
8097
8240
  if (printUrls(), cliShortcutsEnabled) {
@@ -8099,10 +8242,7 @@ async function devServer_createDevServer(options, createCompiler, config, { getP
8099
8242
  openPage,
8100
8243
  closeServer,
8101
8244
  printUrls,
8102
- restartServer: ()=>restartDevServer({
8103
- clear: !1,
8104
- logger
8105
- }),
8245
+ restartServer: context.restartManager.canRestart ? restartServer : void 0,
8106
8246
  help: shortcutsOptions.help,
8107
8247
  customShortcuts: shortcutsOptions.custom,
8108
8248
  logger
@@ -8163,7 +8303,7 @@ async function devServer_createDevServer(options, createCompiler, config, { getP
8163
8303
  port
8164
8304
  }, async (err)=>{
8165
8305
  if (err) throw err;
8166
- middlewares.use(optionsFallbackMiddleware), middlewares.use(notFoundMiddleware), state.devMiddlewares && httpServer.on('upgrade', state.devMiddlewares.onUpgrade), logger.debug('listen dev server done'), await devServer.afterListen(), onBeforeRestartServer(devServer.close), resolve({
8306
+ middlewares.use(optionsFallbackMiddleware), middlewares.use(notFoundMiddleware), state.devMiddlewares && httpServer.on('upgrade', state.devMiddlewares.onUpgrade), logger.debug('listen dev server done'), await devServer.afterListen(), resolve({
8167
8307
  port,
8168
8308
  urls: urls.map((item)=>item.url),
8169
8309
  server: devServer
@@ -8205,7 +8345,11 @@ async function devServer_createDevServer(options, createCompiler, config, { getP
8205
8345
  devServer,
8206
8346
  context,
8207
8347
  postCallbacks
8208
- }), state.buildManager?.watch(), logger.debug('create dev server done'), devServer;
8348
+ }), state.buildManager?.watch(), unregisterRestart = context.restartManager.registerCleanup(closeServerResources), state.restartWatcher = watchFilesForRestart({
8349
+ watchFiles: config.dev.watchFiles,
8350
+ context,
8351
+ restartContext
8352
+ }), logger.debug('create dev server done'), devServer;
8209
8353
  }
8210
8354
  async function startPreviewServer(context, config, { getPortSilently } = {}) {
8211
8355
  let environmentList, { logger } = context, { connect } = await import("./connect-next.js"), middlewares = connect(), { port, portTip } = await resolvePort(config), serverConfig = config.server, { host, headers, proxy, historyApiFallback, compress, base, cors } = serverConfig, assetPrefixes = context.environmentList.map((environment)=>environment.config.output.assetPrefix);
@@ -8437,7 +8581,7 @@ function applyDefaultPlugins(pluginManager, context) {
8437
8581
  let { config } = environment, { buildCache = !1 } = config.performance;
8438
8582
  if (!1 === buildCache) return;
8439
8583
  cacheEnabled = !0;
8440
- let { context } = api, cacheConfig = 'boolean' == typeof buildCache ? {} : buildCache, cacheDirectory = getCacheDirectory(cacheConfig, context), buildDependencies = await getBuildDependencies(context, config, environment, cacheConfig.buildDependencies), cacheVersion = Array.isArray(cacheConfig.cacheDigest) && cacheConfig.cacheDigest.length ? `${environment.name}-${env}-${await helpers_hash(JSON.stringify(cacheConfig.cacheDigest))}` : `${environment.name}-${env}`;
8584
+ 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}`;
8441
8585
  chain.cache({
8442
8586
  type: 'persistent',
8443
8587
  version: cacheVersion,
@@ -8562,7 +8706,7 @@ function applyDefaultPlugins(pluginManager, context) {
8562
8706
  let showDiff = environments.some((environment)=>{
8563
8707
  let { printFileSize } = environment.config.performance;
8564
8708
  return 'object' == typeof printFileSize && !!printFileSize.diff;
8565
- }), { configFilePath } = api.getNormalizedConfig()._privateMeta || {}, snapshotHash = showDiff && configFilePath ? await helpers_hash(configFilePath) : '', snapshotPath = showDiff ? getSnapshotPath(api.context.cachePath, snapshotHash) : '', prevSnapshots = showDiff ? await loadPrevSnapshots(snapshotPath) : null, nextSnapshots = {}, logs = await Promise.all(environments.map(async ({ name, index, config, distPath })=>{
8709
+ }), { configFile } = api.context, snapshotHash = showDiff && configFile ? await helpers_hash(configFile) : '', snapshotPath = showDiff ? getSnapshotPath(api.context.cachePath, snapshotHash) : '', prevSnapshots = showDiff ? await loadPrevSnapshots(snapshotPath) : null, nextSnapshots = {}, logs = await Promise.all(environments.map(async ({ name, index, config, distPath })=>{
8566
8710
  let statsItem = 'stats' in stats ? stats.stats[index] : stats, { logs: sizeLogs, snapshot } = await printFileSizes(((config)=>{
8567
8711
  let { printFileSize } = config.performance, defaultConfig = {
8568
8712
  total: !0,
@@ -9054,9 +9198,16 @@ try {
9054
9198
  setup (api) {
9055
9199
  api.modifyBundlerChain(async (chain, { environment, CHAIN_ID, rspack })=>{
9056
9200
  let { config } = environment, { minifyJs, minifyCss, jsOptions, cssOptions } = parseMinifyOptions(config);
9057
- if (chain.optimization.minimize(minifyJs || minifyCss), minifyJs && chain.optimization.minimizer(CHAIN_ID.MINIMIZER.JS).use(rspack.SwcJsMinimizerRspackPlugin, [
9058
- getSwcMinimizerOptions(config, jsOptions)
9059
- ]).end(), minifyCss) {
9201
+ if (chain.optimization.minimize(minifyJs || minifyCss), minifyJs) {
9202
+ let registerJsMinimizer = (jsOptionsItem, index = 0)=>{
9203
+ let minimizerId = 0 === index ? CHAIN_ID.MINIMIZER.JS : `${CHAIN_ID.MINIMIZER.JS}-${index}`;
9204
+ chain.optimization.minimizer(minimizerId).use(rspack.SwcJsMinimizerRspackPlugin, [
9205
+ getSwcMinimizerOptions(config, jsOptionsItem)
9206
+ ]).end();
9207
+ };
9208
+ Array.isArray(jsOptions) ? 0 === jsOptions.length ? registerJsMinimizer() : jsOptions.forEach(registerJsMinimizer) : registerJsMinimizer(jsOptions);
9209
+ }
9210
+ if (minifyCss) {
9060
9211
  let loaderOptions = await getLightningCSSLoaderOptions(config, environment.browserslist, !0), defaultOptions = {
9061
9212
  minimizerOptions: {
9062
9213
  targets: isPlainObject(loaderOptions.targets) ? environment.browserslist : loaderOptions.targets,
@@ -9070,10 +9221,13 @@ try {
9070
9221
  'errorRecovery'
9071
9222
  ])
9072
9223
  }
9073
- }, mergedOptions = cssOptions ? cjs_0_default()(defaultOptions, cssOptions) : defaultOptions;
9074
- chain.optimization.minimizer(CHAIN_ID.MINIMIZER.CSS).use(rspack.LightningCssMinimizerRspackPlugin, [
9075
- mergedOptions
9076
- ]).end();
9224
+ }, registerCssMinimizer = (cssOptionsItem, index = 0)=>{
9225
+ let options = cssOptionsItem ? cjs_0_default()(defaultOptions, cssOptionsItem) : defaultOptions, minimizerId = 0 === index ? CHAIN_ID.MINIMIZER.CSS : `${CHAIN_ID.MINIMIZER.CSS}-${index}`;
9226
+ chain.optimization.minimizer(minimizerId).use(rspack.LightningCssMinimizerRspackPlugin, [
9227
+ options
9228
+ ]).end();
9229
+ };
9230
+ Array.isArray(cssOptions) ? 0 === cssOptions.length ? registerCssMinimizer() : cssOptions.forEach(registerCssMinimizer) : registerCssMinimizer(cssOptions);
9077
9231
  }
9078
9232
  });
9079
9233
  }
@@ -9418,7 +9572,7 @@ try {
9418
9572
  api.modifyBundlerChain(async (chain, { CHAIN_ID, environment, isDev })=>{
9419
9573
  let { output: { manifest }, dev: { writeToDisk } } = environment.config;
9420
9574
  if (!1 === manifest) return;
9421
- let manifestOptions = normalizeManifestObjectConfig(manifest), { RspackManifestPlugin } = await import("./manifest-plugin.js").then(__webpack_require__.bind(__webpack_require__, "../../node_modules/.pnpm/rspack-manifest-plugin@5.2.2_@rspack+core@2.1.4/node_modules/rspack-manifest-plugin/dist/index.js")), { htmlPaths } = environment, filter = manifestOptions.filter ?? ((file)=>!file.name.endsWith('.LICENSE.txt'));
9575
+ let manifestOptions = normalizeManifestObjectConfig(manifest), { RspackManifestPlugin } = await import("./manifest-plugin.js").then(__webpack_require__.bind(__webpack_require__, "../../node_modules/.pnpm/rspack-manifest-plugin@5.2.2_@rspack+core@2.1.5/node_modules/rspack-manifest-plugin/dist/index.js")), { htmlPaths } = environment, filter = manifestOptions.filter ?? ((file)=>!file.name.endsWith('.LICENSE.txt'));
9422
9576
  manifestFilenames.set(environment.name, manifestOptions.filename);
9423
9577
  let pluginOptions = {
9424
9578
  fileName: manifestOptions.filename,
@@ -9605,7 +9759,7 @@ function applyEnvsToConfig(config, envs) {
9605
9759
  ...config.dev.watchFiles ? helpers_castArray(config.dev.watchFiles) : [],
9606
9760
  {
9607
9761
  paths: envs.filePaths,
9608
- type: 'reload-server'
9762
+ type: 'restart'
9609
9763
  }
9610
9764
  ], config.performance?.buildCache))) {
9611
9765
  let { buildCache } = config.performance;
@@ -9614,11 +9768,16 @@ function applyEnvsToConfig(config, envs) {
9614
9768
  } : (buildCache.buildDependencies ||= [], buildCache.buildDependencies.push(...envs.filePaths));
9615
9769
  }
9616
9770
  }
9771
+ function isLoadConfigResult(result) {
9772
+ return 'object' == typeof result && null !== result && 'content' in result && 'filePath' in result && 'dependencies' in result;
9773
+ }
9617
9774
  async function createRsbuild(options = {}) {
9618
- let envs = options.loadEnv ? loadEnv({
9775
+ let loadConfigResult, envs = options.loadEnv ? loadEnv({
9619
9776
  cwd: options.cwd,
9620
9777
  ...'boolean' == typeof options.loadEnv ? {} : options.loadEnv
9621
- }) : null, configOrFactory = options.config ?? options.rsbuildConfig, config = isFunction(configOrFactory) ? await configOrFactory() : configOrFactory || {}, logger = config.customLogger ?? logger_createLogger({
9778
+ }) : null, configOrFactory = options.config ?? options.rsbuildConfig, config = isFunction(configOrFactory) ? await configOrFactory() : configOrFactory;
9779
+ isLoadConfigResult(config) && (loadConfigResult = config, config = config.content);
9780
+ let logger = (config ||= {}).customLogger ?? logger_createLogger({
9622
9781
  ...src_logger.options,
9623
9782
  level: src_logger.level
9624
9783
  });
@@ -9628,7 +9787,7 @@ async function createRsbuild(options = {}) {
9628
9787
  callerName: 'rsbuild',
9629
9788
  ...options,
9630
9789
  rsbuildConfig: config
9631
- }, pluginManager = createPluginManager(logger), context = await createContext(resolvedOptions, config, logger), getPluginAPI = initPluginAPI({
9790
+ }, pluginManager = createPluginManager(logger), context = await createContext(resolvedOptions, config, logger, loadConfigResult), getPluginAPI = initPluginAPI({
9632
9791
  context,
9633
9792
  pluginManager
9634
9793
  });
@@ -9650,20 +9809,13 @@ async function createRsbuild(options = {}) {
9650
9809
  if (isEmptyDir(distPath)) throw Error(`${color.dim('[rsbuild:preview]')} The output directory ${color.yellow(distPath)} is empty, please build the project before previewing.`);
9651
9810
  }
9652
9811
  return startPreviewServer(context, config, options);
9653
- }, build = async (options)=>{
9654
- context.action = 'build', process.env.NODE_ENV || setNodeEnv('production');
9655
- let buildInstance = await build_build({
9812
+ }, build = async (options = {})=>(context.action = 'build', process.env.NODE_ENV || setNodeEnv('production'), build_build({
9656
9813
  context,
9657
9814
  pluginManager,
9658
9815
  rsbuildOptions: resolvedOptions
9659
- }, options);
9660
- return {
9661
- ...buildInstance,
9662
- close: async ()=>{
9663
- await context.hooks.onCloseBuild.callBatch(), await buildInstance.close();
9664
- }
9665
- };
9666
- }, startDevServer = async (options)=>{
9816
+ }, {
9817
+ ...options
9818
+ })), startDevServer = async (options = {})=>{
9667
9819
  context.action = 'dev', process.env.NODE_ENV || setNodeEnv('development');
9668
9820
  let config = await initRsbuildConfig({
9669
9821
  context,
@@ -9673,7 +9825,9 @@ async function createRsbuild(options = {}) {
9673
9825
  context,
9674
9826
  pluginManager,
9675
9827
  rsbuildOptions: resolvedOptions
9676
- }, createCompiler, config, options)).listen();
9828
+ }, createCompiler, config, {
9829
+ ...options
9830
+ })).listen();
9677
9831
  }, createDevServer = async (options)=>{
9678
9832
  context.action = 'dev', process.env.NODE_ENV || setNodeEnv('development');
9679
9833
  let config = await initRsbuildConfig({
@@ -9750,7 +9904,8 @@ async function createRsbuild(options = {}) {
9750
9904
  'onCloseBuild',
9751
9905
  'onCloseDevServer',
9752
9906
  'onDevCompileDone',
9753
- 'onExit'
9907
+ 'onExit',
9908
+ 'onRestart'
9754
9909
  ])
9755
9910
  };
9756
9911
  envs && (rsbuild.onCloseBuild(envs.cleanup), rsbuild.onCloseDevServer(envs.cleanup));
@@ -9897,7 +10052,8 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, configFileName
9897
10052
  if (!result.filePath) return src_logger.debug('no config file found.'), result;
9898
10053
  if (!isObject(result.content)) throw Error(`The config must be an object or a function that returns an object, get ${color.yellow(String(result.content))}`);
9899
10054
  return result.content._privateMeta = {
9900
- configFilePath: result.filePath
10055
+ configFilePath: result.filePath,
10056
+ configFileDependencies: result.dependencies
9901
10057
  }, src_logger.debug('configuration loaded from:', result.filePath), result;
9902
10058
  }
9903
10059
  let cliState = {
@@ -9905,13 +10061,13 @@ let cliState = {
9905
10061
  }, initCliAction = (command, options)=>{
9906
10062
  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;
9907
10063
  }, init_loadConfig = async (root)=>{
9908
- let { options, command } = cliState, { content: config, filePath, dependencies } = await loadConfig_loadConfig({
10064
+ let { options, command } = cliState, result = await loadConfig_loadConfig({
9909
10065
  cwd: root,
9910
10066
  path: options.config,
9911
10067
  envMode: options.envMode,
9912
10068
  loader: options.configLoader,
9913
10069
  command
9914
- });
10070
+ }), { content: config } = result;
9915
10071
  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), options.port && (config.server.port = options.port), void 0 !== options.strictPort && (config.server.strictPort = options.strictPort), void 0 !== options.distPath) {
9916
10072
  config.output ||= {};
9917
10073
  let { distPath } = config.output;
@@ -9927,18 +10083,14 @@ let cliState = {
9927
10083
  if ('boolean' != typeof sourceMap) throw Error('The "--source-map" option only accepts a boolean value.');
9928
10084
  config.output ||= {}, config.output.sourceMap = sourceMap;
9929
10085
  }
9930
- return void 0 === config.dev.cliShortcuts && (config.dev.cliShortcuts = !0), filePath && (config.dev.watchFiles = [
9931
- ...config.dev.watchFiles ? helpers_castArray(config.dev.watchFiles) : [],
9932
- {
9933
- paths: [
9934
- filePath,
9935
- ...dependencies
9936
- ],
9937
- type: 'reload-server'
9938
- }
9939
- ]), config;
10086
+ return void 0 === config.dev.cliShortcuts && (config.dev.cliShortcuts = !0), result;
10087
+ }, init_restart = async (context)=>{
10088
+ let rsbuild = await init_init({
10089
+ isRestart: !0
10090
+ });
10091
+ return !!rsbuild && ('build' === context.action ? await rsbuild.build(context.options) : await rsbuild.startDevServer(context.options), !0);
9940
10092
  };
9941
- async function init_init({ isRestart, isBuildWatch = !1 } = {}) {
10093
+ async function init_init({ isRestart } = {}) {
9942
10094
  let logger = src_logger, { options } = cliState;
9943
10095
  try {
9944
10096
  var envDir;
@@ -9949,90 +10101,21 @@ async function init_init({ isRestart, isBuildWatch = !1 } = {}) {
9949
10101
  loadEnv: !1 !== options.env && {
9950
10102
  cwd: (envDir = options.envDir) ? node_path.isAbsolute(envDir) ? envDir : node_path.join(root, envDir) : root,
9951
10103
  mode: options.envMode
9952
- }
10104
+ },
10105
+ restart: init_restart
9953
10106
  });
9954
- return logger = rsbuild.logger, rsbuild.onBeforeCreateCompiler(()=>{
9955
- if ('dev' !== rsbuild.context.action && !isBuildWatch) return;
9956
- let files = [], config = rsbuild.getNormalizedConfig();
9957
- if (config.dev.watchFiles) for (let watchConfig of config.dev.watchFiles){
9958
- if ('reload-server' !== watchConfig.type) continue;
9959
- let paths = helpers_castArray(watchConfig.paths);
9960
- watchConfig.options ? watchFilesForRestart({
9961
- files: paths,
9962
- rsbuild,
9963
- isBuildWatch,
9964
- watchOptions: watchConfig.options
9965
- }) : files.push(...paths);
9966
- }
9967
- watchFilesForRestart({
9968
- files,
9969
- rsbuild,
9970
- isBuildWatch
9971
- });
9972
- }), rsbuild;
10107
+ return logger = rsbuild.logger, rsbuild;
9973
10108
  } catch (err) {
9974
10109
  if (isRestart) logger.error(err);
9975
10110
  else throw err;
9976
10111
  }
9977
10112
  }
9978
- let cleaners = [], onBeforeRestartServer = (cleaner)=>{
9979
- cleaners.push(cleaner);
9980
- }, beforeRestart = async ({ filePath, clear = !0, id, logger })=>{
9981
- if (clear && isTTY() && !process.env.DEBUG && process.stdout.write('\x1B[H\x1B[2J'), filePath) {
9982
- let filename = node_path.basename(filePath);
9983
- logger.info(`restarting ${id} as ${color.yellow(filename)} changed\n`);
9984
- } else logger.info(`restarting ${id}...\n`);
9985
- for (let cleaner of cleaners)await cleaner();
9986
- cleaners = [];
9987
- }, restartDevServer = async ({ filePath, clear = !0, logger })=>{
9988
- await beforeRestart({
9989
- filePath,
9990
- clear,
9991
- id: 'server',
9992
- logger
9993
- });
9994
- let rsbuild = await init_init({
9995
- isRestart: !0
9996
- });
9997
- return !!rsbuild && (await rsbuild.startDevServer(), !0);
9998
- }, restartBuild = async ({ filePath, clear = !0, logger })=>{
9999
- await beforeRestart({
10000
- filePath,
10001
- clear,
10002
- id: 'build',
10003
- logger
10004
- });
10005
- let rsbuild = await init_init({
10006
- isRestart: !0,
10007
- isBuildWatch: !0
10008
- });
10009
- return !!rsbuild && (onBeforeRestartServer((await rsbuild.build({
10010
- watch: !0
10011
- })).close), !0);
10012
- };
10013
- async function watchFilesForRestart({ files, rsbuild, isBuildWatch, watchOptions }) {
10014
- if (!files.length) return;
10015
- let root = rsbuild.context.rootPath, watcher = await createChokidar(files, root, {
10016
- ignoreInitial: !0,
10017
- ignorePermissionErrors: !0,
10018
- ...watchOptions
10019
- }), restarting = !1, onChange = async (filePath)=>{
10020
- restarting || (restarting = !0, (isBuildWatch ? await restartBuild({
10021
- filePath,
10022
- logger: rsbuild.logger
10023
- }) : await restartDevServer({
10024
- filePath,
10025
- logger: rsbuild.logger
10026
- })) ? await watcher.close() : rsbuild.logger.error(isBuildWatch ? 'Restart build failed.' : 'Restart server failed.'), restarting = !1);
10027
- };
10028
- watcher.on('add', onChange), watcher.on('change', onChange), watcher.on('unlink', onChange);
10029
- }
10030
10113
  let applyServerOptions = (command)=>{
10031
10114
  command.option('-o, --open [url]', 'Open the page in browser on startup').option('--port <port>', 'Set the port number for the server').option('--strict-port', 'Exit if the specified port is already in use').option('--host [host]', 'Set the host that the server listens to');
10032
10115
  };
10033
10116
  function setupCommands(argv) {
10034
10117
  let cli = ((name = "")=>new CAC(name))('rsbuild');
10035
- cli.version("2.1.6"), cli.option('--base <base>', 'Set the base path of the server').option('-c, --config <config>', 'Set the configuration file (relative or absolute path)').option('--config-loader <loader>', 'Set the config file loader (auto | jiti | native)', {
10118
+ cli.version("2.1.8"), 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)', {
10036
10119
  default: 'auto'
10037
10120
  }).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', {
10038
10121
  type: [
@@ -10056,15 +10139,13 @@ function setupCommands(argv) {
10056
10139
  initCliAction('build', options);
10057
10140
  try {
10058
10141
  options.watch || (process.env.RSPACK_UNSAFE_FAST_DROP = 'true');
10059
- let rsbuild = await init_init({
10060
- isBuildWatch: options.watch
10061
- });
10142
+ let rsbuild = await init_init();
10062
10143
  if (!rsbuild) return;
10063
10144
  logger = rsbuild.logger;
10064
10145
  let buildResult = await rsbuild.build({
10065
10146
  watch: options.watch
10066
10147
  });
10067
- buildResult && (options.watch ? onBeforeRestartServer(buildResult.close) : await buildResult.close());
10148
+ options.watch || await buildResult.close();
10068
10149
  } catch (err) {
10069
10150
  err instanceof Error && err.message === RSPACK_BUILD_ERROR || logger.error('Failed to build.'), logger.error(err), process.exit(1);
10070
10151
  }
@@ -10091,12 +10172,15 @@ function setupCommands(argv) {
10091
10172
  logger.error('Failed to inspect config.'), logger.error(err), process.exit(1);
10092
10173
  }
10093
10174
  }), cli.help((sections)=>{
10094
- for (let section of (sections.shift(), sections))'Usage' === section.title && (section.body = section.body.replace('$ rsbuild', color.yellow("$ rsbuild [command] [options]"))), 'Commands' === section.title && (section.body = section.body.replace(` ${devDescription}`, `dev ${devDescription}`)), section.title?.startsWith('For more info') ? (section.title = color.dim(' For details on a sub-command, run'), section.body = color.dim(' $ rsbuild <command> -h')) : section.title && (section.title = color.cyan(section.title));
10175
+ sections.shift();
10176
+ let commandName = cli.matchedCommandName;
10177
+ for (let section of sections = sections.filter(({ title })=>!commandName || 'Commands' !== title && !title?.startsWith('For more info')))'Usage' === section.title && (section.body = ` ${color.yellow(`$ rsbuild ${commandName || '[command]'} [options]`)}`), 'Commands' === section.title && (section.body = section.body.replace(` ${devDescription}`, `dev ${devDescription}`)), section.title?.startsWith('For more info') ? (section.title = color.dim(' For details on a sub-command, run'), section.body = color.dim(' $ rsbuild <command> -h')) : section.title && (section.title = color.cyan(section.title));
10178
+ return sections;
10095
10179
  }), cli.parse(argv);
10096
10180
  }
10097
10181
  function showGreeting() {
10098
10182
  let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
10099
- src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.1.6\n`);
10183
+ src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.1.8\n`);
10100
10184
  }
10101
10185
  function setupLogLevel(argv) {
10102
10186
  if (argv.length <= 3) return;
@@ -10118,5 +10202,5 @@ function runCLI({ argv = process.argv } = {}) {
10118
10202
  src_logger.error('Failed to start Rsbuild CLI.'), src_logger.error(err), process.exit(1);
10119
10203
  }
10120
10204
  }
10121
- let src_version = "2.1.6";
10205
+ let src_version = "2.1.8";
10122
10206
  export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, core_rspack as rspack, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, loadConfig_loadConfig as loadConfig, loadEnv, logger_createLogger as createLogger, mergeRsbuildConfig, mrmime_lookup, runCLI, src_logger as logger, src_version as version };