@rsbuild/core 1.7.2 → 2.0.0-alpha.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.
- package/compiled/css-loader/index.js +2 -2
- package/compiled/html-rspack-plugin/index.js +14 -14
- package/compiled/http-proxy-middleware/index.d.ts +2 -2
- package/compiled/postcss/index.js +1 -1
- package/compiled/postcss-loader/index.js +6 -6
- package/compiled/ws/index.js +59 -54
- package/compiled/ws/package.json +1 -1
- package/dist/131.js +1000 -1065
- package/dist/31.js +336 -0
- package/dist/710.js +445 -0
- package/dist/743.js +7 -0
- package/dist/{136.mjs → 88.js} +11 -13
- package/dist/client/hmr.js +0 -1
- package/dist/client/overlay.js +32 -21
- package/dist/connect.js +581 -0
- package/dist/connect.js.LICENSE.txt +54 -0
- package/dist/cors.js +188 -0
- package/dist/cors.js.LICENSE.txt +11 -0
- package/dist/launch-editor-middleware.js +439 -0
- package/dist/manifest-plugin.js +177 -0
- package/dist/memfs.js +3644 -0
- package/dist/{0~open.js → open.js} +21 -13
- package/dist/{0~range-parser.js → range-parser.js} +1 -1
- package/dist/remapping.js +196 -0
- package/dist/sirv.js +122 -0
- package/dist/tinyglobby.js +1463 -0
- package/dist/transformLoader.mjs +1 -1
- package/dist/transformRawLoader.mjs +1 -1
- package/dist-types/{provider/build.d.ts → build.d.ts} +2 -2
- package/dist-types/cli/commands.d.ts +1 -1
- package/dist-types/configChain.d.ts +0 -2
- package/dist-types/constants.d.ts +2 -3
- package/dist-types/{provider/createCompiler.d.ts → createCompiler.d.ts} +1 -1
- package/dist-types/defaultConfig.d.ts +1 -1
- package/dist-types/helpers/index.d.ts +1 -1
- package/dist-types/helpers/url.d.ts +0 -1
- package/dist-types/helpers/vendors.d.ts +0 -13
- package/dist-types/hooks.d.ts +3 -5
- package/dist-types/index.d.ts +1 -1
- package/dist-types/{provider/initConfigs.d.ts → initConfigs.d.ts} +1 -1
- package/dist-types/inspectConfig.d.ts +5 -33
- package/dist-types/pluginHelper.d.ts +1 -1
- package/dist-types/plugins/css.d.ts +1 -1
- package/dist-types/plugins/inlineChunk.d.ts +1 -1
- package/dist-types/plugins/minimize.d.ts +2 -2
- package/dist-types/{provider/rspackConfig.d.ts → rspackConfig.d.ts} +1 -1
- package/dist-types/server/assets-middleware/setupOutputFileSystem.d.ts +1 -1
- package/dist-types/server/browserLogs.d.ts +1 -1
- package/dist-types/server/devMiddlewares.d.ts +1 -1
- package/dist-types/server/devServer.d.ts +1 -1
- package/dist-types/server/gzipMiddleware.d.ts +1 -1
- package/dist-types/server/helper.d.ts +3 -2
- package/dist-types/server/proxy.d.ts +1 -1
- package/dist-types/server/socketServer.d.ts +1 -1
- package/dist-types/types/config.d.ts +7 -51
- package/dist-types/types/context.d.ts +3 -2
- package/dist-types/types/hooks.d.ts +9 -9
- package/dist-types/types/plugin.d.ts +3 -40
- package/dist-types/types/rsbuild.d.ts +6 -31
- package/dist-types/types/thirdParty.d.ts +1 -4
- package/package.json +14 -19
- package/compiled/@jridgewell/remapping/index.d.ts +0 -1
- package/compiled/@jridgewell/remapping/index.js +0 -1222
- package/compiled/@jridgewell/remapping/license +0 -19
- package/compiled/@jridgewell/remapping/package.json +0 -1
- package/compiled/@jridgewell/trace-mapping/index.d.ts +0 -194
- package/compiled/@jridgewell/trace-mapping/index.js +0 -1408
- package/compiled/@jridgewell/trace-mapping/license +0 -19
- package/compiled/@jridgewell/trace-mapping/package.json +0 -1
- package/compiled/connect/index.d.ts +0 -90
- package/compiled/connect/index.js +0 -1240
- package/compiled/connect/license +0 -25
- package/compiled/connect/package.json +0 -1
- package/compiled/cors/index.d.ts +0 -56
- package/compiled/cors/index.js +0 -371
- package/compiled/cors/license +0 -22
- package/compiled/cors/package.json +0 -1
- package/compiled/launch-editor-middleware/index.d.ts +0 -1
- package/compiled/launch-editor-middleware/index.js +0 -719
- package/compiled/launch-editor-middleware/license +0 -21
- package/compiled/launch-editor-middleware/package.json +0 -1
- package/compiled/memfs/index.d.ts +0 -1462
- package/compiled/memfs/index.js +0 -1
- package/compiled/memfs/license +0 -201
- package/compiled/memfs/package.json +0 -1
- package/compiled/mrmime/index.d.ts +0 -4
- package/compiled/mrmime/index.js +0 -456
- package/compiled/mrmime/package.json +0 -1
- package/compiled/picocolors/index.d.ts +0 -55
- package/compiled/picocolors/index.js +0 -108
- package/compiled/picocolors/license +0 -15
- package/compiled/picocolors/package.json +0 -1
- package/compiled/rspack-manifest-plugin/index.d.ts +0 -48
- package/compiled/rspack-manifest-plugin/index.js +0 -409
- package/compiled/rspack-manifest-plugin/license +0 -21
- package/compiled/rspack-manifest-plugin/package.json +0 -1
- package/compiled/sirv/index.d.ts +0 -1
- package/compiled/sirv/index.js +0 -274
- package/compiled/sirv/package.json +0 -1
- package/compiled/tinyglobby/index.d.ts +0 -46
- package/compiled/tinyglobby/index.js +0 -2664
- package/compiled/tinyglobby/license +0 -21
- package/compiled/tinyglobby/package.json +0 -1
- package/compiled/webpack-bundle-analyzer/index.d.ts +0 -160
- package/compiled/webpack-bundle-analyzer/index.js +0 -23
- package/compiled/webpack-bundle-analyzer/license +0 -20
- package/compiled/webpack-bundle-analyzer/package.json +0 -1
- package/compiled/webpack-bundle-analyzer/public/viewer.js +0 -16
- package/compiled/webpack-bundle-analyzer/public/viewer.js.LICENSE.txt +0 -10
- package/dist/2~open.cjs +0 -436
- package/dist/2~range-parser.cjs +0 -52
- package/dist/2~range-parser.cjs.LICENSE.txt +0 -6
- package/dist/index.cjs +0 -9456
- package/dist/index.cjs.LICENSE.txt +0 -26
- package/dist-types/plugins/bundleAnalyzer.d.ts +0 -2
- package/dist-types/plugins/performance.d.ts +0 -5
- package/dist-types/provider/helpers.d.ts +0 -12
- package/dist-types/provider/provider.d.ts +0 -2
- /package/dist/{0~range-parser.js.LICENSE.txt → range-parser.js.LICENSE.txt} +0 -0
package/dist/131.js
CHANGED
|
@@ -4,7 +4,9 @@ import { fileURLToPath as __rspack_fileURLToPath } from "node:url";
|
|
|
4
4
|
import { createRequire as __rspack_createRequire } from "node:module";
|
|
5
5
|
let __rspack_createRequire_require = __rspack_createRequire(import.meta.url);
|
|
6
6
|
import * as __rspack_external_async_hooks from "async_hooks";
|
|
7
|
+
import * as __rspack_external_events from "events";
|
|
7
8
|
import * as __rspack_external_fs from "fs";
|
|
9
|
+
import * as __rspack_external_node_fs_5ea92f0c from "node:fs";
|
|
8
10
|
import * as __rspack_external_node_module_ab9f2194 from "node:module";
|
|
9
11
|
import * as __rspack_external_node_path_c5b9b54f from "node:path";
|
|
10
12
|
import * as __rspack_external_node_url_e96de089 from "node:url";
|
|
@@ -15,9 +17,7 @@ import { __webpack_require__ } from "./rslib-runtime.js";
|
|
|
15
17
|
import node_process from "node:process";
|
|
16
18
|
import node_os, { constants as external_node_os_constants } from "node:os";
|
|
17
19
|
import node_tty from "node:tty";
|
|
18
|
-
import { EventEmitter } from "events";
|
|
19
20
|
import { promisify as external_node_util_promisify, stripVTControlCharacters } from "node:util";
|
|
20
|
-
import node_fs, { existsSync } from "node:fs";
|
|
21
21
|
import { isPromise, isRegExp } from "node:util/types";
|
|
22
22
|
import node_zlib from "node:zlib";
|
|
23
23
|
__webpack_require__.add({
|
|
@@ -770,8 +770,66 @@ __webpack_require__.add({
|
|
|
770
770
|
return (asyncHooks.AsyncResource && (res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn')), res && res.runInAsyncScope) ? res.runInAsyncScope.bind(res, fn, null) : fn;
|
|
771
771
|
}
|
|
772
772
|
},
|
|
773
|
-
"../../node_modules/.pnpm/
|
|
774
|
-
let
|
|
773
|
+
"../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js" (module) {
|
|
774
|
+
let p = process || {}, argv = p.argv || [], env = p.env || {}, isColorSupported = !(env.NO_COLOR || argv.includes("--no-color")) && (!!env.FORCE_COLOR || argv.includes("--color") || "win32" === p.platform || (p.stdout || {}).isTTY && "dumb" !== env.TERM || !!env.CI), formatter = (open, close, replace = open)=>(input)=>{
|
|
775
|
+
let string = "" + input, index = string.indexOf(close, open.length);
|
|
776
|
+
return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
|
|
777
|
+
}, replaceClose = (string, close, replace, index)=>{
|
|
778
|
+
let result = "", cursor = 0;
|
|
779
|
+
do result += string.substring(cursor, index) + replace, cursor = index + close.length, index = string.indexOf(close, cursor);
|
|
780
|
+
while (~index);
|
|
781
|
+
return result + string.substring(cursor);
|
|
782
|
+
}, createColors = (enabled = isColorSupported)=>{
|
|
783
|
+
let f = enabled ? formatter : ()=>String;
|
|
784
|
+
return {
|
|
785
|
+
isColorSupported: enabled,
|
|
786
|
+
reset: f("\x1b[0m", "\x1b[0m"),
|
|
787
|
+
bold: f("\x1b[1m", "\x1b[22m", "\x1b[22m\x1b[1m"),
|
|
788
|
+
dim: f("\x1b[2m", "\x1b[22m", "\x1b[22m\x1b[2m"),
|
|
789
|
+
italic: f("\x1b[3m", "\x1b[23m"),
|
|
790
|
+
underline: f("\x1b[4m", "\x1b[24m"),
|
|
791
|
+
inverse: f("\x1b[7m", "\x1b[27m"),
|
|
792
|
+
hidden: f("\x1b[8m", "\x1b[28m"),
|
|
793
|
+
strikethrough: f("\x1b[9m", "\x1b[29m"),
|
|
794
|
+
black: f("\x1b[30m", "\x1b[39m"),
|
|
795
|
+
red: f("\x1b[31m", "\x1b[39m"),
|
|
796
|
+
green: f("\x1b[32m", "\x1b[39m"),
|
|
797
|
+
yellow: f("\x1b[33m", "\x1b[39m"),
|
|
798
|
+
blue: f("\x1b[34m", "\x1b[39m"),
|
|
799
|
+
magenta: f("\x1b[35m", "\x1b[39m"),
|
|
800
|
+
cyan: f("\x1b[36m", "\x1b[39m"),
|
|
801
|
+
white: f("\x1b[37m", "\x1b[39m"),
|
|
802
|
+
gray: f("\x1b[90m", "\x1b[39m"),
|
|
803
|
+
bgBlack: f("\x1b[40m", "\x1b[49m"),
|
|
804
|
+
bgRed: f("\x1b[41m", "\x1b[49m"),
|
|
805
|
+
bgGreen: f("\x1b[42m", "\x1b[49m"),
|
|
806
|
+
bgYellow: f("\x1b[43m", "\x1b[49m"),
|
|
807
|
+
bgBlue: f("\x1b[44m", "\x1b[49m"),
|
|
808
|
+
bgMagenta: f("\x1b[45m", "\x1b[49m"),
|
|
809
|
+
bgCyan: f("\x1b[46m", "\x1b[49m"),
|
|
810
|
+
bgWhite: f("\x1b[47m", "\x1b[49m"),
|
|
811
|
+
blackBright: f("\x1b[90m", "\x1b[39m"),
|
|
812
|
+
redBright: f("\x1b[91m", "\x1b[39m"),
|
|
813
|
+
greenBright: f("\x1b[92m", "\x1b[39m"),
|
|
814
|
+
yellowBright: f("\x1b[93m", "\x1b[39m"),
|
|
815
|
+
blueBright: f("\x1b[94m", "\x1b[39m"),
|
|
816
|
+
magentaBright: f("\x1b[95m", "\x1b[39m"),
|
|
817
|
+
cyanBright: f("\x1b[96m", "\x1b[39m"),
|
|
818
|
+
whiteBright: f("\x1b[97m", "\x1b[39m"),
|
|
819
|
+
bgBlackBright: f("\x1b[100m", "\x1b[49m"),
|
|
820
|
+
bgRedBright: f("\x1b[101m", "\x1b[49m"),
|
|
821
|
+
bgGreenBright: f("\x1b[102m", "\x1b[49m"),
|
|
822
|
+
bgYellowBright: f("\x1b[103m", "\x1b[49m"),
|
|
823
|
+
bgBlueBright: f("\x1b[104m", "\x1b[49m"),
|
|
824
|
+
bgMagentaBright: f("\x1b[105m", "\x1b[49m"),
|
|
825
|
+
bgCyanBright: f("\x1b[106m", "\x1b[49m"),
|
|
826
|
+
bgWhiteBright: f("\x1b[107m", "\x1b[49m")
|
|
827
|
+
};
|
|
828
|
+
};
|
|
829
|
+
module.exports = createColors(), module.exports.createColors = createColors;
|
|
830
|
+
},
|
|
831
|
+
"../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.2/node_modules/postcss-load-config/src/index.js" (module, __unused_rspack_exports, __webpack_require__) {
|
|
832
|
+
let yaml, { resolve } = __webpack_require__("node:path"), 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.6.1_postcss@8.5.6_yaml@2.8.2/node_modules/postcss-load-config/src/options.js"), loadPlugins = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.2/node_modules/postcss-load-config/src/plugins.js"), req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.2/node_modules/postcss-load-config/src/req.js");
|
|
775
833
|
async function processResult(ctx, result) {
|
|
776
834
|
let obj, file = result.filepath || '', projectConfig = ((obj = result.config) && obj.__esModule ? obj : {
|
|
777
835
|
default: obj
|
|
@@ -844,8 +902,8 @@ __webpack_require__.add({
|
|
|
844
902
|
});
|
|
845
903
|
};
|
|
846
904
|
},
|
|
847
|
-
"../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.
|
|
848
|
-
let req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.
|
|
905
|
+
"../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.2/node_modules/postcss-load-config/src/options.js" (module, __unused_rspack_exports, __webpack_require__) {
|
|
906
|
+
let req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.2/node_modules/postcss-load-config/src/req.js");
|
|
849
907
|
module.exports = async function options(config, file) {
|
|
850
908
|
if (config.parser && 'string' == typeof config.parser) try {
|
|
851
909
|
config.parser = await req(config.parser, file);
|
|
@@ -865,8 +923,8 @@ __webpack_require__.add({
|
|
|
865
923
|
return config;
|
|
866
924
|
};
|
|
867
925
|
},
|
|
868
|
-
"../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.
|
|
869
|
-
let req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.
|
|
926
|
+
"../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.2/node_modules/postcss-load-config/src/plugins.js" (module, __unused_rspack_exports, __webpack_require__) {
|
|
927
|
+
let req = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.2/node_modules/postcss-load-config/src/req.js");
|
|
870
928
|
async function load(plugin, options, file) {
|
|
871
929
|
try {
|
|
872
930
|
if (null == options || 0 === Object.keys(options).length) return await req(plugin, file);
|
|
@@ -882,7 +940,7 @@ __webpack_require__.add({
|
|
|
882
940
|
}), list;
|
|
883
941
|
};
|
|
884
942
|
},
|
|
885
|
-
"../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.
|
|
943
|
+
"../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.2/node_modules/postcss-load-config/src/req.js" (module, __unused_rspack_exports, __webpack_require__) {
|
|
886
944
|
let tsx, jiti;
|
|
887
945
|
var __filename = __rspack_fileURLToPath(import.meta.url);
|
|
888
946
|
let { createRequire } = __webpack_require__("node:module"), { pathToFileURL } = __webpack_require__("node:url"), TS_EXT_RE = /\.[mc]?ts$/, importError = [];
|
|
@@ -916,9 +974,15 @@ __webpack_require__.add({
|
|
|
916
974
|
async_hooks (module) {
|
|
917
975
|
module.exports = __rspack_external_async_hooks;
|
|
918
976
|
},
|
|
977
|
+
events (module) {
|
|
978
|
+
module.exports = __rspack_external_events;
|
|
979
|
+
},
|
|
919
980
|
fs (module) {
|
|
920
981
|
module.exports = __rspack_external_fs;
|
|
921
982
|
},
|
|
983
|
+
"node:fs" (module) {
|
|
984
|
+
module.exports = __rspack_external_node_fs_5ea92f0c;
|
|
985
|
+
},
|
|
922
986
|
"node:module" (module) {
|
|
923
987
|
module.exports = __rspack_external_node_module_ab9f2194;
|
|
924
988
|
},
|
|
@@ -938,23 +1002,6 @@ __webpack_require__.add({
|
|
|
938
1002
|
module.exports = __rspack_external_url;
|
|
939
1003
|
}
|
|
940
1004
|
});
|
|
941
|
-
var superClass, superClass1, provider_helpers_namespaceObject = {};
|
|
942
|
-
__webpack_require__.r(provider_helpers_namespaceObject), __webpack_require__.d(provider_helpers_namespaceObject, {
|
|
943
|
-
createDevServer: ()=>devServer_createDevServer,
|
|
944
|
-
formatStats: ()=>formatStats,
|
|
945
|
-
getChainUtils: ()=>getChainUtils,
|
|
946
|
-
getConfigUtils: ()=>getConfigUtils,
|
|
947
|
-
getHTMLPlugin: ()=>pluginHelper_getHTMLPlugin,
|
|
948
|
-
getRsbuildStats: ()=>getRsbuildStats,
|
|
949
|
-
initRsbuildConfig: ()=>initRsbuildConfig,
|
|
950
|
-
inspectConfig: ()=>inspectConfig_inspectConfig,
|
|
951
|
-
modifyBundlerChain: ()=>modifyBundlerChain,
|
|
952
|
-
prettyTime: ()=>prettyTime,
|
|
953
|
-
registerBuildHook: ()=>registerBuildHook,
|
|
954
|
-
registerDevHook: ()=>registerDevHook,
|
|
955
|
-
setCssExtractPlugin: ()=>setCssExtractPlugin,
|
|
956
|
-
setHTMLPlugin: ()=>setHTMLPlugin
|
|
957
|
-
});
|
|
958
1005
|
let external_node_module_ = __webpack_require__("node:module"), rspack_rspack = (0, external_node_module_.createRequire)(import.meta.url)('@rspack/core');
|
|
959
1006
|
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : node_process.argv) {
|
|
960
1007
|
let prefix = flag.startsWith('-') ? '' : 1 === flag.length ? '-' : '--', position = argv.indexOf(prefix + flag), terminatorPosition = argv.indexOf('--');
|
|
@@ -1127,53 +1174,9 @@ let supportsColor = {
|
|
|
1127
1174
|
}), logger.override = (customLogger)=>{
|
|
1128
1175
|
Object.assign(logger, customLogger);
|
|
1129
1176
|
}, logger;
|
|
1130
|
-
})(),
|
|
1131
|
-
|
|
1132
|
-
|
|
1133
|
-
'firefox >= 78',
|
|
1134
|
-
'safari >= 14'
|
|
1135
|
-
], DEFAULT_BROWSERSLIST = {
|
|
1136
|
-
web: DEFAULT_WEB_BROWSERSLIST,
|
|
1137
|
-
'web-worker': DEFAULT_WEB_BROWSERSLIST,
|
|
1138
|
-
node: [
|
|
1139
|
-
'node >= 16'
|
|
1140
|
-
]
|
|
1141
|
-
}, JS_REGEX = /\.(?:js|mjs|cjs|jsx)$/, SCRIPT_REGEX = /\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts)$/, CSS_REGEX = /\.css$/, RAW_QUERY_REGEX = /[?&]raw(?:&|=|$)/, INLINE_QUERY_REGEX = /[?&]inline(?:&|=|$)/, NODE_MODULES_REGEX = /[\\/]node_modules[\\/]/, PLUGIN_SWC_NAME = 'rsbuild:swc', PLUGIN_CSS_NAME = 'rsbuild:css', FONT_EXTENSIONS = [
|
|
1142
|
-
'woff',
|
|
1143
|
-
'woff2',
|
|
1144
|
-
'eot',
|
|
1145
|
-
'ttf',
|
|
1146
|
-
'otf',
|
|
1147
|
-
'ttc'
|
|
1148
|
-
], IMAGE_EXTENSIONS = [
|
|
1149
|
-
'png',
|
|
1150
|
-
'jpg',
|
|
1151
|
-
'jpeg',
|
|
1152
|
-
'pjpeg',
|
|
1153
|
-
'pjp',
|
|
1154
|
-
'gif',
|
|
1155
|
-
'bmp',
|
|
1156
|
-
'webp',
|
|
1157
|
-
'ico',
|
|
1158
|
-
'apng',
|
|
1159
|
-
'avif',
|
|
1160
|
-
'tif',
|
|
1161
|
-
'tiff',
|
|
1162
|
-
'jfif',
|
|
1163
|
-
'cur'
|
|
1164
|
-
], VIDEO_EXTENSIONS = [
|
|
1165
|
-
'mp4',
|
|
1166
|
-
'webm',
|
|
1167
|
-
'ogg',
|
|
1168
|
-
'mov'
|
|
1169
|
-
], AUDIO_EXTENSIONS = [
|
|
1170
|
-
'mp3',
|
|
1171
|
-
'wav',
|
|
1172
|
-
'flac',
|
|
1173
|
-
'aac',
|
|
1174
|
-
'm4a',
|
|
1175
|
-
'opus'
|
|
1176
|
-
], LAZY_COMPILATION_IDENTIFIER = 'lazy-compilation-proxy', vendors_require = (0, external_node_module_.createRequire)(import.meta.url), requireCompiledPackage = (name)=>vendors_require(`${COMPILED_PATH}/${name}/index.js`), color = requireCompiledPackage('picocolors'), isDebug = ()=>{
|
|
1177
|
+
})(), picocolors = __webpack_require__("../../node_modules/.pnpm/picocolors@1.1.1/node_modules/picocolors/picocolors.js");
|
|
1178
|
+
var superClass, superClass1, picocolors_default = __webpack_require__.n(picocolors);
|
|
1179
|
+
let isDebug = ()=>{
|
|
1177
1180
|
if (!process.env.DEBUG) return !1;
|
|
1178
1181
|
let values = process.env.DEBUG.toLocaleLowerCase().split(',');
|
|
1179
1182
|
return [
|
|
@@ -1186,6 +1189,14 @@ function getTime() {
|
|
|
1186
1189
|
let now = new Date(), hours = String(now.getHours()).padStart(2, '0'), minutes = String(now.getMinutes()).padStart(2, '0'), seconds = String(now.getSeconds()).padStart(2, '0');
|
|
1187
1190
|
return `${hours}:${minutes}:${seconds}`;
|
|
1188
1191
|
}
|
|
1192
|
+
isDebug() && (src_logger.level = 'verbose'), src_logger.override({
|
|
1193
|
+
debug: (message, ...args)=>{
|
|
1194
|
+
if ('verbose' !== src_logger.level) return;
|
|
1195
|
+
let time = picocolors_default().gray(getTime());
|
|
1196
|
+
console.log(` ${picocolors_default().magenta('rsbuild')} ${time} ${message}`, ...args);
|
|
1197
|
+
}
|
|
1198
|
+
});
|
|
1199
|
+
let external_events_ = __webpack_require__("events");
|
|
1189
1200
|
function toArr(any) {
|
|
1190
1201
|
return null == any ? [] : Array.isArray(any) ? any : [
|
|
1191
1202
|
any
|
|
@@ -1235,13 +1246,6 @@ function mri2(args, opts) {
|
|
|
1235
1246
|
if (alibi) for(k in out)for(arr = opts.alias[k] || []; arr.length > 0;)out[arr.shift()] = out[k];
|
|
1236
1247
|
return out;
|
|
1237
1248
|
}
|
|
1238
|
-
isDebug() && (src_logger.level = 'verbose'), src_logger.override({
|
|
1239
|
-
debug: (message, ...args)=>{
|
|
1240
|
-
if ('verbose' !== src_logger.level) return;
|
|
1241
|
-
let time = color.gray(getTime());
|
|
1242
|
-
console.log(` ${color.magenta('rsbuild')} ${time} ${message}`, ...args);
|
|
1243
|
-
}
|
|
1244
|
-
});
|
|
1245
1249
|
let removeBrackets = (v)=>v.replace(/[<[].+/, "").trim(), findLongest = (arr)=>arr.sort((a, b)=>a.length > b.length ? -1 : 1)[0], padRight = (str, length)=>str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`, setDotProp = (obj, keys, val)=>{
|
|
1246
1250
|
let x, i = 0, length = keys.length, t = obj;
|
|
1247
1251
|
for(; i < length; ++i)x = t[keys[i]], t = t[keys[i]] = i === length - 1 ? val : null != x ? x : ~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : [];
|
|
@@ -1388,7 +1392,7 @@ class GlobalCommand extends Command {
|
|
|
1388
1392
|
}
|
|
1389
1393
|
}
|
|
1390
1394
|
var __assign = Object.assign;
|
|
1391
|
-
class CAC extends EventEmitter {
|
|
1395
|
+
class CAC extends external_events_.EventEmitter {
|
|
1392
1396
|
constructor(name = ""){
|
|
1393
1397
|
super(), this.name = name, this.commands = [], this.rawArgs = [], this.args = [], this.options = {}, this.globalCommand = new GlobalCommand(this), this.globalCommand.usage("<command> [options]");
|
|
1394
1398
|
}
|
|
@@ -1496,7 +1500,53 @@ class CAC extends EventEmitter {
|
|
|
1496
1500
|
}), actionArgs.push(options), command.commandAction.apply(this, actionArgs);
|
|
1497
1501
|
}
|
|
1498
1502
|
}
|
|
1499
|
-
let
|
|
1503
|
+
let external_node_path_ = __webpack_require__("node:path"), isDeno = "u" > typeof Deno, isWindows = 'win32' === process.platform, ROOT_DIST_DIR = 'dist', dirname = import.meta.dirname, STATIC_PATH = (0, external_node_path_.join)(dirname, '../static'), CLIENT_PATH = (0, external_node_path_.join)(dirname, 'client'), COMPILED_PATH = (0, external_node_path_.join)(dirname, '../compiled'), RSBUILD_OUTPUTS_PATH = '.rsbuild', LOCALHOST = 'localhost', ALL_INTERFACES_IPV4 = '0.0.0.0', DEFAULT_ASSET_PREFIX = '/', DEFAULT_STACK_TRACE = 'summary', DEFAULT_WEB_BROWSERSLIST = [
|
|
1504
|
+
'chrome >= 107',
|
|
1505
|
+
'edge >= 107',
|
|
1506
|
+
'firefox >= 104',
|
|
1507
|
+
'safari >= 16'
|
|
1508
|
+
], DEFAULT_BROWSERSLIST = {
|
|
1509
|
+
web: DEFAULT_WEB_BROWSERSLIST,
|
|
1510
|
+
'web-worker': DEFAULT_WEB_BROWSERSLIST,
|
|
1511
|
+
node: [
|
|
1512
|
+
'node >= 20'
|
|
1513
|
+
]
|
|
1514
|
+
}, JS_REGEX = /\.(?:js|mjs|cjs|jsx)$/, SCRIPT_REGEX = /\.(?:js|jsx|mjs|cjs|ts|tsx|mts|cts)$/, CSS_REGEX = /\.css$/, RAW_QUERY_REGEX = /[?&]raw(?:&|=|$)/, INLINE_QUERY_REGEX = /[?&]inline(?:&|=|$)/, NODE_MODULES_REGEX = /[\\/]node_modules[\\/]/, PLUGIN_SWC_NAME = 'rsbuild:swc', PLUGIN_CSS_NAME = 'rsbuild:css', FONT_EXTENSIONS = [
|
|
1515
|
+
'woff',
|
|
1516
|
+
'woff2',
|
|
1517
|
+
'eot',
|
|
1518
|
+
'ttf',
|
|
1519
|
+
'otf',
|
|
1520
|
+
'ttc'
|
|
1521
|
+
], IMAGE_EXTENSIONS = [
|
|
1522
|
+
'png',
|
|
1523
|
+
'jpg',
|
|
1524
|
+
'jpeg',
|
|
1525
|
+
'pjpeg',
|
|
1526
|
+
'pjp',
|
|
1527
|
+
'gif',
|
|
1528
|
+
'bmp',
|
|
1529
|
+
'webp',
|
|
1530
|
+
'ico',
|
|
1531
|
+
'apng',
|
|
1532
|
+
'avif',
|
|
1533
|
+
'tif',
|
|
1534
|
+
'tiff',
|
|
1535
|
+
'jfif',
|
|
1536
|
+
'cur'
|
|
1537
|
+
], VIDEO_EXTENSIONS = [
|
|
1538
|
+
'mp4',
|
|
1539
|
+
'webm',
|
|
1540
|
+
'ogg',
|
|
1541
|
+
'mov'
|
|
1542
|
+
], AUDIO_EXTENSIONS = [
|
|
1543
|
+
'mp3',
|
|
1544
|
+
'wav',
|
|
1545
|
+
'flac',
|
|
1546
|
+
'aac',
|
|
1547
|
+
'm4a',
|
|
1548
|
+
'opus'
|
|
1549
|
+
], LAZY_COMPILATION_IDENTIFIER = 'lazy-compilation-proxy', cjs = __webpack_require__("../../node_modules/.pnpm/deepmerge@4.3.1/node_modules/deepmerge/dist/cjs.js");
|
|
1500
1550
|
var cjs_default = __webpack_require__.n(cjs);
|
|
1501
1551
|
let dist_0 = __webpack_require__("../../node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/index.js");
|
|
1502
1552
|
function createMap(superClass) {
|
|
@@ -2264,7 +2314,7 @@ function getFilename(config, type, isProd, isServer) {
|
|
|
2264
2314
|
if (filename.html) return filename.html;
|
|
2265
2315
|
return 'flat' === config.html.outputStructure ? '[name].html' : '[name]/index.html';
|
|
2266
2316
|
default:
|
|
2267
|
-
throw Error(`${
|
|
2317
|
+
throw Error(`${picocolors_default().dim('[rsbuild:config]')} unknown key ${picocolors_default().yellow(type)} in ${picocolors_default().yellow('output.filename')}`);
|
|
2268
2318
|
}
|
|
2269
2319
|
}
|
|
2270
2320
|
function partition(array, predicate) {
|
|
@@ -2285,21 +2335,7 @@ function pick(obj, keys) {
|
|
|
2285
2335
|
for (let key of keys)void 0 !== obj[key] && (result[key] = obj[key]);
|
|
2286
2336
|
return result;
|
|
2287
2337
|
}
|
|
2288
|
-
let
|
|
2289
|
-
let time, time1;
|
|
2290
|
-
if (seconds < 10) {
|
|
2291
|
-
let time, digits = seconds >= 0.01 ? 2 : 3;
|
|
2292
|
-
return `${time = seconds.toFixed(digits), color.bold(time)} s`;
|
|
2293
|
-
}
|
|
2294
|
-
if (seconds < 60) {
|
|
2295
|
-
let time;
|
|
2296
|
-
return `${time = seconds.toFixed(1), color.bold(time)} s`;
|
|
2297
|
-
}
|
|
2298
|
-
let minutes = Math.floor(seconds / 60), minutesLabel = `${(time = minutes.toFixed(0), color.bold(time))} m`, remainingSeconds = seconds % 60;
|
|
2299
|
-
if (0 === remainingSeconds) return minutesLabel;
|
|
2300
|
-
let secondsLabel = `${(time1 = remainingSeconds.toFixed(+(remainingSeconds % 1 != 0)), color.bold(time1))} s`;
|
|
2301
|
-
return `${minutesLabel} ${secondsLabel}`;
|
|
2302
|
-
}, isTTY = (type = 'stdout')=>('stdin' === type ? process.stdin.isTTY : process.stdout.isTTY) && !process.env.CI;
|
|
2338
|
+
let isTTY = (type = 'stdout')=>('stdin' === type ? process.stdin.isTTY : process.stdout.isTTY) && !process.env.CI;
|
|
2303
2339
|
async function helpers_hash(data) {
|
|
2304
2340
|
let crypto = await import("node:crypto");
|
|
2305
2341
|
return crypto.hash ? crypto.hash('sha256', data, 'hex').slice(0, 16) : crypto.createHash('sha256').update(data).digest('hex').slice(0, 16);
|
|
@@ -2309,254 +2345,8 @@ let compiler_isMultiCompiler = (compiler)=>'compilers' in compiler && Array.isAr
|
|
|
2309
2345
|
return 'string' == typeof publicPath ? 'auto' === publicPath ? '' : publicPath.endsWith('/') ? publicPath : `${publicPath}/` : DEFAULT_ASSET_PREFIX;
|
|
2310
2346
|
}, applyToCompiler = (compiler, apply)=>{
|
|
2311
2347
|
compiler_isMultiCompiler(compiler) ? compiler.compilers.forEach(apply) : apply(compiler, 0);
|
|
2312
|
-
}, addCompilationError = (compilation, message)=>{
|
|
2313
|
-
compilation.errors.push(new
|
|
2314
|
-
};
|
|
2315
|
-
function createEnvironmentAsyncHook() {
|
|
2316
|
-
let preGroup = [], postGroup = [], defaultGroup = [], tapEnvironment = ({ environment, handler: cb })=>{
|
|
2317
|
-
isFunction(cb) ? defaultGroup.push({
|
|
2318
|
-
environment,
|
|
2319
|
-
handler: cb
|
|
2320
|
-
}) : 'pre' === cb.order ? preGroup.push({
|
|
2321
|
-
environment,
|
|
2322
|
-
handler: cb.handler
|
|
2323
|
-
}) : 'post' === cb.order ? postGroup.push({
|
|
2324
|
-
environment,
|
|
2325
|
-
handler: cb.handler
|
|
2326
|
-
}) : defaultGroup.push({
|
|
2327
|
-
environment,
|
|
2328
|
-
handler: cb.handler
|
|
2329
|
-
});
|
|
2330
|
-
};
|
|
2331
|
-
return {
|
|
2332
|
-
tapEnvironment,
|
|
2333
|
-
tap: (handler)=>{
|
|
2334
|
-
tapEnvironment({
|
|
2335
|
-
handler
|
|
2336
|
-
});
|
|
2337
|
-
},
|
|
2338
|
-
callChain: async ({ environment, args: params, afterEach })=>{
|
|
2339
|
-
for (let callback of [
|
|
2340
|
-
...preGroup,
|
|
2341
|
-
...defaultGroup,
|
|
2342
|
-
...postGroup
|
|
2343
|
-
]){
|
|
2344
|
-
if (environment && callback.environment && callback.environment !== environment) continue;
|
|
2345
|
-
let result = await callback.handler(...params);
|
|
2346
|
-
void 0 !== result && (params[0] = result), afterEach && afterEach(params);
|
|
2347
|
-
}
|
|
2348
|
-
return params;
|
|
2349
|
-
},
|
|
2350
|
-
callBatch: async ({ environment, args: params })=>{
|
|
2351
|
-
let results = [];
|
|
2352
|
-
for (let callback of [
|
|
2353
|
-
...preGroup,
|
|
2354
|
-
...defaultGroup,
|
|
2355
|
-
...postGroup
|
|
2356
|
-
]){
|
|
2357
|
-
if (environment && callback.environment && callback.environment !== environment) continue;
|
|
2358
|
-
let result = await callback.handler(...params);
|
|
2359
|
-
results.push(result);
|
|
2360
|
-
}
|
|
2361
|
-
return results;
|
|
2362
|
-
}
|
|
2363
|
-
};
|
|
2364
|
-
}
|
|
2365
|
-
function createAsyncHook() {
|
|
2366
|
-
let preGroup = [], postGroup = [], defaultGroup = [];
|
|
2367
|
-
return {
|
|
2368
|
-
tap: (cb)=>{
|
|
2369
|
-
isFunction(cb) ? defaultGroup.push(cb) : 'pre' === cb.order ? preGroup.push(cb.handler) : 'post' === cb.order ? postGroup.push(cb.handler) : defaultGroup.push(cb.handler);
|
|
2370
|
-
},
|
|
2371
|
-
callChain: async (...params)=>{
|
|
2372
|
-
for (let callback of [
|
|
2373
|
-
...preGroup,
|
|
2374
|
-
...defaultGroup,
|
|
2375
|
-
...postGroup
|
|
2376
|
-
]){
|
|
2377
|
-
let result = await callback(...params);
|
|
2378
|
-
void 0 !== result && (params[0] = result);
|
|
2379
|
-
}
|
|
2380
|
-
return params;
|
|
2381
|
-
},
|
|
2382
|
-
callBatch: async (...params)=>{
|
|
2383
|
-
let results = [];
|
|
2384
|
-
for (let callback of [
|
|
2385
|
-
...preGroup,
|
|
2386
|
-
...defaultGroup,
|
|
2387
|
-
...postGroup
|
|
2388
|
-
]){
|
|
2389
|
-
let result = await callback(...params);
|
|
2390
|
-
results.push(result);
|
|
2391
|
-
}
|
|
2392
|
-
return results;
|
|
2393
|
-
}
|
|
2394
|
-
};
|
|
2395
|
-
}
|
|
2396
|
-
function initHooks() {
|
|
2397
|
-
return {
|
|
2398
|
-
onExit: createAsyncHook(),
|
|
2399
|
-
onCloseBuild: createAsyncHook(),
|
|
2400
|
-
onAfterBuild: createAsyncHook(),
|
|
2401
|
-
onBeforeBuild: createAsyncHook(),
|
|
2402
|
-
onBeforeDevCompile: createAsyncHook(),
|
|
2403
|
-
onAfterDevCompile: createAsyncHook(),
|
|
2404
|
-
onCloseDevServer: createAsyncHook(),
|
|
2405
|
-
onAfterStartDevServer: createAsyncHook(),
|
|
2406
|
-
onBeforeStartDevServer: createAsyncHook(),
|
|
2407
|
-
onAfterStartProdServer: createAsyncHook(),
|
|
2408
|
-
onBeforeStartProdServer: createAsyncHook(),
|
|
2409
|
-
onAfterCreateCompiler: createAsyncHook(),
|
|
2410
|
-
onBeforeCreateCompiler: createAsyncHook(),
|
|
2411
|
-
modifyHTML: createEnvironmentAsyncHook(),
|
|
2412
|
-
modifyHTMLTags: createEnvironmentAsyncHook(),
|
|
2413
|
-
modifyRspackConfig: createEnvironmentAsyncHook(),
|
|
2414
|
-
modifyBundlerChain: createEnvironmentAsyncHook(),
|
|
2415
|
-
modifyWebpackChain: createEnvironmentAsyncHook(),
|
|
2416
|
-
modifyWebpackConfig: createEnvironmentAsyncHook(),
|
|
2417
|
-
modifyRsbuildConfig: createAsyncHook(),
|
|
2418
|
-
modifyEnvironmentConfig: createEnvironmentAsyncHook(),
|
|
2419
|
-
onBeforeEnvironmentCompile: createEnvironmentAsyncHook(),
|
|
2420
|
-
onAfterEnvironmentCompile: createEnvironmentAsyncHook()
|
|
2421
|
-
};
|
|
2422
|
-
}
|
|
2423
|
-
let onBeforeCompile = ({ compiler, beforeCompile, beforeEnvironmentCompile, isWatch })=>{
|
|
2424
|
-
let name = 'rsbuild:beforeCompile';
|
|
2425
|
-
if (compiler_isMultiCompiler(compiler)) {
|
|
2426
|
-
let waitBeforeCompileDone, { compilers } = compiler;
|
|
2427
|
-
compiler.hooks.invalid.tap(name, ()=>{
|
|
2428
|
-
waitBeforeCompileDone = void 0;
|
|
2429
|
-
});
|
|
2430
|
-
for(let index = 0; index < compilers.length; index++){
|
|
2431
|
-
let compiler = compilers[index];
|
|
2432
|
-
(isWatch ? compiler.hooks.watchRun : compiler.hooks.run).tapPromise(name, async ()=>{
|
|
2433
|
-
waitBeforeCompileDone || (waitBeforeCompileDone = beforeCompile()), await waitBeforeCompileDone, await beforeEnvironmentCompile(index);
|
|
2434
|
-
});
|
|
2435
|
-
}
|
|
2436
|
-
} else (isWatch ? compiler.hooks.watchRun : compiler.hooks.run).tapPromise(name, async ()=>{
|
|
2437
|
-
await beforeCompile(), await beforeEnvironmentCompile(0);
|
|
2438
|
-
});
|
|
2439
|
-
}, onCompileDone = ({ compiler, onDone, onEnvironmentDone, MultiStatsCtor })=>{
|
|
2440
|
-
if (compiler_isMultiCompiler(compiler)) {
|
|
2441
|
-
let { compilers } = compiler, compilerStats = [], doneCompilers = 0;
|
|
2442
|
-
for(let index = 0; index < compilers.length; index++){
|
|
2443
|
-
let compiler = compilers[index], compilerIndex = index, compilerDone = !1;
|
|
2444
|
-
compiler.hooks.done.tapPromise('rsbuild:done', async (stats)=>{
|
|
2445
|
-
!compilerDone && (compilerDone = !0, doneCompilers++), compilerStats[compilerIndex] = stats;
|
|
2446
|
-
let lastCompilerDone = doneCompilers === compilers.length;
|
|
2447
|
-
await onEnvironmentDone(index, stats), lastCompilerDone && await onDone(new MultiStatsCtor(compilerStats));
|
|
2448
|
-
}), compiler.hooks.invalid.tap('rsbuild:done', ()=>{
|
|
2449
|
-
compilerDone && (compilerDone = !1, doneCompilers--);
|
|
2450
|
-
});
|
|
2451
|
-
}
|
|
2452
|
-
} else compiler.hooks.done.tapPromise('rsbuild:done', async (stats)=>{
|
|
2453
|
-
await onEnvironmentDone(0, stats), await onDone(stats);
|
|
2454
|
-
});
|
|
2455
|
-
}, registerBuildHook = ({ context, isWatch, compiler, bundlerConfigs, MultiStatsCtor })=>{
|
|
2456
|
-
let isFirstCompile = !0, { environmentList } = context, onDone = async (stats)=>{
|
|
2457
|
-
let promise = context.hooks.onAfterBuild.callBatch({
|
|
2458
|
-
isFirstCompile,
|
|
2459
|
-
stats,
|
|
2460
|
-
environments: context.environments,
|
|
2461
|
-
isWatch
|
|
2462
|
-
});
|
|
2463
|
-
isFirstCompile = !1, await promise;
|
|
2464
|
-
}, onEnvironmentDone = async (index, stats)=>{
|
|
2465
|
-
let environment = environmentList[index], time = context.buildState.time[environment.name] ?? 0;
|
|
2466
|
-
await context.hooks.onAfterEnvironmentCompile.callBatch({
|
|
2467
|
-
environment: environment.name,
|
|
2468
|
-
args: [
|
|
2469
|
-
{
|
|
2470
|
-
isFirstCompile,
|
|
2471
|
-
stats,
|
|
2472
|
-
environment,
|
|
2473
|
-
isWatch,
|
|
2474
|
-
time
|
|
2475
|
-
}
|
|
2476
|
-
]
|
|
2477
|
-
});
|
|
2478
|
-
};
|
|
2479
|
-
onBeforeCompile({
|
|
2480
|
-
compiler,
|
|
2481
|
-
beforeCompile: async ()=>context.hooks.onBeforeBuild.callBatch({
|
|
2482
|
-
bundlerConfigs,
|
|
2483
|
-
environments: context.environments,
|
|
2484
|
-
isWatch,
|
|
2485
|
-
isFirstCompile
|
|
2486
|
-
}),
|
|
2487
|
-
beforeEnvironmentCompile: async (buildIndex)=>{
|
|
2488
|
-
let environment = environmentList[buildIndex];
|
|
2489
|
-
return context.hooks.onBeforeEnvironmentCompile.callBatch({
|
|
2490
|
-
environment: environment.name,
|
|
2491
|
-
args: [
|
|
2492
|
-
{
|
|
2493
|
-
bundlerConfig: bundlerConfigs[buildIndex],
|
|
2494
|
-
environment,
|
|
2495
|
-
isWatch,
|
|
2496
|
-
isFirstCompile
|
|
2497
|
-
}
|
|
2498
|
-
]
|
|
2499
|
-
});
|
|
2500
|
-
},
|
|
2501
|
-
isWatch
|
|
2502
|
-
}), onCompileDone({
|
|
2503
|
-
compiler,
|
|
2504
|
-
onDone,
|
|
2505
|
-
onEnvironmentDone,
|
|
2506
|
-
MultiStatsCtor
|
|
2507
|
-
});
|
|
2508
|
-
}, registerDevHook = ({ context, compiler, bundlerConfigs, MultiStatsCtor })=>{
|
|
2509
|
-
let isFirstCompile = !0, { environmentList } = context, onDone = async (stats)=>{
|
|
2510
|
-
let promise = context.hooks.onAfterDevCompile.callBatch({
|
|
2511
|
-
isFirstCompile,
|
|
2512
|
-
stats,
|
|
2513
|
-
environments: context.environments
|
|
2514
|
-
});
|
|
2515
|
-
isFirstCompile = !1, await promise;
|
|
2516
|
-
}, onEnvironmentDone = async (index, stats)=>{
|
|
2517
|
-
let environment = environmentList[index], time = context.buildState.time[environment.name] ?? 0;
|
|
2518
|
-
await context.hooks.onAfterEnvironmentCompile.callBatch({
|
|
2519
|
-
environment: environment.name,
|
|
2520
|
-
args: [
|
|
2521
|
-
{
|
|
2522
|
-
isFirstCompile,
|
|
2523
|
-
stats,
|
|
2524
|
-
environment,
|
|
2525
|
-
isWatch: !0,
|
|
2526
|
-
time
|
|
2527
|
-
}
|
|
2528
|
-
]
|
|
2529
|
-
});
|
|
2530
|
-
};
|
|
2531
|
-
onBeforeCompile({
|
|
2532
|
-
compiler,
|
|
2533
|
-
beforeEnvironmentCompile: async (buildIndex)=>{
|
|
2534
|
-
let environment = environmentList[buildIndex];
|
|
2535
|
-
return context.hooks.onBeforeEnvironmentCompile.callBatch({
|
|
2536
|
-
environment: environment.name,
|
|
2537
|
-
args: [
|
|
2538
|
-
{
|
|
2539
|
-
bundlerConfig: bundlerConfigs[buildIndex],
|
|
2540
|
-
environment,
|
|
2541
|
-
isWatch: !0,
|
|
2542
|
-
isFirstCompile
|
|
2543
|
-
}
|
|
2544
|
-
]
|
|
2545
|
-
});
|
|
2546
|
-
},
|
|
2547
|
-
beforeCompile: async ()=>context.hooks.onBeforeDevCompile.callBatch({
|
|
2548
|
-
bundlerConfigs,
|
|
2549
|
-
environments: context.environments,
|
|
2550
|
-
isFirstCompile,
|
|
2551
|
-
isWatch: !0
|
|
2552
|
-
}),
|
|
2553
|
-
isWatch: !0
|
|
2554
|
-
}), onCompileDone({
|
|
2555
|
-
compiler,
|
|
2556
|
-
onDone,
|
|
2557
|
-
onEnvironmentDone,
|
|
2558
|
-
MultiStatsCtor
|
|
2559
|
-
});
|
|
2348
|
+
}, addCompilationError = (compilation, message)=>{
|
|
2349
|
+
compilation.errors.push(new rspack_rspack.WebpackError(message));
|
|
2560
2350
|
};
|
|
2561
2351
|
function resolveFileName(stats) {
|
|
2562
2352
|
let file = stats.file || stats.moduleName;
|
|
@@ -2583,12 +2373,12 @@ function formatModuleTrace(stats, errorFile, level) {
|
|
|
2583
2373
|
...trace.slice(0, 2),
|
|
2584
2374
|
`… (${trace.length - 2 - 2} hidden)`,
|
|
2585
2375
|
...trace.slice(trace.length - 2)
|
|
2586
|
-
]),
|
|
2376
|
+
]), picocolors_default().dim(`Import traces (entry → ${level}):\n ${trace.join('\n ')} ${picocolors_default().bold(picocolors_default().red('×'))}`);
|
|
2587
2377
|
}
|
|
2588
2378
|
function hintUnknownFiles(message) {
|
|
2589
2379
|
let hint = 'You may need an appropriate loader to handle this file type.';
|
|
2590
2380
|
if (-1 === message.indexOf(hint)) return message;
|
|
2591
|
-
let createPluginHint = (packageName, keyword)=>`To enable support for ${keyword}, use "${
|
|
2381
|
+
let createPluginHint = (packageName, keyword)=>`To enable support for ${keyword}, use "${picocolors_default().yellow(`@rsbuild/plugin-${packageName}`)}" ${picocolors_default().dim(`(https://npmjs.com/package/@rsbuild/plugin-${packageName})`)}.\n`;
|
|
2592
2382
|
for (let plugin of [
|
|
2593
2383
|
{
|
|
2594
2384
|
test: /File: .+\.s(c|a)ss/,
|
|
@@ -2631,10 +2421,10 @@ function formatStatsError(stats, root, level = 'error') {
|
|
|
2631
2421
|
let DATA_URI_PREFIX = "data:text/javascript,";
|
|
2632
2422
|
if (fileName.startsWith(DATA_URI_PREFIX)) {
|
|
2633
2423
|
let snippet = fileName.replace(DATA_URI_PREFIX, '');
|
|
2634
|
-
return snippet.length > 30 && (snippet = `${snippet.slice(0, 30)}...`), `File: ${
|
|
2424
|
+
return snippet.length > 30 && (snippet = `${snippet.slice(0, 30)}...`), `File: ${picocolors_default().cyan('data-uri virtual module')} ${picocolors_default().dim(`(${snippet})`)}\n`;
|
|
2635
2425
|
}
|
|
2636
2426
|
let prefix = root + external_node_path_.sep;
|
|
2637
|
-
return (fileName.startsWith(prefix) && (fileName = fileName.replace(prefix, `.${external_node_path_.sep}`)), /:\d+:\d+/.test(fileName)) ? `File: ${
|
|
2427
|
+
return (fileName.startsWith(prefix) && (fileName = fileName.replace(prefix, `.${external_node_path_.sep}`)), /:\d+:\d+/.test(fileName)) ? `File: ${picocolors_default().cyan(fileName)}\n` : stats.loc ? `File: ${picocolors_default().cyan(`${fileName}:${stats.loc}`)}\n` : `File: ${picocolors_default().cyan(`${fileName}:1:1`)}\n`;
|
|
2638
2428
|
})(fileName, stats, root)}${stats.message}`, verbose = isVerbose();
|
|
2639
2429
|
if (verbose && (stats.details && (message += `\nDetails: ${stats.details}\n`), stats.stack && (message += `\n${stats.stack}`)), 'error' === level || isVerbose()) {
|
|
2640
2430
|
let moduleTrace = formatModuleTrace(stats, fileName, level);
|
|
@@ -2644,7 +2434,7 @@ function formatStatsError(stats, root, level = 'error') {
|
|
|
2644
2434
|
!verbose && message.includes(innerError) && (message = message.split(innerError)[0]);
|
|
2645
2435
|
let lines = (message = ((message)=>{
|
|
2646
2436
|
if (-1 === message.indexOf('Multiple assets emit different content to the same filename')) return message;
|
|
2647
|
-
let extraMessage = `You may need to adjust ${
|
|
2437
|
+
let extraMessage = `You may need to adjust ${picocolors_default().yellow('output.filename')} configuration to prevent name conflicts. (See ${picocolors_default().yellow('https://rsbuild.rs/config/output/filename')})`;
|
|
2648
2438
|
return `${message}\n${extraMessage}`;
|
|
2649
2439
|
})(message = ((message)=>{
|
|
2650
2440
|
let getTips = (moduleName)=>{
|
|
@@ -2652,9 +2442,9 @@ function formatStatsError(stats, root, level = 'error') {
|
|
|
2652
2442
|
`Error: "${moduleName}" is a built-in Node.js module and cannot be imported in client-side code.\n`,
|
|
2653
2443
|
'Solution: Check if you need to import Node.js module.',
|
|
2654
2444
|
' - If not needed, remove the import.',
|
|
2655
|
-
` - If needed, use "${
|
|
2445
|
+
` - If needed, use "${picocolors_default().yellow('@rsbuild/plugin-node-polyfill')}" to polyfill it. (See ${picocolors_default().yellow('https://npmjs.com/package/@rsbuild/plugin-node-polyfill')})`
|
|
2656
2446
|
];
|
|
2657
|
-
return `${message}\n\n${
|
|
2447
|
+
return `${message}\n\n${picocolors_default().red(tips.join('\n'))}`;
|
|
2658
2448
|
};
|
|
2659
2449
|
if (message.includes('need an additional plugin to handle "node:" URIs')) return getTips('node:*');
|
|
2660
2450
|
if (!message.includes("Can't resolve")) return message;
|
|
@@ -2668,7 +2458,7 @@ function formatStatsError(stats, root, level = 'error') {
|
|
|
2668
2458
|
let ensureTrailingNewline = (input)=>input.replace(/[ \t]+$/, '').endsWith('\n') ? input : `${input}\n`;
|
|
2669
2459
|
function formatErrorMessage(errors) {
|
|
2670
2460
|
if (!errors.length) return 'Build failed. No errors reported since Rspack\'s "stats.errors" is disabled.';
|
|
2671
|
-
let title =
|
|
2461
|
+
let title = picocolors_default().bold(picocolors_default().red(errors.length > 1 ? 'Build errors: ' : 'Build error: ')), text = ensureTrailingNewline(errors.join('\n\n'));
|
|
2672
2462
|
return `${title}\n${text}`;
|
|
2673
2463
|
}
|
|
2674
2464
|
let getStatsErrors = ({ errors, children })=>void 0 !== errors && errors.length > 0 ? errors : children ? children.reduce((errors, ret)=>ret.errors ? errors.concat(ret.errors) : errors, []) : [], getStatsWarnings = ({ warnings, children })=>void 0 !== warnings && warnings.length > 0 ? warnings : children ? children.reduce((warnings, ret)=>ret.warnings ? warnings.concat(ret.warnings) : warnings, []) : [];
|
|
@@ -2708,7 +2498,7 @@ function formatStats(stats, hasErrors, root) {
|
|
|
2708
2498
|
};
|
|
2709
2499
|
let warningMessages = getStatsWarnings(stats).map((item)=>formatStatsError(item, root, 'warning'));
|
|
2710
2500
|
if (warningMessages.length) {
|
|
2711
|
-
let title =
|
|
2501
|
+
let title = picocolors_default().bold(picocolors_default().yellow(warningMessages.length > 1 ? 'Build warnings: \n' : 'Build warning: \n'));
|
|
2712
2502
|
return {
|
|
2713
2503
|
message: ensureTrailingNewline(`${title}${warningMessages.join('\n\n')}`),
|
|
2714
2504
|
level: 'warning'
|
|
@@ -2717,6 +2507,145 @@ function formatStats(stats, hasErrors, root) {
|
|
|
2717
2507
|
return {};
|
|
2718
2508
|
}
|
|
2719
2509
|
let removeLoaderChainDelimiter = (moduleId)=>isVerbose() ? moduleId : moduleId.split('!=!')[0];
|
|
2510
|
+
function createEnvironmentAsyncHook() {
|
|
2511
|
+
let preGroup = [], postGroup = [], defaultGroup = [], tapEnvironment = ({ environment, handler: cb })=>{
|
|
2512
|
+
isFunction(cb) ? defaultGroup.push({
|
|
2513
|
+
environment,
|
|
2514
|
+
handler: cb
|
|
2515
|
+
}) : 'pre' === cb.order ? preGroup.push({
|
|
2516
|
+
environment,
|
|
2517
|
+
handler: cb.handler
|
|
2518
|
+
}) : 'post' === cb.order ? postGroup.push({
|
|
2519
|
+
environment,
|
|
2520
|
+
handler: cb.handler
|
|
2521
|
+
}) : defaultGroup.push({
|
|
2522
|
+
environment,
|
|
2523
|
+
handler: cb.handler
|
|
2524
|
+
});
|
|
2525
|
+
};
|
|
2526
|
+
return {
|
|
2527
|
+
tapEnvironment,
|
|
2528
|
+
tap: (handler)=>{
|
|
2529
|
+
tapEnvironment({
|
|
2530
|
+
handler
|
|
2531
|
+
});
|
|
2532
|
+
},
|
|
2533
|
+
callChain: async ({ environment, args: params, afterEach })=>{
|
|
2534
|
+
for (let callback of [
|
|
2535
|
+
...preGroup,
|
|
2536
|
+
...defaultGroup,
|
|
2537
|
+
...postGroup
|
|
2538
|
+
]){
|
|
2539
|
+
if (environment && callback.environment && callback.environment !== environment) continue;
|
|
2540
|
+
let result = await callback.handler(...params);
|
|
2541
|
+
void 0 !== result && (params[0] = result), afterEach && afterEach(params);
|
|
2542
|
+
}
|
|
2543
|
+
return params;
|
|
2544
|
+
},
|
|
2545
|
+
callBatch: async ({ environment, args: params })=>{
|
|
2546
|
+
let results = [];
|
|
2547
|
+
for (let callback of [
|
|
2548
|
+
...preGroup,
|
|
2549
|
+
...defaultGroup,
|
|
2550
|
+
...postGroup
|
|
2551
|
+
]){
|
|
2552
|
+
if (environment && callback.environment && callback.environment !== environment) continue;
|
|
2553
|
+
let result = await callback.handler(...params);
|
|
2554
|
+
results.push(result);
|
|
2555
|
+
}
|
|
2556
|
+
return results;
|
|
2557
|
+
}
|
|
2558
|
+
};
|
|
2559
|
+
}
|
|
2560
|
+
function createAsyncHook() {
|
|
2561
|
+
let preGroup = [], postGroup = [], defaultGroup = [];
|
|
2562
|
+
return {
|
|
2563
|
+
tap: (cb)=>{
|
|
2564
|
+
isFunction(cb) ? defaultGroup.push(cb) : 'pre' === cb.order ? preGroup.push(cb.handler) : 'post' === cb.order ? postGroup.push(cb.handler) : defaultGroup.push(cb.handler);
|
|
2565
|
+
},
|
|
2566
|
+
callChain: async (...params)=>{
|
|
2567
|
+
for (let callback of [
|
|
2568
|
+
...preGroup,
|
|
2569
|
+
...defaultGroup,
|
|
2570
|
+
...postGroup
|
|
2571
|
+
]){
|
|
2572
|
+
let result = await callback(...params);
|
|
2573
|
+
void 0 !== result && (params[0] = result);
|
|
2574
|
+
}
|
|
2575
|
+
return params;
|
|
2576
|
+
},
|
|
2577
|
+
callBatch: async (...params)=>{
|
|
2578
|
+
let results = [];
|
|
2579
|
+
for (let callback of [
|
|
2580
|
+
...preGroup,
|
|
2581
|
+
...defaultGroup,
|
|
2582
|
+
...postGroup
|
|
2583
|
+
]){
|
|
2584
|
+
let result = await callback(...params);
|
|
2585
|
+
results.push(result);
|
|
2586
|
+
}
|
|
2587
|
+
return results;
|
|
2588
|
+
}
|
|
2589
|
+
};
|
|
2590
|
+
}
|
|
2591
|
+
function initHooks() {
|
|
2592
|
+
return {
|
|
2593
|
+
onExit: createAsyncHook(),
|
|
2594
|
+
onCloseBuild: createAsyncHook(),
|
|
2595
|
+
onAfterBuild: createAsyncHook(),
|
|
2596
|
+
onBeforeBuild: createAsyncHook(),
|
|
2597
|
+
onBeforeDevCompile: createAsyncHook(),
|
|
2598
|
+
onAfterDevCompile: createAsyncHook(),
|
|
2599
|
+
onCloseDevServer: createAsyncHook(),
|
|
2600
|
+
onAfterStartDevServer: createAsyncHook(),
|
|
2601
|
+
onBeforeStartDevServer: createAsyncHook(),
|
|
2602
|
+
onAfterStartProdServer: createAsyncHook(),
|
|
2603
|
+
onBeforeStartProdServer: createAsyncHook(),
|
|
2604
|
+
onAfterCreateCompiler: createAsyncHook(),
|
|
2605
|
+
onBeforeCreateCompiler: createAsyncHook(),
|
|
2606
|
+
modifyHTML: createEnvironmentAsyncHook(),
|
|
2607
|
+
modifyHTMLTags: createEnvironmentAsyncHook(),
|
|
2608
|
+
modifyRspackConfig: createEnvironmentAsyncHook(),
|
|
2609
|
+
modifyBundlerChain: createEnvironmentAsyncHook(),
|
|
2610
|
+
modifyRsbuildConfig: createAsyncHook(),
|
|
2611
|
+
modifyEnvironmentConfig: createEnvironmentAsyncHook(),
|
|
2612
|
+
onBeforeEnvironmentCompile: createEnvironmentAsyncHook(),
|
|
2613
|
+
onAfterEnvironmentCompile: createEnvironmentAsyncHook()
|
|
2614
|
+
};
|
|
2615
|
+
}
|
|
2616
|
+
let onBeforeCompile = ({ compiler, beforeCompile, beforeEnvironmentCompile, isWatch })=>{
|
|
2617
|
+
let name = 'rsbuild:beforeCompile';
|
|
2618
|
+
if (compiler_isMultiCompiler(compiler)) {
|
|
2619
|
+
let waitBeforeCompileDone, { compilers } = compiler;
|
|
2620
|
+
compiler.hooks.invalid.tap(name, ()=>{
|
|
2621
|
+
waitBeforeCompileDone = void 0;
|
|
2622
|
+
});
|
|
2623
|
+
for(let index = 0; index < compilers.length; index++){
|
|
2624
|
+
let compiler = compilers[index];
|
|
2625
|
+
(isWatch ? compiler.hooks.watchRun : compiler.hooks.run).tapPromise(name, async ()=>{
|
|
2626
|
+
waitBeforeCompileDone || (waitBeforeCompileDone = beforeCompile()), await waitBeforeCompileDone, await beforeEnvironmentCompile(index);
|
|
2627
|
+
});
|
|
2628
|
+
}
|
|
2629
|
+
} else (isWatch ? compiler.hooks.watchRun : compiler.hooks.run).tapPromise(name, async ()=>{
|
|
2630
|
+
await beforeCompile(), await beforeEnvironmentCompile(0);
|
|
2631
|
+
});
|
|
2632
|
+
}, onCompileDone = ({ compiler, onDone, onEnvironmentDone, MultiStatsCtor })=>{
|
|
2633
|
+
if (compiler_isMultiCompiler(compiler)) {
|
|
2634
|
+
let { compilers } = compiler, compilerStats = [], doneCompilers = 0;
|
|
2635
|
+
for(let index = 0; index < compilers.length; index++){
|
|
2636
|
+
let compiler = compilers[index], compilerIndex = index, compilerDone = !1;
|
|
2637
|
+
compiler.hooks.done.tapPromise('rsbuild:done', async (stats)=>{
|
|
2638
|
+
!compilerDone && (compilerDone = !0, doneCompilers++), compilerStats[compilerIndex] = stats;
|
|
2639
|
+
let lastCompilerDone = doneCompilers === compilers.length;
|
|
2640
|
+
await onEnvironmentDone(index, stats), lastCompilerDone && await onDone(new MultiStatsCtor(compilerStats));
|
|
2641
|
+
}), compiler.hooks.invalid.tap('rsbuild:done', ()=>{
|
|
2642
|
+
compilerDone && (compilerDone = !1, doneCompilers--);
|
|
2643
|
+
});
|
|
2644
|
+
}
|
|
2645
|
+
} else compiler.hooks.done.tapPromise('rsbuild:done', async (stats)=>{
|
|
2646
|
+
await onEnvironmentDone(0, stats), await onDone(stats);
|
|
2647
|
+
});
|
|
2648
|
+
}, external_node_fs_ = __webpack_require__("node:fs");
|
|
2720
2649
|
function _define_property(obj, key, value) {
|
|
2721
2650
|
return key in obj ? Object.defineProperty(obj, key, {
|
|
2722
2651
|
value: value,
|
|
@@ -2733,7 +2662,7 @@ class BrowserslistError extends Error {
|
|
|
2733
2662
|
let isFileCache = {};
|
|
2734
2663
|
function isFile(file) {
|
|
2735
2664
|
if (file in isFileCache) return isFileCache[file];
|
|
2736
|
-
let result =
|
|
2665
|
+
let result = external_node_fs_.default.existsSync(file) && external_node_fs_.default.statSync(file).isFile();
|
|
2737
2666
|
return isFileCache[file] = result, result;
|
|
2738
2667
|
}
|
|
2739
2668
|
function dist_check(section) {
|
|
@@ -2743,7 +2672,7 @@ function dist_check(section) {
|
|
|
2743
2672
|
} else if ('string' != typeof section) throw new BrowserslistError(FORMAT);
|
|
2744
2673
|
}
|
|
2745
2674
|
function parsePackage(file) {
|
|
2746
|
-
let config = JSON.parse(
|
|
2675
|
+
let config = JSON.parse(external_node_fs_.default.readFileSync(file).toString().replace(/^\uFEFF/m, ''));
|
|
2747
2676
|
if (config.browserlist && !config.browserslist) throw new BrowserslistError(`\`browserlist\` key instead of \`browserslist\` in ${file}`);
|
|
2748
2677
|
let list = config.browserslist;
|
|
2749
2678
|
for(let i in Array.isArray(list) && (list = {
|
|
@@ -2770,7 +2699,7 @@ function parseConfig(string) {
|
|
|
2770
2699
|
}
|
|
2771
2700
|
function readConfig(file) {
|
|
2772
2701
|
if (!isFile(file)) throw new BrowserslistError(`Can't read ${file} config`);
|
|
2773
|
-
return parseConfig(
|
|
2702
|
+
return parseConfig(external_node_fs_.default.readFileSync(file, 'utf-8'));
|
|
2774
2703
|
}
|
|
2775
2704
|
function parsePackageOrReadConfig(file) {
|
|
2776
2705
|
return 'package.json' === external_node_path_.default.basename(file) ? parsePackage(file) : readConfig(file);
|
|
@@ -2844,7 +2773,7 @@ let getCompiledPath = (packageName)=>(0, external_node_path_.join)(COMPILED_PATH
|
|
|
2844
2773
|
}
|
|
2845
2774
|
}, dedupeNestedPaths = (paths)=>paths.sort((p1, p2)=>p2.length > p1.length ? -1 : 1).reduce((prev, curr)=>prev.find((p)=>curr.startsWith(p) || curr === p) ? prev : prev.concat(curr), []), toPosixPath = (filepath)=>'/' === external_node_path_.sep ? filepath : filepath.replace(/\\/g, '/'), normalizeRuleConditionPath = (filepath)=>isWindows && 'string' == typeof filepath && filepath.includes('/') && external_node_path_.win32.isAbsolute(filepath) ? filepath.replace(/\//g, '\\') : filepath, isFileSync = (filePath)=>{
|
|
2846
2775
|
try {
|
|
2847
|
-
return
|
|
2776
|
+
return external_node_fs_.default.statSync(filePath, {
|
|
2848
2777
|
throwIfNoEntry: !1
|
|
2849
2778
|
})?.isFile();
|
|
2850
2779
|
} catch (_) {
|
|
@@ -2852,7 +2781,7 @@ let getCompiledPath = (packageName)=>(0, external_node_path_.join)(COMPILED_PATH
|
|
|
2852
2781
|
}
|
|
2853
2782
|
};
|
|
2854
2783
|
function isEmptyDir(path) {
|
|
2855
|
-
let files =
|
|
2784
|
+
let files = external_node_fs_.default.readdirSync(path);
|
|
2856
2785
|
return 0 === files.length || 1 === files.length && '.git' === files[0];
|
|
2857
2786
|
}
|
|
2858
2787
|
let findExists = (files)=>{
|
|
@@ -2860,10 +2789,10 @@ let findExists = (files)=>{
|
|
|
2860
2789
|
return !1;
|
|
2861
2790
|
};
|
|
2862
2791
|
async function pathExists(path) {
|
|
2863
|
-
return
|
|
2792
|
+
return external_node_fs_.default.promises.access(path).then(()=>!0).catch(()=>!1);
|
|
2864
2793
|
}
|
|
2865
2794
|
async function isFileExists(file) {
|
|
2866
|
-
return
|
|
2795
|
+
return external_node_fs_.default.promises.access(file, external_node_fs_.default.constants.F_OK).then(()=>!0).catch(()=>!1);
|
|
2867
2796
|
}
|
|
2868
2797
|
async function fileExistsByCompilation({ inputFileSystem }, filePath) {
|
|
2869
2798
|
return new Promise((resolve)=>{
|
|
@@ -2881,7 +2810,7 @@ function readFileAsync(fs, filename) {
|
|
|
2881
2810
|
}
|
|
2882
2811
|
async function emptyDir(dir, keep = [], checkExists = !0) {
|
|
2883
2812
|
if (!checkExists || await pathExists(dir)) try {
|
|
2884
|
-
let entries = await
|
|
2813
|
+
let entries = await external_node_fs_.default.promises.readdir(dir, {
|
|
2885
2814
|
withFileTypes: !0
|
|
2886
2815
|
});
|
|
2887
2816
|
await Promise.all(entries.map(async (entry)=>{
|
|
@@ -2890,7 +2819,7 @@ async function emptyDir(dir, keep = [], checkExists = !0) {
|
|
|
2890
2819
|
let posixFullPath = toPosixPath(fullPath);
|
|
2891
2820
|
if (keep.some((regex)=>regex.test(posixFullPath))) return;
|
|
2892
2821
|
}
|
|
2893
|
-
entry.isDirectory() ? (await emptyDir(fullPath, keep, !1), keep.length || await
|
|
2822
|
+
entry.isDirectory() ? (await emptyDir(fullPath, keep, !1), keep.length || await external_node_fs_.default.promises.rmdir(fullPath)) : await external_node_fs_.default.promises.unlink(fullPath);
|
|
2894
2823
|
}));
|
|
2895
2824
|
} catch (err) {
|
|
2896
2825
|
src_logger.debug(`failed to empty dir: ${dir}`), src_logger.debug(err);
|
|
@@ -2984,7 +2913,7 @@ let OVERRIDE_PATHS = new Set([
|
|
|
2984
2913
|
},
|
|
2985
2914
|
server: {
|
|
2986
2915
|
port: 3000,
|
|
2987
|
-
host:
|
|
2916
|
+
host: LOCALHOST,
|
|
2988
2917
|
open: !1,
|
|
2989
2918
|
base: '/',
|
|
2990
2919
|
htmlFallback: 'index',
|
|
@@ -3060,8 +2989,6 @@ let OVERRIDE_PATHS = new Set([
|
|
|
3060
2989
|
},
|
|
3061
2990
|
legalComments: 'linked',
|
|
3062
2991
|
injectStyles: !1,
|
|
3063
|
-
minify: !0,
|
|
3064
|
-
module: !1,
|
|
3065
2992
|
manifest: !1,
|
|
3066
2993
|
sourceMap: {
|
|
3067
2994
|
js: void 0,
|
|
@@ -3093,7 +3020,6 @@ let OVERRIDE_PATHS = new Set([
|
|
|
3093
3020
|
}
|
|
3094
3021
|
},
|
|
3095
3022
|
performance: {
|
|
3096
|
-
profile: !1,
|
|
3097
3023
|
printFileSize: !0,
|
|
3098
3024
|
removeConsole: !1,
|
|
3099
3025
|
removeMomentLocale: !1,
|
|
@@ -3119,16 +3045,16 @@ function getDefaultEntry(root) {
|
|
|
3119
3045
|
index: entryFile
|
|
3120
3046
|
} : {};
|
|
3121
3047
|
}
|
|
3122
|
-
let withDefaultConfig = async (rootPath,
|
|
3123
|
-
let
|
|
3124
|
-
if (
|
|
3048
|
+
let withDefaultConfig = async (rootPath, userConfig)=>{
|
|
3049
|
+
let config = mergeRsbuildConfig(createDefaultConfig(), userConfig);
|
|
3050
|
+
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 = {
|
|
3125
3051
|
imports: !0,
|
|
3126
3052
|
entries: !1
|
|
3127
|
-
}), !
|
|
3053
|
+
}), !config.source.tsconfigPath) {
|
|
3128
3054
|
let tsconfigPath = (0, external_node_path_.join)(rootPath, 'tsconfig.json');
|
|
3129
|
-
await isFileExists(tsconfigPath) && (
|
|
3055
|
+
await isFileExists(tsconfigPath) && (config.source.tsconfigPath = tsconfigPath);
|
|
3130
3056
|
}
|
|
3131
|
-
return
|
|
3057
|
+
return config;
|
|
3132
3058
|
}, exitHook_callbacks = new Set(), isCalled = !1, isRegistered = !1;
|
|
3133
3059
|
function exit(exitCode, type) {
|
|
3134
3060
|
if (!isCalled) {
|
|
@@ -3150,28 +3076,22 @@ function exitHook(onExit) {
|
|
|
3150
3076
|
exitHook_callbacks.delete(onExit);
|
|
3151
3077
|
};
|
|
3152
3078
|
}
|
|
3153
|
-
let addTrailingSlash = (s)=>s.endsWith('/') ? s : `${s}/`, isURL = (str)=>str.startsWith('http') || str.startsWith('//'), urlJoin = (base, path)=>{
|
|
3079
|
+
let external_node_url_ = __webpack_require__("node:url"), addTrailingSlash = (s)=>s.endsWith('/') ? s : `${s}/`, isURL = (str)=>str.startsWith('http') || str.startsWith('//'), urlJoin = (base, path)=>{
|
|
3154
3080
|
let [urlProtocol, baseUrl] = base.split('://');
|
|
3155
3081
|
return `${urlProtocol}://${external_node_path_.posix.join(baseUrl, path)}`;
|
|
3156
|
-
},
|
|
3157
|
-
try {
|
|
3158
|
-
return new external_node_url_.URL(url), !0;
|
|
3159
|
-
} catch {
|
|
3160
|
-
return !1;
|
|
3161
|
-
}
|
|
3162
|
-
}, ensureAssetPrefix = (url, assetPrefix = DEFAULT_ASSET_PREFIX)=>url.startsWith('//') || canParse(url) || 'auto' === assetPrefix || 'function' == typeof assetPrefix ? url : assetPrefix.startsWith('http') ? urlJoin(assetPrefix, url) : assetPrefix.startsWith('//') ? urlJoin(`https:${assetPrefix}`, url).replace('https:', '') : external_node_path_.posix.join(assetPrefix, url), formatPublicPath = (publicPath, withSlash = !0)=>'auto' === publicPath ? publicPath : withSlash ? addTrailingSlash(publicPath) : publicPath.replace(/\/+$/, ''), getPublicPathFromChain = (chain, withSlash = !0)=>{
|
|
3082
|
+
}, ensureAssetPrefix = (url, assetPrefix = DEFAULT_ASSET_PREFIX)=>url.startsWith('//') || external_node_url_.URL.canParse(url) || 'auto' === assetPrefix || 'function' == typeof assetPrefix ? url : assetPrefix.startsWith('http') ? urlJoin(assetPrefix, url) : assetPrefix.startsWith('//') ? urlJoin(`https:${assetPrefix}`, url).replace('https:', '') : external_node_path_.posix.join(assetPrefix, url), formatPublicPath = (publicPath, withSlash = !0)=>'auto' === publicPath ? publicPath : withSlash ? addTrailingSlash(publicPath) : publicPath.replace(/\/+$/, ''), getPublicPathFromChain = (chain, withSlash = !0)=>{
|
|
3163
3083
|
let publicPath = chain.output.get('publicPath');
|
|
3164
3084
|
return 'string' == typeof publicPath ? formatPublicPath(publicPath, withSlash) : formatPublicPath(DEFAULT_ASSET_PREFIX, withSlash);
|
|
3165
3085
|
};
|
|
3166
3086
|
function validatePlugin(plugin) {
|
|
3167
3087
|
let type = typeof plugin;
|
|
3168
|
-
if ('object' !== type || null === plugin) throw Error(`${
|
|
3088
|
+
if ('object' !== type || null === plugin) throw Error(`${picocolors_default().dim('[rsbuild:plugin]')} Expect Rsbuild plugin instance to be an object, but got ${picocolors_default().yellow(type)}.`);
|
|
3169
3089
|
if (!isFunction(plugin.setup)) {
|
|
3170
3090
|
if (isFunction(plugin.apply)) {
|
|
3171
3091
|
let { name = 'SomeWebpackPlugin' } = plugin.constructor || {};
|
|
3172
3092
|
throw Error([
|
|
3173
|
-
`${
|
|
3174
|
-
|
|
3093
|
+
`${picocolors_default().yellow(name)} looks like a webpack or Rspack plugin, please use ${picocolors_default().yellow('`tools.rspack`')} to register it:`,
|
|
3094
|
+
picocolors_default().green(`
|
|
3175
3095
|
// rsbuild.config.ts
|
|
3176
3096
|
export default {
|
|
3177
3097
|
tools: {
|
|
@@ -3183,7 +3103,7 @@ function validatePlugin(plugin) {
|
|
|
3183
3103
|
`)
|
|
3184
3104
|
].join('\n'));
|
|
3185
3105
|
}
|
|
3186
|
-
throw Error(`${
|
|
3106
|
+
throw Error(`${picocolors_default().dim('[rsbuild:plugin]')} Expect the setup function of Rsbuild plugin to be a function, but got ${picocolors_default().yellow(type)}.`);
|
|
3187
3107
|
}
|
|
3188
3108
|
}
|
|
3189
3109
|
let isEnvironmentMatch = (pluginEnvironment, specifiedEnvironment)=>pluginEnvironment === specifiedEnvironment || void 0 === pluginEnvironment;
|
|
@@ -3221,7 +3141,7 @@ async function initPlugins({ context, pluginManager }) {
|
|
|
3221
3141
|
let allLines = [];
|
|
3222
3142
|
function getPlugin(name) {
|
|
3223
3143
|
let targets = plugins.filter((item)=>item.instance.name === name);
|
|
3224
|
-
if (!targets.length) throw Error(`${
|
|
3144
|
+
if (!targets.length) throw Error(`${picocolors_default().dim('[rsbuild:plugin]')} Plugin "${picocolors_default().yellow(name)}" not existed`);
|
|
3225
3145
|
return targets;
|
|
3226
3146
|
}
|
|
3227
3147
|
for (let plugin of plugins){
|
|
@@ -3242,7 +3162,7 @@ async function initPlugins({ context, pluginManager }) {
|
|
|
3242
3162
|
if (allLines.length) {
|
|
3243
3163
|
let restInRingPoints = {};
|
|
3244
3164
|
for (let l of allLines)restInRingPoints[l[0]] = !0, restInRingPoints[l[1]] = !0;
|
|
3245
|
-
throw Error(`${
|
|
3165
|
+
throw Error(`${picocolors_default().dim('[rsbuild:plugin]')} Plugins dependencies has loop: ${picocolors_default().yellow(Object.keys(restInRingPoints).join(','))}`);
|
|
3246
3166
|
}
|
|
3247
3167
|
return sortedPoint;
|
|
3248
3168
|
})(plugins = ((plugins)=>{
|
|
@@ -3282,10 +3202,10 @@ async function initPlugins({ context, pluginManager }) {
|
|
|
3282
3202
|
}
|
|
3283
3203
|
function getHTMLPathByEntry(entryName, config) {
|
|
3284
3204
|
let filename = getFilename(config, 'html').replace('[name]', entryName), prefix = config.output.distPath.html;
|
|
3285
|
-
return prefix.startsWith('/') && src_logger.warn(`${
|
|
3205
|
+
return prefix.startsWith('/') && src_logger.warn(`${picocolors_default().dim('[rsbuild:config]')} Absolute path is not recommended at ${picocolors_default().yellow(`output.distPath.html: "${prefix}"`)}, use relative path instead.`), external_node_path_.posix.join(prefix, filename).replace(/^\/+/, '');
|
|
3286
3206
|
}
|
|
3287
|
-
let mapProcessAssetsStage = (
|
|
3288
|
-
let { Compilation } =
|
|
3207
|
+
let mapProcessAssetsStage = (stage)=>{
|
|
3208
|
+
let { Compilation } = rspack_rspack;
|
|
3289
3209
|
switch(stage){
|
|
3290
3210
|
case 'additional':
|
|
3291
3211
|
return Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL;
|
|
@@ -3320,7 +3240,7 @@ let mapProcessAssetsStage = (compiler, stage)=>{
|
|
|
3320
3240
|
case 'report':
|
|
3321
3241
|
return Compilation.PROCESS_ASSETS_STAGE_REPORT;
|
|
3322
3242
|
default:
|
|
3323
|
-
throw Error(`${
|
|
3243
|
+
throw Error(`${picocolors_default().dim('[rsbuild]')} Invalid process assets stage: ${stage}`);
|
|
3324
3244
|
}
|
|
3325
3245
|
};
|
|
3326
3246
|
function initPluginAPI({ context, pluginManager }) {
|
|
@@ -3329,12 +3249,12 @@ function initPluginAPI({ context, pluginManager }) {
|
|
|
3329
3249
|
if (context.normalizedConfig) {
|
|
3330
3250
|
if (options?.environment) {
|
|
3331
3251
|
let config = context.normalizedConfig.environments[options.environment];
|
|
3332
|
-
if (!config) throw Error(`${
|
|
3252
|
+
if (!config) throw Error(`${picocolors_default().dim('[rsbuild]')} Cannot find normalized config by environment: ${options.environment}.`);
|
|
3333
3253
|
return config;
|
|
3334
3254
|
}
|
|
3335
3255
|
return context.normalizedConfig;
|
|
3336
3256
|
}
|
|
3337
|
-
throw Error(`${
|
|
3257
|
+
throw Error(`${picocolors_default().dim('[rsbuild]')} Cannot access normalized config until ${picocolors_default().yellow('modifyRsbuildConfig')} is called.`);
|
|
3338
3258
|
}
|
|
3339
3259
|
let getRsbuildConfig = (type = 'current')=>{
|
|
3340
3260
|
switch(type){
|
|
@@ -3345,7 +3265,7 @@ function initPluginAPI({ context, pluginManager }) {
|
|
|
3345
3265
|
case 'normalized':
|
|
3346
3266
|
return getNormalizedConfig();
|
|
3347
3267
|
}
|
|
3348
|
-
throw Error(`${
|
|
3268
|
+
throw Error(`${picocolors_default().dim('[rsbuild]')} ${picocolors_default().yellow('getRsbuildConfig')} get an invalid type param.`);
|
|
3349
3269
|
}, exposed = new Map(), expose = (id, api)=>{
|
|
3350
3270
|
exposed.set(id, api);
|
|
3351
3271
|
}, useExposed = (id)=>exposed.get(id), transformId = 0, transformer = {}, processAssetsFns = [], resolveFns = [];
|
|
@@ -3366,10 +3286,10 @@ function initPluginAPI({ context, pluginManager }) {
|
|
|
3366
3286
|
compilation.hooks.childCompiler.tap(pluginName, (childCompiler)=>{
|
|
3367
3287
|
childCompiler.__rsbuildTransformer = transformer;
|
|
3368
3288
|
});
|
|
3369
|
-
let { sources } =
|
|
3289
|
+
let { sources } = rspack_rspack;
|
|
3370
3290
|
for (let { descriptor, handler, environment: pluginEnvironment } of processAssetsFns)(!descriptor.targets || descriptor.targets.includes(target)) && (!descriptor.environments || descriptor.environments.includes(environment.name)) && (!pluginEnvironment || isEnvironmentMatch(pluginEnvironment, environment.name)) && compilation.hooks.processAssets.tapPromise({
|
|
3371
3291
|
name: pluginName,
|
|
3372
|
-
stage: mapProcessAssetsStage(
|
|
3292
|
+
stage: mapProcessAssetsStage(descriptor.stage)
|
|
3373
3293
|
}, async (assets)=>handler({
|
|
3374
3294
|
assets,
|
|
3375
3295
|
compiler,
|
|
@@ -3400,7 +3320,7 @@ function initPluginAPI({ context, pluginManager }) {
|
|
|
3400
3320
|
if (descriptor.targets && !descriptor.targets.includes(target) || descriptor.environments && !descriptor.environments.includes(environmentContext.name)) return;
|
|
3401
3321
|
let rule = chain.module.rule(id);
|
|
3402
3322
|
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);
|
|
3403
|
-
let loaderName = descriptor.raw ? 'transformRawLoader.mjs' : 'transformLoader.mjs', loaderPath = (0, external_node_path_.join)(
|
|
3323
|
+
let loaderName = descriptor.raw ? 'transformRawLoader.mjs' : 'transformLoader.mjs', loaderPath = (0, external_node_path_.join)(dirname, loaderName);
|
|
3404
3324
|
rule.use(id).loader(loaderPath).options({
|
|
3405
3325
|
id,
|
|
3406
3326
|
getEnvironment: ()=>environmentContext
|
|
@@ -3464,18 +3384,6 @@ function initPluginAPI({ context, pluginManager }) {
|
|
|
3464
3384
|
handler
|
|
3465
3385
|
});
|
|
3466
3386
|
},
|
|
3467
|
-
modifyWebpackChain: (handler)=>{
|
|
3468
|
-
hooks.modifyWebpackChain.tapEnvironment({
|
|
3469
|
-
environment,
|
|
3470
|
-
handler
|
|
3471
|
-
});
|
|
3472
|
-
},
|
|
3473
|
-
modifyWebpackConfig: (handler)=>{
|
|
3474
|
-
hooks.modifyWebpackConfig.tapEnvironment({
|
|
3475
|
-
environment,
|
|
3476
|
-
handler
|
|
3477
|
-
});
|
|
3478
|
-
},
|
|
3479
3387
|
modifyEnvironmentConfig: (handler)=>{
|
|
3480
3388
|
hooks.modifyEnvironmentConfig.tapEnvironment({
|
|
3481
3389
|
environment,
|
|
@@ -3564,14 +3472,14 @@ function createPublicContext(context) {
|
|
|
3564
3472
|
});
|
|
3565
3473
|
}
|
|
3566
3474
|
async function createContext(options, userConfig) {
|
|
3567
|
-
let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = (0, external_node_path_.join)(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0
|
|
3475
|
+
let { cwd } = options, rootPath = userConfig.root ? ensureAbsolutePath(cwd, userConfig.root) : cwd, rsbuildConfig = await withDefaultConfig(rootPath, userConfig), cachePath = (0, external_node_path_.join)(rootPath, 'node_modules', '.cache'), specifiedEnvironments = options.environment && options.environment.length > 0 ? options.environment : void 0;
|
|
3568
3476
|
return {
|
|
3569
|
-
version: "
|
|
3477
|
+
version: "2.0.0-alpha.0",
|
|
3570
3478
|
rootPath,
|
|
3571
3479
|
distPath: '',
|
|
3572
3480
|
cachePath,
|
|
3573
3481
|
callerName: options.callerName,
|
|
3574
|
-
bundlerType,
|
|
3482
|
+
bundlerType: 'rspack',
|
|
3575
3483
|
environments: {},
|
|
3576
3484
|
environmentList: [],
|
|
3577
3485
|
publicPathnames: [],
|
|
@@ -3596,39 +3504,34 @@ let normalizePluginObject = (plugin)=>{
|
|
|
3596
3504
|
setup () {}
|
|
3597
3505
|
};
|
|
3598
3506
|
};
|
|
3599
|
-
async function
|
|
3600
|
-
let { outputPath } = inspectOptions, files = [
|
|
3601
|
-
...
|
|
3602
|
-
|
|
3603
|
-
path: (0, external_node_path_.join)(outputPath, 'rsbuild.config.mjs'),
|
|
3604
|
-
label: 'Rsbuild config',
|
|
3605
|
-
content
|
|
3606
|
-
};
|
|
3607
|
-
let outputFile = `rsbuild.config.${name}.mjs`;
|
|
3507
|
+
async function emitConfigFiles({ bundlerConfigs, environmentConfigs, extraConfigs, inspectOptions }) {
|
|
3508
|
+
let { outputPath } = inspectOptions, isSingle = 1 === environmentConfigs.length, files = [
|
|
3509
|
+
...environmentConfigs.map(({ name, content })=>{
|
|
3510
|
+
let outputFile = isSingle ? 'rsbuild.config.mjs' : `rsbuild.config.${name}.mjs`, label = isSingle ? 'Rsbuild config' : `Rsbuild config (${name})`;
|
|
3608
3511
|
return {
|
|
3609
3512
|
path: (0, external_node_path_.join)(outputPath, outputFile),
|
|
3610
|
-
label
|
|
3513
|
+
label,
|
|
3611
3514
|
content
|
|
3612
3515
|
};
|
|
3613
3516
|
}),
|
|
3614
|
-
...
|
|
3615
|
-
let outputFile =
|
|
3616
|
-
return
|
|
3517
|
+
...bundlerConfigs.map(({ name, content })=>{
|
|
3518
|
+
let outputFile = `rspack.config.${name}.mjs`, outputFilePath = (0, external_node_path_.join)(outputPath, outputFile);
|
|
3519
|
+
return external_node_fs_.default.existsSync(outputFilePath) && (outputFilePath = outputFilePath.replace(/\.mjs$/, `.${Date.now()}.mjs`)), {
|
|
3617
3520
|
path: outputFilePath,
|
|
3618
|
-
label:
|
|
3521
|
+
label: `Rspack Config (${name})`,
|
|
3619
3522
|
content
|
|
3620
3523
|
};
|
|
3621
3524
|
}),
|
|
3622
|
-
...(
|
|
3525
|
+
...(extraConfigs || []).map(({ name, content })=>({
|
|
3623
3526
|
path: (0, external_node_path_.join)(outputPath, `${name}.config.mjs`),
|
|
3624
3527
|
label: `${upperFirst(name)} Config`,
|
|
3625
3528
|
content
|
|
3626
3529
|
}))
|
|
3627
3530
|
];
|
|
3628
|
-
await
|
|
3531
|
+
await external_node_fs_.default.promises.mkdir(outputPath, {
|
|
3629
3532
|
recursive: !0
|
|
3630
|
-
}), await Promise.all(files.map(async (item)=>
|
|
3631
|
-
let fileInfos = files.map((item)=>` - ${
|
|
3533
|
+
}), await Promise.all(files.map(async (item)=>external_node_fs_.default.promises.writeFile(item.path, `export default ${item.content}`)));
|
|
3534
|
+
let fileInfos = files.map((item)=>` - ${picocolors_default().bold(picocolors_default().yellow(item.label))}: ${picocolors_default().underline(item.path)}`).join('\n');
|
|
3632
3535
|
src_logger.success(`config inspection completed, generated files: \n\n${fileInfos}\n`);
|
|
3633
3536
|
}
|
|
3634
3537
|
function stringifyConfig(config, verbose) {
|
|
@@ -3636,59 +3539,49 @@ function stringifyConfig(config, verbose) {
|
|
|
3636
3539
|
verbose
|
|
3637
3540
|
});
|
|
3638
3541
|
}
|
|
3639
|
-
async function inspectConfig_inspectConfig({ context, pluginManager, bundlerConfigs, inspectOptions = {}
|
|
3640
|
-
var context1, inspectOptions1;
|
|
3542
|
+
async function inspectConfig_inspectConfig({ context, pluginManager, bundlerConfigs, inspectOptions = {} }) {
|
|
3641
3543
|
inspectOptions.mode ? setNodeEnv(inspectOptions.mode) : process.env.NODE_ENV || setNodeEnv('development');
|
|
3642
|
-
let
|
|
3544
|
+
let stringifiedBundlerConfigs = bundlerConfigs.map((config, index)=>({
|
|
3643
3545
|
name: config.name || String(index),
|
|
3644
3546
|
content: stringifyConfig(config, inspectOptions.verbose)
|
|
3645
|
-
})), {
|
|
3646
|
-
|
|
3647
|
-
|
|
3648
|
-
|
|
3649
|
-
|
|
3650
|
-
|
|
3651
|
-
|
|
3652
|
-
|
|
3653
|
-
|
|
3654
|
-
|
|
3655
|
-
}).map(normalizePluginObject)
|
|
3656
|
-
};
|
|
3657
|
-
rawEnvironmentConfigs.push({
|
|
3658
|
-
name,
|
|
3659
|
-
content: stringifyConfig(debugConfig, inspectOptions.verbose)
|
|
3660
|
-
}), environmentConfigs[name] = debugConfig;
|
|
3661
|
-
}
|
|
3662
|
-
return {
|
|
3663
|
-
rsbuildConfig,
|
|
3664
|
-
rawRsbuildConfig,
|
|
3665
|
-
environmentConfigs: environments,
|
|
3666
|
-
rawEnvironmentConfigs
|
|
3547
|
+
})), { environments, ...rsbuildConfig } = context.normalizedConfig, stringifiedRsbuildConfig = stringifyConfig({
|
|
3548
|
+
...rsbuildConfig,
|
|
3549
|
+
plugins: pluginManager.getPlugins().map(normalizePluginObject)
|
|
3550
|
+
}, inspectOptions.verbose), stringifiedEnvironmentConfigs = [];
|
|
3551
|
+
for (let [name, config] of Object.entries(environments)){
|
|
3552
|
+
let normalizedEnvConfig = {
|
|
3553
|
+
...config,
|
|
3554
|
+
plugins: pluginManager.getPlugins({
|
|
3555
|
+
environment: name
|
|
3556
|
+
}).map(normalizePluginObject)
|
|
3667
3557
|
};
|
|
3668
|
-
|
|
3669
|
-
|
|
3670
|
-
|
|
3671
|
-
|
|
3672
|
-
}
|
|
3558
|
+
stringifiedEnvironmentConfigs.push({
|
|
3559
|
+
name,
|
|
3560
|
+
content: stringifyConfig(normalizedEnvConfig, inspectOptions.verbose)
|
|
3561
|
+
});
|
|
3562
|
+
}
|
|
3563
|
+
let outputPath = ((context, inspectOptions)=>{
|
|
3564
|
+
let { outputPath } = inspectOptions;
|
|
3565
|
+
return outputPath ? (0, external_node_path_.isAbsolute)(outputPath) ? outputPath : (0, external_node_path_.join)(context.distPath, outputPath) : (0, external_node_path_.join)(context.distPath, RSBUILD_OUTPUTS_PATH);
|
|
3566
|
+
})(context, inspectOptions), stringifiedExtraConfigs = inspectOptions.extraConfigs ? Object.entries(inspectOptions.extraConfigs).map(([name, content])=>({
|
|
3673
3567
|
name,
|
|
3674
3568
|
content: 'string' == typeof content ? content : stringifyConfig(content, inspectOptions.verbose)
|
|
3675
3569
|
})) : void 0;
|
|
3676
|
-
return inspectOptions.writeToDisk && await
|
|
3677
|
-
|
|
3678
|
-
|
|
3679
|
-
|
|
3570
|
+
return inspectOptions.writeToDisk && await emitConfigFiles({
|
|
3571
|
+
bundlerConfigs: stringifiedBundlerConfigs,
|
|
3572
|
+
environmentConfigs: stringifiedEnvironmentConfigs,
|
|
3573
|
+
extraConfigs: stringifiedExtraConfigs,
|
|
3680
3574
|
inspectOptions: {
|
|
3681
3575
|
...inspectOptions,
|
|
3682
3576
|
outputPath
|
|
3683
|
-
}
|
|
3684
|
-
configType: bundler
|
|
3577
|
+
}
|
|
3685
3578
|
}), {
|
|
3686
|
-
rsbuildConfig:
|
|
3687
|
-
environmentConfigs:
|
|
3688
|
-
bundlerConfigs:
|
|
3579
|
+
rsbuildConfig: stringifiedRsbuildConfig,
|
|
3580
|
+
environmentConfigs: stringifiedEnvironmentConfigs.map((item)=>item.content),
|
|
3581
|
+
bundlerConfigs: stringifiedBundlerConfigs.map((item)=>item.content),
|
|
3689
3582
|
origin: {
|
|
3690
3583
|
rsbuildConfig,
|
|
3691
|
-
environmentConfigs,
|
|
3584
|
+
environmentConfigs: environments,
|
|
3692
3585
|
bundlerConfigs
|
|
3693
3586
|
}
|
|
3694
3587
|
};
|
|
@@ -3730,10 +3623,10 @@ function reduceConfigsMergeContext({ initial, config, ctx, mergeFn = Object.assi
|
|
|
3730
3623
|
}
|
|
3731
3624
|
async function modifyBundlerChain(context, utils) {
|
|
3732
3625
|
src_logger.debug('applying modifyBundlerChain hook');
|
|
3733
|
-
let
|
|
3626
|
+
let rspackChain = new src_class(), [modifiedBundlerChain] = await context.hooks.modifyBundlerChain.callChain({
|
|
3734
3627
|
environment: utils.environment.name,
|
|
3735
3628
|
args: [
|
|
3736
|
-
|
|
3629
|
+
rspackChain,
|
|
3737
3630
|
utils
|
|
3738
3631
|
]
|
|
3739
3632
|
});
|
|
@@ -3805,7 +3698,6 @@ let configChain_CHAIN_ID = {
|
|
|
3805
3698
|
PROGRESS: 'progress',
|
|
3806
3699
|
MANIFEST: 'webpack-manifest',
|
|
3807
3700
|
TS_CHECKER: 'ts-checker',
|
|
3808
|
-
BUNDLE_ANALYZER: 'bundle-analyze',
|
|
3809
3701
|
MODULE_FEDERATION: 'module-federation',
|
|
3810
3702
|
HTML_PREFETCH: 'html-prefetch-plugin',
|
|
3811
3703
|
HTML_PRELOAD: 'html-preload-plugin',
|
|
@@ -3821,11 +3713,10 @@ let configChain_CHAIN_ID = {
|
|
|
3821
3713
|
RESOLVE_PLUGIN: {
|
|
3822
3714
|
TS_CONFIG_PATHS: 'ts-config-paths'
|
|
3823
3715
|
}
|
|
3824
|
-
},
|
|
3825
|
-
|
|
3826
|
-
|
|
3827
|
-
|
|
3828
|
-
};
|
|
3716
|
+
}, vendors_require = (0, external_node_module_.createRequire)(import.meta.url), requireCompiledPackage = (name)=>vendors_require(`${COMPILED_PATH}/${name}/index.js`);
|
|
3717
|
+
function pluginHelper_getHTMLPlugin(config) {
|
|
3718
|
+
return config?.html.implementation === 'native' ? rspack_rspack.HtmlRspackPlugin : (pluginHelper_htmlPlugin || (pluginHelper_htmlPlugin = requireCompiledPackage('html-rspack-plugin')), pluginHelper_htmlPlugin);
|
|
3719
|
+
}
|
|
3829
3720
|
async function modifyRspackConfig(context, rspackConfig, chainUtils) {
|
|
3830
3721
|
src_logger.debug('applying modifyRspackConfig hook');
|
|
3831
3722
|
let currentConfig = rspackConfig, utils = getConfigUtils(()=>currentConfig, chainUtils);
|
|
@@ -3896,11 +3787,11 @@ function getChainUtils(target, environment, environments) {
|
|
|
3896
3787
|
function validateRspackConfig(config) {
|
|
3897
3788
|
if (config.plugins) {
|
|
3898
3789
|
for (let plugin of config.plugins)if (plugin && void 0 === plugin.apply && 'name' in plugin && 'setup' in plugin) {
|
|
3899
|
-
let name =
|
|
3900
|
-
throw Error(`${
|
|
3790
|
+
let name = picocolors_default().bold(picocolors_default().yellow(plugin.name));
|
|
3791
|
+
throw Error(`${picocolors_default().dim('[rsbuild:plugin]')} "${picocolors_default().yellow(name)}" appears to be an Rsbuild plugin. It cannot be used as an Rspack plugin.`);
|
|
3901
3792
|
}
|
|
3902
3793
|
}
|
|
3903
|
-
config.devServer && src_logger.warn(`${
|
|
3794
|
+
config.devServer && src_logger.warn(`${picocolors_default().dim('[rsbuild:config]')} Find invalid Rspack config: "${picocolors_default().yellow('devServer')}". Note that Rspack's "devServer" config is not supported by Rsbuild. You can use Rsbuild's "dev" config to configure the Rsbuild dev server.`);
|
|
3904
3795
|
}
|
|
3905
3796
|
async function generateRspackConfig({ target, context, environmentName }) {
|
|
3906
3797
|
let chainUtils = getChainUtils(target, context.environments[environmentName], context.environments), { BannerPlugin, DefinePlugin, IgnorePlugin, ProvidePlugin, SourceMapDevToolPlugin, HotModuleReplacementPlugin } = rspack_rspack, rspackConfig = (await modifyBundlerChain(context, {
|
|
@@ -3931,7 +3822,7 @@ async function modifyRsbuildConfig(context) {
|
|
|
3931
3822
|
let pluginsCount = context.config.plugins?.length ?? 0, [modified] = await context.hooks.modifyRsbuildConfig.callChain(context.config, {
|
|
3932
3823
|
mergeRsbuildConfig: mergeRsbuildConfig
|
|
3933
3824
|
});
|
|
3934
|
-
context.config = modified, (modified.plugins?.length ?? 0) !== pluginsCount && src_logger.warn(`${
|
|
3825
|
+
context.config = modified, (modified.plugins?.length ?? 0) !== pluginsCount && src_logger.warn(`${picocolors_default().dim('[rsbuild]')} Cannot change plugins via ${picocolors_default().yellow('modifyRsbuildConfig')} as plugins are already initialized when it executes.`), src_logger.debug('applied modifyRsbuildConfig hook');
|
|
3935
3826
|
}
|
|
3936
3827
|
async function modifyEnvironmentConfig(context, config, name) {
|
|
3937
3828
|
src_logger.debug(`applying modifyEnvironmentConfig hook (${name})`);
|
|
@@ -3948,8 +3839,8 @@ async function modifyEnvironmentConfig(context, config, name) {
|
|
|
3948
3839
|
return src_logger.debug(`applied modifyEnvironmentConfig hook (${name})`), modified;
|
|
3949
3840
|
}
|
|
3950
3841
|
let createEnvironmentNotFoundError = (environments = [])=>{
|
|
3951
|
-
let envList =
|
|
3952
|
-
return Error(`${
|
|
3842
|
+
let envList = picocolors_default().yellow(environments.join(','));
|
|
3843
|
+
return Error(`${picocolors_default().dim('[rsbuild:config]')} The current build is specified to run only in the ${envList} environment, but the configuration of the specified environment was not found.`);
|
|
3953
3844
|
};
|
|
3954
3845
|
async function initRsbuildConfig({ context, pluginManager }) {
|
|
3955
3846
|
var config, rootPath;
|
|
@@ -3985,10 +3876,10 @@ async function initRsbuildConfig({ context, pluginManager }) {
|
|
|
3985
3876
|
let nodeEnv = process.env.NODE_ENV || '';
|
|
3986
3877
|
return 'production' === nodeEnv || 'development' === nodeEnv ? nodeEnv : 'none';
|
|
3987
3878
|
})(), mergeRsbuildConfig(defaultConfig, config)), environments = {}, mergedEnvironments = ((normalizedConfig, rootPath, specifiedEnvironments)=>{
|
|
3988
|
-
let defaultEntry, { environments, dev, server: _server,
|
|
3879
|
+
let defaultEntry, { environments, dev, server: _server, ...baseConfig } = normalizedConfig, isEnvironmentEnabled = (name)=>!specifiedEnvironments || specifiedEnvironments.includes(name), applyEnvironmentDefaultConfig = (config)=>{
|
|
3989
3880
|
config.source.entry && 0 !== Object.keys(config.source.entry).length || (config.source.entry = (defaultEntry || (defaultEntry = getDefaultEntry(rootPath)), defaultEntry));
|
|
3990
3881
|
let isServer = 'node' === config.output.target;
|
|
3991
|
-
return void 0 === config.output.distPath.js && (config.output.distPath.js = isServer ? '' : 'static/js'), config;
|
|
3882
|
+
return void 0 === config.output.distPath.js && (config.output.distPath.js = isServer ? '' : 'static/js'), void 0 === config.output.module && (config.output.module = isServer), config;
|
|
3992
3883
|
};
|
|
3993
3884
|
if (environments && Object.keys(environments).length > 0) {
|
|
3994
3885
|
let resolvedEnvironments = Object.fromEntries(Object.entries(environments).filter(([name])=>isEnvironmentEnabled(name)).map(([name, config])=>[
|
|
@@ -4034,7 +3925,7 @@ async function initRsbuildConfig({ context, pluginManager }) {
|
|
|
4034
3925
|
...normalizedBaseConfig,
|
|
4035
3926
|
environments
|
|
4036
3927
|
}, await updateEnvironmentContext(context, environments), updateContextByNormalizedConfig(context), ((config)=>{
|
|
4037
|
-
if (config.server.base && !config.server.base.startsWith('/')) throw Error(`${
|
|
3928
|
+
if (config.server.base && !config.server.base.startsWith('/')) throw Error(`${picocolors_default().dim('[rsbuild:config]')} The ${picocolors_default().yellow('"server.base"')} option should start with a slash, for example: "/base"`);
|
|
4038
3929
|
if (!config.environments) return;
|
|
4039
3930
|
let environmentNames = Object.keys(config.environments), environmentNameRegexp = /^[\w$-]+$/, validTargets = [
|
|
4040
3931
|
'web',
|
|
@@ -4042,13 +3933,13 @@ async function initRsbuildConfig({ context, pluginManager }) {
|
|
|
4042
3933
|
'web-worker'
|
|
4043
3934
|
];
|
|
4044
3935
|
for (let name of environmentNames){
|
|
4045
|
-
environmentNameRegexp.test(name) || src_logger.warn(`${
|
|
3936
|
+
environmentNameRegexp.test(name) || src_logger.warn(`${picocolors_default().dim('[rsbuild:config]')} Environment name "${picocolors_default().yellow(name)}" contains invalid characters. Only letters, numbers, "-", "_", and "$" are allowed.`);
|
|
4046
3937
|
let outputConfig = config.environments[name].output;
|
|
4047
|
-
if (outputConfig.target && !validTargets.includes(outputConfig.target)) throw Error(`${
|
|
3938
|
+
if (outputConfig.target && !validTargets.includes(outputConfig.target)) throw Error(`${picocolors_default().dim('[rsbuild:config]')} Invalid value of ${picocolors_default().yellow('output.target')}: ${picocolors_default().yellow(`"${outputConfig.target}"`)}, valid values are: ${picocolors_default().yellow(validTargets.join(', '))}`);
|
|
4048
3939
|
}
|
|
4049
3940
|
})(context.normalizedConfig), context.normalizedConfig;
|
|
4050
3941
|
}
|
|
4051
|
-
async function
|
|
3942
|
+
async function initConfigs_initConfigs({ context, pluginManager, rsbuildOptions }) {
|
|
4052
3943
|
let normalizedConfig = await initRsbuildConfig({
|
|
4053
3944
|
context,
|
|
4054
3945
|
pluginManager
|
|
@@ -4100,21 +3991,21 @@ function printBuildLog(compiler, context, lazyModules) {
|
|
|
4100
3991
|
let { modifiedFiles } = compiler, changedFiles = modifiedFiles?.size ? Array.from(modifiedFiles) : lazyModules.size ? Array.from(lazyModules) : null;
|
|
4101
3992
|
if (changedFiles?.length) {
|
|
4102
3993
|
let fileInfo = formatFileList(changedFiles, context.rootPath);
|
|
4103
|
-
src_logger.start(`building ${
|
|
3994
|
+
src_logger.start(`building ${picocolors_default().dim(fileInfo)}`);
|
|
4104
3995
|
return;
|
|
4105
3996
|
}
|
|
4106
3997
|
let removedFiles = compiler.removedFiles ? Array.from(compiler.removedFiles) : null;
|
|
4107
3998
|
if (removedFiles?.length) {
|
|
4108
|
-
if (removedFiles.every((item)=>item.includes('virtual'))) return void src_logger.start(`building ${
|
|
3999
|
+
if (removedFiles.every((item)=>item.includes('virtual'))) return void src_logger.start(`building ${picocolors_default().dim('virtual modules')}`);
|
|
4109
4000
|
let fileInfo = formatFileList(removedFiles, context.rootPath);
|
|
4110
|
-
return void src_logger.start(`building ${
|
|
4001
|
+
return void src_logger.start(`building ${picocolors_default().dim(`removed ${fileInfo}`)}`);
|
|
4111
4002
|
}
|
|
4112
4003
|
src_logger.start('build started...');
|
|
4113
4004
|
}
|
|
4114
4005
|
async function createCompiler_createCompiler(options) {
|
|
4115
4006
|
let version;
|
|
4116
4007
|
src_logger.debug('creating compiler');
|
|
4117
|
-
let HOOK_NAME = 'rsbuild:compiler', { context } = options, { rspackConfigs } = await
|
|
4008
|
+
let HOOK_NAME = 'rsbuild:compiler', { context } = options, { rspackConfigs } = await initConfigs_initConfigs(options);
|
|
4118
4009
|
if (await context.hooks.onBeforeCreateCompiler.callBatch({
|
|
4119
4010
|
bundlerConfigs: rspackConfigs,
|
|
4120
4011
|
environments: context.environments
|
|
@@ -4126,7 +4017,7 @@ async function createCompiler_createCompiler(options) {
|
|
|
4126
4017
|
if (item1 < item2) return -1;
|
|
4127
4018
|
}
|
|
4128
4019
|
return 0;
|
|
4129
|
-
})(version, '1.5.0') >= 0)) throw Error(`${
|
|
4020
|
+
})(version, '1.5.0') >= 0)) throw Error(`${picocolors_default().dim('[rsbuild]')} The current Rspack version does not meet the requirements, the minimum supported version of Rspack is ${picocolors_default().green("1.5.0")}`);
|
|
4130
4021
|
let isMultiCompiler = rspackConfigs.length > 1, compiler = isMultiCompiler ? rspack_rspack(rspackConfigs) : rspack_rspack(rspackConfigs[0]);
|
|
4131
4022
|
'true' === process.env.RSPACK_UNSAFE_FAST_DROP && (compiler.unsafeFastDrop = !0);
|
|
4132
4023
|
let isVersionLogged = !1, isCompiling = !1, logRspackVersion = ()=>{
|
|
@@ -4158,7 +4049,21 @@ async function createCompiler_createCompiler(options) {
|
|
|
4158
4049
|
if (null === startTime) return;
|
|
4159
4050
|
let { name } = context.environmentList[index], time = Date.now() - startTime;
|
|
4160
4051
|
context.buildState.time[name] = time;
|
|
4161
|
-
let suffix = isMultiCompiler ?
|
|
4052
|
+
let suffix = isMultiCompiler ? picocolors_default().dim(` (${name})`) : '', timeStr = `${((seconds)=>{
|
|
4053
|
+
let time, time1;
|
|
4054
|
+
if (seconds < 10) {
|
|
4055
|
+
let time, digits = seconds >= 0.01 ? 2 : 3;
|
|
4056
|
+
return `${time = seconds.toFixed(digits), picocolors_default().bold(time)} s`;
|
|
4057
|
+
}
|
|
4058
|
+
if (seconds < 60) {
|
|
4059
|
+
let time;
|
|
4060
|
+
return `${time = seconds.toFixed(1), picocolors_default().bold(time)} s`;
|
|
4061
|
+
}
|
|
4062
|
+
let minutes = Math.floor(seconds / 60), minutesLabel = `${(time = minutes.toFixed(0), picocolors_default().bold(time))} m`, remainingSeconds = seconds % 60;
|
|
4063
|
+
if (0 === remainingSeconds) return minutesLabel;
|
|
4064
|
+
let secondsLabel = `${(time1 = remainingSeconds.toFixed(+(remainingSeconds % 1 != 0)), picocolors_default().bold(time1))} s`;
|
|
4065
|
+
return `${minutesLabel} ${secondsLabel}`;
|
|
4066
|
+
})(time / 1000)}${suffix}`;
|
|
4162
4067
|
hasErrors ? src_logger.error(`build failed in ${timeStr}`) : src_logger.ready(`built in ${timeStr}`);
|
|
4163
4068
|
};
|
|
4164
4069
|
return isMultiCompiler && compiler.compilers.forEach((item, index)=>{
|
|
@@ -4170,7 +4075,59 @@ async function createCompiler_createCompiler(options) {
|
|
|
4170
4075
|
context.buildState.stats = stats, context.buildState.status = 'done', context.buildState.hasErrors = hasErrors, context.socketServer?.onBuildDone();
|
|
4171
4076
|
let { message, level } = formatStats(stats, hasErrors, options.context.rootPath);
|
|
4172
4077
|
'error' === level && src_logger.error(message), 'warning' === level && src_logger.warn(message), isMultiCompiler || printTime(0, hasErrors), isCompiling = !1;
|
|
4173
|
-
}), 'dev' === context.action &&
|
|
4078
|
+
}), 'dev' === context.action && (({ context, compiler, bundlerConfigs, MultiStatsCtor })=>{
|
|
4079
|
+
let isFirstCompile = !0, { environmentList } = context, onDone = async (stats)=>{
|
|
4080
|
+
let promise = context.hooks.onAfterDevCompile.callBatch({
|
|
4081
|
+
isFirstCompile,
|
|
4082
|
+
stats,
|
|
4083
|
+
environments: context.environments
|
|
4084
|
+
});
|
|
4085
|
+
isFirstCompile = !1, await promise;
|
|
4086
|
+
}, onEnvironmentDone = async (index, stats)=>{
|
|
4087
|
+
let environment = environmentList[index], time = context.buildState.time[environment.name] ?? 0;
|
|
4088
|
+
await context.hooks.onAfterEnvironmentCompile.callBatch({
|
|
4089
|
+
environment: environment.name,
|
|
4090
|
+
args: [
|
|
4091
|
+
{
|
|
4092
|
+
isFirstCompile,
|
|
4093
|
+
stats,
|
|
4094
|
+
environment,
|
|
4095
|
+
isWatch: !0,
|
|
4096
|
+
time
|
|
4097
|
+
}
|
|
4098
|
+
]
|
|
4099
|
+
});
|
|
4100
|
+
};
|
|
4101
|
+
onBeforeCompile({
|
|
4102
|
+
compiler,
|
|
4103
|
+
beforeEnvironmentCompile: async (buildIndex)=>{
|
|
4104
|
+
let environment = environmentList[buildIndex];
|
|
4105
|
+
return context.hooks.onBeforeEnvironmentCompile.callBatch({
|
|
4106
|
+
environment: environment.name,
|
|
4107
|
+
args: [
|
|
4108
|
+
{
|
|
4109
|
+
bundlerConfig: bundlerConfigs[buildIndex],
|
|
4110
|
+
environment,
|
|
4111
|
+
isWatch: !0,
|
|
4112
|
+
isFirstCompile
|
|
4113
|
+
}
|
|
4114
|
+
]
|
|
4115
|
+
});
|
|
4116
|
+
},
|
|
4117
|
+
beforeCompile: async ()=>context.hooks.onBeforeDevCompile.callBatch({
|
|
4118
|
+
bundlerConfigs,
|
|
4119
|
+
environments: context.environments,
|
|
4120
|
+
isFirstCompile,
|
|
4121
|
+
isWatch: !0
|
|
4122
|
+
}),
|
|
4123
|
+
isWatch: !0
|
|
4124
|
+
}), onCompileDone({
|
|
4125
|
+
compiler,
|
|
4126
|
+
onDone,
|
|
4127
|
+
onEnvironmentDone,
|
|
4128
|
+
MultiStatsCtor
|
|
4129
|
+
});
|
|
4130
|
+
})({
|
|
4174
4131
|
context,
|
|
4175
4132
|
compiler,
|
|
4176
4133
|
bundlerConfigs: rspackConfigs,
|
|
@@ -4183,21 +4140,69 @@ async function createCompiler_createCompiler(options) {
|
|
|
4183
4140
|
rspackConfigs
|
|
4184
4141
|
};
|
|
4185
4142
|
}
|
|
4186
|
-
let RSPACK_BUILD_ERROR = 'Rspack build failed.', build_build = async (initOptions, { watch
|
|
4187
|
-
let
|
|
4188
|
-
if (
|
|
4189
|
-
|
|
4190
|
-
|
|
4191
|
-
|
|
4192
|
-
|
|
4193
|
-
|
|
4143
|
+
let RSPACK_BUILD_ERROR = 'Rspack build failed.', build_build = async (initOptions, { watch } = {})=>{
|
|
4144
|
+
let { context } = initOptions, { compiler, rspackConfigs } = await createCompiler_createCompiler(initOptions);
|
|
4145
|
+
if ((({ context, isWatch, compiler, rspackConfigs, MultiStatsCtor })=>{
|
|
4146
|
+
let isFirstCompile = !0, { environmentList } = context, onDone = async (stats)=>{
|
|
4147
|
+
let promise = context.hooks.onAfterBuild.callBatch({
|
|
4148
|
+
isFirstCompile,
|
|
4149
|
+
stats,
|
|
4150
|
+
environments: context.environments,
|
|
4151
|
+
isWatch
|
|
4152
|
+
});
|
|
4153
|
+
isFirstCompile = !1, await promise;
|
|
4154
|
+
}, onEnvironmentDone = async (index, stats)=>{
|
|
4155
|
+
let environment = environmentList[index], time = context.buildState.time[environment.name] ?? 0;
|
|
4156
|
+
await context.hooks.onAfterEnvironmentCompile.callBatch({
|
|
4157
|
+
environment: environment.name,
|
|
4158
|
+
args: [
|
|
4159
|
+
{
|
|
4160
|
+
isFirstCompile,
|
|
4161
|
+
stats,
|
|
4162
|
+
environment,
|
|
4163
|
+
isWatch,
|
|
4164
|
+
time
|
|
4165
|
+
}
|
|
4166
|
+
]
|
|
4167
|
+
});
|
|
4168
|
+
};
|
|
4169
|
+
onBeforeCompile({
|
|
4170
|
+
compiler,
|
|
4171
|
+
beforeCompile: async ()=>context.hooks.onBeforeBuild.callBatch({
|
|
4172
|
+
bundlerConfigs: rspackConfigs,
|
|
4173
|
+
environments: context.environments,
|
|
4174
|
+
isWatch,
|
|
4175
|
+
isFirstCompile
|
|
4176
|
+
}),
|
|
4177
|
+
beforeEnvironmentCompile: async (buildIndex)=>{
|
|
4178
|
+
let environment = environmentList[buildIndex];
|
|
4179
|
+
return context.hooks.onBeforeEnvironmentCompile.callBatch({
|
|
4180
|
+
environment: environment.name,
|
|
4181
|
+
args: [
|
|
4182
|
+
{
|
|
4183
|
+
bundlerConfig: rspackConfigs[buildIndex],
|
|
4184
|
+
environment,
|
|
4185
|
+
isWatch,
|
|
4186
|
+
isFirstCompile
|
|
4187
|
+
}
|
|
4188
|
+
]
|
|
4189
|
+
});
|
|
4190
|
+
},
|
|
4191
|
+
isWatch
|
|
4192
|
+
}), onCompileDone({
|
|
4193
|
+
compiler,
|
|
4194
|
+
onDone,
|
|
4195
|
+
onEnvironmentDone,
|
|
4196
|
+
MultiStatsCtor
|
|
4197
|
+
});
|
|
4198
|
+
})({
|
|
4194
4199
|
context,
|
|
4195
|
-
|
|
4200
|
+
rspackConfigs,
|
|
4196
4201
|
compiler,
|
|
4197
4202
|
isWatch: !!watch,
|
|
4198
4203
|
MultiStatsCtor: rspack_rspack.MultiStats
|
|
4199
4204
|
}), watch) {
|
|
4200
|
-
let watchOptions =
|
|
4205
|
+
let watchOptions = rspackConfigs.map((options)=>options.watchOptions || {});
|
|
4201
4206
|
return compiler.watch(watchOptions.length > 1 ? watchOptions : watchOptions[0] || {}, (err)=>{
|
|
4202
4207
|
err && src_logger.error(err);
|
|
4203
4208
|
}), {
|
|
@@ -4233,14 +4238,14 @@ function loadEnv_parse(src) {
|
|
|
4233
4238
|
function loadEnv({ cwd = process.cwd(), mode = process.env.NODE_ENV || '', prefixes = [
|
|
4234
4239
|
'PUBLIC_'
|
|
4235
4240
|
], processEnv = process.env } = {}) {
|
|
4236
|
-
if ('local' === mode) throw Error(`${
|
|
4241
|
+
if ('local' === mode) throw Error(`${picocolors_default().dim('[rsbuild:loadEnv]')} ${picocolors_default().yellow('local')} cannot be used as a value for env mode, because ${picocolors_default().yellow('.env.local')} represents a temporary local file. Please use another value.`);
|
|
4237
4242
|
let filePaths = [
|
|
4238
4243
|
'.env',
|
|
4239
4244
|
'.env.local',
|
|
4240
4245
|
`.env.${mode}`,
|
|
4241
4246
|
`.env.${mode}.local`
|
|
4242
4247
|
].map((filename)=>(0, external_node_path_.join)(cwd, filename)).filter(isFileSync), parsed = {};
|
|
4243
|
-
for (let envPath of filePaths)Object.assign(parsed, loadEnv_parse(
|
|
4248
|
+
for (let envPath of filePaths)Object.assign(parsed, loadEnv_parse(external_node_fs_.default.readFileSync(envPath))), src_logger.debug('loaded env file:', envPath);
|
|
4244
4249
|
parsed.NODE_ENV && (processEnv.NODE_ENV = parsed.NODE_ENV), (0, main.expand)({
|
|
4245
4250
|
parsed,
|
|
4246
4251
|
processEnv
|
|
@@ -4283,55 +4288,6 @@ function getRegExpForExts(exts) {
|
|
|
4283
4288
|
let matcher = normalizedExts.join('|');
|
|
4284
4289
|
return RegExp(1 === normalizedExts.length ? `\\.${matcher}$` : `\\.(?:${matcher})$`, 'i');
|
|
4285
4290
|
}
|
|
4286
|
-
let isUseAnalyzer = (config)=>process.env.BUNDLE_ANALYZE || config.performance?.bundleAnalyze;
|
|
4287
|
-
function pluginBundleAnalyzer() {
|
|
4288
|
-
return {
|
|
4289
|
-
name: 'rsbuild:bundle-analyzer',
|
|
4290
|
-
setup (api) {
|
|
4291
|
-
api.modifyRsbuildConfig({
|
|
4292
|
-
order: 'post',
|
|
4293
|
-
handler: (config)=>{
|
|
4294
|
-
if (isUseAnalyzer(config) || Object.values(config.environments || []).some((config)=>isUseAnalyzer(config))) return config.dev ||= {}, config.dev.writeToDisk = !0, config;
|
|
4295
|
-
}
|
|
4296
|
-
}), api.modifyBundlerChain((chain, { CHAIN_ID, environment })=>{
|
|
4297
|
-
let { config } = environment;
|
|
4298
|
-
if (!isUseAnalyzer(config)) return;
|
|
4299
|
-
let BundleAnalyzer = requireCompiledPackage('webpack-bundle-analyzer');
|
|
4300
|
-
chain.plugin(CHAIN_ID.PLUGIN.BUNDLE_ANALYZER).use(BundleAnalyzer.BundleAnalyzerPlugin, [
|
|
4301
|
-
{
|
|
4302
|
-
analyzerMode: 'static',
|
|
4303
|
-
openAnalyzer: !1,
|
|
4304
|
-
reportFilename: `report-${environment.name}.html`,
|
|
4305
|
-
...config.performance.bundleAnalyze || {}
|
|
4306
|
-
}
|
|
4307
|
-
]);
|
|
4308
|
-
});
|
|
4309
|
-
}
|
|
4310
|
-
};
|
|
4311
|
-
}
|
|
4312
|
-
async function validateWebpackCache(cacheDirectory, buildDependencies) {
|
|
4313
|
-
let configFile = (0, external_node_path_.join)(cacheDirectory, 'buildDependencies.json');
|
|
4314
|
-
if (await isFileExists(configFile)) {
|
|
4315
|
-
let rawConfigFile = await node_fs.promises.readFile(configFile, 'utf-8'), prevBuildDependencies = null;
|
|
4316
|
-
try {
|
|
4317
|
-
prevBuildDependencies = JSON.parse(rawConfigFile);
|
|
4318
|
-
} catch (e) {
|
|
4319
|
-
src_logger.debug('failed to parse the previous buildDependencies.json', e);
|
|
4320
|
-
}
|
|
4321
|
-
if (JSON.stringify(prevBuildDependencies) === JSON.stringify(buildDependencies)) return;
|
|
4322
|
-
await node_fs.promises.rm(cacheDirectory, {
|
|
4323
|
-
force: !0,
|
|
4324
|
-
recursive: !0
|
|
4325
|
-
});
|
|
4326
|
-
}
|
|
4327
|
-
try {
|
|
4328
|
-
await node_fs.promises.mkdir(cacheDirectory, {
|
|
4329
|
-
recursive: !0
|
|
4330
|
-
}), await node_fs.promises.writeFile(configFile, JSON.stringify(buildDependencies));
|
|
4331
|
-
} catch (e) {
|
|
4332
|
-
src_logger.debug('failed to write the buildDependencies.json', e);
|
|
4333
|
-
}
|
|
4334
|
-
}
|
|
4335
4291
|
function getCacheDirectory({ cacheDirectory }, context) {
|
|
4336
4292
|
return cacheDirectory ? (0, external_node_path_.isAbsolute)(cacheDirectory) ? cacheDirectory : (0, external_node_path_.join)(context.rootPath, cacheDirectory) : (0, external_node_path_.join)(context.cachePath, context.bundlerType);
|
|
4337
4293
|
}
|
|
@@ -4372,8 +4328,34 @@ let addTrailingSep = (dir)=>dir.endsWith(external_node_path_.sep) ? dir : dir +
|
|
|
4372
4328
|
...defaultOptions,
|
|
4373
4329
|
...userOptions
|
|
4374
4330
|
};
|
|
4375
|
-
}
|
|
4376
|
-
|
|
4331
|
+
};
|
|
4332
|
+
function getSwcMinimizerOptions(config, jsOptions) {
|
|
4333
|
+
let options = {};
|
|
4334
|
+
options.minimizerOptions ||= {}, options.minimizerOptions.format ||= {};
|
|
4335
|
+
let { removeConsole } = config.performance;
|
|
4336
|
+
if (!0 === removeConsole) options.minimizerOptions.compress = {
|
|
4337
|
+
drop_console: !0
|
|
4338
|
+
};
|
|
4339
|
+
else if (Array.isArray(removeConsole)) {
|
|
4340
|
+
let pureFuncs = removeConsole.map((method)=>`console.${method}`);
|
|
4341
|
+
options.minimizerOptions.compress = {
|
|
4342
|
+
pure_funcs: pureFuncs
|
|
4343
|
+
};
|
|
4344
|
+
}
|
|
4345
|
+
if (config.output.legalComments) switch(config.output.legalComments){
|
|
4346
|
+
case 'inline':
|
|
4347
|
+
options.minimizerOptions.format.comments = 'some', options.extractComments = !1;
|
|
4348
|
+
break;
|
|
4349
|
+
case 'linked':
|
|
4350
|
+
options.extractComments = !0;
|
|
4351
|
+
break;
|
|
4352
|
+
case 'none':
|
|
4353
|
+
options.minimizerOptions.format.comments = !1, options.extractComments = !1;
|
|
4354
|
+
}
|
|
4355
|
+
return (options.minimizerOptions.format.asciiOnly = 'ascii' === config.output.charset, jsOptions) ? cjs_default()(options, jsOptions) : options;
|
|
4356
|
+
}
|
|
4357
|
+
function parseMinifyOptions(config) {
|
|
4358
|
+
let isProd = 'production' === config.mode, { minify = 'node' !== config.output.target } = config.output;
|
|
4377
4359
|
if ('boolean' == typeof minify) {
|
|
4378
4360
|
let shouldMinify = minify && isProd;
|
|
4379
4361
|
return {
|
|
@@ -4387,9 +4369,10 @@ let addTrailingSep = (dir)=>dir.endsWith(external_node_path_.sep) ? dir : dir +
|
|
|
4387
4369
|
jsOptions: minify.jsOptions,
|
|
4388
4370
|
cssOptions: minify.cssOptions
|
|
4389
4371
|
};
|
|
4390
|
-
}
|
|
4372
|
+
}
|
|
4373
|
+
let src_0 = __webpack_require__("../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.2/node_modules/postcss-load-config/src/index.js");
|
|
4391
4374
|
var src_0_default = __webpack_require__.n(src_0);
|
|
4392
|
-
|
|
4375
|
+
function getLightningCSSLoaderOptions(config, targets, minify) {
|
|
4393
4376
|
let userOptions = 'object' == typeof config.tools.lightningcssLoader ? config.tools.lightningcssLoader : {}, initialOptions = {
|
|
4394
4377
|
targets,
|
|
4395
4378
|
errorRecovery: !0
|
|
@@ -4398,7 +4381,8 @@ let getLightningCSSLoaderOptions = (config, targets, minify)=>{
|
|
|
4398
4381
|
initial: initialOptions,
|
|
4399
4382
|
config: userOptions
|
|
4400
4383
|
});
|
|
4401
|
-
}
|
|
4384
|
+
}
|
|
4385
|
+
let clonePostCSSConfig = (config)=>({
|
|
4402
4386
|
...config,
|
|
4403
4387
|
plugins: config.plugins ? [
|
|
4404
4388
|
...config.plugins
|
|
@@ -4438,7 +4422,7 @@ let getPostcssLoaderOptions = async ({ config, root, postcssrcCache })=>{
|
|
|
4438
4422
|
if ('function' == typeof postcssOptions) {
|
|
4439
4423
|
let postcssOptionsWrapper = (loaderContext)=>{
|
|
4440
4424
|
let options = postcssOptions(loaderContext);
|
|
4441
|
-
if ('object' != typeof options || null === options) throw Error(`${
|
|
4425
|
+
if ('object' != typeof options || null === options) throw Error(`${picocolors_default().dim('[rsbuild:css]')} \`postcssOptions\` function must return a PostCSSOptions object, got ${picocolors_default().yellow(typeof options)}.`);
|
|
4442
4426
|
return updatePostcssOptions({
|
|
4443
4427
|
...userOptions,
|
|
4444
4428
|
...options,
|
|
@@ -4460,7 +4444,7 @@ function checkProcessEnvSecurity(define) {
|
|
|
4460
4444
|
if (!value) return;
|
|
4461
4445
|
let check = (value)=>{
|
|
4462
4446
|
let pathKey = Object.keys(value).find((key)=>'path' === key.toLowerCase() && value[key] === process.env[key]);
|
|
4463
|
-
pathKey && src_logger.warn(`${
|
|
4447
|
+
pathKey && src_logger.warn(`${picocolors_default().dim('[rsbuild:config]')} The ${picocolors_default().yellow('"source.define"')} option includes an object with the key ${picocolors_default().yellow(JSON.stringify(pathKey))} under ${picocolors_default().yellow('"process.env"')}, indicating potential exposure of all environment variables. This can lead to security risks and should be avoided.`);
|
|
4464
4448
|
};
|
|
4465
4449
|
if ('object' == typeof value) return void check(value);
|
|
4466
4450
|
if ('string' == typeof value) try {
|
|
@@ -4496,7 +4480,7 @@ function normalizeFilePath(filePath) {
|
|
|
4496
4480
|
}
|
|
4497
4481
|
async function loadPrevSnapshots(snapshotPath) {
|
|
4498
4482
|
try {
|
|
4499
|
-
let content = await
|
|
4483
|
+
let content = await external_node_fs_.default.promises.readFile(snapshotPath, 'utf-8');
|
|
4500
4484
|
return JSON.parse(content);
|
|
4501
4485
|
} catch {
|
|
4502
4486
|
return null;
|
|
@@ -4504,9 +4488,9 @@ async function loadPrevSnapshots(snapshotPath) {
|
|
|
4504
4488
|
}
|
|
4505
4489
|
async function saveSnapshots(snapshotPath, snapshots) {
|
|
4506
4490
|
try {
|
|
4507
|
-
await
|
|
4491
|
+
await external_node_fs_.default.promises.mkdir(external_node_path_.default.dirname(snapshotPath), {
|
|
4508
4492
|
recursive: !0
|
|
4509
|
-
}), await
|
|
4493
|
+
}), await external_node_fs_.default.promises.writeFile(snapshotPath, JSON.stringify(snapshots, null, 2));
|
|
4510
4494
|
} catch (err) {
|
|
4511
4495
|
src_logger.debug('Failed to save file size snapshots:', err);
|
|
4512
4496
|
}
|
|
@@ -4514,10 +4498,10 @@ async function saveSnapshots(snapshotPath, snapshots) {
|
|
|
4514
4498
|
let EXCLUDE_ASSET_REGEX = /\.(?:map|LICENSE\.txt|d\.ts)$/, excludeAsset = (asset)=>EXCLUDE_ASSET_REGEX.test(asset.name), isSignificantDiff = (diff)=>Math.abs(diff) >= 10, formatDiff = (diff)=>{
|
|
4515
4499
|
let label = `(${diff > 0 ? '+' : '-'}${calcFileSize(Math.abs(diff))})`;
|
|
4516
4500
|
return {
|
|
4517
|
-
label: (diff > 0 ?
|
|
4501
|
+
label: (diff > 0 ? picocolors_default().red : picocolors_default().green)(label),
|
|
4518
4502
|
length: label.length
|
|
4519
4503
|
};
|
|
4520
|
-
}, getAssetColor = (size)=>size > 300000 ?
|
|
4504
|
+
}, getAssetColor = (size)=>size > 300000 ? picocolors_default().red : size > 100000 ? picocolors_default().yellow : (input)=>input;
|
|
4521
4505
|
function getHeader(maxFileLength, maxSizeLength, fileHeader, showGzipHeader) {
|
|
4522
4506
|
let lengths = [
|
|
4523
4507
|
maxFileLength,
|
|
@@ -4531,7 +4515,7 @@ function getHeader(maxFileLength, maxSizeLength, fileHeader, showGzipHeader) {
|
|
|
4531
4515
|
let length = lengths[index], curLabel = cur;
|
|
4532
4516
|
return length && (curLabel = cur.length < length ? cur + ' '.repeat(length - cur.length) : cur), `${prev + curLabel} `;
|
|
4533
4517
|
}, '');
|
|
4534
|
-
return
|
|
4518
|
+
return picocolors_default().blue(headerRow);
|
|
4535
4519
|
}
|
|
4536
4520
|
let calcFileSize = (len)=>{
|
|
4537
4521
|
let val = len / 1000;
|
|
@@ -4564,7 +4548,7 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
|
|
|
4564
4548
|
isSignificantDiff(gzipDiff) && (gzipSizeLabel += ` ${formatDiff(gzipDiff).label}`);
|
|
4565
4549
|
}
|
|
4566
4550
|
}
|
|
4567
|
-
let folder = external_node_path_.default.join(relativeDistPath, external_node_path_.default.dirname(filePath)), filename = external_node_path_.default.basename(filePath), filenameLabel =
|
|
4551
|
+
let folder = external_node_path_.default.join(relativeDistPath, external_node_path_.default.dirname(filePath)), filename = external_node_path_.default.basename(filePath), filenameLabel = picocolors_default().dim(folder + external_node_path_.default.sep) + (JS_REGEX.test(filename) ? picocolors_default().cyan(filename) : filename.endsWith('.css') ? picocolors_default().yellow(filename) : filename.endsWith('.html') ? picocolors_default().green(filename) : picocolors_default().magenta(filename)), filenameLength = (folder + external_node_path_.default.sep + filename).length;
|
|
4568
4552
|
return {
|
|
4569
4553
|
filePath,
|
|
4570
4554
|
filename,
|
|
@@ -4582,7 +4566,7 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
|
|
|
4582
4566
|
try {
|
|
4583
4567
|
content = value.source();
|
|
4584
4568
|
} catch {
|
|
4585
|
-
content =
|
|
4569
|
+
content = external_node_fs_.default.readFileSync(external_node_path_.default.join(distPath, filePath));
|
|
4586
4570
|
}
|
|
4587
4571
|
return {
|
|
4588
4572
|
filePath,
|
|
@@ -4654,7 +4638,7 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
|
|
|
4654
4638
|
if (customTotal) logs.push(customTotal);
|
|
4655
4639
|
else {
|
|
4656
4640
|
let log = '';
|
|
4657
|
-
if (log += ' '.repeat(maxFileLength - totalSizeTitle.length), log +=
|
|
4641
|
+
if (log += ' '.repeat(maxFileLength - totalSizeTitle.length), log += picocolors_default().magenta(totalSizeTitle), log += ` ${totalSizeLabel}`, options.compressed) {
|
|
4658
4642
|
let colorFn = getAssetColor(totalGzipSize / assets.length);
|
|
4659
4643
|
if (log += ' '.repeat(maxSizeLength - totalSizeLabelLength), log += ` ${colorFn(calcFileSize(totalGzipSize))}`, showDiff) {
|
|
4660
4644
|
let totalGzipSizeDiff = totalGzipSize - (previousSizes[environmentName]?.totalGzipSize ?? 0);
|
|
@@ -4668,8 +4652,8 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
|
|
|
4668
4652
|
let customTotal = getCustomTotal();
|
|
4669
4653
|
if (customTotal) logs.push(customTotal);
|
|
4670
4654
|
else {
|
|
4671
|
-
let log = `${
|
|
4672
|
-
options.compressed && (log +=
|
|
4655
|
+
let log = `${picocolors_default().magenta(totalSizeTitle)} ${totalSizeLabel}`;
|
|
4656
|
+
options.compressed && (log += picocolors_default().green(` (${calcFileSize(totalGzipSize)} gzipped)`)), logs.push(log);
|
|
4673
4657
|
}
|
|
4674
4658
|
}
|
|
4675
4659
|
return logs.push(''), {
|
|
@@ -4736,14 +4720,14 @@ class RsbuildHtmlPlugin {
|
|
|
4736
4720
|
let fileContent, name = external_node_path_.default.basename(favicon);
|
|
4737
4721
|
if (compilation.assets[name]) return name;
|
|
4738
4722
|
let inputFs = compilation.inputFileSystem;
|
|
4739
|
-
if (!inputFs) return addCompilationError(compilation, `${
|
|
4723
|
+
if (!inputFs) return addCompilationError(compilation, `${picocolors_default().dim('[rsbuild:html]')} Failed to read the favicon file as ${picocolors_default().yellow('compilation.inputFileSystem')} is not available.`), null;
|
|
4740
4724
|
let inputFilename = external_node_path_.default.isAbsolute(favicon) ? favicon : external_node_path_.default.join(compilation.compiler.context, favicon);
|
|
4741
4725
|
try {
|
|
4742
4726
|
fileContent = await readFileAsync(inputFs, inputFilename);
|
|
4743
4727
|
} catch (error) {
|
|
4744
|
-
return src_logger.debug(`read favicon error: ${error}`), addCompilationError(compilation, `${
|
|
4728
|
+
return src_logger.debug(`read favicon error: ${error}`), addCompilationError(compilation, `${picocolors_default().dim('[rsbuild:html]')} Failed to read the favicon file at ${picocolors_default().yellow(inputFilename)}.`), null;
|
|
4745
4729
|
}
|
|
4746
|
-
let source = new
|
|
4730
|
+
let source = new rspack_rspack.sources.RawSource(fileContent, !1), outputFilename = external_node_path_.default.posix.join(faviconDistPath, name);
|
|
4747
4731
|
return compilation.emitAsset(outputFilename, source), outputFilename;
|
|
4748
4732
|
}, addFavicon = async ({ headTags, favicon, faviconDistPath, compilation, publicPath })=>{
|
|
4749
4733
|
let href = favicon;
|
|
@@ -4904,10 +4888,10 @@ async function getTemplate(entryName, config, rootPath) {
|
|
|
4904
4888
|
}
|
|
4905
4889
|
let absolutePath = (0, external_node_path_.isAbsolute)(templatePath) ? templatePath : external_node_path_.default.join(rootPath, templatePath);
|
|
4906
4890
|
if (!existTemplatePath.has(absolutePath)) {
|
|
4907
|
-
if (!await isFileExists(absolutePath)) throw Error(`${
|
|
4891
|
+
if (!await isFileExists(absolutePath)) throw Error(`${picocolors_default().dim('[rsbuild:html]')} Failed to resolve HTML template, check if the file exists: ${picocolors_default().yellow(absolutePath)}`);
|
|
4908
4892
|
existTemplatePath.add(absolutePath);
|
|
4909
4893
|
}
|
|
4910
|
-
let templateContent = await
|
|
4894
|
+
let templateContent = await external_node_fs_.default.promises.readFile(absolutePath, 'utf-8');
|
|
4911
4895
|
return {
|
|
4912
4896
|
templatePath: absolutePath,
|
|
4913
4897
|
templateContent
|
|
@@ -4934,21 +4918,19 @@ function getMetaTags(entryName, config, templateContent) {
|
|
|
4934
4918
|
}
|
|
4935
4919
|
function getTemplateParameters(entryName, config, assetPrefix) {
|
|
4936
4920
|
return (compilation, assets, assetTags, pluginOptions)=>{
|
|
4937
|
-
let { mountId, templateParameters } = config.html, rspackConfig = compilation.options
|
|
4938
|
-
tags: assetTags,
|
|
4939
|
-
files: assets,
|
|
4940
|
-
options: pluginOptions
|
|
4941
|
-
};
|
|
4921
|
+
let { mountId, templateParameters } = config.html, rspackConfig = compilation.options;
|
|
4942
4922
|
return reduceConfigsWithContext({
|
|
4943
4923
|
initial: {
|
|
4944
4924
|
mountId,
|
|
4945
4925
|
entryName,
|
|
4946
4926
|
assetPrefix,
|
|
4947
4927
|
compilation,
|
|
4948
|
-
htmlPlugin
|
|
4949
|
-
|
|
4950
|
-
|
|
4951
|
-
|
|
4928
|
+
htmlPlugin: {
|
|
4929
|
+
tags: assetTags,
|
|
4930
|
+
files: assets,
|
|
4931
|
+
options: pluginOptions
|
|
4932
|
+
},
|
|
4933
|
+
rspackConfig
|
|
4952
4934
|
},
|
|
4953
4935
|
config: templateParameters,
|
|
4954
4936
|
ctx: {
|
|
@@ -4982,13 +4964,14 @@ function matchTests(name, asset, tests) {
|
|
|
4982
4964
|
size: asset.size()
|
|
4983
4965
|
}) : test.exec(name));
|
|
4984
4966
|
}
|
|
4985
|
-
|
|
4967
|
+
function getInlineTests(config) {
|
|
4986
4968
|
let isProd = 'production' === config.mode, { inlineStyles, inlineScripts } = config.output, scriptTests = [], styleTests = [];
|
|
4987
4969
|
return inlineScripts && (!0 === inlineScripts ? isProd && scriptTests.push(JS_REGEX) : isRegExp(inlineScripts) || isFunction(inlineScripts) ? isProd && scriptTests.push(inlineScripts) : ('auto' === inlineScripts.enable ? isProd : inlineScripts.enable) && scriptTests.push(inlineScripts.test)), inlineStyles && (!0 === inlineStyles ? isProd && styleTests.push(CSS_REGEX) : isRegExp(inlineStyles) || isFunction(inlineStyles) ? isProd && styleTests.push(inlineStyles) : ('auto' === inlineStyles.enable ? isProd : inlineStyles.enable) && styleTests.push(inlineStyles.test)), {
|
|
4988
4970
|
scriptTests,
|
|
4989
4971
|
styleTests
|
|
4990
4972
|
};
|
|
4991
|
-
}
|
|
4973
|
+
}
|
|
4974
|
+
let normalizeUrl = (url)=>url.replace(/([^:]\/)\/+/g, '$1'), joinUrlSegments = (s1, s2)=>s1 && s2 ? addTrailingSlash(s1) + s2.replace(/^\/+/, '') : s1 || s2 || '', stripBase = (path, base)=>{
|
|
4992
4975
|
if (path === base) return '/';
|
|
4993
4976
|
let trailingSlashBase = addTrailingSlash(base);
|
|
4994
4977
|
return path.startsWith(trailingSlashBase) ? path.slice(trailingSlashBase.length - 1) : path;
|
|
@@ -5016,16 +4999,16 @@ function getURLMessages(urls, routes) {
|
|
|
5016
4999
|
if (routes.length <= 1) {
|
|
5017
5000
|
let pathname = routes.length ? routes[0].pathname : '';
|
|
5018
5001
|
return urls.map(({ label, url })=>{
|
|
5019
|
-
let normalizedPathname = normalizeUrl(`${url}${pathname}`), prefix = `➜ ${
|
|
5020
|
-
return ` ${prefix}${
|
|
5002
|
+
let normalizedPathname = normalizeUrl(`${url}${pathname}`), prefix = `➜ ${picocolors_default().dim(label.padEnd(10))}`;
|
|
5003
|
+
return ` ${prefix}${picocolors_default().cyan(normalizedPathname)}\n`;
|
|
5021
5004
|
}).join('');
|
|
5022
5005
|
}
|
|
5023
5006
|
let message = '', prevLabel = '', maxNameLength = Math.max(...routes.map((r)=>r.entryName.length));
|
|
5024
5007
|
return urls.forEach(({ label, url }, index)=>{
|
|
5025
|
-
for (let { entryName, pathname } of (prevLabel !== label && (index > 0 && (message += '\n'), message += ` ➜ ${label}\n`, prevLabel = label), routes))message += ` ${
|
|
5008
|
+
for (let { entryName, pathname } of (prevLabel !== label && (index > 0 && (message += '\n'), message += ` ➜ ${label}\n`, prevLabel = label), routes))message += ` ${picocolors_default().dim('-')} ${picocolors_default().dim(entryName.padEnd(maxNameLength + 4))}${picocolors_default().cyan(normalizeUrl(`${url}${pathname}`))}\n`;
|
|
5026
5009
|
}), message;
|
|
5027
5010
|
}
|
|
5028
|
-
function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls, trailingLineBreak = !0 }) {
|
|
5011
|
+
function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls, trailingLineBreak = !0, originalConfig }) {
|
|
5029
5012
|
if (!1 === printUrls) return null;
|
|
5030
5013
|
let urls = originalUrls, useCustomUrl = isFunction(printUrls);
|
|
5031
5014
|
if (useCustomUrl) {
|
|
@@ -5036,7 +5019,7 @@ function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls
|
|
|
5036
5019
|
protocol
|
|
5037
5020
|
});
|
|
5038
5021
|
if (!newUrls) return null;
|
|
5039
|
-
if (!Array.isArray(newUrls)) throw Error(`${
|
|
5022
|
+
if (!Array.isArray(newUrls)) throw Error(`${picocolors_default().dim('[rsbuild:config]')} "server.printUrls" must return an array, but got ${typeof newUrls}.`);
|
|
5040
5023
|
urls = newUrls.map((u)=>{
|
|
5041
5024
|
let { url, label } = 'string' == typeof u ? {
|
|
5042
5025
|
url: u
|
|
@@ -5049,7 +5032,7 @@ function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls
|
|
|
5049
5032
|
}
|
|
5050
5033
|
if (0 === urls.length || 0 === routes.length && !useCustomUrl) return null;
|
|
5051
5034
|
let message = getURLMessages(urls, routes);
|
|
5052
|
-
return !trailingLineBreak && message.endsWith('\n') && (message = message.slice(0, -1)), src_logger.log(message), message;
|
|
5035
|
+
return originalConfig && originalConfig.server?.host === void 0 && (message += ` ➜ ${picocolors_default().dim('Network:')} ${picocolors_default().dim('use')} ${picocolors_default().bold('--host')} ${picocolors_default().dim('to expose')}\n`), !trailingLineBreak && message.endsWith('\n') && (message = message.slice(0, -1)), src_logger.log(message), message;
|
|
5053
5036
|
}
|
|
5054
5037
|
let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
|
|
5055
5038
|
'string' == typeof port && (port = Number.parseInt(port, 10)), strictPort && (tryLimits = 1);
|
|
@@ -5068,15 +5051,15 @@ let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
|
|
|
5068
5051
|
if ('EADDRINUSE' !== e.code) throw e;
|
|
5069
5052
|
port++, attempts++;
|
|
5070
5053
|
}
|
|
5071
|
-
if (!found) throw Error(`${
|
|
5072
|
-
if (port !== original && strictPort) throw Error(`${
|
|
5054
|
+
if (!found) throw Error(`${picocolors_default().dim('[rsbuild:server]')} Failed to find an available port after ${tryLimits + 1} attempts, starting from ${picocolors_default().yellow(original)}.`);
|
|
5055
|
+
if (port !== original && strictPort) throw Error(`${picocolors_default().dim('[rsbuild:server]')} Port ${picocolors_default().yellow(original)} is occupied, please choose another one.`);
|
|
5073
5056
|
return port;
|
|
5074
5057
|
}, getServerConfig = async ({ config })=>{
|
|
5075
5058
|
let { host, port: originalPort, strictPort } = config.server, port = await getPort({
|
|
5076
5059
|
host,
|
|
5077
5060
|
port: originalPort,
|
|
5078
5061
|
strictPort
|
|
5079
|
-
}), https = !!config.server.https, portTip = port !== originalPort ? `port ${originalPort} is in use, ${
|
|
5062
|
+
}), https = !!config.server.https, portTip = port !== originalPort ? `port ${originalPort} is in use, ${picocolors_default().yellow(`using port ${port}.`)}` : void 0;
|
|
5080
5063
|
return {
|
|
5081
5064
|
port,
|
|
5082
5065
|
host,
|
|
@@ -5084,12 +5067,12 @@ let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
|
|
|
5084
5067
|
portTip
|
|
5085
5068
|
};
|
|
5086
5069
|
}, isLoopbackHost = (host)=>new Set([
|
|
5087
|
-
|
|
5070
|
+
LOCALHOST,
|
|
5088
5071
|
'127.0.0.1',
|
|
5089
5072
|
'::1',
|
|
5090
5073
|
'0000:0000:0000:0000:0000:0000:0000:0001'
|
|
5091
5074
|
]).has(host), getHostInUrl = async (host)=>{
|
|
5092
|
-
if (host ===
|
|
5075
|
+
if (host === ALL_INTERFACES_IPV4 || host === LOCALHOST) return LOCALHOST;
|
|
5093
5076
|
let { isIPv6 } = await import("node:net");
|
|
5094
5077
|
return isIPv6(host) ? '::' === host ? '[::1]' : `[${host}]` : host;
|
|
5095
5078
|
}, concatUrl = ({ host, port, protocol })=>`${protocol}://${host}:${port}`, LOCAL_LABEL = 'Local: ', NETWORK_LABEL = 'Network: ', getUrlLabel = (url)=>{
|
|
@@ -5100,7 +5083,7 @@ let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
|
|
|
5100
5083
|
return NETWORK_LABEL;
|
|
5101
5084
|
}
|
|
5102
5085
|
}, getAddressUrls = async ({ protocol = 'http', port, host })=>{
|
|
5103
|
-
if (host && host !==
|
|
5086
|
+
if (host && host !== ALL_INTERFACES_IPV4) {
|
|
5104
5087
|
let url = concatUrl({
|
|
5105
5088
|
port,
|
|
5106
5089
|
host: await getHostInUrl(host),
|
|
@@ -5126,7 +5109,7 @@ let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
|
|
|
5126
5109
|
addressUrls.push({
|
|
5127
5110
|
label: LOCAL_LABEL,
|
|
5128
5111
|
url: concatUrl({
|
|
5129
|
-
host:
|
|
5112
|
+
host: LOCALHOST,
|
|
5130
5113
|
port,
|
|
5131
5114
|
protocol
|
|
5132
5115
|
})
|
|
@@ -5186,7 +5169,7 @@ async function openBrowser(url) {
|
|
|
5186
5169
|
src_logger.debug("failed to open start URL with apple script."), src_logger.debug(err);
|
|
5187
5170
|
}
|
|
5188
5171
|
}
|
|
5189
|
-
let { apps, default: baseOpen } = await import("./
|
|
5172
|
+
let { apps, default: baseOpen } = await import("./open.js").then((mod)=>({
|
|
5190
5173
|
apps: mod.open_apps,
|
|
5191
5174
|
default: mod.node_modules_open
|
|
5192
5175
|
}));
|
|
@@ -5206,11 +5189,11 @@ async function openBrowser(url) {
|
|
|
5206
5189
|
}
|
|
5207
5190
|
let openedURLs = [], replacePortPlaceholder = (url, port)=>url.replace(/<port>/g, String(port));
|
|
5208
5191
|
function resolveUrl(str, base) {
|
|
5209
|
-
if (canParse(str)) return str;
|
|
5192
|
+
if (external_node_url_.URL.canParse(str)) return str;
|
|
5210
5193
|
try {
|
|
5211
|
-
return new URL(str, base).href;
|
|
5194
|
+
return new external_node_url_.URL(str, base).href;
|
|
5212
5195
|
} catch {
|
|
5213
|
-
throw Error(`${
|
|
5196
|
+
throw Error(`${picocolors_default().dim('[rsbuild:open]')} Invalid input: ${picocolors_default().yellow(str)} is not a valid URL or pathname`);
|
|
5214
5197
|
}
|
|
5215
5198
|
}
|
|
5216
5199
|
async function open_open({ https, port, routes, config, clearCache }) {
|
|
@@ -5273,7 +5256,7 @@ function pluginModuleFederation() {
|
|
|
5273
5256
|
return {
|
|
5274
5257
|
name: 'rsbuild:module-federation',
|
|
5275
5258
|
setup (api) {
|
|
5276
|
-
|
|
5259
|
+
api.modifyRsbuildConfig((config)=>{
|
|
5277
5260
|
let { moduleFederation } = config;
|
|
5278
5261
|
if (moduleFederation?.options && moduleFederation.options.exposes) {
|
|
5279
5262
|
let userConfig = api.getRsbuildConfig('original');
|
|
@@ -5294,7 +5277,7 @@ function pluginModuleFederation() {
|
|
|
5294
5277
|
chain.plugin(CHAIN_ID.PLUGIN.MODULE_FEDERATION).use(rspack_rspack.container.ModuleFederationPlugin, [
|
|
5295
5278
|
options
|
|
5296
5279
|
]), options.name && !chain.output.get('uniqueName') && chain.output.set('uniqueName', options.name);
|
|
5297
|
-
})
|
|
5280
|
+
});
|
|
5298
5281
|
}
|
|
5299
5282
|
};
|
|
5300
5283
|
}
|
|
@@ -5303,8 +5286,8 @@ function getPublicPath({ isDev, config, context }) {
|
|
|
5303
5286
|
if (isDev) {
|
|
5304
5287
|
if ('string' == typeof dev.assetPrefix) publicPath = dev.assetPrefix;
|
|
5305
5288
|
else if (dev.assetPrefix) {
|
|
5306
|
-
let protocol = context.devServer?.https ? 'https' : 'http', hostname = context.devServer?.hostname ||
|
|
5307
|
-
publicPath = hostname ===
|
|
5289
|
+
let protocol = context.devServer?.https ? 'https' : 'http', hostname = context.devServer?.hostname || LOCALHOST;
|
|
5290
|
+
publicPath = hostname === ALL_INTERFACES_IPV4 ? `${protocol}://localhost:<port>/` : `${protocol}://${hostname}:<port>/`, server.base && '/' !== server.base && (publicPath = urlJoin(publicPath, server.base));
|
|
5308
5291
|
}
|
|
5309
5292
|
} else 'string' == typeof output.assetPrefix && (publicPath = output.assetPrefix);
|
|
5310
5293
|
let defaultPort = server.port ?? 3000;
|
|
@@ -5316,13 +5299,10 @@ function applyAlias({ chain, config, rootPath }) {
|
|
|
5316
5299
|
initial: {},
|
|
5317
5300
|
config: config.resolve.alias
|
|
5318
5301
|
});
|
|
5319
|
-
if (config.
|
|
5320
|
-
initial: mergedAlias,
|
|
5321
|
-
config: config.source.alias
|
|
5322
|
-
})), config.resolve.dedupe) for (let pkgName of config.resolve.dedupe){
|
|
5302
|
+
if (config.resolve.dedupe) for (let pkgName of config.resolve.dedupe){
|
|
5323
5303
|
let pkgPath;
|
|
5324
5304
|
if (mergedAlias[pkgName]) {
|
|
5325
|
-
src_logger.debug(`${
|
|
5305
|
+
src_logger.debug(`${picocolors_default().dim('[rsbuild:resolve]')} The package ${picocolors_default().yellow(pkgName)} is already in the alias config, dedupe option for ${picocolors_default().yellow(pkgName)} will be ignored.`);
|
|
5326
5306
|
continue;
|
|
5327
5307
|
}
|
|
5328
5308
|
try {
|
|
@@ -5344,7 +5324,7 @@ function applyAlias({ chain, config, rootPath }) {
|
|
|
5344
5324
|
].join(external_node_path_.sep);
|
|
5345
5325
|
for(; !pkgPath.endsWith(trailing) && pkgPath.includes('node_modules');)pkgPath = (0, external_node_path_.dirname)(pkgPath);
|
|
5346
5326
|
} catch {
|
|
5347
|
-
src_logger.debug(`${
|
|
5327
|
+
src_logger.debug(`${picocolors_default().dim('[rsbuild:resolve]')} The package ${picocolors_default().yellow(pkgName)} is not resolved in the project, dedupe option for ${picocolors_default().yellow(pkgName)} will be ignored.`);
|
|
5348
5328
|
continue;
|
|
5349
5329
|
}
|
|
5350
5330
|
mergedAlias[pkgName] = pkgPath;
|
|
@@ -5469,7 +5449,7 @@ function resolveLayer(value) {
|
|
|
5469
5449
|
}
|
|
5470
5450
|
async function ensureFileDir(outputFilePath) {
|
|
5471
5451
|
let dir = external_node_path_.default.dirname(outputFilePath);
|
|
5472
|
-
await
|
|
5452
|
+
await external_node_fs_.default.promises.mkdir(dir, {
|
|
5473
5453
|
recursive: !0
|
|
5474
5454
|
});
|
|
5475
5455
|
}
|
|
@@ -5632,10 +5612,21 @@ function getDefaultSwcConfig({ browserslist, cacheRoot, config, isProd }) {
|
|
|
5632
5612
|
}
|
|
5633
5613
|
};
|
|
5634
5614
|
}
|
|
5635
|
-
function applyCoreJs(swcConfig, polyfillMode) {
|
|
5636
|
-
let coreJsPath =
|
|
5615
|
+
function applyCoreJs(swcConfig, polyfillMode, rootPath) {
|
|
5616
|
+
let coreJsPath = ((rootPath)=>{
|
|
5617
|
+
try {
|
|
5618
|
+
return swc_require.resolve('core-js/package.json', {
|
|
5619
|
+
paths: [
|
|
5620
|
+
rootPath,
|
|
5621
|
+
import.meta.dirname
|
|
5622
|
+
]
|
|
5623
|
+
});
|
|
5624
|
+
} catch {
|
|
5625
|
+
throw Error(`${picocolors_default().dim('[rsbuild:polyfill]')} Failed to resolve ${picocolors_default().yellow('core-js')} dependency. Install ${picocolors_default().yellow('core-js >= 3.0.0')} to use polyfills.`);
|
|
5626
|
+
}
|
|
5627
|
+
})(rootPath), version = ((corejsPkgPath)=>{
|
|
5637
5628
|
try {
|
|
5638
|
-
let rawJson =
|
|
5629
|
+
let rawJson = external_node_fs_.default.readFileSync(corejsPkgPath, 'utf-8'), { version } = JSON.parse(rawJson), [major, minor] = version.split('.');
|
|
5639
5630
|
return `${major}.${minor}`;
|
|
5640
5631
|
} catch {
|
|
5641
5632
|
return '3';
|
|
@@ -5663,28 +5654,28 @@ function applySwcDecoratorConfig(swcConfig, config) {
|
|
|
5663
5654
|
swcConfig.jsc.transform.legacyDecorator = !1, swcConfig.jsc.transform.decoratorVersion = '2022-03';
|
|
5664
5655
|
break;
|
|
5665
5656
|
default:
|
|
5666
|
-
throw Error(`${
|
|
5657
|
+
throw Error(`${picocolors_default().dim('[rsbuild:swc]')} Unknown decorators version: ${picocolors_default().yellow(version)}`);
|
|
5667
5658
|
}
|
|
5668
5659
|
}
|
|
5669
5660
|
async function getLocalhostResolvedAddress() {
|
|
5670
5661
|
let { promises: dns } = await import("node:dns"), [defaultLookup, explicitLookup] = await Promise.all([
|
|
5671
|
-
dns.lookup(
|
|
5672
|
-
dns.lookup(
|
|
5662
|
+
dns.lookup(LOCALHOST),
|
|
5663
|
+
dns.lookup(LOCALHOST, {
|
|
5673
5664
|
verbatim: !0
|
|
5674
5665
|
})
|
|
5675
5666
|
]);
|
|
5676
5667
|
return defaultLookup.family === explicitLookup.family && defaultLookup.address === explicitLookup.address ? void 0 : defaultLookup.address;
|
|
5677
5668
|
}
|
|
5678
|
-
async function resolveHostname(host =
|
|
5679
|
-
if (
|
|
5669
|
+
async function resolveHostname(host = LOCALHOST) {
|
|
5670
|
+
if (host === LOCALHOST) {
|
|
5680
5671
|
let resolvedAddress = await getLocalhostResolvedAddress();
|
|
5681
5672
|
if (resolvedAddress) return resolvedAddress;
|
|
5682
5673
|
}
|
|
5683
5674
|
return void 0 === host || new Set([
|
|
5684
|
-
|
|
5675
|
+
ALL_INTERFACES_IPV4,
|
|
5685
5676
|
'::',
|
|
5686
5677
|
'0000:0000:0000:0000:0000:0000:0000:0000'
|
|
5687
|
-
]).has(host) ?
|
|
5678
|
+
]).has(host) ? LOCALHOST : host;
|
|
5688
5679
|
}
|
|
5689
5680
|
let UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
|
|
5690
5681
|
async function getFileFromUrl(url, outputFileSystem, context) {
|
|
@@ -5770,8 +5761,10 @@ function createReadStreamOrReadFileSync(filename, outputFileSystem, start, end)
|
|
|
5770
5761
|
byteLength: 0 === end ? 0 : end - start + 1
|
|
5771
5762
|
};
|
|
5772
5763
|
}
|
|
5773
|
-
function getContentType(str) {
|
|
5774
|
-
let { lookup } =
|
|
5764
|
+
async function getContentType(str) {
|
|
5765
|
+
let { lookup } = await import("./710.js").then((mod)=>({
|
|
5766
|
+
lookup: mod.lookup
|
|
5767
|
+
})), mime = lookup(str);
|
|
5775
5768
|
return !!mime && ((mime.startsWith('text/') || 'application/json' === mime || 'application/manifest+json' === mime) && (mime += '; charset=utf-8'), mime);
|
|
5776
5769
|
}
|
|
5777
5770
|
let BYTES_RANGE_REGEXP = /^ *bytes/i;
|
|
@@ -5789,7 +5782,7 @@ function destroyStream(stream, suppress) {
|
|
|
5789
5782
|
}), 'function' == typeof stream.addListener && suppress && (stream.removeAllListeners('error'), stream.addListener('error', ()=>{}));
|
|
5790
5783
|
}
|
|
5791
5784
|
let parseRangeHeaders = async (value)=>{
|
|
5792
|
-
let { default: rangeParser } = await import("./
|
|
5785
|
+
let { default: rangeParser } = await import("./range-parser.js").then(__webpack_require__.t.bind(__webpack_require__, "../../node_modules/.pnpm/range-parser@1.2.1/node_modules/range-parser/index.js", 23)), [len, rangeHeader] = value.split('|');
|
|
5793
5786
|
return rangeParser(Number(len), rangeHeader, {
|
|
5794
5787
|
combine: !0
|
|
5795
5788
|
});
|
|
@@ -5916,7 +5909,7 @@ function createMiddleware(context, ready, outputFileSystem) {
|
|
|
5916
5909
|
}
|
|
5917
5910
|
let { fsStats, filename } = resolved, { size } = fsStats, len = size, offset = 0;
|
|
5918
5911
|
if (!res.getHeader('Content-Type')) {
|
|
5919
|
-
let contentType = getContentType(filename);
|
|
5912
|
+
let contentType = await getContentType(filename);
|
|
5920
5913
|
contentType && res.setHeader('Content-Type', contentType);
|
|
5921
5914
|
}
|
|
5922
5915
|
res.getHeader('Accept-Ranges') || res.setHeader('Accept-Ranges', 'bytes');
|
|
@@ -5972,13 +5965,13 @@ function createMiddleware(context, ready, outputFileSystem) {
|
|
|
5972
5965
|
});
|
|
5973
5966
|
};
|
|
5974
5967
|
}
|
|
5975
|
-
function setupOutputFileSystem(writeToDisk, compilers) {
|
|
5968
|
+
async function setupOutputFileSystem(writeToDisk, compilers) {
|
|
5976
5969
|
if (!0 !== writeToDisk) {
|
|
5977
|
-
let { createFsFromVolume, Volume } =
|
|
5970
|
+
let { createFsFromVolume, Volume } = await import("./memfs.js").then(__webpack_require__.t.bind(__webpack_require__, "../../node_modules/.pnpm/memfs@4.51.1/node_modules/memfs/lib/index.js", 23)), outputFileSystem = createFsFromVolume(new Volume());
|
|
5978
5971
|
for (let compiler of compilers)compiler.outputFileSystem = outputFileSystem;
|
|
5979
5972
|
}
|
|
5980
5973
|
let compiler = compilers.find((compiler)=>!!compiler.outputFileSystem);
|
|
5981
|
-
return compiler?.outputFileSystem ??
|
|
5974
|
+
return compiler?.outputFileSystem ?? external_node_fs_.default;
|
|
5982
5975
|
}
|
|
5983
5976
|
function setupWriteToDisk(compilers, writeToDisk) {
|
|
5984
5977
|
for (let compiler of compilers)compiler.hooks.emit.tap('DevMiddleware', ()=>{
|
|
@@ -5986,14 +5979,14 @@ function setupWriteToDisk(compilers, writeToDisk) {
|
|
|
5986
5979
|
let { targetPath, content, compilation } = info;
|
|
5987
5980
|
if (!(!writeToDisk || 'function' != typeof writeToDisk || writeToDisk(targetPath, compilation.name))) return void callback();
|
|
5988
5981
|
let dir = external_node_path_.default.dirname(targetPath), name = compiler.options.name ? `Child "${compiler.options.name}": ` : '';
|
|
5989
|
-
|
|
5982
|
+
external_node_fs_.default.mkdir(dir, {
|
|
5990
5983
|
recursive: !0
|
|
5991
5984
|
}, (mkdirError)=>{
|
|
5992
5985
|
if (mkdirError) {
|
|
5993
5986
|
src_logger.error(`[rsbuild:middleware] ${name}Unable to write "${dir}" directory to disk:\n${mkdirError.message}`), callback(mkdirError);
|
|
5994
5987
|
return;
|
|
5995
5988
|
}
|
|
5996
|
-
|
|
5989
|
+
external_node_fs_.default.writeFile(targetPath, content, (writeFileError)=>{
|
|
5997
5990
|
if (writeFileError) {
|
|
5998
5991
|
src_logger.error(`[rsbuild:middleware] ${name}Unable to write "${targetPath}" asset to disk:\n${writeFileError.message}`), callback(writeFileError);
|
|
5999
5992
|
return;
|
|
@@ -6026,7 +6019,7 @@ init(
|
|
|
6026
6019
|
${JSON.stringify(config.dev.client.logLevel)}
|
|
6027
6020
|
)
|
|
6028
6021
|
`;
|
|
6029
|
-
new
|
|
6022
|
+
new rspack_rspack.EntryPlugin(compiler.context, createVirtualModule(hmrEntry), {
|
|
6030
6023
|
name: void 0
|
|
6031
6024
|
}).apply(compiler);
|
|
6032
6025
|
}
|
|
@@ -6102,7 +6095,7 @@ let assets_middleware_assetsMiddleware = async ({ config, compiler, context, soc
|
|
|
6102
6095
|
writeToDisk && setupWriteToDisk(compilers, writeToDisk);
|
|
6103
6096
|
let instance = createMiddleware(context, (callback)=>{
|
|
6104
6097
|
'done' === context.buildState.status ? callback() : callbacks.push(callback);
|
|
6105
|
-
}, setupOutputFileSystem(writeToDisk, compilers));
|
|
6098
|
+
}, await setupOutputFileSystem(writeToDisk, compilers));
|
|
6106
6099
|
return instance.watch = ()=>{
|
|
6107
6100
|
if (compiler.watching) watching = compiler.watching;
|
|
6108
6101
|
else {
|
|
@@ -6186,7 +6179,10 @@ function parseNode(line) {
|
|
|
6186
6179
|
let isValidMethodName = (methodName)=>'<unknown>' !== methodName && !/[\\/]/.test(methodName), parseFrame = async (frame, fs, context, cachedTraceMap)=>{
|
|
6187
6180
|
let { file, column, lineNumber } = frame, sourceMapInfo = await getFileFromUrl(`${file}.map`, fs, context);
|
|
6188
6181
|
if (!sourceMapInfo || 'errorCode' in sourceMapInfo) return;
|
|
6189
|
-
let { TraceMap, originalPositionFor } =
|
|
6182
|
+
let { TraceMap, originalPositionFor } = await import("./31.js").then((mod)=>({
|
|
6183
|
+
TraceMap: mod.TraceMap,
|
|
6184
|
+
originalPositionFor: mod.originalPositionFor
|
|
6185
|
+
})), sourceMapPath = sourceMapInfo.filename;
|
|
6190
6186
|
try {
|
|
6191
6187
|
let tracer = cachedTraceMap.get(sourceMapPath);
|
|
6192
6188
|
if (!tracer) {
|
|
@@ -6245,14 +6241,14 @@ let isValidMethodName = (methodName)=>'<unknown>' !== methodName && !/[\\/]/.tes
|
|
|
6245
6241
|
return result;
|
|
6246
6242
|
}, formatBrowserErrorLog = async (message, context, fs, stackTrace, stackFrames, cachedTraceMap)=>{
|
|
6247
6243
|
var log;
|
|
6248
|
-
let log1 =
|
|
6244
|
+
let log1 = picocolors_default().red(message);
|
|
6249
6245
|
if (stackFrames?.length) switch(stackTrace){
|
|
6250
6246
|
case 'summary':
|
|
6251
6247
|
{
|
|
6252
6248
|
let resolved = await resolveOriginalLocation(stackFrames, fs, context, cachedTraceMap);
|
|
6253
6249
|
if (!resolved) break;
|
|
6254
6250
|
let { frame, location } = resolved, { methodName } = frame, suffix = '';
|
|
6255
|
-
isValidMethodName(methodName) && (suffix += ` at ${methodName}`), location && (suffix += ` (${location})`), log1 += suffix ?
|
|
6251
|
+
isValidMethodName(methodName) && (suffix += ` at ${methodName}`), location && (suffix += ` (${location})`), log1 += suffix ? picocolors_default().dim(suffix) : '';
|
|
6256
6252
|
break;
|
|
6257
6253
|
}
|
|
6258
6254
|
case 'full':
|
|
@@ -6261,7 +6257,7 @@ let isValidMethodName = (methodName)=>'<unknown>' !== methodName && !/[\\/]/.tes
|
|
|
6261
6257
|
fullStack && (log1 += fullStack);
|
|
6262
6258
|
}
|
|
6263
6259
|
}
|
|
6264
|
-
return (log = log1).includes('ReferenceError: process is not defined') ? `${log}\n${
|
|
6260
|
+
return (log = log1).includes('ReferenceError: process is not defined') ? `${log}\n${picocolors_default().yellow(` - \`process\` is a Node.js global and not available in browsers.
|
|
6265
6261
|
- To access \`process.env.*\`, define them in a \`.env\` file with the \`PUBLIC_\` prefix.
|
|
6266
6262
|
- Or configure them via \`source.define\`.
|
|
6267
6263
|
- Alternatively, install \`@rsbuild/plugin-node-polyfill\` to polyfill Node.js globals.`)}` : log;
|
|
@@ -6429,9 +6425,9 @@ class SocketServer {
|
|
|
6429
6425
|
let payload = JSON.parse('string' == typeof data ? data : data.toString()), { context } = this, config = context.normalizedConfig;
|
|
6430
6426
|
if (!config) return;
|
|
6431
6427
|
let { browserLogs, client } = config.dev;
|
|
6432
|
-
if ('client-error' === payload.type &&
|
|
6428
|
+
if ('client-error' === payload.type && !context.buildState.hasErrors && browserLogs) {
|
|
6433
6429
|
let stackTrace = isObject(browserLogs) && browserLogs.stackTrace || DEFAULT_STACK_TRACE, outputFs = this.getOutputFileSystem(), stackFrames = payload.stack ? stack_trace_parser_esm_parse(payload.stack) : null, cachedTraceMap = new Map(), log = await formatBrowserErrorLog(payload.message, context, outputFs, stackTrace, stackFrames, cachedTraceMap);
|
|
6434
|
-
if (this.reportedBrowserLogs.has(log) || (this.reportedBrowserLogs.add(log), src_logger.error(`${
|
|
6430
|
+
if (this.reportedBrowserLogs.has(log) || (this.reportedBrowserLogs.add(log), src_logger.error(`${picocolors_default().cyan('[browser]')} ${log}`)), 'object' == typeof client.overlay && client.overlay.runtime) {
|
|
6435
6431
|
let resolvedLog = 'full' === stackTrace ? log : await formatBrowserErrorLog(payload.message, context, outputFs, 'full', stackFrames, cachedTraceMap);
|
|
6436
6432
|
this.sockWrite({
|
|
6437
6433
|
type: 'resolved-client-error',
|
|
@@ -6506,12 +6502,12 @@ class BuildManager {
|
|
|
6506
6502
|
resolvedPort;
|
|
6507
6503
|
context;
|
|
6508
6504
|
constructor({ config, context, compiler, resolvedPort }){
|
|
6509
|
-
this.config = config, this.context = context, this.compiler = compiler, this.resolvedPort = resolvedPort, this.outputFileSystem =
|
|
6505
|
+
this.config = config, this.context = context, this.compiler = compiler, this.resolvedPort = resolvedPort, this.outputFileSystem = external_node_fs_.default, this.socketServer = new SocketServer(context, config.dev, ()=>this.outputFileSystem), this.context.socketServer = this.socketServer;
|
|
6510
6506
|
}
|
|
6511
6507
|
async init() {
|
|
6512
6508
|
await this.setupCompilationMiddleware(), this.socketServer.prepare();
|
|
6513
6509
|
let { compiler } = this;
|
|
6514
|
-
this.outputFileSystem = (compiler_isMultiCompiler(compiler) ? compiler.compilers[0].outputFileSystem : compiler.outputFileSystem) ||
|
|
6510
|
+
this.outputFileSystem = (compiler_isMultiCompiler(compiler) ? compiler.compilers[0].outputFileSystem : compiler.outputFileSystem) || external_node_fs_.default;
|
|
6515
6511
|
}
|
|
6516
6512
|
watch() {
|
|
6517
6513
|
this.assetsMiddleware.watch();
|
|
@@ -6527,7 +6523,7 @@ class BuildManager {
|
|
|
6527
6523
|
});
|
|
6528
6524
|
});
|
|
6529
6525
|
}
|
|
6530
|
-
readFileSync = (fileName)=>'readFileSync' in this.outputFileSystem ? this.outputFileSystem.readFileSync(fileName, 'utf-8') :
|
|
6526
|
+
readFileSync = (fileName)=>'readFileSync' in this.outputFileSystem ? this.outputFileSystem.readFileSync(fileName, 'utf-8') : external_node_fs_.default.readFileSync(fileName, 'utf-8');
|
|
6531
6527
|
async setupCompilationMiddleware() {
|
|
6532
6528
|
let { config, context } = this, middleware = await assets_middleware_assetsMiddleware({
|
|
6533
6529
|
config,
|
|
@@ -6544,19 +6540,19 @@ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls,
|
|
|
6544
6540
|
let shortcuts = [
|
|
6545
6541
|
{
|
|
6546
6542
|
key: 'c',
|
|
6547
|
-
description: `${
|
|
6543
|
+
description: `${picocolors_default().bold('c + enter')} ${picocolors_default().dim('clear console')}`,
|
|
6548
6544
|
action: ()=>{
|
|
6549
6545
|
console.clear();
|
|
6550
6546
|
}
|
|
6551
6547
|
},
|
|
6552
6548
|
{
|
|
6553
6549
|
key: 'o',
|
|
6554
|
-
description: `${
|
|
6550
|
+
description: `${picocolors_default().bold('o + enter')} ${picocolors_default().dim('open in browser')}`,
|
|
6555
6551
|
action: openPage
|
|
6556
6552
|
},
|
|
6557
6553
|
{
|
|
6558
6554
|
key: 'q',
|
|
6559
|
-
description: `${
|
|
6555
|
+
description: `${picocolors_default().bold('q + enter')} ${picocolors_default().dim('quit process')}`,
|
|
6560
6556
|
action: async ()=>{
|
|
6561
6557
|
try {
|
|
6562
6558
|
await closeServer();
|
|
@@ -6567,23 +6563,23 @@ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls,
|
|
|
6567
6563
|
},
|
|
6568
6564
|
restartServer ? {
|
|
6569
6565
|
key: 'r',
|
|
6570
|
-
description: `${
|
|
6566
|
+
description: `${picocolors_default().bold('r + enter')} ${picocolors_default().dim('restart server')}`,
|
|
6571
6567
|
action: restartServer
|
|
6572
6568
|
} : null,
|
|
6573
6569
|
{
|
|
6574
6570
|
key: 'u',
|
|
6575
|
-
description: `${
|
|
6571
|
+
description: `${picocolors_default().bold('u + enter')} ${picocolors_default().dim('show urls')}`,
|
|
6576
6572
|
action: printUrls
|
|
6577
6573
|
}
|
|
6578
6574
|
].filter(Boolean);
|
|
6579
|
-
if (customShortcuts && !Array.isArray(shortcuts = customShortcuts(shortcuts))) throw Error(`${
|
|
6580
|
-
help && src_logger.log(!0 === help ? ` ➜ ${
|
|
6575
|
+
if (customShortcuts && !Array.isArray(shortcuts = customShortcuts(shortcuts))) throw Error(`${picocolors_default().dim('[rsbuild:config]')} ${picocolors_default().yellow('dev.cliShortcuts')} option must return an array of shortcuts.`);
|
|
6576
|
+
help && src_logger.log(!0 === help ? ` ➜ ${picocolors_default().dim('press')} ${picocolors_default().bold('h + enter')} ${picocolors_default().dim('to show shortcuts')}\n` : ` ➜ ${help}\n`);
|
|
6581
6577
|
let { createInterface } = await import("node:readline"), rl = createInterface({
|
|
6582
6578
|
input: process.stdin
|
|
6583
6579
|
});
|
|
6584
6580
|
return rl.on('line', (input)=>{
|
|
6585
6581
|
if ('h' === input) {
|
|
6586
|
-
let message = `\n ${
|
|
6582
|
+
let message = `\n ${picocolors_default().bold(picocolors_default().blue('Shortcuts:'))}\n`;
|
|
6587
6583
|
for (let shortcut of shortcuts)message += ` ${shortcut.description}\n`;
|
|
6588
6584
|
src_logger.log(message);
|
|
6589
6585
|
}
|
|
@@ -6592,7 +6588,9 @@ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls,
|
|
|
6592
6588
|
rl.close();
|
|
6593
6589
|
};
|
|
6594
6590
|
}
|
|
6595
|
-
let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xml/i
|
|
6591
|
+
let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xml/i;
|
|
6592
|
+
function gzipMiddleware_gzipMiddleware({ filter, level = node_zlib.constants.Z_BEST_SPEED } = {}) {
|
|
6593
|
+
return function gzipMiddleware(req, res, next) {
|
|
6596
6594
|
let gzip, writeHeadStatus, writeHeadMessage;
|
|
6597
6595
|
if (filter && !filter(req, res)) return void next();
|
|
6598
6596
|
let accept = req.headers['accept-encoding'], encoding = 'string' == typeof accept && ENCODING_REGEX.test(accept);
|
|
@@ -6626,6 +6624,7 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
|
|
|
6626
6624
|
listener
|
|
6627
6625
|
]), res), next();
|
|
6628
6626
|
};
|
|
6627
|
+
}
|
|
6629
6628
|
function historyApiFallback_historyApiFallbackMiddleware(options = {}) {
|
|
6630
6629
|
return function historyApiFallbackMiddleware(req, _res, next) {
|
|
6631
6630
|
let rewriteTarget, { headers } = req;
|
|
@@ -6673,7 +6672,7 @@ function historyApiFallback_historyApiFallbackMiddleware(options = {}) {
|
|
|
6673
6672
|
};
|
|
6674
6673
|
}
|
|
6675
6674
|
function parseReqUrl(req) {
|
|
6676
|
-
let proto = req.headers['x-forwarded-proto'] || 'http', host = req.headers['x-forwarded-host'] || req.headers.host ||
|
|
6675
|
+
let proto = req.headers['x-forwarded-proto'] || 'http', host = req.headers['x-forwarded-host'] || req.headers.host || LOCALHOST;
|
|
6677
6676
|
try {
|
|
6678
6677
|
return new external_node_url_.URL(req.url || '/', `${proto}://${host}`);
|
|
6679
6678
|
} catch {
|
|
@@ -6686,8 +6685,8 @@ let faviconFallbackMiddleware = (req, res, next)=>{
|
|
|
6686
6685
|
return (req, res, next)=>{
|
|
6687
6686
|
let _startAt = process.hrtime();
|
|
6688
6687
|
on_finished_default()(res, ()=>{
|
|
6689
|
-
let method = req.method, url = req.originalUrl || req.url, status = Number(res.statusCode), statusColor = status >= 500 ?
|
|
6690
|
-
src_logger.debug(`${statusColor(status)} ${method} ${url} ${
|
|
6688
|
+
let method = req.method, url = req.originalUrl || req.url, status = Number(res.statusCode), statusColor = status >= 500 ? picocolors_default().red : status >= 400 ? picocolors_default().yellow : status >= 300 ? picocolors_default().cyan : status >= 200 ? picocolors_default().green : (res)=>res, endAt = process.hrtime(), totalTime = (endAt[0] - _startAt[0]) * 1e3 + (endAt[1] - _startAt[1]) * 1e-6;
|
|
6689
|
+
src_logger.debug(`${statusColor(status)} ${method} ${url} ${picocolors_default().dim(`${totalTime.toFixed(3)} ms`)}`);
|
|
6691
6690
|
}), next();
|
|
6692
6691
|
};
|
|
6693
6692
|
}, notFoundMiddleware = (_req, res, _next)=>{
|
|
@@ -6744,7 +6743,7 @@ function formatProxyOptions(proxyOptions) {
|
|
|
6744
6743
|
}
|
|
6745
6744
|
return ret;
|
|
6746
6745
|
}
|
|
6747
|
-
|
|
6746
|
+
function createProxyMiddleware(proxyOptions) {
|
|
6748
6747
|
let formattedOptions = formatProxyOptions(proxyOptions), proxyMiddlewares = [], middlewares = [], { createProxyMiddleware: baseMiddleware } = requireCompiledPackage('http-proxy-middleware');
|
|
6749
6748
|
for (let opts of formattedOptions){
|
|
6750
6749
|
let { onProxyRes } = opts;
|
|
@@ -6765,6 +6764,177 @@ let createProxyMiddleware = (proxyOptions)=>{
|
|
|
6765
6764
|
for (let middleware of proxyMiddlewares)'function' == typeof middleware.upgrade && middleware.upgrade(req, socket, head);
|
|
6766
6765
|
}
|
|
6767
6766
|
};
|
|
6767
|
+
}
|
|
6768
|
+
let applyDefaultMiddlewares = async ({ config, buildManager, context, devServerAPI, middlewares, postCallbacks })=>{
|
|
6769
|
+
let upgradeEvents = [], { server } = config;
|
|
6770
|
+
if (server.cors) {
|
|
6771
|
+
let { default: corsMiddleware } = await import("./cors.js").then(__webpack_require__.t.bind(__webpack_require__, "../../node_modules/.pnpm/cors@2.8.5/node_modules/cors/lib/index.js", 23));
|
|
6772
|
+
middlewares.push(corsMiddleware('boolean' == typeof server.cors ? {} : server.cors));
|
|
6773
|
+
}
|
|
6774
|
+
let { headers } = server;
|
|
6775
|
+
if (headers && middlewares.push((_req, res, next)=>{
|
|
6776
|
+
for (let [key, value] of Object.entries(headers))res.setHeader(key, value);
|
|
6777
|
+
next();
|
|
6778
|
+
}), server.proxy) {
|
|
6779
|
+
let { middlewares: proxyMiddlewares, upgrade } = createProxyMiddleware(server.proxy);
|
|
6780
|
+
for (let middleware of (upgradeEvents.push(upgrade), proxyMiddlewares))middlewares.push(middleware);
|
|
6781
|
+
}
|
|
6782
|
+
let { compress } = server;
|
|
6783
|
+
if (compress && middlewares.push(gzipMiddleware_gzipMiddleware('object' == typeof compress ? compress : void 0)), 'dev' === context.action && buildManager) {
|
|
6784
|
+
let { compiler } = buildManager;
|
|
6785
|
+
(compiler_isMultiCompiler(compiler) ? compiler.compilers.some((childCompiler)=>childCompiler.options.lazyCompilation) : compiler.options.lazyCompilation) && middlewares.push(rspack_rspack.lazyCompilationMiddleware(compiler));
|
|
6786
|
+
}
|
|
6787
|
+
server.base && '/' !== server.base && middlewares.push(getBaseUrlMiddleware({
|
|
6788
|
+
base: server.base
|
|
6789
|
+
}));
|
|
6790
|
+
let { default: launchEditorMiddleware } = await import("./launch-editor-middleware.js").then(__webpack_require__.t.bind(__webpack_require__, "../../node_modules/.pnpm/launch-editor-middleware@2.12.0/node_modules/launch-editor-middleware/index.js", 23));
|
|
6791
|
+
if (middlewares.push([
|
|
6792
|
+
'/__open-in-editor',
|
|
6793
|
+
launchEditorMiddleware()
|
|
6794
|
+
]), middlewares.push((({ environments })=>async function viewingServedFilesMiddleware(req, res, next) {
|
|
6795
|
+
if ('/rsbuild-dev-server' !== req.url.replace(postfixRE, '')) return void next();
|
|
6796
|
+
res.writeHead(200, {
|
|
6797
|
+
'Content-Type': 'text/html; charset=utf-8'
|
|
6798
|
+
}), res.write(`<!DOCTYPE html>
|
|
6799
|
+
<html>
|
|
6800
|
+
<head>
|
|
6801
|
+
<meta charset="utf-8"/>
|
|
6802
|
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
6803
|
+
<style>
|
|
6804
|
+
body {
|
|
6805
|
+
margin: 0;
|
|
6806
|
+
color: #f6f7f9;
|
|
6807
|
+
padding: 32px 40px;
|
|
6808
|
+
line-height: 1.8;
|
|
6809
|
+
min-height: 100vh;
|
|
6810
|
+
background-image: linear-gradient(#020917, #101725);
|
|
6811
|
+
font-family: ui-sans-serif,system-ui,sans-serif;
|
|
6812
|
+
}
|
|
6813
|
+
h1, h2 {
|
|
6814
|
+
font-weight: 500;
|
|
6815
|
+
}
|
|
6816
|
+
h1 {
|
|
6817
|
+
margin: 0;
|
|
6818
|
+
font-size: 36px;
|
|
6819
|
+
}
|
|
6820
|
+
h2 {
|
|
6821
|
+
font-size: 20px;
|
|
6822
|
+
margin: 24px 0 16px;
|
|
6823
|
+
}
|
|
6824
|
+
ul {
|
|
6825
|
+
margin: 0;
|
|
6826
|
+
padding-left: 16px;
|
|
6827
|
+
}
|
|
6828
|
+
a {
|
|
6829
|
+
color: #58c4dc;
|
|
6830
|
+
text-decoration: none;
|
|
6831
|
+
}
|
|
6832
|
+
a:hover {
|
|
6833
|
+
text-decoration: underline;
|
|
6834
|
+
}
|
|
6835
|
+
</style>
|
|
6836
|
+
</head>
|
|
6837
|
+
<body>
|
|
6838
|
+
<h1>Assets Report</h1>
|
|
6839
|
+
</body>
|
|
6840
|
+
</html>`);
|
|
6841
|
+
try {
|
|
6842
|
+
for(let key in environments){
|
|
6843
|
+
res.write(`<h2>Environment: ${key}</h2>`);
|
|
6844
|
+
let list = [], environment = environments[key], stats = await environment.getStats(), assets = Object.keys(stats.compilation.assets);
|
|
6845
|
+
for (let asset of (res.write('<ul>'), assets))list.push(`<li><a target="_blank" href="${asset}">${asset}</a></li>`);
|
|
6846
|
+
res.write(list?.join('')), res.write('</ul>');
|
|
6847
|
+
}
|
|
6848
|
+
res.end('</body></html>');
|
|
6849
|
+
} catch (err) {
|
|
6850
|
+
src_logger.error(err), res.writeHead(500), res.end('Failed to list the files');
|
|
6851
|
+
}
|
|
6852
|
+
})({
|
|
6853
|
+
environments: devServerAPI.environments
|
|
6854
|
+
})), buildManager && (middlewares.push(buildManager.assetsMiddleware), upgradeEvents.push(buildManager.socketServer.upgrade), middlewares.push(function hotUpdateJsonFallbackMiddleware(req, res, next) {
|
|
6855
|
+
req.url?.endsWith('.hot-update.json') && 'OPTIONS' !== req.method ? notFoundMiddleware(req, res, next) : next();
|
|
6856
|
+
})), buildManager && middlewares.push((({ distPath, buildManager })=>async function htmlCompletionMiddleware(req, res, next) {
|
|
6857
|
+
if (!maybeHTMLRequest(req)) return void next();
|
|
6858
|
+
let pathname = req.url.replace(postfixRE, ''), rewrite = (newUrl)=>{
|
|
6859
|
+
req.url = newUrl, buildManager.assetsMiddleware(req, res, (...args)=>{
|
|
6860
|
+
next(...args);
|
|
6861
|
+
});
|
|
6862
|
+
};
|
|
6863
|
+
if (pathname.endsWith('/')) {
|
|
6864
|
+
let newUrl = `${pathname}index.html`, filePath = external_node_path_.default.join(distPath, newUrl);
|
|
6865
|
+
if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) return void rewrite(newUrl);
|
|
6866
|
+
} else if (!external_node_path_.default.extname(pathname)) {
|
|
6867
|
+
let newUrl = `${pathname}.html`, filePath = external_node_path_.default.join(distPath, newUrl);
|
|
6868
|
+
if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) return void rewrite(newUrl);
|
|
6869
|
+
}
|
|
6870
|
+
next();
|
|
6871
|
+
})({
|
|
6872
|
+
buildManager,
|
|
6873
|
+
distPath: context.distPath
|
|
6874
|
+
})), server.publicDir.length) {
|
|
6875
|
+
let { default: sirv } = await import("./sirv.js").then((mod)=>({
|
|
6876
|
+
default: mod.build
|
|
6877
|
+
}));
|
|
6878
|
+
for (let { name } of server.publicDir){
|
|
6879
|
+
let sirvMiddleware = sirv(name, {
|
|
6880
|
+
etag: !0,
|
|
6881
|
+
dev: !0
|
|
6882
|
+
});
|
|
6883
|
+
middlewares.push(function publicDirMiddleware(req, res, next) {
|
|
6884
|
+
sirvMiddleware(req, res, next);
|
|
6885
|
+
});
|
|
6886
|
+
}
|
|
6887
|
+
}
|
|
6888
|
+
for (let callback of postCallbacks)callback();
|
|
6889
|
+
return server.historyApiFallback && (middlewares.push(historyApiFallback_historyApiFallbackMiddleware(!0 === server.historyApiFallback ? {} : server.historyApiFallback)), buildManager?.assetsMiddleware && middlewares.push(buildManager.assetsMiddleware)), buildManager && middlewares.push((({ htmlFallback, distPath, buildManager })=>async function htmlFallbackMiddleware(req, res, next) {
|
|
6890
|
+
if (!maybeHTMLRequest(req) || '/favicon.ico' === req.url || 'index' !== htmlFallback) return void next();
|
|
6891
|
+
let filePath = external_node_path_.default.join(distPath, 'index.html');
|
|
6892
|
+
if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) {
|
|
6893
|
+
let newUrl = '/index.html';
|
|
6894
|
+
isVerbose() && src_logger.debug(` ${req.method} ${req.url} ${picocolors_default().yellow('fallback to')} ${newUrl}`), req.url = newUrl, buildManager.assetsMiddleware(req, res, (...args)=>{
|
|
6895
|
+
next(...args);
|
|
6896
|
+
});
|
|
6897
|
+
return;
|
|
6898
|
+
}
|
|
6899
|
+
next();
|
|
6900
|
+
})({
|
|
6901
|
+
buildManager,
|
|
6902
|
+
distPath: context.distPath,
|
|
6903
|
+
htmlFallback: server.htmlFallback
|
|
6904
|
+
})), middlewares.push(faviconFallbackMiddleware), {
|
|
6905
|
+
onUpgrade: (...args)=>{
|
|
6906
|
+
for (let cb of upgradeEvents)cb(...args);
|
|
6907
|
+
}
|
|
6908
|
+
};
|
|
6909
|
+
}, getDevMiddlewares = async (options)=>{
|
|
6910
|
+
let middlewares = [], { buildManager } = options;
|
|
6911
|
+
isVerbose() && middlewares.push(getRequestLoggerMiddleware());
|
|
6912
|
+
let { before, after } = ((config, devServerAPI)=>{
|
|
6913
|
+
let setupMiddlewares = config.dev.setupMiddlewares || [], serverOptions = pick(devServerAPI, [
|
|
6914
|
+
'sockWrite',
|
|
6915
|
+
'environments'
|
|
6916
|
+
]), before = [], after = [];
|
|
6917
|
+
for (let handler of helpers_castArray(setupMiddlewares))handler({
|
|
6918
|
+
unshift: (...handlers)=>before.unshift(...handlers),
|
|
6919
|
+
push: (...handlers)=>after.push(...handlers)
|
|
6920
|
+
}, serverOptions);
|
|
6921
|
+
return {
|
|
6922
|
+
before,
|
|
6923
|
+
after
|
|
6924
|
+
};
|
|
6925
|
+
})(options.config, options.devServerAPI);
|
|
6926
|
+
middlewares.push(...before);
|
|
6927
|
+
let { onUpgrade } = await applyDefaultMiddlewares({
|
|
6928
|
+
...options,
|
|
6929
|
+
middlewares
|
|
6930
|
+
});
|
|
6931
|
+
return middlewares.push(...after), {
|
|
6932
|
+
close: async ()=>{
|
|
6933
|
+
await buildManager?.close();
|
|
6934
|
+
},
|
|
6935
|
+
onUpgrade,
|
|
6936
|
+
middlewares
|
|
6937
|
+
};
|
|
6768
6938
|
}, asModule = async (something, context, unlinked)=>{
|
|
6769
6939
|
let { Module, SyntheticModule } = await import("node:vm");
|
|
6770
6940
|
if (something instanceof Module) return something;
|
|
@@ -6824,7 +6994,7 @@ class BasicRunner {
|
|
|
6824
6994
|
postExecute(_m, _file) {}
|
|
6825
6995
|
createRunner() {
|
|
6826
6996
|
this.requirers.set('entry', (_currentDirectory, _modulePath, _context = {})=>{
|
|
6827
|
-
throw Error(`${
|
|
6997
|
+
throw Error(`${picocolors_default().dim('[rsbuild:runner]')} Not implemented`);
|
|
6828
6998
|
});
|
|
6829
6999
|
}
|
|
6830
7000
|
}
|
|
@@ -6919,7 +7089,7 @@ class EsmRunner extends CommonJsRunner {
|
|
|
6919
7089
|
createEsmRequirer() {
|
|
6920
7090
|
let esmCache = new Map(), esmIdentifier = this._options.name, vm = esm_require('node:vm');
|
|
6921
7091
|
return (currentDirectory, modulePath, context = {})=>{
|
|
6922
|
-
if (!vm.SourceTextModule) throw Error(`${
|
|
7092
|
+
if (!vm.SourceTextModule) throw Error(`${picocolors_default().dim('[rsbuild:runner]')} Running ESM bundle needs add Node.js option ${picocolors_default().yellow('--experimental-vm-modules')}.`);
|
|
6923
7093
|
let _require = this.getRequire(), file = context.file || this.getFile(modulePath, currentDirectory);
|
|
6924
7094
|
if (!file) return this.requirers.get('miss')(currentDirectory, modulePath);
|
|
6925
7095
|
let esm = esmCache.get(file.path);
|
|
@@ -6955,7 +7125,7 @@ class BasicRunnerFactory {
|
|
|
6955
7125
|
name: this.name,
|
|
6956
7126
|
...options
|
|
6957
7127
|
}, { compilerOptions } = options;
|
|
6958
|
-
if ('web' === compilerOptions.target || 'webworker' === compilerOptions.target) throw Error(`${
|
|
7128
|
+
if ('web' === compilerOptions.target || 'webworker' === compilerOptions.target) throw Error(`${picocolors_default().dim('[rsbuild:runner]')} Not support run ${picocolors_default().yellow(compilerOptions.target)} resource in Rsbuild server`);
|
|
6959
7129
|
return new EsmRunner(runnerOptions);
|
|
6960
7130
|
}
|
|
6961
7131
|
}
|
|
@@ -6969,13 +7139,13 @@ let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>{
|
|
|
6969
7139
|
entrypoints: !0,
|
|
6970
7140
|
outputPath: !0
|
|
6971
7141
|
});
|
|
6972
|
-
if (!entrypoints?.[entryName]) throw Error(`${
|
|
7142
|
+
if (!entrypoints?.[entryName]) throw Error(`${picocolors_default().dim('[rsbuild:loadBundle]')} Can't find entry: ${picocolors_default().yellow(entryName)}`);
|
|
6973
7143
|
let { chunks: entryChunks = [] } = entrypoints[entryName], files = entryChunks.reduce((prev, entryChunkName)=>{
|
|
6974
7144
|
let chunk = chunks?.find((chunk)=>chunk.entry && chunk.names?.includes(String(entryChunkName)));
|
|
6975
7145
|
return chunk?.files ? prev.concat(chunk.files.filter((file)=>!file.endsWith('.css'))) : prev;
|
|
6976
7146
|
}, []);
|
|
6977
|
-
if (0 === files.length) throw Error(`${
|
|
6978
|
-
if (files.length > 1) throw Error(`${
|
|
7147
|
+
if (0 === files.length) throw Error(`${picocolors_default().dim('[rsbuild:loadBundle]')} Failed to get bundle by entryName: ${picocolors_default().yellow(entryName)}`);
|
|
7148
|
+
if (files.length > 1) throw Error(`${picocolors_default().dim('[rsbuild:loadBundle]')} Only support load single entry chunk, but got ${picocolors_default().yellow(files.length)}: ${files.join(',')}`);
|
|
6979
7149
|
let allChunkFiles = chunks?.flatMap((c)=>c.files).map((file)=>(0, external_node_path_.join)(outputPath, file)) || [];
|
|
6980
7150
|
return await runner_run({
|
|
6981
7151
|
bundlePath: files[0],
|
|
@@ -7078,7 +7248,9 @@ let GLOB_REGEX = /[*?{}[\]()!+|]/;
|
|
|
7078
7248
|
async function createChokidar(pathOrGlobs, root, options) {
|
|
7079
7249
|
let chokidar = requireCompiledPackage('chokidar'), watchFiles = new Set(), globPatterns = pathOrGlobs.filter((pathOrGlob)=>!!GLOB_REGEX.test(pathOrGlob) || (watchFiles.add(pathOrGlob), !1));
|
|
7080
7250
|
if (globPatterns.length) {
|
|
7081
|
-
let { glob } =
|
|
7251
|
+
let { glob } = await import("./tinyglobby.js").then((mod)=>({
|
|
7252
|
+
glob: mod.glob
|
|
7253
|
+
}));
|
|
7082
7254
|
for (let file of (await glob(globPatterns, {
|
|
7083
7255
|
cwd: root,
|
|
7084
7256
|
absolute: !0
|
|
@@ -7095,7 +7267,7 @@ async function startWatchFiles({ paths, options, type = 'reload-page' }, buildMa
|
|
|
7095
7267
|
});
|
|
7096
7268
|
}), watcher;
|
|
7097
7269
|
}
|
|
7098
|
-
async function devServer_createDevServer(options, createCompiler, config, {
|
|
7270
|
+
async function devServer_createDevServer(options, createCompiler, config, { getPortSilently, runCompile = !0 } = {}) {
|
|
7099
7271
|
let lastStats, fileWatcher, devMiddlewares;
|
|
7100
7272
|
src_logger.debug('create dev server');
|
|
7101
7273
|
let { port, host, https, portTip } = await getServerConfig({
|
|
@@ -7115,8 +7287,8 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
|
|
|
7115
7287
|
], waitLastCompileDoneResolve && (waitLastCompileDoneResolve(), waitLastCompileDoneResolve = null);
|
|
7116
7288
|
});
|
|
7117
7289
|
let startCompile = async ()=>{
|
|
7118
|
-
let compiler =
|
|
7119
|
-
if (!compiler) throw Error(`${
|
|
7290
|
+
let compiler = await createCompiler();
|
|
7291
|
+
if (!compiler) throw Error(`${picocolors_default().dim('[rsbuild:server]')} Failed to get compiler instance.`);
|
|
7120
7292
|
let publicPaths = compiler_isMultiCompiler(compiler) ? compiler.compilers.map(getPublicPathFromCompiler) : [
|
|
7121
7293
|
getPublicPathFromCompiler(compiler)
|
|
7122
7294
|
], { base } = config.server;
|
|
@@ -7142,7 +7314,8 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
|
|
|
7142
7314
|
routes,
|
|
7143
7315
|
protocol,
|
|
7144
7316
|
printUrls: config.server.printUrls,
|
|
7145
|
-
trailingLineBreak: !cliShortcutsEnabled
|
|
7317
|
+
trailingLineBreak: !cliShortcutsEnabled,
|
|
7318
|
+
originalConfig: context.originalConfig
|
|
7146
7319
|
}), openPage = async ()=>open_open({
|
|
7147
7320
|
https,
|
|
7148
7321
|
port,
|
|
@@ -7173,10 +7346,10 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
|
|
|
7173
7346
|
!getPortSilently && portTip && src_logger.info(portTip);
|
|
7174
7347
|
}, cacheableLoadBundle = createCacheableFunction(loadBundle), cacheableTransformedHtml = createCacheableFunction((_stats, entryName, utils)=>((entryName, utils)=>{
|
|
7175
7348
|
let { htmlPaths, distPath } = utils.environment, htmlPath = htmlPaths[entryName];
|
|
7176
|
-
if (!htmlPath) throw Error(`${
|
|
7349
|
+
if (!htmlPath) throw Error(`${picocolors_default().dim('[rsbuild:getTransformedHtml]')} Failed to get HTML file by entryName: ${picocolors_default().yellow(entryName)}`);
|
|
7177
7350
|
let fileName = (0, external_node_path_.join)(distPath, htmlPath);
|
|
7178
7351
|
return utils.readFileSync(fileName);
|
|
7179
|
-
})(entryName, utils)), environmentAPI = {}, getErrorMsg = (method)=>`${
|
|
7352
|
+
})(entryName, utils)), environmentAPI = {}, getErrorMsg = (method)=>`${picocolors_default().dim('[rsbuild:server]')} Can not call ${picocolors_default().yellow(method)} when ${picocolors_default().yellow('runCompile')} is false`;
|
|
7180
7353
|
context.environmentList.forEach((environment, index)=>{
|
|
7181
7354
|
environmentAPI[environment.name] = {
|
|
7182
7355
|
context: environment,
|
|
@@ -7200,7 +7373,7 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
|
|
|
7200
7373
|
}
|
|
7201
7374
|
};
|
|
7202
7375
|
});
|
|
7203
|
-
let
|
|
7376
|
+
let { default: connect } = await import("./connect.js").then(__webpack_require__.t.bind(__webpack_require__, "../../node_modules/.pnpm/connect@3.7.0/node_modules/connect/index.js", 23)), middlewares = connect(), httpServer = middlewareMode ? null : await createHttpServer({
|
|
7204
7377
|
serverConfig: config.server,
|
|
7205
7378
|
middlewares
|
|
7206
7379
|
}), devServerAPI = {
|
|
@@ -7213,7 +7386,7 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
|
|
|
7213
7386
|
data
|
|
7214
7387
|
}),
|
|
7215
7388
|
listen: async ()=>{
|
|
7216
|
-
if (!httpServer) throw Error(`${
|
|
7389
|
+
if (!httpServer) throw Error(`${picocolors_default().dim('[rsbuild:server]')} Can not listen dev server as ${picocolors_default().yellow('server.middlewareMode')} is enabled.`);
|
|
7217
7390
|
let serverTerminator = getServerTerminator(httpServer);
|
|
7218
7391
|
return src_logger.debug('listen dev server'), context.hooks.onCloseDevServer.tap(serverTerminator), new Promise((resolve)=>{
|
|
7219
7392
|
httpServer.listen({
|
|
@@ -7254,172 +7427,7 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
|
|
|
7254
7427
|
config,
|
|
7255
7428
|
buildManager,
|
|
7256
7429
|
root
|
|
7257
|
-
}), (devMiddlewares = (
|
|
7258
|
-
let middlewares = [], { buildManager } = options;
|
|
7259
|
-
isVerbose() && middlewares.push(getRequestLoggerMiddleware());
|
|
7260
|
-
let { before, after } = ((config, devServerAPI)=>{
|
|
7261
|
-
let setupMiddlewares = config.dev.setupMiddlewares || [], serverOptions = pick(devServerAPI, [
|
|
7262
|
-
'sockWrite',
|
|
7263
|
-
'environments'
|
|
7264
|
-
]), before = [], after = [];
|
|
7265
|
-
for (let handler of helpers_castArray(setupMiddlewares))handler({
|
|
7266
|
-
unshift: (...handlers)=>before.unshift(...handlers),
|
|
7267
|
-
push: (...handlers)=>after.push(...handlers)
|
|
7268
|
-
}, serverOptions);
|
|
7269
|
-
return {
|
|
7270
|
-
before,
|
|
7271
|
-
after
|
|
7272
|
-
};
|
|
7273
|
-
})(options.config, options.devServerAPI);
|
|
7274
|
-
middlewares.push(...before);
|
|
7275
|
-
let { onUpgrade } = (({ config, buildManager, context, devServerAPI, middlewares, postCallbacks })=>{
|
|
7276
|
-
let upgradeEvents = [], { server } = config;
|
|
7277
|
-
if (server.cors) {
|
|
7278
|
-
let corsMiddleware = requireCompiledPackage('cors');
|
|
7279
|
-
middlewares.push(corsMiddleware('boolean' == typeof server.cors ? {} : server.cors));
|
|
7280
|
-
}
|
|
7281
|
-
let { headers } = server;
|
|
7282
|
-
if (headers && middlewares.push((_req, res, next)=>{
|
|
7283
|
-
for (let [key, value] of Object.entries(headers))res.setHeader(key, value);
|
|
7284
|
-
next();
|
|
7285
|
-
}), server.proxy) {
|
|
7286
|
-
let { middlewares: proxyMiddlewares, upgrade } = createProxyMiddleware(server.proxy);
|
|
7287
|
-
for (let middleware of (upgradeEvents.push(upgrade), proxyMiddlewares))middlewares.push(middleware);
|
|
7288
|
-
}
|
|
7289
|
-
let { compress } = server;
|
|
7290
|
-
if (compress && middlewares.push(gzipMiddleware_gzipMiddleware('object' == typeof compress ? compress : void 0)), 'dev' === context.action && 'rspack' === context.bundlerType && buildManager) {
|
|
7291
|
-
let { compiler } = buildManager;
|
|
7292
|
-
(compiler_isMultiCompiler(compiler) ? compiler.compilers.some((childCompiler)=>childCompiler.options.lazyCompilation) : compiler.options.lazyCompilation) && middlewares.push(rspack_rspack.lazyCompilationMiddleware(compiler));
|
|
7293
|
-
}
|
|
7294
|
-
server.base && '/' !== server.base && middlewares.push(getBaseUrlMiddleware({
|
|
7295
|
-
base: server.base
|
|
7296
|
-
}));
|
|
7297
|
-
let launchEditorMiddleware = requireCompiledPackage('launch-editor-middleware');
|
|
7298
|
-
for (let { name } of (middlewares.push([
|
|
7299
|
-
'/__open-in-editor',
|
|
7300
|
-
launchEditorMiddleware()
|
|
7301
|
-
]), middlewares.push((({ environments })=>async function viewingServedFilesMiddleware(req, res, next) {
|
|
7302
|
-
if ('/rsbuild-dev-server' !== req.url.replace(postfixRE, '')) return void next();
|
|
7303
|
-
res.writeHead(200, {
|
|
7304
|
-
'Content-Type': 'text/html; charset=utf-8'
|
|
7305
|
-
}), res.write(`<!DOCTYPE html>
|
|
7306
|
-
<html>
|
|
7307
|
-
<head>
|
|
7308
|
-
<meta charset="utf-8"/>
|
|
7309
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
7310
|
-
<style>
|
|
7311
|
-
body {
|
|
7312
|
-
margin: 0;
|
|
7313
|
-
color: #f6f7f9;
|
|
7314
|
-
padding: 32px 40px;
|
|
7315
|
-
line-height: 1.8;
|
|
7316
|
-
min-height: 100vh;
|
|
7317
|
-
background-image: linear-gradient(#020917, #101725);
|
|
7318
|
-
font-family: ui-sans-serif,system-ui,sans-serif;
|
|
7319
|
-
}
|
|
7320
|
-
h1, h2 {
|
|
7321
|
-
font-weight: 500;
|
|
7322
|
-
}
|
|
7323
|
-
h1 {
|
|
7324
|
-
margin: 0;
|
|
7325
|
-
font-size: 36px;
|
|
7326
|
-
}
|
|
7327
|
-
h2 {
|
|
7328
|
-
font-size: 20px;
|
|
7329
|
-
margin: 24px 0 16px;
|
|
7330
|
-
}
|
|
7331
|
-
ul {
|
|
7332
|
-
margin: 0;
|
|
7333
|
-
padding-left: 16px;
|
|
7334
|
-
}
|
|
7335
|
-
a {
|
|
7336
|
-
color: #58c4dc;
|
|
7337
|
-
text-decoration: none;
|
|
7338
|
-
}
|
|
7339
|
-
a:hover {
|
|
7340
|
-
text-decoration: underline;
|
|
7341
|
-
}
|
|
7342
|
-
</style>
|
|
7343
|
-
</head>
|
|
7344
|
-
<body>
|
|
7345
|
-
<h1>Assets Report</h1>
|
|
7346
|
-
</body>
|
|
7347
|
-
</html>`);
|
|
7348
|
-
try {
|
|
7349
|
-
for(let key in environments){
|
|
7350
|
-
res.write(`<h2>Environment: ${key}</h2>`);
|
|
7351
|
-
let list = [], environment = environments[key], stats = await environment.getStats(), assets = Object.keys(stats.compilation.assets);
|
|
7352
|
-
for (let asset of (res.write('<ul>'), assets))list.push(`<li><a target="_blank" href="${asset}">${asset}</a></li>`);
|
|
7353
|
-
res.write(list?.join('')), res.write('</ul>');
|
|
7354
|
-
}
|
|
7355
|
-
res.end('</body></html>');
|
|
7356
|
-
} catch (err) {
|
|
7357
|
-
src_logger.error(err), res.writeHead(500), res.end('Failed to list the files');
|
|
7358
|
-
}
|
|
7359
|
-
})({
|
|
7360
|
-
environments: devServerAPI.environments
|
|
7361
|
-
})), buildManager && (middlewares.push(buildManager.assetsMiddleware), upgradeEvents.push(buildManager.socketServer.upgrade), middlewares.push(function hotUpdateJsonFallbackMiddleware(req, res, next) {
|
|
7362
|
-
req.url?.endsWith('.hot-update.json') && 'OPTIONS' !== req.method ? notFoundMiddleware(req, res, next) : next();
|
|
7363
|
-
})), buildManager && middlewares.push((({ distPath, buildManager })=>async function htmlCompletionMiddleware(req, res, next) {
|
|
7364
|
-
if (!maybeHTMLRequest(req)) return void next();
|
|
7365
|
-
let pathname = req.url.replace(postfixRE, ''), rewrite = (newUrl)=>{
|
|
7366
|
-
req.url = newUrl, buildManager.assetsMiddleware(req, res, (...args)=>{
|
|
7367
|
-
next(...args);
|
|
7368
|
-
});
|
|
7369
|
-
};
|
|
7370
|
-
if (pathname.endsWith('/')) {
|
|
7371
|
-
let newUrl = `${pathname}index.html`, filePath = external_node_path_.default.join(distPath, newUrl);
|
|
7372
|
-
if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) return void rewrite(newUrl);
|
|
7373
|
-
} else if (!external_node_path_.default.extname(pathname)) {
|
|
7374
|
-
let newUrl = `${pathname}.html`, filePath = external_node_path_.default.join(distPath, newUrl);
|
|
7375
|
-
if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) return void rewrite(newUrl);
|
|
7376
|
-
}
|
|
7377
|
-
next();
|
|
7378
|
-
})({
|
|
7379
|
-
buildManager,
|
|
7380
|
-
distPath: context.distPath
|
|
7381
|
-
})), server.publicDir)){
|
|
7382
|
-
let sirvMiddleware = requireCompiledPackage('sirv')(name, {
|
|
7383
|
-
etag: !0,
|
|
7384
|
-
dev: !0
|
|
7385
|
-
});
|
|
7386
|
-
middlewares.push(function publicDirMiddleware(req, res, next) {
|
|
7387
|
-
sirvMiddleware(req, res, next);
|
|
7388
|
-
});
|
|
7389
|
-
}
|
|
7390
|
-
for (let callback of postCallbacks)callback();
|
|
7391
|
-
return server.historyApiFallback && (middlewares.push(historyApiFallback_historyApiFallbackMiddleware(!0 === server.historyApiFallback ? {} : server.historyApiFallback)), buildManager?.assetsMiddleware && middlewares.push(buildManager.assetsMiddleware)), buildManager && middlewares.push((({ htmlFallback, distPath, buildManager })=>async function htmlFallbackMiddleware(req, res, next) {
|
|
7392
|
-
if (!maybeHTMLRequest(req) || '/favicon.ico' === req.url || 'index' !== htmlFallback) return void next();
|
|
7393
|
-
let filePath = external_node_path_.default.join(distPath, 'index.html');
|
|
7394
|
-
if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) {
|
|
7395
|
-
let newUrl = '/index.html';
|
|
7396
|
-
isVerbose() && src_logger.debug(` ${req.method} ${req.url} ${color.yellow('fallback to')} ${newUrl}`), req.url = newUrl, buildManager.assetsMiddleware(req, res, (...args)=>{
|
|
7397
|
-
next(...args);
|
|
7398
|
-
});
|
|
7399
|
-
return;
|
|
7400
|
-
}
|
|
7401
|
-
next();
|
|
7402
|
-
})({
|
|
7403
|
-
buildManager,
|
|
7404
|
-
distPath: context.distPath,
|
|
7405
|
-
htmlFallback: server.htmlFallback
|
|
7406
|
-
})), middlewares.push(faviconFallbackMiddleware), {
|
|
7407
|
-
onUpgrade: (...args)=>{
|
|
7408
|
-
for (let cb of upgradeEvents)cb(...args);
|
|
7409
|
-
}
|
|
7410
|
-
};
|
|
7411
|
-
})({
|
|
7412
|
-
...options,
|
|
7413
|
-
middlewares
|
|
7414
|
-
});
|
|
7415
|
-
return middlewares.push(...after), {
|
|
7416
|
-
close: async ()=>{
|
|
7417
|
-
await buildManager?.close();
|
|
7418
|
-
},
|
|
7419
|
-
onUpgrade,
|
|
7420
|
-
middlewares
|
|
7421
|
-
};
|
|
7422
|
-
})({
|
|
7430
|
+
}), (devMiddlewares = await getDevMiddlewares({
|
|
7423
7431
|
buildManager,
|
|
7424
7432
|
config,
|
|
7425
7433
|
devServerAPI,
|
|
@@ -7428,71 +7436,6 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
|
|
|
7428
7436
|
})).middlewares))Array.isArray(item) ? middlewares.use(...item) : middlewares.use(item);
|
|
7429
7437
|
return buildManager?.watch(), src_logger.debug('create dev server done'), devServerAPI;
|
|
7430
7438
|
}
|
|
7431
|
-
let rspackProvider = ({ context, pluginManager, rsbuildOptions })=>{
|
|
7432
|
-
let createCompiler = async ()=>(await createCompiler_createCompiler({
|
|
7433
|
-
context,
|
|
7434
|
-
pluginManager,
|
|
7435
|
-
rsbuildOptions
|
|
7436
|
-
})).compiler;
|
|
7437
|
-
return {
|
|
7438
|
-
bundler: 'rspack',
|
|
7439
|
-
createCompiler,
|
|
7440
|
-
async createDevServer (options) {
|
|
7441
|
-
let config = await initRsbuildConfig({
|
|
7442
|
-
context,
|
|
7443
|
-
pluginManager
|
|
7444
|
-
});
|
|
7445
|
-
return devServer_createDevServer({
|
|
7446
|
-
context,
|
|
7447
|
-
pluginManager,
|
|
7448
|
-
rsbuildOptions
|
|
7449
|
-
}, createCompiler, config, options);
|
|
7450
|
-
},
|
|
7451
|
-
async startDevServer (options) {
|
|
7452
|
-
let config = await initRsbuildConfig({
|
|
7453
|
-
context,
|
|
7454
|
-
pluginManager
|
|
7455
|
-
});
|
|
7456
|
-
return (await devServer_createDevServer({
|
|
7457
|
-
context,
|
|
7458
|
-
pluginManager,
|
|
7459
|
-
rsbuildOptions
|
|
7460
|
-
}, createCompiler, config, options)).listen();
|
|
7461
|
-
},
|
|
7462
|
-
build: async (options)=>build_build({
|
|
7463
|
-
context,
|
|
7464
|
-
pluginManager,
|
|
7465
|
-
rsbuildOptions
|
|
7466
|
-
}, options),
|
|
7467
|
-
async initConfigs (options) {
|
|
7468
|
-
if (context.action && options?.action && context.action !== options.action) throw Error(`\
|
|
7469
|
-
[rsbuild] initConfigs() can only be called with the same action type.
|
|
7470
|
-
- Expected: ${context.action}
|
|
7471
|
-
- Actual: ${options?.action}`);
|
|
7472
|
-
options?.action && (context.action = options.action);
|
|
7473
|
-
let { rspackConfigs } = await initConfigs({
|
|
7474
|
-
context,
|
|
7475
|
-
pluginManager,
|
|
7476
|
-
rsbuildOptions
|
|
7477
|
-
});
|
|
7478
|
-
return rspackConfigs;
|
|
7479
|
-
},
|
|
7480
|
-
async inspectConfig (inspectOptions) {
|
|
7481
|
-
let bundlerConfigs = (await initConfigs({
|
|
7482
|
-
context,
|
|
7483
|
-
pluginManager,
|
|
7484
|
-
rsbuildOptions
|
|
7485
|
-
})).rspackConfigs;
|
|
7486
|
-
return inspectConfig_inspectConfig({
|
|
7487
|
-
context,
|
|
7488
|
-
pluginManager,
|
|
7489
|
-
rsbuildOptions,
|
|
7490
|
-
inspectOptions,
|
|
7491
|
-
bundlerConfigs
|
|
7492
|
-
});
|
|
7493
|
-
}
|
|
7494
|
-
};
|
|
7495
|
-
};
|
|
7496
7439
|
class RsbuildProdServer {
|
|
7497
7440
|
app;
|
|
7498
7441
|
options;
|
|
@@ -7506,7 +7449,7 @@ class RsbuildProdServer {
|
|
|
7506
7449
|
async applyDefaultMiddlewares() {
|
|
7507
7450
|
let { headers, proxy, historyApiFallback, compress, base, cors } = this.options.serverConfig;
|
|
7508
7451
|
if (isVerbose() && this.middlewares.use(getRequestLoggerMiddleware()), cors) {
|
|
7509
|
-
let corsMiddleware =
|
|
7452
|
+
let { default: corsMiddleware } = await import("./cors.js").then(__webpack_require__.t.bind(__webpack_require__, "../../node_modules/.pnpm/cors@2.8.5/node_modules/cors/lib/index.js", 23));
|
|
7510
7453
|
this.middlewares.use(corsMiddleware('boolean' == typeof cors ? {} : cors));
|
|
7511
7454
|
}
|
|
7512
7455
|
if (headers && this.middlewares.use((_req, res, next)=>{
|
|
@@ -7526,10 +7469,12 @@ class RsbuildProdServer {
|
|
|
7526
7469
|
}
|
|
7527
7470
|
base && '/' !== base && this.middlewares.use(getBaseUrlMiddleware({
|
|
7528
7471
|
base
|
|
7529
|
-
})), this.applyStaticAssetMiddleware(), historyApiFallback && (this.middlewares.use(historyApiFallback_historyApiFallbackMiddleware(!0 === historyApiFallback ? {} : historyApiFallback)), this.applyStaticAssetMiddleware()), this.middlewares.use(faviconFallbackMiddleware), this.middlewares.use(optionsFallbackMiddleware), this.middlewares.use(notFoundMiddleware);
|
|
7472
|
+
})), await this.applyStaticAssetMiddleware(), historyApiFallback && (this.middlewares.use(historyApiFallback_historyApiFallbackMiddleware(!0 === historyApiFallback ? {} : historyApiFallback)), await this.applyStaticAssetMiddleware()), this.middlewares.use(faviconFallbackMiddleware), this.middlewares.use(optionsFallbackMiddleware), this.middlewares.use(notFoundMiddleware);
|
|
7530
7473
|
}
|
|
7531
|
-
applyStaticAssetMiddleware() {
|
|
7532
|
-
let { output: { path, assetPrefixes }, serverConfig: { htmlFallback } } = this.options,
|
|
7474
|
+
async applyStaticAssetMiddleware() {
|
|
7475
|
+
let { output: { path, assetPrefixes }, serverConfig: { htmlFallback } } = this.options, { default: sirv } = await import("./sirv.js").then((mod)=>({
|
|
7476
|
+
default: mod.build
|
|
7477
|
+
})), assetsMiddleware = sirv(path, {
|
|
7533
7478
|
etag: !0,
|
|
7534
7479
|
dev: !0,
|
|
7535
7480
|
ignores: [
|
|
@@ -7549,7 +7494,7 @@ class RsbuildProdServer {
|
|
|
7549
7494
|
async function startProdServer(context, config, { getPortSilently } = {}) {
|
|
7550
7495
|
let { port, host, https, portTip } = await getServerConfig({
|
|
7551
7496
|
config
|
|
7552
|
-
}),
|
|
7497
|
+
}), { default: connect } = await import("./connect.js").then(__webpack_require__.t.bind(__webpack_require__, "../../node_modules/.pnpm/connect@3.7.0/node_modules/connect/index.js", 23)), middlewares = connect(), serverConfig = config.server, server = new RsbuildProdServer({
|
|
7553
7498
|
pwd: context.rootPath,
|
|
7554
7499
|
output: {
|
|
7555
7500
|
path: context.distPath,
|
|
@@ -7590,7 +7535,8 @@ async function startProdServer(context, config, { getPortSilently } = {}) {
|
|
|
7590
7535
|
routes,
|
|
7591
7536
|
protocol,
|
|
7592
7537
|
printUrls: serverConfig.printUrls,
|
|
7593
|
-
trailingLineBreak: !cliShortcutsEnabled
|
|
7538
|
+
trailingLineBreak: !cliShortcutsEnabled,
|
|
7539
|
+
originalConfig: context.originalConfig
|
|
7594
7540
|
}), openPage = async ()=>open_open({
|
|
7595
7541
|
https,
|
|
7596
7542
|
port,
|
|
@@ -7633,7 +7579,7 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
7633
7579
|
javascript: {
|
|
7634
7580
|
exportsPresence: 'error'
|
|
7635
7581
|
}
|
|
7636
|
-
}), isDev && config.dev.hmr && 'web' === target && chain.plugin(CHAIN_ID.PLUGIN.HMR).use(bundler.HotModuleReplacementPlugin),
|
|
7582
|
+
}), isDev && config.dev.hmr && 'web' === target && chain.plugin(CHAIN_ID.PLUGIN.HMR).use(bundler.HotModuleReplacementPlugin), chain.module.parser.merge({
|
|
7637
7583
|
javascript: {
|
|
7638
7584
|
typeReexportsPresence: 'tolerant'
|
|
7639
7585
|
}
|
|
@@ -7644,7 +7590,7 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
7644
7590
|
force: !1
|
|
7645
7591
|
}
|
|
7646
7592
|
}
|
|
7647
|
-
})
|
|
7593
|
+
});
|
|
7648
7594
|
});
|
|
7649
7595
|
}
|
|
7650
7596
|
},
|
|
@@ -7670,7 +7616,7 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
7670
7616
|
if (bundlerConfigs.some(({ plugins })=>plugins?.some(isModuleFederationPlugin))) return void bundlerConfigs.forEach((config)=>{
|
|
7671
7617
|
config.entry = {};
|
|
7672
7618
|
});
|
|
7673
|
-
throw Error(`${
|
|
7619
|
+
throw Error(`${picocolors_default().dim('[rsbuild:config]')} Could not find any entry module, please make sure that ${picocolors_default().yellow('src/index.(ts|js|tsx|jsx|mts|cts|mjs|cjs)')} exists, or customize entry through the ${picocolors_default().yellow('source.entry')} configuration.`);
|
|
7674
7620
|
}
|
|
7675
7621
|
});
|
|
7676
7622
|
}
|
|
@@ -7683,7 +7629,7 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
7683
7629
|
let { sourceMap } = config.output, isProd = 'production' === config.mode;
|
|
7684
7630
|
return !1 !== sourceMap && (!0 === sourceMap ? isProd ? 'source-map' : 'cheap-module-source-map' : void 0 === sourceMap.js ? !isProd && 'cheap-module-source-map' : sourceMap.js);
|
|
7685
7631
|
})(config);
|
|
7686
|
-
chain.devtool(devtool), isDev && 'web' === target
|
|
7632
|
+
chain.devtool(devtool), isDev && 'web' === target ? chain.output.devtoolModuleFilenameTemplate((info)=>toPosixPath(info.absoluteResourcePath)) : chain.output.devtoolModuleFilenameTemplate('[relative-resource-path]'), !devtool && ((config)=>{
|
|
7687
7633
|
let { sourceMap } = config.output;
|
|
7688
7634
|
return 'object' == typeof sourceMap && sourceMap.css;
|
|
7689
7635
|
})(config) && chain.plugin('source-map-css').use(bundler.SourceMapDevToolPlugin, [
|
|
@@ -7700,13 +7646,11 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
7700
7646
|
setup (api) {
|
|
7701
7647
|
let cacheEnabled = !1;
|
|
7702
7648
|
api.modifyBundlerChain(async (chain, { environment, env })=>{
|
|
7703
|
-
let { config } = environment, {
|
|
7649
|
+
let { config } = environment, { buildCache = !1 } = config.performance;
|
|
7704
7650
|
if (!1 === buildCache) return;
|
|
7705
7651
|
cacheEnabled = !0;
|
|
7706
|
-
let { context } = api, cacheConfig = 'boolean' == typeof buildCache ? {} : buildCache, cacheDirectory = getCacheDirectory(cacheConfig, context), buildDependencies = await getBuildDependencies(context, config, environment, cacheConfig.buildDependencies)
|
|
7707
|
-
|
|
7708
|
-
let cacheVersion = Array.isArray(cacheConfig.cacheDigest) && cacheConfig.cacheDigest.length ? `${environment.name}-${env}-${await helpers_hash(JSON.stringify(cacheConfig.cacheDigest))}` : `${environment.name}-${env}`;
|
|
7709
|
-
'rspack' === bundlerType ? (chain.cache(!0), chain.experiments({
|
|
7652
|
+
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}`;
|
|
7653
|
+
chain.cache(!0), chain.experiments({
|
|
7710
7654
|
...chain.get('experiments'),
|
|
7711
7655
|
cache: {
|
|
7712
7656
|
type: 'persistent',
|
|
@@ -7717,14 +7661,9 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
7717
7661
|
},
|
|
7718
7662
|
buildDependencies: Object.values(buildDependencies).flat()
|
|
7719
7663
|
}
|
|
7720
|
-
})) : chain.cache({
|
|
7721
|
-
name: cacheVersion,
|
|
7722
|
-
type: 'filesystem',
|
|
7723
|
-
cacheDirectory,
|
|
7724
|
-
buildDependencies
|
|
7725
7664
|
});
|
|
7726
7665
|
}), api.onAfterCreateCompiler(()=>{
|
|
7727
|
-
cacheEnabled &&
|
|
7666
|
+
cacheEnabled && src_logger.debug('Rspack persistent cache enabled');
|
|
7728
7667
|
});
|
|
7729
7668
|
}
|
|
7730
7669
|
},
|
|
@@ -7768,10 +7707,10 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
7768
7707
|
} : external_node_path_.posix.join(jsPath, jsFilename)).chunkFilename(isJsFilenameFn ? (...args)=>{
|
|
7769
7708
|
let name = jsFilename(...args);
|
|
7770
7709
|
return external_node_path_.posix.join(jsAsyncPath, name);
|
|
7771
|
-
} : external_node_path_.posix.join(jsAsyncPath, jsFilename)).publicPath(publicPath)
|
|
7710
|
+
} : external_node_path_.posix.join(jsAsyncPath, jsFilename)).publicPath(publicPath), isServer && chain.output.library({
|
|
7772
7711
|
type: 'commonjs2',
|
|
7773
7712
|
...chain.output.get('library') || {}
|
|
7774
|
-
}), config.output.copy
|
|
7713
|
+
}), config.output.copy) {
|
|
7775
7714
|
let { copy } = config.output, options = Array.isArray(copy) ? {
|
|
7776
7715
|
patterns: copy
|
|
7777
7716
|
} : copy;
|
|
@@ -7806,9 +7745,9 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
7806
7745
|
chain,
|
|
7807
7746
|
config,
|
|
7808
7747
|
rootPath: api.context.rootPath
|
|
7809
|
-
}), chain.module.rule(CHAIN_ID.RULE.MJS).test(/\.m?js/).resolve.set('fullySpecified', !1)
|
|
7810
|
-
let aliasStrategy = config.
|
|
7811
|
-
tsconfigPath && '
|
|
7748
|
+
}), chain.module.rule(CHAIN_ID.RULE.MJS).test(/\.m?js/).resolve.set('fullySpecified', !1);
|
|
7749
|
+
let { aliasStrategy } = config.resolve;
|
|
7750
|
+
tsconfigPath && 'prefer-tsconfig' === aliasStrategy && chain.resolve.tsConfig({
|
|
7812
7751
|
configFile: tsconfigPath,
|
|
7813
7752
|
references: 'auto'
|
|
7814
7753
|
});
|
|
@@ -7844,7 +7783,7 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
7844
7783
|
})).catch((err)=>{
|
|
7845
7784
|
src_logger.warn('Failed to print file size.'), src_logger.warn(err);
|
|
7846
7785
|
});
|
|
7847
|
-
logs && src_logger.log(logs.join('
|
|
7786
|
+
logs && src_logger.log(logs.join('')), showDiff && await saveSnapshots(snapshotPath, nextSnapshots);
|
|
7848
7787
|
});
|
|
7849
7788
|
}
|
|
7850
7789
|
},
|
|
@@ -7858,7 +7797,7 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
7858
7797
|
return 'auto' === enable ? isDev && !config.dev.writeToDisk ? void 0 : isStrictSubdir(rootPath, distPath) ? {
|
|
7859
7798
|
path: distPath,
|
|
7860
7799
|
keep
|
|
7861
|
-
} : (src_logger.warn('The dist path is not a subdir of root path, Rsbuild will not empty it.'), src_logger.warn(`Please set ${
|
|
7800
|
+
} : (src_logger.warn('The dist path is not a subdir of root path, Rsbuild will not empty it.'), src_logger.warn(`Please set ${picocolors_default().yellow('`output.cleanDistPath`')} config manually.`), src_logger.warn(`Current root path: ${picocolors_default().dim(rootPath)}`), void src_logger.warn(`Current dist path: ${picocolors_default().dim(distPath)}`)) : !0 === enable ? {
|
|
7862
7801
|
path: distPath,
|
|
7863
7802
|
keep
|
|
7864
7803
|
} : void 0;
|
|
@@ -8028,7 +7967,9 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
8028
7967
|
}, async ({ compilation, environment, sources })=>{
|
|
8029
7968
|
let { config } = environment, { appIcon } = config.html;
|
|
8030
7969
|
if (!appIcon) return;
|
|
8031
|
-
let { lookup } =
|
|
7970
|
+
let { lookup } = await import("./710.js").then((mod)=>({
|
|
7971
|
+
lookup: mod.lookup
|
|
7972
|
+
})), distDir = config.output.distPath.image, manifestFile = appIcon.filename ?? 'manifest.webmanifest', publicPath = getPublicPathFromCompiler(compilation), icons = appIcon.icons.map((icon)=>((icon, distDir, publicPath, lookup)=>{
|
|
8032
7973
|
let { src, size } = icon, cacheKey = `${distDir}|${publicPath}|${src}`, cached = iconFormatMap.get(cacheKey);
|
|
8033
7974
|
if (cached) return cached;
|
|
8034
7975
|
let sizes = `${size}x${size}`;
|
|
@@ -8055,16 +7996,16 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
8055
7996
|
})(icon, distDir, publicPath, lookup)), tags = [];
|
|
8056
7997
|
for (let icon of icons){
|
|
8057
7998
|
if ('web-app-manifest' === icon.target && !appIcon.name) {
|
|
8058
|
-
addCompilationError(compilation, `${
|
|
7999
|
+
addCompilationError(compilation, `${picocolors_default().dim('[rsbuild:app-icon]')} ${picocolors_default().yellow('"appIcon.name"')} is required when ${picocolors_default().yellow('"target"')} is ${picocolors_default().yellow('"web-app-manifest"')}.`);
|
|
8059
8000
|
continue;
|
|
8060
8001
|
}
|
|
8061
8002
|
if (!icon.isURL) {
|
|
8062
8003
|
if (!compilation.inputFileSystem) {
|
|
8063
|
-
addCompilationError(compilation, `${
|
|
8004
|
+
addCompilationError(compilation, `${picocolors_default().dim('[rsbuild:app-icon]')} Failed to read the icon file as ${picocolors_default().yellow('"compilation.inputFileSystem"')} is not available.`);
|
|
8064
8005
|
continue;
|
|
8065
8006
|
}
|
|
8066
8007
|
if (!await fileExistsByCompilation(compilation, icon.absolutePath)) {
|
|
8067
|
-
addCompilationError(compilation, `${
|
|
8008
|
+
addCompilationError(compilation, `${picocolors_default().dim('[rsbuild:app-icon]')} Failed to find the icon file at ${picocolors_default().yellow(icon.absolutePath)}.`);
|
|
8068
8009
|
continue;
|
|
8069
8010
|
}
|
|
8070
8011
|
let source = await readFileAsync(compilation.inputFileSystem, icon.absolutePath);
|
|
@@ -8120,7 +8061,7 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
8120
8061
|
name: 'rsbuild:wasm',
|
|
8121
8062
|
setup (api) {
|
|
8122
8063
|
api.modifyBundlerChain((chain, { CHAIN_ID, environment, isProd })=>{
|
|
8123
|
-
let { config } = environment, distPath = config.output.distPath.wasm, filename = external_node_path_.posix.join(distPath,
|
|
8064
|
+
let { config } = environment, distPath = config.output.distPath.wasm, filename = external_node_path_.posix.join(distPath, getFilename(config, 'wasm', isProd));
|
|
8124
8065
|
chain.experiments({
|
|
8125
8066
|
...chain.get('experiments'),
|
|
8126
8067
|
asyncWebAssembly: !0
|
|
@@ -8155,7 +8096,7 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
8155
8096
|
raw: !0
|
|
8156
8097
|
}, ({ code, emitFile, resourcePath })=>{
|
|
8157
8098
|
let name, filename = (name = resourcePath && external_node_path_.default.parse(resourcePath).name) ? `${name}.node` : null;
|
|
8158
|
-
if (null === filename) throw Error(`${
|
|
8099
|
+
if (null === filename) throw Error(`${picocolors_default().dim('[rsbuild:node-addons]')} Failed to load Node.js addon: ${picocolors_default().yellow(resourcePath)}`);
|
|
8159
8100
|
emitFile(filename, code);
|
|
8160
8101
|
let config = api.getNormalizedConfig(), handleErrorSnippet = `throw new Error('Failed to load Node.js addon: "${filename}"', {
|
|
8161
8102
|
cause: error,
|
|
@@ -8236,7 +8177,7 @@ try {
|
|
|
8236
8177
|
});
|
|
8237
8178
|
rule.use(CHAIN_ID.USE.STYLE).loader(getCompiledPath('style-loader')).options(styleLoaderOptions);
|
|
8238
8179
|
} else rule.use(CHAIN_ID.USE.MINI_CSS_EXTRACT).loader((cssExtractPlugin || rspack_rspack.CssExtractRspackPlugin).loader).options(config.tools.cssExtract.loaderOptions);
|
|
8239
|
-
else rule.use(CHAIN_ID.USE.IGNORE_CSS).loader(external_node_path_.default.join(
|
|
8180
|
+
else rule.use(CHAIN_ID.USE.IGNORE_CSS).loader(external_node_path_.default.join(dirname, 'ignoreCssLoader.mjs'));
|
|
8240
8181
|
let importLoaders = {
|
|
8241
8182
|
normal: 0,
|
|
8242
8183
|
inline: 0
|
|
@@ -8245,15 +8186,15 @@ try {
|
|
|
8245
8186
|
}, cssLoaderPath = getCompiledPath('css-loader');
|
|
8246
8187
|
if (updateRules((rule)=>{
|
|
8247
8188
|
rule.use(CHAIN_ID.USE.CSS).loader(cssLoaderPath);
|
|
8248
|
-
}),
|
|
8189
|
+
}), !1 !== config.tools.lightningcssLoader) {
|
|
8249
8190
|
emitCss && importLoaders.normal++, importLoaders.inline++;
|
|
8250
|
-
let
|
|
8191
|
+
let minifyCss = parseMinifyOptions(config).minifyCss, { browserslist } = environment;
|
|
8251
8192
|
if ('node' === target) {
|
|
8252
8193
|
let webEnvironment = Object.values(environments).find((env)=>'web' === env.config.output.target);
|
|
8253
|
-
webEnvironment
|
|
8194
|
+
webEnvironment && (browserslist = webEnvironment.browserslist, minifyCss = parseMinifyOptions(webEnvironment.config).minifyCss);
|
|
8254
8195
|
}
|
|
8255
8196
|
updateRules((rule, type)=>{
|
|
8256
|
-
let
|
|
8197
|
+
let minify = ('inline' === type || config.output.injectStyles) && minifyCss, lightningcssOptions = getLightningCSSLoaderOptions(config, browserslist, minify);
|
|
8257
8198
|
rule.use(CHAIN_ID.USE.LIGHTNINGCSS).loader('builtin:lightningcss-loader').options(lightningcssOptions);
|
|
8258
8199
|
}, {
|
|
8259
8200
|
skipNormal: !emitCss
|
|
@@ -8344,36 +8285,11 @@ try {
|
|
|
8344
8285
|
{
|
|
8345
8286
|
name: 'rsbuild:minimize',
|
|
8346
8287
|
setup (api) {
|
|
8347
|
-
let isRspack = 'rspack' === api.context.bundlerType;
|
|
8348
8288
|
api.modifyBundlerChain((chain, { environment, CHAIN_ID, rspack })=>{
|
|
8349
8289
|
let { config } = environment, { minifyJs, minifyCss, jsOptions, cssOptions } = parseMinifyOptions(config);
|
|
8350
|
-
if (chain.optimization.minimize(minifyJs || minifyCss), minifyJs &&
|
|
8351
|
-
(
|
|
8352
|
-
|
|
8353
|
-
options.minimizerOptions ||= {}, options.minimizerOptions.format ||= {};
|
|
8354
|
-
let { removeConsole } = config.performance;
|
|
8355
|
-
if (!0 === removeConsole) options.minimizerOptions.compress = {
|
|
8356
|
-
drop_console: !0
|
|
8357
|
-
};
|
|
8358
|
-
else if (Array.isArray(removeConsole)) {
|
|
8359
|
-
let pureFuncs = removeConsole.map((method)=>`console.${method}`);
|
|
8360
|
-
options.minimizerOptions.compress = {
|
|
8361
|
-
pure_funcs: pureFuncs
|
|
8362
|
-
};
|
|
8363
|
-
}
|
|
8364
|
-
if (config.output.legalComments) switch(config.output.legalComments){
|
|
8365
|
-
case 'inline':
|
|
8366
|
-
options.minimizerOptions.format.comments = 'some', options.extractComments = !1;
|
|
8367
|
-
break;
|
|
8368
|
-
case 'linked':
|
|
8369
|
-
options.extractComments = !0;
|
|
8370
|
-
break;
|
|
8371
|
-
case 'none':
|
|
8372
|
-
options.minimizerOptions.format.comments = !1, options.extractComments = !1;
|
|
8373
|
-
}
|
|
8374
|
-
return (options.minimizerOptions.format.asciiOnly = 'ascii' === config.output.charset, jsOptions) ? cjs_default()(options, jsOptions) : options;
|
|
8375
|
-
})(config, jsOptions)
|
|
8376
|
-
]).end(), minifyCss && isRspack) {
|
|
8290
|
+
if (chain.optimization.minimize(minifyJs || minifyCss), minifyJs && chain.optimization.minimizer(CHAIN_ID.MINIMIZER.JS).use(rspack.SwcJsMinimizerRspackPlugin, [
|
|
8291
|
+
getSwcMinimizerOptions(config, jsOptions)
|
|
8292
|
+
]).end(), minifyCss) {
|
|
8377
8293
|
let loaderOptions = getLightningCSSLoaderOptions(config, environment.browserslist, !0), defaultOptions = {
|
|
8378
8294
|
minimizerOptions: {
|
|
8379
8295
|
targets: isPlainObject(loaderOptions.targets) ? environment.browserslist : loaderOptions.targets,
|
|
@@ -8398,7 +8314,7 @@ try {
|
|
|
8398
8314
|
{
|
|
8399
8315
|
name: 'rsbuild:progress',
|
|
8400
8316
|
setup (api) {
|
|
8401
|
-
|
|
8317
|
+
api.modifyBundlerChain((chain, { CHAIN_ID, environment, rspack })=>{
|
|
8402
8318
|
let { config } = environment, options = config.dev.progressBar;
|
|
8403
8319
|
if (!options) return;
|
|
8404
8320
|
let prefix = !0 !== options && void 0 !== options.id ? options.id : environment.name;
|
|
@@ -8429,12 +8345,12 @@ try {
|
|
|
8429
8345
|
"application/javascript"
|
|
8430
8346
|
]
|
|
8431
8347
|
});
|
|
8432
|
-
|
|
8348
|
+
applyScriptCondition({
|
|
8433
8349
|
rule,
|
|
8434
8350
|
isDev,
|
|
8435
8351
|
config,
|
|
8436
8352
|
rsbuildTarget: target
|
|
8437
|
-
})
|
|
8353
|
+
});
|
|
8438
8354
|
let swcConfig = getDefaultSwcConfig({
|
|
8439
8355
|
browserslist,
|
|
8440
8356
|
cacheRoot,
|
|
@@ -8445,8 +8361,8 @@ try {
|
|
|
8445
8361
|
let { polyfill } = config.output;
|
|
8446
8362
|
if ('off' !== polyfill) {
|
|
8447
8363
|
swcConfig.env.mode = polyfill;
|
|
8448
|
-
let coreJsDir = applyCoreJs(swcConfig, polyfill);
|
|
8449
|
-
for (let item of [
|
|
8364
|
+
let coreJsDir = applyCoreJs(swcConfig, polyfill, api.context.rootPath);
|
|
8365
|
+
if (coreJsDir) for (let item of [
|
|
8450
8366
|
rule,
|
|
8451
8367
|
dataUriRule
|
|
8452
8368
|
])item.resolve.alias.set('core-js', coreJsDir);
|
|
@@ -8496,9 +8412,7 @@ try {
|
|
|
8496
8412
|
let { config } = environment, defaultConfig = {
|
|
8497
8413
|
chunks: config.moduleFederation?.options?.exposes ? 'async' : 'all',
|
|
8498
8414
|
cacheGroups: {}
|
|
8499
|
-
};
|
|
8500
|
-
'webpack' === api.context.bundlerType && (defaultConfig.enforceSizeThreshold = 50000);
|
|
8501
|
-
let { chunkSplit } = config.performance, forceSplittingGroups = {};
|
|
8415
|
+
}, { chunkSplit } = config.performance, forceSplittingGroups = {};
|
|
8502
8416
|
chunkSplit.forceSplitting && (forceSplittingGroups = getForceSplittingGroups(chunkSplit.forceSplitting, chunkSplit.strategy));
|
|
8503
8417
|
let override = 'custom' === chunkSplit.strategy ? chunkSplit.splitChunks ?? chunkSplit.override : chunkSplit.override, splitChunksOptions = await SPLIT_STRATEGY_DISPATCHER[chunkSplit.strategy || 'split-by-experience']({
|
|
8504
8418
|
defaultConfig,
|
|
@@ -8595,9 +8509,9 @@ try {
|
|
|
8595
8509
|
api.onBeforeCreateCompiler(async ({ bundlerConfigs })=>{
|
|
8596
8510
|
let packagePath, module;
|
|
8597
8511
|
if ('true' !== process.env.RSDOCTOR) return;
|
|
8598
|
-
let
|
|
8512
|
+
let pluginName = 'RsdoctorRspackPlugin', isRsdoctorPlugin = (plugin)=>plugin?.isRsdoctorPlugin === !0 || plugin?.constructor?.name === pluginName;
|
|
8599
8513
|
for (let config of bundlerConfigs)if (config.plugins?.some((plugin)=>isRsdoctorPlugin(plugin))) return;
|
|
8600
|
-
let packageName =
|
|
8514
|
+
let packageName = '@rsdoctor/rspack-plugin';
|
|
8601
8515
|
try {
|
|
8602
8516
|
packagePath = rsdoctor_require.resolve(packageName, {
|
|
8603
8517
|
paths: [
|
|
@@ -8605,19 +8519,19 @@ try {
|
|
|
8605
8519
|
]
|
|
8606
8520
|
});
|
|
8607
8521
|
} catch {
|
|
8608
|
-
src_logger.warn(`\`process.env.RSDOCTOR\` enabled, please install ${
|
|
8522
|
+
src_logger.warn(`\`process.env.RSDOCTOR\` enabled, please install ${picocolors_default().bold(picocolors_default().yellow(packageName))} package.`);
|
|
8609
8523
|
return;
|
|
8610
8524
|
}
|
|
8611
8525
|
try {
|
|
8612
8526
|
let moduleURL = isWindows ? (0, external_node_url_.pathToFileURL)(packagePath).href : packagePath;
|
|
8613
8527
|
module = await import(moduleURL);
|
|
8614
8528
|
} catch {
|
|
8615
|
-
src_logger.error(`\`process.env.RSDOCTOR\` enabled, but failed to load ${
|
|
8529
|
+
src_logger.error(`\`process.env.RSDOCTOR\` enabled, but failed to load ${picocolors_default().bold(picocolors_default().yellow(packageName))} module.`);
|
|
8616
8530
|
return;
|
|
8617
8531
|
}
|
|
8618
8532
|
if (module && module[pluginName]) {
|
|
8619
8533
|
for (let config of bundlerConfigs)config.plugins ||= [], config.plugins.push(new module[pluginName]());
|
|
8620
|
-
src_logger.info(`${
|
|
8534
|
+
src_logger.info(`${picocolors_default().bold(picocolors_default().yellow(packageName))} enabled.`);
|
|
8621
8535
|
}
|
|
8622
8536
|
});
|
|
8623
8537
|
}
|
|
@@ -8682,31 +8596,6 @@ try {
|
|
|
8682
8596
|
});
|
|
8683
8597
|
}
|
|
8684
8598
|
},
|
|
8685
|
-
{
|
|
8686
|
-
name: 'rsbuild:performance',
|
|
8687
|
-
setup (api) {
|
|
8688
|
-
api.modifyRsbuildConfig({
|
|
8689
|
-
order: 'post',
|
|
8690
|
-
handler: (rsbuildConfig)=>{
|
|
8691
|
-
let applyBundleAnalyzeConfig = (config)=>{
|
|
8692
|
-
config.performance?.bundleAnalyze ? config.performance.bundleAnalyze = {
|
|
8693
|
-
generateStatsFile: !0,
|
|
8694
|
-
...config.performance.bundleAnalyze || {}
|
|
8695
|
-
} : (config.performance ??= {}, config.performance.bundleAnalyze = {
|
|
8696
|
-
analyzerMode: 'disabled',
|
|
8697
|
-
generateStatsFile: !0
|
|
8698
|
-
});
|
|
8699
|
-
};
|
|
8700
|
-
if (rsbuildConfig.performance?.profile) applyBundleAnalyzeConfig(rsbuildConfig);
|
|
8701
|
-
else if (rsbuildConfig.environments) for (let config of Object.values(rsbuildConfig.environments))config.performance?.profile && applyBundleAnalyzeConfig(config);
|
|
8702
|
-
}
|
|
8703
|
-
}), api.modifyBundlerChain((chain, { environment })=>{
|
|
8704
|
-
let { config } = environment, { profile } = config.performance;
|
|
8705
|
-
profile && chain.profile(profile);
|
|
8706
|
-
});
|
|
8707
|
-
}
|
|
8708
|
-
},
|
|
8709
|
-
pluginBundleAnalyzer(),
|
|
8710
8599
|
{
|
|
8711
8600
|
name: 'rsbuild:server',
|
|
8712
8601
|
setup (api) {
|
|
@@ -8721,21 +8610,21 @@ try {
|
|
|
8721
8610
|
};
|
|
8722
8611
|
api.onAfterStartDevServer(onStartServer), api.onAfterStartProdServer(onStartServer), api.onBeforeBuild(async ({ isFirstCompile, environments })=>{
|
|
8723
8612
|
if (isFirstCompile) for (let { name: publicDir, copyOnBuild } of api.getNormalizedConfig().server.publicDir){
|
|
8724
|
-
if (!1 === copyOnBuild || !
|
|
8613
|
+
if (!1 === copyOnBuild || !external_node_fs_.default.existsSync(publicDir)) continue;
|
|
8725
8614
|
let distPaths = dedupeNestedPaths(Object.values(environments).filter(({ config })=>!0 === copyOnBuild || 'auto' === copyOnBuild && 'node' !== config.output.target).map(({ distPath })=>distPath));
|
|
8726
8615
|
try {
|
|
8727
8616
|
await Promise.all(distPaths.map(async (distPath)=>{
|
|
8728
|
-
isDeno &&
|
|
8617
|
+
isDeno && external_node_fs_.default.existsSync(distPath) && await external_node_fs_.default.promises.rm(distPath, {
|
|
8729
8618
|
recursive: !0,
|
|
8730
8619
|
force: !0
|
|
8731
|
-
}), await
|
|
8620
|
+
}), await external_node_fs_.default.promises.cp(publicDir, distPath, {
|
|
8732
8621
|
recursive: !0,
|
|
8733
8622
|
dereference: !0,
|
|
8734
|
-
mode:
|
|
8623
|
+
mode: external_node_fs_.default.constants.COPYFILE_FICLONE
|
|
8735
8624
|
});
|
|
8736
8625
|
}));
|
|
8737
8626
|
} catch (err) {
|
|
8738
|
-
throw err instanceof Error && (err.message = `Failed to copy public directory '${
|
|
8627
|
+
throw err instanceof Error && (err.message = `Failed to copy public directory '${picocolors_default().yellow(publicDir)}' to output directory. To disable public directory copying, set \`${picocolors_default().cyan('server.publicDir: false')}\` in your config.\n${err.message}`), err;
|
|
8739
8628
|
}
|
|
8740
8629
|
}
|
|
8741
8630
|
});
|
|
@@ -8745,10 +8634,10 @@ try {
|
|
|
8745
8634
|
name: 'rsbuild:manifest',
|
|
8746
8635
|
setup (api) {
|
|
8747
8636
|
let manifestFilenames = new Map();
|
|
8748
|
-
api.modifyBundlerChain((chain, { CHAIN_ID, environment, isDev })=>{
|
|
8637
|
+
api.modifyBundlerChain(async (chain, { CHAIN_ID, environment, isDev })=>{
|
|
8749
8638
|
let { output: { manifest }, dev: { writeToDisk } } = environment.config;
|
|
8750
8639
|
if (!1 === manifest) return;
|
|
8751
|
-
let manifestOptions = normalizeManifestObjectConfig(manifest), { RspackManifestPlugin } =
|
|
8640
|
+
let manifestOptions = normalizeManifestObjectConfig(manifest), { RspackManifestPlugin } = await import("./manifest-plugin.js").then(__webpack_require__.bind(__webpack_require__, "../../node_modules/.pnpm/rspack-manifest-plugin@5.2.0_@rspack+core@1.7.2_@swc+helpers@0.5.18_/node_modules/rspack-manifest-plugin/dist/index.js")), { htmlPaths } = environment, filter = manifestOptions.filter ?? ((file)=>!file.name.endsWith('.LICENSE.txt'));
|
|
8752
8641
|
manifestFilenames.set(environment.name, manifestOptions.filename);
|
|
8753
8642
|
let pluginOptions = {
|
|
8754
8643
|
fileName: manifestOptions.filename,
|
|
@@ -8805,7 +8694,7 @@ try {
|
|
|
8805
8694
|
manifestData
|
|
8806
8695
|
});
|
|
8807
8696
|
if (isObject(generatedManifest)) return environment.manifest = generatedManifest, generatedManifest;
|
|
8808
|
-
throw Error(`${
|
|
8697
|
+
throw Error(`${picocolors_default().dim('[rsbuild:manifest]')} \`manifest.generate\` function must return a valid manifest object.`);
|
|
8809
8698
|
}
|
|
8810
8699
|
return environment.manifest = manifestData, manifestData;
|
|
8811
8700
|
}
|
|
@@ -8816,7 +8705,7 @@ try {
|
|
|
8816
8705
|
}), api.onAfterCreateCompiler(()=>{
|
|
8817
8706
|
if (manifestFilenames.size <= 1) return void manifestFilenames.clear();
|
|
8818
8707
|
let environmentNames = Array.from(manifestFilenames.keys()), filenames = Array.from(manifestFilenames.values());
|
|
8819
|
-
new Set(filenames).size !== filenames.length && src_logger.warn(`${
|
|
8708
|
+
new Set(filenames).size !== filenames.length && src_logger.warn(`${picocolors_default().dim('[rsbuild:manifest]')} The ${picocolors_default().yellow('"manifest.filename"')} option must be unique when there are multiple environments (${environmentNames.join(', ')}), otherwise the manifest file will be overwritten.`), manifestFilenames.clear();
|
|
8820
8709
|
});
|
|
8821
8710
|
}
|
|
8822
8711
|
},
|
|
@@ -8824,9 +8713,7 @@ try {
|
|
|
8824
8713
|
{
|
|
8825
8714
|
name: 'rsbuild:rspack-profile',
|
|
8826
8715
|
setup (api) {
|
|
8827
|
-
let traceOutput;
|
|
8828
|
-
if ('webpack' === api.context.bundlerType) return;
|
|
8829
|
-
let { RSPACK_PROFILE } = process.env;
|
|
8716
|
+
let traceOutput, { RSPACK_PROFILE } = process.env;
|
|
8830
8717
|
if (!RSPACK_PROFILE) return;
|
|
8831
8718
|
let onStart = async ()=>{
|
|
8832
8719
|
traceOutput = await applyProfile(api.context.rootPath, RSPACK_PROFILE, process.env.RSPACK_TRACE_LAYER, process.env.RSPACK_TRACE_OUTPUT);
|
|
@@ -8834,7 +8721,7 @@ try {
|
|
|
8834
8721
|
api.onBeforeBuild(async ({ isFirstCompile })=>{
|
|
8835
8722
|
isFirstCompile && await onStart();
|
|
8836
8723
|
}), api.onBeforeStartDevServer(onStart), api.onExit(()=>{
|
|
8837
|
-
traceOutput && (rspack_rspack.experiments.globalTrace.cleanup(), src_logger.info(`profile file saved to ${
|
|
8724
|
+
traceOutput && (rspack_rspack.experiments.globalTrace.cleanup(), src_logger.info(`profile file saved to ${picocolors_default().cyan(traceOutput)}`));
|
|
8838
8725
|
});
|
|
8839
8726
|
}
|
|
8840
8727
|
},
|
|
@@ -8843,7 +8730,7 @@ try {
|
|
|
8843
8730
|
apply: 'serve',
|
|
8844
8731
|
setup (api) {
|
|
8845
8732
|
api.modifyBundlerChain((chain, { environment, target })=>{
|
|
8846
|
-
if ('web' !== target
|
|
8733
|
+
if ('web' !== target) return;
|
|
8847
8734
|
let { config } = environment, options = config.dev?.lazyCompilation;
|
|
8848
8735
|
if (options) {
|
|
8849
8736
|
if (!0 === options && Object.keys(chain.entryPoints.entries() || {}).length <= 1) return void chain.lazyCompilation({
|
|
@@ -8863,7 +8750,6 @@ try {
|
|
|
8863
8750
|
name: 'rsbuild:sri',
|
|
8864
8751
|
setup (api) {
|
|
8865
8752
|
api.modifyBundlerChain((chain, { environment, CHAIN_ID, rspack })=>{
|
|
8866
|
-
if ('webpack' === api.context.bundlerType) return;
|
|
8867
8753
|
let { config, htmlPaths } = environment;
|
|
8868
8754
|
if (0 === Object.keys(htmlPaths).length) return;
|
|
8869
8755
|
let { sri } = config.security;
|
|
@@ -8890,7 +8776,7 @@ try {
|
|
|
8890
8776
|
let nonce = nonces[index], environment = environmentList.find((item)=>item.index === index);
|
|
8891
8777
|
if (!Object.keys(environment?.htmlPaths ?? {}).length || !nonce) return;
|
|
8892
8778
|
let injectCode = createVirtualModule(`__webpack_nonce__ = "${nonce}";`);
|
|
8893
|
-
new
|
|
8779
|
+
new rspack_rspack.EntryPlugin(compiler.context, injectCode, {
|
|
8894
8780
|
name: void 0
|
|
8895
8781
|
}).apply(compiler);
|
|
8896
8782
|
});
|
|
@@ -8947,17 +8833,31 @@ async function createRsbuild(options = {}) {
|
|
|
8947
8833
|
context.getPluginAPI = getPluginAPI;
|
|
8948
8834
|
let globalPluginAPI = getPluginAPI();
|
|
8949
8835
|
src_logger.debug('registering default plugins'), applyDefaultPlugins(pluginManager, context), src_logger.debug('default plugins registered');
|
|
8950
|
-
let
|
|
8951
|
-
|
|
8952
|
-
|
|
8953
|
-
|
|
8954
|
-
|
|
8955
|
-
|
|
8836
|
+
let createCompiler = async ()=>(initAction(), (await createCompiler_createCompiler({
|
|
8837
|
+
context,
|
|
8838
|
+
pluginManager,
|
|
8839
|
+
rsbuildOptions: resolvedOptions
|
|
8840
|
+
})).compiler), createDevServer = async (options)=>{
|
|
8841
|
+
context.action = 'dev', process.env.NODE_ENV || setNodeEnv('development');
|
|
8842
|
+
let config = await initRsbuildConfig({
|
|
8843
|
+
context,
|
|
8844
|
+
pluginManager
|
|
8845
|
+
});
|
|
8846
|
+
return devServer_createDevServer({
|
|
8847
|
+
context,
|
|
8848
|
+
pluginManager,
|
|
8849
|
+
rsbuildOptions: resolvedOptions
|
|
8850
|
+
}, createCompiler, config, options);
|
|
8851
|
+
}, initAction = ()=>{
|
|
8956
8852
|
context.action || (context.action = 'development' === config.mode ? 'dev' : 'build');
|
|
8957
8853
|
}, rsbuild = {
|
|
8958
|
-
build: async (
|
|
8854
|
+
build: async (options)=>{
|
|
8959
8855
|
context.action = 'build', process.env.NODE_ENV || setNodeEnv('production');
|
|
8960
|
-
let buildInstance = await
|
|
8856
|
+
let buildInstance = await build_build({
|
|
8857
|
+
context,
|
|
8858
|
+
pluginManager,
|
|
8859
|
+
rsbuildOptions: resolvedOptions
|
|
8860
|
+
}, options);
|
|
8961
8861
|
return {
|
|
8962
8862
|
...buildInstance,
|
|
8963
8863
|
close: async ()=>{
|
|
@@ -8972,15 +8872,53 @@ async function createRsbuild(options = {}) {
|
|
|
8972
8872
|
pluginManager
|
|
8973
8873
|
}), { distPath } = context, { checkDistDir = !0 } = options;
|
|
8974
8874
|
if (checkDistDir) {
|
|
8975
|
-
if (!existsSync(distPath)) throw Error(`${
|
|
8976
|
-
if (isEmptyDir(distPath)) throw Error(`${
|
|
8875
|
+
if (!(0, external_node_fs_.existsSync)(distPath)) throw Error(`${picocolors_default().dim('[rsbuild:preview]')} The output directory ${picocolors_default().yellow(distPath)} does not exist, please build the project before previewing.`);
|
|
8876
|
+
if (isEmptyDir(distPath)) throw Error(`${picocolors_default().dim('[rsbuild:preview]')} The output directory ${picocolors_default().yellow(distPath)} is empty, please build the project before previewing.`);
|
|
8977
8877
|
}
|
|
8978
8878
|
return startProdServer(context, config, options);
|
|
8979
8879
|
},
|
|
8980
|
-
startDevServer: (
|
|
8981
|
-
|
|
8982
|
-
|
|
8983
|
-
|
|
8880
|
+
startDevServer: async (options)=>{
|
|
8881
|
+
context.action = 'dev', process.env.NODE_ENV || setNodeEnv('development');
|
|
8882
|
+
let config = await initRsbuildConfig({
|
|
8883
|
+
context,
|
|
8884
|
+
pluginManager
|
|
8885
|
+
});
|
|
8886
|
+
return (await devServer_createDevServer({
|
|
8887
|
+
context,
|
|
8888
|
+
pluginManager,
|
|
8889
|
+
rsbuildOptions: resolvedOptions
|
|
8890
|
+
}, createCompiler, config, options)).listen();
|
|
8891
|
+
},
|
|
8892
|
+
createCompiler,
|
|
8893
|
+
createDevServer,
|
|
8894
|
+
inspectConfig: async (inspectOptions)=>{
|
|
8895
|
+
initAction();
|
|
8896
|
+
let bundlerConfigs = (await initConfigs_initConfigs({
|
|
8897
|
+
context,
|
|
8898
|
+
pluginManager,
|
|
8899
|
+
rsbuildOptions: resolvedOptions
|
|
8900
|
+
})).rspackConfigs;
|
|
8901
|
+
return inspectConfig_inspectConfig({
|
|
8902
|
+
context,
|
|
8903
|
+
pluginManager,
|
|
8904
|
+
rsbuildOptions: resolvedOptions,
|
|
8905
|
+
inspectOptions,
|
|
8906
|
+
bundlerConfigs
|
|
8907
|
+
});
|
|
8908
|
+
},
|
|
8909
|
+
initConfigs: async (options)=>{
|
|
8910
|
+
if (context.action && options?.action && context.action !== options.action) throw Error(`\
|
|
8911
|
+
[rsbuild] initConfigs() can only be called with the same action type.
|
|
8912
|
+
- Expected: ${context.action}
|
|
8913
|
+
- Actual: ${options?.action}`);
|
|
8914
|
+
options?.action && (context.action = options.action);
|
|
8915
|
+
let { rspackConfigs } = await initConfigs_initConfigs({
|
|
8916
|
+
context,
|
|
8917
|
+
pluginManager,
|
|
8918
|
+
rsbuildOptions: resolvedOptions
|
|
8919
|
+
});
|
|
8920
|
+
return rspackConfigs;
|
|
8921
|
+
},
|
|
8984
8922
|
...pick(pluginManager, [
|
|
8985
8923
|
'addPlugins',
|
|
8986
8924
|
'getPlugins',
|
|
@@ -9010,9 +8948,6 @@ async function createRsbuild(options = {}) {
|
|
|
9010
8948
|
'onCloseDevServer',
|
|
9011
8949
|
'onDevCompileDone',
|
|
9012
8950
|
'onExit'
|
|
9013
|
-
]),
|
|
9014
|
-
...pick(providerInstance, [
|
|
9015
|
-
'initConfigs'
|
|
9016
8951
|
])
|
|
9017
8952
|
};
|
|
9018
8953
|
envs && (rsbuild.onCloseBuild(envs.cleanup), rsbuild.onCloseDevServer(envs.cleanup));
|
|
@@ -9041,8 +8976,8 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
|
|
|
9041
8976
|
let configExport, configFilePath = ((root, customConfig)=>{
|
|
9042
8977
|
if (customConfig) {
|
|
9043
8978
|
let customConfigPath = (0, external_node_path_.isAbsolute)(customConfig) ? customConfig : (0, external_node_path_.join)(root, customConfig);
|
|
9044
|
-
if (
|
|
9045
|
-
throw Error(`${
|
|
8979
|
+
if (external_node_fs_.default.existsSync(customConfigPath)) return customConfigPath;
|
|
8980
|
+
throw Error(`${picocolors_default().dim('[rsbuild:loadConfig]')} Cannot find config file: ${picocolors_default().dim(customConfigPath)}`);
|
|
9046
8981
|
}
|
|
9047
8982
|
for (let file of [
|
|
9048
8983
|
'rsbuild.config.mjs',
|
|
@@ -9053,7 +8988,7 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
|
|
|
9053
8988
|
'rsbuild.config.cts'
|
|
9054
8989
|
]){
|
|
9055
8990
|
let configFile = (0, external_node_path_.join)(root, file);
|
|
9056
|
-
if (
|
|
8991
|
+
if (external_node_fs_.default.existsSync(configFile)) return configFile;
|
|
9057
8992
|
}
|
|
9058
8993
|
return null;
|
|
9059
8994
|
})(cwd, path);
|
|
@@ -9068,12 +9003,12 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
|
|
|
9068
9003
|
let configFileURL = (0, external_node_url_.pathToFileURL)(configFilePath).href, exportModule = await import(`${configFileURL}?t=${Date.now()}`);
|
|
9069
9004
|
configExport = exportModule.default ? exportModule.default : exportModule;
|
|
9070
9005
|
} catch (err) {
|
|
9071
|
-
let errorMessage = `Failed to load file with native loader: ${
|
|
9006
|
+
let errorMessage = `Failed to load file with native loader: ${picocolors_default().dim(configFilePath)}`;
|
|
9072
9007
|
if ('native' === loader) throw src_logger.error(errorMessage), err;
|
|
9073
9008
|
src_logger.debug(`${errorMessage}, fallback to jiti.`), src_logger.debug(err);
|
|
9074
9009
|
}
|
|
9075
9010
|
if (void 0 === configExport) try {
|
|
9076
|
-
let { createJiti } = await import("jiti"), jiti = createJiti(
|
|
9011
|
+
let { createJiti } = await import("jiti"), jiti = createJiti(import.meta.filename, {
|
|
9077
9012
|
moduleCache: !1,
|
|
9078
9013
|
interopDefault: !0,
|
|
9079
9014
|
nativeModules: [
|
|
@@ -9085,7 +9020,7 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
|
|
|
9085
9020
|
default: !0
|
|
9086
9021
|
});
|
|
9087
9022
|
} catch (err) {
|
|
9088
|
-
throw src_logger.error(`Failed to load file with jiti: ${
|
|
9023
|
+
throw src_logger.error(`Failed to load file with jiti: ${picocolors_default().dim(configFilePath)}`), err;
|
|
9089
9024
|
}
|
|
9090
9025
|
if ('function' == typeof configExport) {
|
|
9091
9026
|
let command = process.argv[2], nodeEnv = process.env.NODE_ENV || '', result = await configExport({
|
|
@@ -9094,13 +9029,13 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
|
|
|
9094
9029
|
envMode: envMode || nodeEnv,
|
|
9095
9030
|
meta
|
|
9096
9031
|
});
|
|
9097
|
-
if (void 0 === result) throw Error(`${
|
|
9032
|
+
if (void 0 === result) throw Error(`${picocolors_default().dim('[rsbuild:loadConfig]')} The config function must return a config object.`);
|
|
9098
9033
|
return {
|
|
9099
9034
|
content: applyMetaInfo(result),
|
|
9100
9035
|
filePath: configFilePath
|
|
9101
9036
|
};
|
|
9102
9037
|
}
|
|
9103
|
-
if (!isObject(configExport)) throw Error(`${
|
|
9038
|
+
if (!isObject(configExport)) throw Error(`${picocolors_default().dim('[rsbuild:loadConfig]')} The config must be an object or a function that returns an object, get ${picocolors_default().yellow(configExport)}`);
|
|
9104
9039
|
return src_logger.debug('configuration loaded from:', configFilePath), {
|
|
9105
9040
|
content: applyMetaInfo(configExport),
|
|
9106
9041
|
filePath: configFilePath
|
|
@@ -9113,7 +9048,7 @@ let commonOpts = {}, init_loadConfig = async (root)=>{
|
|
|
9113
9048
|
envMode: commonOpts.envMode,
|
|
9114
9049
|
loader: commonOpts.configLoader
|
|
9115
9050
|
});
|
|
9116
|
-
return config.dev ||= {}, config.source ||= {}, config.server ||= {}, commonOpts.base && (config.server.base = commonOpts.base), commonOpts.root && (config.root = root), commonOpts.mode && (config.mode = commonOpts.mode), commonOpts.logLevel && (config.logLevel = commonOpts.logLevel), commonOpts.open && !config.server?.open && (config.server.open = commonOpts.open), commonOpts.host && (config.server.host = commonOpts.host), commonOpts.port && (config.server.port = commonOpts.port), void 0 === config.dev.cliShortcuts && (config.dev.cliShortcuts = !0), filePath && (config.dev.watchFiles = [
|
|
9051
|
+
return config.dev ||= {}, config.source ||= {}, config.server ||= {}, commonOpts.base && (config.server.base = commonOpts.base), commonOpts.root && (config.root = root), commonOpts.mode && (config.mode = commonOpts.mode), commonOpts.logLevel && (config.logLevel = commonOpts.logLevel), commonOpts.open && !config.server?.open && (config.server.open = commonOpts.open), commonOpts.host && (config.server.host = !0 === commonOpts.host ? ALL_INTERFACES_IPV4 : commonOpts.host), commonOpts.port && (config.server.port = commonOpts.port), void 0 === config.dev.cliShortcuts && (config.dev.cliShortcuts = !0), filePath && (config.dev.watchFiles = [
|
|
9117
9052
|
...config.dev.watchFiles ? helpers_castArray(config.dev.watchFiles) : [],
|
|
9118
9053
|
{
|
|
9119
9054
|
paths: filePath,
|
|
@@ -9163,7 +9098,7 @@ let cleaners = [], onBeforeRestartServer = (cleaner)=>{
|
|
|
9163
9098
|
}, beforeRestart = async ({ filePath, clear = !0, id })=>{
|
|
9164
9099
|
if (clear && isTTY() && !process.env.DEBUG && process.stdout.write('\x1B[H\x1B[2J'), filePath) {
|
|
9165
9100
|
let filename = external_node_path_.default.basename(filePath);
|
|
9166
|
-
src_logger.info(`restarting ${id} as ${
|
|
9101
|
+
src_logger.info(`restarting ${id} as ${picocolors_default().yellow(filename)} changed\n`);
|
|
9167
9102
|
} else src_logger.info(`restarting ${id}...\n`);
|
|
9168
9103
|
for (let cleaner of cleaners)await cleaner();
|
|
9169
9104
|
cleaners = [];
|
|
@@ -9207,11 +9142,11 @@ async function watchFilesForRestart({ files, rsbuild, isBuildWatch, watchOptions
|
|
|
9207
9142
|
watcher.on('add', onChange), watcher.on('change', onChange), watcher.on('unlink', onChange);
|
|
9208
9143
|
}
|
|
9209
9144
|
let applyServerOptions = (command)=>{
|
|
9210
|
-
command.option('-o, --open [url]', 'Open the page in browser on startup').option('--port <port>', 'Set the port number for the server').option('--host
|
|
9145
|
+
command.option('-o, --open [url]', 'Open the page in browser on startup').option('--port <port>', 'Set the port number for the server').option('--host [host]', 'Set the host that the server listens to');
|
|
9211
9146
|
};
|
|
9212
9147
|
function setupCommands() {
|
|
9213
9148
|
let cli = ((name = "")=>new CAC(name))('rsbuild');
|
|
9214
|
-
cli.version("
|
|
9149
|
+
cli.version("2.0.0-alpha.0"), 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)', {
|
|
9215
9150
|
default: 'auto'
|
|
9216
9151
|
}).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', {
|
|
9217
9152
|
type: [
|
|
@@ -9219,7 +9154,7 @@ function setupCommands() {
|
|
|
9219
9154
|
],
|
|
9220
9155
|
default: []
|
|
9221
9156
|
}).option('--log-level <level>', 'Set the log level (info | warn | error | silent)').option('-m, --mode <mode>', 'Set the build mode (development | production | none)').option('-r, --root <root>', 'Set the project root directory (absolute path or relative to cwd)').option('--no-env', 'Disable loading of `.env` files');
|
|
9222
|
-
let devDescription = `Start the dev server ${
|
|
9157
|
+
let devDescription = `Start the dev server ${picocolors_default().dim('(default if no command is given)')}`, devCommand = cli.command('', devDescription).alias('dev'), buildCommand = cli.command('build', 'Build the app for production'), previewCommand = cli.command('preview', 'Preview the production build locally'), inspectCommand = cli.command('inspect', 'Inspect the Rspack and Rsbuild configs');
|
|
9223
9158
|
applyServerOptions(devCommand), applyServerOptions(previewCommand), devCommand.action(async (options)=>{
|
|
9224
9159
|
try {
|
|
9225
9160
|
let rsbuild = await init_init({
|
|
@@ -9265,7 +9200,7 @@ function setupCommands() {
|
|
|
9265
9200
|
src_logger.error('Failed to inspect config.'), src_logger.error(err), process.exit(1);
|
|
9266
9201
|
}
|
|
9267
9202
|
}), cli.help((sections)=>{
|
|
9268
|
-
for (let section of (sections.shift(), sections))'Usage' === section.title && (section.body = section.body.replace('$ rsbuild',
|
|
9203
|
+
for (let section of (sections.shift(), sections))'Usage' === section.title && (section.body = section.body.replace('$ rsbuild', picocolors_default().yellow("$ rsbuild [command] [options]"))), 'Commands' === section.title && (section.body = section.body.replace(` ${devDescription}`, `dev ${devDescription}`)), section.title?.startsWith('For more info') ? (section.title = picocolors_default().dim(' For details on a sub-command, run'), section.body = picocolors_default().dim(' $ rsbuild <command> -h')) : section.title = picocolors_default().cyan(section.title);
|
|
9269
9204
|
}), cli.parse();
|
|
9270
9205
|
}
|
|
9271
9206
|
let { argv: cli_argv } = process;
|
|
@@ -9280,7 +9215,7 @@ function initNodeEnv() {
|
|
|
9280
9215
|
}
|
|
9281
9216
|
function showGreeting() {
|
|
9282
9217
|
let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
|
|
9283
|
-
src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild
|
|
9218
|
+
src_logger.greet(`${'npx' === npm_lifecycle_event || isBun || NODE_RUN_SCRIPT_NAME ? '\n' : ''}Rsbuild v2.0.0-alpha.0\n`);
|
|
9284
9219
|
}
|
|
9285
9220
|
function setupLogLevel() {
|
|
9286
9221
|
let logLevelIndex = process.argv.findIndex((item)=>'--log-level' === item || '--logLevel' === item);
|
|
@@ -9301,5 +9236,5 @@ function runCLI() {
|
|
|
9301
9236
|
src_logger.error('Failed to start Rsbuild CLI.'), src_logger.error(err);
|
|
9302
9237
|
}
|
|
9303
9238
|
}
|
|
9304
|
-
let src_version = "
|
|
9305
|
-
export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, external_node_util_promisify, loadConfig_loadConfig as loadConfig, loadEnv, mergeRsbuildConfig,
|
|
9239
|
+
let src_version = "2.0.0-alpha.0";
|
|
9240
|
+
export { PLUGIN_CSS_NAME, PLUGIN_SWC_NAME, createRsbuild, defaultAllowedOrigins, defineConfig, ensureAssetPrefix, external_node_util_promisify, loadConfig_loadConfig as loadConfig, loadEnv, mergeRsbuildConfig, node_os, node_process, rspack_rspack as rspack, runCLI, src_logger as logger, src_version as version };
|