@rslib/core 0.0.4 → 0.0.6

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
@@ -1,6 +1,4 @@
1
- import * as __WEBPACK_EXTERNAL_MODULE_process__ from "process";
2
- import * as __WEBPACK_EXTERNAL_MODULE_os__ from "os";
3
- import * as __WEBPACK_EXTERNAL_MODULE_tty__ from "tty";
1
+ import * as __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__ from "../compiled/rslog/index.js";
4
2
  import * as __WEBPACK_EXTERNAL_MODULE_node_fs__ from "node:fs";
5
3
  import * as __WEBPACK_EXTERNAL_MODULE_node_fs_promises__ from "node:fs/promises";
6
4
  import * as __WEBPACK_EXTERNAL_MODULE_node_path__ from "node:path";
@@ -8,368 +6,12 @@ import * as __WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js__ from "../c
8
6
  import * as __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__ from "../compiled/commander/index.js";
9
7
  import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core__ from "@rsbuild/core";
10
8
  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
20
- var __webpack_module_cache__ = {};
21
-
22
- // The require function
23
- 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
-
46
- var external_process_namespaceObject = __WEBPACK_EXTERNAL_MODULE_process__;
47
-
48
- ;// CONCATENATED MODULE: external "os"
49
-
50
- var external_os_namespaceObject = __WEBPACK_EXTERNAL_MODULE_os__;
51
-
52
- ;// CONCATENATED MODULE: external "tty"
53
-
54
- 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
- // node_modules/.pnpm/supports-color@9.4.0/node_modules/supports-color/index.js
58
-
59
-
60
-
61
- 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);
66
- }
67
- var { env } = external_process_namespaceObject["default"];
68
- 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
- }
74
- 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;
81
- }
82
- return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
83
- }
84
- }
85
- 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
- };
95
- }
96
- 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;
111
- }
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;
127
- }
128
- return 1;
129
- }
130
- if ("CI" in env) {
131
- if ("GITHUB_ACTIONS" in env || "GITEA_ACTIONS" in env) {
132
- return 3;
133
- }
134
- if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
135
- return 1;
136
- }
137
- 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
- }
170
- function createSupportsColor(stream, options = {}) {
171
- const level = _supportsColor(stream, {
172
- streamIsTTY: stream && stream.isTTY,
173
- ...options
174
- });
175
- return translateLevel(level);
176
- }
177
- var supportsColor = {
178
- stdout: createSupportsColor({ isTTY: external_tty_namespaceObject["default"].isatty(1) }),
179
- stderr: createSupportsColor({ isTTY: external_tty_namespaceObject["default"].isatty(2) })
180
- };
181
- var supports_color_default = supportsColor;
182
-
183
- // src/utils.ts
184
- var colorLevel = supports_color_default.stdout ? supports_color_default.stdout.level : 0;
185
- 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
-
189
- // 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;
200
- };
201
- var bold = formatter("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m");
202
- var red = formatter("\x1B[31m", "\x1B[39m");
203
- var green = formatter("\x1B[32m", "\x1B[39m");
204
- var yellow = formatter("\x1B[33m", "\x1B[39m");
205
- var magenta = formatter("\x1B[35m", "\x1B[39m");
206
- var cyan = formatter("\x1B[36m", "\x1B[39m");
207
- var gray = formatter("\x1B[90m", "\x1B[39m");
208
-
209
- // 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;
231
- }
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);
237
- };
238
-
239
- // src/constants.ts
240
- var LOG_LEVEL = {
241
- error: 0,
242
- warn: 1,
243
- info: 2,
244
- log: 3,
245
- verbose: 4
246
- };
247
- 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
- }
291
- };
292
-
293
- // 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);
315
- }
316
- text = `${name}
317
- ${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;
345
- };
346
-
347
- // src/index.ts
348
- var dist_logger = createLogger();
349
-
350
-
351
- ;// CONCATENATED MODULE: external "node:fs"
352
-
9
+ import * as __WEBPACK_EXTERNAL_MODULE_module__ from "module";
10
+ var index_js_namespaceObject = __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__;
353
11
  var external_node_fs_namespaceObject = __WEBPACK_EXTERNAL_MODULE_node_fs__;
354
-
355
- ;// CONCATENATED MODULE: external "node:fs/promises"
356
-
357
12
  var promises_namespaceObject = __WEBPACK_EXTERNAL_MODULE_node_fs_promises__;
358
-
359
- ;// CONCATENATED MODULE: external "node:path"
360
-
361
13
  var external_node_path_namespaceObject = __WEBPACK_EXTERNAL_MODULE_node_path__;
362
-
363
- ;// CONCATENATED MODULE: external "../compiled/picocolors/index.js"
364
-
365
- var index_js_namespaceObject = __WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js__;
366
-
367
- ;// CONCATENATED MODULE: ./src/utils/helper.ts
368
-
369
-
370
-
371
-
372
-
14
+ var picocolors_index_js_namespaceObject = __WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js__;
373
15
  /**
374
16
  * Node.js built-in modules.
375
17
  * Copied from https://github.com/webpack/webpack/blob/dd44b206a9c50f4b4cb4d134e1a0bd0387b159a3/lib/node/NodeTargetPlugin.js#L12-L72
@@ -434,9 +76,7 @@ var index_js_namespaceObject = __WEBPACK_EXTERNAL_MODULE__compiled_picocolors_in
434
76
  'pnpapi'
435
77
  ];
436
78
  async function calcLongestCommonPath(absPaths) {
437
- if (absPaths.length === 0) {
438
- return null;
439
- }
79
+ if (0 === absPaths.length) return null;
440
80
  // we support two cases
441
81
  // 1. /packages-a/src/index.ts
442
82
  // 2. D:/packages-a/src/index.ts
@@ -447,119 +87,62 @@ async function calcLongestCommonPath(absPaths) {
447
87
  const currentPath = splitPaths[i];
448
88
  const minLength = Math.min(lcaFragments.length, currentPath.length);
449
89
  let j = 0;
450
- while(j < minLength && lcaFragments[j] === currentPath[j]){
451
- j++;
452
- }
90
+ while(j < minLength && lcaFragments[j] === currentPath[j])j++;
453
91
  lcaFragments = lcaFragments.slice(0, j);
454
92
  }
455
93
  let lca = lcaFragments.length > 0 ? lcaFragments.join(sep) : sep;
456
94
  const stats = await promises_namespaceObject["default"].stat(lca);
457
- if (stats?.isFile()) {
458
- lca = external_node_path_namespaceObject["default"].dirname(lca);
459
- }
95
+ if (stats?.isFile()) lca = external_node_path_namespaceObject["default"].dirname(lca);
460
96
  return lca;
461
97
  }
462
98
  const readPackageJson = (rootPath)=>{
463
99
  const pkgJsonPath = external_node_path_namespaceObject["default"].join(rootPath, './package.json');
464
100
  if (!external_node_fs_namespaceObject["default"].existsSync(pkgJsonPath)) {
465
- dist_logger.warn(`package.json does not exist in the ${rootPath} directory`);
101
+ index_js_namespaceObject.logger.warn(`package.json does not exist in the ${rootPath} directory`);
466
102
  return;
467
103
  }
468
104
  try {
469
105
  return JSON.parse(external_node_fs_namespaceObject["default"].readFileSync(pkgJsonPath, 'utf8'));
470
106
  } catch (err) {
471
- dist_logger.warn(`Failed to parse ${pkgJsonPath}, it might not be valid JSON`);
107
+ index_js_namespaceObject.logger.warn(`Failed to parse ${pkgJsonPath}, it might not be valid JSON`);
472
108
  return;
473
109
  }
474
110
  };
475
- const isObject = (obj)=>Object.prototype.toString.call(obj) === '[object Object]';
476
- function omitDeep(obj, keys) {
477
- if (typeof obj === 'string' || typeof obj !== 'object' || obj === null) return obj;
478
- if (Array.isArray(obj)) {
479
- return obj.map((item)=>omitDeep(item, keys));
480
- }
481
- const clone = {};
482
- for(const property in obj){
483
- if (keys.includes(property)) {
484
- continue;
485
- }
486
- const value = obj[property];
487
- if (value && typeof value === 'object') {
488
- clone[property] = omitDeep(value, keys);
489
- } else {
490
- clone[property] = value;
491
- }
492
- }
493
- return clone;
494
- }
495
-
496
-
497
- ;// CONCATENATED MODULE: ./src/utils/logger.ts
498
-
499
-
500
- // setup the logger level
501
- if (process.env.DEBUG) {
502
- dist_logger.level = 'verbose';
111
+ const isObject = (obj)=>'[object Object]' === Object.prototype.toString.call(obj);
112
+ const isEmptyObject = (obj)=>0 === Object.keys(obj).length;
113
+ function pick(obj, keys) {
114
+ return keys.reduce((ret, key)=>{
115
+ if (void 0 !== obj[key]) ret[key] = obj[key];
116
+ return ret;
117
+ }, {});
503
118
  }
504
- const isDebug = ()=>{
505
- if (!process.env.DEBUG) {
506
- return false;
507
- }
508
- logger.level = 'verbose';
509
- // support `process.env.DEBUG` in e2e
510
- const values = process.env.DEBUG.toLocaleLowerCase().split(',');
511
- return [
512
- 'rslib',
513
- 'rsbuild',
514
- 'builder',
515
- '*'
516
- ].some((key)=>values.includes(key));
517
- };
518
- function getTime() {
519
- const now = new Date();
520
- const hours = String(now.getHours()).padStart(2, '0');
521
- const minutes = String(now.getMinutes()).padStart(2, '0');
522
- const seconds = String(now.getSeconds()).padStart(2, '0');
523
- return `${hours}:${minutes}:${seconds}`;
119
+ function omit(obj, keys) {
120
+ return Object.keys(obj).reduce((ret, key)=>{
121
+ if (!keys.includes(key)) ret[key] = obj[key];
122
+ return ret;
123
+ }, {});
524
124
  }
525
- const debug = (message)=>{
526
- if (isDebug()) {
527
- const result = typeof message === 'string' ? message : message();
528
- const time = color.gray(`${getTime()}`);
529
- logger.debug(`${time} ${result}`);
530
- }
531
- };
532
-
533
-
534
- ;// CONCATENATED MODULE: ./src/cli/prepare.ts
535
-
125
+ // setup the logger level
126
+ if (process.env.DEBUG) index_js_namespaceObject.logger.level = 'verbose';
536
127
  function initNodeEnv() {
537
- if (false) {}
128
+ if (!process.env.NODE_ENV) {
129
+ const command = process.argv[2] ?? '';
130
+ process.env.NODE_ENV = [
131
+ 'build'
132
+ ].includes(command) ? 'production' : 'development';
133
+ }
538
134
  }
539
135
  function prepareCli() {
540
136
  initNodeEnv();
541
137
  // Print a blank line to keep the greet log nice.
542
138
  // Some package managers automatically output a blank line, some do not.
543
139
  const { npm_execpath } = process.env;
544
- if (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) {
545
- console.log();
546
- }
547
- dist_logger.greet(` ${`Rslib v${"0.0.4"}`}\n`);
140
+ if (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) console.log();
141
+ index_js_namespaceObject.logger.greet(` Rslib v0.0.6\n`);
548
142
  }
549
-
550
- ;// CONCATENATED MODULE: external "../compiled/commander/index.js"
551
-
552
143
  var commander_index_js_namespaceObject = __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__;
553
-
554
- ;// CONCATENATED MODULE: external "@rsbuild/core"
555
-
556
144
  var core_namespaceObject = __WEBPACK_EXTERNAL_MODULE__rsbuild_core__;
557
-
558
- ;// CONCATENATED MODULE: external "../compiled/fast-glob/index.js"
559
-
560
145
  var fast_glob_index_js_namespaceObject = __WEBPACK_EXTERNAL_MODULE__compiled_fast_glob_index_js__;
561
-
562
- ;// CONCATENATED MODULE: ./src/constant.ts
563
146
  const DEFAULT_CONFIG_NAME = 'rslib.config';
564
147
  const DEFAULT_EXTENSIONS = [
565
148
  '.js',
@@ -569,32 +152,28 @@ const DEFAULT_EXTENSIONS = [
569
152
  '.cjs',
570
153
  '.cts'
571
154
  ];
572
-
573
- ;// CONCATENATED MODULE: ./src/utils/extension.ts
574
-
155
+ const SWC_HELPERS = '@swc/helpers';
575
156
  const getDefaultExtension = (options)=>{
576
157
  const { format, pkgJson, autoExtension } = options;
577
158
  let jsExtension = '.js';
578
159
  let dtsExtension = '.d.ts';
579
- if (!autoExtension) {
580
- return {
581
- jsExtension,
582
- dtsExtension
583
- };
584
- }
160
+ if (!autoExtension) return {
161
+ jsExtension,
162
+ dtsExtension
163
+ };
585
164
  if (!pkgJson) {
586
- dist_logger.warn('autoExtension configuration will not be applied due to read package.json failed');
165
+ index_js_namespaceObject.logger.warn('autoExtension configuration will not be applied due to read package.json failed');
587
166
  return {
588
167
  jsExtension,
589
168
  dtsExtension
590
169
  };
591
170
  }
592
- const isModule = pkgJson.type === 'module';
593
- if (isModule && format === 'cjs') {
171
+ const isModule = 'module' === pkgJson.type;
172
+ if (isModule && 'cjs' === format) {
594
173
  jsExtension = '.cjs';
595
174
  dtsExtension = '.d.cts';
596
175
  }
597
- if (!isModule && format === 'esm') {
176
+ if (!isModule && 'esm' === format) {
598
177
  jsExtension = '.mjs';
599
178
  dtsExtension = '.d.mts';
600
179
  }
@@ -604,8 +183,30 @@ const getDefaultExtension = (options)=>{
604
183
  isModule
605
184
  };
606
185
  };
607
-
608
- ;// CONCATENATED MODULE: ./src/utils/syntax.ts
186
+ const LATEST_TARGET_VERSIONS = {
187
+ node: [
188
+ 'last 1 node versions'
189
+ ],
190
+ web: [
191
+ 'last 1 Chrome versions',
192
+ 'last 1 Firefox versions',
193
+ 'last 1 Edge versions',
194
+ 'last 1 Safari versions',
195
+ 'last 1 ios_saf versions',
196
+ 'not dead'
197
+ ],
198
+ get 'web-worker' () {
199
+ return LATEST_TARGET_VERSIONS.web;
200
+ }
201
+ };
202
+ const calcEsnextBrowserslistByTarget = (target)=>{
203
+ if (!target) return [
204
+ ...LATEST_TARGET_VERSIONS.node,
205
+ ...LATEST_TARGET_VERSIONS.web
206
+ ];
207
+ if ('node' === target) return LATEST_TARGET_VERSIONS.node;
208
+ return LATEST_TARGET_VERSIONS.web;
209
+ };
609
210
  /**
610
211
  * The esX to browserslist mapping is transformed from esbuild:
611
212
  * https://github.com/evanw/esbuild/blob/main/internal/compat/js_table.go
@@ -710,8 +311,8 @@ const getDefaultExtension = (options)=>{
710
311
  Opera: '62.0.0',
711
312
  Safari: '13.1.0'
712
313
  },
713
- es2024: {},
714
- esnext: {},
314
+ es2024: calcEsnextBrowserslistByTarget,
315
+ esnext: calcEsnextBrowserslistByTarget,
715
316
  es5: {
716
317
  Chrome: '5.0.0',
717
318
  Edge: '12.0.0',
@@ -723,84 +324,776 @@ const getDefaultExtension = (options)=>{
723
324
  Safari: '3.1.0'
724
325
  }
725
326
  };
726
- const transformSyntaxToBrowserslist = (syntax)=>{
727
- // only single esX is allowed
728
- if (typeof syntax === 'string' && syntax.toLowerCase().startsWith('es')) {
729
- if (syntax.toLowerCase() in ESX_TO_BROWSERSLIST) {
730
- return Object.entries(ESX_TO_BROWSERSLIST[syntax]).flatMap(([engine, version])=>{
731
- if (Array.isArray(version)) {
732
- return version;
327
+ function transformSyntaxToBrowserslist(syntax, target) {
328
+ const handleSyntaxItem = (syntaxItem)=>{
329
+ const normalizedSyntaxItem = syntaxItem.toLowerCase();
330
+ if (normalizedSyntaxItem.startsWith('es')) {
331
+ if (normalizedSyntaxItem in ESX_TO_BROWSERSLIST) {
332
+ const browserslistItem = ESX_TO_BROWSERSLIST[normalizedSyntaxItem];
333
+ if ('function' == typeof browserslistItem) return browserslistItem(target);
334
+ return Object.entries(browserslistItem).flatMap(([engine, version])=>{
335
+ if (Array.isArray(version)) return version;
336
+ return `${engine} >= ${version}`;
337
+ });
338
+ }
339
+ throw new Error(`Unsupported ES version: ${syntaxItem}`);
340
+ }
341
+ return [
342
+ syntaxItem
343
+ ];
344
+ };
345
+ if (Array.isArray(syntax)) return syntax.flatMap(handleSyntaxItem);
346
+ return handleSyntaxItem(syntax);
347
+ }
348
+ const POSIX_SEP_RE = new RegExp('\\' + external_node_path_namespaceObject["default"].posix.sep, 'g');
349
+ const NATIVE_SEP_RE = new RegExp('\\' + external_node_path_namespaceObject["default"].sep, 'g');
350
+ /** @type {Map<string,RegExp>}*/ const PATTERN_REGEX_CACHE = new Map();
351
+ const GLOB_ALL_PATTERN = "**/*";
352
+ const TS_EXTENSIONS = [
353
+ '.ts',
354
+ '.tsx',
355
+ '.mts',
356
+ '.cts'
357
+ ];
358
+ const JS_EXTENSIONS = [
359
+ '.js',
360
+ '.jsx',
361
+ '.mjs',
362
+ '.cjs'
363
+ ];
364
+ const TSJS_EXTENSIONS = TS_EXTENSIONS.concat(JS_EXTENSIONS);
365
+ const TS_EXTENSIONS_RE_GROUP = `\\.(?:${TS_EXTENSIONS.map((ext)=>ext.substring(1)).join('|')})`;
366
+ const TSJS_EXTENSIONS_RE_GROUP = `\\.(?:${TSJS_EXTENSIONS.map((ext)=>ext.substring(1)).join('|')})`;
367
+ const IS_POSIX = external_node_path_namespaceObject["default"].posix.sep === external_node_path_namespaceObject["default"].sep;
368
+ /**
369
+ * @template T
370
+ * @returns {{resolve:(result:T)=>void, reject:(error:any)=>void, promise: Promise<T>}}
371
+ */ function util_makePromise() {
372
+ let resolve, reject;
373
+ const promise = new Promise((res, rej)=>{
374
+ resolve = res;
375
+ reject = rej;
376
+ });
377
+ return {
378
+ promise,
379
+ resolve,
380
+ reject
381
+ };
382
+ }
383
+ /**
384
+ * @param {string} filename
385
+ * @param {import('./cache.js').TSConfckCache} [cache]
386
+ * @returns {Promise<string|void>}
387
+ */ async function util_resolveTSConfigJson(filename, cache) {
388
+ if ('.json' !== external_node_path_namespaceObject["default"].extname(filename)) return; // ignore files that are not json
389
+ const tsconfig = external_node_path_namespaceObject["default"].resolve(filename);
390
+ if (cache && (cache.hasParseResult(tsconfig) || cache.hasParseResult(filename))) return tsconfig;
391
+ return external_node_fs_namespaceObject.promises.stat(tsconfig).then((stat)=>{
392
+ if (stat.isFile() || stat.isFIFO()) return tsconfig;
393
+ throw new Error(`${filename} exists but is not a regular file.`);
394
+ });
395
+ }
396
+ /**
397
+ *
398
+ * @param {string} dir an absolute directory path
399
+ * @returns {boolean} if dir path includes a node_modules segment
400
+ */ const util_isInNodeModules = IS_POSIX ? (dir)=>dir.includes('/node_modules/') : (dir)=>dir.match(/[/\\]node_modules[/\\]/);
401
+ /**
402
+ * convert posix separator to native separator
403
+ *
404
+ * eg.
405
+ * windows: C:/foo/bar -> c:\foo\bar
406
+ * linux: /foo/bar -> /foo/bar
407
+ *
408
+ * @param {string} filename with posix separators
409
+ * @returns {string} filename with native separators
410
+ */ const posix2native = IS_POSIX ? (filename)=>filename : (filename)=>filename.replace(POSIX_SEP_RE, external_node_path_namespaceObject["default"].sep);
411
+ /**
412
+ * convert native separator to posix separator
413
+ *
414
+ * eg.
415
+ * windows: C:\foo\bar -> c:/foo/bar
416
+ * linux: /foo/bar -> /foo/bar
417
+ *
418
+ * @param {string} filename - filename with native separators
419
+ * @returns {string} filename with posix separators
420
+ */ const util_native2posix = IS_POSIX ? (filename)=>filename : (filename)=>filename.replace(NATIVE_SEP_RE, external_node_path_namespaceObject["default"].posix.sep);
421
+ /**
422
+ * converts params to native separator, resolves path and converts native back to posix
423
+ *
424
+ * needed on windows to handle posix paths in tsconfig
425
+ *
426
+ * @param dir {string|null} directory to resolve from
427
+ * @param filename {string} filename or pattern to resolve
428
+ * @returns string
429
+ */ const resolve2posix = IS_POSIX ? (dir, filename)=>dir ? external_node_path_namespaceObject["default"].resolve(dir, filename) : external_node_path_namespaceObject["default"].resolve(filename) : (dir, filename)=>util_native2posix(dir ? external_node_path_namespaceObject["default"].resolve(posix2native(dir), posix2native(filename)) : external_node_path_namespaceObject["default"].resolve(posix2native(filename)));
430
+ /**
431
+ *
432
+ * @param {import('./public.d.ts').TSConfckParseResult} result
433
+ * @param {import('./public.d.ts').TSConfckParseOptions} [options]
434
+ * @returns {string[]}
435
+ */ function util_resolveReferencedTSConfigFiles(result, options) {
436
+ const dir = external_node_path_namespaceObject["default"].dirname(result.tsconfigFile);
437
+ return result.tsconfig.references.map((ref)=>{
438
+ const refPath = ref.path.endsWith('.json') ? ref.path : external_node_path_namespaceObject["default"].join(ref.path, options?.configName ?? 'tsconfig.json');
439
+ return resolve2posix(dir, refPath);
440
+ });
441
+ }
442
+ /**
443
+ * @param {string} filename
444
+ * @param {import('./public.d.ts').TSConfckParseResult} result
445
+ * @returns {import('./public.d.ts').TSConfckParseResult}
446
+ */ function util_resolveSolutionTSConfig(filename, result) {
447
+ const allowJs = result.tsconfig.compilerOptions?.allowJs;
448
+ const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
449
+ if (result.referenced && extensions.some((ext)=>filename.endsWith(ext)) && !util_isIncluded(filename, result)) {
450
+ const solutionTSConfig = result.referenced.find((referenced)=>util_isIncluded(filename, referenced));
451
+ if (solutionTSConfig) return solutionTSConfig;
452
+ }
453
+ return result;
454
+ }
455
+ /**
456
+ *
457
+ * @param {string} filename
458
+ * @param {import('./public.d.ts').TSConfckParseResult} result
459
+ * @returns {boolean}
460
+ */ function util_isIncluded(filename, result) {
461
+ const dir = util_native2posix(external_node_path_namespaceObject["default"].dirname(result.tsconfigFile));
462
+ const files = (result.tsconfig.files || []).map((file)=>resolve2posix(dir, file));
463
+ const absoluteFilename = resolve2posix(null, filename);
464
+ if (files.includes(filename)) return true;
465
+ const allowJs = result.tsconfig.compilerOptions?.allowJs;
466
+ const isIncluded = isGlobMatch(absoluteFilename, dir, result.tsconfig.include || (result.tsconfig.files ? [] : [
467
+ GLOB_ALL_PATTERN
468
+ ]), allowJs);
469
+ if (isIncluded) {
470
+ const isExcluded = isGlobMatch(absoluteFilename, dir, result.tsconfig.exclude || [], allowJs);
471
+ return !isExcluded;
472
+ }
473
+ return false;
474
+ }
475
+ /**
476
+ * test filenames agains glob patterns in tsconfig
477
+ *
478
+ * @param filename {string} posix style abolute path to filename to test
479
+ * @param dir {string} posix style absolute path to directory of tsconfig containing patterns
480
+ * @param patterns {string[]} glob patterns to match against
481
+ * @param allowJs {boolean} allowJs setting in tsconfig to include js extensions in checks
482
+ * @returns {boolean} true when at least one pattern matches filename
483
+ */ function isGlobMatch(filename, dir, patterns, allowJs) {
484
+ const extensions = allowJs ? TSJS_EXTENSIONS : TS_EXTENSIONS;
485
+ return patterns.some((pattern)=>{
486
+ // filename must end with part of pattern that comes after last wildcard
487
+ let lastWildcardIndex = pattern.length;
488
+ let hasWildcard = false;
489
+ for(let i = pattern.length - 1; i > -1; i--)if ('*' === pattern[i] || '?' === pattern[i]) {
490
+ lastWildcardIndex = i;
491
+ hasWildcard = true;
492
+ break;
493
+ }
494
+ // if pattern does not end with wildcard, filename must end with pattern after last wildcard
495
+ if (lastWildcardIndex < pattern.length - 1 && !filename.endsWith(pattern.slice(lastWildcardIndex + 1))) return false;
496
+ // if pattern ends with *, filename must end with a default extension
497
+ if (pattern.endsWith('*') && !extensions.some((ext)=>filename.endsWith(ext))) return false;
498
+ // for **/* , filename must start with the dir
499
+ if (pattern === GLOB_ALL_PATTERN) return filename.startsWith(`${dir}/`);
500
+ const resolvedPattern = resolve2posix(dir, pattern);
501
+ // filename must start with part of pattern that comes before first wildcard
502
+ let firstWildcardIndex = -1;
503
+ for(let i = 0; i < resolvedPattern.length; i++)if ('*' === resolvedPattern[i] || '?' === resolvedPattern[i]) {
504
+ firstWildcardIndex = i;
505
+ hasWildcard = true;
506
+ break;
507
+ }
508
+ if (firstWildcardIndex > 1 && !filename.startsWith(resolvedPattern.slice(0, firstWildcardIndex - 1))) return false;
509
+ // if no wildcard in pattern, filename must be equal to resolved pattern
510
+ if (!hasWildcard) return filename === resolvedPattern;
511
+ // complex pattern, use regex to check it
512
+ if (PATTERN_REGEX_CACHE.has(resolvedPattern)) return PATTERN_REGEX_CACHE.get(resolvedPattern).test(filename);
513
+ const regex = pattern2regex(resolvedPattern, allowJs);
514
+ PATTERN_REGEX_CACHE.set(resolvedPattern, regex);
515
+ return regex.test(filename);
516
+ });
517
+ }
518
+ /**
519
+ * @param {string} resolvedPattern
520
+ * @param {boolean} allowJs
521
+ * @returns {RegExp}
522
+ */ function pattern2regex(resolvedPattern, allowJs) {
523
+ let regexStr = '^';
524
+ for(let i = 0; i < resolvedPattern.length; i++){
525
+ const char = resolvedPattern[i];
526
+ if ('?' === char) {
527
+ regexStr += '[^\\/]';
528
+ continue;
529
+ }
530
+ if ('*' === char) {
531
+ if ('*' === resolvedPattern[i + 1] && '/' === resolvedPattern[i + 2]) {
532
+ i += 2;
533
+ regexStr += '(?:[^\\/]*\\/)*'; // zero or more path segments
534
+ continue;
535
+ }
536
+ regexStr += '[^\\/]*';
537
+ continue;
538
+ }
539
+ if ('/.+^${}()|[]\\'.includes(char)) regexStr += "\\";
540
+ regexStr += char;
541
+ }
542
+ // add known file endings if pattern ends on *
543
+ if (resolvedPattern.endsWith('*')) regexStr += allowJs ? TSJS_EXTENSIONS_RE_GROUP : TS_EXTENSIONS_RE_GROUP;
544
+ regexStr += '$';
545
+ return new RegExp(regexStr);
546
+ }
547
+ /**
548
+ * replace tokens like ${configDir}
549
+ * @param {any} tsconfig
550
+ * @param {string} configDir
551
+ * @returns {any}
552
+ */ function util_replaceTokens(tsconfig, configDir) {
553
+ return JSON.parse(JSON.stringify(tsconfig)// replace ${configDir}
554
+ .replaceAll(/"\${configDir}/g, `"${util_native2posix(configDir)}`));
555
+ }
556
+ /**
557
+ * find the closest tsconfig.json file
558
+ *
559
+ * @param {string} filename - path to file to find tsconfig for (absolute or relative to cwd)
560
+ * @param {import('./public.d.ts').TSConfckFindOptions} [options] - options
561
+ * @returns {Promise<string|null>} absolute path to closest tsconfig.json or null if not found
562
+ */ async function find(filename, options) {
563
+ let dir = external_node_path_namespaceObject["default"].dirname(external_node_path_namespaceObject["default"].resolve(filename));
564
+ if (options?.ignoreNodeModules && util_isInNodeModules(dir)) return null;
565
+ const cache = options?.cache;
566
+ const configName = options?.configName ?? 'tsconfig.json';
567
+ if (cache?.hasConfigPath(dir, configName)) return cache.getConfigPath(dir, configName);
568
+ const { promise, resolve, reject } = util_makePromise();
569
+ if (options?.root && !external_node_path_namespaceObject["default"].isAbsolute(options.root)) options.root = external_node_path_namespaceObject["default"].resolve(options.root);
570
+ findUp(dir, {
571
+ promise,
572
+ resolve,
573
+ reject
574
+ }, options);
575
+ return promise;
576
+ }
577
+ /**
578
+ *
579
+ * @param {string} dir
580
+ * @param {{promise:Promise<string|null>,resolve:(result:string|null)=>void,reject:(err:any)=>void}} madePromise
581
+ * @param {import('./public.d.ts').TSConfckFindOptions} [options] - options
582
+ */ function findUp(dir, { resolve, reject, promise }, options) {
583
+ const { cache, root, configName } = options ?? {};
584
+ if (cache) {
585
+ if (cache.hasConfigPath(dir, configName)) {
586
+ let cached;
587
+ try {
588
+ cached = cache.getConfigPath(dir, configName);
589
+ } catch (e) {
590
+ reject(e);
591
+ return;
592
+ }
593
+ if (cached?.then) cached.then(resolve).catch(reject);
594
+ else resolve(cached);
595
+ } else cache.setConfigPath(dir, promise, configName);
596
+ }
597
+ const tsconfig = external_node_path_namespaceObject["default"].join(dir, options?.configName ?? 'tsconfig.json');
598
+ external_node_fs_namespaceObject["default"].stat(tsconfig, (err, stats)=>{
599
+ if (stats && (stats.isFile() || stats.isFIFO())) resolve(tsconfig);
600
+ else if (err?.code !== 'ENOENT') reject(err);
601
+ else {
602
+ let parent;
603
+ if (root === dir || (parent = external_node_path_namespaceObject["default"].dirname(dir)) === dir) resolve(null);
604
+ else findUp(parent, {
605
+ promise,
606
+ resolve,
607
+ reject
608
+ }, options);
609
+ }
610
+ });
611
+ }
612
+ /**
613
+ * @typedef WalkState
614
+ * @interface
615
+ * @property {string[]} files - files
616
+ * @property {number} calls - number of ongoing calls
617
+ * @property {(dir: string)=>boolean} skip - function to skip dirs
618
+ * @property {boolean} err - error flag
619
+ * @property {string[]} configNames - config file names
620
+ */ external_node_path_namespaceObject["default"].sep;
621
+ /*
622
+ this file contains code from strip-bom and strip-json-comments by Sindre Sorhus
623
+ https://github.com/sindresorhus/strip-json-comments/blob/v4.0.0/index.js
624
+ https://github.com/sindresorhus/strip-bom/blob/v5.0.0/index.js
625
+ licensed under MIT, see ../LICENSE
626
+ */ /**
627
+ * convert content of tsconfig.json to regular json
628
+ *
629
+ * @param {string} tsconfigJson - content of tsconfig.json
630
+ * @returns {string} content as regular json, comments and dangling commas have been replaced with whitespace
631
+ */ function toJson(tsconfigJson) {
632
+ const stripped = stripDanglingComma(stripJsonComments(stripBom(tsconfigJson)));
633
+ if ('' === stripped.trim()) // only whitespace left after stripping, return empty object so that JSON.parse still works
634
+ return '{}';
635
+ return stripped;
636
+ }
637
+ /**
638
+ * replace dangling commas from pseudo-json string with single space
639
+ * implementation heavily inspired by strip-json-comments
640
+ *
641
+ * @param {string} pseudoJson
642
+ * @returns {string}
643
+ */ function stripDanglingComma(pseudoJson) {
644
+ let insideString = false;
645
+ let offset = 0;
646
+ let result = '';
647
+ let danglingCommaPos = null;
648
+ for(let i = 0; i < pseudoJson.length; i++){
649
+ const currentCharacter = pseudoJson[i];
650
+ if ('"' === currentCharacter) {
651
+ const escaped = isEscaped(pseudoJson, i);
652
+ if (!escaped) insideString = !insideString;
653
+ }
654
+ if (insideString) {
655
+ danglingCommaPos = null;
656
+ continue;
657
+ }
658
+ if (',' === currentCharacter) {
659
+ danglingCommaPos = i;
660
+ continue;
661
+ }
662
+ if (danglingCommaPos) {
663
+ if ('}' === currentCharacter || ']' === currentCharacter) {
664
+ result += pseudoJson.slice(offset, danglingCommaPos) + ' ';
665
+ offset = danglingCommaPos + 1;
666
+ danglingCommaPos = null;
667
+ } else if (!currentCharacter.match(/\s/)) danglingCommaPos = null;
668
+ }
669
+ }
670
+ return result + pseudoJson.substring(offset);
671
+ }
672
+ // start strip-json-comments
673
+ /**
674
+ *
675
+ * @param {string} jsonString
676
+ * @param {number} quotePosition
677
+ * @returns {boolean}
678
+ */ function isEscaped(jsonString, quotePosition) {
679
+ let index = quotePosition - 1;
680
+ let backslashCount = 0;
681
+ while('\\' === jsonString[index]){
682
+ index -= 1;
683
+ backslashCount += 1;
684
+ }
685
+ return Boolean(backslashCount % 2);
686
+ }
687
+ /**
688
+ *
689
+ * @param {string} string
690
+ * @param {number?} start
691
+ * @param {number?} end
692
+ */ function strip(string, start, end) {
693
+ return string.slice(start, end).replace(/\S/g, ' ');
694
+ }
695
+ const singleComment = Symbol('singleComment');
696
+ const multiComment = Symbol('multiComment');
697
+ /**
698
+ * @param {string} jsonString
699
+ * @returns {string}
700
+ */ function stripJsonComments(jsonString) {
701
+ let isInsideString = false;
702
+ /** @type {false | symbol} */ let isInsideComment = false;
703
+ let offset = 0;
704
+ let result = '';
705
+ for(let index = 0; index < jsonString.length; index++){
706
+ const currentCharacter = jsonString[index];
707
+ const nextCharacter = jsonString[index + 1];
708
+ if (!isInsideComment && '"' === currentCharacter) {
709
+ const escaped = isEscaped(jsonString, index);
710
+ if (!escaped) isInsideString = !isInsideString;
711
+ }
712
+ if (!isInsideString) if (isInsideComment || currentCharacter + nextCharacter !== '//') {
713
+ if (isInsideComment === singleComment && currentCharacter + nextCharacter === '\r\n') {
714
+ index++;
715
+ isInsideComment = false;
716
+ result += strip(jsonString, offset, index);
717
+ offset = index;
718
+ } else if (isInsideComment === singleComment && '\n' === currentCharacter) {
719
+ isInsideComment = false;
720
+ result += strip(jsonString, offset, index);
721
+ offset = index;
722
+ } else if (isInsideComment || currentCharacter + nextCharacter !== '/*') {
723
+ if (isInsideComment === multiComment && currentCharacter + nextCharacter === '*/') {
724
+ index++;
725
+ isInsideComment = false;
726
+ result += strip(jsonString, offset, index + 1);
727
+ offset = index + 1;
733
728
  }
734
- return `${engine} >= ${version}`;
735
- });
729
+ } else {
730
+ result += jsonString.slice(offset, index);
731
+ offset = index;
732
+ isInsideComment = multiComment;
733
+ index++;
734
+ }
735
+ } else {
736
+ result += jsonString.slice(offset, index);
737
+ offset = index;
738
+ isInsideComment = singleComment;
739
+ index++;
740
+ }
741
+ }
742
+ return result + (isInsideComment ? strip(jsonString.slice(offset)) : jsonString.slice(offset));
743
+ }
744
+ // end strip-json-comments
745
+ // start strip-bom
746
+ /**
747
+ * @param {string} string
748
+ * @returns {string}
749
+ */ function stripBom(string) {
750
+ // Catches EFBBBF (UTF-8 BOM) because the buffer-to-string
751
+ // conversion translates it to FEFF (UTF-16 BOM).
752
+ if (0xfeff === string.charCodeAt(0)) return string.slice(1);
753
+ return string;
754
+ }
755
+ var external_module_namespaceObject = __WEBPACK_EXTERNAL_MODULE_module__;
756
+ const not_found_result = {
757
+ tsconfigFile: null,
758
+ tsconfig: {}
759
+ };
760
+ /**
761
+ * parse the closest tsconfig.json file
762
+ *
763
+ * @param {string} filename - path to a tsconfig .json or a source file or directory (absolute or relative to cwd)
764
+ * @param {import('./public.d.ts').TSConfckParseOptions} [options] - options
765
+ * @returns {Promise<import('./public.d.ts').TSConfckParseResult>}
766
+ * @throws {TSConfckParseError}
767
+ */ async function parse(filename, options) {
768
+ /** @type {import('./cache.js').TSConfckCache} */ const cache = options?.cache;
769
+ if (cache?.hasParseResult(filename)) return getParsedDeep(filename, cache, options);
770
+ const { resolve, reject, /** @type {Promise<import('./public.d.ts').TSConfckParseResult>}*/ promise } = util_makePromise();
771
+ cache?.setParseResult(filename, promise, true);
772
+ try {
773
+ let tsconfigFile = await util_resolveTSConfigJson(filename, cache) || await find(filename, options);
774
+ if (!tsconfigFile) {
775
+ resolve(not_found_result);
776
+ return promise;
777
+ }
778
+ let result;
779
+ if (filename !== tsconfigFile && cache?.hasParseResult(tsconfigFile)) result = await getParsedDeep(tsconfigFile, cache, options);
780
+ else {
781
+ result = await parseFile(tsconfigFile, cache, filename === tsconfigFile);
782
+ await Promise.all([
783
+ parseExtends(result, cache),
784
+ parseReferences(result, options)
785
+ ]);
786
+ }
787
+ result.tsconfig = util_replaceTokens(result.tsconfig, external_node_path_namespaceObject["default"].dirname(tsconfigFile));
788
+ resolve(util_resolveSolutionTSConfig(filename, result));
789
+ } catch (e) {
790
+ reject(e);
791
+ }
792
+ return promise;
793
+ }
794
+ /**
795
+ * ensure extends and references are parsed
796
+ *
797
+ * @param {string} filename - cached file
798
+ * @param {import('./cache.js').TSConfckCache} cache - cache
799
+ * @param {import('./public.d.ts').TSConfckParseOptions} options - options
800
+ */ async function getParsedDeep(filename, cache, options) {
801
+ const result = await cache.getParseResult(filename);
802
+ if (result.tsconfig.extends && !result.extended || result.tsconfig.references && !result.referenced) {
803
+ const promise = Promise.all([
804
+ parseExtends(result, cache),
805
+ parseReferences(result, options)
806
+ ]).then(()=>result);
807
+ cache.setParseResult(filename, promise, true);
808
+ return promise;
809
+ }
810
+ return result;
811
+ }
812
+ /**
813
+ *
814
+ * @param {string} tsconfigFile - path to tsconfig file
815
+ * @param {import('./cache.js').TSConfckCache} [cache] - cache
816
+ * @param {boolean} [skipCache] - skip cache
817
+ * @returns {Promise<import('./public.d.ts').TSConfckParseResult>}
818
+ */ async function parseFile(tsconfigFile, cache, skipCache) {
819
+ if (!skipCache && cache?.hasParseResult(tsconfigFile) && !cache.getParseResult(tsconfigFile)._isRootFile_) return cache.getParseResult(tsconfigFile);
820
+ const promise = external_node_fs_namespaceObject.promises.readFile(tsconfigFile, 'utf-8').then(toJson).then((json)=>{
821
+ const parsed = JSON.parse(json);
822
+ applyDefaults(parsed, tsconfigFile);
823
+ return {
824
+ tsconfigFile,
825
+ tsconfig: normalizeTSConfig(parsed, external_node_path_namespaceObject["default"].dirname(tsconfigFile))
826
+ };
827
+ }).catch((e)=>{
828
+ throw new TSConfckParseError(`parsing ${tsconfigFile} failed: ${e}`, 'PARSE_FILE', tsconfigFile, e);
829
+ });
830
+ if (!skipCache && (!cache?.hasParseResult(tsconfigFile) || !cache.getParseResult(tsconfigFile)._isRootFile_)) cache?.setParseResult(tsconfigFile, promise);
831
+ return promise;
832
+ }
833
+ /**
834
+ * normalize to match the output of ts.parseJsonConfigFileContent
835
+ *
836
+ * @param {any} tsconfig - typescript tsconfig output
837
+ * @param {string} dir - directory
838
+ */ function normalizeTSConfig(tsconfig, dir) {
839
+ // set baseUrl to absolute path
840
+ const baseUrl = tsconfig.compilerOptions?.baseUrl;
841
+ if (baseUrl && !baseUrl.startsWith('${') && !external_node_path_namespaceObject["default"].isAbsolute(baseUrl)) tsconfig.compilerOptions.baseUrl = resolve2posix(dir, baseUrl);
842
+ return tsconfig;
843
+ }
844
+ /**
845
+ *
846
+ * @param {import('./public.d.ts').TSConfckParseResult} result
847
+ * @param {import('./public.d.ts').TSConfckParseOptions} [options]
848
+ * @returns {Promise<void>}
849
+ */ async function parseReferences(result, options) {
850
+ if (!result.tsconfig.references) return;
851
+ const referencedFiles = util_resolveReferencedTSConfigFiles(result, options);
852
+ const referenced = await Promise.all(referencedFiles.map((file)=>parseFile(file, options?.cache)));
853
+ await Promise.all(referenced.map((ref)=>parseExtends(ref, options?.cache)));
854
+ referenced.forEach((ref)=>{
855
+ ref.solution = result;
856
+ });
857
+ result.referenced = referenced;
858
+ }
859
+ /**
860
+ * @param {import('./public.d.ts').TSConfckParseResult} result
861
+ * @param {import('./cache.js').TSConfckCache}[cache]
862
+ * @returns {Promise<void>}
863
+ */ async function parseExtends(result, cache) {
864
+ if (!result.tsconfig.extends) return;
865
+ // use result as first element in extended
866
+ // but dereference tsconfig so that mergeExtended can modify the original without affecting extended[0]
867
+ /** @type {import('./public.d.ts').TSConfckParseResult[]} */ const extended = [
868
+ {
869
+ tsconfigFile: result.tsconfigFile,
870
+ tsconfig: JSON.parse(JSON.stringify(result.tsconfig))
871
+ }
872
+ ];
873
+ // flatten extends graph into extended
874
+ let pos = 0;
875
+ /** @type {string[]} */ const extendsPath = [];
876
+ let currentBranchDepth = 0;
877
+ while(pos < extended.length){
878
+ const extending = extended[pos];
879
+ extendsPath.push(extending.tsconfigFile);
880
+ if (extending.tsconfig.extends) {
881
+ // keep following this branch
882
+ currentBranchDepth += 1;
883
+ /** @type {string[]} */ let resolvedExtends;
884
+ // reverse because typescript 5.0 treats ['a','b','c'] as c extends b extends a
885
+ resolvedExtends = Array.isArray(extending.tsconfig.extends) ? extending.tsconfig.extends.reverse().map((ex)=>resolveExtends(ex, extending.tsconfigFile)) : [
886
+ resolveExtends(extending.tsconfig.extends, extending.tsconfigFile)
887
+ ];
888
+ const circularExtends = resolvedExtends.find((tsconfigFile)=>extendsPath.includes(tsconfigFile));
889
+ if (circularExtends) {
890
+ const circle = extendsPath.concat([
891
+ circularExtends
892
+ ]).join(' -> ');
893
+ throw new TSConfckParseError(`Circular dependency in "extends": ${circle}`, 'EXTENDS_CIRCULAR', result.tsconfigFile);
894
+ }
895
+ // add new extends to the list directly after current
896
+ extended.splice(pos + 1, 0, ...await Promise.all(resolvedExtends.map((file)=>parseFile(file, cache))));
897
+ } else {
898
+ // reached a leaf, backtrack to the last branching point and continue
899
+ extendsPath.splice(-currentBranchDepth);
900
+ currentBranchDepth = 0;
901
+ }
902
+ pos += 1;
903
+ }
904
+ result.extended = extended;
905
+ // skip first as it is the original config
906
+ for (const ext of result.extended.slice(1))extendTSConfig(result, ext);
907
+ }
908
+ /**
909
+ *
910
+ * @param {string} extended
911
+ * @param {string} from
912
+ * @returns {string}
913
+ */ function resolveExtends(extended, from) {
914
+ if ('..' === extended) // see #149
915
+ extended = '../tsconfig.json';
916
+ const req = (0, external_module_namespaceObject.createRequire)(from);
917
+ let error;
918
+ try {
919
+ return req.resolve(extended);
920
+ } catch (e) {
921
+ error = e;
922
+ }
923
+ if ('.' !== extended[0] && !external_node_path_namespaceObject["default"].isAbsolute(extended)) try {
924
+ return req.resolve(`${extended}/tsconfig.json`);
925
+ } catch (e) {
926
+ error = e;
927
+ }
928
+ throw new TSConfckParseError(`failed to resolve "extends":"${extended}" in ${from}`, 'EXTENDS_RESOLVE', from, error);
929
+ }
930
+ // references, extends and custom keys are not carried over
931
+ const EXTENDABLE_KEYS = [
932
+ 'compilerOptions',
933
+ 'files',
934
+ 'include',
935
+ 'exclude',
936
+ 'watchOptions',
937
+ 'compileOnSave',
938
+ 'typeAcquisition',
939
+ 'buildOptions'
940
+ ];
941
+ /**
942
+ *
943
+ * @param {import('./public.d.ts').TSConfckParseResult} extending
944
+ * @param {import('./public.d.ts').TSConfckParseResult} extended
945
+ * @returns void
946
+ */ function extendTSConfig(extending, extended) {
947
+ const extendingConfig = extending.tsconfig;
948
+ const extendedConfig = extended.tsconfig;
949
+ const relativePath = util_native2posix(external_node_path_namespaceObject["default"].relative(external_node_path_namespaceObject["default"].dirname(extending.tsconfigFile), external_node_path_namespaceObject["default"].dirname(extended.tsconfigFile)));
950
+ for (const key of Object.keys(extendedConfig).filter((key)=>EXTENDABLE_KEYS.includes(key)))if ('compilerOptions' === key) {
951
+ if (!extendingConfig.compilerOptions) extendingConfig.compilerOptions = {};
952
+ for (const option of Object.keys(extendedConfig.compilerOptions)){
953
+ if (!Object.prototype.hasOwnProperty.call(extendingConfig.compilerOptions, option)) extendingConfig.compilerOptions[option] = rebaseRelative(option, extendedConfig.compilerOptions[option], relativePath);
736
954
  }
737
- throw new Error(`Unsupported ES version: ${syntax}`);
955
+ } else if (void 0 === extendingConfig[key]) {
956
+ if ('watchOptions' === key) {
957
+ extendingConfig.watchOptions = {};
958
+ for (const option of Object.keys(extendedConfig.watchOptions))extendingConfig.watchOptions[option] = rebaseRelative(option, extendedConfig.watchOptions[option], relativePath);
959
+ } else extendingConfig[key] = rebaseRelative(key, extendedConfig[key], relativePath);
738
960
  }
739
- // inline browserslist query
740
- if (Array.isArray(syntax)) {
741
- return syntax;
961
+ }
962
+ const REBASE_KEYS = [
963
+ // root
964
+ 'files',
965
+ 'include',
966
+ 'exclude',
967
+ // compilerOptions
968
+ 'baseUrl',
969
+ 'rootDir',
970
+ 'rootDirs',
971
+ 'typeRoots',
972
+ 'outDir',
973
+ 'outFile',
974
+ 'declarationDir',
975
+ // watchOptions
976
+ 'excludeDirectories',
977
+ 'excludeFiles'
978
+ ];
979
+ /** @typedef {string | string[]} PathValue */ /**
980
+ *
981
+ * @param {string} key
982
+ * @param {PathValue} value
983
+ * @param {string} prependPath
984
+ * @returns {PathValue}
985
+ */ function rebaseRelative(key, value, prependPath) {
986
+ if (!REBASE_KEYS.includes(key)) return value;
987
+ if (Array.isArray(value)) return value.map((x)=>rebasePath(x, prependPath));
988
+ return rebasePath(value, prependPath);
989
+ }
990
+ /**
991
+ *
992
+ * @param {string} value
993
+ * @param {string} prependPath
994
+ * @returns {string}
995
+ */ function rebasePath(value, prependPath) {
996
+ if (external_node_path_namespaceObject["default"].isAbsolute(value) || value.startsWith('${configDir}')) return value;
997
+ // relative paths use posix syntax in tsconfig
998
+ return external_node_path_namespaceObject["default"].posix.normalize(external_node_path_namespaceObject["default"].posix.join(prependPath, value));
999
+ }
1000
+ class TSConfckParseError extends Error {
1001
+ /**
1002
+ * error code
1003
+ * @type {string}
1004
+ */ code;
1005
+ /**
1006
+ * error cause
1007
+ * @type { Error | undefined}
1008
+ */ cause;
1009
+ /**
1010
+ * absolute path of tsconfig file where the error happened
1011
+ * @type {string}
1012
+ */ tsconfigFile;
1013
+ /**
1014
+ *
1015
+ * @param {string} message - error message
1016
+ * @param {string} code - error code
1017
+ * @param {string} tsconfigFile - path to tsconfig file
1018
+ * @param {Error?} cause - cause of this error
1019
+ */ constructor(message, code, tsconfigFile, cause){
1020
+ super(message);
1021
+ // Set the prototype explicitly.
1022
+ Object.setPrototypeOf(this, TSConfckParseError.prototype);
1023
+ this.name = TSConfckParseError.name;
1024
+ this.code = code;
1025
+ this.cause = cause;
1026
+ this.tsconfigFile = tsconfigFile;
742
1027
  }
743
- throw new Error(`Unsupported syntax: ${syntax}`);
1028
+ }
1029
+ /**
1030
+ *
1031
+ * @param {any} tsconfig
1032
+ * @param {string} tsconfigFile
1033
+ */ function applyDefaults(tsconfig, tsconfigFile) {
1034
+ if (isJSConfig(tsconfigFile)) tsconfig.compilerOptions = {
1035
+ ...DEFAULT_JSCONFIG_COMPILER_OPTIONS,
1036
+ ...tsconfig.compilerOptions
1037
+ };
1038
+ }
1039
+ const DEFAULT_JSCONFIG_COMPILER_OPTIONS = {
1040
+ allowJs: true,
1041
+ maxNodeModuleJsDepth: 2,
1042
+ allowSyntheticDefaultImports: true,
1043
+ skipLibCheck: true,
1044
+ noEmit: true
744
1045
  };
745
-
746
- ;// CONCATENATED MODULE: ./src/config.ts
747
-
748
-
749
-
750
-
751
-
752
-
753
-
754
-
755
-
1046
+ /**
1047
+ * @param {string} configFileName
1048
+ */ function isJSConfig(configFileName) {
1049
+ return 'jsconfig.json' === external_node_path_namespaceObject["default"].basename(configFileName);
1050
+ }
1051
+ async function loadTsconfig(root, tsconfigPath = 'tsconfig.json') {
1052
+ const tsconfigFileName = await find((0, external_node_path_namespaceObject.join)(root, tsconfigPath), {
1053
+ root,
1054
+ configName: (0, external_node_path_namespaceObject.basename)(tsconfigPath)
1055
+ });
1056
+ if (tsconfigFileName) {
1057
+ const { tsconfig } = await parse(tsconfigFileName);
1058
+ return tsconfig;
1059
+ }
1060
+ return {};
1061
+ }
756
1062
  /**
757
1063
  * This function helps you to autocomplete configuration types.
758
1064
  * It accepts a Rslib config object, or a function that returns a config.
759
1065
  */ function defineConfig(config) {
760
1066
  return config;
761
1067
  }
762
- const findConfig = (basePath)=>{
763
- return DEFAULT_EXTENSIONS.map((ext)=>basePath + ext).find(external_node_fs_namespaceObject["default"].existsSync);
764
- };
1068
+ const findConfig = (basePath)=>DEFAULT_EXTENSIONS.map((ext)=>basePath + ext).find(external_node_fs_namespaceObject["default"].existsSync);
765
1069
  const resolveConfigPath = (root, customConfig)=>{
766
1070
  if (customConfig) {
767
- const customConfigPath = (0,external_node_path_namespaceObject.isAbsolute)(customConfig) ? customConfig : (0,external_node_path_namespaceObject.join)(root, customConfig);
768
- if (external_node_fs_namespaceObject["default"].existsSync(customConfigPath)) {
769
- return customConfigPath;
770
- }
771
- dist_logger.warn(`Cannot find config file: ${index_js_namespaceObject["default"].dim(customConfigPath)}\n`);
772
- }
773
- const configFilePath = findConfig((0,external_node_path_namespaceObject.join)(root, DEFAULT_CONFIG_NAME));
774
- if (configFilePath) {
775
- return configFilePath;
1071
+ const customConfigPath = (0, external_node_path_namespaceObject.isAbsolute)(customConfig) ? customConfig : (0, external_node_path_namespaceObject.join)(root, customConfig);
1072
+ if (external_node_fs_namespaceObject["default"].existsSync(customConfigPath)) return customConfigPath;
1073
+ index_js_namespaceObject.logger.warn(`Cannot find config file: ${picocolors_index_js_namespaceObject["default"].dim(customConfigPath)}\n`);
776
1074
  }
1075
+ const configFilePath = findConfig((0, external_node_path_namespaceObject.join)(root, DEFAULT_CONFIG_NAME));
1076
+ if (configFilePath) return configFilePath;
777
1077
  throw new Error(`${DEFAULT_CONFIG_NAME} not found in ${root}`);
778
1078
  };
779
1079
  async function loadConfig({ cwd = process.cwd(), path, envMode }) {
780
1080
  const configFilePath = resolveConfigPath(cwd, path);
781
- const { content } = await (0,core_namespaceObject.loadConfig)({
782
- cwd: (0,external_node_path_namespaceObject.dirname)(configFilePath),
1081
+ const { content } = await (0, core_namespaceObject.loadConfig)({
1082
+ cwd: (0, external_node_path_namespaceObject.dirname)(configFilePath),
783
1083
  path: configFilePath,
784
1084
  envMode
785
1085
  });
786
1086
  return content;
787
1087
  }
788
1088
  const composeExternalsWarnConfig = (format, ...externalsArray)=>{
789
- if (format !== 'esm') {
790
- return {};
791
- }
1089
+ if ('esm' !== format) return {};
792
1090
  const externals = [];
793
- for (const e of externalsArray.filter(Boolean)){
794
- if (Array.isArray(e)) {
795
- externals.push(...e);
796
- } else {
797
- // @ts-ignore
798
- externals.push(e);
799
- }
800
- }
1091
+ for (const e of externalsArray.filter(Boolean))if (Array.isArray(e)) externals.push(...e);
1092
+ else // @ts-ignore
1093
+ externals.push(e);
801
1094
  // Match logic is derived from https://github.com/webpack/webpack/blob/94aba382eccf3de1004d235045d4462918dfdbb7/lib/ExternalModuleFactoryPlugin.js#L166-L293.
802
1095
  const matchUserExternals = (externals, request, callback)=>{
803
- if (typeof externals === 'string') {
1096
+ if ('string' == typeof externals) {
804
1097
  if (externals === request) {
805
1098
  callback(true);
806
1099
  return;
@@ -821,9 +1114,7 @@ const composeExternalsWarnConfig = (format, ...externalsArray)=>{
821
1114
  };
822
1115
  do {
823
1116
  asyncFlag = true;
824
- if (i >= externals.length) {
825
- return callback();
826
- }
1117
+ if (i >= externals.length) return callback();
827
1118
  matchUserExternals(externals[i++], request, handleExternalsAndCallback);
828
1119
  }while (!asyncFlag);
829
1120
  asyncFlag = false;
@@ -835,8 +1126,8 @@ const composeExternalsWarnConfig = (format, ...externalsArray)=>{
835
1126
  callback(true);
836
1127
  return;
837
1128
  }
838
- } else if (typeof externals === 'function') {} else // TODO: Support function
839
- if (typeof externals === 'object') {
1129
+ } else if ('function' == typeof externals) ;
1130
+ else if ('object' == typeof externals) {
840
1131
  if (Object.prototype.hasOwnProperty.call(externals, request)) {
841
1132
  callback(true);
842
1133
  return;
@@ -850,15 +1141,11 @@ const composeExternalsWarnConfig = (format, ...externalsArray)=>{
850
1141
  ({ request, dependencyType, contextInfo }, callback)=>{
851
1142
  let externalized = false;
852
1143
  const _callback = (matched)=>{
853
- if (matched) {
854
- externalized = true;
855
- }
1144
+ if (matched) externalized = true;
856
1145
  };
857
- if (contextInfo.issuer && dependencyType === 'commonjs') {
1146
+ if (contextInfo.issuer && 'commonjs' === dependencyType) {
858
1147
  matchUserExternals(externals, request, _callback);
859
- if (externalized) {
860
- dist_logger.warn(composeModuleImportWarn(request));
861
- }
1148
+ if (externalized) index_js_namespaceObject.logger.warn(composeModuleImportWarn(request));
862
1149
  }
863
1150
  callback();
864
1151
  }
@@ -868,18 +1155,16 @@ const composeExternalsWarnConfig = (format, ...externalsArray)=>{
868
1155
  };
869
1156
  const composeAutoExternalConfig = (options)=>{
870
1157
  const { autoExternal, pkgJson, userExternals } = options;
871
- if (!autoExternal) {
872
- return {};
873
- }
1158
+ if (!autoExternal) return {};
874
1159
  if (!pkgJson) {
875
- dist_logger.warn('autoExternal configuration will not be applied due to read package.json failed');
1160
+ index_js_namespaceObject.logger.warn('autoExternal configuration will not be applied due to read package.json failed');
876
1161
  return {};
877
1162
  }
878
1163
  const externalOptions = {
879
1164
  dependencies: true,
880
1165
  peerDependencies: true,
881
1166
  devDependencies: false,
882
- ...autoExternal === true ? {} : autoExternal
1167
+ ...true === autoExternal ? {} : autoExternal
883
1168
  };
884
1169
  // User externals configuration has higher priority than autoExternal
885
1170
  // eg: autoExternal: ['react'], user: output: { externals: { react: 'react-1' } }
@@ -890,9 +1175,7 @@ const composeAutoExternalConfig = (options)=>{
890
1175
  'peerDependencies',
891
1176
  'devDependencies'
892
1177
  ].reduce((prev, type)=>{
893
- if (externalOptions[type]) {
894
- return pkgJson[type] ? prev.concat(Object.keys(pkgJson[type])) : prev;
895
- }
1178
+ if (externalOptions[type]) return pkgJson[type] ? prev.concat(Object.keys(pkgJson[type])) : prev;
896
1179
  return prev;
897
1180
  }, []).filter((name)=>!userExternalKeys.includes(name));
898
1181
  const uniqueExternals = Array.from(new Set(externals));
@@ -906,8 +1189,96 @@ const composeAutoExternalConfig = (options)=>{
906
1189
  }
907
1190
  } : {};
908
1191
  };
1192
+ function composeMinifyConfig(minify) {
1193
+ if (void 0 !== minify) // User's minify configuration will be merged afterwards.
1194
+ return {};
1195
+ // When minify is not specified, Rslib will use a sane default for minify options.
1196
+ // The default options will only perform dead code elimination and unused code elimination.
1197
+ return {
1198
+ output: {
1199
+ minify: {
1200
+ js: true,
1201
+ css: false,
1202
+ jsOptions: {
1203
+ minimizerOptions: {
1204
+ mangle: false,
1205
+ minify: false,
1206
+ compress: {
1207
+ defaults: false,
1208
+ unused: true,
1209
+ dead_code: true,
1210
+ toplevel: true
1211
+ },
1212
+ format: {
1213
+ comments: 'all'
1214
+ }
1215
+ }
1216
+ }
1217
+ }
1218
+ }
1219
+ };
1220
+ }
1221
+ function composeBannerFooterConfig(banner, footer) {
1222
+ const bannerConfig = pick(banner, [
1223
+ 'js',
1224
+ 'css'
1225
+ ]);
1226
+ const footerConfig = pick(footer, [
1227
+ 'js',
1228
+ 'css'
1229
+ ]);
1230
+ if (isEmptyObject(bannerConfig) && isEmptyObject(footerConfig)) return {};
1231
+ const plugins = [];
1232
+ if (!isEmptyObject(bannerConfig)) {
1233
+ if (bannerConfig.js) plugins.push(new core_namespaceObject.rspack.BannerPlugin({
1234
+ banner: bannerConfig.js,
1235
+ stage: core_namespaceObject.rspack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE + 1,
1236
+ raw: true,
1237
+ include: /\.(js|mjs|cjs)$/
1238
+ }));
1239
+ if (bannerConfig.css) plugins.push(new core_namespaceObject.rspack.BannerPlugin({
1240
+ banner: bannerConfig.css,
1241
+ stage: core_namespaceObject.rspack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE + 1,
1242
+ raw: true,
1243
+ include: /\.(css)$/
1244
+ }));
1245
+ }
1246
+ if (!isEmptyObject(footerConfig)) {
1247
+ if (footerConfig.js) plugins.push(new core_namespaceObject.rspack.BannerPlugin({
1248
+ banner: footerConfig.js,
1249
+ stage: core_namespaceObject.rspack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE + 1,
1250
+ raw: true,
1251
+ footer: true,
1252
+ include: /\.(js|mjs|cjs)$/
1253
+ }));
1254
+ if (footerConfig.css) plugins.push(new core_namespaceObject.rspack.BannerPlugin({
1255
+ banner: footerConfig.css,
1256
+ stage: core_namespaceObject.rspack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_SIZE + 1,
1257
+ raw: true,
1258
+ footer: true,
1259
+ include: /\.(css)$/
1260
+ }));
1261
+ }
1262
+ return {
1263
+ tools: {
1264
+ rspack: {
1265
+ plugins
1266
+ }
1267
+ }
1268
+ };
1269
+ }
1270
+ function composeDecoratorsConfig(compilerOptions, version) {
1271
+ if (version || !compilerOptions?.experimentalDecorators) return {};
1272
+ return {
1273
+ source: {
1274
+ decorators: {
1275
+ version: 'legacy'
1276
+ }
1277
+ }
1278
+ };
1279
+ }
909
1280
  async function createConstantRsbuildConfig() {
910
- return (0,core_namespaceObject.defineConfig)({
1281
+ return (0, core_namespaceObject.defineConfig)({
911
1282
  mode: 'production',
912
1283
  dev: {
913
1284
  progressBar: false
@@ -916,7 +1287,8 @@ async function createConstantRsbuildConfig() {
916
1287
  htmlPlugin: false,
917
1288
  rspack: {
918
1289
  optimization: {
919
- moduleIds: 'named'
1290
+ moduleIds: 'named',
1291
+ nodeEnv: false
920
1292
  },
921
1293
  experiments: {
922
1294
  rspackFuture: {
@@ -953,25 +1325,6 @@ async function createConstantRsbuildConfig() {
953
1325
  },
954
1326
  output: {
955
1327
  filenameHash: false,
956
- minify: {
957
- js: true,
958
- css: false,
959
- jsOptions: {
960
- minimizerOptions: {
961
- mangle: false,
962
- minify: false,
963
- compress: {
964
- defaults: false,
965
- unused: true,
966
- dead_code: true,
967
- toplevel: true
968
- },
969
- format: {
970
- comments: 'all'
971
- }
972
- }
973
- }
974
- },
975
1328
  distPath: {
976
1329
  js: './'
977
1330
  }
@@ -1037,9 +1390,7 @@ const composeFormatConfig = (format)=>{
1037
1390
  throw new Error(`Unsupported format: ${format}`);
1038
1391
  }
1039
1392
  };
1040
- const composeModuleImportWarn = (request)=>{
1041
- return `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"')}.`;
1042
- };
1393
+ const composeModuleImportWarn = (request)=>`The externalized commonjs request ${picocolors_index_js_namespaceObject["default"].green(`"${request}"`)} will use ${picocolors_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 ${picocolors_index_js_namespaceObject["default"].blue('"output.externals"')}.`;
1043
1394
  const composeExternalsConfig = (format, externals)=>{
1044
1395
  // TODO: Define the internal externals config in Rsbuild's externals instead
1045
1396
  // Rspack's externals as they will not be merged from different fields. All externals
@@ -1088,37 +1439,21 @@ const composeAutoExtensionConfig = (config, autoExtension, pkgJson)=>{
1088
1439
  };
1089
1440
  const composeSyntaxConfig = (syntax, target)=>{
1090
1441
  // Defaults to ESNext, Rslib will assume all of the latest JavaScript and CSS features are supported.
1091
- if (syntax) {
1092
- return {
1093
- tools: {
1094
- rspack: (config)=>{
1095
- // TODO: Rspack should could resolve `browserslist:{query}` like webpack.
1096
- // https://webpack.js.org/configuration/target/#browserslist
1097
- // Using 'es5' as a temporary solution for compatibility.
1098
- config.target = [
1099
- 'es5'
1100
- ];
1101
- return config;
1102
- }
1103
- },
1104
- output: {
1105
- overrideBrowserslist: transformSyntaxToBrowserslist(syntax)
1442
+ if (syntax) return {
1443
+ tools: {
1444
+ rspack: (config)=>{
1445
+ // TODO: Rspack should could resolve `browserslist:{query}` like webpack.
1446
+ // https://webpack.js.org/configuration/target/#browserslist
1447
+ // Using 'es5' as a temporary solution for compatibility.
1448
+ config.target = [
1449
+ 'es5'
1450
+ ];
1451
+ return config;
1106
1452
  }
1107
- };
1108
- }
1109
- // If `syntax` is not defined, Rslib will try to determine by the `target`, with the last version of the target.
1110
- const lastTargetVersions = {
1111
- node: [
1112
- 'last 1 node versions'
1113
- ],
1114
- web: [
1115
- 'last 1 Chrome versions',
1116
- 'last 1 Firefox versions',
1117
- 'last 1 Edge versions',
1118
- 'last 1 Safari versions',
1119
- 'last 1 ios_saf versions',
1120
- 'not dead'
1121
- ]
1453
+ },
1454
+ output: {
1455
+ overrideBrowserslist: transformSyntaxToBrowserslist(syntax, target)
1456
+ }
1122
1457
  };
1123
1458
  return {
1124
1459
  tools: {
@@ -1130,24 +1465,18 @@ const composeSyntaxConfig = (syntax, target)=>{
1130
1465
  }
1131
1466
  },
1132
1467
  output: {
1133
- overrideBrowserslist: target === 'web' ? lastTargetVersions.web : target === 'node' ? lastTargetVersions.node : [
1134
- ...lastTargetVersions.node,
1135
- ...lastTargetVersions.web
1136
- ]
1468
+ // If `syntax` is not defined, Rslib will try to determine by the `target`, with the last version of the target.
1469
+ overrideBrowserslist: ESX_TO_BROWSERSLIST.esnext(target)
1137
1470
  }
1138
1471
  };
1139
1472
  };
1140
1473
  const composeEntryConfig = async (entries, bundle, root)=>{
1141
- if (!entries) {
1142
- return {};
1143
- }
1144
- if (bundle !== false) {
1145
- return {
1146
- source: {
1147
- entry: entries
1148
- }
1149
- };
1150
- }
1474
+ if (!entries) return {};
1475
+ if (false !== bundle) return {
1476
+ source: {
1477
+ entry: entries
1478
+ }
1479
+ };
1151
1480
  // In bundleless mode, resolve glob patterns and convert them to entry object.
1152
1481
  const resolvedEntries = {};
1153
1482
  for (const key of Object.keys(entries)){
@@ -1156,23 +1485,19 @@ const composeEntryConfig = async (entries, bundle, root)=>{
1156
1485
  // 1. A string of glob pattern: { entry: { index: 'src/*.ts' } }
1157
1486
  // 2. An array of glob patterns: { entry: { index: ['src/*.ts', 'src/*.tsx'] } }
1158
1487
  // Not supported for now: entry description object
1159
- const entryFiles = Array.isArray(entry) ? entry : typeof entry === 'string' ? [
1488
+ const entryFiles = Array.isArray(entry) ? entry : 'string' == typeof entry ? [
1160
1489
  entry
1161
1490
  ] : null;
1162
- if (!entryFiles) {
1163
- throw new Error('Entry can only be a string or an array of strings for now');
1164
- }
1491
+ if (!entryFiles) throw new Error('Entry can only be a string or an array of strings for now');
1165
1492
  // Turn entries in array into each separate entry.
1166
- const resolvedEntryFiles = await (0,fast_glob_index_js_namespaceObject["default"])(entryFiles, {
1493
+ const resolvedEntryFiles = await (0, fast_glob_index_js_namespaceObject["default"])(entryFiles, {
1167
1494
  cwd: root
1168
1495
  });
1169
- if (resolvedEntryFiles.length === 0) {
1170
- throw new Error(`Cannot find ${resolvedEntryFiles}`);
1171
- }
1496
+ if (0 === resolvedEntryFiles.length) throw new Error(`Cannot find ${resolvedEntryFiles}`);
1172
1497
  // Similar to `rootDir` in tsconfig and `outbase` in esbuild.
1173
1498
  const lcp = await calcLongestCommonPath(resolvedEntryFiles);
1174
1499
  // Using the longest common path of all non-declaration input files by default.
1175
- const outBase = lcp === null ? root : lcp;
1500
+ const outBase = null === lcp ? root : lcp;
1176
1501
  for (const file of resolvedEntryFiles){
1177
1502
  const { dir, name } = external_node_path_namespaceObject["default"].parse(external_node_path_namespaceObject["default"].relative(outBase, file));
1178
1503
  // Entry filename contains nested path to preserve source directory structure.
@@ -1202,9 +1527,7 @@ const composeBundleConfig = (jsExtension, bundle = true)=>{
1202
1527
  // This may result in a change in semantics,
1203
1528
  // user should use copy to keep origin file or use another separate entry to deal this
1204
1529
  let request = data.request;
1205
- if (request[0] === '.') {
1206
- request = (0,external_node_path_namespaceObject.extname)(request) ? request.replace(/\.[^.]+$/, jsExtension) : `${request}${jsExtension}`;
1207
- }
1530
+ if ('.' === request[0]) request = (0, external_node_path_namespaceObject.extname)(request) ? request.replace(/\.[^.]+$/, jsExtension) : `${request}${jsExtension}`;
1208
1531
  return callback(null, request);
1209
1532
  }
1210
1533
  callback();
@@ -1214,9 +1537,9 @@ const composeBundleConfig = (jsExtension, bundle = true)=>{
1214
1537
  };
1215
1538
  };
1216
1539
  const composeDtsConfig = async (libConfig, dtsExtension)=>{
1217
- const { dts, bundle, output, autoExternal } = libConfig;
1218
- if (dts === false || dts === undefined) return {};
1219
- const { pluginDts } = await Promise.resolve(/* import() */ ).then(__webpack_require__.bind(__webpack_require__, "rsbuild-plugin-dts"));
1540
+ const { dts, bundle, output, autoExternal, banner, footer } = libConfig;
1541
+ if (false === dts || void 0 === dts) return {};
1542
+ const { pluginDts } = await import("rsbuild-plugin-dts");
1220
1543
  return {
1221
1544
  plugins: [
1222
1545
  pluginDts({
@@ -1224,7 +1547,9 @@ const composeDtsConfig = async (libConfig, dtsExtension)=>{
1224
1547
  distPath: dts?.distPath ?? output?.distPath?.root ?? './dist',
1225
1548
  abortOnError: dts?.abortOnError ?? true,
1226
1549
  dtsExtension,
1227
- autoExternal
1550
+ autoExternal,
1551
+ banner: banner?.dts,
1552
+ footer: footer?.dts
1228
1553
  })
1229
1554
  ]
1230
1555
  };
@@ -1261,51 +1586,79 @@ const composeTargetConfig = (target = 'web')=>{
1261
1586
  target: 'node'
1262
1587
  }
1263
1588
  };
1264
- case 'neutral':
1265
- return {
1266
- tools: {
1267
- rspack: {
1268
- target: [
1269
- 'web',
1270
- 'node'
1271
- ]
1272
- }
1273
- }
1274
- };
1589
+ // TODO: Support `neutral` target, however Rsbuild don't list it as an option in the target field.
1590
+ // case 'neutral':
1591
+ // return {
1592
+ // tools: {
1593
+ // rspack: {
1594
+ // target: ['web', 'node'],
1595
+ // },
1596
+ // },
1597
+ // };
1275
1598
  default:
1276
1599
  throw new Error(`Unsupported platform: ${target}`);
1277
1600
  }
1278
1601
  };
1602
+ const composeExternalHelpersConfig = (externalHelpers, pkgJson)=>{
1603
+ let defaultConfig = {
1604
+ tools: {
1605
+ swc: {
1606
+ jsc: {
1607
+ externalHelpers: false
1608
+ }
1609
+ }
1610
+ }
1611
+ };
1612
+ if (externalHelpers) {
1613
+ const deps = [
1614
+ ...Object.keys(pkgJson?.dependencies ?? []),
1615
+ ...Object.keys(pkgJson?.devDependencies ?? [])
1616
+ ];
1617
+ if (!deps.includes(SWC_HELPERS)) {
1618
+ index_js_namespaceObject.logger.error(`${picocolors_index_js_namespaceObject["default"].green('externalHelpers')} is enabled, but the ${picocolors_index_js_namespaceObject["default"].blue(SWC_HELPERS)} dependency declaration was not found in package.json.`);
1619
+ process.exit(1);
1620
+ }
1621
+ defaultConfig = Object.assign(defaultConfig, {
1622
+ output: {
1623
+ externals: new RegExp(`^${SWC_HELPERS}($|\\/|\\\\)`)
1624
+ }
1625
+ });
1626
+ defaultConfig.tools.swc.jsc.externalHelpers = true;
1627
+ }
1628
+ return defaultConfig;
1629
+ };
1279
1630
  async function composeLibRsbuildConfig(config, configPath) {
1280
- const rootPath = (0,external_node_path_namespaceObject.dirname)(configPath);
1631
+ const rootPath = (0, external_node_path_namespaceObject.dirname)(configPath);
1281
1632
  const pkgJson = readPackageJson(rootPath);
1282
- const { format, autoExtension = true, autoExternal = true } = config;
1633
+ const { compilerOptions } = await loadTsconfig(rootPath, config.source?.tsconfigPath);
1634
+ const { format, banner = {}, footer = {}, autoExtension = true, autoExternal = true, externalHelpers = false } = config;
1283
1635
  const formatConfig = composeFormatConfig(format);
1636
+ const externalHelpersConfig = composeExternalHelpersConfig(externalHelpers, pkgJson);
1284
1637
  const externalsConfig = composeExternalsConfig(format, config.output?.externals);
1285
1638
  const { config: autoExtensionConfig, jsExtension, dtsExtension } = composeAutoExtensionConfig(config, autoExtension, pkgJson);
1286
1639
  const bundleConfig = composeBundleConfig(jsExtension, config.bundle);
1287
1640
  const targetConfig = composeTargetConfig(config.output?.target);
1288
- const syntaxConfig = composeSyntaxConfig(config.output?.syntax, config.output?.target);
1641
+ const syntaxConfig = composeSyntaxConfig(config?.syntax, config.output?.target);
1289
1642
  const autoExternalConfig = composeAutoExternalConfig({
1290
1643
  autoExternal,
1291
1644
  pkgJson,
1292
1645
  userExternals: config.output?.externals
1293
1646
  });
1294
- const entryConfig = await composeEntryConfig(config.source?.entry, config.bundle, (0,external_node_path_namespaceObject.dirname)(configPath));
1647
+ const entryConfig = await composeEntryConfig(config.source?.entry, config.bundle, (0, external_node_path_namespaceObject.dirname)(configPath));
1295
1648
  const dtsConfig = await composeDtsConfig(config, dtsExtension);
1296
1649
  const externalsWarnConfig = composeExternalsWarnConfig(format, autoExternalConfig?.output?.externals, externalsConfig?.output?.externals);
1297
- return (0,core_namespaceObject.mergeRsbuildConfig)(formatConfig, // externalsWarnConfig should before other externals config
1298
- externalsWarnConfig, externalsConfig, autoExternalConfig, autoExtensionConfig, syntaxConfig, bundleConfig, targetConfig, entryConfig, dtsConfig);
1650
+ const minifyConfig = composeMinifyConfig(config.output?.minify);
1651
+ const bannerFooterConfig = composeBannerFooterConfig(banner, footer);
1652
+ const decoratorsConfig = composeDecoratorsConfig(compilerOptions, config.source?.decorators?.version);
1653
+ return (0, core_namespaceObject.mergeRsbuildConfig)(formatConfig, externalHelpersConfig, externalsWarnConfig, externalsConfig, autoExternalConfig, autoExtensionConfig, syntaxConfig, bundleConfig, targetConfig, entryConfig, minifyConfig, dtsConfig, bannerFooterConfig, decoratorsConfig);
1299
1654
  }
1300
1655
  async function composeCreateRsbuildConfig(rslibConfig, path) {
1301
1656
  const constantRsbuildConfig = await createConstantRsbuildConfig();
1302
1657
  const configPath = path ?? rslibConfig._privateMeta?.configFilePath;
1303
1658
  const { lib: libConfigsArray, ...sharedRsbuildConfig } = rslibConfig;
1304
- if (!libConfigsArray) {
1305
- throw new Error(`Expect lib field to be an array, but got ${libConfigsArray}.`);
1306
- }
1659
+ if (!libConfigsArray) throw new Error(`Expect lib field to be an array, but got ${libConfigsArray}.`);
1307
1660
  const libConfigPromises = libConfigsArray.map(async (libConfig)=>{
1308
- const userConfig = (0,core_namespaceObject.mergeRsbuildConfig)(sharedRsbuildConfig, libConfig);
1661
+ const userConfig = (0, core_namespaceObject.mergeRsbuildConfig)(sharedRsbuildConfig, libConfig);
1309
1662
  // Merge the configuration of each environment based on the shared Rsbuild
1310
1663
  // configuration and Lib configuration in the settings.
1311
1664
  const libRsbuildConfig = await composeLibRsbuildConfig(userConfig, configPath);
@@ -1327,12 +1680,15 @@ async function composeCreateRsbuildConfig(rslibConfig, path) {
1327
1680
  // We should state in the document that the built-in configuration should not be changed optionally
1328
1681
  // In compose process of 2, we may read some config from 1, and reassemble the related config,
1329
1682
  // so before final mergeRsbuildConfig, we reset some specified fields
1330
- config: (0,core_namespaceObject.mergeRsbuildConfig)(constantRsbuildConfig, libRsbuildConfig, omitDeep(userConfig, [
1683
+ config: (0, core_namespaceObject.mergeRsbuildConfig)(constantRsbuildConfig, libRsbuildConfig, omit(userConfig, [
1331
1684
  'bundle',
1332
1685
  'format',
1333
1686
  'autoExtension',
1334
1687
  'autoExternal',
1335
1688
  'syntax',
1689
+ 'externalHelpers',
1690
+ 'banner',
1691
+ 'footer',
1336
1692
  'dts'
1337
1693
  ]))
1338
1694
  };
@@ -1355,17 +1711,14 @@ async function initRsbuild(rslibConfig) {
1355
1711
  for (const { format, config } of rsbuildConfigObject){
1356
1712
  const currentFormatCount = formatCount[format];
1357
1713
  const currentFormatIndex = formatIndex[format]++;
1358
- environments[currentFormatCount === 1 ? format : `${format}${currentFormatIndex}`] = config;
1714
+ environments[1 === currentFormatCount ? format : `${format}${currentFormatIndex}`] = config;
1359
1715
  }
1360
- return (0,core_namespaceObject.createRsbuild)({
1716
+ return (0, core_namespaceObject.createRsbuild)({
1361
1717
  rsbuildConfig: {
1362
1718
  environments
1363
1719
  }
1364
1720
  });
1365
1721
  }
1366
-
1367
- ;// CONCATENATED MODULE: ./src/build.ts
1368
-
1369
1722
  async function build(config, options) {
1370
1723
  const rsbuildInstance = await initRsbuild(config);
1371
1724
  await rsbuildInstance.build({
@@ -1373,17 +1726,11 @@ async function build(config, options) {
1373
1726
  });
1374
1727
  return rsbuildInstance;
1375
1728
  }
1376
-
1377
- ;// CONCATENATED MODULE: ./src/cli/commands.ts
1378
-
1379
-
1380
-
1381
-
1382
1729
  const applyCommonOptions = (command)=>{
1383
1730
  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');
1384
1731
  };
1385
1732
  function runCli() {
1386
- commander_index_js_namespaceObject.program.name('rslib').usage('<command> [options]').version("0.0.4");
1733
+ commander_index_js_namespaceObject.program.name('rslib').usage('<command> [options]').version("0.0.6");
1387
1734
  const buildCommand = commander_index_js_namespaceObject.program.command('build');
1388
1735
  const inspectCommand = commander_index_js_namespaceObject.program.command('inspect');
1389
1736
  [
@@ -1398,8 +1745,8 @@ function runCli() {
1398
1745
  });
1399
1746
  await build(rslibConfig, options);
1400
1747
  } catch (err) {
1401
- dist_logger.error('Failed to build.');
1402
- dist_logger.error(err);
1748
+ index_js_namespaceObject.logger.error('Failed to build.');
1749
+ index_js_namespaceObject.logger.error(err);
1403
1750
  process.exit(1);
1404
1751
  }
1405
1752
  });
@@ -1418,20 +1765,13 @@ function runCli() {
1418
1765
  writeToDisk: true
1419
1766
  });
1420
1767
  } catch (err) {
1421
- dist_logger.error('Failed to inspect config.');
1422
- dist_logger.error(err);
1768
+ index_js_namespaceObject.logger.error('Failed to inspect config.');
1769
+ index_js_namespaceObject.logger.error(err);
1423
1770
  process.exit(1);
1424
1771
  }
1425
1772
  });
1426
1773
  commander_index_js_namespaceObject.program.parse();
1427
1774
  }
1428
-
1429
- ;// CONCATENATED MODULE: ./src/index.ts
1430
-
1431
-
1432
-
1433
-
1434
-
1435
- const src_version = "0.0.4";
1436
-
1437
- export { build, defineConfig, loadConfig, dist_logger as logger, prepareCli, runCli, src_version as version };
1775
+ const src_version = "0.0.6";
1776
+ var __webpack_exports__logger = index_js_namespaceObject.logger;
1777
+ export { build, defineConfig, loadConfig, prepareCli, runCli, src_version as version, __webpack_exports__logger as logger };