@rsbuild/core 1.7.1 → 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 +1070 -1122
- 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/fs.d.ts +4 -0
- 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/getFileFromUrl.d.ts +1 -2
- 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 +13 -10
- package/dist-types/server/proxy.d.ts +2 -2
- 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 +15 -20
- 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 -9442
- 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
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
/*! For license information please see 131.js.LICENSE.txt */
|
|
2
|
-
"use strict";
|
|
3
2
|
let flagForceColor, swcHelpersPath, pluginHelper_htmlPlugin, cssExtractPlugin;
|
|
4
3
|
import { fileURLToPath as __rspack_fileURLToPath } from "node:url";
|
|
5
4
|
import { createRequire as __rspack_createRequire } from "node:module";
|
|
6
5
|
let __rspack_createRequire_require = __rspack_createRequire(import.meta.url);
|
|
7
6
|
import * as __rspack_external_async_hooks from "async_hooks";
|
|
7
|
+
import * as __rspack_external_events from "events";
|
|
8
8
|
import * as __rspack_external_fs from "fs";
|
|
9
|
+
import * as __rspack_external_node_fs_5ea92f0c from "node:fs";
|
|
9
10
|
import * as __rspack_external_node_module_ab9f2194 from "node:module";
|
|
10
11
|
import * as __rspack_external_node_path_c5b9b54f from "node:path";
|
|
11
12
|
import * as __rspack_external_node_url_e96de089 from "node:url";
|
|
@@ -16,9 +17,7 @@ import { __webpack_require__ } from "./rslib-runtime.js";
|
|
|
16
17
|
import node_process from "node:process";
|
|
17
18
|
import node_os, { constants as external_node_os_constants } from "node:os";
|
|
18
19
|
import node_tty from "node:tty";
|
|
19
|
-
import { EventEmitter } from "events";
|
|
20
20
|
import { promisify as external_node_util_promisify, stripVTControlCharacters } from "node:util";
|
|
21
|
-
import node_fs, { existsSync } from "node:fs";
|
|
22
21
|
import { isPromise, isRegExp } from "node:util/types";
|
|
23
22
|
import node_zlib from "node:zlib";
|
|
24
23
|
__webpack_require__.add({
|
|
@@ -771,8 +770,66 @@ __webpack_require__.add({
|
|
|
771
770
|
return (asyncHooks.AsyncResource && (res = new asyncHooks.AsyncResource(fn.name || 'bound-anonymous-fn')), res && res.runInAsyncScope) ? res.runInAsyncScope.bind(res, fn, null) : fn;
|
|
772
771
|
}
|
|
773
772
|
},
|
|
774
|
-
"../../node_modules/.pnpm/
|
|
775
|
-
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");
|
|
776
833
|
async function processResult(ctx, result) {
|
|
777
834
|
let obj, file = result.filepath || '', projectConfig = ((obj = result.config) && obj.__esModule ? obj : {
|
|
778
835
|
default: obj
|
|
@@ -845,8 +902,8 @@ __webpack_require__.add({
|
|
|
845
902
|
});
|
|
846
903
|
};
|
|
847
904
|
},
|
|
848
|
-
"../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.
|
|
849
|
-
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");
|
|
850
907
|
module.exports = async function options(config, file) {
|
|
851
908
|
if (config.parser && 'string' == typeof config.parser) try {
|
|
852
909
|
config.parser = await req(config.parser, file);
|
|
@@ -866,8 +923,8 @@ __webpack_require__.add({
|
|
|
866
923
|
return config;
|
|
867
924
|
};
|
|
868
925
|
},
|
|
869
|
-
"../../node_modules/.pnpm/postcss-load-config@6.0.1_jiti@2.6.1_postcss@8.5.6_yaml@2.8.
|
|
870
|
-
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");
|
|
871
928
|
async function load(plugin, options, file) {
|
|
872
929
|
try {
|
|
873
930
|
if (null == options || 0 === Object.keys(options).length) return await req(plugin, file);
|
|
@@ -883,7 +940,7 @@ __webpack_require__.add({
|
|
|
883
940
|
}), list;
|
|
884
941
|
};
|
|
885
942
|
},
|
|
886
|
-
"../../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__) {
|
|
887
944
|
let tsx, jiti;
|
|
888
945
|
var __filename = __rspack_fileURLToPath(import.meta.url);
|
|
889
946
|
let { createRequire } = __webpack_require__("node:module"), { pathToFileURL } = __webpack_require__("node:url"), TS_EXT_RE = /\.[mc]?ts$/, importError = [];
|
|
@@ -917,9 +974,15 @@ __webpack_require__.add({
|
|
|
917
974
|
async_hooks (module) {
|
|
918
975
|
module.exports = __rspack_external_async_hooks;
|
|
919
976
|
},
|
|
977
|
+
events (module) {
|
|
978
|
+
module.exports = __rspack_external_events;
|
|
979
|
+
},
|
|
920
980
|
fs (module) {
|
|
921
981
|
module.exports = __rspack_external_fs;
|
|
922
982
|
},
|
|
983
|
+
"node:fs" (module) {
|
|
984
|
+
module.exports = __rspack_external_node_fs_5ea92f0c;
|
|
985
|
+
},
|
|
923
986
|
"node:module" (module) {
|
|
924
987
|
module.exports = __rspack_external_node_module_ab9f2194;
|
|
925
988
|
},
|
|
@@ -939,23 +1002,6 @@ __webpack_require__.add({
|
|
|
939
1002
|
module.exports = __rspack_external_url;
|
|
940
1003
|
}
|
|
941
1004
|
});
|
|
942
|
-
var superClass, superClass1, provider_helpers_namespaceObject = {};
|
|
943
|
-
__webpack_require__.r(provider_helpers_namespaceObject), __webpack_require__.d(provider_helpers_namespaceObject, {
|
|
944
|
-
createDevServer: ()=>devServer_createDevServer,
|
|
945
|
-
formatStats: ()=>formatStats,
|
|
946
|
-
getChainUtils: ()=>getChainUtils,
|
|
947
|
-
getConfigUtils: ()=>getConfigUtils,
|
|
948
|
-
getHTMLPlugin: ()=>pluginHelper_getHTMLPlugin,
|
|
949
|
-
getRsbuildStats: ()=>getRsbuildStats,
|
|
950
|
-
initRsbuildConfig: ()=>initRsbuildConfig,
|
|
951
|
-
inspectConfig: ()=>inspectConfig_inspectConfig,
|
|
952
|
-
modifyBundlerChain: ()=>modifyBundlerChain,
|
|
953
|
-
prettyTime: ()=>prettyTime,
|
|
954
|
-
registerBuildHook: ()=>registerBuildHook,
|
|
955
|
-
registerDevHook: ()=>registerDevHook,
|
|
956
|
-
setCssExtractPlugin: ()=>setCssExtractPlugin,
|
|
957
|
-
setHTMLPlugin: ()=>setHTMLPlugin
|
|
958
|
-
});
|
|
959
1005
|
let external_node_module_ = __webpack_require__("node:module"), rspack_rspack = (0, external_node_module_.createRequire)(import.meta.url)('@rspack/core');
|
|
960
1006
|
function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : node_process.argv) {
|
|
961
1007
|
let prefix = flag.startsWith('-') ? '' : 1 === flag.length ? '-' : '--', position = argv.indexOf(prefix + flag), terminatorPosition = argv.indexOf('--');
|
|
@@ -1128,53 +1174,9 @@ let supportsColor = {
|
|
|
1128
1174
|
}), logger.override = (customLogger)=>{
|
|
1129
1175
|
Object.assign(logger, customLogger);
|
|
1130
1176
|
}, logger;
|
|
1131
|
-
})(),
|
|
1132
|
-
|
|
1133
|
-
|
|
1134
|
-
'firefox >= 78',
|
|
1135
|
-
'safari >= 14'
|
|
1136
|
-
], DEFAULT_BROWSERSLIST = {
|
|
1137
|
-
web: DEFAULT_WEB_BROWSERSLIST,
|
|
1138
|
-
'web-worker': DEFAULT_WEB_BROWSERSLIST,
|
|
1139
|
-
node: [
|
|
1140
|
-
'node >= 16'
|
|
1141
|
-
]
|
|
1142
|
-
}, 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 = [
|
|
1143
|
-
'woff',
|
|
1144
|
-
'woff2',
|
|
1145
|
-
'eot',
|
|
1146
|
-
'ttf',
|
|
1147
|
-
'otf',
|
|
1148
|
-
'ttc'
|
|
1149
|
-
], IMAGE_EXTENSIONS = [
|
|
1150
|
-
'png',
|
|
1151
|
-
'jpg',
|
|
1152
|
-
'jpeg',
|
|
1153
|
-
'pjpeg',
|
|
1154
|
-
'pjp',
|
|
1155
|
-
'gif',
|
|
1156
|
-
'bmp',
|
|
1157
|
-
'webp',
|
|
1158
|
-
'ico',
|
|
1159
|
-
'apng',
|
|
1160
|
-
'avif',
|
|
1161
|
-
'tif',
|
|
1162
|
-
'tiff',
|
|
1163
|
-
'jfif',
|
|
1164
|
-
'cur'
|
|
1165
|
-
], VIDEO_EXTENSIONS = [
|
|
1166
|
-
'mp4',
|
|
1167
|
-
'webm',
|
|
1168
|
-
'ogg',
|
|
1169
|
-
'mov'
|
|
1170
|
-
], AUDIO_EXTENSIONS = [
|
|
1171
|
-
'mp3',
|
|
1172
|
-
'wav',
|
|
1173
|
-
'flac',
|
|
1174
|
-
'aac',
|
|
1175
|
-
'm4a',
|
|
1176
|
-
'opus'
|
|
1177
|
-
], 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 = ()=>{
|
|
1178
1180
|
if (!process.env.DEBUG) return !1;
|
|
1179
1181
|
let values = process.env.DEBUG.toLocaleLowerCase().split(',');
|
|
1180
1182
|
return [
|
|
@@ -1187,6 +1189,14 @@ function getTime() {
|
|
|
1187
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');
|
|
1188
1190
|
return `${hours}:${minutes}:${seconds}`;
|
|
1189
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");
|
|
1190
1200
|
function toArr(any) {
|
|
1191
1201
|
return null == any ? [] : Array.isArray(any) ? any : [
|
|
1192
1202
|
any
|
|
@@ -1236,13 +1246,6 @@ function mri2(args, opts) {
|
|
|
1236
1246
|
if (alibi) for(k in out)for(arr = opts.alias[k] || []; arr.length > 0;)out[arr.shift()] = out[k];
|
|
1237
1247
|
return out;
|
|
1238
1248
|
}
|
|
1239
|
-
isDebug() && (src_logger.level = 'verbose'), src_logger.override({
|
|
1240
|
-
debug: (message, ...args)=>{
|
|
1241
|
-
if ('verbose' !== src_logger.level) return;
|
|
1242
|
-
let time = color.gray(getTime());
|
|
1243
|
-
console.log(` ${color.magenta('rsbuild')} ${time} ${message}`, ...args);
|
|
1244
|
-
}
|
|
1245
|
-
});
|
|
1246
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)=>{
|
|
1247
1250
|
let x, i = 0, length = keys.length, t = obj;
|
|
1248
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) ? {} : [];
|
|
@@ -1389,7 +1392,7 @@ class GlobalCommand extends Command {
|
|
|
1389
1392
|
}
|
|
1390
1393
|
}
|
|
1391
1394
|
var __assign = Object.assign;
|
|
1392
|
-
class CAC extends EventEmitter {
|
|
1395
|
+
class CAC extends external_events_.EventEmitter {
|
|
1393
1396
|
constructor(name = ""){
|
|
1394
1397
|
super(), this.name = name, this.commands = [], this.rawArgs = [], this.args = [], this.options = {}, this.globalCommand = new GlobalCommand(this), this.globalCommand.usage("<command> [options]");
|
|
1395
1398
|
}
|
|
@@ -1497,7 +1500,53 @@ class CAC extends EventEmitter {
|
|
|
1497
1500
|
}), actionArgs.push(options), command.commandAction.apply(this, actionArgs);
|
|
1498
1501
|
}
|
|
1499
1502
|
}
|
|
1500
|
-
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");
|
|
1501
1550
|
var cjs_default = __webpack_require__.n(cjs);
|
|
1502
1551
|
let dist_0 = __webpack_require__("../../node_modules/.pnpm/javascript-stringify@2.1.0/node_modules/javascript-stringify/dist/index.js");
|
|
1503
1552
|
function createMap(superClass) {
|
|
@@ -2265,7 +2314,7 @@ function getFilename(config, type, isProd, isServer) {
|
|
|
2265
2314
|
if (filename.html) return filename.html;
|
|
2266
2315
|
return 'flat' === config.html.outputStructure ? '[name].html' : '[name]/index.html';
|
|
2267
2316
|
default:
|
|
2268
|
-
throw Error(`${
|
|
2317
|
+
throw Error(`${picocolors_default().dim('[rsbuild:config]')} unknown key ${picocolors_default().yellow(type)} in ${picocolors_default().yellow('output.filename')}`);
|
|
2269
2318
|
}
|
|
2270
2319
|
}
|
|
2271
2320
|
function partition(array, predicate) {
|
|
@@ -2286,21 +2335,7 @@ function pick(obj, keys) {
|
|
|
2286
2335
|
for (let key of keys)void 0 !== obj[key] && (result[key] = obj[key]);
|
|
2287
2336
|
return result;
|
|
2288
2337
|
}
|
|
2289
|
-
let
|
|
2290
|
-
let time, time1;
|
|
2291
|
-
if (seconds < 10) {
|
|
2292
|
-
let time, digits = seconds >= 0.01 ? 2 : 3;
|
|
2293
|
-
return `${time = seconds.toFixed(digits), color.bold(time)} s`;
|
|
2294
|
-
}
|
|
2295
|
-
if (seconds < 60) {
|
|
2296
|
-
let time;
|
|
2297
|
-
return `${time = seconds.toFixed(1), color.bold(time)} s`;
|
|
2298
|
-
}
|
|
2299
|
-
let minutes = Math.floor(seconds / 60), minutesLabel = `${(time = minutes.toFixed(0), color.bold(time))} m`, remainingSeconds = seconds % 60;
|
|
2300
|
-
if (0 === remainingSeconds) return minutesLabel;
|
|
2301
|
-
let secondsLabel = `${(time1 = remainingSeconds.toFixed(+(remainingSeconds % 1 != 0)), color.bold(time1))} s`;
|
|
2302
|
-
return `${minutesLabel} ${secondsLabel}`;
|
|
2303
|
-
}, 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;
|
|
2304
2339
|
async function helpers_hash(data) {
|
|
2305
2340
|
let crypto = await import("node:crypto");
|
|
2306
2341
|
return crypto.hash ? crypto.hash('sha256', data, 'hex').slice(0, 16) : crypto.createHash('sha256').update(data).digest('hex').slice(0, 16);
|
|
@@ -2311,253 +2346,7 @@ let compiler_isMultiCompiler = (compiler)=>'compilers' in compiler && Array.isAr
|
|
|
2311
2346
|
}, applyToCompiler = (compiler, apply)=>{
|
|
2312
2347
|
compiler_isMultiCompiler(compiler) ? compiler.compilers.forEach(apply) : apply(compiler, 0);
|
|
2313
2348
|
}, addCompilationError = (compilation, message)=>{
|
|
2314
|
-
compilation.errors.push(new
|
|
2315
|
-
};
|
|
2316
|
-
function createEnvironmentAsyncHook() {
|
|
2317
|
-
let preGroup = [], postGroup = [], defaultGroup = [], tapEnvironment = ({ environment, handler: cb })=>{
|
|
2318
|
-
isFunction(cb) ? defaultGroup.push({
|
|
2319
|
-
environment,
|
|
2320
|
-
handler: cb
|
|
2321
|
-
}) : 'pre' === cb.order ? preGroup.push({
|
|
2322
|
-
environment,
|
|
2323
|
-
handler: cb.handler
|
|
2324
|
-
}) : 'post' === cb.order ? postGroup.push({
|
|
2325
|
-
environment,
|
|
2326
|
-
handler: cb.handler
|
|
2327
|
-
}) : defaultGroup.push({
|
|
2328
|
-
environment,
|
|
2329
|
-
handler: cb.handler
|
|
2330
|
-
});
|
|
2331
|
-
};
|
|
2332
|
-
return {
|
|
2333
|
-
tapEnvironment,
|
|
2334
|
-
tap: (handler)=>{
|
|
2335
|
-
tapEnvironment({
|
|
2336
|
-
handler
|
|
2337
|
-
});
|
|
2338
|
-
},
|
|
2339
|
-
callChain: async ({ environment, args: params, afterEach })=>{
|
|
2340
|
-
for (let callback of [
|
|
2341
|
-
...preGroup,
|
|
2342
|
-
...defaultGroup,
|
|
2343
|
-
...postGroup
|
|
2344
|
-
]){
|
|
2345
|
-
if (environment && callback.environment && callback.environment !== environment) continue;
|
|
2346
|
-
let result = await callback.handler(...params);
|
|
2347
|
-
void 0 !== result && (params[0] = result), afterEach && afterEach(params);
|
|
2348
|
-
}
|
|
2349
|
-
return params;
|
|
2350
|
-
},
|
|
2351
|
-
callBatch: async ({ environment, args: params })=>{
|
|
2352
|
-
let results = [];
|
|
2353
|
-
for (let callback of [
|
|
2354
|
-
...preGroup,
|
|
2355
|
-
...defaultGroup,
|
|
2356
|
-
...postGroup
|
|
2357
|
-
]){
|
|
2358
|
-
if (environment && callback.environment && callback.environment !== environment) continue;
|
|
2359
|
-
let result = await callback.handler(...params);
|
|
2360
|
-
results.push(result);
|
|
2361
|
-
}
|
|
2362
|
-
return results;
|
|
2363
|
-
}
|
|
2364
|
-
};
|
|
2365
|
-
}
|
|
2366
|
-
function createAsyncHook() {
|
|
2367
|
-
let preGroup = [], postGroup = [], defaultGroup = [];
|
|
2368
|
-
return {
|
|
2369
|
-
tap: (cb)=>{
|
|
2370
|
-
isFunction(cb) ? defaultGroup.push(cb) : 'pre' === cb.order ? preGroup.push(cb.handler) : 'post' === cb.order ? postGroup.push(cb.handler) : defaultGroup.push(cb.handler);
|
|
2371
|
-
},
|
|
2372
|
-
callChain: async (...params)=>{
|
|
2373
|
-
for (let callback of [
|
|
2374
|
-
...preGroup,
|
|
2375
|
-
...defaultGroup,
|
|
2376
|
-
...postGroup
|
|
2377
|
-
]){
|
|
2378
|
-
let result = await callback(...params);
|
|
2379
|
-
void 0 !== result && (params[0] = result);
|
|
2380
|
-
}
|
|
2381
|
-
return params;
|
|
2382
|
-
},
|
|
2383
|
-
callBatch: async (...params)=>{
|
|
2384
|
-
let results = [];
|
|
2385
|
-
for (let callback of [
|
|
2386
|
-
...preGroup,
|
|
2387
|
-
...defaultGroup,
|
|
2388
|
-
...postGroup
|
|
2389
|
-
]){
|
|
2390
|
-
let result = await callback(...params);
|
|
2391
|
-
results.push(result);
|
|
2392
|
-
}
|
|
2393
|
-
return results;
|
|
2394
|
-
}
|
|
2395
|
-
};
|
|
2396
|
-
}
|
|
2397
|
-
function initHooks() {
|
|
2398
|
-
return {
|
|
2399
|
-
onExit: createAsyncHook(),
|
|
2400
|
-
onCloseBuild: createAsyncHook(),
|
|
2401
|
-
onAfterBuild: createAsyncHook(),
|
|
2402
|
-
onBeforeBuild: createAsyncHook(),
|
|
2403
|
-
onBeforeDevCompile: createAsyncHook(),
|
|
2404
|
-
onAfterDevCompile: createAsyncHook(),
|
|
2405
|
-
onCloseDevServer: createAsyncHook(),
|
|
2406
|
-
onAfterStartDevServer: createAsyncHook(),
|
|
2407
|
-
onBeforeStartDevServer: createAsyncHook(),
|
|
2408
|
-
onAfterStartProdServer: createAsyncHook(),
|
|
2409
|
-
onBeforeStartProdServer: createAsyncHook(),
|
|
2410
|
-
onAfterCreateCompiler: createAsyncHook(),
|
|
2411
|
-
onBeforeCreateCompiler: createAsyncHook(),
|
|
2412
|
-
modifyHTML: createEnvironmentAsyncHook(),
|
|
2413
|
-
modifyHTMLTags: createEnvironmentAsyncHook(),
|
|
2414
|
-
modifyRspackConfig: createEnvironmentAsyncHook(),
|
|
2415
|
-
modifyBundlerChain: createEnvironmentAsyncHook(),
|
|
2416
|
-
modifyWebpackChain: createEnvironmentAsyncHook(),
|
|
2417
|
-
modifyWebpackConfig: createEnvironmentAsyncHook(),
|
|
2418
|
-
modifyRsbuildConfig: createAsyncHook(),
|
|
2419
|
-
modifyEnvironmentConfig: createEnvironmentAsyncHook(),
|
|
2420
|
-
onBeforeEnvironmentCompile: createEnvironmentAsyncHook(),
|
|
2421
|
-
onAfterEnvironmentCompile: createEnvironmentAsyncHook()
|
|
2422
|
-
};
|
|
2423
|
-
}
|
|
2424
|
-
let onBeforeCompile = ({ compiler, beforeCompile, beforeEnvironmentCompile, isWatch })=>{
|
|
2425
|
-
let name = 'rsbuild:beforeCompile';
|
|
2426
|
-
if (compiler_isMultiCompiler(compiler)) {
|
|
2427
|
-
let waitBeforeCompileDone, { compilers } = compiler;
|
|
2428
|
-
compiler.hooks.invalid.tap(name, ()=>{
|
|
2429
|
-
waitBeforeCompileDone = void 0;
|
|
2430
|
-
});
|
|
2431
|
-
for(let index = 0; index < compilers.length; index++){
|
|
2432
|
-
let compiler = compilers[index];
|
|
2433
|
-
(isWatch ? compiler.hooks.watchRun : compiler.hooks.run).tapPromise(name, async ()=>{
|
|
2434
|
-
waitBeforeCompileDone || (waitBeforeCompileDone = beforeCompile()), await waitBeforeCompileDone, await beforeEnvironmentCompile(index);
|
|
2435
|
-
});
|
|
2436
|
-
}
|
|
2437
|
-
} else (isWatch ? compiler.hooks.watchRun : compiler.hooks.run).tapPromise(name, async ()=>{
|
|
2438
|
-
await beforeCompile(), await beforeEnvironmentCompile(0);
|
|
2439
|
-
});
|
|
2440
|
-
}, onCompileDone = ({ compiler, onDone, onEnvironmentDone, MultiStatsCtor })=>{
|
|
2441
|
-
if (compiler_isMultiCompiler(compiler)) {
|
|
2442
|
-
let { compilers } = compiler, compilerStats = [], doneCompilers = 0;
|
|
2443
|
-
for(let index = 0; index < compilers.length; index++){
|
|
2444
|
-
let compiler = compilers[index], compilerIndex = index, compilerDone = !1;
|
|
2445
|
-
compiler.hooks.done.tapPromise('rsbuild:done', async (stats)=>{
|
|
2446
|
-
!compilerDone && (compilerDone = !0, doneCompilers++), compilerStats[compilerIndex] = stats;
|
|
2447
|
-
let lastCompilerDone = doneCompilers === compilers.length;
|
|
2448
|
-
await onEnvironmentDone(index, stats), lastCompilerDone && await onDone(new MultiStatsCtor(compilerStats));
|
|
2449
|
-
}), compiler.hooks.invalid.tap('rsbuild:done', ()=>{
|
|
2450
|
-
compilerDone && (compilerDone = !1, doneCompilers--);
|
|
2451
|
-
});
|
|
2452
|
-
}
|
|
2453
|
-
} else compiler.hooks.done.tapPromise('rsbuild:done', async (stats)=>{
|
|
2454
|
-
await onEnvironmentDone(0, stats), await onDone(stats);
|
|
2455
|
-
});
|
|
2456
|
-
}, registerBuildHook = ({ context, isWatch, compiler, bundlerConfigs, MultiStatsCtor })=>{
|
|
2457
|
-
let isFirstCompile = !0, { environmentList } = context, onDone = async (stats)=>{
|
|
2458
|
-
let promise = context.hooks.onAfterBuild.callBatch({
|
|
2459
|
-
isFirstCompile,
|
|
2460
|
-
stats,
|
|
2461
|
-
environments: context.environments,
|
|
2462
|
-
isWatch
|
|
2463
|
-
});
|
|
2464
|
-
isFirstCompile = !1, await promise;
|
|
2465
|
-
}, onEnvironmentDone = async (index, stats)=>{
|
|
2466
|
-
let environment = environmentList[index], time = context.buildState.time[environment.name] ?? 0;
|
|
2467
|
-
await context.hooks.onAfterEnvironmentCompile.callBatch({
|
|
2468
|
-
environment: environment.name,
|
|
2469
|
-
args: [
|
|
2470
|
-
{
|
|
2471
|
-
isFirstCompile,
|
|
2472
|
-
stats,
|
|
2473
|
-
environment,
|
|
2474
|
-
isWatch,
|
|
2475
|
-
time
|
|
2476
|
-
}
|
|
2477
|
-
]
|
|
2478
|
-
});
|
|
2479
|
-
};
|
|
2480
|
-
onBeforeCompile({
|
|
2481
|
-
compiler,
|
|
2482
|
-
beforeCompile: async ()=>context.hooks.onBeforeBuild.callBatch({
|
|
2483
|
-
bundlerConfigs,
|
|
2484
|
-
environments: context.environments,
|
|
2485
|
-
isWatch,
|
|
2486
|
-
isFirstCompile
|
|
2487
|
-
}),
|
|
2488
|
-
beforeEnvironmentCompile: async (buildIndex)=>{
|
|
2489
|
-
let environment = environmentList[buildIndex];
|
|
2490
|
-
return context.hooks.onBeforeEnvironmentCompile.callBatch({
|
|
2491
|
-
environment: environment.name,
|
|
2492
|
-
args: [
|
|
2493
|
-
{
|
|
2494
|
-
bundlerConfig: bundlerConfigs[buildIndex],
|
|
2495
|
-
environment,
|
|
2496
|
-
isWatch,
|
|
2497
|
-
isFirstCompile
|
|
2498
|
-
}
|
|
2499
|
-
]
|
|
2500
|
-
});
|
|
2501
|
-
},
|
|
2502
|
-
isWatch
|
|
2503
|
-
}), onCompileDone({
|
|
2504
|
-
compiler,
|
|
2505
|
-
onDone,
|
|
2506
|
-
onEnvironmentDone,
|
|
2507
|
-
MultiStatsCtor
|
|
2508
|
-
});
|
|
2509
|
-
}, registerDevHook = ({ context, compiler, bundlerConfigs, MultiStatsCtor })=>{
|
|
2510
|
-
let isFirstCompile = !0, { environmentList } = context, onDone = async (stats)=>{
|
|
2511
|
-
let promise = context.hooks.onAfterDevCompile.callBatch({
|
|
2512
|
-
isFirstCompile,
|
|
2513
|
-
stats,
|
|
2514
|
-
environments: context.environments
|
|
2515
|
-
});
|
|
2516
|
-
isFirstCompile = !1, await promise;
|
|
2517
|
-
}, onEnvironmentDone = async (index, stats)=>{
|
|
2518
|
-
let environment = environmentList[index], time = context.buildState.time[environment.name] ?? 0;
|
|
2519
|
-
await context.hooks.onAfterEnvironmentCompile.callBatch({
|
|
2520
|
-
environment: environment.name,
|
|
2521
|
-
args: [
|
|
2522
|
-
{
|
|
2523
|
-
isFirstCompile,
|
|
2524
|
-
stats,
|
|
2525
|
-
environment,
|
|
2526
|
-
isWatch: !0,
|
|
2527
|
-
time
|
|
2528
|
-
}
|
|
2529
|
-
]
|
|
2530
|
-
});
|
|
2531
|
-
};
|
|
2532
|
-
onBeforeCompile({
|
|
2533
|
-
compiler,
|
|
2534
|
-
beforeEnvironmentCompile: async (buildIndex)=>{
|
|
2535
|
-
let environment = environmentList[buildIndex];
|
|
2536
|
-
return context.hooks.onBeforeEnvironmentCompile.callBatch({
|
|
2537
|
-
environment: environment.name,
|
|
2538
|
-
args: [
|
|
2539
|
-
{
|
|
2540
|
-
bundlerConfig: bundlerConfigs[buildIndex],
|
|
2541
|
-
environment,
|
|
2542
|
-
isWatch: !0,
|
|
2543
|
-
isFirstCompile
|
|
2544
|
-
}
|
|
2545
|
-
]
|
|
2546
|
-
});
|
|
2547
|
-
},
|
|
2548
|
-
beforeCompile: async ()=>context.hooks.onBeforeDevCompile.callBatch({
|
|
2549
|
-
bundlerConfigs,
|
|
2550
|
-
environments: context.environments,
|
|
2551
|
-
isFirstCompile,
|
|
2552
|
-
isWatch: !0
|
|
2553
|
-
}),
|
|
2554
|
-
isWatch: !0
|
|
2555
|
-
}), onCompileDone({
|
|
2556
|
-
compiler,
|
|
2557
|
-
onDone,
|
|
2558
|
-
onEnvironmentDone,
|
|
2559
|
-
MultiStatsCtor
|
|
2560
|
-
});
|
|
2349
|
+
compilation.errors.push(new rspack_rspack.WebpackError(message));
|
|
2561
2350
|
};
|
|
2562
2351
|
function resolveFileName(stats) {
|
|
2563
2352
|
let file = stats.file || stats.moduleName;
|
|
@@ -2584,12 +2373,12 @@ function formatModuleTrace(stats, errorFile, level) {
|
|
|
2584
2373
|
...trace.slice(0, 2),
|
|
2585
2374
|
`… (${trace.length - 2 - 2} hidden)`,
|
|
2586
2375
|
...trace.slice(trace.length - 2)
|
|
2587
|
-
]),
|
|
2376
|
+
]), picocolors_default().dim(`Import traces (entry → ${level}):\n ${trace.join('\n ')} ${picocolors_default().bold(picocolors_default().red('×'))}`);
|
|
2588
2377
|
}
|
|
2589
2378
|
function hintUnknownFiles(message) {
|
|
2590
2379
|
let hint = 'You may need an appropriate loader to handle this file type.';
|
|
2591
2380
|
if (-1 === message.indexOf(hint)) return message;
|
|
2592
|
-
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`;
|
|
2593
2382
|
for (let plugin of [
|
|
2594
2383
|
{
|
|
2595
2384
|
test: /File: .+\.s(c|a)ss/,
|
|
@@ -2632,10 +2421,10 @@ function formatStatsError(stats, root, level = 'error') {
|
|
|
2632
2421
|
let DATA_URI_PREFIX = "data:text/javascript,";
|
|
2633
2422
|
if (fileName.startsWith(DATA_URI_PREFIX)) {
|
|
2634
2423
|
let snippet = fileName.replace(DATA_URI_PREFIX, '');
|
|
2635
|
-
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`;
|
|
2636
2425
|
}
|
|
2637
2426
|
let prefix = root + external_node_path_.sep;
|
|
2638
|
-
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`;
|
|
2639
2428
|
})(fileName, stats, root)}${stats.message}`, verbose = isVerbose();
|
|
2640
2429
|
if (verbose && (stats.details && (message += `\nDetails: ${stats.details}\n`), stats.stack && (message += `\n${stats.stack}`)), 'error' === level || isVerbose()) {
|
|
2641
2430
|
let moduleTrace = formatModuleTrace(stats, fileName, level);
|
|
@@ -2645,7 +2434,7 @@ function formatStatsError(stats, root, level = 'error') {
|
|
|
2645
2434
|
!verbose && message.includes(innerError) && (message = message.split(innerError)[0]);
|
|
2646
2435
|
let lines = (message = ((message)=>{
|
|
2647
2436
|
if (-1 === message.indexOf('Multiple assets emit different content to the same filename')) return message;
|
|
2648
|
-
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')})`;
|
|
2649
2438
|
return `${message}\n${extraMessage}`;
|
|
2650
2439
|
})(message = ((message)=>{
|
|
2651
2440
|
let getTips = (moduleName)=>{
|
|
@@ -2653,9 +2442,9 @@ function formatStatsError(stats, root, level = 'error') {
|
|
|
2653
2442
|
`Error: "${moduleName}" is a built-in Node.js module and cannot be imported in client-side code.\n`,
|
|
2654
2443
|
'Solution: Check if you need to import Node.js module.',
|
|
2655
2444
|
' - If not needed, remove the import.',
|
|
2656
|
-
` - 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')})`
|
|
2657
2446
|
];
|
|
2658
|
-
return `${message}\n\n${
|
|
2447
|
+
return `${message}\n\n${picocolors_default().red(tips.join('\n'))}`;
|
|
2659
2448
|
};
|
|
2660
2449
|
if (message.includes('need an additional plugin to handle "node:" URIs')) return getTips('node:*');
|
|
2661
2450
|
if (!message.includes("Can't resolve")) return message;
|
|
@@ -2669,7 +2458,7 @@ function formatStatsError(stats, root, level = 'error') {
|
|
|
2669
2458
|
let ensureTrailingNewline = (input)=>input.replace(/[ \t]+$/, '').endsWith('\n') ? input : `${input}\n`;
|
|
2670
2459
|
function formatErrorMessage(errors) {
|
|
2671
2460
|
if (!errors.length) return 'Build failed. No errors reported since Rspack\'s "stats.errors" is disabled.';
|
|
2672
|
-
let title =
|
|
2461
|
+
let title = picocolors_default().bold(picocolors_default().red(errors.length > 1 ? 'Build errors: ' : 'Build error: ')), text = ensureTrailingNewline(errors.join('\n\n'));
|
|
2673
2462
|
return `${title}\n${text}`;
|
|
2674
2463
|
}
|
|
2675
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, []) : [];
|
|
@@ -2689,35 +2478,174 @@ function getStatsOptions(compiler, action) {
|
|
|
2689
2478
|
...defaultOptions,
|
|
2690
2479
|
children: compiler.compilers.map((compiler)=>compiler.options ? compiler.options.stats : void 0)
|
|
2691
2480
|
};
|
|
2692
|
-
let { stats } = compiler.options;
|
|
2693
|
-
return 'string' == typeof stats ? {
|
|
2694
|
-
...defaultOptions,
|
|
2695
|
-
preset: stats
|
|
2696
|
-
} : 'object' == typeof stats ? {
|
|
2697
|
-
...defaultOptions,
|
|
2698
|
-
...stats
|
|
2699
|
-
} : defaultOptions;
|
|
2481
|
+
let { stats } = compiler.options;
|
|
2482
|
+
return 'string' == typeof stats ? {
|
|
2483
|
+
...defaultOptions,
|
|
2484
|
+
preset: stats
|
|
2485
|
+
} : 'object' == typeof stats ? {
|
|
2486
|
+
...defaultOptions,
|
|
2487
|
+
...stats
|
|
2488
|
+
} : defaultOptions;
|
|
2489
|
+
}
|
|
2490
|
+
function getRsbuildStats(statsInstance, compiler, action) {
|
|
2491
|
+
let statsOptions = getStatsOptions(compiler, action);
|
|
2492
|
+
return statsInstance.toJson(statsOptions);
|
|
2493
|
+
}
|
|
2494
|
+
function formatStats(stats, hasErrors, root) {
|
|
2495
|
+
if (hasErrors) return {
|
|
2496
|
+
message: formatErrorMessage(getStatsErrors(stats).map((item)=>formatStatsError(item, root))),
|
|
2497
|
+
level: 'error'
|
|
2498
|
+
};
|
|
2499
|
+
let warningMessages = getStatsWarnings(stats).map((item)=>formatStatsError(item, root, 'warning'));
|
|
2500
|
+
if (warningMessages.length) {
|
|
2501
|
+
let title = picocolors_default().bold(picocolors_default().yellow(warningMessages.length > 1 ? 'Build warnings: \n' : 'Build warning: \n'));
|
|
2502
|
+
return {
|
|
2503
|
+
message: ensureTrailingNewline(`${title}${warningMessages.join('\n\n')}`),
|
|
2504
|
+
level: 'warning'
|
|
2505
|
+
};
|
|
2506
|
+
}
|
|
2507
|
+
return {};
|
|
2508
|
+
}
|
|
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
|
+
};
|
|
2700
2559
|
}
|
|
2701
|
-
function
|
|
2702
|
-
let
|
|
2703
|
-
return
|
|
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
|
+
};
|
|
2704
2590
|
}
|
|
2705
|
-
function
|
|
2706
|
-
|
|
2707
|
-
|
|
2708
|
-
|
|
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()
|
|
2709
2614
|
};
|
|
2710
|
-
let warningMessages = getStatsWarnings(stats).map((item)=>formatStatsError(item, root, 'warning'));
|
|
2711
|
-
if (warningMessages.length) {
|
|
2712
|
-
let title = color.bold(color.yellow(warningMessages.length > 1 ? 'Build warnings: \n' : 'Build warning: \n'));
|
|
2713
|
-
return {
|
|
2714
|
-
message: ensureTrailingNewline(`${title}${warningMessages.join('\n\n')}`),
|
|
2715
|
-
level: 'warning'
|
|
2716
|
-
};
|
|
2717
|
-
}
|
|
2718
|
-
return {};
|
|
2719
2615
|
}
|
|
2720
|
-
let
|
|
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");
|
|
2721
2649
|
function _define_property(obj, key, value) {
|
|
2722
2650
|
return key in obj ? Object.defineProperty(obj, key, {
|
|
2723
2651
|
value: value,
|
|
@@ -2734,7 +2662,7 @@ class BrowserslistError extends Error {
|
|
|
2734
2662
|
let isFileCache = {};
|
|
2735
2663
|
function isFile(file) {
|
|
2736
2664
|
if (file in isFileCache) return isFileCache[file];
|
|
2737
|
-
let result =
|
|
2665
|
+
let result = external_node_fs_.default.existsSync(file) && external_node_fs_.default.statSync(file).isFile();
|
|
2738
2666
|
return isFileCache[file] = result, result;
|
|
2739
2667
|
}
|
|
2740
2668
|
function dist_check(section) {
|
|
@@ -2744,7 +2672,7 @@ function dist_check(section) {
|
|
|
2744
2672
|
} else if ('string' != typeof section) throw new BrowserslistError(FORMAT);
|
|
2745
2673
|
}
|
|
2746
2674
|
function parsePackage(file) {
|
|
2747
|
-
let config = JSON.parse(
|
|
2675
|
+
let config = JSON.parse(external_node_fs_.default.readFileSync(file).toString().replace(/^\uFEFF/m, ''));
|
|
2748
2676
|
if (config.browserlist && !config.browserslist) throw new BrowserslistError(`\`browserlist\` key instead of \`browserslist\` in ${file}`);
|
|
2749
2677
|
let list = config.browserslist;
|
|
2750
2678
|
for(let i in Array.isArray(list) && (list = {
|
|
@@ -2771,7 +2699,7 @@ function parseConfig(string) {
|
|
|
2771
2699
|
}
|
|
2772
2700
|
function readConfig(file) {
|
|
2773
2701
|
if (!isFile(file)) throw new BrowserslistError(`Can't read ${file} config`);
|
|
2774
|
-
return parseConfig(
|
|
2702
|
+
return parseConfig(external_node_fs_.default.readFileSync(file, 'utf-8'));
|
|
2775
2703
|
}
|
|
2776
2704
|
function parsePackageOrReadConfig(file) {
|
|
2777
2705
|
return 'package.json' === external_node_path_.default.basename(file) ? parsePackage(file) : readConfig(file);
|
|
@@ -2845,7 +2773,7 @@ let getCompiledPath = (packageName)=>(0, external_node_path_.join)(COMPILED_PATH
|
|
|
2845
2773
|
}
|
|
2846
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)=>{
|
|
2847
2775
|
try {
|
|
2848
|
-
return
|
|
2776
|
+
return external_node_fs_.default.statSync(filePath, {
|
|
2849
2777
|
throwIfNoEntry: !1
|
|
2850
2778
|
})?.isFile();
|
|
2851
2779
|
} catch (_) {
|
|
@@ -2853,7 +2781,7 @@ let getCompiledPath = (packageName)=>(0, external_node_path_.join)(COMPILED_PATH
|
|
|
2853
2781
|
}
|
|
2854
2782
|
};
|
|
2855
2783
|
function isEmptyDir(path) {
|
|
2856
|
-
let files =
|
|
2784
|
+
let files = external_node_fs_.default.readdirSync(path);
|
|
2857
2785
|
return 0 === files.length || 1 === files.length && '.git' === files[0];
|
|
2858
2786
|
}
|
|
2859
2787
|
let findExists = (files)=>{
|
|
@@ -2861,10 +2789,10 @@ let findExists = (files)=>{
|
|
|
2861
2789
|
return !1;
|
|
2862
2790
|
};
|
|
2863
2791
|
async function pathExists(path) {
|
|
2864
|
-
return
|
|
2792
|
+
return external_node_fs_.default.promises.access(path).then(()=>!0).catch(()=>!1);
|
|
2865
2793
|
}
|
|
2866
2794
|
async function isFileExists(file) {
|
|
2867
|
-
return
|
|
2795
|
+
return external_node_fs_.default.promises.access(file, external_node_fs_.default.constants.F_OK).then(()=>!0).catch(()=>!1);
|
|
2868
2796
|
}
|
|
2869
2797
|
async function fileExistsByCompilation({ inputFileSystem }, filePath) {
|
|
2870
2798
|
return new Promise((resolve)=>{
|
|
@@ -2873,14 +2801,25 @@ async function fileExistsByCompilation({ inputFileSystem }, filePath) {
|
|
|
2873
2801
|
}) : resolve(!1);
|
|
2874
2802
|
});
|
|
2875
2803
|
}
|
|
2804
|
+
function readFileAsync(fs, filename) {
|
|
2805
|
+
return new Promise((resolve, reject)=>{
|
|
2806
|
+
fs.readFile(filename, (err, data)=>{
|
|
2807
|
+
err ? reject(err) : void 0 === data ? reject(Error(`Failed to read file: ${filename}, data is undefined`)) : resolve(data);
|
|
2808
|
+
});
|
|
2809
|
+
});
|
|
2810
|
+
}
|
|
2876
2811
|
async function emptyDir(dir, keep = [], checkExists = !0) {
|
|
2877
2812
|
if (!checkExists || await pathExists(dir)) try {
|
|
2878
|
-
let entries = await
|
|
2813
|
+
let entries = await external_node_fs_.default.promises.readdir(dir, {
|
|
2879
2814
|
withFileTypes: !0
|
|
2880
2815
|
});
|
|
2881
2816
|
await Promise.all(entries.map(async (entry)=>{
|
|
2882
2817
|
let fullPath = external_node_path_.default.join(dir, entry.name);
|
|
2883
|
-
|
|
2818
|
+
if (keep.length) {
|
|
2819
|
+
let posixFullPath = toPosixPath(fullPath);
|
|
2820
|
+
if (keep.some((regex)=>regex.test(posixFullPath))) return;
|
|
2821
|
+
}
|
|
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);
|
|
2884
2823
|
}));
|
|
2885
2824
|
} catch (err) {
|
|
2886
2825
|
src_logger.debug(`failed to empty dir: ${dir}`), src_logger.debug(err);
|
|
@@ -2974,7 +2913,7 @@ let OVERRIDE_PATHS = new Set([
|
|
|
2974
2913
|
},
|
|
2975
2914
|
server: {
|
|
2976
2915
|
port: 3000,
|
|
2977
|
-
host:
|
|
2916
|
+
host: LOCALHOST,
|
|
2978
2917
|
open: !1,
|
|
2979
2918
|
base: '/',
|
|
2980
2919
|
htmlFallback: 'index',
|
|
@@ -3050,8 +2989,6 @@ let OVERRIDE_PATHS = new Set([
|
|
|
3050
2989
|
},
|
|
3051
2990
|
legalComments: 'linked',
|
|
3052
2991
|
injectStyles: !1,
|
|
3053
|
-
minify: !0,
|
|
3054
|
-
module: !1,
|
|
3055
2992
|
manifest: !1,
|
|
3056
2993
|
sourceMap: {
|
|
3057
2994
|
js: void 0,
|
|
@@ -3083,7 +3020,6 @@ let OVERRIDE_PATHS = new Set([
|
|
|
3083
3020
|
}
|
|
3084
3021
|
},
|
|
3085
3022
|
performance: {
|
|
3086
|
-
profile: !1,
|
|
3087
3023
|
printFileSize: !0,
|
|
3088
3024
|
removeConsole: !1,
|
|
3089
3025
|
removeMomentLocale: !1,
|
|
@@ -3109,16 +3045,16 @@ function getDefaultEntry(root) {
|
|
|
3109
3045
|
index: entryFile
|
|
3110
3046
|
} : {};
|
|
3111
3047
|
}
|
|
3112
|
-
let withDefaultConfig = async (rootPath,
|
|
3113
|
-
let
|
|
3114
|
-
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 = {
|
|
3115
3051
|
imports: !0,
|
|
3116
3052
|
entries: !1
|
|
3117
|
-
}), !
|
|
3053
|
+
}), !config.source.tsconfigPath) {
|
|
3118
3054
|
let tsconfigPath = (0, external_node_path_.join)(rootPath, 'tsconfig.json');
|
|
3119
|
-
await isFileExists(tsconfigPath) && (
|
|
3055
|
+
await isFileExists(tsconfigPath) && (config.source.tsconfigPath = tsconfigPath);
|
|
3120
3056
|
}
|
|
3121
|
-
return
|
|
3057
|
+
return config;
|
|
3122
3058
|
}, exitHook_callbacks = new Set(), isCalled = !1, isRegistered = !1;
|
|
3123
3059
|
function exit(exitCode, type) {
|
|
3124
3060
|
if (!isCalled) {
|
|
@@ -3140,28 +3076,22 @@ function exitHook(onExit) {
|
|
|
3140
3076
|
exitHook_callbacks.delete(onExit);
|
|
3141
3077
|
};
|
|
3142
3078
|
}
|
|
3143
|
-
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)=>{
|
|
3144
3080
|
let [urlProtocol, baseUrl] = base.split('://');
|
|
3145
3081
|
return `${urlProtocol}://${external_node_path_.posix.join(baseUrl, path)}`;
|
|
3146
|
-
},
|
|
3147
|
-
try {
|
|
3148
|
-
return new external_node_url_.URL(url), !0;
|
|
3149
|
-
} catch {
|
|
3150
|
-
return !1;
|
|
3151
|
-
}
|
|
3152
|
-
}, 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)=>{
|
|
3153
3083
|
let publicPath = chain.output.get('publicPath');
|
|
3154
3084
|
return 'string' == typeof publicPath ? formatPublicPath(publicPath, withSlash) : formatPublicPath(DEFAULT_ASSET_PREFIX, withSlash);
|
|
3155
3085
|
};
|
|
3156
3086
|
function validatePlugin(plugin) {
|
|
3157
3087
|
let type = typeof plugin;
|
|
3158
|
-
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)}.`);
|
|
3159
3089
|
if (!isFunction(plugin.setup)) {
|
|
3160
3090
|
if (isFunction(plugin.apply)) {
|
|
3161
3091
|
let { name = 'SomeWebpackPlugin' } = plugin.constructor || {};
|
|
3162
3092
|
throw Error([
|
|
3163
|
-
`${
|
|
3164
|
-
|
|
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(`
|
|
3165
3095
|
// rsbuild.config.ts
|
|
3166
3096
|
export default {
|
|
3167
3097
|
tools: {
|
|
@@ -3173,7 +3103,7 @@ function validatePlugin(plugin) {
|
|
|
3173
3103
|
`)
|
|
3174
3104
|
].join('\n'));
|
|
3175
3105
|
}
|
|
3176
|
-
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)}.`);
|
|
3177
3107
|
}
|
|
3178
3108
|
}
|
|
3179
3109
|
let isEnvironmentMatch = (pluginEnvironment, specifiedEnvironment)=>pluginEnvironment === specifiedEnvironment || void 0 === pluginEnvironment;
|
|
@@ -3211,7 +3141,7 @@ async function initPlugins({ context, pluginManager }) {
|
|
|
3211
3141
|
let allLines = [];
|
|
3212
3142
|
function getPlugin(name) {
|
|
3213
3143
|
let targets = plugins.filter((item)=>item.instance.name === name);
|
|
3214
|
-
if (!targets.length) throw Error(`${
|
|
3144
|
+
if (!targets.length) throw Error(`${picocolors_default().dim('[rsbuild:plugin]')} Plugin "${picocolors_default().yellow(name)}" not existed`);
|
|
3215
3145
|
return targets;
|
|
3216
3146
|
}
|
|
3217
3147
|
for (let plugin of plugins){
|
|
@@ -3232,7 +3162,7 @@ async function initPlugins({ context, pluginManager }) {
|
|
|
3232
3162
|
if (allLines.length) {
|
|
3233
3163
|
let restInRingPoints = {};
|
|
3234
3164
|
for (let l of allLines)restInRingPoints[l[0]] = !0, restInRingPoints[l[1]] = !0;
|
|
3235
|
-
throw Error(`${
|
|
3165
|
+
throw Error(`${picocolors_default().dim('[rsbuild:plugin]')} Plugins dependencies has loop: ${picocolors_default().yellow(Object.keys(restInRingPoints).join(','))}`);
|
|
3236
3166
|
}
|
|
3237
3167
|
return sortedPoint;
|
|
3238
3168
|
})(plugins = ((plugins)=>{
|
|
@@ -3272,10 +3202,10 @@ async function initPlugins({ context, pluginManager }) {
|
|
|
3272
3202
|
}
|
|
3273
3203
|
function getHTMLPathByEntry(entryName, config) {
|
|
3274
3204
|
let filename = getFilename(config, 'html').replace('[name]', entryName), prefix = config.output.distPath.html;
|
|
3275
|
-
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(/^\/+/, '');
|
|
3276
3206
|
}
|
|
3277
|
-
let mapProcessAssetsStage = (
|
|
3278
|
-
let { Compilation } =
|
|
3207
|
+
let mapProcessAssetsStage = (stage)=>{
|
|
3208
|
+
let { Compilation } = rspack_rspack;
|
|
3279
3209
|
switch(stage){
|
|
3280
3210
|
case 'additional':
|
|
3281
3211
|
return Compilation.PROCESS_ASSETS_STAGE_ADDITIONAL;
|
|
@@ -3310,7 +3240,7 @@ let mapProcessAssetsStage = (compiler, stage)=>{
|
|
|
3310
3240
|
case 'report':
|
|
3311
3241
|
return Compilation.PROCESS_ASSETS_STAGE_REPORT;
|
|
3312
3242
|
default:
|
|
3313
|
-
throw Error(`${
|
|
3243
|
+
throw Error(`${picocolors_default().dim('[rsbuild]')} Invalid process assets stage: ${stage}`);
|
|
3314
3244
|
}
|
|
3315
3245
|
};
|
|
3316
3246
|
function initPluginAPI({ context, pluginManager }) {
|
|
@@ -3319,12 +3249,12 @@ function initPluginAPI({ context, pluginManager }) {
|
|
|
3319
3249
|
if (context.normalizedConfig) {
|
|
3320
3250
|
if (options?.environment) {
|
|
3321
3251
|
let config = context.normalizedConfig.environments[options.environment];
|
|
3322
|
-
if (!config) throw Error(`${
|
|
3252
|
+
if (!config) throw Error(`${picocolors_default().dim('[rsbuild]')} Cannot find normalized config by environment: ${options.environment}.`);
|
|
3323
3253
|
return config;
|
|
3324
3254
|
}
|
|
3325
3255
|
return context.normalizedConfig;
|
|
3326
3256
|
}
|
|
3327
|
-
throw Error(`${
|
|
3257
|
+
throw Error(`${picocolors_default().dim('[rsbuild]')} Cannot access normalized config until ${picocolors_default().yellow('modifyRsbuildConfig')} is called.`);
|
|
3328
3258
|
}
|
|
3329
3259
|
let getRsbuildConfig = (type = 'current')=>{
|
|
3330
3260
|
switch(type){
|
|
@@ -3335,7 +3265,7 @@ function initPluginAPI({ context, pluginManager }) {
|
|
|
3335
3265
|
case 'normalized':
|
|
3336
3266
|
return getNormalizedConfig();
|
|
3337
3267
|
}
|
|
3338
|
-
throw Error(`${
|
|
3268
|
+
throw Error(`${picocolors_default().dim('[rsbuild]')} ${picocolors_default().yellow('getRsbuildConfig')} get an invalid type param.`);
|
|
3339
3269
|
}, exposed = new Map(), expose = (id, api)=>{
|
|
3340
3270
|
exposed.set(id, api);
|
|
3341
3271
|
}, useExposed = (id)=>exposed.get(id), transformId = 0, transformer = {}, processAssetsFns = [], resolveFns = [];
|
|
@@ -3356,10 +3286,10 @@ function initPluginAPI({ context, pluginManager }) {
|
|
|
3356
3286
|
compilation.hooks.childCompiler.tap(pluginName, (childCompiler)=>{
|
|
3357
3287
|
childCompiler.__rsbuildTransformer = transformer;
|
|
3358
3288
|
});
|
|
3359
|
-
let { sources } =
|
|
3289
|
+
let { sources } = rspack_rspack;
|
|
3360
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({
|
|
3361
3291
|
name: pluginName,
|
|
3362
|
-
stage: mapProcessAssetsStage(
|
|
3292
|
+
stage: mapProcessAssetsStage(descriptor.stage)
|
|
3363
3293
|
}, async (assets)=>handler({
|
|
3364
3294
|
assets,
|
|
3365
3295
|
compiler,
|
|
@@ -3390,7 +3320,7 @@ function initPluginAPI({ context, pluginManager }) {
|
|
|
3390
3320
|
if (descriptor.targets && !descriptor.targets.includes(target) || descriptor.environments && !descriptor.environments.includes(environmentContext.name)) return;
|
|
3391
3321
|
let rule = chain.module.rule(id);
|
|
3392
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);
|
|
3393
|
-
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);
|
|
3394
3324
|
rule.use(id).loader(loaderPath).options({
|
|
3395
3325
|
id,
|
|
3396
3326
|
getEnvironment: ()=>environmentContext
|
|
@@ -3454,18 +3384,6 @@ function initPluginAPI({ context, pluginManager }) {
|
|
|
3454
3384
|
handler
|
|
3455
3385
|
});
|
|
3456
3386
|
},
|
|
3457
|
-
modifyWebpackChain: (handler)=>{
|
|
3458
|
-
hooks.modifyWebpackChain.tapEnvironment({
|
|
3459
|
-
environment,
|
|
3460
|
-
handler
|
|
3461
|
-
});
|
|
3462
|
-
},
|
|
3463
|
-
modifyWebpackConfig: (handler)=>{
|
|
3464
|
-
hooks.modifyWebpackConfig.tapEnvironment({
|
|
3465
|
-
environment,
|
|
3466
|
-
handler
|
|
3467
|
-
});
|
|
3468
|
-
},
|
|
3469
3387
|
modifyEnvironmentConfig: (handler)=>{
|
|
3470
3388
|
hooks.modifyEnvironmentConfig.tapEnvironment({
|
|
3471
3389
|
environment,
|
|
@@ -3554,14 +3472,14 @@ function createPublicContext(context) {
|
|
|
3554
3472
|
});
|
|
3555
3473
|
}
|
|
3556
3474
|
async function createContext(options, userConfig) {
|
|
3557
|
-
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;
|
|
3558
3476
|
return {
|
|
3559
|
-
version: "
|
|
3477
|
+
version: "2.0.0-alpha.0",
|
|
3560
3478
|
rootPath,
|
|
3561
3479
|
distPath: '',
|
|
3562
3480
|
cachePath,
|
|
3563
3481
|
callerName: options.callerName,
|
|
3564
|
-
bundlerType,
|
|
3482
|
+
bundlerType: 'rspack',
|
|
3565
3483
|
environments: {},
|
|
3566
3484
|
environmentList: [],
|
|
3567
3485
|
publicPathnames: [],
|
|
@@ -3586,39 +3504,34 @@ let normalizePluginObject = (plugin)=>{
|
|
|
3586
3504
|
setup () {}
|
|
3587
3505
|
};
|
|
3588
3506
|
};
|
|
3589
|
-
async function
|
|
3590
|
-
let { outputPath } = inspectOptions, files = [
|
|
3591
|
-
...
|
|
3592
|
-
|
|
3593
|
-
path: (0, external_node_path_.join)(outputPath, 'rsbuild.config.mjs'),
|
|
3594
|
-
label: 'Rsbuild config',
|
|
3595
|
-
content
|
|
3596
|
-
};
|
|
3597
|
-
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})`;
|
|
3598
3511
|
return {
|
|
3599
3512
|
path: (0, external_node_path_.join)(outputPath, outputFile),
|
|
3600
|
-
label
|
|
3513
|
+
label,
|
|
3601
3514
|
content
|
|
3602
3515
|
};
|
|
3603
3516
|
}),
|
|
3604
|
-
...
|
|
3605
|
-
let outputFile =
|
|
3606
|
-
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`)), {
|
|
3607
3520
|
path: outputFilePath,
|
|
3608
|
-
label:
|
|
3521
|
+
label: `Rspack Config (${name})`,
|
|
3609
3522
|
content
|
|
3610
3523
|
};
|
|
3611
3524
|
}),
|
|
3612
|
-
...(
|
|
3525
|
+
...(extraConfigs || []).map(({ name, content })=>({
|
|
3613
3526
|
path: (0, external_node_path_.join)(outputPath, `${name}.config.mjs`),
|
|
3614
3527
|
label: `${upperFirst(name)} Config`,
|
|
3615
3528
|
content
|
|
3616
3529
|
}))
|
|
3617
3530
|
];
|
|
3618
|
-
await
|
|
3531
|
+
await external_node_fs_.default.promises.mkdir(outputPath, {
|
|
3619
3532
|
recursive: !0
|
|
3620
|
-
}), await Promise.all(files.map(async (item)=>
|
|
3621
|
-
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');
|
|
3622
3535
|
src_logger.success(`config inspection completed, generated files: \n\n${fileInfos}\n`);
|
|
3623
3536
|
}
|
|
3624
3537
|
function stringifyConfig(config, verbose) {
|
|
@@ -3626,59 +3539,49 @@ function stringifyConfig(config, verbose) {
|
|
|
3626
3539
|
verbose
|
|
3627
3540
|
});
|
|
3628
3541
|
}
|
|
3629
|
-
async function inspectConfig_inspectConfig({ context, pluginManager, bundlerConfigs, inspectOptions = {}
|
|
3630
|
-
var context1, inspectOptions1;
|
|
3542
|
+
async function inspectConfig_inspectConfig({ context, pluginManager, bundlerConfigs, inspectOptions = {} }) {
|
|
3631
3543
|
inspectOptions.mode ? setNodeEnv(inspectOptions.mode) : process.env.NODE_ENV || setNodeEnv('development');
|
|
3632
|
-
let
|
|
3544
|
+
let stringifiedBundlerConfigs = bundlerConfigs.map((config, index)=>({
|
|
3633
3545
|
name: config.name || String(index),
|
|
3634
3546
|
content: stringifyConfig(config, inspectOptions.verbose)
|
|
3635
|
-
})), {
|
|
3636
|
-
|
|
3637
|
-
|
|
3638
|
-
|
|
3639
|
-
|
|
3640
|
-
|
|
3641
|
-
|
|
3642
|
-
|
|
3643
|
-
|
|
3644
|
-
|
|
3645
|
-
}).map(normalizePluginObject)
|
|
3646
|
-
};
|
|
3647
|
-
rawEnvironmentConfigs.push({
|
|
3648
|
-
name,
|
|
3649
|
-
content: stringifyConfig(debugConfig, inspectOptions.verbose)
|
|
3650
|
-
}), environmentConfigs[name] = debugConfig;
|
|
3651
|
-
}
|
|
3652
|
-
return {
|
|
3653
|
-
rsbuildConfig,
|
|
3654
|
-
rawRsbuildConfig,
|
|
3655
|
-
environmentConfigs: environments,
|
|
3656
|
-
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)
|
|
3657
3557
|
};
|
|
3658
|
-
|
|
3659
|
-
|
|
3660
|
-
|
|
3661
|
-
|
|
3662
|
-
}
|
|
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])=>({
|
|
3663
3567
|
name,
|
|
3664
3568
|
content: 'string' == typeof content ? content : stringifyConfig(content, inspectOptions.verbose)
|
|
3665
3569
|
})) : void 0;
|
|
3666
|
-
return inspectOptions.writeToDisk && await
|
|
3667
|
-
|
|
3668
|
-
|
|
3669
|
-
|
|
3570
|
+
return inspectOptions.writeToDisk && await emitConfigFiles({
|
|
3571
|
+
bundlerConfigs: stringifiedBundlerConfigs,
|
|
3572
|
+
environmentConfigs: stringifiedEnvironmentConfigs,
|
|
3573
|
+
extraConfigs: stringifiedExtraConfigs,
|
|
3670
3574
|
inspectOptions: {
|
|
3671
3575
|
...inspectOptions,
|
|
3672
3576
|
outputPath
|
|
3673
|
-
}
|
|
3674
|
-
configType: bundler
|
|
3577
|
+
}
|
|
3675
3578
|
}), {
|
|
3676
|
-
rsbuildConfig:
|
|
3677
|
-
environmentConfigs:
|
|
3678
|
-
bundlerConfigs:
|
|
3579
|
+
rsbuildConfig: stringifiedRsbuildConfig,
|
|
3580
|
+
environmentConfigs: stringifiedEnvironmentConfigs.map((item)=>item.content),
|
|
3581
|
+
bundlerConfigs: stringifiedBundlerConfigs.map((item)=>item.content),
|
|
3679
3582
|
origin: {
|
|
3680
3583
|
rsbuildConfig,
|
|
3681
|
-
environmentConfigs,
|
|
3584
|
+
environmentConfigs: environments,
|
|
3682
3585
|
bundlerConfigs
|
|
3683
3586
|
}
|
|
3684
3587
|
};
|
|
@@ -3720,10 +3623,10 @@ function reduceConfigsMergeContext({ initial, config, ctx, mergeFn = Object.assi
|
|
|
3720
3623
|
}
|
|
3721
3624
|
async function modifyBundlerChain(context, utils) {
|
|
3722
3625
|
src_logger.debug('applying modifyBundlerChain hook');
|
|
3723
|
-
let
|
|
3626
|
+
let rspackChain = new src_class(), [modifiedBundlerChain] = await context.hooks.modifyBundlerChain.callChain({
|
|
3724
3627
|
environment: utils.environment.name,
|
|
3725
3628
|
args: [
|
|
3726
|
-
|
|
3629
|
+
rspackChain,
|
|
3727
3630
|
utils
|
|
3728
3631
|
]
|
|
3729
3632
|
});
|
|
@@ -3795,7 +3698,6 @@ let configChain_CHAIN_ID = {
|
|
|
3795
3698
|
PROGRESS: 'progress',
|
|
3796
3699
|
MANIFEST: 'webpack-manifest',
|
|
3797
3700
|
TS_CHECKER: 'ts-checker',
|
|
3798
|
-
BUNDLE_ANALYZER: 'bundle-analyze',
|
|
3799
3701
|
MODULE_FEDERATION: 'module-federation',
|
|
3800
3702
|
HTML_PREFETCH: 'html-prefetch-plugin',
|
|
3801
3703
|
HTML_PRELOAD: 'html-preload-plugin',
|
|
@@ -3811,11 +3713,10 @@ let configChain_CHAIN_ID = {
|
|
|
3811
3713
|
RESOLVE_PLUGIN: {
|
|
3812
3714
|
TS_CONFIG_PATHS: 'ts-config-paths'
|
|
3813
3715
|
}
|
|
3814
|
-
},
|
|
3815
|
-
|
|
3816
|
-
|
|
3817
|
-
|
|
3818
|
-
};
|
|
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
|
+
}
|
|
3819
3720
|
async function modifyRspackConfig(context, rspackConfig, chainUtils) {
|
|
3820
3721
|
src_logger.debug('applying modifyRspackConfig hook');
|
|
3821
3722
|
let currentConfig = rspackConfig, utils = getConfigUtils(()=>currentConfig, chainUtils);
|
|
@@ -3886,11 +3787,11 @@ function getChainUtils(target, environment, environments) {
|
|
|
3886
3787
|
function validateRspackConfig(config) {
|
|
3887
3788
|
if (config.plugins) {
|
|
3888
3789
|
for (let plugin of config.plugins)if (plugin && void 0 === plugin.apply && 'name' in plugin && 'setup' in plugin) {
|
|
3889
|
-
let name =
|
|
3890
|
-
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.`);
|
|
3891
3792
|
}
|
|
3892
3793
|
}
|
|
3893
|
-
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.`);
|
|
3894
3795
|
}
|
|
3895
3796
|
async function generateRspackConfig({ target, context, environmentName }) {
|
|
3896
3797
|
let chainUtils = getChainUtils(target, context.environments[environmentName], context.environments), { BannerPlugin, DefinePlugin, IgnorePlugin, ProvidePlugin, SourceMapDevToolPlugin, HotModuleReplacementPlugin } = rspack_rspack, rspackConfig = (await modifyBundlerChain(context, {
|
|
@@ -3921,7 +3822,7 @@ async function modifyRsbuildConfig(context) {
|
|
|
3921
3822
|
let pluginsCount = context.config.plugins?.length ?? 0, [modified] = await context.hooks.modifyRsbuildConfig.callChain(context.config, {
|
|
3922
3823
|
mergeRsbuildConfig: mergeRsbuildConfig
|
|
3923
3824
|
});
|
|
3924
|
-
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');
|
|
3925
3826
|
}
|
|
3926
3827
|
async function modifyEnvironmentConfig(context, config, name) {
|
|
3927
3828
|
src_logger.debug(`applying modifyEnvironmentConfig hook (${name})`);
|
|
@@ -3938,8 +3839,8 @@ async function modifyEnvironmentConfig(context, config, name) {
|
|
|
3938
3839
|
return src_logger.debug(`applied modifyEnvironmentConfig hook (${name})`), modified;
|
|
3939
3840
|
}
|
|
3940
3841
|
let createEnvironmentNotFoundError = (environments = [])=>{
|
|
3941
|
-
let envList =
|
|
3942
|
-
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.`);
|
|
3943
3844
|
};
|
|
3944
3845
|
async function initRsbuildConfig({ context, pluginManager }) {
|
|
3945
3846
|
var config, rootPath;
|
|
@@ -3975,10 +3876,10 @@ async function initRsbuildConfig({ context, pluginManager }) {
|
|
|
3975
3876
|
let nodeEnv = process.env.NODE_ENV || '';
|
|
3976
3877
|
return 'production' === nodeEnv || 'development' === nodeEnv ? nodeEnv : 'none';
|
|
3977
3878
|
})(), mergeRsbuildConfig(defaultConfig, config)), environments = {}, mergedEnvironments = ((normalizedConfig, rootPath, specifiedEnvironments)=>{
|
|
3978
|
-
let defaultEntry, { environments, dev, server: _server,
|
|
3879
|
+
let defaultEntry, { environments, dev, server: _server, ...baseConfig } = normalizedConfig, isEnvironmentEnabled = (name)=>!specifiedEnvironments || specifiedEnvironments.includes(name), applyEnvironmentDefaultConfig = (config)=>{
|
|
3979
3880
|
config.source.entry && 0 !== Object.keys(config.source.entry).length || (config.source.entry = (defaultEntry || (defaultEntry = getDefaultEntry(rootPath)), defaultEntry));
|
|
3980
3881
|
let isServer = 'node' === config.output.target;
|
|
3981
|
-
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;
|
|
3982
3883
|
};
|
|
3983
3884
|
if (environments && Object.keys(environments).length > 0) {
|
|
3984
3885
|
let resolvedEnvironments = Object.fromEntries(Object.entries(environments).filter(([name])=>isEnvironmentEnabled(name)).map(([name, config])=>[
|
|
@@ -4024,7 +3925,7 @@ async function initRsbuildConfig({ context, pluginManager }) {
|
|
|
4024
3925
|
...normalizedBaseConfig,
|
|
4025
3926
|
environments
|
|
4026
3927
|
}, await updateEnvironmentContext(context, environments), updateContextByNormalizedConfig(context), ((config)=>{
|
|
4027
|
-
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"`);
|
|
4028
3929
|
if (!config.environments) return;
|
|
4029
3930
|
let environmentNames = Object.keys(config.environments), environmentNameRegexp = /^[\w$-]+$/, validTargets = [
|
|
4030
3931
|
'web',
|
|
@@ -4032,13 +3933,13 @@ async function initRsbuildConfig({ context, pluginManager }) {
|
|
|
4032
3933
|
'web-worker'
|
|
4033
3934
|
];
|
|
4034
3935
|
for (let name of environmentNames){
|
|
4035
|
-
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.`);
|
|
4036
3937
|
let outputConfig = config.environments[name].output;
|
|
4037
|
-
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(', '))}`);
|
|
4038
3939
|
}
|
|
4039
3940
|
})(context.normalizedConfig), context.normalizedConfig;
|
|
4040
3941
|
}
|
|
4041
|
-
async function
|
|
3942
|
+
async function initConfigs_initConfigs({ context, pluginManager, rsbuildOptions }) {
|
|
4042
3943
|
let normalizedConfig = await initRsbuildConfig({
|
|
4043
3944
|
context,
|
|
4044
3945
|
pluginManager
|
|
@@ -4090,21 +3991,21 @@ function printBuildLog(compiler, context, lazyModules) {
|
|
|
4090
3991
|
let { modifiedFiles } = compiler, changedFiles = modifiedFiles?.size ? Array.from(modifiedFiles) : lazyModules.size ? Array.from(lazyModules) : null;
|
|
4091
3992
|
if (changedFiles?.length) {
|
|
4092
3993
|
let fileInfo = formatFileList(changedFiles, context.rootPath);
|
|
4093
|
-
src_logger.start(`building ${
|
|
3994
|
+
src_logger.start(`building ${picocolors_default().dim(fileInfo)}`);
|
|
4094
3995
|
return;
|
|
4095
3996
|
}
|
|
4096
3997
|
let removedFiles = compiler.removedFiles ? Array.from(compiler.removedFiles) : null;
|
|
4097
3998
|
if (removedFiles?.length) {
|
|
4098
|
-
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')}`);
|
|
4099
4000
|
let fileInfo = formatFileList(removedFiles, context.rootPath);
|
|
4100
|
-
return void src_logger.start(`building ${
|
|
4001
|
+
return void src_logger.start(`building ${picocolors_default().dim(`removed ${fileInfo}`)}`);
|
|
4101
4002
|
}
|
|
4102
4003
|
src_logger.start('build started...');
|
|
4103
4004
|
}
|
|
4104
4005
|
async function createCompiler_createCompiler(options) {
|
|
4105
4006
|
let version;
|
|
4106
4007
|
src_logger.debug('creating compiler');
|
|
4107
|
-
let HOOK_NAME = 'rsbuild:compiler', { context } = options, { rspackConfigs } = await
|
|
4008
|
+
let HOOK_NAME = 'rsbuild:compiler', { context } = options, { rspackConfigs } = await initConfigs_initConfigs(options);
|
|
4108
4009
|
if (await context.hooks.onBeforeCreateCompiler.callBatch({
|
|
4109
4010
|
bundlerConfigs: rspackConfigs,
|
|
4110
4011
|
environments: context.environments
|
|
@@ -4116,7 +4017,7 @@ async function createCompiler_createCompiler(options) {
|
|
|
4116
4017
|
if (item1 < item2) return -1;
|
|
4117
4018
|
}
|
|
4118
4019
|
return 0;
|
|
4119
|
-
})(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")}`);
|
|
4120
4021
|
let isMultiCompiler = rspackConfigs.length > 1, compiler = isMultiCompiler ? rspack_rspack(rspackConfigs) : rspack_rspack(rspackConfigs[0]);
|
|
4121
4022
|
'true' === process.env.RSPACK_UNSAFE_FAST_DROP && (compiler.unsafeFastDrop = !0);
|
|
4122
4023
|
let isVersionLogged = !1, isCompiling = !1, logRspackVersion = ()=>{
|
|
@@ -4148,7 +4049,21 @@ async function createCompiler_createCompiler(options) {
|
|
|
4148
4049
|
if (null === startTime) return;
|
|
4149
4050
|
let { name } = context.environmentList[index], time = Date.now() - startTime;
|
|
4150
4051
|
context.buildState.time[name] = time;
|
|
4151
|
-
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}`;
|
|
4152
4067
|
hasErrors ? src_logger.error(`build failed in ${timeStr}`) : src_logger.ready(`built in ${timeStr}`);
|
|
4153
4068
|
};
|
|
4154
4069
|
return isMultiCompiler && compiler.compilers.forEach((item, index)=>{
|
|
@@ -4160,7 +4075,59 @@ async function createCompiler_createCompiler(options) {
|
|
|
4160
4075
|
context.buildState.stats = stats, context.buildState.status = 'done', context.buildState.hasErrors = hasErrors, context.socketServer?.onBuildDone();
|
|
4161
4076
|
let { message, level } = formatStats(stats, hasErrors, options.context.rootPath);
|
|
4162
4077
|
'error' === level && src_logger.error(message), 'warning' === level && src_logger.warn(message), isMultiCompiler || printTime(0, hasErrors), isCompiling = !1;
|
|
4163
|
-
}), '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
|
+
})({
|
|
4164
4131
|
context,
|
|
4165
4132
|
compiler,
|
|
4166
4133
|
bundlerConfigs: rspackConfigs,
|
|
@@ -4173,21 +4140,69 @@ async function createCompiler_createCompiler(options) {
|
|
|
4173
4140
|
rspackConfigs
|
|
4174
4141
|
};
|
|
4175
4142
|
}
|
|
4176
|
-
let RSPACK_BUILD_ERROR = 'Rspack build failed.', build_build = async (initOptions, { watch
|
|
4177
|
-
let
|
|
4178
|
-
if (
|
|
4179
|
-
|
|
4180
|
-
|
|
4181
|
-
|
|
4182
|
-
|
|
4183
|
-
|
|
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
|
+
})({
|
|
4184
4199
|
context,
|
|
4185
|
-
|
|
4200
|
+
rspackConfigs,
|
|
4186
4201
|
compiler,
|
|
4187
4202
|
isWatch: !!watch,
|
|
4188
4203
|
MultiStatsCtor: rspack_rspack.MultiStats
|
|
4189
4204
|
}), watch) {
|
|
4190
|
-
let watchOptions =
|
|
4205
|
+
let watchOptions = rspackConfigs.map((options)=>options.watchOptions || {});
|
|
4191
4206
|
return compiler.watch(watchOptions.length > 1 ? watchOptions : watchOptions[0] || {}, (err)=>{
|
|
4192
4207
|
err && src_logger.error(err);
|
|
4193
4208
|
}), {
|
|
@@ -4223,14 +4238,14 @@ function loadEnv_parse(src) {
|
|
|
4223
4238
|
function loadEnv({ cwd = process.cwd(), mode = process.env.NODE_ENV || '', prefixes = [
|
|
4224
4239
|
'PUBLIC_'
|
|
4225
4240
|
], processEnv = process.env } = {}) {
|
|
4226
|
-
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.`);
|
|
4227
4242
|
let filePaths = [
|
|
4228
4243
|
'.env',
|
|
4229
4244
|
'.env.local',
|
|
4230
4245
|
`.env.${mode}`,
|
|
4231
4246
|
`.env.${mode}.local`
|
|
4232
4247
|
].map((filename)=>(0, external_node_path_.join)(cwd, filename)).filter(isFileSync), parsed = {};
|
|
4233
|
-
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);
|
|
4234
4249
|
parsed.NODE_ENV && (processEnv.NODE_ENV = parsed.NODE_ENV), (0, main.expand)({
|
|
4235
4250
|
parsed,
|
|
4236
4251
|
processEnv
|
|
@@ -4273,55 +4288,6 @@ function getRegExpForExts(exts) {
|
|
|
4273
4288
|
let matcher = normalizedExts.join('|');
|
|
4274
4289
|
return RegExp(1 === normalizedExts.length ? `\\.${matcher}$` : `\\.(?:${matcher})$`, 'i');
|
|
4275
4290
|
}
|
|
4276
|
-
let isUseAnalyzer = (config)=>process.env.BUNDLE_ANALYZE || config.performance?.bundleAnalyze;
|
|
4277
|
-
function pluginBundleAnalyzer() {
|
|
4278
|
-
return {
|
|
4279
|
-
name: 'rsbuild:bundle-analyzer',
|
|
4280
|
-
setup (api) {
|
|
4281
|
-
api.modifyRsbuildConfig({
|
|
4282
|
-
order: 'post',
|
|
4283
|
-
handler: (config)=>{
|
|
4284
|
-
if (isUseAnalyzer(config) || Object.values(config.environments || []).some((config)=>isUseAnalyzer(config))) return config.dev ||= {}, config.dev.writeToDisk = !0, config;
|
|
4285
|
-
}
|
|
4286
|
-
}), api.modifyBundlerChain((chain, { CHAIN_ID, environment })=>{
|
|
4287
|
-
let { config } = environment;
|
|
4288
|
-
if (!isUseAnalyzer(config)) return;
|
|
4289
|
-
let BundleAnalyzer = requireCompiledPackage('webpack-bundle-analyzer');
|
|
4290
|
-
chain.plugin(CHAIN_ID.PLUGIN.BUNDLE_ANALYZER).use(BundleAnalyzer.BundleAnalyzerPlugin, [
|
|
4291
|
-
{
|
|
4292
|
-
analyzerMode: 'static',
|
|
4293
|
-
openAnalyzer: !1,
|
|
4294
|
-
reportFilename: `report-${environment.name}.html`,
|
|
4295
|
-
...config.performance.bundleAnalyze || {}
|
|
4296
|
-
}
|
|
4297
|
-
]);
|
|
4298
|
-
});
|
|
4299
|
-
}
|
|
4300
|
-
};
|
|
4301
|
-
}
|
|
4302
|
-
async function validateWebpackCache(cacheDirectory, buildDependencies) {
|
|
4303
|
-
let configFile = (0, external_node_path_.join)(cacheDirectory, 'buildDependencies.json');
|
|
4304
|
-
if (await isFileExists(configFile)) {
|
|
4305
|
-
let rawConfigFile = await node_fs.promises.readFile(configFile, 'utf-8'), prevBuildDependencies = null;
|
|
4306
|
-
try {
|
|
4307
|
-
prevBuildDependencies = JSON.parse(rawConfigFile);
|
|
4308
|
-
} catch (e) {
|
|
4309
|
-
src_logger.debug('failed to parse the previous buildDependencies.json', e);
|
|
4310
|
-
}
|
|
4311
|
-
if (JSON.stringify(prevBuildDependencies) === JSON.stringify(buildDependencies)) return;
|
|
4312
|
-
await node_fs.promises.rm(cacheDirectory, {
|
|
4313
|
-
force: !0,
|
|
4314
|
-
recursive: !0
|
|
4315
|
-
});
|
|
4316
|
-
}
|
|
4317
|
-
try {
|
|
4318
|
-
await node_fs.promises.mkdir(cacheDirectory, {
|
|
4319
|
-
recursive: !0
|
|
4320
|
-
}), await node_fs.promises.writeFile(configFile, JSON.stringify(buildDependencies));
|
|
4321
|
-
} catch (e) {
|
|
4322
|
-
src_logger.debug('failed to write the buildDependencies.json', e);
|
|
4323
|
-
}
|
|
4324
|
-
}
|
|
4325
4291
|
function getCacheDirectory({ cacheDirectory }, context) {
|
|
4326
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);
|
|
4327
4293
|
}
|
|
@@ -4362,8 +4328,34 @@ let addTrailingSep = (dir)=>dir.endsWith(external_node_path_.sep) ? dir : dir +
|
|
|
4362
4328
|
...defaultOptions,
|
|
4363
4329
|
...userOptions
|
|
4364
4330
|
};
|
|
4365
|
-
}
|
|
4366
|
-
|
|
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;
|
|
4367
4359
|
if ('boolean' == typeof minify) {
|
|
4368
4360
|
let shouldMinify = minify && isProd;
|
|
4369
4361
|
return {
|
|
@@ -4377,9 +4369,10 @@ let addTrailingSep = (dir)=>dir.endsWith(external_node_path_.sep) ? dir : dir +
|
|
|
4377
4369
|
jsOptions: minify.jsOptions,
|
|
4378
4370
|
cssOptions: minify.cssOptions
|
|
4379
4371
|
};
|
|
4380
|
-
}
|
|
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");
|
|
4381
4374
|
var src_0_default = __webpack_require__.n(src_0);
|
|
4382
|
-
|
|
4375
|
+
function getLightningCSSLoaderOptions(config, targets, minify) {
|
|
4383
4376
|
let userOptions = 'object' == typeof config.tools.lightningcssLoader ? config.tools.lightningcssLoader : {}, initialOptions = {
|
|
4384
4377
|
targets,
|
|
4385
4378
|
errorRecovery: !0
|
|
@@ -4388,7 +4381,8 @@ let getLightningCSSLoaderOptions = (config, targets, minify)=>{
|
|
|
4388
4381
|
initial: initialOptions,
|
|
4389
4382
|
config: userOptions
|
|
4390
4383
|
});
|
|
4391
|
-
}
|
|
4384
|
+
}
|
|
4385
|
+
let clonePostCSSConfig = (config)=>({
|
|
4392
4386
|
...config,
|
|
4393
4387
|
plugins: config.plugins ? [
|
|
4394
4388
|
...config.plugins
|
|
@@ -4428,7 +4422,7 @@ let getPostcssLoaderOptions = async ({ config, root, postcssrcCache })=>{
|
|
|
4428
4422
|
if ('function' == typeof postcssOptions) {
|
|
4429
4423
|
let postcssOptionsWrapper = (loaderContext)=>{
|
|
4430
4424
|
let options = postcssOptions(loaderContext);
|
|
4431
|
-
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)}.`);
|
|
4432
4426
|
return updatePostcssOptions({
|
|
4433
4427
|
...userOptions,
|
|
4434
4428
|
...options,
|
|
@@ -4450,7 +4444,7 @@ function checkProcessEnvSecurity(define) {
|
|
|
4450
4444
|
if (!value) return;
|
|
4451
4445
|
let check = (value)=>{
|
|
4452
4446
|
let pathKey = Object.keys(value).find((key)=>'path' === key.toLowerCase() && value[key] === process.env[key]);
|
|
4453
|
-
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.`);
|
|
4454
4448
|
};
|
|
4455
4449
|
if ('object' == typeof value) return void check(value);
|
|
4456
4450
|
if ('string' == typeof value) try {
|
|
@@ -4470,9 +4464,12 @@ function pluginExternals() {
|
|
|
4470
4464
|
}
|
|
4471
4465
|
};
|
|
4472
4466
|
}
|
|
4473
|
-
let fileSize_gzip = external_node_util_promisify(node_zlib.gzip);
|
|
4474
4467
|
async function gzipSize(input) {
|
|
4475
|
-
let data = await
|
|
4468
|
+
let data = await new Promise((resolve, reject)=>{
|
|
4469
|
+
node_zlib.gzip(input, (err, result)=>{
|
|
4470
|
+
err ? reject(err) : resolve(result);
|
|
4471
|
+
});
|
|
4472
|
+
});
|
|
4476
4473
|
return Buffer.byteLength(data);
|
|
4477
4474
|
}
|
|
4478
4475
|
function getSnapshotPath(dir, snapshotHash) {
|
|
@@ -4483,7 +4480,7 @@ function normalizeFilePath(filePath) {
|
|
|
4483
4480
|
}
|
|
4484
4481
|
async function loadPrevSnapshots(snapshotPath) {
|
|
4485
4482
|
try {
|
|
4486
|
-
let content = await
|
|
4483
|
+
let content = await external_node_fs_.default.promises.readFile(snapshotPath, 'utf-8');
|
|
4487
4484
|
return JSON.parse(content);
|
|
4488
4485
|
} catch {
|
|
4489
4486
|
return null;
|
|
@@ -4491,9 +4488,9 @@ async function loadPrevSnapshots(snapshotPath) {
|
|
|
4491
4488
|
}
|
|
4492
4489
|
async function saveSnapshots(snapshotPath, snapshots) {
|
|
4493
4490
|
try {
|
|
4494
|
-
await
|
|
4491
|
+
await external_node_fs_.default.promises.mkdir(external_node_path_.default.dirname(snapshotPath), {
|
|
4495
4492
|
recursive: !0
|
|
4496
|
-
}), await
|
|
4493
|
+
}), await external_node_fs_.default.promises.writeFile(snapshotPath, JSON.stringify(snapshots, null, 2));
|
|
4497
4494
|
} catch (err) {
|
|
4498
4495
|
src_logger.debug('Failed to save file size snapshots:', err);
|
|
4499
4496
|
}
|
|
@@ -4501,10 +4498,10 @@ async function saveSnapshots(snapshotPath, snapshots) {
|
|
|
4501
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)=>{
|
|
4502
4499
|
let label = `(${diff > 0 ? '+' : '-'}${calcFileSize(Math.abs(diff))})`;
|
|
4503
4500
|
return {
|
|
4504
|
-
label: (diff > 0 ?
|
|
4501
|
+
label: (diff > 0 ? picocolors_default().red : picocolors_default().green)(label),
|
|
4505
4502
|
length: label.length
|
|
4506
4503
|
};
|
|
4507
|
-
}, getAssetColor = (size)=>size > 300000 ?
|
|
4504
|
+
}, getAssetColor = (size)=>size > 300000 ? picocolors_default().red : size > 100000 ? picocolors_default().yellow : (input)=>input;
|
|
4508
4505
|
function getHeader(maxFileLength, maxSizeLength, fileHeader, showGzipHeader) {
|
|
4509
4506
|
let lengths = [
|
|
4510
4507
|
maxFileLength,
|
|
@@ -4518,7 +4515,7 @@ function getHeader(maxFileLength, maxSizeLength, fileHeader, showGzipHeader) {
|
|
|
4518
4515
|
let length = lengths[index], curLabel = cur;
|
|
4519
4516
|
return length && (curLabel = cur.length < length ? cur + ' '.repeat(length - cur.length) : cur), `${prev + curLabel} `;
|
|
4520
4517
|
}, '');
|
|
4521
|
-
return
|
|
4518
|
+
return picocolors_default().blue(headerRow);
|
|
4522
4519
|
}
|
|
4523
4520
|
let calcFileSize = (len)=>{
|
|
4524
4521
|
let val = len / 1000;
|
|
@@ -4551,7 +4548,7 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
|
|
|
4551
4548
|
isSignificantDiff(gzipDiff) && (gzipSizeLabel += ` ${formatDiff(gzipDiff).label}`);
|
|
4552
4549
|
}
|
|
4553
4550
|
}
|
|
4554
|
-
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;
|
|
4555
4552
|
return {
|
|
4556
4553
|
filePath,
|
|
4557
4554
|
filename,
|
|
@@ -4569,7 +4566,7 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
|
|
|
4569
4566
|
try {
|
|
4570
4567
|
content = value.source();
|
|
4571
4568
|
} catch {
|
|
4572
|
-
content =
|
|
4569
|
+
content = external_node_fs_.default.readFileSync(external_node_path_.default.join(distPath, filePath));
|
|
4573
4570
|
}
|
|
4574
4571
|
return {
|
|
4575
4572
|
filePath,
|
|
@@ -4641,7 +4638,7 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
|
|
|
4641
4638
|
if (customTotal) logs.push(customTotal);
|
|
4642
4639
|
else {
|
|
4643
4640
|
let log = '';
|
|
4644
|
-
if (log += ' '.repeat(maxFileLength - totalSizeTitle.length), log +=
|
|
4641
|
+
if (log += ' '.repeat(maxFileLength - totalSizeTitle.length), log += picocolors_default().magenta(totalSizeTitle), log += ` ${totalSizeLabel}`, options.compressed) {
|
|
4645
4642
|
let colorFn = getAssetColor(totalGzipSize / assets.length);
|
|
4646
4643
|
if (log += ' '.repeat(maxSizeLength - totalSizeLabelLength), log += ` ${colorFn(calcFileSize(totalGzipSize))}`, showDiff) {
|
|
4647
4644
|
let totalGzipSizeDiff = totalGzipSize - (previousSizes[environmentName]?.totalGzipSize ?? 0);
|
|
@@ -4655,8 +4652,8 @@ async function printFileSizes(options, stats, rootPath, distPath, environmentNam
|
|
|
4655
4652
|
let customTotal = getCustomTotal();
|
|
4656
4653
|
if (customTotal) logs.push(customTotal);
|
|
4657
4654
|
else {
|
|
4658
|
-
let log = `${
|
|
4659
|
-
options.compressed && (log +=
|
|
4655
|
+
let log = `${picocolors_default().magenta(totalSizeTitle)} ${totalSizeLabel}`;
|
|
4656
|
+
options.compressed && (log += picocolors_default().green(` (${calcFileSize(totalGzipSize)} gzipped)`)), logs.push(log);
|
|
4660
4657
|
}
|
|
4661
4658
|
}
|
|
4662
4659
|
return logs.push(''), {
|
|
@@ -4720,16 +4717,17 @@ class RsbuildHtmlPlugin {
|
|
|
4720
4717
|
}
|
|
4721
4718
|
apply(compiler) {
|
|
4722
4719
|
let emitFavicon = async ({ compilation, favicon, faviconDistPath })=>{
|
|
4723
|
-
let
|
|
4720
|
+
let fileContent, name = external_node_path_.default.basename(favicon);
|
|
4724
4721
|
if (compilation.assets[name]) return name;
|
|
4725
|
-
|
|
4722
|
+
let inputFs = compilation.inputFileSystem;
|
|
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;
|
|
4726
4724
|
let inputFilename = external_node_path_.default.isAbsolute(favicon) ? favicon : external_node_path_.default.join(compilation.compiler.context, favicon);
|
|
4727
4725
|
try {
|
|
4728
|
-
|
|
4726
|
+
fileContent = await readFileAsync(inputFs, inputFilename);
|
|
4729
4727
|
} catch (error) {
|
|
4730
|
-
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;
|
|
4731
4729
|
}
|
|
4732
|
-
let source = new
|
|
4730
|
+
let source = new rspack_rspack.sources.RawSource(fileContent, !1), outputFilename = external_node_path_.default.posix.join(faviconDistPath, name);
|
|
4733
4731
|
return compilation.emitAsset(outputFilename, source), outputFilename;
|
|
4734
4732
|
}, addFavicon = async ({ headTags, favicon, faviconDistPath, compilation, publicPath })=>{
|
|
4735
4733
|
let href = favicon;
|
|
@@ -4890,10 +4888,10 @@ async function getTemplate(entryName, config, rootPath) {
|
|
|
4890
4888
|
}
|
|
4891
4889
|
let absolutePath = (0, external_node_path_.isAbsolute)(templatePath) ? templatePath : external_node_path_.default.join(rootPath, templatePath);
|
|
4892
4890
|
if (!existTemplatePath.has(absolutePath)) {
|
|
4893
|
-
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)}`);
|
|
4894
4892
|
existTemplatePath.add(absolutePath);
|
|
4895
4893
|
}
|
|
4896
|
-
let templateContent = await
|
|
4894
|
+
let templateContent = await external_node_fs_.default.promises.readFile(absolutePath, 'utf-8');
|
|
4897
4895
|
return {
|
|
4898
4896
|
templatePath: absolutePath,
|
|
4899
4897
|
templateContent
|
|
@@ -4920,21 +4918,19 @@ function getMetaTags(entryName, config, templateContent) {
|
|
|
4920
4918
|
}
|
|
4921
4919
|
function getTemplateParameters(entryName, config, assetPrefix) {
|
|
4922
4920
|
return (compilation, assets, assetTags, pluginOptions)=>{
|
|
4923
|
-
let { mountId, templateParameters } = config.html, rspackConfig = compilation.options
|
|
4924
|
-
tags: assetTags,
|
|
4925
|
-
files: assets,
|
|
4926
|
-
options: pluginOptions
|
|
4927
|
-
};
|
|
4921
|
+
let { mountId, templateParameters } = config.html, rspackConfig = compilation.options;
|
|
4928
4922
|
return reduceConfigsWithContext({
|
|
4929
4923
|
initial: {
|
|
4930
4924
|
mountId,
|
|
4931
4925
|
entryName,
|
|
4932
4926
|
assetPrefix,
|
|
4933
4927
|
compilation,
|
|
4934
|
-
htmlPlugin
|
|
4935
|
-
|
|
4936
|
-
|
|
4937
|
-
|
|
4928
|
+
htmlPlugin: {
|
|
4929
|
+
tags: assetTags,
|
|
4930
|
+
files: assets,
|
|
4931
|
+
options: pluginOptions
|
|
4932
|
+
},
|
|
4933
|
+
rspackConfig
|
|
4938
4934
|
},
|
|
4939
4935
|
config: templateParameters,
|
|
4940
4936
|
ctx: {
|
|
@@ -4968,13 +4964,14 @@ function matchTests(name, asset, tests) {
|
|
|
4968
4964
|
size: asset.size()
|
|
4969
4965
|
}) : test.exec(name));
|
|
4970
4966
|
}
|
|
4971
|
-
|
|
4967
|
+
function getInlineTests(config) {
|
|
4972
4968
|
let isProd = 'production' === config.mode, { inlineStyles, inlineScripts } = config.output, scriptTests = [], styleTests = [];
|
|
4973
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)), {
|
|
4974
4970
|
scriptTests,
|
|
4975
4971
|
styleTests
|
|
4976
4972
|
};
|
|
4977
|
-
}
|
|
4973
|
+
}
|
|
4974
|
+
let normalizeUrl = (url)=>url.replace(/([^:]\/)\/+/g, '$1'), joinUrlSegments = (s1, s2)=>s1 && s2 ? addTrailingSlash(s1) + s2.replace(/^\/+/, '') : s1 || s2 || '', stripBase = (path, base)=>{
|
|
4978
4975
|
if (path === base) return '/';
|
|
4979
4976
|
let trailingSlashBase = addTrailingSlash(base);
|
|
4980
4977
|
return path.startsWith(trailingSlashBase) ? path.slice(trailingSlashBase.length - 1) : path;
|
|
@@ -5002,16 +4999,16 @@ function getURLMessages(urls, routes) {
|
|
|
5002
4999
|
if (routes.length <= 1) {
|
|
5003
5000
|
let pathname = routes.length ? routes[0].pathname : '';
|
|
5004
5001
|
return urls.map(({ label, url })=>{
|
|
5005
|
-
let normalizedPathname = normalizeUrl(`${url}${pathname}`), prefix = `➜ ${
|
|
5006
|
-
return ` ${prefix}${
|
|
5002
|
+
let normalizedPathname = normalizeUrl(`${url}${pathname}`), prefix = `➜ ${picocolors_default().dim(label.padEnd(10))}`;
|
|
5003
|
+
return ` ${prefix}${picocolors_default().cyan(normalizedPathname)}\n`;
|
|
5007
5004
|
}).join('');
|
|
5008
5005
|
}
|
|
5009
5006
|
let message = '', prevLabel = '', maxNameLength = Math.max(...routes.map((r)=>r.entryName.length));
|
|
5010
5007
|
return urls.forEach(({ label, url }, index)=>{
|
|
5011
|
-
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`;
|
|
5012
5009
|
}), message;
|
|
5013
5010
|
}
|
|
5014
|
-
function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls, trailingLineBreak = !0 }) {
|
|
5011
|
+
function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls, trailingLineBreak = !0, originalConfig }) {
|
|
5015
5012
|
if (!1 === printUrls) return null;
|
|
5016
5013
|
let urls = originalUrls, useCustomUrl = isFunction(printUrls);
|
|
5017
5014
|
if (useCustomUrl) {
|
|
@@ -5022,7 +5019,7 @@ function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls
|
|
|
5022
5019
|
protocol
|
|
5023
5020
|
});
|
|
5024
5021
|
if (!newUrls) return null;
|
|
5025
|
-
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}.`);
|
|
5026
5023
|
urls = newUrls.map((u)=>{
|
|
5027
5024
|
let { url, label } = 'string' == typeof u ? {
|
|
5028
5025
|
url: u
|
|
@@ -5035,7 +5032,7 @@ function printServerURLs({ urls: originalUrls, port, routes, protocol, printUrls
|
|
|
5035
5032
|
}
|
|
5036
5033
|
if (0 === urls.length || 0 === routes.length && !useCustomUrl) return null;
|
|
5037
5034
|
let message = getURLMessages(urls, routes);
|
|
5038
|
-
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;
|
|
5039
5036
|
}
|
|
5040
5037
|
let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
|
|
5041
5038
|
'string' == typeof port && (port = Number.parseInt(port, 10)), strictPort && (tryLimits = 1);
|
|
@@ -5054,15 +5051,15 @@ let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
|
|
|
5054
5051
|
if ('EADDRINUSE' !== e.code) throw e;
|
|
5055
5052
|
port++, attempts++;
|
|
5056
5053
|
}
|
|
5057
|
-
if (!found) throw Error(`${
|
|
5058
|
-
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.`);
|
|
5059
5056
|
return port;
|
|
5060
5057
|
}, getServerConfig = async ({ config })=>{
|
|
5061
5058
|
let { host, port: originalPort, strictPort } = config.server, port = await getPort({
|
|
5062
5059
|
host,
|
|
5063
5060
|
port: originalPort,
|
|
5064
5061
|
strictPort
|
|
5065
|
-
}), 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;
|
|
5066
5063
|
return {
|
|
5067
5064
|
port,
|
|
5068
5065
|
host,
|
|
@@ -5070,12 +5067,12 @@ let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
|
|
|
5070
5067
|
portTip
|
|
5071
5068
|
};
|
|
5072
5069
|
}, isLoopbackHost = (host)=>new Set([
|
|
5073
|
-
|
|
5070
|
+
LOCALHOST,
|
|
5074
5071
|
'127.0.0.1',
|
|
5075
5072
|
'::1',
|
|
5076
5073
|
'0000:0000:0000:0000:0000:0000:0000:0001'
|
|
5077
5074
|
]).has(host), getHostInUrl = async (host)=>{
|
|
5078
|
-
if (host ===
|
|
5075
|
+
if (host === ALL_INTERFACES_IPV4 || host === LOCALHOST) return LOCALHOST;
|
|
5079
5076
|
let { isIPv6 } = await import("node:net");
|
|
5080
5077
|
return isIPv6(host) ? '::' === host ? '[::1]' : `[${host}]` : host;
|
|
5081
5078
|
}, concatUrl = ({ host, port, protocol })=>`${protocol}://${host}:${port}`, LOCAL_LABEL = 'Local: ', NETWORK_LABEL = 'Network: ', getUrlLabel = (url)=>{
|
|
@@ -5086,7 +5083,7 @@ let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
|
|
|
5086
5083
|
return NETWORK_LABEL;
|
|
5087
5084
|
}
|
|
5088
5085
|
}, getAddressUrls = async ({ protocol = 'http', port, host })=>{
|
|
5089
|
-
if (host && host !==
|
|
5086
|
+
if (host && host !== ALL_INTERFACES_IPV4) {
|
|
5090
5087
|
let url = concatUrl({
|
|
5091
5088
|
port,
|
|
5092
5089
|
host: await getHostInUrl(host),
|
|
@@ -5112,7 +5109,7 @@ let getPort = async ({ host, port, strictPort, tryLimits = 20 })=>{
|
|
|
5112
5109
|
addressUrls.push({
|
|
5113
5110
|
label: LOCAL_LABEL,
|
|
5114
5111
|
url: concatUrl({
|
|
5115
|
-
host:
|
|
5112
|
+
host: LOCALHOST,
|
|
5116
5113
|
port,
|
|
5117
5114
|
protocol
|
|
5118
5115
|
})
|
|
@@ -5172,7 +5169,7 @@ async function openBrowser(url) {
|
|
|
5172
5169
|
src_logger.debug("failed to open start URL with apple script."), src_logger.debug(err);
|
|
5173
5170
|
}
|
|
5174
5171
|
}
|
|
5175
|
-
let { apps, default: baseOpen } = await import("./
|
|
5172
|
+
let { apps, default: baseOpen } = await import("./open.js").then((mod)=>({
|
|
5176
5173
|
apps: mod.open_apps,
|
|
5177
5174
|
default: mod.node_modules_open
|
|
5178
5175
|
}));
|
|
@@ -5192,11 +5189,11 @@ async function openBrowser(url) {
|
|
|
5192
5189
|
}
|
|
5193
5190
|
let openedURLs = [], replacePortPlaceholder = (url, port)=>url.replace(/<port>/g, String(port));
|
|
5194
5191
|
function resolveUrl(str, base) {
|
|
5195
|
-
if (canParse(str)) return str;
|
|
5192
|
+
if (external_node_url_.URL.canParse(str)) return str;
|
|
5196
5193
|
try {
|
|
5197
|
-
return new URL(str, base).href;
|
|
5194
|
+
return new external_node_url_.URL(str, base).href;
|
|
5198
5195
|
} catch {
|
|
5199
|
-
throw Error(`${
|
|
5196
|
+
throw Error(`${picocolors_default().dim('[rsbuild:open]')} Invalid input: ${picocolors_default().yellow(str)} is not a valid URL or pathname`);
|
|
5200
5197
|
}
|
|
5201
5198
|
}
|
|
5202
5199
|
async function open_open({ https, port, routes, config, clearCache }) {
|
|
@@ -5259,7 +5256,7 @@ function pluginModuleFederation() {
|
|
|
5259
5256
|
return {
|
|
5260
5257
|
name: 'rsbuild:module-federation',
|
|
5261
5258
|
setup (api) {
|
|
5262
|
-
|
|
5259
|
+
api.modifyRsbuildConfig((config)=>{
|
|
5263
5260
|
let { moduleFederation } = config;
|
|
5264
5261
|
if (moduleFederation?.options && moduleFederation.options.exposes) {
|
|
5265
5262
|
let userConfig = api.getRsbuildConfig('original');
|
|
@@ -5280,7 +5277,7 @@ function pluginModuleFederation() {
|
|
|
5280
5277
|
chain.plugin(CHAIN_ID.PLUGIN.MODULE_FEDERATION).use(rspack_rspack.container.ModuleFederationPlugin, [
|
|
5281
5278
|
options
|
|
5282
5279
|
]), options.name && !chain.output.get('uniqueName') && chain.output.set('uniqueName', options.name);
|
|
5283
|
-
})
|
|
5280
|
+
});
|
|
5284
5281
|
}
|
|
5285
5282
|
};
|
|
5286
5283
|
}
|
|
@@ -5289,8 +5286,8 @@ function getPublicPath({ isDev, config, context }) {
|
|
|
5289
5286
|
if (isDev) {
|
|
5290
5287
|
if ('string' == typeof dev.assetPrefix) publicPath = dev.assetPrefix;
|
|
5291
5288
|
else if (dev.assetPrefix) {
|
|
5292
|
-
let protocol = context.devServer?.https ? 'https' : 'http', hostname = context.devServer?.hostname ||
|
|
5293
|
-
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));
|
|
5294
5291
|
}
|
|
5295
5292
|
} else 'string' == typeof output.assetPrefix && (publicPath = output.assetPrefix);
|
|
5296
5293
|
let defaultPort = server.port ?? 3000;
|
|
@@ -5302,13 +5299,10 @@ function applyAlias({ chain, config, rootPath }) {
|
|
|
5302
5299
|
initial: {},
|
|
5303
5300
|
config: config.resolve.alias
|
|
5304
5301
|
});
|
|
5305
|
-
if (config.
|
|
5306
|
-
initial: mergedAlias,
|
|
5307
|
-
config: config.source.alias
|
|
5308
|
-
})), config.resolve.dedupe) for (let pkgName of config.resolve.dedupe){
|
|
5302
|
+
if (config.resolve.dedupe) for (let pkgName of config.resolve.dedupe){
|
|
5309
5303
|
let pkgPath;
|
|
5310
5304
|
if (mergedAlias[pkgName]) {
|
|
5311
|
-
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.`);
|
|
5312
5306
|
continue;
|
|
5313
5307
|
}
|
|
5314
5308
|
try {
|
|
@@ -5330,7 +5324,7 @@ function applyAlias({ chain, config, rootPath }) {
|
|
|
5330
5324
|
].join(external_node_path_.sep);
|
|
5331
5325
|
for(; !pkgPath.endsWith(trailing) && pkgPath.includes('node_modules');)pkgPath = (0, external_node_path_.dirname)(pkgPath);
|
|
5332
5326
|
} catch {
|
|
5333
|
-
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.`);
|
|
5334
5328
|
continue;
|
|
5335
5329
|
}
|
|
5336
5330
|
mergedAlias[pkgName] = pkgPath;
|
|
@@ -5455,7 +5449,7 @@ function resolveLayer(value) {
|
|
|
5455
5449
|
}
|
|
5456
5450
|
async function ensureFileDir(outputFilePath) {
|
|
5457
5451
|
let dir = external_node_path_.default.dirname(outputFilePath);
|
|
5458
|
-
await
|
|
5452
|
+
await external_node_fs_.default.promises.mkdir(dir, {
|
|
5459
5453
|
recursive: !0
|
|
5460
5454
|
});
|
|
5461
5455
|
}
|
|
@@ -5618,10 +5612,21 @@ function getDefaultSwcConfig({ browserslist, cacheRoot, config, isProd }) {
|
|
|
5618
5612
|
}
|
|
5619
5613
|
};
|
|
5620
5614
|
}
|
|
5621
|
-
function applyCoreJs(swcConfig, polyfillMode) {
|
|
5622
|
-
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)=>{
|
|
5623
5628
|
try {
|
|
5624
|
-
let rawJson =
|
|
5629
|
+
let rawJson = external_node_fs_.default.readFileSync(corejsPkgPath, 'utf-8'), { version } = JSON.parse(rawJson), [major, minor] = version.split('.');
|
|
5625
5630
|
return `${major}.${minor}`;
|
|
5626
5631
|
} catch {
|
|
5627
5632
|
return '3';
|
|
@@ -5649,28 +5654,28 @@ function applySwcDecoratorConfig(swcConfig, config) {
|
|
|
5649
5654
|
swcConfig.jsc.transform.legacyDecorator = !1, swcConfig.jsc.transform.decoratorVersion = '2022-03';
|
|
5650
5655
|
break;
|
|
5651
5656
|
default:
|
|
5652
|
-
throw Error(`${
|
|
5657
|
+
throw Error(`${picocolors_default().dim('[rsbuild:swc]')} Unknown decorators version: ${picocolors_default().yellow(version)}`);
|
|
5653
5658
|
}
|
|
5654
5659
|
}
|
|
5655
5660
|
async function getLocalhostResolvedAddress() {
|
|
5656
5661
|
let { promises: dns } = await import("node:dns"), [defaultLookup, explicitLookup] = await Promise.all([
|
|
5657
|
-
dns.lookup(
|
|
5658
|
-
dns.lookup(
|
|
5662
|
+
dns.lookup(LOCALHOST),
|
|
5663
|
+
dns.lookup(LOCALHOST, {
|
|
5659
5664
|
verbatim: !0
|
|
5660
5665
|
})
|
|
5661
5666
|
]);
|
|
5662
5667
|
return defaultLookup.family === explicitLookup.family && defaultLookup.address === explicitLookup.address ? void 0 : defaultLookup.address;
|
|
5663
5668
|
}
|
|
5664
|
-
async function resolveHostname(host =
|
|
5665
|
-
if (
|
|
5669
|
+
async function resolveHostname(host = LOCALHOST) {
|
|
5670
|
+
if (host === LOCALHOST) {
|
|
5666
5671
|
let resolvedAddress = await getLocalhostResolvedAddress();
|
|
5667
5672
|
if (resolvedAddress) return resolvedAddress;
|
|
5668
5673
|
}
|
|
5669
5674
|
return void 0 === host || new Set([
|
|
5670
|
-
|
|
5675
|
+
ALL_INTERFACES_IPV4,
|
|
5671
5676
|
'::',
|
|
5672
5677
|
'0000:0000:0000:0000:0000:0000:0000:0000'
|
|
5673
|
-
]).has(host) ?
|
|
5678
|
+
]).has(host) ? LOCALHOST : host;
|
|
5674
5679
|
}
|
|
5675
5680
|
let UP_PATH_REGEXP = /(?:^|[\\/])\.\.(?:[\\/]|$)/;
|
|
5676
5681
|
async function getFileFromUrl(url, outputFileSystem, context) {
|
|
@@ -5756,8 +5761,10 @@ function createReadStreamOrReadFileSync(filename, outputFileSystem, start, end)
|
|
|
5756
5761
|
byteLength: 0 === end ? 0 : end - start + 1
|
|
5757
5762
|
};
|
|
5758
5763
|
}
|
|
5759
|
-
function getContentType(str) {
|
|
5760
|
-
let { lookup } =
|
|
5764
|
+
async function getContentType(str) {
|
|
5765
|
+
let { lookup } = await import("./710.js").then((mod)=>({
|
|
5766
|
+
lookup: mod.lookup
|
|
5767
|
+
})), mime = lookup(str);
|
|
5761
5768
|
return !!mime && ((mime.startsWith('text/') || 'application/json' === mime || 'application/manifest+json' === mime) && (mime += '; charset=utf-8'), mime);
|
|
5762
5769
|
}
|
|
5763
5770
|
let BYTES_RANGE_REGEXP = /^ *bytes/i;
|
|
@@ -5775,7 +5782,7 @@ function destroyStream(stream, suppress) {
|
|
|
5775
5782
|
}), 'function' == typeof stream.addListener && suppress && (stream.removeAllListeners('error'), stream.addListener('error', ()=>{}));
|
|
5776
5783
|
}
|
|
5777
5784
|
let parseRangeHeaders = async (value)=>{
|
|
5778
|
-
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('|');
|
|
5779
5786
|
return rangeParser(Number(len), rangeHeader, {
|
|
5780
5787
|
combine: !0
|
|
5781
5788
|
});
|
|
@@ -5784,14 +5791,14 @@ let parseRangeHeaders = async (value)=>{
|
|
|
5784
5791
|
'HEAD'
|
|
5785
5792
|
];
|
|
5786
5793
|
function sendError(res, code) {
|
|
5787
|
-
let
|
|
5794
|
+
let content = {
|
|
5788
5795
|
400: 'Bad Request',
|
|
5789
5796
|
403: 'Forbidden',
|
|
5790
5797
|
404: 'Not Found',
|
|
5791
5798
|
412: 'Precondition Failed',
|
|
5792
5799
|
416: 'Range Not Satisfiable',
|
|
5793
5800
|
500: 'Internal Server Error'
|
|
5794
|
-
}[code]}`, document = Buffer.from(`<!DOCTYPE html>
|
|
5801
|
+
}[code], message = `${code} ${content}`, document = Buffer.from(`<!DOCTYPE html>
|
|
5795
5802
|
<html lang="en">
|
|
5796
5803
|
<head>
|
|
5797
5804
|
<meta charset="utf-8">
|
|
@@ -5902,7 +5909,7 @@ function createMiddleware(context, ready, outputFileSystem) {
|
|
|
5902
5909
|
}
|
|
5903
5910
|
let { fsStats, filename } = resolved, { size } = fsStats, len = size, offset = 0;
|
|
5904
5911
|
if (!res.getHeader('Content-Type')) {
|
|
5905
|
-
let contentType = getContentType(filename);
|
|
5912
|
+
let contentType = await getContentType(filename);
|
|
5906
5913
|
contentType && res.setHeader('Content-Type', contentType);
|
|
5907
5914
|
}
|
|
5908
5915
|
res.getHeader('Accept-Ranges') || res.setHeader('Accept-Ranges', 'bytes');
|
|
@@ -5958,13 +5965,13 @@ function createMiddleware(context, ready, outputFileSystem) {
|
|
|
5958
5965
|
});
|
|
5959
5966
|
};
|
|
5960
5967
|
}
|
|
5961
|
-
function setupOutputFileSystem(writeToDisk, compilers) {
|
|
5968
|
+
async function setupOutputFileSystem(writeToDisk, compilers) {
|
|
5962
5969
|
if (!0 !== writeToDisk) {
|
|
5963
|
-
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());
|
|
5964
5971
|
for (let compiler of compilers)compiler.outputFileSystem = outputFileSystem;
|
|
5965
5972
|
}
|
|
5966
5973
|
let compiler = compilers.find((compiler)=>!!compiler.outputFileSystem);
|
|
5967
|
-
return compiler?.outputFileSystem ??
|
|
5974
|
+
return compiler?.outputFileSystem ?? external_node_fs_.default;
|
|
5968
5975
|
}
|
|
5969
5976
|
function setupWriteToDisk(compilers, writeToDisk) {
|
|
5970
5977
|
for (let compiler of compilers)compiler.hooks.emit.tap('DevMiddleware', ()=>{
|
|
@@ -5972,14 +5979,14 @@ function setupWriteToDisk(compilers, writeToDisk) {
|
|
|
5972
5979
|
let { targetPath, content, compilation } = info;
|
|
5973
5980
|
if (!(!writeToDisk || 'function' != typeof writeToDisk || writeToDisk(targetPath, compilation.name))) return void callback();
|
|
5974
5981
|
let dir = external_node_path_.default.dirname(targetPath), name = compiler.options.name ? `Child "${compiler.options.name}": ` : '';
|
|
5975
|
-
|
|
5982
|
+
external_node_fs_.default.mkdir(dir, {
|
|
5976
5983
|
recursive: !0
|
|
5977
5984
|
}, (mkdirError)=>{
|
|
5978
5985
|
if (mkdirError) {
|
|
5979
5986
|
src_logger.error(`[rsbuild:middleware] ${name}Unable to write "${dir}" directory to disk:\n${mkdirError.message}`), callback(mkdirError);
|
|
5980
5987
|
return;
|
|
5981
5988
|
}
|
|
5982
|
-
|
|
5989
|
+
external_node_fs_.default.writeFile(targetPath, content, (writeFileError)=>{
|
|
5983
5990
|
if (writeFileError) {
|
|
5984
5991
|
src_logger.error(`[rsbuild:middleware] ${name}Unable to write "${targetPath}" asset to disk:\n${writeFileError.message}`), callback(writeFileError);
|
|
5985
5992
|
return;
|
|
@@ -6012,7 +6019,7 @@ init(
|
|
|
6012
6019
|
${JSON.stringify(config.dev.client.logLevel)}
|
|
6013
6020
|
)
|
|
6014
6021
|
`;
|
|
6015
|
-
new
|
|
6022
|
+
new rspack_rspack.EntryPlugin(compiler.context, createVirtualModule(hmrEntry), {
|
|
6016
6023
|
name: void 0
|
|
6017
6024
|
}).apply(compiler);
|
|
6018
6025
|
}
|
|
@@ -6088,7 +6095,7 @@ let assets_middleware_assetsMiddleware = async ({ config, compiler, context, soc
|
|
|
6088
6095
|
writeToDisk && setupWriteToDisk(compilers, writeToDisk);
|
|
6089
6096
|
let instance = createMiddleware(context, (callback)=>{
|
|
6090
6097
|
'done' === context.buildState.status ? callback() : callbacks.push(callback);
|
|
6091
|
-
}, setupOutputFileSystem(writeToDisk, compilers));
|
|
6098
|
+
}, await setupOutputFileSystem(writeToDisk, compilers));
|
|
6092
6099
|
return instance.watch = ()=>{
|
|
6093
6100
|
if (compiler.watching) watching = compiler.watching;
|
|
6094
6101
|
else {
|
|
@@ -6172,12 +6179,14 @@ function parseNode(line) {
|
|
|
6172
6179
|
let isValidMethodName = (methodName)=>'<unknown>' !== methodName && !/[\\/]/.test(methodName), parseFrame = async (frame, fs, context, cachedTraceMap)=>{
|
|
6173
6180
|
let { file, column, lineNumber } = frame, sourceMapInfo = await getFileFromUrl(`${file}.map`, fs, context);
|
|
6174
6181
|
if (!sourceMapInfo || 'errorCode' in sourceMapInfo) return;
|
|
6175
|
-
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;
|
|
6176
6186
|
try {
|
|
6177
6187
|
let tracer = cachedTraceMap.get(sourceMapPath);
|
|
6178
6188
|
if (!tracer) {
|
|
6179
|
-
let
|
|
6180
|
-
if (!sourceMap) return;
|
|
6189
|
+
let sourceMap = await readFileAsync(fs, sourceMapPath);
|
|
6181
6190
|
tracer = new TraceMap(sourceMap.toString()), cachedTraceMap.set(sourceMapPath, tracer);
|
|
6182
6191
|
}
|
|
6183
6192
|
let originalPosition = originalPositionFor(tracer, {
|
|
@@ -6232,14 +6241,14 @@ let isValidMethodName = (methodName)=>'<unknown>' !== methodName && !/[\\/]/.tes
|
|
|
6232
6241
|
return result;
|
|
6233
6242
|
}, formatBrowserErrorLog = async (message, context, fs, stackTrace, stackFrames, cachedTraceMap)=>{
|
|
6234
6243
|
var log;
|
|
6235
|
-
let log1 =
|
|
6244
|
+
let log1 = picocolors_default().red(message);
|
|
6236
6245
|
if (stackFrames?.length) switch(stackTrace){
|
|
6237
6246
|
case 'summary':
|
|
6238
6247
|
{
|
|
6239
6248
|
let resolved = await resolveOriginalLocation(stackFrames, fs, context, cachedTraceMap);
|
|
6240
6249
|
if (!resolved) break;
|
|
6241
6250
|
let { frame, location } = resolved, { methodName } = frame, suffix = '';
|
|
6242
|
-
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) : '';
|
|
6243
6252
|
break;
|
|
6244
6253
|
}
|
|
6245
6254
|
case 'full':
|
|
@@ -6248,7 +6257,7 @@ let isValidMethodName = (methodName)=>'<unknown>' !== methodName && !/[\\/]/.tes
|
|
|
6248
6257
|
fullStack && (log1 += fullStack);
|
|
6249
6258
|
}
|
|
6250
6259
|
}
|
|
6251
|
-
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.
|
|
6252
6261
|
- To access \`process.env.*\`, define them in a \`.env\` file with the \`PUBLIC_\` prefix.
|
|
6253
6262
|
- Or configure them via \`source.define\`.
|
|
6254
6263
|
- Alternatively, install \`@rsbuild/plugin-node-polyfill\` to polyfill Node.js globals.`)}` : log;
|
|
@@ -6416,9 +6425,9 @@ class SocketServer {
|
|
|
6416
6425
|
let payload = JSON.parse('string' == typeof data ? data : data.toString()), { context } = this, config = context.normalizedConfig;
|
|
6417
6426
|
if (!config) return;
|
|
6418
6427
|
let { browserLogs, client } = config.dev;
|
|
6419
|
-
if ('client-error' === payload.type &&
|
|
6428
|
+
if ('client-error' === payload.type && !context.buildState.hasErrors && browserLogs) {
|
|
6420
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);
|
|
6421
|
-
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) {
|
|
6422
6431
|
let resolvedLog = 'full' === stackTrace ? log : await formatBrowserErrorLog(payload.message, context, outputFs, 'full', stackFrames, cachedTraceMap);
|
|
6423
6432
|
this.sockWrite({
|
|
6424
6433
|
type: 'resolved-client-error',
|
|
@@ -6493,12 +6502,12 @@ class BuildManager {
|
|
|
6493
6502
|
resolvedPort;
|
|
6494
6503
|
context;
|
|
6495
6504
|
constructor({ config, context, compiler, resolvedPort }){
|
|
6496
|
-
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;
|
|
6497
6506
|
}
|
|
6498
6507
|
async init() {
|
|
6499
6508
|
await this.setupCompilationMiddleware(), this.socketServer.prepare();
|
|
6500
6509
|
let { compiler } = this;
|
|
6501
|
-
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;
|
|
6502
6511
|
}
|
|
6503
6512
|
watch() {
|
|
6504
6513
|
this.assetsMiddleware.watch();
|
|
@@ -6514,7 +6523,7 @@ class BuildManager {
|
|
|
6514
6523
|
});
|
|
6515
6524
|
});
|
|
6516
6525
|
}
|
|
6517
|
-
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');
|
|
6518
6527
|
async setupCompilationMiddleware() {
|
|
6519
6528
|
let { config, context } = this, middleware = await assets_middleware_assetsMiddleware({
|
|
6520
6529
|
config,
|
|
@@ -6531,19 +6540,19 @@ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls,
|
|
|
6531
6540
|
let shortcuts = [
|
|
6532
6541
|
{
|
|
6533
6542
|
key: 'c',
|
|
6534
|
-
description: `${
|
|
6543
|
+
description: `${picocolors_default().bold('c + enter')} ${picocolors_default().dim('clear console')}`,
|
|
6535
6544
|
action: ()=>{
|
|
6536
6545
|
console.clear();
|
|
6537
6546
|
}
|
|
6538
6547
|
},
|
|
6539
6548
|
{
|
|
6540
6549
|
key: 'o',
|
|
6541
|
-
description: `${
|
|
6550
|
+
description: `${picocolors_default().bold('o + enter')} ${picocolors_default().dim('open in browser')}`,
|
|
6542
6551
|
action: openPage
|
|
6543
6552
|
},
|
|
6544
6553
|
{
|
|
6545
6554
|
key: 'q',
|
|
6546
|
-
description: `${
|
|
6555
|
+
description: `${picocolors_default().bold('q + enter')} ${picocolors_default().dim('quit process')}`,
|
|
6547
6556
|
action: async ()=>{
|
|
6548
6557
|
try {
|
|
6549
6558
|
await closeServer();
|
|
@@ -6554,23 +6563,23 @@ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls,
|
|
|
6554
6563
|
},
|
|
6555
6564
|
restartServer ? {
|
|
6556
6565
|
key: 'r',
|
|
6557
|
-
description: `${
|
|
6566
|
+
description: `${picocolors_default().bold('r + enter')} ${picocolors_default().dim('restart server')}`,
|
|
6558
6567
|
action: restartServer
|
|
6559
6568
|
} : null,
|
|
6560
6569
|
{
|
|
6561
6570
|
key: 'u',
|
|
6562
|
-
description: `${
|
|
6571
|
+
description: `${picocolors_default().bold('u + enter')} ${picocolors_default().dim('show urls')}`,
|
|
6563
6572
|
action: printUrls
|
|
6564
6573
|
}
|
|
6565
6574
|
].filter(Boolean);
|
|
6566
|
-
if (customShortcuts && !Array.isArray(shortcuts = customShortcuts(shortcuts))) throw Error(`${
|
|
6567
|
-
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`);
|
|
6568
6577
|
let { createInterface } = await import("node:readline"), rl = createInterface({
|
|
6569
6578
|
input: process.stdin
|
|
6570
6579
|
});
|
|
6571
6580
|
return rl.on('line', (input)=>{
|
|
6572
6581
|
if ('h' === input) {
|
|
6573
|
-
let message = `\n ${
|
|
6582
|
+
let message = `\n ${picocolors_default().bold(picocolors_default().blue('Shortcuts:'))}\n`;
|
|
6574
6583
|
for (let shortcut of shortcuts)message += ` ${shortcut.description}\n`;
|
|
6575
6584
|
src_logger.log(message);
|
|
6576
6585
|
}
|
|
@@ -6579,7 +6588,9 @@ async function setupCliShortcuts({ help = !0, openPage, closeServer, printUrls,
|
|
|
6579
6588
|
rl.close();
|
|
6580
6589
|
};
|
|
6581
6590
|
}
|
|
6582
|
-
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) {
|
|
6583
6594
|
let gzip, writeHeadStatus, writeHeadMessage;
|
|
6584
6595
|
if (filter && !filter(req, res)) return void next();
|
|
6585
6596
|
let accept = req.headers['accept-encoding'], encoding = 'string' == typeof accept && ENCODING_REGEX.test(accept);
|
|
@@ -6613,6 +6624,7 @@ let ENCODING_REGEX = /\bgzip\b/, CONTENT_TYPE_REGEX = /text|javascript|\/json|xm
|
|
|
6613
6624
|
listener
|
|
6614
6625
|
]), res), next();
|
|
6615
6626
|
};
|
|
6627
|
+
}
|
|
6616
6628
|
function historyApiFallback_historyApiFallbackMiddleware(options = {}) {
|
|
6617
6629
|
return function historyApiFallbackMiddleware(req, _res, next) {
|
|
6618
6630
|
let rewriteTarget, { headers } = req;
|
|
@@ -6660,7 +6672,7 @@ function historyApiFallback_historyApiFallbackMiddleware(options = {}) {
|
|
|
6660
6672
|
};
|
|
6661
6673
|
}
|
|
6662
6674
|
function parseReqUrl(req) {
|
|
6663
|
-
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;
|
|
6664
6676
|
try {
|
|
6665
6677
|
return new external_node_url_.URL(req.url || '/', `${proto}://${host}`);
|
|
6666
6678
|
} catch {
|
|
@@ -6673,12 +6685,12 @@ let faviconFallbackMiddleware = (req, res, next)=>{
|
|
|
6673
6685
|
return (req, res, next)=>{
|
|
6674
6686
|
let _startAt = process.hrtime();
|
|
6675
6687
|
on_finished_default()(res, ()=>{
|
|
6676
|
-
let method = req.method, url = req.originalUrl || req.url, status = Number(res.statusCode), statusColor = status >= 500 ?
|
|
6677
|
-
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`)}`);
|
|
6678
6690
|
}), next();
|
|
6679
6691
|
};
|
|
6680
6692
|
}, notFoundMiddleware = (_req, res, _next)=>{
|
|
6681
|
-
res.statusCode = 404, res.end();
|
|
6693
|
+
res.statusCode = 404, res.setHeader('Content-Type', 'text/plain; charset=utf-8'), res.end('This page could not be found');
|
|
6682
6694
|
}, optionsFallbackMiddleware = (req, res, next)=>{
|
|
6683
6695
|
if ('OPTIONS' === req.method) {
|
|
6684
6696
|
res.statusCode = 204, res.setHeader('Content-Length', '0'), res.end();
|
|
@@ -6731,7 +6743,7 @@ function formatProxyOptions(proxyOptions) {
|
|
|
6731
6743
|
}
|
|
6732
6744
|
return ret;
|
|
6733
6745
|
}
|
|
6734
|
-
|
|
6746
|
+
function createProxyMiddleware(proxyOptions) {
|
|
6735
6747
|
let formattedOptions = formatProxyOptions(proxyOptions), proxyMiddlewares = [], middlewares = [], { createProxyMiddleware: baseMiddleware } = requireCompiledPackage('http-proxy-middleware');
|
|
6736
6748
|
for (let opts of formattedOptions){
|
|
6737
6749
|
let { onProxyRes } = opts;
|
|
@@ -6752,6 +6764,177 @@ let createProxyMiddleware = (proxyOptions)=>{
|
|
|
6752
6764
|
for (let middleware of proxyMiddlewares)'function' == typeof middleware.upgrade && middleware.upgrade(req, socket, head);
|
|
6753
6765
|
}
|
|
6754
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
|
+
};
|
|
6755
6938
|
}, asModule = async (something, context, unlinked)=>{
|
|
6756
6939
|
let { Module, SyntheticModule } = await import("node:vm");
|
|
6757
6940
|
if (something instanceof Module) return something;
|
|
@@ -6811,7 +6994,7 @@ class BasicRunner {
|
|
|
6811
6994
|
postExecute(_m, _file) {}
|
|
6812
6995
|
createRunner() {
|
|
6813
6996
|
this.requirers.set('entry', (_currentDirectory, _modulePath, _context = {})=>{
|
|
6814
|
-
throw Error(`${
|
|
6997
|
+
throw Error(`${picocolors_default().dim('[rsbuild:runner]')} Not implemented`);
|
|
6815
6998
|
});
|
|
6816
6999
|
}
|
|
6817
7000
|
}
|
|
@@ -6906,7 +7089,7 @@ class EsmRunner extends CommonJsRunner {
|
|
|
6906
7089
|
createEsmRequirer() {
|
|
6907
7090
|
let esmCache = new Map(), esmIdentifier = this._options.name, vm = esm_require('node:vm');
|
|
6908
7091
|
return (currentDirectory, modulePath, context = {})=>{
|
|
6909
|
-
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')}.`);
|
|
6910
7093
|
let _require = this.getRequire(), file = context.file || this.getFile(modulePath, currentDirectory);
|
|
6911
7094
|
if (!file) return this.requirers.get('miss')(currentDirectory, modulePath);
|
|
6912
7095
|
let esm = esmCache.get(file.path);
|
|
@@ -6942,7 +7125,7 @@ class BasicRunnerFactory {
|
|
|
6942
7125
|
name: this.name,
|
|
6943
7126
|
...options
|
|
6944
7127
|
}, { compilerOptions } = options;
|
|
6945
|
-
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`);
|
|
6946
7129
|
return new EsmRunner(runnerOptions);
|
|
6947
7130
|
}
|
|
6948
7131
|
}
|
|
@@ -6956,13 +7139,13 @@ let runner_run = async ({ bundlePath, ...runnerFactoryOptions })=>{
|
|
|
6956
7139
|
entrypoints: !0,
|
|
6957
7140
|
outputPath: !0
|
|
6958
7141
|
});
|
|
6959
|
-
if (!entrypoints?.[entryName]) throw Error(`${
|
|
7142
|
+
if (!entrypoints?.[entryName]) throw Error(`${picocolors_default().dim('[rsbuild:loadBundle]')} Can't find entry: ${picocolors_default().yellow(entryName)}`);
|
|
6960
7143
|
let { chunks: entryChunks = [] } = entrypoints[entryName], files = entryChunks.reduce((prev, entryChunkName)=>{
|
|
6961
7144
|
let chunk = chunks?.find((chunk)=>chunk.entry && chunk.names?.includes(String(entryChunkName)));
|
|
6962
7145
|
return chunk?.files ? prev.concat(chunk.files.filter((file)=>!file.endsWith('.css'))) : prev;
|
|
6963
7146
|
}, []);
|
|
6964
|
-
if (0 === files.length) throw Error(`${
|
|
6965
|
-
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(',')}`);
|
|
6966
7149
|
let allChunkFiles = chunks?.flatMap((c)=>c.files).map((file)=>(0, external_node_path_.join)(outputPath, file)) || [];
|
|
6967
7150
|
return await runner_run({
|
|
6968
7151
|
bundlePath: files[0],
|
|
@@ -7065,7 +7248,9 @@ let GLOB_REGEX = /[*?{}[\]()!+|]/;
|
|
|
7065
7248
|
async function createChokidar(pathOrGlobs, root, options) {
|
|
7066
7249
|
let chokidar = requireCompiledPackage('chokidar'), watchFiles = new Set(), globPatterns = pathOrGlobs.filter((pathOrGlob)=>!!GLOB_REGEX.test(pathOrGlob) || (watchFiles.add(pathOrGlob), !1));
|
|
7067
7250
|
if (globPatterns.length) {
|
|
7068
|
-
let { glob } =
|
|
7251
|
+
let { glob } = await import("./tinyglobby.js").then((mod)=>({
|
|
7252
|
+
glob: mod.glob
|
|
7253
|
+
}));
|
|
7069
7254
|
for (let file of (await glob(globPatterns, {
|
|
7070
7255
|
cwd: root,
|
|
7071
7256
|
absolute: !0
|
|
@@ -7082,7 +7267,7 @@ async function startWatchFiles({ paths, options, type = 'reload-page' }, buildMa
|
|
|
7082
7267
|
});
|
|
7083
7268
|
}), watcher;
|
|
7084
7269
|
}
|
|
7085
|
-
async function devServer_createDevServer(options, createCompiler, config, {
|
|
7270
|
+
async function devServer_createDevServer(options, createCompiler, config, { getPortSilently, runCompile = !0 } = {}) {
|
|
7086
7271
|
let lastStats, fileWatcher, devMiddlewares;
|
|
7087
7272
|
src_logger.debug('create dev server');
|
|
7088
7273
|
let { port, host, https, portTip } = await getServerConfig({
|
|
@@ -7102,8 +7287,8 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
|
|
|
7102
7287
|
], waitLastCompileDoneResolve && (waitLastCompileDoneResolve(), waitLastCompileDoneResolve = null);
|
|
7103
7288
|
});
|
|
7104
7289
|
let startCompile = async ()=>{
|
|
7105
|
-
let compiler =
|
|
7106
|
-
if (!compiler) throw Error(`${
|
|
7290
|
+
let compiler = await createCompiler();
|
|
7291
|
+
if (!compiler) throw Error(`${picocolors_default().dim('[rsbuild:server]')} Failed to get compiler instance.`);
|
|
7107
7292
|
let publicPaths = compiler_isMultiCompiler(compiler) ? compiler.compilers.map(getPublicPathFromCompiler) : [
|
|
7108
7293
|
getPublicPathFromCompiler(compiler)
|
|
7109
7294
|
], { base } = config.server;
|
|
@@ -7129,7 +7314,8 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
|
|
|
7129
7314
|
routes,
|
|
7130
7315
|
protocol,
|
|
7131
7316
|
printUrls: config.server.printUrls,
|
|
7132
|
-
trailingLineBreak: !cliShortcutsEnabled
|
|
7317
|
+
trailingLineBreak: !cliShortcutsEnabled,
|
|
7318
|
+
originalConfig: context.originalConfig
|
|
7133
7319
|
}), openPage = async ()=>open_open({
|
|
7134
7320
|
https,
|
|
7135
7321
|
port,
|
|
@@ -7160,10 +7346,10 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
|
|
|
7160
7346
|
!getPortSilently && portTip && src_logger.info(portTip);
|
|
7161
7347
|
}, cacheableLoadBundle = createCacheableFunction(loadBundle), cacheableTransformedHtml = createCacheableFunction((_stats, entryName, utils)=>((entryName, utils)=>{
|
|
7162
7348
|
let { htmlPaths, distPath } = utils.environment, htmlPath = htmlPaths[entryName];
|
|
7163
|
-
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)}`);
|
|
7164
7350
|
let fileName = (0, external_node_path_.join)(distPath, htmlPath);
|
|
7165
7351
|
return utils.readFileSync(fileName);
|
|
7166
|
-
})(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`;
|
|
7167
7353
|
context.environmentList.forEach((environment, index)=>{
|
|
7168
7354
|
environmentAPI[environment.name] = {
|
|
7169
7355
|
context: environment,
|
|
@@ -7187,7 +7373,7 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
|
|
|
7187
7373
|
}
|
|
7188
7374
|
};
|
|
7189
7375
|
});
|
|
7190
|
-
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({
|
|
7191
7377
|
serverConfig: config.server,
|
|
7192
7378
|
middlewares
|
|
7193
7379
|
}), devServerAPI = {
|
|
@@ -7200,7 +7386,7 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
|
|
|
7200
7386
|
data
|
|
7201
7387
|
}),
|
|
7202
7388
|
listen: async ()=>{
|
|
7203
|
-
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.`);
|
|
7204
7390
|
let serverTerminator = getServerTerminator(httpServer);
|
|
7205
7391
|
return src_logger.debug('listen dev server'), context.hooks.onCloseDevServer.tap(serverTerminator), new Promise((resolve)=>{
|
|
7206
7392
|
httpServer.listen({
|
|
@@ -7241,172 +7427,7 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
|
|
|
7241
7427
|
config,
|
|
7242
7428
|
buildManager,
|
|
7243
7429
|
root
|
|
7244
|
-
}), (devMiddlewares = (
|
|
7245
|
-
let middlewares = [], { buildManager } = options;
|
|
7246
|
-
isVerbose() && middlewares.push(getRequestLoggerMiddleware());
|
|
7247
|
-
let { before, after } = ((config, devServerAPI)=>{
|
|
7248
|
-
let setupMiddlewares = config.dev.setupMiddlewares || [], serverOptions = pick(devServerAPI, [
|
|
7249
|
-
'sockWrite',
|
|
7250
|
-
'environments'
|
|
7251
|
-
]), before = [], after = [];
|
|
7252
|
-
for (let handler of helpers_castArray(setupMiddlewares))handler({
|
|
7253
|
-
unshift: (...handlers)=>before.unshift(...handlers),
|
|
7254
|
-
push: (...handlers)=>after.push(...handlers)
|
|
7255
|
-
}, serverOptions);
|
|
7256
|
-
return {
|
|
7257
|
-
before,
|
|
7258
|
-
after
|
|
7259
|
-
};
|
|
7260
|
-
})(options.config, options.devServerAPI);
|
|
7261
|
-
middlewares.push(...before);
|
|
7262
|
-
let { onUpgrade } = (({ config, buildManager, context, devServerAPI, middlewares, postCallbacks })=>{
|
|
7263
|
-
let upgradeEvents = [], { server } = config;
|
|
7264
|
-
if (server.cors) {
|
|
7265
|
-
let corsMiddleware = requireCompiledPackage('cors');
|
|
7266
|
-
middlewares.push(corsMiddleware('boolean' == typeof server.cors ? {} : server.cors));
|
|
7267
|
-
}
|
|
7268
|
-
let { headers } = server;
|
|
7269
|
-
if (headers && middlewares.push((_req, res, next)=>{
|
|
7270
|
-
for (let [key, value] of Object.entries(headers))res.setHeader(key, value);
|
|
7271
|
-
next();
|
|
7272
|
-
}), server.proxy) {
|
|
7273
|
-
let { middlewares: proxyMiddlewares, upgrade } = createProxyMiddleware(server.proxy);
|
|
7274
|
-
for (let middleware of (upgradeEvents.push(upgrade), proxyMiddlewares))middlewares.push(middleware);
|
|
7275
|
-
}
|
|
7276
|
-
let { compress } = server;
|
|
7277
|
-
if (compress && middlewares.push(gzipMiddleware_gzipMiddleware('object' == typeof compress ? compress : void 0)), 'dev' === context.action && 'rspack' === context.bundlerType && buildManager) {
|
|
7278
|
-
let { compiler } = buildManager;
|
|
7279
|
-
(compiler_isMultiCompiler(compiler) ? compiler.compilers.some((childCompiler)=>childCompiler.options.lazyCompilation) : compiler.options.lazyCompilation) && middlewares.push(rspack_rspack.lazyCompilationMiddleware(compiler));
|
|
7280
|
-
}
|
|
7281
|
-
server.base && '/' !== server.base && middlewares.push(getBaseUrlMiddleware({
|
|
7282
|
-
base: server.base
|
|
7283
|
-
}));
|
|
7284
|
-
let launchEditorMiddleware = requireCompiledPackage('launch-editor-middleware');
|
|
7285
|
-
for (let { name } of (middlewares.push([
|
|
7286
|
-
'/__open-in-editor',
|
|
7287
|
-
launchEditorMiddleware()
|
|
7288
|
-
]), middlewares.push((({ environments })=>async function viewingServedFilesMiddleware(req, res, next) {
|
|
7289
|
-
if ('/rsbuild-dev-server' !== req.url.replace(postfixRE, '')) return void next();
|
|
7290
|
-
res.writeHead(200, {
|
|
7291
|
-
'Content-Type': 'text/html; charset=utf-8'
|
|
7292
|
-
}), res.write(`<!DOCTYPE html>
|
|
7293
|
-
<html>
|
|
7294
|
-
<head>
|
|
7295
|
-
<meta charset="utf-8"/>
|
|
7296
|
-
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
7297
|
-
<style>
|
|
7298
|
-
body {
|
|
7299
|
-
margin: 0;
|
|
7300
|
-
color: #f6f7f9;
|
|
7301
|
-
padding: 32px 40px;
|
|
7302
|
-
line-height: 1.8;
|
|
7303
|
-
min-height: 100vh;
|
|
7304
|
-
background-image: linear-gradient(#020917, #101725);
|
|
7305
|
-
font-family: ui-sans-serif,system-ui,sans-serif;
|
|
7306
|
-
}
|
|
7307
|
-
h1, h2 {
|
|
7308
|
-
font-weight: 500;
|
|
7309
|
-
}
|
|
7310
|
-
h1 {
|
|
7311
|
-
margin: 0;
|
|
7312
|
-
font-size: 36px;
|
|
7313
|
-
}
|
|
7314
|
-
h2 {
|
|
7315
|
-
font-size: 20px;
|
|
7316
|
-
margin: 24px 0 16px;
|
|
7317
|
-
}
|
|
7318
|
-
ul {
|
|
7319
|
-
margin: 0;
|
|
7320
|
-
padding-left: 16px;
|
|
7321
|
-
}
|
|
7322
|
-
a {
|
|
7323
|
-
color: #58c4dc;
|
|
7324
|
-
text-decoration: none;
|
|
7325
|
-
}
|
|
7326
|
-
a:hover {
|
|
7327
|
-
text-decoration: underline;
|
|
7328
|
-
}
|
|
7329
|
-
</style>
|
|
7330
|
-
</head>
|
|
7331
|
-
<body>
|
|
7332
|
-
<h1>Assets Report</h1>
|
|
7333
|
-
</body>
|
|
7334
|
-
</html>`);
|
|
7335
|
-
try {
|
|
7336
|
-
for(let key in environments){
|
|
7337
|
-
res.write(`<h2>Environment: ${key}</h2>`);
|
|
7338
|
-
let list = [], environment = environments[key], stats = await environment.getStats(), assets = Object.keys(stats.compilation.assets);
|
|
7339
|
-
for (let asset of (res.write('<ul>'), assets))list.push(`<li><a target="_blank" href="${asset}">${asset}</a></li>`);
|
|
7340
|
-
res.write(list?.join('')), res.write('</ul>');
|
|
7341
|
-
}
|
|
7342
|
-
res.end('</body></html>');
|
|
7343
|
-
} catch (err) {
|
|
7344
|
-
src_logger.error(err), res.writeHead(500), res.end('Failed to list the files');
|
|
7345
|
-
}
|
|
7346
|
-
})({
|
|
7347
|
-
environments: devServerAPI.environments
|
|
7348
|
-
})), buildManager && (middlewares.push(buildManager.assetsMiddleware), upgradeEvents.push(buildManager.socketServer.upgrade), middlewares.push(function hotUpdateJsonFallbackMiddleware(req, res, next) {
|
|
7349
|
-
req.url?.endsWith('.hot-update.json') && 'OPTIONS' !== req.method ? (res.statusCode = 404, res.end()) : next();
|
|
7350
|
-
})), buildManager && middlewares.push((({ distPath, buildManager })=>async function htmlCompletionMiddleware(req, res, next) {
|
|
7351
|
-
if (!maybeHTMLRequest(req)) return void next();
|
|
7352
|
-
let pathname = req.url.replace(postfixRE, ''), rewrite = (newUrl)=>{
|
|
7353
|
-
req.url = newUrl, buildManager.assetsMiddleware(req, res, (...args)=>{
|
|
7354
|
-
next(...args);
|
|
7355
|
-
});
|
|
7356
|
-
};
|
|
7357
|
-
if (pathname.endsWith('/')) {
|
|
7358
|
-
let newUrl = `${pathname}index.html`, filePath = external_node_path_.default.join(distPath, newUrl);
|
|
7359
|
-
if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) return void rewrite(newUrl);
|
|
7360
|
-
} else if (!external_node_path_.default.extname(pathname)) {
|
|
7361
|
-
let newUrl = `${pathname}.html`, filePath = external_node_path_.default.join(distPath, newUrl);
|
|
7362
|
-
if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) return void rewrite(newUrl);
|
|
7363
|
-
}
|
|
7364
|
-
next();
|
|
7365
|
-
})({
|
|
7366
|
-
buildManager,
|
|
7367
|
-
distPath: context.distPath
|
|
7368
|
-
})), server.publicDir)){
|
|
7369
|
-
let sirvMiddleware = requireCompiledPackage('sirv')(name, {
|
|
7370
|
-
etag: !0,
|
|
7371
|
-
dev: !0
|
|
7372
|
-
});
|
|
7373
|
-
middlewares.push(function publicDirMiddleware(req, res, next) {
|
|
7374
|
-
sirvMiddleware(req, res, next);
|
|
7375
|
-
});
|
|
7376
|
-
}
|
|
7377
|
-
for (let callback of postCallbacks)callback();
|
|
7378
|
-
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) {
|
|
7379
|
-
if (!maybeHTMLRequest(req) || '/favicon.ico' === req.url || 'index' !== htmlFallback) return void next();
|
|
7380
|
-
let filePath = external_node_path_.default.join(distPath, 'index.html');
|
|
7381
|
-
if (await middlewares_isFileExists(filePath, buildManager.outputFileSystem)) {
|
|
7382
|
-
let newUrl = '/index.html';
|
|
7383
|
-
isVerbose() && src_logger.debug(` ${req.method} ${req.url} ${color.yellow('fallback to')} ${newUrl}`), req.url = newUrl, buildManager.assetsMiddleware(req, res, (...args)=>{
|
|
7384
|
-
next(...args);
|
|
7385
|
-
});
|
|
7386
|
-
return;
|
|
7387
|
-
}
|
|
7388
|
-
next();
|
|
7389
|
-
})({
|
|
7390
|
-
buildManager,
|
|
7391
|
-
distPath: context.distPath,
|
|
7392
|
-
htmlFallback: server.htmlFallback
|
|
7393
|
-
})), middlewares.push(faviconFallbackMiddleware), {
|
|
7394
|
-
onUpgrade: (...args)=>{
|
|
7395
|
-
for (let cb of upgradeEvents)cb(...args);
|
|
7396
|
-
}
|
|
7397
|
-
};
|
|
7398
|
-
})({
|
|
7399
|
-
...options,
|
|
7400
|
-
middlewares
|
|
7401
|
-
});
|
|
7402
|
-
return middlewares.push(...after), {
|
|
7403
|
-
close: async ()=>{
|
|
7404
|
-
await buildManager?.close();
|
|
7405
|
-
},
|
|
7406
|
-
onUpgrade,
|
|
7407
|
-
middlewares
|
|
7408
|
-
};
|
|
7409
|
-
})({
|
|
7430
|
+
}), (devMiddlewares = await getDevMiddlewares({
|
|
7410
7431
|
buildManager,
|
|
7411
7432
|
config,
|
|
7412
7433
|
devServerAPI,
|
|
@@ -7415,71 +7436,6 @@ async function devServer_createDevServer(options, createCompiler, config, { comp
|
|
|
7415
7436
|
})).middlewares))Array.isArray(item) ? middlewares.use(...item) : middlewares.use(item);
|
|
7416
7437
|
return buildManager?.watch(), src_logger.debug('create dev server done'), devServerAPI;
|
|
7417
7438
|
}
|
|
7418
|
-
let rspackProvider = ({ context, pluginManager, rsbuildOptions })=>{
|
|
7419
|
-
let createCompiler = async ()=>(await createCompiler_createCompiler({
|
|
7420
|
-
context,
|
|
7421
|
-
pluginManager,
|
|
7422
|
-
rsbuildOptions
|
|
7423
|
-
})).compiler;
|
|
7424
|
-
return {
|
|
7425
|
-
bundler: 'rspack',
|
|
7426
|
-
createCompiler,
|
|
7427
|
-
async createDevServer (options) {
|
|
7428
|
-
let config = await initRsbuildConfig({
|
|
7429
|
-
context,
|
|
7430
|
-
pluginManager
|
|
7431
|
-
});
|
|
7432
|
-
return devServer_createDevServer({
|
|
7433
|
-
context,
|
|
7434
|
-
pluginManager,
|
|
7435
|
-
rsbuildOptions
|
|
7436
|
-
}, createCompiler, config, options);
|
|
7437
|
-
},
|
|
7438
|
-
async startDevServer (options) {
|
|
7439
|
-
let config = await initRsbuildConfig({
|
|
7440
|
-
context,
|
|
7441
|
-
pluginManager
|
|
7442
|
-
});
|
|
7443
|
-
return (await devServer_createDevServer({
|
|
7444
|
-
context,
|
|
7445
|
-
pluginManager,
|
|
7446
|
-
rsbuildOptions
|
|
7447
|
-
}, createCompiler, config, options)).listen();
|
|
7448
|
-
},
|
|
7449
|
-
build: async (options)=>build_build({
|
|
7450
|
-
context,
|
|
7451
|
-
pluginManager,
|
|
7452
|
-
rsbuildOptions
|
|
7453
|
-
}, options),
|
|
7454
|
-
async initConfigs (options) {
|
|
7455
|
-
if (context.action && options?.action && context.action !== options.action) throw Error(`\
|
|
7456
|
-
[rsbuild] initConfigs() can only be called with the same action type.
|
|
7457
|
-
- Expected: ${context.action}
|
|
7458
|
-
- Actual: ${options?.action}`);
|
|
7459
|
-
options?.action && (context.action = options.action);
|
|
7460
|
-
let { rspackConfigs } = await initConfigs({
|
|
7461
|
-
context,
|
|
7462
|
-
pluginManager,
|
|
7463
|
-
rsbuildOptions
|
|
7464
|
-
});
|
|
7465
|
-
return rspackConfigs;
|
|
7466
|
-
},
|
|
7467
|
-
async inspectConfig (inspectOptions) {
|
|
7468
|
-
let bundlerConfigs = (await initConfigs({
|
|
7469
|
-
context,
|
|
7470
|
-
pluginManager,
|
|
7471
|
-
rsbuildOptions
|
|
7472
|
-
})).rspackConfigs;
|
|
7473
|
-
return inspectConfig_inspectConfig({
|
|
7474
|
-
context,
|
|
7475
|
-
pluginManager,
|
|
7476
|
-
rsbuildOptions,
|
|
7477
|
-
inspectOptions,
|
|
7478
|
-
bundlerConfigs
|
|
7479
|
-
});
|
|
7480
|
-
}
|
|
7481
|
-
};
|
|
7482
|
-
};
|
|
7483
7439
|
class RsbuildProdServer {
|
|
7484
7440
|
app;
|
|
7485
7441
|
options;
|
|
@@ -7493,7 +7449,7 @@ class RsbuildProdServer {
|
|
|
7493
7449
|
async applyDefaultMiddlewares() {
|
|
7494
7450
|
let { headers, proxy, historyApiFallback, compress, base, cors } = this.options.serverConfig;
|
|
7495
7451
|
if (isVerbose() && this.middlewares.use(getRequestLoggerMiddleware()), cors) {
|
|
7496
|
-
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));
|
|
7497
7453
|
this.middlewares.use(corsMiddleware('boolean' == typeof cors ? {} : cors));
|
|
7498
7454
|
}
|
|
7499
7455
|
if (headers && this.middlewares.use((_req, res, next)=>{
|
|
@@ -7513,10 +7469,12 @@ class RsbuildProdServer {
|
|
|
7513
7469
|
}
|
|
7514
7470
|
base && '/' !== base && this.middlewares.use(getBaseUrlMiddleware({
|
|
7515
7471
|
base
|
|
7516
|
-
})), 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);
|
|
7517
7473
|
}
|
|
7518
|
-
applyStaticAssetMiddleware() {
|
|
7519
|
-
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, {
|
|
7520
7478
|
etag: !0,
|
|
7521
7479
|
dev: !0,
|
|
7522
7480
|
ignores: [
|
|
@@ -7536,7 +7494,7 @@ class RsbuildProdServer {
|
|
|
7536
7494
|
async function startProdServer(context, config, { getPortSilently } = {}) {
|
|
7537
7495
|
let { port, host, https, portTip } = await getServerConfig({
|
|
7538
7496
|
config
|
|
7539
|
-
}),
|
|
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({
|
|
7540
7498
|
pwd: context.rootPath,
|
|
7541
7499
|
output: {
|
|
7542
7500
|
path: context.distPath,
|
|
@@ -7577,7 +7535,8 @@ async function startProdServer(context, config, { getPortSilently } = {}) {
|
|
|
7577
7535
|
routes,
|
|
7578
7536
|
protocol,
|
|
7579
7537
|
printUrls: serverConfig.printUrls,
|
|
7580
|
-
trailingLineBreak: !cliShortcutsEnabled
|
|
7538
|
+
trailingLineBreak: !cliShortcutsEnabled,
|
|
7539
|
+
originalConfig: context.originalConfig
|
|
7581
7540
|
}), openPage = async ()=>open_open({
|
|
7582
7541
|
https,
|
|
7583
7542
|
port,
|
|
@@ -7620,7 +7579,7 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
7620
7579
|
javascript: {
|
|
7621
7580
|
exportsPresence: 'error'
|
|
7622
7581
|
}
|
|
7623
|
-
}), 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({
|
|
7624
7583
|
javascript: {
|
|
7625
7584
|
typeReexportsPresence: 'tolerant'
|
|
7626
7585
|
}
|
|
@@ -7631,7 +7590,7 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
7631
7590
|
force: !1
|
|
7632
7591
|
}
|
|
7633
7592
|
}
|
|
7634
|
-
})
|
|
7593
|
+
});
|
|
7635
7594
|
});
|
|
7636
7595
|
}
|
|
7637
7596
|
},
|
|
@@ -7657,7 +7616,7 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
7657
7616
|
if (bundlerConfigs.some(({ plugins })=>plugins?.some(isModuleFederationPlugin))) return void bundlerConfigs.forEach((config)=>{
|
|
7658
7617
|
config.entry = {};
|
|
7659
7618
|
});
|
|
7660
|
-
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.`);
|
|
7661
7620
|
}
|
|
7662
7621
|
});
|
|
7663
7622
|
}
|
|
@@ -7670,7 +7629,7 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
7670
7629
|
let { sourceMap } = config.output, isProd = 'production' === config.mode;
|
|
7671
7630
|
return !1 !== sourceMap && (!0 === sourceMap ? isProd ? 'source-map' : 'cheap-module-source-map' : void 0 === sourceMap.js ? !isProd && 'cheap-module-source-map' : sourceMap.js);
|
|
7672
7631
|
})(config);
|
|
7673
|
-
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)=>{
|
|
7674
7633
|
let { sourceMap } = config.output;
|
|
7675
7634
|
return 'object' == typeof sourceMap && sourceMap.css;
|
|
7676
7635
|
})(config) && chain.plugin('source-map-css').use(bundler.SourceMapDevToolPlugin, [
|
|
@@ -7687,13 +7646,11 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
7687
7646
|
setup (api) {
|
|
7688
7647
|
let cacheEnabled = !1;
|
|
7689
7648
|
api.modifyBundlerChain(async (chain, { environment, env })=>{
|
|
7690
|
-
let { config } = environment, {
|
|
7649
|
+
let { config } = environment, { buildCache = !1 } = config.performance;
|
|
7691
7650
|
if (!1 === buildCache) return;
|
|
7692
7651
|
cacheEnabled = !0;
|
|
7693
|
-
let { context } = api, cacheConfig = 'boolean' == typeof buildCache ? {} : buildCache, cacheDirectory = getCacheDirectory(cacheConfig, context), buildDependencies = await getBuildDependencies(context, config, environment, cacheConfig.buildDependencies)
|
|
7694
|
-
|
|
7695
|
-
let cacheVersion = Array.isArray(cacheConfig.cacheDigest) && cacheConfig.cacheDigest.length ? `${environment.name}-${env}-${await helpers_hash(JSON.stringify(cacheConfig.cacheDigest))}` : `${environment.name}-${env}`;
|
|
7696
|
-
'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({
|
|
7697
7654
|
...chain.get('experiments'),
|
|
7698
7655
|
cache: {
|
|
7699
7656
|
type: 'persistent',
|
|
@@ -7704,14 +7661,9 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
7704
7661
|
},
|
|
7705
7662
|
buildDependencies: Object.values(buildDependencies).flat()
|
|
7706
7663
|
}
|
|
7707
|
-
})) : chain.cache({
|
|
7708
|
-
name: cacheVersion,
|
|
7709
|
-
type: 'filesystem',
|
|
7710
|
-
cacheDirectory,
|
|
7711
|
-
buildDependencies
|
|
7712
7664
|
});
|
|
7713
7665
|
}), api.onAfterCreateCompiler(()=>{
|
|
7714
|
-
cacheEnabled &&
|
|
7666
|
+
cacheEnabled && src_logger.debug('Rspack persistent cache enabled');
|
|
7715
7667
|
});
|
|
7716
7668
|
}
|
|
7717
7669
|
},
|
|
@@ -7755,10 +7707,10 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
7755
7707
|
} : external_node_path_.posix.join(jsPath, jsFilename)).chunkFilename(isJsFilenameFn ? (...args)=>{
|
|
7756
7708
|
let name = jsFilename(...args);
|
|
7757
7709
|
return external_node_path_.posix.join(jsAsyncPath, name);
|
|
7758
|
-
} : external_node_path_.posix.join(jsAsyncPath, jsFilename)).publicPath(publicPath)
|
|
7710
|
+
} : external_node_path_.posix.join(jsAsyncPath, jsFilename)).publicPath(publicPath), isServer && chain.output.library({
|
|
7759
7711
|
type: 'commonjs2',
|
|
7760
7712
|
...chain.output.get('library') || {}
|
|
7761
|
-
}), config.output.copy
|
|
7713
|
+
}), config.output.copy) {
|
|
7762
7714
|
let { copy } = config.output, options = Array.isArray(copy) ? {
|
|
7763
7715
|
patterns: copy
|
|
7764
7716
|
} : copy;
|
|
@@ -7793,9 +7745,9 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
7793
7745
|
chain,
|
|
7794
7746
|
config,
|
|
7795
7747
|
rootPath: api.context.rootPath
|
|
7796
|
-
}), chain.module.rule(CHAIN_ID.RULE.MJS).test(/\.m?js/).resolve.set('fullySpecified', !1)
|
|
7797
|
-
let aliasStrategy = config.
|
|
7798
|
-
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({
|
|
7799
7751
|
configFile: tsconfigPath,
|
|
7800
7752
|
references: 'auto'
|
|
7801
7753
|
});
|
|
@@ -7831,7 +7783,7 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
7831
7783
|
})).catch((err)=>{
|
|
7832
7784
|
src_logger.warn('Failed to print file size.'), src_logger.warn(err);
|
|
7833
7785
|
});
|
|
7834
|
-
logs && src_logger.log(logs.join('
|
|
7786
|
+
logs && src_logger.log(logs.join('')), showDiff && await saveSnapshots(snapshotPath, nextSnapshots);
|
|
7835
7787
|
});
|
|
7836
7788
|
}
|
|
7837
7789
|
},
|
|
@@ -7845,7 +7797,7 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
7845
7797
|
return 'auto' === enable ? isDev && !config.dev.writeToDisk ? void 0 : isStrictSubdir(rootPath, distPath) ? {
|
|
7846
7798
|
path: distPath,
|
|
7847
7799
|
keep
|
|
7848
|
-
} : (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 ? {
|
|
7849
7801
|
path: distPath,
|
|
7850
7802
|
keep
|
|
7851
7803
|
} : void 0;
|
|
@@ -8015,7 +7967,9 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
8015
7967
|
}, async ({ compilation, environment, sources })=>{
|
|
8016
7968
|
let { config } = environment, { appIcon } = config.html;
|
|
8017
7969
|
if (!appIcon) return;
|
|
8018
|
-
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)=>{
|
|
8019
7973
|
let { src, size } = icon, cacheKey = `${distDir}|${publicPath}|${src}`, cached = iconFormatMap.get(cacheKey);
|
|
8020
7974
|
if (cached) return cached;
|
|
8021
7975
|
let sizes = `${size}x${size}`;
|
|
@@ -8042,23 +7996,19 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
8042
7996
|
})(icon, distDir, publicPath, lookup)), tags = [];
|
|
8043
7997
|
for (let icon of icons){
|
|
8044
7998
|
if ('web-app-manifest' === icon.target && !appIcon.name) {
|
|
8045
|
-
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"')}.`);
|
|
8046
8000
|
continue;
|
|
8047
8001
|
}
|
|
8048
8002
|
if (!icon.isURL) {
|
|
8049
8003
|
if (!compilation.inputFileSystem) {
|
|
8050
|
-
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.`);
|
|
8051
8005
|
continue;
|
|
8052
8006
|
}
|
|
8053
8007
|
if (!await fileExistsByCompilation(compilation, icon.absolutePath)) {
|
|
8054
|
-
addCompilationError(compilation, `${
|
|
8055
|
-
continue;
|
|
8056
|
-
}
|
|
8057
|
-
let source = await external_node_util_promisify(compilation.inputFileSystem.readFile)(icon.absolutePath);
|
|
8058
|
-
if (!source) {
|
|
8059
|
-
addCompilationError(compilation, `${color.dim('[rsbuild:app-icon]')} Failed to read the icon file at ${color.yellow(icon.absolutePath)}.`);
|
|
8008
|
+
addCompilationError(compilation, `${picocolors_default().dim('[rsbuild:app-icon]')} Failed to find the icon file at ${picocolors_default().yellow(icon.absolutePath)}.`);
|
|
8060
8009
|
continue;
|
|
8061
8010
|
}
|
|
8011
|
+
let source = await readFileAsync(compilation.inputFileSystem, icon.absolutePath);
|
|
8062
8012
|
compilation.emitAsset(icon.relativePath, new sources.RawSource(source));
|
|
8063
8013
|
}
|
|
8064
8014
|
('apple-touch-icon' === icon.target || !icon.target && icon.size < 200) && tags.push({
|
|
@@ -8111,7 +8061,7 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
8111
8061
|
name: 'rsbuild:wasm',
|
|
8112
8062
|
setup (api) {
|
|
8113
8063
|
api.modifyBundlerChain((chain, { CHAIN_ID, environment, isProd })=>{
|
|
8114
|
-
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));
|
|
8115
8065
|
chain.experiments({
|
|
8116
8066
|
...chain.get('experiments'),
|
|
8117
8067
|
asyncWebAssembly: !0
|
|
@@ -8146,7 +8096,7 @@ function applyDefaultPlugins(pluginManager, context) {
|
|
|
8146
8096
|
raw: !0
|
|
8147
8097
|
}, ({ code, emitFile, resourcePath })=>{
|
|
8148
8098
|
let name, filename = (name = resourcePath && external_node_path_.default.parse(resourcePath).name) ? `${name}.node` : null;
|
|
8149
|
-
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)}`);
|
|
8150
8100
|
emitFile(filename, code);
|
|
8151
8101
|
let config = api.getNormalizedConfig(), handleErrorSnippet = `throw new Error('Failed to load Node.js addon: "${filename}"', {
|
|
8152
8102
|
cause: error,
|
|
@@ -8227,7 +8177,7 @@ try {
|
|
|
8227
8177
|
});
|
|
8228
8178
|
rule.use(CHAIN_ID.USE.STYLE).loader(getCompiledPath('style-loader')).options(styleLoaderOptions);
|
|
8229
8179
|
} else rule.use(CHAIN_ID.USE.MINI_CSS_EXTRACT).loader((cssExtractPlugin || rspack_rspack.CssExtractRspackPlugin).loader).options(config.tools.cssExtract.loaderOptions);
|
|
8230
|
-
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'));
|
|
8231
8181
|
let importLoaders = {
|
|
8232
8182
|
normal: 0,
|
|
8233
8183
|
inline: 0
|
|
@@ -8236,15 +8186,15 @@ try {
|
|
|
8236
8186
|
}, cssLoaderPath = getCompiledPath('css-loader');
|
|
8237
8187
|
if (updateRules((rule)=>{
|
|
8238
8188
|
rule.use(CHAIN_ID.USE.CSS).loader(cssLoaderPath);
|
|
8239
|
-
}),
|
|
8189
|
+
}), !1 !== config.tools.lightningcssLoader) {
|
|
8240
8190
|
emitCss && importLoaders.normal++, importLoaders.inline++;
|
|
8241
|
-
let
|
|
8191
|
+
let minifyCss = parseMinifyOptions(config).minifyCss, { browserslist } = environment;
|
|
8242
8192
|
if ('node' === target) {
|
|
8243
8193
|
let webEnvironment = Object.values(environments).find((env)=>'web' === env.config.output.target);
|
|
8244
|
-
webEnvironment
|
|
8194
|
+
webEnvironment && (browserslist = webEnvironment.browserslist, minifyCss = parseMinifyOptions(webEnvironment.config).minifyCss);
|
|
8245
8195
|
}
|
|
8246
8196
|
updateRules((rule, type)=>{
|
|
8247
|
-
let
|
|
8197
|
+
let minify = ('inline' === type || config.output.injectStyles) && minifyCss, lightningcssOptions = getLightningCSSLoaderOptions(config, browserslist, minify);
|
|
8248
8198
|
rule.use(CHAIN_ID.USE.LIGHTNINGCSS).loader('builtin:lightningcss-loader').options(lightningcssOptions);
|
|
8249
8199
|
}, {
|
|
8250
8200
|
skipNormal: !emitCss
|
|
@@ -8335,36 +8285,11 @@ try {
|
|
|
8335
8285
|
{
|
|
8336
8286
|
name: 'rsbuild:minimize',
|
|
8337
8287
|
setup (api) {
|
|
8338
|
-
let isRspack = 'rspack' === api.context.bundlerType;
|
|
8339
8288
|
api.modifyBundlerChain((chain, { environment, CHAIN_ID, rspack })=>{
|
|
8340
8289
|
let { config } = environment, { minifyJs, minifyCss, jsOptions, cssOptions } = parseMinifyOptions(config);
|
|
8341
|
-
if (chain.optimization.minimize(minifyJs || minifyCss), minifyJs &&
|
|
8342
|
-
(
|
|
8343
|
-
|
|
8344
|
-
options.minimizerOptions ||= {}, options.minimizerOptions.format ||= {};
|
|
8345
|
-
let { removeConsole } = config.performance;
|
|
8346
|
-
if (!0 === removeConsole) options.minimizerOptions.compress = {
|
|
8347
|
-
drop_console: !0
|
|
8348
|
-
};
|
|
8349
|
-
else if (Array.isArray(removeConsole)) {
|
|
8350
|
-
let pureFuncs = removeConsole.map((method)=>`console.${method}`);
|
|
8351
|
-
options.minimizerOptions.compress = {
|
|
8352
|
-
pure_funcs: pureFuncs
|
|
8353
|
-
};
|
|
8354
|
-
}
|
|
8355
|
-
if (config.output.legalComments) switch(config.output.legalComments){
|
|
8356
|
-
case 'inline':
|
|
8357
|
-
options.minimizerOptions.format.comments = 'some', options.extractComments = !1;
|
|
8358
|
-
break;
|
|
8359
|
-
case 'linked':
|
|
8360
|
-
options.extractComments = !0;
|
|
8361
|
-
break;
|
|
8362
|
-
case 'none':
|
|
8363
|
-
options.minimizerOptions.format.comments = !1, options.extractComments = !1;
|
|
8364
|
-
}
|
|
8365
|
-
return (options.minimizerOptions.format.asciiOnly = 'ascii' === config.output.charset, jsOptions) ? cjs_default()(options, jsOptions) : options;
|
|
8366
|
-
})(config, jsOptions)
|
|
8367
|
-
]).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) {
|
|
8368
8293
|
let loaderOptions = getLightningCSSLoaderOptions(config, environment.browserslist, !0), defaultOptions = {
|
|
8369
8294
|
minimizerOptions: {
|
|
8370
8295
|
targets: isPlainObject(loaderOptions.targets) ? environment.browserslist : loaderOptions.targets,
|
|
@@ -8389,7 +8314,7 @@ try {
|
|
|
8389
8314
|
{
|
|
8390
8315
|
name: 'rsbuild:progress',
|
|
8391
8316
|
setup (api) {
|
|
8392
|
-
|
|
8317
|
+
api.modifyBundlerChain((chain, { CHAIN_ID, environment, rspack })=>{
|
|
8393
8318
|
let { config } = environment, options = config.dev.progressBar;
|
|
8394
8319
|
if (!options) return;
|
|
8395
8320
|
let prefix = !0 !== options && void 0 !== options.id ? options.id : environment.name;
|
|
@@ -8420,12 +8345,12 @@ try {
|
|
|
8420
8345
|
"application/javascript"
|
|
8421
8346
|
]
|
|
8422
8347
|
});
|
|
8423
|
-
|
|
8348
|
+
applyScriptCondition({
|
|
8424
8349
|
rule,
|
|
8425
8350
|
isDev,
|
|
8426
8351
|
config,
|
|
8427
8352
|
rsbuildTarget: target
|
|
8428
|
-
})
|
|
8353
|
+
});
|
|
8429
8354
|
let swcConfig = getDefaultSwcConfig({
|
|
8430
8355
|
browserslist,
|
|
8431
8356
|
cacheRoot,
|
|
@@ -8433,23 +8358,22 @@ try {
|
|
|
8433
8358
|
isProd
|
|
8434
8359
|
});
|
|
8435
8360
|
if (applyTransformImport(swcConfig, config.source.transformImport), applySwcDecoratorConfig(swcConfig, config), isWebTarget(target)) {
|
|
8436
|
-
let
|
|
8437
|
-
if ('off'
|
|
8438
|
-
|
|
8439
|
-
swcConfig.
|
|
8440
|
-
|
|
8441
|
-
for (let item of [
|
|
8361
|
+
let { polyfill } = config.output;
|
|
8362
|
+
if ('off' !== polyfill) {
|
|
8363
|
+
swcConfig.env.mode = polyfill;
|
|
8364
|
+
let coreJsDir = applyCoreJs(swcConfig, polyfill, api.context.rootPath);
|
|
8365
|
+
if (coreJsDir) for (let item of [
|
|
8442
8366
|
rule,
|
|
8443
8367
|
dataUriRule
|
|
8444
8368
|
])item.resolve.alias.set('core-js', coreJsDir);
|
|
8445
8369
|
}
|
|
8446
8370
|
}
|
|
8447
|
-
let
|
|
8371
|
+
let mergedConfig = reduceConfigs({
|
|
8448
8372
|
initial: swcConfig,
|
|
8449
8373
|
config: config.tools.swc,
|
|
8450
8374
|
mergeFn: cjs_default()
|
|
8451
8375
|
});
|
|
8452
|
-
rule.use(CHAIN_ID.USE.SWC).loader(builtinSwcLoaderName).options(
|
|
8376
|
+
mergedConfig.jsc?.target !== void 0 && mergedConfig.env?.targets !== void 0 && 1 === Object.keys(mergedConfig.env).length && delete mergedConfig.env, rule.use(CHAIN_ID.USE.SWC).loader(builtinSwcLoaderName).options(mergedConfig), dataUriRule.resolve.set('fullySpecified', !1).end().use(CHAIN_ID.USE.SWC).loader(builtinSwcLoaderName).options(cloneDeep(mergedConfig));
|
|
8453
8377
|
}
|
|
8454
8378
|
});
|
|
8455
8379
|
}
|
|
@@ -8488,9 +8412,7 @@ try {
|
|
|
8488
8412
|
let { config } = environment, defaultConfig = {
|
|
8489
8413
|
chunks: config.moduleFederation?.options?.exposes ? 'async' : 'all',
|
|
8490
8414
|
cacheGroups: {}
|
|
8491
|
-
};
|
|
8492
|
-
'webpack' === api.context.bundlerType && (defaultConfig.enforceSizeThreshold = 50000);
|
|
8493
|
-
let { chunkSplit } = config.performance, forceSplittingGroups = {};
|
|
8415
|
+
}, { chunkSplit } = config.performance, forceSplittingGroups = {};
|
|
8494
8416
|
chunkSplit.forceSplitting && (forceSplittingGroups = getForceSplittingGroups(chunkSplit.forceSplitting, chunkSplit.strategy));
|
|
8495
8417
|
let override = 'custom' === chunkSplit.strategy ? chunkSplit.splitChunks ?? chunkSplit.override : chunkSplit.override, splitChunksOptions = await SPLIT_STRATEGY_DISPATCHER[chunkSplit.strategy || 'split-by-experience']({
|
|
8496
8418
|
defaultConfig,
|
|
@@ -8507,32 +8429,37 @@ try {
|
|
|
8507
8429
|
{
|
|
8508
8430
|
name: 'rsbuild:inline-chunk',
|
|
8509
8431
|
setup (api) {
|
|
8510
|
-
let
|
|
8432
|
+
let inlineAssetsByEnvironment = new Map();
|
|
8511
8433
|
api.processAssets({
|
|
8512
8434
|
stage: 'summarize'
|
|
8513
|
-
}, ({ compiler, compilation })=>{
|
|
8514
|
-
|
|
8435
|
+
}, ({ compiler, compilation, environment })=>{
|
|
8436
|
+
let inlinedAssets = inlineAssetsByEnvironment.get(environment.name);
|
|
8437
|
+
if (!inlinedAssets || 0 === inlinedAssets.size) return;
|
|
8515
8438
|
let { devtool } = compiler.options, hasSourceMap = 'hidden-source-map' !== devtool && !1 !== devtool;
|
|
8516
|
-
for (let name of inlinedAssets)
|
|
8517
|
-
|
|
8518
|
-
|
|
8519
|
-
|
|
8520
|
-
|
|
8439
|
+
for (let name of inlinedAssets){
|
|
8440
|
+
let asset = compilation.assets[name];
|
|
8441
|
+
asset && (hasSourceMap && compilation.updateAsset(name, asset, {
|
|
8442
|
+
related: {
|
|
8443
|
+
sourceMap: null
|
|
8444
|
+
}
|
|
8445
|
+
}), compilation.deleteAsset(name));
|
|
8446
|
+
}
|
|
8521
8447
|
inlinedAssets.clear();
|
|
8522
8448
|
}), api.modifyHTMLTags(({ headTags, bodyTags }, { compiler, compilation, environment })=>{
|
|
8523
|
-
|
|
8449
|
+
var name;
|
|
8450
|
+
let set, { htmlPaths, config } = environment;
|
|
8524
8451
|
if (0 === Object.keys(htmlPaths).length) return {
|
|
8525
8452
|
headTags,
|
|
8526
8453
|
bodyTags
|
|
8527
8454
|
};
|
|
8528
|
-
let { scriptTests, styleTests } = getInlineTests(config);
|
|
8455
|
+
let inlinedAssets = (name = environment.name, (set = inlineAssetsByEnvironment.get(name)) || (set = new Set(), inlineAssetsByEnvironment.set(name, set)), set), { scriptTests, styleTests } = getInlineTests(config);
|
|
8529
8456
|
if (!scriptTests.length && !styleTests.length) return {
|
|
8530
8457
|
headTags,
|
|
8531
8458
|
bodyTags
|
|
8532
8459
|
};
|
|
8533
8460
|
let publicPath = getPublicPathFromCompiler(compiler), updateTag = (tag)=>{
|
|
8534
8461
|
var config;
|
|
8535
|
-
return config = environment.config, "script" === tag.tag ? ((publicPath, tag, compilation, scriptTests, config)=>{
|
|
8462
|
+
return config = environment.config, "script" === tag.tag ? ((publicPath, tag, compilation, inlinedAssets, scriptTests, config)=>{
|
|
8536
8463
|
let { assets } = compilation;
|
|
8537
8464
|
if (!(tag.attrs?.src && 'string' == typeof tag.attrs.src)) return tag;
|
|
8538
8465
|
let { src, ...otherAttrs } = tag.attrs, scriptName = publicPath ? src.replace(publicPath, '') : src, asset = assets[scriptName];
|
|
@@ -8551,7 +8478,7 @@ try {
|
|
|
8551
8478
|
}
|
|
8552
8479
|
};
|
|
8553
8480
|
return inlinedAssets.add(scriptName), ret;
|
|
8554
|
-
})(publicPath, tag, compilation, scriptTests, config) : 'link' === tag.tag && tag.attrs && 'stylesheet' === tag.attrs.rel ? ((publicPath, tag, compilation, styleTests, config)=>{
|
|
8481
|
+
})(publicPath, tag, compilation, inlinedAssets, scriptTests, config) : 'link' === tag.tag && tag.attrs && 'stylesheet' === tag.attrs.rel ? ((publicPath, tag, compilation, inlinedAssets, styleTests, config)=>{
|
|
8555
8482
|
let { assets } = compilation;
|
|
8556
8483
|
if (!(tag.attrs?.href && 'string' == typeof tag.attrs.href)) return tag;
|
|
8557
8484
|
let linkName = publicPath ? tag.attrs.href.replace(publicPath, '') : tag.attrs.href, asset = assets[linkName];
|
|
@@ -8567,7 +8494,7 @@ try {
|
|
|
8567
8494
|
})
|
|
8568
8495
|
};
|
|
8569
8496
|
return inlinedAssets.add(linkName), ret;
|
|
8570
|
-
})(publicPath, tag, compilation, styleTests, config) : tag;
|
|
8497
|
+
})(publicPath, tag, compilation, inlinedAssets, styleTests, config) : tag;
|
|
8571
8498
|
};
|
|
8572
8499
|
return {
|
|
8573
8500
|
headTags: headTags.map(updateTag),
|
|
@@ -8582,9 +8509,9 @@ try {
|
|
|
8582
8509
|
api.onBeforeCreateCompiler(async ({ bundlerConfigs })=>{
|
|
8583
8510
|
let packagePath, module;
|
|
8584
8511
|
if ('true' !== process.env.RSDOCTOR) return;
|
|
8585
|
-
let
|
|
8512
|
+
let pluginName = 'RsdoctorRspackPlugin', isRsdoctorPlugin = (plugin)=>plugin?.isRsdoctorPlugin === !0 || plugin?.constructor?.name === pluginName;
|
|
8586
8513
|
for (let config of bundlerConfigs)if (config.plugins?.some((plugin)=>isRsdoctorPlugin(plugin))) return;
|
|
8587
|
-
let packageName =
|
|
8514
|
+
let packageName = '@rsdoctor/rspack-plugin';
|
|
8588
8515
|
try {
|
|
8589
8516
|
packagePath = rsdoctor_require.resolve(packageName, {
|
|
8590
8517
|
paths: [
|
|
@@ -8592,19 +8519,19 @@ try {
|
|
|
8592
8519
|
]
|
|
8593
8520
|
});
|
|
8594
8521
|
} catch {
|
|
8595
|
-
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.`);
|
|
8596
8523
|
return;
|
|
8597
8524
|
}
|
|
8598
8525
|
try {
|
|
8599
8526
|
let moduleURL = isWindows ? (0, external_node_url_.pathToFileURL)(packagePath).href : packagePath;
|
|
8600
8527
|
module = await import(moduleURL);
|
|
8601
8528
|
} catch {
|
|
8602
|
-
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.`);
|
|
8603
8530
|
return;
|
|
8604
8531
|
}
|
|
8605
8532
|
if (module && module[pluginName]) {
|
|
8606
8533
|
for (let config of bundlerConfigs)config.plugins ||= [], config.plugins.push(new module[pluginName]());
|
|
8607
|
-
src_logger.info(`${
|
|
8534
|
+
src_logger.info(`${picocolors_default().bold(picocolors_default().yellow(packageName))} enabled.`);
|
|
8608
8535
|
}
|
|
8609
8536
|
});
|
|
8610
8537
|
}
|
|
@@ -8669,31 +8596,6 @@ try {
|
|
|
8669
8596
|
});
|
|
8670
8597
|
}
|
|
8671
8598
|
},
|
|
8672
|
-
{
|
|
8673
|
-
name: 'rsbuild:performance',
|
|
8674
|
-
setup (api) {
|
|
8675
|
-
api.modifyRsbuildConfig({
|
|
8676
|
-
order: 'post',
|
|
8677
|
-
handler: (rsbuildConfig)=>{
|
|
8678
|
-
let applyBundleAnalyzeConfig = (config)=>{
|
|
8679
|
-
config.performance?.bundleAnalyze ? config.performance.bundleAnalyze = {
|
|
8680
|
-
generateStatsFile: !0,
|
|
8681
|
-
...config.performance.bundleAnalyze || {}
|
|
8682
|
-
} : (config.performance ??= {}, config.performance.bundleAnalyze = {
|
|
8683
|
-
analyzerMode: 'disabled',
|
|
8684
|
-
generateStatsFile: !0
|
|
8685
|
-
});
|
|
8686
|
-
};
|
|
8687
|
-
if (rsbuildConfig.performance?.profile) applyBundleAnalyzeConfig(rsbuildConfig);
|
|
8688
|
-
else if (rsbuildConfig.environments) for (let config of Object.values(rsbuildConfig.environments))config.performance?.profile && applyBundleAnalyzeConfig(config);
|
|
8689
|
-
}
|
|
8690
|
-
}), api.modifyBundlerChain((chain, { environment })=>{
|
|
8691
|
-
let { config } = environment, { profile } = config.performance;
|
|
8692
|
-
profile && chain.profile(profile);
|
|
8693
|
-
});
|
|
8694
|
-
}
|
|
8695
|
-
},
|
|
8696
|
-
pluginBundleAnalyzer(),
|
|
8697
8599
|
{
|
|
8698
8600
|
name: 'rsbuild:server',
|
|
8699
8601
|
setup (api) {
|
|
@@ -8708,21 +8610,21 @@ try {
|
|
|
8708
8610
|
};
|
|
8709
8611
|
api.onAfterStartDevServer(onStartServer), api.onAfterStartProdServer(onStartServer), api.onBeforeBuild(async ({ isFirstCompile, environments })=>{
|
|
8710
8612
|
if (isFirstCompile) for (let { name: publicDir, copyOnBuild } of api.getNormalizedConfig().server.publicDir){
|
|
8711
|
-
if (!1 === copyOnBuild || !
|
|
8613
|
+
if (!1 === copyOnBuild || !external_node_fs_.default.existsSync(publicDir)) continue;
|
|
8712
8614
|
let distPaths = dedupeNestedPaths(Object.values(environments).filter(({ config })=>!0 === copyOnBuild || 'auto' === copyOnBuild && 'node' !== config.output.target).map(({ distPath })=>distPath));
|
|
8713
8615
|
try {
|
|
8714
8616
|
await Promise.all(distPaths.map(async (distPath)=>{
|
|
8715
|
-
isDeno &&
|
|
8617
|
+
isDeno && external_node_fs_.default.existsSync(distPath) && await external_node_fs_.default.promises.rm(distPath, {
|
|
8716
8618
|
recursive: !0,
|
|
8717
8619
|
force: !0
|
|
8718
|
-
}), await
|
|
8620
|
+
}), await external_node_fs_.default.promises.cp(publicDir, distPath, {
|
|
8719
8621
|
recursive: !0,
|
|
8720
8622
|
dereference: !0,
|
|
8721
|
-
mode:
|
|
8623
|
+
mode: external_node_fs_.default.constants.COPYFILE_FICLONE
|
|
8722
8624
|
});
|
|
8723
8625
|
}));
|
|
8724
8626
|
} catch (err) {
|
|
8725
|
-
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;
|
|
8726
8628
|
}
|
|
8727
8629
|
}
|
|
8728
8630
|
});
|
|
@@ -8732,10 +8634,10 @@ try {
|
|
|
8732
8634
|
name: 'rsbuild:manifest',
|
|
8733
8635
|
setup (api) {
|
|
8734
8636
|
let manifestFilenames = new Map();
|
|
8735
|
-
api.modifyBundlerChain((chain, { CHAIN_ID, environment, isDev })=>{
|
|
8637
|
+
api.modifyBundlerChain(async (chain, { CHAIN_ID, environment, isDev })=>{
|
|
8736
8638
|
let { output: { manifest }, dev: { writeToDisk } } = environment.config;
|
|
8737
8639
|
if (!1 === manifest) return;
|
|
8738
|
-
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'));
|
|
8739
8641
|
manifestFilenames.set(environment.name, manifestOptions.filename);
|
|
8740
8642
|
let pluginOptions = {
|
|
8741
8643
|
fileName: manifestOptions.filename,
|
|
@@ -8792,7 +8694,7 @@ try {
|
|
|
8792
8694
|
manifestData
|
|
8793
8695
|
});
|
|
8794
8696
|
if (isObject(generatedManifest)) return environment.manifest = generatedManifest, generatedManifest;
|
|
8795
|
-
throw Error(`${
|
|
8697
|
+
throw Error(`${picocolors_default().dim('[rsbuild:manifest]')} \`manifest.generate\` function must return a valid manifest object.`);
|
|
8796
8698
|
}
|
|
8797
8699
|
return environment.manifest = manifestData, manifestData;
|
|
8798
8700
|
}
|
|
@@ -8803,7 +8705,7 @@ try {
|
|
|
8803
8705
|
}), api.onAfterCreateCompiler(()=>{
|
|
8804
8706
|
if (manifestFilenames.size <= 1) return void manifestFilenames.clear();
|
|
8805
8707
|
let environmentNames = Array.from(manifestFilenames.keys()), filenames = Array.from(manifestFilenames.values());
|
|
8806
|
-
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();
|
|
8807
8709
|
});
|
|
8808
8710
|
}
|
|
8809
8711
|
},
|
|
@@ -8811,9 +8713,7 @@ try {
|
|
|
8811
8713
|
{
|
|
8812
8714
|
name: 'rsbuild:rspack-profile',
|
|
8813
8715
|
setup (api) {
|
|
8814
|
-
let traceOutput;
|
|
8815
|
-
if ('webpack' === api.context.bundlerType) return;
|
|
8816
|
-
let { RSPACK_PROFILE } = process.env;
|
|
8716
|
+
let traceOutput, { RSPACK_PROFILE } = process.env;
|
|
8817
8717
|
if (!RSPACK_PROFILE) return;
|
|
8818
8718
|
let onStart = async ()=>{
|
|
8819
8719
|
traceOutput = await applyProfile(api.context.rootPath, RSPACK_PROFILE, process.env.RSPACK_TRACE_LAYER, process.env.RSPACK_TRACE_OUTPUT);
|
|
@@ -8821,7 +8721,7 @@ try {
|
|
|
8821
8721
|
api.onBeforeBuild(async ({ isFirstCompile })=>{
|
|
8822
8722
|
isFirstCompile && await onStart();
|
|
8823
8723
|
}), api.onBeforeStartDevServer(onStart), api.onExit(()=>{
|
|
8824
|
-
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)}`));
|
|
8825
8725
|
});
|
|
8826
8726
|
}
|
|
8827
8727
|
},
|
|
@@ -8830,7 +8730,7 @@ try {
|
|
|
8830
8730
|
apply: 'serve',
|
|
8831
8731
|
setup (api) {
|
|
8832
8732
|
api.modifyBundlerChain((chain, { environment, target })=>{
|
|
8833
|
-
if ('web' !== target
|
|
8733
|
+
if ('web' !== target) return;
|
|
8834
8734
|
let { config } = environment, options = config.dev?.lazyCompilation;
|
|
8835
8735
|
if (options) {
|
|
8836
8736
|
if (!0 === options && Object.keys(chain.entryPoints.entries() || {}).length <= 1) return void chain.lazyCompilation({
|
|
@@ -8850,7 +8750,6 @@ try {
|
|
|
8850
8750
|
name: 'rsbuild:sri',
|
|
8851
8751
|
setup (api) {
|
|
8852
8752
|
api.modifyBundlerChain((chain, { environment, CHAIN_ID, rspack })=>{
|
|
8853
|
-
if ('webpack' === api.context.bundlerType) return;
|
|
8854
8753
|
let { config, htmlPaths } = environment;
|
|
8855
8754
|
if (0 === Object.keys(htmlPaths).length) return;
|
|
8856
8755
|
let { sri } = config.security;
|
|
@@ -8877,7 +8776,7 @@ try {
|
|
|
8877
8776
|
let nonce = nonces[index], environment = environmentList.find((item)=>item.index === index);
|
|
8878
8777
|
if (!Object.keys(environment?.htmlPaths ?? {}).length || !nonce) return;
|
|
8879
8778
|
let injectCode = createVirtualModule(`__webpack_nonce__ = "${nonce}";`);
|
|
8880
|
-
new
|
|
8779
|
+
new rspack_rspack.EntryPlugin(compiler.context, injectCode, {
|
|
8881
8780
|
name: void 0
|
|
8882
8781
|
}).apply(compiler);
|
|
8883
8782
|
});
|
|
@@ -8934,17 +8833,31 @@ async function createRsbuild(options = {}) {
|
|
|
8934
8833
|
context.getPluginAPI = getPluginAPI;
|
|
8935
8834
|
let globalPluginAPI = getPluginAPI();
|
|
8936
8835
|
src_logger.debug('registering default plugins'), applyDefaultPlugins(pluginManager, context), src_logger.debug('default plugins registered');
|
|
8937
|
-
let
|
|
8938
|
-
|
|
8939
|
-
|
|
8940
|
-
|
|
8941
|
-
|
|
8942
|
-
|
|
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 = ()=>{
|
|
8943
8852
|
context.action || (context.action = 'development' === config.mode ? 'dev' : 'build');
|
|
8944
8853
|
}, rsbuild = {
|
|
8945
|
-
build: async (
|
|
8854
|
+
build: async (options)=>{
|
|
8946
8855
|
context.action = 'build', process.env.NODE_ENV || setNodeEnv('production');
|
|
8947
|
-
let buildInstance = await
|
|
8856
|
+
let buildInstance = await build_build({
|
|
8857
|
+
context,
|
|
8858
|
+
pluginManager,
|
|
8859
|
+
rsbuildOptions: resolvedOptions
|
|
8860
|
+
}, options);
|
|
8948
8861
|
return {
|
|
8949
8862
|
...buildInstance,
|
|
8950
8863
|
close: async ()=>{
|
|
@@ -8959,15 +8872,53 @@ async function createRsbuild(options = {}) {
|
|
|
8959
8872
|
pluginManager
|
|
8960
8873
|
}), { distPath } = context, { checkDistDir = !0 } = options;
|
|
8961
8874
|
if (checkDistDir) {
|
|
8962
|
-
if (!existsSync(distPath)) throw Error(`${
|
|
8963
|
-
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.`);
|
|
8964
8877
|
}
|
|
8965
8878
|
return startProdServer(context, config, options);
|
|
8966
8879
|
},
|
|
8967
|
-
startDevServer: (
|
|
8968
|
-
|
|
8969
|
-
|
|
8970
|
-
|
|
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
|
+
},
|
|
8971
8922
|
...pick(pluginManager, [
|
|
8972
8923
|
'addPlugins',
|
|
8973
8924
|
'getPlugins',
|
|
@@ -8997,9 +8948,6 @@ async function createRsbuild(options = {}) {
|
|
|
8997
8948
|
'onCloseDevServer',
|
|
8998
8949
|
'onDevCompileDone',
|
|
8999
8950
|
'onExit'
|
|
9000
|
-
]),
|
|
9001
|
-
...pick(providerInstance, [
|
|
9002
|
-
'initConfigs'
|
|
9003
8951
|
])
|
|
9004
8952
|
};
|
|
9005
8953
|
envs && (rsbuild.onCloseBuild(envs.cleanup), rsbuild.onCloseDevServer(envs.cleanup));
|
|
@@ -9028,8 +8976,8 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
|
|
|
9028
8976
|
let configExport, configFilePath = ((root, customConfig)=>{
|
|
9029
8977
|
if (customConfig) {
|
|
9030
8978
|
let customConfigPath = (0, external_node_path_.isAbsolute)(customConfig) ? customConfig : (0, external_node_path_.join)(root, customConfig);
|
|
9031
|
-
if (
|
|
9032
|
-
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)}`);
|
|
9033
8981
|
}
|
|
9034
8982
|
for (let file of [
|
|
9035
8983
|
'rsbuild.config.mjs',
|
|
@@ -9040,7 +8988,7 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
|
|
|
9040
8988
|
'rsbuild.config.cts'
|
|
9041
8989
|
]){
|
|
9042
8990
|
let configFile = (0, external_node_path_.join)(root, file);
|
|
9043
|
-
if (
|
|
8991
|
+
if (external_node_fs_.default.existsSync(configFile)) return configFile;
|
|
9044
8992
|
}
|
|
9045
8993
|
return null;
|
|
9046
8994
|
})(cwd, path);
|
|
@@ -9055,12 +9003,12 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
|
|
|
9055
9003
|
let configFileURL = (0, external_node_url_.pathToFileURL)(configFilePath).href, exportModule = await import(`${configFileURL}?t=${Date.now()}`);
|
|
9056
9004
|
configExport = exportModule.default ? exportModule.default : exportModule;
|
|
9057
9005
|
} catch (err) {
|
|
9058
|
-
let errorMessage = `Failed to load file with native loader: ${
|
|
9006
|
+
let errorMessage = `Failed to load file with native loader: ${picocolors_default().dim(configFilePath)}`;
|
|
9059
9007
|
if ('native' === loader) throw src_logger.error(errorMessage), err;
|
|
9060
9008
|
src_logger.debug(`${errorMessage}, fallback to jiti.`), src_logger.debug(err);
|
|
9061
9009
|
}
|
|
9062
9010
|
if (void 0 === configExport) try {
|
|
9063
|
-
let { createJiti } = await import("jiti"), jiti = createJiti(
|
|
9011
|
+
let { createJiti } = await import("jiti"), jiti = createJiti(import.meta.filename, {
|
|
9064
9012
|
moduleCache: !1,
|
|
9065
9013
|
interopDefault: !0,
|
|
9066
9014
|
nativeModules: [
|
|
@@ -9072,7 +9020,7 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
|
|
|
9072
9020
|
default: !0
|
|
9073
9021
|
});
|
|
9074
9022
|
} catch (err) {
|
|
9075
|
-
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;
|
|
9076
9024
|
}
|
|
9077
9025
|
if ('function' == typeof configExport) {
|
|
9078
9026
|
let command = process.argv[2], nodeEnv = process.env.NODE_ENV || '', result = await configExport({
|
|
@@ -9081,13 +9029,13 @@ async function loadConfig_loadConfig({ cwd = process.cwd(), path, envMode, meta,
|
|
|
9081
9029
|
envMode: envMode || nodeEnv,
|
|
9082
9030
|
meta
|
|
9083
9031
|
});
|
|
9084
|
-
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.`);
|
|
9085
9033
|
return {
|
|
9086
9034
|
content: applyMetaInfo(result),
|
|
9087
9035
|
filePath: configFilePath
|
|
9088
9036
|
};
|
|
9089
9037
|
}
|
|
9090
|
-
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)}`);
|
|
9091
9039
|
return src_logger.debug('configuration loaded from:', configFilePath), {
|
|
9092
9040
|
content: applyMetaInfo(configExport),
|
|
9093
9041
|
filePath: configFilePath
|
|
@@ -9100,7 +9048,7 @@ let commonOpts = {}, init_loadConfig = async (root)=>{
|
|
|
9100
9048
|
envMode: commonOpts.envMode,
|
|
9101
9049
|
loader: commonOpts.configLoader
|
|
9102
9050
|
});
|
|
9103
|
-
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 = [
|
|
9104
9052
|
...config.dev.watchFiles ? helpers_castArray(config.dev.watchFiles) : [],
|
|
9105
9053
|
{
|
|
9106
9054
|
paths: filePath,
|
|
@@ -9150,7 +9098,7 @@ let cleaners = [], onBeforeRestartServer = (cleaner)=>{
|
|
|
9150
9098
|
}, beforeRestart = async ({ filePath, clear = !0, id })=>{
|
|
9151
9099
|
if (clear && isTTY() && !process.env.DEBUG && process.stdout.write('\x1B[H\x1B[2J'), filePath) {
|
|
9152
9100
|
let filename = external_node_path_.default.basename(filePath);
|
|
9153
|
-
src_logger.info(`restarting ${id} as ${
|
|
9101
|
+
src_logger.info(`restarting ${id} as ${picocolors_default().yellow(filename)} changed\n`);
|
|
9154
9102
|
} else src_logger.info(`restarting ${id}...\n`);
|
|
9155
9103
|
for (let cleaner of cleaners)await cleaner();
|
|
9156
9104
|
cleaners = [];
|
|
@@ -9194,11 +9142,11 @@ async function watchFilesForRestart({ files, rsbuild, isBuildWatch, watchOptions
|
|
|
9194
9142
|
watcher.on('add', onChange), watcher.on('change', onChange), watcher.on('unlink', onChange);
|
|
9195
9143
|
}
|
|
9196
9144
|
let applyServerOptions = (command)=>{
|
|
9197
|
-
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');
|
|
9198
9146
|
};
|
|
9199
9147
|
function setupCommands() {
|
|
9200
9148
|
let cli = ((name = "")=>new CAC(name))('rsbuild');
|
|
9201
|
-
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)', {
|
|
9202
9150
|
default: 'auto'
|
|
9203
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', {
|
|
9204
9152
|
type: [
|
|
@@ -9206,7 +9154,7 @@ function setupCommands() {
|
|
|
9206
9154
|
],
|
|
9207
9155
|
default: []
|
|
9208
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');
|
|
9209
|
-
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');
|
|
9210
9158
|
applyServerOptions(devCommand), applyServerOptions(previewCommand), devCommand.action(async (options)=>{
|
|
9211
9159
|
try {
|
|
9212
9160
|
let rsbuild = await init_init({
|
|
@@ -9252,7 +9200,7 @@ function setupCommands() {
|
|
|
9252
9200
|
src_logger.error('Failed to inspect config.'), src_logger.error(err), process.exit(1);
|
|
9253
9201
|
}
|
|
9254
9202
|
}), cli.help((sections)=>{
|
|
9255
|
-
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);
|
|
9256
9204
|
}), cli.parse();
|
|
9257
9205
|
}
|
|
9258
9206
|
let { argv: cli_argv } = process;
|
|
@@ -9267,7 +9215,7 @@ function initNodeEnv() {
|
|
|
9267
9215
|
}
|
|
9268
9216
|
function showGreeting() {
|
|
9269
9217
|
let { npm_execpath, npm_lifecycle_event, NODE_RUN_SCRIPT_NAME } = process.env, isBun = npm_execpath?.includes('.bun');
|
|
9270
|
-
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`);
|
|
9271
9219
|
}
|
|
9272
9220
|
function setupLogLevel() {
|
|
9273
9221
|
let logLevelIndex = process.argv.findIndex((item)=>'--log-level' === item || '--logLevel' === item);
|
|
@@ -9288,5 +9236,5 @@ function runCLI() {
|
|
|
9288
9236
|
src_logger.error('Failed to start Rsbuild CLI.'), src_logger.error(err);
|
|
9289
9237
|
}
|
|
9290
9238
|
}
|
|
9291
|
-
let src_version = "
|
|
9292
|
-
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 };
|