@rsbuild/core 0.4.3 → 0.4.4

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.
@@ -112,7 +112,7 @@ const applyServerOptions = (command) => {
112
112
  command.option("-o --open [url]", "open the page in browser on startup").option("--port <port>", "specify a port number for server to listen").option("--host <host>", "specify the host that the server listens to");
113
113
  };
114
114
  function runCli() {
115
- import_commander.program.name("rsbuild").usage("<command> [options]").version("0.4.3");
115
+ import_commander.program.name("rsbuild").usage("<command> [options]").version("0.4.4");
116
116
  const devCommand = import_commander.program.command("dev");
117
117
  const buildCommand = import_commander.program.command("build");
118
118
  const previewCommand = import_commander.program.command("preview");
@@ -34,7 +34,7 @@ function prepareCli() {
34
34
  if (!npm_execpath || npm_execpath.includes("npx-cli.js")) {
35
35
  console.log();
36
36
  }
37
- import_rslog.logger.greet(` ${`Rsbuild v${"0.4.3"}`}
37
+ import_rslog.logger.greet(` ${`Rsbuild v${"0.4.4"}`}
38
38
  `);
39
39
  }
40
40
  // Annotate the CommonJS export names for ESM import in node:
@@ -0,0 +1,286 @@
1
+ // src/client/formatStats.ts
2
+ var friendlySyntaxErrorLabel = "SyntaxError:";
3
+ function isLikelyASyntaxError(message) {
4
+ return message.includes(friendlySyntaxErrorLabel);
5
+ }
6
+ function formatMessage(stats) {
7
+ let lines = [];
8
+ let message;
9
+ if (typeof stats === "object") {
10
+ const fileName = stats.moduleName ? `File: ${stats.moduleName}
11
+ ` : "";
12
+ const mainMessage = typeof stats.formatted === "string" ? stats.formatted : stats.message;
13
+ const details = stats.details ? `
14
+ Details: ${stats.details}
15
+ ` : "";
16
+ const stack = stats.stack ? `
17
+ ${stats.stack}` : "";
18
+ message = `${fileName}${mainMessage}${details}${stack}`;
19
+ } else {
20
+ message = stats;
21
+ }
22
+ lines = message.split("\n");
23
+ lines = lines.map((line) => {
24
+ const parsingError = /Line (\d+):(?:(\d+):)?\s*Parsing error: (.+)$/.exec(
25
+ line
26
+ );
27
+ if (!parsingError) {
28
+ return line;
29
+ }
30
+ const [, errorLine, errorColumn, errorMessage] = parsingError;
31
+ return `${friendlySyntaxErrorLabel} ${errorMessage} (${errorLine}:${errorColumn})`;
32
+ });
33
+ message = lines.join("\n");
34
+ message = message.replace(
35
+ /SyntaxError\s+\((\d+):(\d+)\)\s*(.+?)\n/g,
36
+ `${friendlySyntaxErrorLabel} $3 ($1:$2)
37
+ `
38
+ );
39
+ lines = message.split("\n");
40
+ if (lines.length > 2 && lines[1].trim() === "") {
41
+ lines.splice(1, 1);
42
+ }
43
+ lines[0] = lines[0].replace(/^(.*) \d+:\d+-\d+$/, "$1");
44
+ if (lines[1] && lines[1].indexOf("Module not found:") !== -1) {
45
+ lines[1] = lines[1].replace("Error: ", "");
46
+ }
47
+ lines = lines.filter(
48
+ (line, index, arr) => index === 0 || line.trim() !== "" || line.trim() !== arr[index - 1].trim()
49
+ );
50
+ message = lines.join("\n");
51
+ return message.trim();
52
+ }
53
+ function formatStatsMessages(json) {
54
+ const formattedErrors = json?.errors?.map(formatMessage);
55
+ const formattedWarnings = json?.warnings?.map(formatMessage);
56
+ const result = {
57
+ errors: formattedErrors || [],
58
+ warnings: formattedWarnings || [],
59
+ errorTips: []
60
+ };
61
+ if (result.errors?.some(isLikelyASyntaxError)) {
62
+ result.errors = result.errors.filter(isLikelyASyntaxError);
63
+ }
64
+ if (result.errors.length > 1) {
65
+ result.errors.length = 1;
66
+ }
67
+ return result;
68
+ }
69
+
70
+ // src/client/hmr/createSocketUrl.ts
71
+ var HMR_SOCK_PATH = "/rsbuild-hmr";
72
+ function createSocketUrl(resourceQuery) {
73
+ const searchParams = resourceQuery.substr(1).split("&");
74
+ const options = {};
75
+ for (const pair of searchParams) {
76
+ const ary = pair.split("=");
77
+ options[ary[0]] = decodeURIComponent(ary[1]);
78
+ }
79
+ const currentLocation = self.location;
80
+ return getSocketUrl(options, currentLocation);
81
+ }
82
+ function formatURL({
83
+ port,
84
+ protocol,
85
+ hostname,
86
+ pathname
87
+ }) {
88
+ if (typeof URL !== "undefined") {
89
+ const url = new URL("http://localhost");
90
+ url.port = port;
91
+ url.hostname = hostname;
92
+ url.protocol = protocol;
93
+ url.pathname = pathname;
94
+ return url.toString();
95
+ }
96
+ const colon = protocol.indexOf(":") === -1 ? ":" : "";
97
+ return `${protocol}${colon}//${hostname}:${port}${pathname}`;
98
+ }
99
+ function getSocketUrl(urlParts, location) {
100
+ const { host, port, path, protocol } = urlParts;
101
+ return formatURL({
102
+ protocol: protocol || (location.protocol === "https:" ? "wss" : "ws"),
103
+ hostname: host || location.hostname,
104
+ port: port || location.port,
105
+ pathname: path || HMR_SOCK_PATH
106
+ });
107
+ }
108
+
109
+ // src/client/hmr/index.ts
110
+ var socketUrl = createSocketUrl(__resourceQuery);
111
+ var isFirstCompilation = true;
112
+ var mostRecentCompilationHash = null;
113
+ var hasCompileErrors = false;
114
+ function clearOutdatedErrors() {
115
+ if (typeof console !== "undefined" && typeof console.clear === "function") {
116
+ if (hasCompileErrors) {
117
+ console.clear();
118
+ }
119
+ }
120
+ }
121
+ function handleSuccess() {
122
+ clearOutdatedErrors();
123
+ const isHotUpdate = !isFirstCompilation;
124
+ isFirstCompilation = false;
125
+ hasCompileErrors = false;
126
+ if (isHotUpdate) {
127
+ tryApplyUpdates();
128
+ }
129
+ }
130
+ function handleWarnings(warnings) {
131
+ clearOutdatedErrors();
132
+ const isHotUpdate = !isFirstCompilation;
133
+ isFirstCompilation = false;
134
+ hasCompileErrors = false;
135
+ function printWarnings() {
136
+ const formatted = formatStatsMessages({
137
+ warnings,
138
+ errors: []
139
+ });
140
+ if (typeof console !== "undefined" && typeof console.warn === "function") {
141
+ for (let i = 0; i < formatted.warnings.length; i++) {
142
+ if (i === 5) {
143
+ console.warn(
144
+ "There were more warnings in other files.\nYou can find a complete log in the terminal."
145
+ );
146
+ break;
147
+ }
148
+ console.warn(formatted.warnings[i]);
149
+ }
150
+ }
151
+ }
152
+ printWarnings();
153
+ if (isHotUpdate) {
154
+ tryApplyUpdates();
155
+ }
156
+ }
157
+ function handleErrors(errors) {
158
+ clearOutdatedErrors();
159
+ isFirstCompilation = false;
160
+ hasCompileErrors = true;
161
+ const formatted = formatStatsMessages({
162
+ errors,
163
+ warnings: []
164
+ });
165
+ if (typeof console !== "undefined" && typeof console.error === "function") {
166
+ for (const error of formatted.errors) {
167
+ console.error(error);
168
+ }
169
+ }
170
+ }
171
+ function handleAvailableHash(hash) {
172
+ mostRecentCompilationHash = hash;
173
+ }
174
+ function isUpdateAvailable() {
175
+ return mostRecentCompilationHash !== __webpack_hash__;
176
+ }
177
+ function canApplyUpdates() {
178
+ return import.meta.webpackHot.status() === "idle";
179
+ }
180
+ function tryApplyUpdates() {
181
+ if (!isUpdateAvailable()) {
182
+ return;
183
+ }
184
+ if (!import.meta.webpackHot) {
185
+ window.location.reload();
186
+ return;
187
+ }
188
+ if (!canApplyUpdates()) {
189
+ return;
190
+ }
191
+ function handleApplyUpdates(err, updatedModules) {
192
+ const wantsForcedReload = err || !updatedModules;
193
+ if (wantsForcedReload) {
194
+ window.location.reload();
195
+ return;
196
+ }
197
+ if (isUpdateAvailable()) {
198
+ tryApplyUpdates();
199
+ }
200
+ }
201
+ import.meta.webpackHot.check(true).then(
202
+ (updatedModules) => {
203
+ handleApplyUpdates(null, updatedModules);
204
+ },
205
+ (err) => {
206
+ handleApplyUpdates(err, null);
207
+ }
208
+ );
209
+ }
210
+ var MAX_RETRIES = 100;
211
+ var connection = null;
212
+ var retry_counter = 0;
213
+ function onOpen() {
214
+ if (typeof console !== "undefined" && typeof console.info === "function") {
215
+ console.info("[HMR] connected.");
216
+ }
217
+ }
218
+ function onMessage(e) {
219
+ const message = JSON.parse(e.data);
220
+ switch (message.type) {
221
+ case "hash":
222
+ handleAvailableHash(message.data);
223
+ break;
224
+ case "still-ok":
225
+ case "ok":
226
+ handleSuccess();
227
+ break;
228
+ case "content-changed":
229
+ window.location.reload();
230
+ break;
231
+ case "warnings":
232
+ handleWarnings(message.data);
233
+ break;
234
+ case "errors":
235
+ handleErrors(message.data);
236
+ break;
237
+ default:
238
+ }
239
+ }
240
+ async function sleep(msec = 1e3) {
241
+ return new Promise((resolve) => {
242
+ setTimeout(resolve, msec);
243
+ });
244
+ }
245
+ async function onClose() {
246
+ if (typeof console !== "undefined" && typeof console.info === "function") {
247
+ console.info("[HMR] disconnected. Attempting to reconnect.");
248
+ }
249
+ removeListeners();
250
+ await sleep(1e3);
251
+ retry_counter++;
252
+ if (connection && (connection.readyState === connection.CONNECTING || connection.readyState === connection.OPEN)) {
253
+ retry_counter = 0;
254
+ return;
255
+ }
256
+ if (retry_counter > MAX_RETRIES) {
257
+ if (typeof console !== "undefined" && typeof console.info === "function") {
258
+ console.info(
259
+ "[HMR] Unable to establish a connection after exceeding the maximum retry attempts."
260
+ );
261
+ }
262
+ retry_counter = 0;
263
+ return;
264
+ }
265
+ reconnect();
266
+ }
267
+ function connect() {
268
+ connection = new WebSocket(socketUrl);
269
+ connection.addEventListener("open", onOpen);
270
+ connection.addEventListener("close", onClose);
271
+ connection.addEventListener("message", onMessage);
272
+ }
273
+ function removeListeners() {
274
+ if (connection) {
275
+ connection.removeEventListener("open", onOpen);
276
+ connection.removeEventListener("close", onClose);
277
+ connection.removeEventListener("message", onMessage);
278
+ }
279
+ }
280
+ function reconnect() {
281
+ if (connection) {
282
+ connection = null;
283
+ }
284
+ connect();
285
+ }
286
+ connect();
package/dist/index.d.ts CHANGED
@@ -9,5 +9,5 @@ export declare const version: any;
9
9
  export { logger, mergeRsbuildConfig } from '@rsbuild/shared';
10
10
  export { PLUGIN_SWC_NAME, PLUGIN_CSS_NAME, PLUGIN_SASS_NAME, PLUGIN_LESS_NAME, PLUGIN_STYLUS_NAME, } from './constants';
11
11
  export type { Rspack } from './provider';
12
- export type { RsbuildConfig, DevConfig, HtmlConfig, ToolsConfig, SourceConfig, OutputConfig, SecurityConfig, PerformanceConfig, NormalizedConfig, NormalizedDevConfig, NormalizedHtmlConfig, NormalizedToolsConfig, NormalizedSourceConfig, NormalizedOutputConfig, NormalizedSecurityConfig, NormalizedPerformanceConfig, RsbuildPlugin, RsbuildPlugins, RsbuildPluginAPI, } from './types';
12
+ export type { RsbuildConfig, DevConfig, HtmlConfig, ToolsConfig, SourceConfig, ServerConfig, OutputConfig, SecurityConfig, PerformanceConfig, ModuleFederationConfig, NormalizedConfig, NormalizedDevConfig, NormalizedHtmlConfig, NormalizedToolsConfig, NormalizedSourceConfig, NormalizedServerConfig, NormalizedOutputConfig, NormalizedSecurityConfig, NormalizedPerformanceConfig, NormalizedModuleFederationConfig, RsbuildPlugin, RsbuildPlugins, RsbuildPluginAPI, } from './types';
13
13
  export type { RsbuildMode, RsbuildEntry, RsbuildTarget, RsbuildContext, RsbuildInstance, CreateRsbuildOptions, InspectConfigOptions, OnExitFn, OnAfterBuildFn, OnAfterCreateCompilerFn, OnAfterStartDevServerFn, OnAfterStartProdServerFn, OnBeforeBuildFn, OnBeforeStartDevServerFn, OnBeforeStartProdServerFn, OnBeforeCreateCompilerFn, OnCloseDevServerFn, OnDevCompileDoneFn, ModifyRsbuildConfigFn, } from '@rsbuild/shared';
package/dist/index.js CHANGED
@@ -37,7 +37,7 @@ var import_createRsbuild = require("./createRsbuild");
37
37
  var import_config = require("./cli/config");
38
38
  var import_shared = require("@rsbuild/shared");
39
39
  var import_constants = require("./constants");
40
- const version = "0.4.3";
40
+ const version = "0.4.4";
41
41
  // Annotate the CommonJS export names for ESM import in node:
42
42
  0 && (module.exports = {
43
43
  PLUGIN_CSS_NAME,
@@ -43,7 +43,7 @@ async function createContextByConfig(options, bundlerType, config = {}) {
43
43
  const context = {
44
44
  entry: config.source?.entry || {},
45
45
  targets: config.output?.targets || [],
46
- version: "0.4.3",
46
+ version: "0.4.4",
47
47
  rootPath,
48
48
  distPath,
49
49
  cachePath,
@@ -61,10 +61,7 @@ async function applyBaseCSSRule({
61
61
  });
62
62
  if (!isServer && !isWebWorker) {
63
63
  const styleLoaderOptions = (0, import_shared.mergeChainedOptions)({
64
- defaults: {
65
- // todo: hmr does not work while esModule is true
66
- esModule: false
67
- },
64
+ defaults: {},
68
65
  options: config.tools.styleLoader
69
66
  });
70
67
  rule.use(CHAIN_ID.USE.STYLE).loader((0, import_shared.getSharedPkgCompiledPath)("style-loader")).options(styleLoaderOptions).end();
package/dist/types.d.ts CHANGED
@@ -14,4 +14,4 @@ export type InternalContext = RsbuildContext & {
14
14
  /** The plugin API. */
15
15
  pluginAPI?: RsbuildPluginAPI;
16
16
  };
17
- export type { RsbuildConfig, NormalizedConfig, DevConfig, HtmlConfig, ToolsConfig, SourceConfig, OutputConfig, SecurityConfig, PerformanceConfig, NormalizedDevConfig, NormalizedHtmlConfig, NormalizedToolsConfig, NormalizedSourceConfig, NormalizedOutputConfig, NormalizedSecurityConfig, NormalizedPerformanceConfig, } from '@rsbuild/shared';
17
+ export type { RsbuildConfig, NormalizedConfig, DevConfig, HtmlConfig, ToolsConfig, SourceConfig, ServerConfig, OutputConfig, SecurityConfig, PerformanceConfig, ModuleFederationConfig, NormalizedDevConfig, NormalizedHtmlConfig, NormalizedToolsConfig, NormalizedSourceConfig, NormalizedServerConfig, NormalizedOutputConfig, NormalizedSecurityConfig, NormalizedPerformanceConfig, NormalizedModuleFederationConfig, } from '@rsbuild/shared';
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsbuild/core",
3
- "version": "0.4.3",
3
+ "version": "0.4.4",
4
4
  "description": "The Rspack-based build tool.",
5
5
  "homepage": "https://rsbuild.dev",
6
6
  "bugs": {
@@ -22,9 +22,9 @@
22
22
  "types": "./dist/server/index.d.ts",
23
23
  "default": "./dist/server/index.js"
24
24
  },
25
- "./client/*": {
26
- "types": "./dist/client/*.d.ts",
27
- "default": "./dist/client/*.js"
25
+ "./client/hmr": {
26
+ "types": "./dist/client/hmr/index.d.ts",
27
+ "default": "./dist/client/hmr.mjs"
28
28
  },
29
29
  "./plugins/*": {
30
30
  "types": "./dist/plugins/*.d.ts",
@@ -57,7 +57,7 @@
57
57
  "core-js": "~3.32.2",
58
58
  "html-webpack-plugin": "npm:html-rspack-plugin@5.6.0",
59
59
  "postcss": "^8.4.33",
60
- "@rsbuild/shared": "0.4.3"
60
+ "@rsbuild/shared": "0.4.4"
61
61
  },
62
62
  "devDependencies": {
63
63
  "@types/node": "16.x",
@@ -1,509 +0,0 @@
1
- "use strict";
2
- function _array_like_to_array(arr, len) {
3
- if (len == null || len > arr.length) len = arr.length;
4
- for(var i = 0, arr2 = new Array(len); i < len; i++)arr2[i] = arr[i];
5
- return arr2;
6
- }
7
- function _array_with_holes(arr) {
8
- if (Array.isArray(arr)) return arr;
9
- }
10
- function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
11
- try {
12
- var info = gen[key](arg);
13
- var value = info.value;
14
- } catch (error) {
15
- reject(error);
16
- return;
17
- }
18
- if (info.done) {
19
- resolve(value);
20
- } else {
21
- Promise.resolve(value).then(_next, _throw);
22
- }
23
- }
24
- function _async_to_generator(fn) {
25
- return function() {
26
- var self1 = this, args = arguments;
27
- return new Promise(function(resolve, reject) {
28
- var gen = fn.apply(self1, args);
29
- function _next(value) {
30
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
31
- }
32
- function _throw(err) {
33
- asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
34
- }
35
- _next(undefined);
36
- });
37
- };
38
- }
39
- function _iterable_to_array_limit(arr, i) {
40
- var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"];
41
- if (_i == null) return;
42
- var _arr = [];
43
- var _n = true;
44
- var _d = false;
45
- var _s, _e;
46
- try {
47
- for(_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true){
48
- _arr.push(_s.value);
49
- if (i && _arr.length === i) break;
50
- }
51
- } catch (err) {
52
- _d = true;
53
- _e = err;
54
- } finally{
55
- try {
56
- if (!_n && _i["return"] != null) _i["return"]();
57
- } finally{
58
- if (_d) throw _e;
59
- }
60
- }
61
- return _arr;
62
- }
63
- function _non_iterable_rest() {
64
- throw new TypeError("Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
65
- }
66
- function _sliced_to_array(arr, i) {
67
- return _array_with_holes(arr) || _iterable_to_array_limit(arr, i) || _unsupported_iterable_to_array(arr, i) || _non_iterable_rest();
68
- }
69
- function _unsupported_iterable_to_array(o, minLen) {
70
- if (!o) return;
71
- if (typeof o === "string") return _array_like_to_array(o, minLen);
72
- var n = Object.prototype.toString.call(o).slice(8, -1);
73
- if (n === "Object" && o.constructor) n = o.constructor.name;
74
- if (n === "Map" || n === "Set") return Array.from(n);
75
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
76
- }
77
- function _ts_generator(thisArg, body) {
78
- var f, y, t, g, _ = {
79
- label: 0,
80
- sent: function() {
81
- if (t[0] & 1) throw t[1];
82
- return t[1];
83
- },
84
- trys: [],
85
- ops: []
86
- };
87
- return g = {
88
- next: verb(0),
89
- "throw": verb(1),
90
- "return": verb(2)
91
- }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
92
- return this;
93
- }), g;
94
- function verb(n) {
95
- return function(v) {
96
- return step([
97
- n,
98
- v
99
- ]);
100
- };
101
- }
102
- function step(op) {
103
- if (f) throw new TypeError("Generator is already executing.");
104
- while(_)try {
105
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
106
- if (y = 0, t) op = [
107
- op[0] & 2,
108
- t.value
109
- ];
110
- switch(op[0]){
111
- case 0:
112
- case 1:
113
- t = op;
114
- break;
115
- case 4:
116
- _.label++;
117
- return {
118
- value: op[1],
119
- done: false
120
- };
121
- case 5:
122
- _.label++;
123
- y = op[1];
124
- op = [
125
- 0
126
- ];
127
- continue;
128
- case 7:
129
- op = _.ops.pop();
130
- _.trys.pop();
131
- continue;
132
- default:
133
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
134
- _ = 0;
135
- continue;
136
- }
137
- if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
138
- _.label = op[1];
139
- break;
140
- }
141
- if (op[0] === 6 && _.label < t[1]) {
142
- _.label = t[1];
143
- t = op;
144
- break;
145
- }
146
- if (t && _.label < t[2]) {
147
- _.label = t[2];
148
- _.ops.push(op);
149
- break;
150
- }
151
- if (t[2]) _.ops.pop();
152
- _.trys.pop();
153
- continue;
154
- }
155
- op = body.call(thisArg, _);
156
- } catch (e) {
157
- op = [
158
- 6,
159
- e
160
- ];
161
- y = 0;
162
- } finally{
163
- f = t = 0;
164
- }
165
- if (op[0] & 5) throw op[1];
166
- return {
167
- value: op[0] ? op[1] : void 0,
168
- done: true
169
- };
170
- }
171
- }
172
- // src/client/formatStats.ts
173
- var friendlySyntaxErrorLabel = "SyntaxError:";
174
- function isLikelyASyntaxError(message) {
175
- return message.includes(friendlySyntaxErrorLabel);
176
- }
177
- function formatMessage(stats) {
178
- var lines = [];
179
- var message;
180
- if (typeof stats === "object") {
181
- var fileName = stats.moduleName ? "File: ".concat(stats.moduleName, "\n") : "";
182
- var mainMessage = typeof stats.formatted === "string" ? stats.formatted : stats.message;
183
- var details = stats.details ? "\nDetails: ".concat(stats.details, "\n") : "";
184
- var stack = stats.stack ? "\n".concat(stats.stack) : "";
185
- message = "".concat(fileName).concat(mainMessage).concat(details).concat(stack);
186
- } else {
187
- message = stats;
188
- }
189
- lines = message.split("\n");
190
- lines = lines.map(function(line) {
191
- var parsingError = /Line (\d+):(?:(\d+):)?\s*Parsing error: (.+)$/.exec(line);
192
- if (!parsingError) {
193
- return line;
194
- }
195
- var _parsingError = _sliced_to_array(parsingError, 4), errorLine = _parsingError[1], errorColumn = _parsingError[2], errorMessage = _parsingError[3];
196
- return "".concat(friendlySyntaxErrorLabel, " ").concat(errorMessage, " (").concat(errorLine, ":").concat(errorColumn, ")");
197
- });
198
- message = lines.join("\n");
199
- message = message.replace(/SyntaxError\s+\((\d+):(\d+)\)\s*(.+?)\n/g, "".concat(friendlySyntaxErrorLabel, " $3 ($1:$2)\n"));
200
- lines = message.split("\n");
201
- if (lines.length > 2 && lines[1].trim() === "") {
202
- lines.splice(1, 1);
203
- }
204
- lines[0] = lines[0].replace(/^(.*) \d+:\d+-\d+$/, "$1");
205
- if (lines[1] && lines[1].indexOf("Module not found:") !== -1) {
206
- lines[1] = lines[1].replace("Error: ", "");
207
- }
208
- lines = lines.filter(function(line, index, arr) {
209
- return index === 0 || line.trim() !== "" || line.trim() !== arr[index - 1].trim();
210
- });
211
- message = lines.join("\n");
212
- return message.trim();
213
- }
214
- function formatStatsMessages(json) {
215
- var _json_errors, _json_warnings, _result_errors;
216
- var formattedErrors = json === null || json === void 0 ? void 0 : (_json_errors = json.errors) === null || _json_errors === void 0 ? void 0 : _json_errors.map(formatMessage);
217
- var formattedWarnings = json === null || json === void 0 ? void 0 : (_json_warnings = json.warnings) === null || _json_warnings === void 0 ? void 0 : _json_warnings.map(formatMessage);
218
- var result = {
219
- errors: formattedErrors || [],
220
- warnings: formattedWarnings || [],
221
- errorTips: []
222
- };
223
- if ((_result_errors = result.errors) === null || _result_errors === void 0 ? void 0 : _result_errors.some(isLikelyASyntaxError)) {
224
- result.errors = result.errors.filter(isLikelyASyntaxError);
225
- }
226
- if (result.errors.length > 1) {
227
- result.errors.length = 1;
228
- }
229
- return result;
230
- }
231
- // src/client/hmr/createSocketUrl.ts
232
- var HMR_SOCK_PATH = "/rsbuild-hmr";
233
- function createSocketUrl(resourceQuery) {
234
- var searchParams = resourceQuery.substr(1).split("&");
235
- var options = {};
236
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
237
- try {
238
- for(var _iterator = searchParams[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
239
- var pair = _step.value;
240
- var ary = pair.split("=");
241
- options[ary[0]] = decodeURIComponent(ary[1]);
242
- }
243
- } catch (err) {
244
- _didIteratorError = true;
245
- _iteratorError = err;
246
- } finally{
247
- try {
248
- if (!_iteratorNormalCompletion && _iterator.return != null) {
249
- _iterator.return();
250
- }
251
- } finally{
252
- if (_didIteratorError) {
253
- throw _iteratorError;
254
- }
255
- }
256
- }
257
- var currentLocation = self.location;
258
- return getSocketUrl(options, currentLocation);
259
- }
260
- function formatURL(param) {
261
- var port = param.port, protocol = param.protocol, hostname = param.hostname, pathname = param.pathname;
262
- if (typeof URL !== "undefined") {
263
- var url = new URL("http://localhost");
264
- url.port = port;
265
- url.hostname = hostname;
266
- url.protocol = protocol;
267
- url.pathname = pathname;
268
- return url.toString();
269
- }
270
- var colon = protocol.indexOf(":") === -1 ? ":" : "";
271
- return "".concat(protocol).concat(colon, "//").concat(hostname, ":").concat(port).concat(pathname);
272
- }
273
- function getSocketUrl(urlParts, location) {
274
- var host = urlParts.host, port = urlParts.port, path = urlParts.path, protocol = urlParts.protocol;
275
- return formatURL({
276
- protocol: protocol || (location.protocol === "https:" ? "wss" : "ws"),
277
- hostname: host || location.hostname,
278
- port: port || location.port,
279
- pathname: path || HMR_SOCK_PATH
280
- });
281
- }
282
- // src/client/hmr/index.ts
283
- var socketUrl = createSocketUrl(__resourceQuery);
284
- var isFirstCompilation = true;
285
- var mostRecentCompilationHash = null;
286
- var hasCompileErrors = false;
287
- function clearOutdatedErrors() {
288
- if (typeof console !== "undefined" && typeof console.clear === "function") {
289
- if (hasCompileErrors) {
290
- console.clear();
291
- }
292
- }
293
- }
294
- function handleSuccess() {
295
- clearOutdatedErrors();
296
- var isHotUpdate = !isFirstCompilation;
297
- isFirstCompilation = false;
298
- hasCompileErrors = false;
299
- if (isHotUpdate) {
300
- tryApplyUpdates();
301
- }
302
- }
303
- function handleWarnings(warnings) {
304
- clearOutdatedErrors();
305
- var isHotUpdate = !isFirstCompilation;
306
- isFirstCompilation = false;
307
- hasCompileErrors = false;
308
- function printWarnings() {
309
- var formatted = formatStatsMessages({
310
- warnings: warnings,
311
- errors: []
312
- });
313
- if (typeof console !== "undefined" && typeof console.warn === "function") {
314
- for(var i = 0; i < formatted.warnings.length; i++){
315
- if (i === 5) {
316
- console.warn("There were more warnings in other files.\nYou can find a complete log in the terminal.");
317
- break;
318
- }
319
- console.warn(formatted.warnings[i]);
320
- }
321
- }
322
- }
323
- printWarnings();
324
- if (isHotUpdate) {
325
- tryApplyUpdates();
326
- }
327
- }
328
- function handleErrors(errors) {
329
- clearOutdatedErrors();
330
- isFirstCompilation = false;
331
- hasCompileErrors = true;
332
- var formatted = formatStatsMessages({
333
- errors: errors,
334
- warnings: []
335
- });
336
- if (typeof console !== "undefined" && typeof console.error === "function") {
337
- var _iteratorNormalCompletion = true, _didIteratorError = false, _iteratorError = undefined;
338
- try {
339
- for(var _iterator = formatted.errors[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true){
340
- var error = _step.value;
341
- console.error(error);
342
- }
343
- } catch (err) {
344
- _didIteratorError = true;
345
- _iteratorError = err;
346
- } finally{
347
- try {
348
- if (!_iteratorNormalCompletion && _iterator.return != null) {
349
- _iterator.return();
350
- }
351
- } finally{
352
- if (_didIteratorError) {
353
- throw _iteratorError;
354
- }
355
- }
356
- }
357
- }
358
- }
359
- function handleAvailableHash(hash) {
360
- mostRecentCompilationHash = hash;
361
- }
362
- function isUpdateAvailable() {
363
- return mostRecentCompilationHash !== __webpack_hash__;
364
- }
365
- function canApplyUpdates() {
366
- return module.hot.status() === "idle";
367
- }
368
- function tryApplyUpdates() {
369
- if (!isUpdateAvailable()) {
370
- return;
371
- }
372
- if (!module.hot) {
373
- window.location.reload();
374
- return;
375
- }
376
- if (!canApplyUpdates()) {
377
- return;
378
- }
379
- function handleApplyUpdates(err, updatedModules) {
380
- var wantsForcedReload = err || !updatedModules;
381
- if (wantsForcedReload) {
382
- window.location.reload();
383
- return;
384
- }
385
- if (isUpdateAvailable()) {
386
- tryApplyUpdates();
387
- }
388
- }
389
- var result = module.hot.check(/* autoApply */ true, handleApplyUpdates);
390
- if (result === null || result === void 0 ? void 0 : result.then) {
391
- result.then(function(updatedModules) {
392
- handleApplyUpdates(null, updatedModules);
393
- }, function(err) {
394
- handleApplyUpdates(err, null);
395
- });
396
- }
397
- }
398
- var MAX_RETRIES = 100;
399
- var connection = null;
400
- var retry_counter = 0;
401
- function onOpen() {
402
- if (typeof console !== "undefined" && typeof console.info === "function") {
403
- console.info("[HMR] connected.");
404
- }
405
- }
406
- function onMessage(e) {
407
- var message = JSON.parse(e.data);
408
- switch(message.type){
409
- case "hash":
410
- handleAvailableHash(message.data);
411
- break;
412
- case "still-ok":
413
- case "ok":
414
- handleSuccess();
415
- break;
416
- case "content-changed":
417
- window.location.reload();
418
- break;
419
- case "warnings":
420
- handleWarnings(message.data);
421
- break;
422
- case "errors":
423
- handleErrors(message.data);
424
- break;
425
- default:
426
- }
427
- }
428
- function sleep() {
429
- return _sleep.apply(this, arguments);
430
- }
431
- function _sleep() {
432
- _sleep = _async_to_generator(function() {
433
- var msec;
434
- var _arguments = arguments;
435
- return _ts_generator(this, function(_state) {
436
- msec = _arguments.length > 0 && _arguments[0] !== void 0 ? _arguments[0] : 1e3;
437
- return [
438
- 2,
439
- new Promise(function(resolve) {
440
- setTimeout(resolve, msec);
441
- })
442
- ];
443
- });
444
- });
445
- return _sleep.apply(this, arguments);
446
- }
447
- function onClose() {
448
- return _onClose.apply(this, arguments);
449
- }
450
- function _onClose() {
451
- _onClose = _async_to_generator(function() {
452
- return _ts_generator(this, function(_state) {
453
- switch(_state.label){
454
- case 0:
455
- if (typeof console !== "undefined" && typeof console.info === "function") {
456
- console.info("[HMR] disconnected. Attempting to reconnect.");
457
- }
458
- removeListeners();
459
- return [
460
- 4,
461
- sleep(1e3)
462
- ];
463
- case 1:
464
- _state.sent();
465
- retry_counter++;
466
- if (connection && (connection.readyState === connection.CONNECTING || connection.readyState === connection.OPEN)) {
467
- retry_counter = 0;
468
- return [
469
- 2
470
- ];
471
- }
472
- if (retry_counter > MAX_RETRIES) {
473
- if (typeof console !== "undefined" && typeof console.info === "function") {
474
- console.info("[HMR] Unable to establish a connection after exceeding the maximum retry attempts.");
475
- }
476
- retry_counter = 0;
477
- return [
478
- 2
479
- ];
480
- }
481
- reconnect();
482
- return [
483
- 2
484
- ];
485
- }
486
- });
487
- });
488
- return _onClose.apply(this, arguments);
489
- }
490
- function connect() {
491
- connection = new WebSocket(socketUrl);
492
- connection.addEventListener("open", onOpen);
493
- connection.addEventListener("close", onClose);
494
- connection.addEventListener("message", onMessage);
495
- }
496
- function removeListeners() {
497
- if (connection) {
498
- connection.removeEventListener("open", onOpen);
499
- connection.removeEventListener("close", onClose);
500
- connection.removeEventListener("message", onMessage);
501
- }
502
- }
503
- function reconnect() {
504
- if (connection) {
505
- connection = null;
506
- }
507
- connect();
508
- }
509
- connect();