@rslib/core 0.0.0 → 0.0.2

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 DELETED
@@ -1,1093 +0,0 @@
1
- // ../../node_modules/.pnpm/rslog@1.2.2/node_modules/rslog/dist/index.mjs
2
- import process2 from "process";
3
- import os from "os";
4
- import tty from "tty";
5
- function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : process2.argv) {
6
- const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
7
- const position = argv.indexOf(prefix + flag);
8
- const terminatorPosition = argv.indexOf("--");
9
- return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
10
- }
11
- var { env } = process2;
12
- var flagForceColor;
13
- if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
14
- flagForceColor = 0;
15
- } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
16
- flagForceColor = 1;
17
- }
18
- function envForceColor() {
19
- if ("FORCE_COLOR" in env) {
20
- if (env.FORCE_COLOR === "true") {
21
- return 1;
22
- }
23
- if (env.FORCE_COLOR === "false") {
24
- return 0;
25
- }
26
- return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
27
- }
28
- }
29
- function translateLevel(level) {
30
- if (level === 0) {
31
- return false;
32
- }
33
- return {
34
- level,
35
- hasBasic: true,
36
- has256: level >= 2,
37
- has16m: level >= 3
38
- };
39
- }
40
- function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
41
- const noFlagForceColor = envForceColor();
42
- if (noFlagForceColor !== void 0) {
43
- flagForceColor = noFlagForceColor;
44
- }
45
- const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
46
- if (forceColor === 0) {
47
- return 0;
48
- }
49
- if (sniffFlags) {
50
- if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
51
- return 3;
52
- }
53
- if (hasFlag("color=256")) {
54
- return 2;
55
- }
56
- }
57
- if ("TF_BUILD" in env && "AGENT_NAME" in env) {
58
- return 1;
59
- }
60
- if (haveStream && !streamIsTTY && forceColor === void 0) {
61
- return 0;
62
- }
63
- const min = forceColor || 0;
64
- if (env.TERM === "dumb") {
65
- return min;
66
- }
67
- if (process2.platform === "win32") {
68
- const osRelease = os.release().split(".");
69
- if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
70
- return Number(osRelease[2]) >= 14931 ? 3 : 2;
71
- }
72
- return 1;
73
- }
74
- if ("CI" in env) {
75
- if ("GITHUB_ACTIONS" in env || "GITEA_ACTIONS" in env) {
76
- return 3;
77
- }
78
- if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
79
- return 1;
80
- }
81
- return min;
82
- }
83
- if ("TEAMCITY_VERSION" in env) {
84
- return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
85
- }
86
- if (env.COLORTERM === "truecolor") {
87
- return 3;
88
- }
89
- if (env.TERM === "xterm-kitty") {
90
- return 3;
91
- }
92
- if ("TERM_PROGRAM" in env) {
93
- const version2 = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
94
- switch (env.TERM_PROGRAM) {
95
- case "iTerm.app": {
96
- return version2 >= 3 ? 3 : 2;
97
- }
98
- case "Apple_Terminal": {
99
- return 2;
100
- }
101
- }
102
- }
103
- if (/-256(color)?$/i.test(env.TERM)) {
104
- return 2;
105
- }
106
- if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
107
- return 1;
108
- }
109
- if ("COLORTERM" in env) {
110
- return 1;
111
- }
112
- return min;
113
- }
114
- function createSupportsColor(stream, options = {}) {
115
- const level = _supportsColor(stream, {
116
- streamIsTTY: stream && stream.isTTY,
117
- ...options
118
- });
119
- return translateLevel(level);
120
- }
121
- var supportsColor = {
122
- stdout: createSupportsColor({ isTTY: tty.isatty(1) }),
123
- stderr: createSupportsColor({ isTTY: tty.isatty(2) })
124
- };
125
- var supports_color_default = supportsColor;
126
- var colorLevel = supports_color_default.stdout ? supports_color_default.stdout.level : 0;
127
- var errorStackRegExp = /at\s.*:\d+:\d+[\s\)]*$/;
128
- var anonymousErrorStackRegExp = /^\s*at\s.*\(<anonymous>\)$/;
129
- var isErrorStackMessage = (message) => errorStackRegExp.test(message) || anonymousErrorStackRegExp.test(message);
130
- var formatter = (open, close, replace = open) => colorLevel >= 2 ? (input) => {
131
- let string = "" + input;
132
- let index = string.indexOf(close, open.length);
133
- return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
134
- } : String;
135
- var replaceClose = (string, close, replace, index) => {
136
- let start = string.substring(0, index) + replace;
137
- let end = string.substring(index + close.length);
138
- let nextIndex = end.indexOf(close);
139
- return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end;
140
- };
141
- var bold = formatter("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m");
142
- var red = formatter("\x1B[31m", "\x1B[39m");
143
- var green = formatter("\x1B[32m", "\x1B[39m");
144
- var yellow = formatter("\x1B[33m", "\x1B[39m");
145
- var magenta = formatter("\x1B[35m", "\x1B[39m");
146
- var cyan = formatter("\x1B[36m", "\x1B[39m");
147
- var gray = formatter("\x1B[90m", "\x1B[39m");
148
- var startColor = [189, 255, 243];
149
- var endColor = [74, 194, 154];
150
- var isWord = (char) => !/[\s\n]/.test(char);
151
- var gradient = (message) => {
152
- if (colorLevel < 3) {
153
- return colorLevel === 2 ? bold(cyan(message)) : message;
154
- }
155
- let chars = [...message];
156
- let steps = chars.filter(isWord).length;
157
- let r = startColor[0];
158
- let g = startColor[1];
159
- let b = startColor[2];
160
- let rStep = (endColor[0] - r) / steps;
161
- let gStep = (endColor[1] - g) / steps;
162
- let bStep = (endColor[2] - b) / steps;
163
- let output = "";
164
- for (let char of chars) {
165
- if (isWord(char)) {
166
- r += rStep;
167
- g += gStep;
168
- b += bStep;
169
- }
170
- output += `\x1B[38;2;${Math.round(r)};${Math.round(g)};${Math.round(
171
- b
172
- )}m${char}\x1B[39m`;
173
- }
174
- return bold(output);
175
- };
176
- var LOG_LEVEL = {
177
- error: 0,
178
- warn: 1,
179
- info: 2,
180
- log: 3,
181
- verbose: 4
182
- };
183
- var LOG_TYPES = {
184
- // Level error
185
- error: {
186
- label: "error",
187
- level: "error",
188
- color: red
189
- },
190
- // Level warn
191
- warn: {
192
- label: "warn",
193
- level: "warn",
194
- color: yellow
195
- },
196
- // Level info
197
- info: {
198
- label: "info",
199
- level: "info",
200
- color: cyan
201
- },
202
- start: {
203
- label: "start",
204
- level: "info",
205
- color: cyan
206
- },
207
- ready: {
208
- label: "ready",
209
- level: "info",
210
- color: green
211
- },
212
- success: {
213
- label: "success",
214
- level: "info",
215
- color: green
216
- },
217
- // Level log
218
- log: {
219
- level: "log"
220
- },
221
- // Level debug
222
- debug: {
223
- label: "debug",
224
- level: "verbose",
225
- color: magenta
226
- }
227
- };
228
- var createLogger = (options = {}) => {
229
- let maxLevel = options.level || "log";
230
- let log = (type, message, ...args) => {
231
- if (LOG_LEVEL[LOG_TYPES[type].level] > LOG_LEVEL[maxLevel]) {
232
- return;
233
- }
234
- if (message === void 0 || message === null) {
235
- return console.log();
236
- }
237
- let logType = LOG_TYPES[type];
238
- let label = "";
239
- let text = "";
240
- if ("label" in logType) {
241
- label = (logType.label || "").padEnd(7);
242
- label = bold(logType.color ? logType.color(label) : label);
243
- }
244
- if (message instanceof Error) {
245
- if (message.stack) {
246
- let [name, ...rest] = message.stack.split("\n");
247
- if (name.startsWith("Error: ")) {
248
- name = name.slice(7);
249
- }
250
- text = `${name}
251
- ${gray(rest.join("\n"))}`;
252
- } else {
253
- text = message.message;
254
- }
255
- } else if (logType.level === "error" && typeof message === "string") {
256
- let lines = message.split("\n");
257
- text = lines.map((line) => isErrorStackMessage(line) ? gray(line) : line).join("\n");
258
- } else {
259
- text = `${message}`;
260
- }
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;
279
- };
280
- var logger = createLogger();
281
-
282
- // src/utils/helper.ts
283
- import fs from "fs";
284
- import fsP from "fs/promises";
285
- import path from "path";
286
- import color from "../compiled/picocolors/index.js";
287
- var nodeBuiltInModules = [
288
- "assert",
289
- "assert/strict",
290
- "async_hooks",
291
- "buffer",
292
- "child_process",
293
- "cluster",
294
- "console",
295
- "constants",
296
- "crypto",
297
- "dgram",
298
- "diagnostics_channel",
299
- "dns",
300
- "dns/promises",
301
- "domain",
302
- "events",
303
- "fs",
304
- "fs/promises",
305
- "http",
306
- "http2",
307
- "https",
308
- "inspector",
309
- "inspector/promises",
310
- "module",
311
- "net",
312
- "os",
313
- "path",
314
- "path/posix",
315
- "path/win32",
316
- "perf_hooks",
317
- "process",
318
- "punycode",
319
- "querystring",
320
- "readline",
321
- "readline/promises",
322
- "repl",
323
- "stream",
324
- "stream/consumers",
325
- "stream/promises",
326
- "stream/web",
327
- "string_decoder",
328
- "sys",
329
- "timers",
330
- "timers/promises",
331
- "tls",
332
- "trace_events",
333
- "tty",
334
- "url",
335
- "util",
336
- "util/types",
337
- "v8",
338
- "vm",
339
- "wasi",
340
- "worker_threads",
341
- "zlib",
342
- /^node:/,
343
- // cspell:word pnpapi
344
- // Yarn PnP adds pnpapi as "builtin"
345
- "pnpapi"
346
- ];
347
- async function calcLongestCommonPath(absPaths) {
348
- if (absPaths.length === 0) {
349
- return null;
350
- }
351
- const sep = path.posix.sep;
352
- const splitPaths = absPaths.map((p) => p.split(sep));
353
- let lcaFragments = splitPaths[0];
354
- for (let i = 1; i < splitPaths.length; i++) {
355
- const currentPath = splitPaths[i];
356
- const minLength = Math.min(lcaFragments.length, currentPath.length);
357
- let j = 0;
358
- while (j < minLength && lcaFragments[j] === currentPath[j]) {
359
- j++;
360
- }
361
- lcaFragments = lcaFragments.slice(0, j);
362
- }
363
- let lca = lcaFragments.length > 0 ? lcaFragments.join(sep) : sep;
364
- const stats = await fsP.stat(lca);
365
- if (stats?.isFile()) {
366
- lca = path.dirname(lca);
367
- }
368
- return lca;
369
- }
370
- var readPackageJson = (rootPath) => {
371
- const pkgJsonPath = path.resolve(rootPath, "./package.json");
372
- if (!fs.existsSync(pkgJsonPath)) {
373
- logger.warn(`package.json does not exist in the ${rootPath} directory`);
374
- return;
375
- }
376
- try {
377
- return JSON.parse(fs.readFileSync(pkgJsonPath, "utf8"));
378
- } catch (err) {
379
- logger.warn(`Failed to parse ${pkgJsonPath}, it might not be valid JSON`);
380
- return;
381
- }
382
- };
383
- var isObject = (obj) => Object.prototype.toString.call(obj) === "[object Object]";
384
-
385
- // src/utils/logger.ts
386
- if (process.env.DEBUG) {
387
- logger.level = "verbose";
388
- }
389
-
390
- // src/cli/prepare.ts
391
- function initNodeEnv() {
392
- if (!process.env.NODE_ENV) {
393
- const command = process.argv[2] ?? "";
394
- process.env.NODE_ENV = ["build"].includes(command) ? "production" : "development";
395
- }
396
- }
397
- function prepareCli() {
398
- initNodeEnv();
399
- const { npm_execpath } = process.env;
400
- if (!npm_execpath || npm_execpath.includes("npx-cli.js") || npm_execpath.includes(".bun")) {
401
- console.log();
402
- }
403
- logger.greet(` ${`Rslib v${"0.0.0"}`}
404
- `);
405
- }
406
-
407
- // src/cli/commands.ts
408
- import { program } from "../compiled/commander/index.js";
409
-
410
- // src/config.ts
411
- import fs2 from "fs";
412
- import path2, { dirname, isAbsolute, join } from "path";
413
- import {
414
- createRsbuild,
415
- defineConfig as defineRsbuildConfig,
416
- loadConfig as loadRsbuildConfig,
417
- mergeRsbuildConfig
418
- } from "@rsbuild/core";
419
- import glob from "../compiled/fast-glob/index.js";
420
-
421
- // src/constant.ts
422
- var DEFAULT_CONFIG_NAME = "rslib.config";
423
- var DEFAULT_EXTENSIONS = [
424
- ".js",
425
- ".ts",
426
- ".mjs",
427
- ".mts",
428
- ".cjs",
429
- ".cts"
430
- ];
431
-
432
- // src/utils/extension.ts
433
- var getDefaultExtension = (options) => {
434
- const { format, pkgJson, autoExtension } = options;
435
- let jsExtension = ".js";
436
- let dtsExtension = ".d.ts";
437
- if (!autoExtension) {
438
- return {
439
- jsExtension,
440
- dtsExtension
441
- };
442
- }
443
- if (!pkgJson) {
444
- logger.warn(
445
- "autoExtension configuration will not be applied due to read package.json failed"
446
- );
447
- return {
448
- jsExtension,
449
- dtsExtension
450
- };
451
- }
452
- const isModule = pkgJson.type === "module";
453
- if (isModule && format === "cjs") {
454
- jsExtension = ".cjs";
455
- dtsExtension = ".d.cts";
456
- }
457
- if (!isModule && format === "esm") {
458
- jsExtension = ".mjs";
459
- dtsExtension = ".d.mts";
460
- }
461
- return {
462
- jsExtension,
463
- dtsExtension,
464
- isModule
465
- };
466
- };
467
-
468
- // src/utils/syntax.ts
469
- var ESX_TO_BROWSERSLIST = {
470
- es6: {
471
- Chrome: "63.0.0",
472
- Edge: "79.0.0",
473
- Firefox: "67.0.0",
474
- iOS: "13.0.0",
475
- Node: ["node > 12.20.0 and node < 13.0.0", "node > 13.2.0"],
476
- Opera: "50.0.0",
477
- Safari: "13.0.0"
478
- },
479
- es2015: {
480
- Chrome: "63.0.0",
481
- Edge: "79.0.0",
482
- Firefox: "67.0.0",
483
- iOS: "13.0.0",
484
- Node: "10.0.0",
485
- Opera: "50.0.0",
486
- Safari: "13.0.0"
487
- },
488
- es2016: {
489
- Chrome: "52.0.0",
490
- Edge: "14.0.0",
491
- Firefox: "52.0.0",
492
- iOS: "10.3.0",
493
- Node: "7.0.0",
494
- Opera: "39.0.0",
495
- Safari: "10.1.0"
496
- },
497
- es2017: {
498
- Chrome: "55.0.0",
499
- Edge: "15.0.0",
500
- Firefox: "52.0.0",
501
- iOS: "11.0.0",
502
- Node: "7.6.0",
503
- Opera: "42.0.0",
504
- Safari: "11.0.0"
505
- },
506
- es2018: {
507
- Chrome: "64.0.0",
508
- Edge: "79.0.0",
509
- Firefox: "78.0.0",
510
- iOS: "16.4.0",
511
- Node: [
512
- "node > 18.20.0 and node < 19.0.0",
513
- "node > 20.12.0 and node < 21.0.0",
514
- "node > 21.3.0"
515
- ],
516
- Opera: "51.0.0",
517
- Safari: "16.4.0"
518
- },
519
- es2019: {
520
- Chrome: "66.0.0",
521
- Edge: "79.0.0",
522
- Firefox: "58.0.0",
523
- iOS: "11.3.0",
524
- Node: "10.0.0",
525
- Opera: "53.0.0",
526
- Safari: "11.1.0"
527
- },
528
- es2020: {
529
- Chrome: "91.0.0",
530
- Edge: "91.0.0",
531
- Firefox: "80.0.0",
532
- iOS: "14.5.0",
533
- Node: "16.1.0",
534
- Opera: "77.0.0",
535
- Safari: "14.1.0"
536
- },
537
- es2021: {
538
- Chrome: "85.0.0",
539
- Edge: "85.0.0",
540
- Firefox: "79.0.0",
541
- iOS: "14.0.0",
542
- Node: "15.0.0",
543
- Opera: "71.0.0",
544
- Safari: "14.0.0"
545
- },
546
- es2022: {
547
- Chrome: "91.0.0",
548
- Edge: "94.0.0",
549
- Firefox: "93.0.0",
550
- iOS: "16.4.0",
551
- Node: "16.11.0",
552
- Opera: "80.0.0",
553
- Safari: "16.4.0"
554
- },
555
- es2023: {
556
- Chrome: "74.0.0",
557
- Edge: "79.0.0",
558
- Firefox: "67.0.0",
559
- iOS: "13.4.0",
560
- Node: "12.5.0",
561
- Opera: "62.0.0",
562
- Safari: "13.1.0"
563
- },
564
- es2024: {},
565
- esnext: {},
566
- es5: {
567
- Chrome: "5.0.0",
568
- Edge: "12.0.0",
569
- Firefox: "2.0.0",
570
- ie: "9.0.0",
571
- iOS: "6.0.0",
572
- Node: "0.4.0",
573
- Opera: "10.10.0",
574
- Safari: "3.1.0"
575
- }
576
- };
577
- var transformSyntaxToBrowserslist = (syntax) => {
578
- if (typeof syntax === "string" && syntax.toLowerCase().startsWith("es")) {
579
- if (syntax.toLowerCase() in ESX_TO_BROWSERSLIST) {
580
- return Object.entries(ESX_TO_BROWSERSLIST[syntax]).flatMap(
581
- ([engine, version2]) => {
582
- if (Array.isArray(version2)) {
583
- return version2;
584
- }
585
- return `${engine} >= ${version2}`;
586
- }
587
- );
588
- }
589
- throw new Error(`Unsupported ES version: ${syntax}`);
590
- }
591
- if (Array.isArray(syntax)) {
592
- return syntax;
593
- }
594
- throw new Error(`Unsupported syntax: ${syntax}`);
595
- };
596
-
597
- // src/config.ts
598
- function defineConfig(config) {
599
- return config;
600
- }
601
- var findConfig = (basePath) => {
602
- return DEFAULT_EXTENSIONS.map((ext) => basePath + ext).find(fs2.existsSync);
603
- };
604
- var resolveConfigPath = (root, customConfig) => {
605
- if (customConfig) {
606
- const customConfigPath = isAbsolute(customConfig) ? customConfig : join(root, customConfig);
607
- if (fs2.existsSync(customConfigPath)) {
608
- return customConfigPath;
609
- }
610
- logger.warn(`Cannot find config file: ${color.dim(customConfigPath)}
611
- `);
612
- }
613
- const configFilePath = findConfig(join(root, DEFAULT_CONFIG_NAME));
614
- if (configFilePath) {
615
- return configFilePath;
616
- }
617
- return void 0;
618
- };
619
- async function loadConfig(customConfig, envMode) {
620
- const root = process.cwd();
621
- const configFilePath = resolveConfigPath(root, customConfig);
622
- const { content } = await loadRsbuildConfig({
623
- cwd: dirname(configFilePath),
624
- path: configFilePath,
625
- envMode
626
- });
627
- return content;
628
- }
629
- var composeAutoExternalConfig = (options) => {
630
- const { autoExternal, pkgJson, userExternals } = options;
631
- if (!autoExternal) {
632
- return {};
633
- }
634
- if (!pkgJson) {
635
- logger.warn(
636
- "autoExternal configuration will not be applied due to read package.json failed"
637
- );
638
- return {};
639
- }
640
- const externalOptions = {
641
- dependencies: true,
642
- peerDependencies: true,
643
- devDependencies: false,
644
- ...autoExternal === true ? {} : autoExternal
645
- };
646
- const userExternalKeys = userExternals && isObject(userExternals) ? Object.keys(userExternals) : [];
647
- const externals = ["dependencies", "peerDependencies", "devDependencies"].reduce((prev, type) => {
648
- if (externalOptions[type]) {
649
- return pkgJson[type] ? prev.concat(Object.keys(pkgJson[type])) : prev;
650
- }
651
- return prev;
652
- }, []).filter((name) => !userExternalKeys.includes(name));
653
- const uniqueExternals = Array.from(new Set(externals));
654
- return externals.length ? {
655
- output: {
656
- externals: [
657
- // Exclude dependencies, e.g. `react`, `react/jsx-runtime`
658
- ...uniqueExternals.map((dep) => new RegExp(`^${dep}($|\\/|\\\\)`)),
659
- ...uniqueExternals
660
- ]
661
- }
662
- } : {};
663
- };
664
- async function createInternalRsbuildConfig() {
665
- return defineRsbuildConfig({
666
- mode: "production",
667
- dev: {
668
- progressBar: false
669
- },
670
- tools: {
671
- htmlPlugin: false,
672
- rspack: {
673
- optimization: {
674
- moduleIds: "named"
675
- },
676
- experiments: {
677
- rspackFuture: {
678
- bundlerInfo: {
679
- force: false
680
- }
681
- }
682
- }
683
- }
684
- },
685
- output: {
686
- filenameHash: false,
687
- // TODO: easy to development at the moment
688
- minify: false,
689
- distPath: {
690
- js: "./"
691
- }
692
- }
693
- });
694
- }
695
- var composeFormatConfig = (format) => {
696
- switch (format) {
697
- case "esm":
698
- return {
699
- tools: {
700
- rspack: {
701
- externalsType: "module-import",
702
- output: {
703
- module: true,
704
- chunkFormat: "module",
705
- library: {
706
- type: "modern-module"
707
- }
708
- },
709
- module: {
710
- parser: {
711
- javascript: {
712
- importMeta: false
713
- }
714
- }
715
- },
716
- optimization: {
717
- concatenateModules: true
718
- },
719
- experiments: {
720
- outputModule: true
721
- }
722
- }
723
- }
724
- };
725
- case "cjs":
726
- return {
727
- tools: {
728
- rspack: {
729
- externalsType: "commonjs",
730
- output: {
731
- iife: false,
732
- chunkFormat: "commonjs",
733
- library: {
734
- type: "commonjs"
735
- }
736
- }
737
- }
738
- }
739
- };
740
- case "umd":
741
- return {
742
- tools: {
743
- rspack: {
744
- externalsType: "umd",
745
- output: {
746
- library: {
747
- type: "umd"
748
- }
749
- }
750
- }
751
- }
752
- };
753
- default:
754
- throw new Error(`Unsupported format: ${format}`);
755
- }
756
- };
757
- var composeAutoExtensionConfig = (format, autoExtension, pkgJson) => {
758
- const { jsExtension, dtsExtension } = getDefaultExtension({
759
- format,
760
- pkgJson,
761
- autoExtension
762
- });
763
- return {
764
- config: {
765
- output: {
766
- filename: {
767
- js: `[name]${jsExtension}`
768
- }
769
- }
770
- },
771
- jsExtension,
772
- dtsExtension
773
- };
774
- };
775
- var composeSyntaxConfig = (syntax, target) => {
776
- if (syntax) {
777
- return {
778
- tools: {
779
- rspack: (config) => {
780
- config.target = ["es5"];
781
- return config;
782
- }
783
- },
784
- output: {
785
- overrideBrowserslist: transformSyntaxToBrowserslist(syntax)
786
- }
787
- };
788
- }
789
- const lastTargetVersions = {
790
- node: ["last 1 node versions"],
791
- web: [
792
- "last 1 Chrome versions",
793
- "last 1 Firefox versions",
794
- "last 1 Edge versions",
795
- "last 1 Safari versions",
796
- "last 1 ios_saf versions",
797
- "not dead"
798
- ]
799
- };
800
- return {
801
- tools: {
802
- rspack: (config) => {
803
- config.target = ["es2022"];
804
- return config;
805
- }
806
- },
807
- output: {
808
- overrideBrowserslist: target === "web" ? lastTargetVersions.web : target === "node" ? lastTargetVersions.node : [...lastTargetVersions.node, ...lastTargetVersions.web]
809
- }
810
- };
811
- };
812
- var composeEntryConfig = async (entries, bundle, root) => {
813
- if (!entries) {
814
- return {};
815
- }
816
- if (bundle !== false) {
817
- return {
818
- source: {
819
- entry: entries
820
- }
821
- };
822
- }
823
- const resolvedEntries = {};
824
- for (const key of Object.keys(entries)) {
825
- const entry = entries[key];
826
- const entryFiles = Array.isArray(entry) ? entry : typeof entry === "string" ? [entry] : null;
827
- if (!entryFiles) {
828
- throw new Error(
829
- "Entry can only be a string or an array of strings for now"
830
- );
831
- }
832
- const resolvedEntryFiles = await glob(entryFiles, {
833
- cwd: root
834
- });
835
- if (resolvedEntryFiles.length === 0) {
836
- throw new Error(`Cannot find ${resolvedEntryFiles}`);
837
- }
838
- const lcp = await calcLongestCommonPath(resolvedEntryFiles);
839
- const outBase = lcp === null ? root : lcp;
840
- for (const file of resolvedEntryFiles) {
841
- const { dir, name } = path2.parse(path2.relative(outBase, file));
842
- const entryFileName = path2.join(dir, name);
843
- resolvedEntries[entryFileName] = file;
844
- }
845
- }
846
- return {
847
- source: {
848
- entry: resolvedEntries
849
- }
850
- };
851
- };
852
- var composeBundleConfig = (jsExtension, bundle = true) => {
853
- if (bundle)
854
- return {};
855
- return {
856
- output: {
857
- externals: [
858
- (data, callback) => {
859
- if (data.contextInfo.issuer) {
860
- return callback(
861
- null,
862
- data.request[0] === "." ? `${data.request}${jsExtension}` : data.request
863
- );
864
- }
865
- callback();
866
- }
867
- ]
868
- }
869
- };
870
- };
871
- var composeDtsConfig = async (libConfig, dtsExtension) => {
872
- const { dts, bundle, output, autoExternal } = libConfig;
873
- if (dts === false || dts === void 0)
874
- return {};
875
- const { pluginDts } = await import("rsbuild-plugin-dts");
876
- return {
877
- plugins: [
878
- pluginDts({
879
- bundle: dts?.bundle ?? bundle,
880
- distPath: dts?.distPath ?? output?.distPath?.root ?? "./dist",
881
- abortOnError: dts?.abortOnError ?? true,
882
- dtsExtension,
883
- autoExternal
884
- })
885
- ]
886
- };
887
- };
888
- var composeTargetConfig = (target = "web") => {
889
- switch (target) {
890
- case "web":
891
- return {
892
- tools: {
893
- rspack: {
894
- target: ["web"]
895
- }
896
- }
897
- };
898
- case "node":
899
- return {
900
- tools: {
901
- rspack: {
902
- target: ["node"]
903
- // "__dirname" and "__filename" shims will automatically be enabled when `output.module` is `true`,
904
- // and leave them as-is in the rest of the cases.
905
- // { node: { __dirname: ..., __filename: ... } }
906
- }
907
- },
908
- output: {
909
- // When output.target is 'node', Node.js's built-in will be treated as externals of type `node-commonjs`.
910
- // Simply override the built-in modules to make them external.
911
- // https://github.com/webpack/webpack/blob/dd44b206a9c50f4b4cb4d134e1a0bd0387b159a3/lib/node/NodeTargetPlugin.js#L81
912
- externals: nodeBuiltInModules,
913
- target: "node"
914
- }
915
- };
916
- case "neutral":
917
- return {
918
- tools: {
919
- rspack: {
920
- target: ["web", "node"]
921
- }
922
- }
923
- };
924
- default:
925
- throw new Error(`Unsupported platform: ${target}`);
926
- }
927
- };
928
- async function composeLibRsbuildConfig(libConfig, rsbuildConfig, configPath) {
929
- const config = mergeRsbuildConfig(rsbuildConfig, libConfig);
930
- const rootPath = dirname(configPath);
931
- const pkgJson = readPackageJson(rootPath);
932
- const { format, autoExtension = true, autoExternal = true } = config;
933
- const formatConfig = composeFormatConfig(format);
934
- const {
935
- config: autoExtensionConfig,
936
- jsExtension,
937
- dtsExtension
938
- } = composeAutoExtensionConfig(format, autoExtension, pkgJson);
939
- const bundleConfig = composeBundleConfig(jsExtension, config.bundle);
940
- const targetConfig = composeTargetConfig(config.output?.target);
941
- const syntaxConfig = composeSyntaxConfig(
942
- config.output?.syntax,
943
- config.output?.target
944
- );
945
- const autoExternalConfig = composeAutoExternalConfig({
946
- autoExternal,
947
- pkgJson,
948
- userExternals: rsbuildConfig.output?.externals
949
- });
950
- const entryConfig = await composeEntryConfig(
951
- config.source?.entry,
952
- config.bundle,
953
- dirname(configPath)
954
- );
955
- const dtsConfig = await composeDtsConfig(config, dtsExtension);
956
- return mergeRsbuildConfig(
957
- formatConfig,
958
- autoExtensionConfig,
959
- autoExternalConfig,
960
- syntaxConfig,
961
- bundleConfig,
962
- targetConfig,
963
- entryConfig,
964
- dtsConfig
965
- );
966
- }
967
- async function composeCreateRsbuildConfig(rslibConfig, path3) {
968
- const internalRsbuildConfig = await createInternalRsbuildConfig();
969
- const configPath = path3 ?? rslibConfig._privateMeta?.configFilePath;
970
- const { lib: libConfigsArray, ...sharedRsbuildConfig } = rslibConfig;
971
- if (!libConfigsArray) {
972
- throw new Error(
973
- `Expect lib field to be an array, but got ${libConfigsArray}.`
974
- );
975
- }
976
- const libConfigPromises = libConfigsArray.map(async (libConfig) => {
977
- const { format, ...overrideRsbuildConfig } = libConfig;
978
- const baseRsbuildConfig = mergeRsbuildConfig(
979
- sharedRsbuildConfig,
980
- overrideRsbuildConfig
981
- );
982
- const libRsbuildConfig = await composeLibRsbuildConfig(
983
- libConfig,
984
- baseRsbuildConfig,
985
- configPath
986
- );
987
- baseRsbuildConfig.source ?? (baseRsbuildConfig.source = {});
988
- baseRsbuildConfig.source.entry = {};
989
- return {
990
- format,
991
- config: mergeRsbuildConfig(
992
- baseRsbuildConfig,
993
- libRsbuildConfig,
994
- // Merge order matters, keep `internalRsbuildConfig` at the last position
995
- // to ensure that the internal config is not overridden by user's config.
996
- internalRsbuildConfig
997
- )
998
- };
999
- });
1000
- const composedRsbuildConfig = await Promise.all(libConfigPromises);
1001
- return composedRsbuildConfig;
1002
- }
1003
- async function initRsbuild(rslibConfig) {
1004
- const rsbuildConfigObject = await composeCreateRsbuildConfig(rslibConfig);
1005
- const environments = {};
1006
- const formatCount = rsbuildConfigObject.reduce(
1007
- (acc, { format }) => {
1008
- acc[format] = (acc[format] ?? 0) + 1;
1009
- return acc;
1010
- },
1011
- {}
1012
- );
1013
- const formatIndex = {
1014
- esm: 0,
1015
- cjs: 0,
1016
- umd: 0
1017
- };
1018
- for (const { format, config } of rsbuildConfigObject) {
1019
- const currentFormatCount = formatCount[format];
1020
- const currentFormatIndex = formatIndex[format]++;
1021
- environments[currentFormatCount === 1 ? format : `${format}${currentFormatIndex}`] = config;
1022
- }
1023
- return createRsbuild({
1024
- rsbuildConfig: {
1025
- environments
1026
- }
1027
- });
1028
- }
1029
-
1030
- // src/build.ts
1031
- async function build(config, options) {
1032
- const rsbuildInstance = await initRsbuild(config);
1033
- await rsbuildInstance.build({
1034
- watch: options?.watch
1035
- });
1036
- return rsbuildInstance;
1037
- }
1038
-
1039
- // src/cli/commands.ts
1040
- var applyCommonOptions = (command) => {
1041
- command.option(
1042
- "-c --config <config>",
1043
- "specify the configuration file, can be a relative or absolute path"
1044
- ).option(
1045
- "--env-mode <mode>",
1046
- "specify the env mode to load the `.env.[mode]` file"
1047
- );
1048
- };
1049
- function runCli() {
1050
- program.name("rslib").usage("<command> [options]").version("0.0.0");
1051
- const buildCommand = program.command("build");
1052
- const inspectCommand = program.command("inspect");
1053
- [buildCommand, inspectCommand].forEach(applyCommonOptions);
1054
- buildCommand.option("-w --watch", "turn on watch mode, watch for changes and rebuild").description("build the library for production").action(async (options) => {
1055
- try {
1056
- const rslibConfig = await loadConfig(options.config, options.envMode);
1057
- await build(rslibConfig, options);
1058
- } catch (err) {
1059
- logger.error("Failed to build.");
1060
- logger.error(err);
1061
- process.exit(1);
1062
- }
1063
- });
1064
- inspectCommand.description("inspect the Rslib / Rsbuild / Rspack configs").option("--env <env>", "specify env mode", "development").option("--output <output>", "specify inspect content output path", "./").option("--verbose", "show full function definitions in output").action(async (options) => {
1065
- try {
1066
- const rslibConfig = await loadConfig(options.config, options.envMode);
1067
- const rsbuildInstance = await initRsbuild(rslibConfig);
1068
- await rsbuildInstance.inspectConfig({
1069
- mode: options.mode,
1070
- verbose: options.verbose,
1071
- outputPath: options.output,
1072
- writeToDisk: true
1073
- });
1074
- } catch (err) {
1075
- logger.error("Failed to inspect config.");
1076
- logger.error(err);
1077
- process.exit(1);
1078
- }
1079
- });
1080
- program.parse();
1081
- }
1082
-
1083
- // src/index.ts
1084
- var version = "0.0.0";
1085
- export {
1086
- build,
1087
- defineConfig,
1088
- loadConfig,
1089
- logger,
1090
- prepareCli,
1091
- runCli,
1092
- version
1093
- };