@rslib/core 0.0.3 → 0.0.5

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/dist/index.js CHANGED
@@ -8,195 +8,136 @@ import * as __WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js__ from "../c
8
8
  import * as __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__ from "../compiled/commander/index.js";
9
9
  import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core__ from "@rsbuild/core";
10
10
  import * as __WEBPACK_EXTERNAL_MODULE__compiled_fast_glob_index_js__ from "../compiled/fast-glob/index.js";
11
- var __webpack_modules__ = ({
12
- "rsbuild-plugin-dts": (function (module) {
13
- module.exports = import("rsbuild-plugin-dts");
14
-
15
- }),
16
-
17
- });
18
- /************************************************************************/
19
- // The module cache
11
+ var __webpack_modules__ = {
12
+ "rsbuild-plugin-dts": function(module) {
13
+ module.exports = import("rsbuild-plugin-dts");
14
+ }
15
+ };
16
+ /************************************************************************/ // The module cache
20
17
  var __webpack_module_cache__ = {};
21
-
22
18
  // The require function
23
19
  function __webpack_require__(moduleId) {
24
-
25
- // Check if module is in cache
26
- var cachedModule = __webpack_module_cache__[moduleId];
27
- if (cachedModule !== undefined) {
28
- return cachedModule.exports;
29
- }
30
- // Create a new module (and put it into the cache)
31
- var module = (__webpack_module_cache__[moduleId] = {
32
- exports: {}
33
- });
34
- // Execute the module function
35
- __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
36
-
37
- // Return the exports of the module
38
- return module.exports;
39
-
40
- }
41
-
42
- /************************************************************************/
43
-
44
- ;// CONCATENATED MODULE: external "process"
45
-
20
+ // Check if module is in cache
21
+ var cachedModule = __webpack_module_cache__[moduleId];
22
+ if (void 0 !== cachedModule) return cachedModule.exports;
23
+ // Create a new module (and put it into the cache)
24
+ var module = __webpack_module_cache__[moduleId] = {
25
+ exports: {}
26
+ };
27
+ // Execute the module function
28
+ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
29
+ // Return the exports of the module
30
+ return module.exports;
31
+ } /************************************************************************/
46
32
  var external_process_namespaceObject = __WEBPACK_EXTERNAL_MODULE_process__;
47
-
48
- ;// CONCATENATED MODULE: external "os"
49
-
50
33
  var external_os_namespaceObject = __WEBPACK_EXTERNAL_MODULE_os__;
51
-
52
- ;// CONCATENATED MODULE: external "tty"
53
-
54
34
  var external_tty_namespaceObject = __WEBPACK_EXTERNAL_MODULE_tty__;
55
-
56
- ;// CONCATENATED MODULE: ../../node_modules/.pnpm/rslog@1.2.2/node_modules/rslog/dist/index.mjs
57
35
  // node_modules/.pnpm/supports-color@9.4.0/node_modules/supports-color/index.js
58
-
59
-
60
-
61
36
  function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : external_process_namespaceObject["default"].argv) {
62
- const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
63
- const position = argv.indexOf(prefix + flag);
64
- const terminatorPosition = argv.indexOf("--");
65
- return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
37
+ const prefix = flag.startsWith("-") ? "" : 1 === flag.length ? "-" : "--";
38
+ const position = argv.indexOf(prefix + flag);
39
+ const terminatorPosition = argv.indexOf("--");
40
+ return -1 !== position && (-1 === terminatorPosition || position < terminatorPosition);
66
41
  }
67
42
  var { env } = external_process_namespaceObject["default"];
68
43
  var flagForceColor;
69
- if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
70
- flagForceColor = 0;
71
- } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
72
- flagForceColor = 1;
73
- }
44
+ if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) flagForceColor = 0;
45
+ else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) flagForceColor = 1;
74
46
  function envForceColor() {
75
- if ("FORCE_COLOR" in env) {
76
- if (env.FORCE_COLOR === "true") {
77
- return 1;
78
- }
79
- if (env.FORCE_COLOR === "false") {
80
- return 0;
47
+ if ("FORCE_COLOR" in env) {
48
+ if ("true" === env.FORCE_COLOR) return 1;
49
+ if ("false" === env.FORCE_COLOR) return 0;
50
+ return 0 === env.FORCE_COLOR.length ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
81
51
  }
82
- return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
83
- }
84
52
  }
85
53
  function translateLevel(level) {
86
- if (level === 0) {
87
- return false;
88
- }
89
- return {
90
- level,
91
- hasBasic: true,
92
- has256: level >= 2,
93
- has16m: level >= 3
94
- };
54
+ if (0 === level) return false;
55
+ return {
56
+ level,
57
+ hasBasic: true,
58
+ has256: level >= 2,
59
+ has16m: level >= 3
60
+ };
95
61
  }
96
62
  function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
97
- const noFlagForceColor = envForceColor();
98
- if (noFlagForceColor !== void 0) {
99
- flagForceColor = noFlagForceColor;
100
- }
101
- const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
102
- if (forceColor === 0) {
103
- return 0;
104
- }
105
- if (sniffFlags) {
106
- if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
107
- return 3;
108
- }
109
- if (hasFlag("color=256")) {
110
- return 2;
63
+ const noFlagForceColor = envForceColor();
64
+ if (void 0 !== noFlagForceColor) flagForceColor = noFlagForceColor;
65
+ const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
66
+ if (0 === forceColor) return 0;
67
+ if (sniffFlags) {
68
+ if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) return 3;
69
+ if (hasFlag("color=256")) return 2;
111
70
  }
112
- }
113
- if ("TF_BUILD" in env && "AGENT_NAME" in env) {
114
- return 1;
115
- }
116
- if (haveStream && !streamIsTTY && forceColor === void 0) {
117
- return 0;
118
- }
119
- const min = forceColor || 0;
120
- if (env.TERM === "dumb") {
121
- return min;
122
- }
123
- if (external_process_namespaceObject["default"].platform === "win32") {
124
- const osRelease = external_os_namespaceObject["default"].release().split(".");
125
- if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
126
- return Number(osRelease[2]) >= 14931 ? 3 : 2;
71
+ if ("TF_BUILD" in env && "AGENT_NAME" in env) return 1;
72
+ if (haveStream && !streamIsTTY && void 0 === forceColor) return 0;
73
+ const min = forceColor || 0;
74
+ if ("dumb" === env.TERM) return min;
75
+ if ("win32" === external_process_namespaceObject["default"].platform) {
76
+ const osRelease = external_os_namespaceObject["default"].release().split(".");
77
+ if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) return Number(osRelease[2]) >= 14931 ? 3 : 2;
78
+ return 1;
127
79
  }
128
- return 1;
129
- }
130
- if ("CI" in env) {
131
- if ("GITHUB_ACTIONS" in env || "GITEA_ACTIONS" in env) {
132
- return 3;
80
+ if ("CI" in env) {
81
+ if ("GITHUB_ACTIONS" in env || "GITEA_ACTIONS" in env) return 3;
82
+ if ([
83
+ "TRAVIS",
84
+ "CIRCLECI",
85
+ "APPVEYOR",
86
+ "GITLAB_CI",
87
+ "BUILDKITE",
88
+ "DRONE"
89
+ ].some((sign)=>sign in env) || "codeship" === env.CI_NAME) return 1;
90
+ return min;
133
91
  }
134
- if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
135
- return 1;
92
+ if ("TEAMCITY_VERSION" in env) return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
93
+ if ("truecolor" === env.COLORTERM) return 3;
94
+ if ("xterm-kitty" === env.TERM) return 3;
95
+ if ("TERM_PROGRAM" in env) {
96
+ const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
97
+ switch(env.TERM_PROGRAM){
98
+ case "iTerm.app":
99
+ return version >= 3 ? 3 : 2;
100
+ case "Apple_Terminal":
101
+ return 2;
102
+ }
136
103
  }
104
+ if (/-256(color)?$/i.test(env.TERM)) return 2;
105
+ if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) return 1;
106
+ if ("COLORTERM" in env) return 1;
137
107
  return min;
138
- }
139
- if ("TEAMCITY_VERSION" in env) {
140
- return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
141
- }
142
- if (env.COLORTERM === "truecolor") {
143
- return 3;
144
- }
145
- if (env.TERM === "xterm-kitty") {
146
- return 3;
147
- }
148
- if ("TERM_PROGRAM" in env) {
149
- const version = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
150
- switch (env.TERM_PROGRAM) {
151
- case "iTerm.app": {
152
- return version >= 3 ? 3 : 2;
153
- }
154
- case "Apple_Terminal": {
155
- return 2;
156
- }
157
- }
158
- }
159
- if (/-256(color)?$/i.test(env.TERM)) {
160
- return 2;
161
- }
162
- if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
163
- return 1;
164
- }
165
- if ("COLORTERM" in env) {
166
- return 1;
167
- }
168
- return min;
169
108
  }
170
109
  function createSupportsColor(stream, options = {}) {
171
- const level = _supportsColor(stream, {
172
- streamIsTTY: stream && stream.isTTY,
173
- ...options
174
- });
175
- return translateLevel(level);
110
+ const level = _supportsColor(stream, {
111
+ streamIsTTY: stream && stream.isTTY,
112
+ ...options
113
+ });
114
+ return translateLevel(level);
176
115
  }
177
116
  var supportsColor = {
178
- stdout: createSupportsColor({ isTTY: external_tty_namespaceObject["default"].isatty(1) }),
179
- stderr: createSupportsColor({ isTTY: external_tty_namespaceObject["default"].isatty(2) })
117
+ stdout: createSupportsColor({
118
+ isTTY: external_tty_namespaceObject["default"].isatty(1)
119
+ }),
120
+ stderr: createSupportsColor({
121
+ isTTY: external_tty_namespaceObject["default"].isatty(2)
122
+ })
180
123
  };
181
124
  var supports_color_default = supportsColor;
182
-
183
125
  // src/utils.ts
184
126
  var colorLevel = supports_color_default.stdout ? supports_color_default.stdout.level : 0;
185
127
  var errorStackRegExp = /at\s.*:\d+:\d+[\s\)]*$/;
186
- var anonymousErrorStackRegExp = /^\s*at\s.*\(<anonymous>\)$/;
187
- var isErrorStackMessage = (message) => errorStackRegExp.test(message) || anonymousErrorStackRegExp.test(message);
188
-
128
+ var anonymousErrorStackRegExp = /at\s.*\(<anonymous>\)$/;
129
+ var isErrorStackMessage = (message)=>errorStackRegExp.test(message) || anonymousErrorStackRegExp.test(message);
189
130
  // src/color.ts
190
- var formatter = (open, close, replace = open) => colorLevel >= 2 ? (input) => {
191
- let string = "" + input;
192
- let index = string.indexOf(close, open.length);
193
- return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
194
- } : String;
195
- var replaceClose = (string, close, replace, index) => {
196
- let start = string.substring(0, index) + replace;
197
- let end = string.substring(index + close.length);
198
- let nextIndex = end.indexOf(close);
199
- return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end;
131
+ var formatter = (open, close, replace = open)=>colorLevel >= 2 ? (input)=>{
132
+ let string = "" + input;
133
+ let index = string.indexOf(close, open.length);
134
+ return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
135
+ } : String;
136
+ var replaceClose = (string, close, replace, index)=>{
137
+ let start = string.substring(0, index) + replace;
138
+ let end = string.substring(index + close.length);
139
+ let nextIndex = end.indexOf(close);
140
+ return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end;
200
141
  };
201
142
  var bold = formatter("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m");
202
143
  var red = formatter("\x1B[31m", "\x1B[39m");
@@ -205,171 +146,143 @@ var yellow = formatter("\x1B[33m", "\x1B[39m");
205
146
  var magenta = formatter("\x1B[35m", "\x1B[39m");
206
147
  var cyan = formatter("\x1B[36m", "\x1B[39m");
207
148
  var gray = formatter("\x1B[90m", "\x1B[39m");
208
-
209
149
  // src/gradient.ts
210
- var startColor = [189, 255, 243];
211
- var endColor = [74, 194, 154];
212
- var isWord = (char) => !/[\s\n]/.test(char);
213
- var gradient = (message) => {
214
- if (colorLevel < 3) {
215
- return colorLevel === 2 ? bold(cyan(message)) : message;
216
- }
217
- let chars = [...message];
218
- let steps = chars.filter(isWord).length;
219
- let r = startColor[0];
220
- let g = startColor[1];
221
- let b = startColor[2];
222
- let rStep = (endColor[0] - r) / steps;
223
- let gStep = (endColor[1] - g) / steps;
224
- let bStep = (endColor[2] - b) / steps;
225
- let output = "";
226
- for (let char of chars) {
227
- if (isWord(char)) {
228
- r += rStep;
229
- g += gStep;
230
- b += bStep;
150
+ var startColor = [
151
+ 189,
152
+ 255,
153
+ 243
154
+ ];
155
+ var endColor = [
156
+ 74,
157
+ 194,
158
+ 154
159
+ ];
160
+ var isWord = (char)=>!/[\s\n]/.test(char);
161
+ var gradient = (message)=>{
162
+ if (colorLevel < 3) return 2 === colorLevel ? bold(cyan(message)) : message;
163
+ let chars = [
164
+ ...message
165
+ ];
166
+ let steps = chars.filter(isWord).length;
167
+ let r = startColor[0];
168
+ let g = startColor[1];
169
+ let b = startColor[2];
170
+ let rStep = (endColor[0] - r) / steps;
171
+ let gStep = (endColor[1] - g) / steps;
172
+ let bStep = (endColor[2] - b) / steps;
173
+ let output = "";
174
+ for (let char of chars){
175
+ if (isWord(char)) {
176
+ r += rStep;
177
+ g += gStep;
178
+ b += bStep;
179
+ }
180
+ output += `\x1B[38;2;${Math.round(r)};${Math.round(g)};${Math.round(b)}m${char}\x1B[39m`;
231
181
  }
232
- output += `\x1B[38;2;${Math.round(r)};${Math.round(g)};${Math.round(
233
- b
234
- )}m${char}\x1B[39m`;
235
- }
236
- return bold(output);
182
+ return bold(output);
237
183
  };
238
-
239
184
  // src/constants.ts
240
185
  var LOG_LEVEL = {
241
- error: 0,
242
- warn: 1,
243
- info: 2,
244
- log: 3,
245
- verbose: 4
186
+ error: 0,
187
+ warn: 1,
188
+ info: 2,
189
+ log: 3,
190
+ verbose: 4
246
191
  };
247
192
  var LOG_TYPES = {
248
- // Level error
249
- error: {
250
- label: "error",
251
- level: "error",
252
- color: red
253
- },
254
- // Level warn
255
- warn: {
256
- label: "warn",
257
- level: "warn",
258
- color: yellow
259
- },
260
- // Level info
261
- info: {
262
- label: "info",
263
- level: "info",
264
- color: cyan
265
- },
266
- start: {
267
- label: "start",
268
- level: "info",
269
- color: cyan
270
- },
271
- ready: {
272
- label: "ready",
273
- level: "info",
274
- color: green
275
- },
276
- success: {
277
- label: "success",
278
- level: "info",
279
- color: green
280
- },
281
- // Level log
282
- log: {
283
- level: "log"
284
- },
285
- // Level debug
286
- debug: {
287
- label: "debug",
288
- level: "verbose",
289
- color: magenta
290
- }
193
+ // Level error
194
+ error: {
195
+ label: "error",
196
+ level: "error",
197
+ color: red
198
+ },
199
+ // Level warn
200
+ warn: {
201
+ label: "warn",
202
+ level: "warn",
203
+ color: yellow
204
+ },
205
+ // Level info
206
+ info: {
207
+ label: "info",
208
+ level: "info",
209
+ color: cyan
210
+ },
211
+ start: {
212
+ label: "start",
213
+ level: "info",
214
+ color: cyan
215
+ },
216
+ ready: {
217
+ label: "ready",
218
+ level: "info",
219
+ color: green
220
+ },
221
+ success: {
222
+ label: "success",
223
+ level: "info",
224
+ color: green
225
+ },
226
+ // Level log
227
+ log: {
228
+ level: "log"
229
+ },
230
+ // Level debug
231
+ debug: {
232
+ label: "debug",
233
+ level: "verbose",
234
+ color: magenta
235
+ }
291
236
  };
292
-
293
237
  // src/createLogger.ts
294
- var createLogger = (options = {}) => {
295
- let maxLevel = options.level || "log";
296
- let log = (type, message, ...args) => {
297
- if (LOG_LEVEL[LOG_TYPES[type].level] > LOG_LEVEL[maxLevel]) {
298
- return;
299
- }
300
- if (message === void 0 || message === null) {
301
- return console.log();
302
- }
303
- let logType = LOG_TYPES[type];
304
- let label = "";
305
- let text = "";
306
- if ("label" in logType) {
307
- label = (logType.label || "").padEnd(7);
308
- label = bold(logType.color ? logType.color(label) : label);
309
- }
310
- if (message instanceof Error) {
311
- if (message.stack) {
312
- let [name, ...rest] = message.stack.split("\n");
313
- if (name.startsWith("Error: ")) {
314
- name = name.slice(7);
238
+ var createLogger = (options = {})=>{
239
+ let maxLevel = options.level || "log";
240
+ let log = (type, message, ...args)=>{
241
+ if (LOG_LEVEL[LOG_TYPES[type].level] > LOG_LEVEL[maxLevel]) return;
242
+ if (null == message) return console.log();
243
+ let logType = LOG_TYPES[type];
244
+ let label = "";
245
+ let text = "";
246
+ if ("label" in logType) {
247
+ label = (logType.label || "").padEnd(7);
248
+ label = bold(logType.color ? logType.color(label) : label);
315
249
  }
316
- text = `${name}
250
+ if (message instanceof Error) {
251
+ if (message.stack) {
252
+ let [name, ...rest] = message.stack.split("\n");
253
+ if (name.startsWith("Error: ")) name = name.slice(7);
254
+ text = `${name}
317
255
  ${gray(rest.join("\n"))}`;
318
- } else {
319
- text = message.message;
320
- }
321
- } else if (logType.level === "error" && typeof message === "string") {
322
- let lines = message.split("\n");
323
- text = lines.map((line) => isErrorStackMessage(line) ? gray(line) : line).join("\n");
324
- } else {
325
- text = `${message}`;
326
- }
327
- console.log(label.length ? `${label} ${text}` : text, ...args);
328
- };
329
- let logger2 = {
330
- greet: (message) => log("log", gradient(message))
331
- };
332
- Object.keys(LOG_TYPES).forEach((key) => {
333
- logger2[key] = (...args) => log(key, ...args);
334
- });
335
- Object.defineProperty(logger2, "level", {
336
- get: () => maxLevel,
337
- set(val) {
338
- maxLevel = val;
339
- }
340
- });
341
- logger2.override = (customLogger) => {
342
- Object.assign(logger2, customLogger);
343
- };
344
- return logger2;
256
+ } else text = message.message;
257
+ } else if ("error" === logType.level && "string" == typeof message) {
258
+ let lines = message.split("\n");
259
+ text = lines.map((line)=>isErrorStackMessage(line) ? gray(line) : line).join("\n");
260
+ } else text = `${message}`;
261
+ console.log(label.length ? `${label} ${text}` : text, ...args);
262
+ };
263
+ let logger2 = {
264
+ greet: (message)=>log("log", gradient(message))
265
+ };
266
+ Object.keys(LOG_TYPES).forEach((key)=>{
267
+ logger2[key] = (...args)=>log(key, ...args);
268
+ });
269
+ Object.defineProperty(logger2, "level", {
270
+ get: ()=>maxLevel,
271
+ set (val) {
272
+ maxLevel = val;
273
+ }
274
+ });
275
+ logger2.override = (customLogger)=>{
276
+ Object.assign(logger2, customLogger);
277
+ };
278
+ return logger2;
345
279
  };
346
-
347
280
  // src/index.ts
348
281
  var dist_logger = createLogger();
349
-
350
-
351
- ;// CONCATENATED MODULE: external "node:fs"
352
-
353
282
  var external_node_fs_namespaceObject = __WEBPACK_EXTERNAL_MODULE_node_fs__;
354
-
355
- ;// CONCATENATED MODULE: external "node:fs/promises"
356
-
357
283
  var promises_namespaceObject = __WEBPACK_EXTERNAL_MODULE_node_fs_promises__;
358
-
359
- ;// CONCATENATED MODULE: external "node:path"
360
-
361
284
  var external_node_path_namespaceObject = __WEBPACK_EXTERNAL_MODULE_node_path__;
362
-
363
- ;// CONCATENATED MODULE: external "../compiled/picocolors/index.js"
364
-
365
285
  var index_js_namespaceObject = __WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js__;
366
-
367
- ;// CONCATENATED MODULE: ./src/utils/helper.ts
368
-
369
-
370
-
371
-
372
-
373
286
  /**
374
287
  * Node.js built-in modules.
375
288
  * Copied from https://github.com/webpack/webpack/blob/dd44b206a9c50f4b4cb4d134e1a0bd0387b159a3/lib/node/NodeTargetPlugin.js#L12-L72
@@ -434,9 +347,7 @@ var index_js_namespaceObject = __WEBPACK_EXTERNAL_MODULE__compiled_picocolors_in
434
347
  'pnpapi'
435
348
  ];
436
349
  async function calcLongestCommonPath(absPaths) {
437
- if (absPaths.length === 0) {
438
- return null;
439
- }
350
+ if (0 === absPaths.length) return null;
440
351
  // we support two cases
441
352
  // 1. /packages-a/src/index.ts
442
353
  // 2. D:/packages-a/src/index.ts
@@ -447,16 +358,12 @@ async function calcLongestCommonPath(absPaths) {
447
358
  const currentPath = splitPaths[i];
448
359
  const minLength = Math.min(lcaFragments.length, currentPath.length);
449
360
  let j = 0;
450
- while(j < minLength && lcaFragments[j] === currentPath[j]){
451
- j++;
452
- }
361
+ while(j < minLength && lcaFragments[j] === currentPath[j])j++;
453
362
  lcaFragments = lcaFragments.slice(0, j);
454
363
  }
455
364
  let lca = lcaFragments.length > 0 ? lcaFragments.join(sep) : sep;
456
365
  const stats = await promises_namespaceObject["default"].stat(lca);
457
- if (stats?.isFile()) {
458
- lca = external_node_path_namespaceObject["default"].dirname(lca);
459
- }
366
+ if (stats?.isFile()) lca = external_node_path_namespaceObject["default"].dirname(lca);
460
367
  return lca;
461
368
  }
462
369
  const readPackageJson = (rootPath)=>{
@@ -472,75 +379,34 @@ const readPackageJson = (rootPath)=>{
472
379
  return;
473
380
  }
474
381
  };
475
- const isObject = (obj)=>Object.prototype.toString.call(obj) === '[object Object]';
476
-
477
-
478
- ;// CONCATENATED MODULE: ./src/utils/logger.ts
479
-
480
-
481
- // setup the logger level
482
- if (process.env.DEBUG) {
483
- dist_logger.level = 'verbose';
484
- }
485
- const isDebug = ()=>{
486
- if (!process.env.DEBUG) {
487
- return false;
488
- }
489
- logger.level = 'verbose';
490
- // support `process.env.DEBUG` in e2e
491
- const values = process.env.DEBUG.toLocaleLowerCase().split(',');
492
- return [
493
- 'rslib',
494
- 'rsbuild',
495
- 'builder',
496
- '*'
497
- ].some((key)=>values.includes(key));
498
- };
499
- function getTime() {
500
- const now = new Date();
501
- const hours = String(now.getHours()).padStart(2, '0');
502
- const minutes = String(now.getMinutes()).padStart(2, '0');
503
- const seconds = String(now.getSeconds()).padStart(2, '0');
504
- return `${hours}:${minutes}:${seconds}`;
382
+ const isObject = (obj)=>'[object Object]' === Object.prototype.toString.call(obj);
383
+ const isEmptyObject = (obj)=>0 === Object.keys(obj).length;
384
+ function pick(obj, keys) {
385
+ return keys.reduce((ret, key)=>{
386
+ if (void 0 !== obj[key]) ret[key] = obj[key];
387
+ return ret;
388
+ }, {});
505
389
  }
506
- const debug = (message)=>{
507
- if (isDebug()) {
508
- const result = typeof message === 'string' ? message : message();
509
- const time = color.gray(`${getTime()}`);
510
- logger.debug(`${time} ${result}`);
511
- }
512
- };
513
-
514
-
515
- ;// CONCATENATED MODULE: ./src/cli/prepare.ts
516
-
517
- function initNodeEnv() {
518
- if (false) {}
390
+ function omit(obj, keys) {
391
+ return Object.keys(obj).reduce((ret, key)=>{
392
+ if (!keys.includes(key)) ret[key] = obj[key];
393
+ return ret;
394
+ }, {});
519
395
  }
396
+ // setup the logger level
397
+ if (process.env.DEBUG) dist_logger.level = 'verbose';
398
+ function initNodeEnv() {}
520
399
  function prepareCli() {
521
400
  initNodeEnv();
522
401
  // Print a blank line to keep the greet log nice.
523
402
  // Some package managers automatically output a blank line, some do not.
524
403
  const { npm_execpath } = process.env;
525
- if (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) {
526
- console.log();
527
- }
528
- dist_logger.greet(` ${`Rslib v${"0.0.3"}`}\n`);
404
+ if (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) console.log();
405
+ dist_logger.greet(` Rslib v0.0.5\n`);
529
406
  }
530
-
531
- ;// CONCATENATED MODULE: external "../compiled/commander/index.js"
532
-
533
407
  var commander_index_js_namespaceObject = __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__;
534
-
535
- ;// CONCATENATED MODULE: external "@rsbuild/core"
536
-
537
408
  var core_namespaceObject = __WEBPACK_EXTERNAL_MODULE__rsbuild_core__;
538
-
539
- ;// CONCATENATED MODULE: external "../compiled/fast-glob/index.js"
540
-
541
409
  var fast_glob_index_js_namespaceObject = __WEBPACK_EXTERNAL_MODULE__compiled_fast_glob_index_js__;
542
-
543
- ;// CONCATENATED MODULE: ./src/constant.ts
544
410
  const DEFAULT_CONFIG_NAME = 'rslib.config';
545
411
  const DEFAULT_EXTENSIONS = [
546
412
  '.js',
@@ -550,19 +416,15 @@ const DEFAULT_EXTENSIONS = [
550
416
  '.cjs',
551
417
  '.cts'
552
418
  ];
553
-
554
- ;// CONCATENATED MODULE: ./src/utils/extension.ts
555
-
419
+ const SWC_HELPERS = '@swc/helpers';
556
420
  const getDefaultExtension = (options)=>{
557
421
  const { format, pkgJson, autoExtension } = options;
558
422
  let jsExtension = '.js';
559
423
  let dtsExtension = '.d.ts';
560
- if (!autoExtension) {
561
- return {
562
- jsExtension,
563
- dtsExtension
564
- };
565
- }
424
+ if (!autoExtension) return {
425
+ jsExtension,
426
+ dtsExtension
427
+ };
566
428
  if (!pkgJson) {
567
429
  dist_logger.warn('autoExtension configuration will not be applied due to read package.json failed');
568
430
  return {
@@ -570,12 +432,12 @@ const getDefaultExtension = (options)=>{
570
432
  dtsExtension
571
433
  };
572
434
  }
573
- const isModule = pkgJson.type === 'module';
574
- if (isModule && format === 'cjs') {
435
+ const isModule = 'module' === pkgJson.type;
436
+ if (isModule && 'cjs' === format) {
575
437
  jsExtension = '.cjs';
576
438
  dtsExtension = '.d.cts';
577
439
  }
578
- if (!isModule && format === 'esm') {
440
+ if (!isModule && 'esm' === format) {
579
441
  jsExtension = '.mjs';
580
442
  dtsExtension = '.d.mts';
581
443
  }
@@ -585,8 +447,6 @@ const getDefaultExtension = (options)=>{
585
447
  isModule
586
448
  };
587
449
  };
588
-
589
- ;// CONCATENATED MODULE: ./src/utils/syntax.ts
590
450
  /**
591
451
  * The esX to browserslist mapping is transformed from esbuild:
592
452
  * https://github.com/evanw/esbuild/blob/main/internal/compat/js_table.go
@@ -705,72 +565,118 @@ const getDefaultExtension = (options)=>{
705
565
  }
706
566
  };
707
567
  const transformSyntaxToBrowserslist = (syntax)=>{
708
- // only single esX is allowed
709
- if (typeof syntax === 'string' && syntax.toLowerCase().startsWith('es')) {
710
- if (syntax.toLowerCase() in ESX_TO_BROWSERSLIST) {
711
- return Object.entries(ESX_TO_BROWSERSLIST[syntax]).flatMap(([engine, version])=>{
712
- if (Array.isArray(version)) {
713
- return version;
714
- }
568
+ const handleSyntaxItem = (syntaxItem)=>{
569
+ if ('string' == typeof syntaxItem && syntaxItem.toLowerCase().startsWith('es')) {
570
+ if (syntaxItem.toLowerCase() in ESX_TO_BROWSERSLIST) return Object.entries(ESX_TO_BROWSERSLIST[syntaxItem]).flatMap(([engine, version])=>{
571
+ if (Array.isArray(version)) return version;
715
572
  return `${engine} >= ${version}`;
716
573
  });
574
+ throw new Error(`Unsupported ES version: ${syntaxItem}`);
717
575
  }
718
- throw new Error(`Unsupported ES version: ${syntax}`);
719
- }
720
- // inline browserslist query
721
- if (Array.isArray(syntax)) {
722
- return syntax;
723
- }
724
- throw new Error(`Unsupported syntax: ${syntax}`);
576
+ return [
577
+ syntaxItem
578
+ ];
579
+ };
580
+ if (Array.isArray(syntax)) return syntax.flatMap(handleSyntaxItem);
581
+ return handleSyntaxItem(syntax);
725
582
  };
726
-
727
- ;// CONCATENATED MODULE: ./src/config.ts
728
-
729
-
730
-
731
-
732
-
733
-
734
-
735
-
736
-
737
583
  /**
738
584
  * This function helps you to autocomplete configuration types.
739
585
  * It accepts a Rslib config object, or a function that returns a config.
740
586
  */ function defineConfig(config) {
741
587
  return config;
742
588
  }
743
- const findConfig = (basePath)=>{
744
- return DEFAULT_EXTENSIONS.map((ext)=>basePath + ext).find(external_node_fs_namespaceObject["default"].existsSync);
745
- };
589
+ const findConfig = (basePath)=>DEFAULT_EXTENSIONS.map((ext)=>basePath + ext).find(external_node_fs_namespaceObject["default"].existsSync);
746
590
  const resolveConfigPath = (root, customConfig)=>{
747
591
  if (customConfig) {
748
- const customConfigPath = (0,external_node_path_namespaceObject.isAbsolute)(customConfig) ? customConfig : (0,external_node_path_namespaceObject.join)(root, customConfig);
749
- if (external_node_fs_namespaceObject["default"].existsSync(customConfigPath)) {
750
- return customConfigPath;
751
- }
592
+ const customConfigPath = (0, external_node_path_namespaceObject.isAbsolute)(customConfig) ? customConfig : (0, external_node_path_namespaceObject.join)(root, customConfig);
593
+ if (external_node_fs_namespaceObject["default"].existsSync(customConfigPath)) return customConfigPath;
752
594
  dist_logger.warn(`Cannot find config file: ${index_js_namespaceObject["default"].dim(customConfigPath)}\n`);
753
595
  }
754
- const configFilePath = findConfig((0,external_node_path_namespaceObject.join)(root, DEFAULT_CONFIG_NAME));
755
- if (configFilePath) {
756
- return configFilePath;
757
- }
596
+ const configFilePath = findConfig((0, external_node_path_namespaceObject.join)(root, DEFAULT_CONFIG_NAME));
597
+ if (configFilePath) return configFilePath;
758
598
  throw new Error(`${DEFAULT_CONFIG_NAME} not found in ${root}`);
759
599
  };
760
600
  async function loadConfig({ cwd = process.cwd(), path, envMode }) {
761
601
  const configFilePath = resolveConfigPath(cwd, path);
762
- const { content } = await (0,core_namespaceObject.loadConfig)({
763
- cwd: (0,external_node_path_namespaceObject.dirname)(configFilePath),
602
+ const { content } = await (0, core_namespaceObject.loadConfig)({
603
+ cwd: (0, external_node_path_namespaceObject.dirname)(configFilePath),
764
604
  path: configFilePath,
765
605
  envMode
766
606
  });
767
607
  return content;
768
608
  }
609
+ const composeExternalsWarnConfig = (format, ...externalsArray)=>{
610
+ if ('esm' !== format) return {};
611
+ const externals = [];
612
+ for (const e of externalsArray.filter(Boolean))if (Array.isArray(e)) externals.push(...e);
613
+ else // @ts-ignore
614
+ externals.push(e);
615
+ // Match logic is derived from https://github.com/webpack/webpack/blob/94aba382eccf3de1004d235045d4462918dfdbb7/lib/ExternalModuleFactoryPlugin.js#L166-L293.
616
+ const matchUserExternals = (externals, request, callback)=>{
617
+ if ('string' == typeof externals) {
618
+ if (externals === request) {
619
+ callback(true);
620
+ return;
621
+ }
622
+ } else if (Array.isArray(externals)) {
623
+ let i = 0;
624
+ const next = ()=>{
625
+ let asyncFlag;
626
+ const handleExternalsAndCallback = (matched)=>{
627
+ if (!matched) {
628
+ if (asyncFlag) {
629
+ asyncFlag = false;
630
+ return;
631
+ }
632
+ return next();
633
+ }
634
+ callback(matched);
635
+ };
636
+ do {
637
+ asyncFlag = true;
638
+ if (i >= externals.length) return callback();
639
+ matchUserExternals(externals[i++], request, handleExternalsAndCallback);
640
+ }while (!asyncFlag);
641
+ asyncFlag = false;
642
+ };
643
+ next();
644
+ return;
645
+ } else if (externals instanceof RegExp) {
646
+ if (externals.test(request)) {
647
+ callback(true);
648
+ return;
649
+ }
650
+ } else if ('function' == typeof externals) ;
651
+ else if ('object' == typeof externals) {
652
+ if (Object.prototype.hasOwnProperty.call(externals, request)) {
653
+ callback(true);
654
+ return;
655
+ }
656
+ }
657
+ callback();
658
+ };
659
+ return {
660
+ output: {
661
+ externals: [
662
+ ({ request, dependencyType, contextInfo }, callback)=>{
663
+ let externalized = false;
664
+ const _callback = (matched)=>{
665
+ if (matched) externalized = true;
666
+ };
667
+ if (contextInfo.issuer && 'commonjs' === dependencyType) {
668
+ matchUserExternals(externals, request, _callback);
669
+ if (externalized) dist_logger.warn(composeModuleImportWarn(request));
670
+ }
671
+ callback();
672
+ }
673
+ ]
674
+ }
675
+ };
676
+ };
769
677
  const composeAutoExternalConfig = (options)=>{
770
678
  const { autoExternal, pkgJson, userExternals } = options;
771
- if (!autoExternal) {
772
- return {};
773
- }
679
+ if (!autoExternal) return {};
774
680
  if (!pkgJson) {
775
681
  dist_logger.warn('autoExternal configuration will not be applied due to read package.json failed');
776
682
  return {};
@@ -779,7 +685,7 @@ const composeAutoExternalConfig = (options)=>{
779
685
  dependencies: true,
780
686
  peerDependencies: true,
781
687
  devDependencies: false,
782
- ...autoExternal === true ? {} : autoExternal
688
+ ...true === autoExternal ? {} : autoExternal
783
689
  };
784
690
  // User externals configuration has higher priority than autoExternal
785
691
  // eg: autoExternal: ['react'], user: output: { externals: { react: 'react-1' } }
@@ -790,9 +696,7 @@ const composeAutoExternalConfig = (options)=>{
790
696
  'peerDependencies',
791
697
  'devDependencies'
792
698
  ].reduce((prev, type)=>{
793
- if (externalOptions[type]) {
794
- return pkgJson[type] ? prev.concat(Object.keys(pkgJson[type])) : prev;
795
- }
699
+ if (externalOptions[type]) return pkgJson[type] ? prev.concat(Object.keys(pkgJson[type])) : prev;
796
700
  return prev;
797
701
  }, []).filter((name)=>!userExternalKeys.includes(name));
798
702
  const uniqueExternals = Array.from(new Set(externals));
@@ -806,8 +710,86 @@ const composeAutoExternalConfig = (options)=>{
806
710
  }
807
711
  } : {};
808
712
  };
809
- async function createInternalRsbuildConfig() {
810
- return (0,core_namespaceObject.defineConfig)({
713
+ function composeMinifyConfig(minify) {
714
+ if (void 0 !== minify) // User's minify configuration will be merged afterwards.
715
+ return {};
716
+ // When minify is not specified, Rslib will use a sane default for minify options.
717
+ // The default options will only perform dead code elimination and unused code elimination.
718
+ return {
719
+ output: {
720
+ minify: {
721
+ js: true,
722
+ css: false,
723
+ jsOptions: {
724
+ minimizerOptions: {
725
+ mangle: false,
726
+ minify: false,
727
+ compress: {
728
+ defaults: false,
729
+ unused: true,
730
+ dead_code: true,
731
+ toplevel: true
732
+ },
733
+ format: {
734
+ comments: 'all'
735
+ }
736
+ }
737
+ }
738
+ }
739
+ }
740
+ };
741
+ }
742
+ function composeBannerFooterConfig(banner, footer) {
743
+ const bannerConfig = pick(banner, [
744
+ 'js',
745
+ 'css'
746
+ ]);
747
+ const footerConfig = pick(footer, [
748
+ 'js',
749
+ 'css'
750
+ ]);
751
+ if (isEmptyObject(bannerConfig) && isEmptyObject(footerConfig)) return {};
752
+ const plugins = [];
753
+ if (!isEmptyObject(bannerConfig)) {
754
+ if (bannerConfig.js) plugins.push(new core_namespaceObject.rspack.BannerPlugin({
755
+ banner: bannerConfig.js,
756
+ stage: core_namespaceObject.rspack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE + 1,
757
+ raw: true,
758
+ include: /\.(js|mjs|cjs)$/
759
+ }));
760
+ if (bannerConfig.css) plugins.push(new core_namespaceObject.rspack.BannerPlugin({
761
+ banner: bannerConfig.css,
762
+ stage: core_namespaceObject.rspack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE + 1,
763
+ raw: true,
764
+ include: /\.(css)$/
765
+ }));
766
+ }
767
+ if (!isEmptyObject(footerConfig)) {
768
+ if (footerConfig.js) plugins.push(new core_namespaceObject.rspack.BannerPlugin({
769
+ banner: footerConfig.js,
770
+ stage: core_namespaceObject.rspack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE + 1,
771
+ raw: true,
772
+ footer: true,
773
+ include: /\.(js|mjs|cjs)$/
774
+ }));
775
+ if (footerConfig.css) plugins.push(new core_namespaceObject.rspack.BannerPlugin({
776
+ banner: footerConfig.css,
777
+ stage: core_namespaceObject.rspack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE + 1,
778
+ raw: true,
779
+ footer: true,
780
+ include: /\.(css)$/
781
+ }));
782
+ }
783
+ return {
784
+ tools: {
785
+ rspack: {
786
+ plugins
787
+ }
788
+ }
789
+ };
790
+ }
791
+ async function createConstantRsbuildConfig() {
792
+ return (0, core_namespaceObject.defineConfig)({
811
793
  mode: 'production',
812
794
  dev: {
813
795
  progressBar: false
@@ -816,7 +798,8 @@ async function createInternalRsbuildConfig() {
816
798
  htmlPlugin: false,
817
799
  rspack: {
818
800
  optimization: {
819
- moduleIds: 'named'
801
+ moduleIds: 'named',
802
+ nodeEnv: false
820
803
  },
821
804
  experiments: {
822
805
  rspackFuture: {
@@ -824,13 +807,35 @@ async function createInternalRsbuildConfig() {
824
807
  force: false
825
808
  }
826
809
  }
810
+ },
811
+ // TypeScript-specific behavior: if the extension is ".js" or ".jsx", try replacing it with ".ts" or ".tsx"
812
+ // see https://github.com/web-infra-dev/rslib/issues/41
813
+ resolve: {
814
+ extensionAlias: {
815
+ '.js': [
816
+ '.ts',
817
+ '.tsx',
818
+ '.js',
819
+ '.jsx'
820
+ ],
821
+ '.jsx': [
822
+ '.tsx',
823
+ '.jsx'
824
+ ],
825
+ '.mjs': [
826
+ '.mts',
827
+ '.mjs'
828
+ ],
829
+ '.cjs': [
830
+ '.cts',
831
+ '.cjs'
832
+ ]
833
+ }
827
834
  }
828
835
  }
829
836
  },
830
837
  output: {
831
838
  filenameHash: false,
832
- // TODO: easy to development at the moment
833
- minify: false,
834
839
  distPath: {
835
840
  js: './'
836
841
  }
@@ -843,7 +848,6 @@ const composeFormatConfig = (format)=>{
843
848
  return {
844
849
  tools: {
845
850
  rspack: {
846
- externalsType: 'module-import',
847
851
  output: {
848
852
  module: true,
849
853
  chunkFormat: 'module',
@@ -871,7 +875,6 @@ const composeFormatConfig = (format)=>{
871
875
  return {
872
876
  tools: {
873
877
  rspack: {
874
- externalsType: 'commonjs',
875
878
  output: {
876
879
  iife: false,
877
880
  chunkFormat: 'commonjs',
@@ -886,7 +889,6 @@ const composeFormatConfig = (format)=>{
886
889
  return {
887
890
  tools: {
888
891
  rspack: {
889
- externalsType: 'umd',
890
892
  output: {
891
893
  library: {
892
894
  type: 'umd'
@@ -899,6 +901,34 @@ const composeFormatConfig = (format)=>{
899
901
  throw new Error(`Unsupported format: ${format}`);
900
902
  }
901
903
  };
904
+ const composeModuleImportWarn = (request)=>`The externalized commonjs request ${index_js_namespaceObject["default"].green(`"${request}"`)} will use ${index_js_namespaceObject["default"].blue('"module"')} external type in ESM format. If you want to specify other external type, considering set the request and type with ${index_js_namespaceObject["default"].blue('"output.externals"')}.`;
905
+ const composeExternalsConfig = (format, externals)=>{
906
+ // TODO: Define the internal externals config in Rsbuild's externals instead
907
+ // Rspack's externals as they will not be merged from different fields. All externals
908
+ // should to be unified and merged together in the future.
909
+ const externalsTypeMap = {
910
+ esm: 'module-import',
911
+ cjs: 'commonjs',
912
+ umd: 'umd'
913
+ };
914
+ switch(format){
915
+ case 'esm':
916
+ case 'cjs':
917
+ case 'umd':
918
+ return {
919
+ output: externals ? {
920
+ externals
921
+ } : {},
922
+ tools: {
923
+ rspack: {
924
+ externalsType: externalsTypeMap[format]
925
+ }
926
+ }
927
+ };
928
+ default:
929
+ throw new Error(`Unsupported format: ${format}`);
930
+ }
931
+ };
902
932
  const composeAutoExtensionConfig = (config, autoExtension, pkgJson)=>{
903
933
  const { jsExtension, dtsExtension } = getDefaultExtension({
904
934
  format: config.format,
@@ -920,24 +950,22 @@ const composeAutoExtensionConfig = (config, autoExtension, pkgJson)=>{
920
950
  };
921
951
  const composeSyntaxConfig = (syntax, target)=>{
922
952
  // Defaults to ESNext, Rslib will assume all of the latest JavaScript and CSS features are supported.
923
- if (syntax) {
924
- return {
925
- tools: {
926
- rspack: (config)=>{
927
- // TODO: Rspack should could resolve `browserslist:{query}` like webpack.
928
- // https://webpack.js.org/configuration/target/#browserslist
929
- // Using 'es5' as a temporary solution for compatibility.
930
- config.target = [
931
- 'es5'
932
- ];
933
- return config;
934
- }
935
- },
936
- output: {
937
- overrideBrowserslist: transformSyntaxToBrowserslist(syntax)
953
+ if (syntax) return {
954
+ tools: {
955
+ rspack: (config)=>{
956
+ // TODO: Rspack should could resolve `browserslist:{query}` like webpack.
957
+ // https://webpack.js.org/configuration/target/#browserslist
958
+ // Using 'es5' as a temporary solution for compatibility.
959
+ config.target = [
960
+ 'es5'
961
+ ];
962
+ return config;
938
963
  }
939
- };
940
- }
964
+ },
965
+ output: {
966
+ overrideBrowserslist: transformSyntaxToBrowserslist(syntax)
967
+ }
968
+ };
941
969
  // If `syntax` is not defined, Rslib will try to determine by the `target`, with the last version of the target.
942
970
  const lastTargetVersions = {
943
971
  node: [
@@ -962,7 +990,7 @@ const composeSyntaxConfig = (syntax, target)=>{
962
990
  }
963
991
  },
964
992
  output: {
965
- overrideBrowserslist: target === 'web' ? lastTargetVersions.web : target === 'node' ? lastTargetVersions.node : [
993
+ overrideBrowserslist: 'web' === target ? lastTargetVersions.web : 'node' === target ? lastTargetVersions.node : [
966
994
  ...lastTargetVersions.node,
967
995
  ...lastTargetVersions.web
968
996
  ]
@@ -970,16 +998,12 @@ const composeSyntaxConfig = (syntax, target)=>{
970
998
  };
971
999
  };
972
1000
  const composeEntryConfig = async (entries, bundle, root)=>{
973
- if (!entries) {
974
- return {};
975
- }
976
- if (bundle !== false) {
977
- return {
978
- source: {
979
- entry: entries
980
- }
981
- };
982
- }
1001
+ if (!entries) return {};
1002
+ if (false !== bundle) return {
1003
+ source: {
1004
+ entry: entries
1005
+ }
1006
+ };
983
1007
  // In bundleless mode, resolve glob patterns and convert them to entry object.
984
1008
  const resolvedEntries = {};
985
1009
  for (const key of Object.keys(entries)){
@@ -988,23 +1012,19 @@ const composeEntryConfig = async (entries, bundle, root)=>{
988
1012
  // 1. A string of glob pattern: { entry: { index: 'src/*.ts' } }
989
1013
  // 2. An array of glob patterns: { entry: { index: ['src/*.ts', 'src/*.tsx'] } }
990
1014
  // Not supported for now: entry description object
991
- const entryFiles = Array.isArray(entry) ? entry : typeof entry === 'string' ? [
1015
+ const entryFiles = Array.isArray(entry) ? entry : 'string' == typeof entry ? [
992
1016
  entry
993
1017
  ] : null;
994
- if (!entryFiles) {
995
- throw new Error('Entry can only be a string or an array of strings for now');
996
- }
1018
+ if (!entryFiles) throw new Error('Entry can only be a string or an array of strings for now');
997
1019
  // Turn entries in array into each separate entry.
998
- const resolvedEntryFiles = await (0,fast_glob_index_js_namespaceObject["default"])(entryFiles, {
1020
+ const resolvedEntryFiles = await (0, fast_glob_index_js_namespaceObject["default"])(entryFiles, {
999
1021
  cwd: root
1000
1022
  });
1001
- if (resolvedEntryFiles.length === 0) {
1002
- throw new Error(`Cannot find ${resolvedEntryFiles}`);
1003
- }
1023
+ if (0 === resolvedEntryFiles.length) throw new Error(`Cannot find ${resolvedEntryFiles}`);
1004
1024
  // Similar to `rootDir` in tsconfig and `outbase` in esbuild.
1005
1025
  const lcp = await calcLongestCommonPath(resolvedEntryFiles);
1006
1026
  // Using the longest common path of all non-declaration input files by default.
1007
- const outBase = lcp === null ? root : lcp;
1027
+ const outBase = null === lcp ? root : lcp;
1008
1028
  for (const file of resolvedEntryFiles){
1009
1029
  const { dir, name } = external_node_path_namespaceObject["default"].parse(external_node_path_namespaceObject["default"].relative(outBase, file));
1010
1030
  // Entry filename contains nested path to preserve source directory structure.
@@ -1028,8 +1048,14 @@ const composeBundleConfig = (jsExtension, bundle = true)=>{
1028
1048
  // Prevent from externalizing entry modules here.
1029
1049
  if (data.contextInfo.issuer) {
1030
1050
  // Node.js ECMAScript module loader does no extension searching.
1031
- // So we add a file extension here when data.request is a relative path
1032
- return callback(null, data.request[0] === '.' ? `${data.request}${jsExtension}` : data.request);
1051
+ // Add a file extension according to autoExtension config
1052
+ // when data.request is a relative path and do not have an extension.
1053
+ // If data.request already have an extension, we replace it with new extension
1054
+ // This may result in a change in semantics,
1055
+ // user should use copy to keep origin file or use another separate entry to deal this
1056
+ let request = data.request;
1057
+ if ('.' === request[0]) request = (0, external_node_path_namespaceObject.extname)(request) ? request.replace(/\.[^.]+$/, jsExtension) : `${request}${jsExtension}`;
1058
+ return callback(null, request);
1033
1059
  }
1034
1060
  callback();
1035
1061
  }
@@ -1038,9 +1064,9 @@ const composeBundleConfig = (jsExtension, bundle = true)=>{
1038
1064
  };
1039
1065
  };
1040
1066
  const composeDtsConfig = async (libConfig, dtsExtension)=>{
1041
- const { dts, bundle, output, autoExternal } = libConfig;
1042
- if (dts === false || dts === undefined) return {};
1043
- const { pluginDts } = await Promise.resolve(/* import() */ ).then(__webpack_require__.bind(__webpack_require__, "rsbuild-plugin-dts"));
1067
+ const { dts, bundle, output, autoExternal, banner, footer } = libConfig;
1068
+ if (false === dts || void 0 === dts) return {};
1069
+ const { pluginDts } = await Promise.resolve().then(__webpack_require__.bind(__webpack_require__, "rsbuild-plugin-dts"));
1044
1070
  return {
1045
1071
  plugins: [
1046
1072
  pluginDts({
@@ -1048,7 +1074,9 @@ const composeDtsConfig = async (libConfig, dtsExtension)=>{
1048
1074
  distPath: dts?.distPath ?? output?.distPath?.root ?? './dist',
1049
1075
  abortOnError: dts?.abortOnError ?? true,
1050
1076
  dtsExtension,
1051
- autoExternal
1077
+ autoExternal,
1078
+ banner: banner?.dts,
1079
+ footer: footer?.dts
1052
1080
  })
1053
1081
  ]
1054
1082
  };
@@ -1100,48 +1128,96 @@ const composeTargetConfig = (target = 'web')=>{
1100
1128
  throw new Error(`Unsupported platform: ${target}`);
1101
1129
  }
1102
1130
  };
1103
- async function composeLibRsbuildConfig(libConfig, rsbuildConfig, configPath) {
1104
- const config = (0,core_namespaceObject.mergeRsbuildConfig)(rsbuildConfig, libConfig);
1105
- const rootPath = (0,external_node_path_namespaceObject.dirname)(configPath);
1131
+ const composeExternalHelpersConfig = (externalHelpers, pkgJson)=>{
1132
+ let defaultConfig = {
1133
+ tools: {
1134
+ swc: {
1135
+ jsc: {
1136
+ externalHelpers: false
1137
+ }
1138
+ }
1139
+ }
1140
+ };
1141
+ if (externalHelpers) {
1142
+ const deps = [
1143
+ ...Object.keys(pkgJson?.dependencies ?? []),
1144
+ ...Object.keys(pkgJson?.devDependencies ?? [])
1145
+ ];
1146
+ if (!deps.includes(SWC_HELPERS)) {
1147
+ dist_logger.error(`${index_js_namespaceObject["default"].green('externalHelpers')} is enabled, but the ${index_js_namespaceObject["default"].blue(SWC_HELPERS)} dependency declaration was not found in package.json.`);
1148
+ process.exit(1);
1149
+ }
1150
+ defaultConfig = Object.assign(defaultConfig, {
1151
+ output: {
1152
+ externals: new RegExp(`^${SWC_HELPERS}($|\\/|\\\\)`)
1153
+ }
1154
+ });
1155
+ defaultConfig.tools.swc.jsc.externalHelpers = true;
1156
+ }
1157
+ return defaultConfig;
1158
+ };
1159
+ async function composeLibRsbuildConfig(config, configPath) {
1160
+ const rootPath = (0, external_node_path_namespaceObject.dirname)(configPath);
1106
1161
  const pkgJson = readPackageJson(rootPath);
1107
- const { format, autoExtension = true, autoExternal = true } = config;
1162
+ const { format, banner = {}, footer = {}, autoExtension = true, autoExternal = true, externalHelpers = false } = config;
1108
1163
  const formatConfig = composeFormatConfig(format);
1164
+ const externalHelpersConfig = composeExternalHelpersConfig(externalHelpers, pkgJson);
1165
+ const externalsConfig = composeExternalsConfig(format, config.output?.externals);
1109
1166
  const { config: autoExtensionConfig, jsExtension, dtsExtension } = composeAutoExtensionConfig(config, autoExtension, pkgJson);
1110
1167
  const bundleConfig = composeBundleConfig(jsExtension, config.bundle);
1111
1168
  const targetConfig = composeTargetConfig(config.output?.target);
1112
- const syntaxConfig = composeSyntaxConfig(config.output?.syntax, config.output?.target);
1169
+ const syntaxConfig = composeSyntaxConfig(config?.syntax, config.output?.target);
1113
1170
  const autoExternalConfig = composeAutoExternalConfig({
1114
1171
  autoExternal,
1115
1172
  pkgJson,
1116
- userExternals: rsbuildConfig.output?.externals
1173
+ userExternals: config.output?.externals
1117
1174
  });
1118
- const entryConfig = await composeEntryConfig(config.source?.entry, config.bundle, (0,external_node_path_namespaceObject.dirname)(configPath));
1175
+ const entryConfig = await composeEntryConfig(config.source?.entry, config.bundle, (0, external_node_path_namespaceObject.dirname)(configPath));
1119
1176
  const dtsConfig = await composeDtsConfig(config, dtsExtension);
1120
- return (0,core_namespaceObject.mergeRsbuildConfig)(formatConfig, autoExtensionConfig, autoExternalConfig, syntaxConfig, bundleConfig, targetConfig, entryConfig, dtsConfig);
1177
+ const externalsWarnConfig = composeExternalsWarnConfig(format, autoExternalConfig?.output?.externals, externalsConfig?.output?.externals);
1178
+ const minifyConfig = composeMinifyConfig(config.output?.minify);
1179
+ const bannerFooterConfig = composeBannerFooterConfig(banner, footer);
1180
+ return (0, core_namespaceObject.mergeRsbuildConfig)(formatConfig, externalHelpersConfig, externalsWarnConfig, externalsConfig, autoExternalConfig, autoExtensionConfig, syntaxConfig, bundleConfig, targetConfig, entryConfig, minifyConfig, dtsConfig, bannerFooterConfig);
1121
1181
  }
1122
1182
  async function composeCreateRsbuildConfig(rslibConfig, path) {
1123
- const internalRsbuildConfig = await createInternalRsbuildConfig();
1183
+ const constantRsbuildConfig = await createConstantRsbuildConfig();
1124
1184
  const configPath = path ?? rslibConfig._privateMeta?.configFilePath;
1125
1185
  const { lib: libConfigsArray, ...sharedRsbuildConfig } = rslibConfig;
1126
- if (!libConfigsArray) {
1127
- throw new Error(`Expect lib field to be an array, but got ${libConfigsArray}.`);
1128
- }
1186
+ if (!libConfigsArray) throw new Error(`Expect lib field to be an array, but got ${libConfigsArray}.`);
1129
1187
  const libConfigPromises = libConfigsArray.map(async (libConfig)=>{
1130
- const { format, ...overrideRsbuildConfig } = libConfig;
1131
- const baseRsbuildConfig = (0,core_namespaceObject.mergeRsbuildConfig)(sharedRsbuildConfig, overrideRsbuildConfig);
1188
+ const userConfig = (0, core_namespaceObject.mergeRsbuildConfig)(sharedRsbuildConfig, libConfig);
1132
1189
  // Merge the configuration of each environment based on the shared Rsbuild
1133
1190
  // configuration and Lib configuration in the settings.
1134
- const libRsbuildConfig = await composeLibRsbuildConfig(libConfig, baseRsbuildConfig, configPath);
1191
+ const libRsbuildConfig = await composeLibRsbuildConfig(userConfig, configPath);
1135
1192
  // Reset certain fields because they will be completely overridden by the upcoming merge.
1136
1193
  // We don't want to retain them in the final configuration.
1137
1194
  // The reset process should occur after merging the library configuration.
1138
- baseRsbuildConfig.source ??= {};
1139
- baseRsbuildConfig.source.entry = {};
1195
+ userConfig.source ??= {};
1196
+ userConfig.source.entry = {};
1197
+ // Already manually sort and merge the externals configuration.
1198
+ userConfig.output ??= {};
1199
+ delete userConfig.output.externals;
1140
1200
  return {
1141
- format: format,
1142
- config: (0,core_namespaceObject.mergeRsbuildConfig)(baseRsbuildConfig, libRsbuildConfig, // Merge order matters, keep `internalRsbuildConfig` at the last position
1143
- // to ensure that the internal config is not overridden by user's config.
1144
- internalRsbuildConfig)
1201
+ format: libConfig.format,
1202
+ // The merge order represents the priority of the configuration
1203
+ // The priorities from high to low are as follows:
1204
+ // 1 - userConfig: users can configure any Rsbuild and Rspack config
1205
+ // 2 - libRsbuildConfig: the configuration that we compose from Rslib unique config and userConfig from 1
1206
+ // 3 - constantRsbuildConfig: the built-in best practice Rsbuild configuration we provide in Rslib
1207
+ // We should state in the document that the built-in configuration should not be changed optionally
1208
+ // In compose process of 2, we may read some config from 1, and reassemble the related config,
1209
+ // so before final mergeRsbuildConfig, we reset some specified fields
1210
+ config: (0, core_namespaceObject.mergeRsbuildConfig)(constantRsbuildConfig, libRsbuildConfig, omit(userConfig, [
1211
+ 'bundle',
1212
+ 'format',
1213
+ 'autoExtension',
1214
+ 'autoExternal',
1215
+ 'syntax',
1216
+ 'externalHelpers',
1217
+ 'banner',
1218
+ 'footer',
1219
+ 'dts'
1220
+ ]))
1145
1221
  };
1146
1222
  });
1147
1223
  const composedRsbuildConfig = await Promise.all(libConfigPromises);
@@ -1162,17 +1238,14 @@ async function initRsbuild(rslibConfig) {
1162
1238
  for (const { format, config } of rsbuildConfigObject){
1163
1239
  const currentFormatCount = formatCount[format];
1164
1240
  const currentFormatIndex = formatIndex[format]++;
1165
- environments[currentFormatCount === 1 ? format : `${format}${currentFormatIndex}`] = config;
1241
+ environments[1 === currentFormatCount ? format : `${format}${currentFormatIndex}`] = config;
1166
1242
  }
1167
- return (0,core_namespaceObject.createRsbuild)({
1243
+ return (0, core_namespaceObject.createRsbuild)({
1168
1244
  rsbuildConfig: {
1169
1245
  environments
1170
1246
  }
1171
1247
  });
1172
1248
  }
1173
-
1174
- ;// CONCATENATED MODULE: ./src/build.ts
1175
-
1176
1249
  async function build(config, options) {
1177
1250
  const rsbuildInstance = await initRsbuild(config);
1178
1251
  await rsbuildInstance.build({
@@ -1180,17 +1253,11 @@ async function build(config, options) {
1180
1253
  });
1181
1254
  return rsbuildInstance;
1182
1255
  }
1183
-
1184
- ;// CONCATENATED MODULE: ./src/cli/commands.ts
1185
-
1186
-
1187
-
1188
-
1189
1256
  const applyCommonOptions = (command)=>{
1190
1257
  command.option('-c --config <config>', 'specify the configuration file, can be a relative or absolute path').option('--env-mode <mode>', 'specify the env mode to load the `.env.[mode]` file');
1191
1258
  };
1192
1259
  function runCli() {
1193
- commander_index_js_namespaceObject.program.name('rslib').usage('<command> [options]').version("0.0.3");
1260
+ commander_index_js_namespaceObject.program.name('rslib').usage('<command> [options]').version("0.0.5");
1194
1261
  const buildCommand = commander_index_js_namespaceObject.program.command('build');
1195
1262
  const inspectCommand = commander_index_js_namespaceObject.program.command('inspect');
1196
1263
  [
@@ -1232,13 +1299,5 @@ function runCli() {
1232
1299
  });
1233
1300
  commander_index_js_namespaceObject.program.parse();
1234
1301
  }
1235
-
1236
- ;// CONCATENATED MODULE: ./src/index.ts
1237
-
1238
-
1239
-
1240
-
1241
-
1242
- const src_version = "0.0.3";
1243
-
1302
+ const src_version = "0.0.5";
1244
1303
  export { build, defineConfig, loadConfig, dist_logger as logger, prepareCli, runCli, src_version as version };