@empjs/cli 3.1.0-rc.7 → 3.1.0-rc.9

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,2952 +1,18 @@
1
1
  import {createRequire as __createRequire} from 'module';var require=__createRequire(import.meta.url);
2
- var __defProp = Object.defineProperty;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
5
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
6
- }) : x)(function(x) {
7
- if (typeof require !== "undefined") return require.apply(this, arguments);
8
- throw Error('Dynamic require of "' + x + '" is not supported');
9
- });
10
- var __esm = (fn, res) => function __init() {
11
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
- };
13
- var __export = (target, all) => {
14
- for (var name in all)
15
- __defProp(target, name, { get: all[name], enumerable: true });
16
- };
17
-
18
- // ../../node_modules/.pnpm/tsup@8.1.0_postcss@8.4.38_ts-node@10.9.2_typescript@5.5.4/node_modules/tsup/assets/esm_shims.js
19
- import { fileURLToPath } from "url";
20
- import path from "path";
21
- var getFilename, getDirname, __dirname, __filename;
22
- var init_esm_shims = __esm({
23
- "../../node_modules/.pnpm/tsup@8.1.0_postcss@8.4.38_ts-node@10.9.2_typescript@5.5.4/node_modules/tsup/assets/esm_shims.js"() {
24
- "use strict";
25
- getFilename = () => fileURLToPath(import.meta.url);
26
- getDirname = () => path.dirname(getFilename());
27
- __dirname = /* @__PURE__ */ getDirname();
28
- __filename = /* @__PURE__ */ getFilename();
29
- }
30
- });
31
-
32
- // src/helper/color.ts
33
- import chalk from "chalk";
34
- var lightGreen, green, lightCyan, cyan, lightRed, red, yellow, orange, lightBlue, blue, white, lightMagenta, magenta, gray, color_default;
35
- var init_color = __esm({
36
- "src/helper/color.ts"() {
37
- "use strict";
38
- init_esm_shims();
39
- lightGreen = chalk.hex("#1abc9c");
40
- green = chalk.hex("#16a085");
41
- lightCyan = chalk.hex("#2ecc71");
42
- cyan = chalk.hex("#27ae60");
43
- lightRed = chalk.hex("#e74c3c");
44
- red = chalk.hex("#c0392b");
45
- yellow = chalk.hex("#f1c40f");
46
- orange = chalk.hex("#f39c12");
47
- lightBlue = chalk.hex("#3498db");
48
- blue = chalk.hex("#2980b9");
49
- white = chalk.hex("#ecf0f1");
50
- lightMagenta = chalk.hex("#fd79a8");
51
- magenta = chalk.hex("#e84393");
52
- gray = chalk.hex("#7f8c8d");
53
- color_default = {
54
- lightGreen,
55
- green,
56
- lightCyan,
57
- cyan,
58
- lightRed,
59
- red,
60
- yellow,
61
- orange,
62
- lightBlue,
63
- blue,
64
- white,
65
- lightMagenta,
66
- magenta,
67
- gray
68
- };
69
- }
70
- });
71
-
72
- // src/helper/logger.ts
73
- var Logger, logger_default;
74
- var init_logger = __esm({
75
- "src/helper/logger.ts"() {
76
- "use strict";
77
- init_esm_shims();
78
- init_color();
79
- Logger = class {
80
- brandName = "";
81
- fullName = "";
82
- logLevel = "debug";
83
- isLogTime = true;
84
- setup({ brandName, logLevel, fullName }) {
85
- this.brandName = ` [${brandName}] `;
86
- this.fullName = ` ${fullName} `;
87
- this.fullName = color_default.green.bold(this.fullName);
88
- if (logLevel) this.logLevel = logLevel;
89
- }
90
- time = (...args) => this.isLogTime && console.time(...args);
91
- timeEnd = (...args) => this.isLogTime && console.timeEnd(...args);
92
- debug = (...args) => ["debug"].includes(this.logLevel) && console.log(...args);
93
- info = (...args) => ["debug", "info"].includes(this.logLevel) && console.log(...args);
94
- warn = (...args) => ["debug", "info", "warn"].includes(this.logLevel) && console.warn(...args);
95
- error = (...args) => ["debug", "info", "warn", "error"].includes(this.logLevel) && console.error(...args);
96
- blue = (msg) => {
97
- console.log(`${color_default.lightBlue(this.brandName)}${color_default.blue(` ${msg} `)}
98
- `);
99
- };
100
- cyan = (msg) => {
101
- console.log(`${color_default.lightCyan(this.brandName)}${color_default.cyan(` ${msg} `)}
102
- `);
103
- };
104
- magenta = (msg) => {
105
- console.log(`${color_default.lightMagenta(this.brandName)}${color_default.magenta(` ${msg} `)}
106
- `);
107
- };
108
- green = (msg) => {
109
- console.log(`${color_default.lightGreen(this.brandName)}${color_default.green(` ${msg} `)}
110
- `);
111
- };
112
- yellow = (msg) => {
113
- console.log(`${color_default.yellow(this.brandName)}${color_default.orange(` ${msg} `)}
114
- `);
115
- };
116
- red = (msg) => {
117
- console.log(`${color_default.lightRed(this.brandName)}${color_default.red(` ${msg} `)}
118
- `);
119
- };
120
- sysError = (msg) => {
121
- console.log(`${color_default.lightRed(` System Error Tips `)}${color_default.red(` ${msg} `)}
122
- `);
123
- };
124
- //
125
- link = (msg) => {
126
- return color_default.blue(msg);
127
- };
128
- title = (msg) => {
129
- console.log(`${this.fullName}${color_default.yellow.underline(`${msg}`)}
130
- `);
131
- };
132
- };
133
- logger_default = new Logger();
134
- }
135
- });
136
-
137
- // src/helper/utils.ts
138
- var utils_exports = {};
139
- __export(utils_exports, {
140
- clearConsole: () => clearConsole,
141
- deepAssign: () => deepAssign,
142
- ensureArray: () => ensureArray,
143
- getLanIp: () => getLanIp,
144
- getPkgVersion: () => getPkgVersion,
145
- importJsVm: () => importJsVm,
146
- jsonFilter: () => jsonFilter,
147
- timeFormat: () => timeFormat,
148
- vCompare: () => vCompare
149
- });
150
- import { ip } from "address";
151
- import chalk2 from "chalk";
152
- import { gateway4sync } from "default-gateway";
153
- import fs from "fs-extra";
154
- function clearConsole() {
155
- process.stdout.write(process.platform === "win32" ? "\x1B[2J\x1B[0f" : "\x1B[2J\x1B[3J\x1B[H");
156
- }
157
- function deepAssign(target, ...sources) {
158
- for (const source of sources) {
159
- for (const k in source) {
160
- const vs = source[k], vt = target[k];
161
- if (Object(vs) == vs && Object(vt) === vt) {
162
- target[k] = deepAssign(vt, vs);
163
- continue;
164
- }
165
- target[k] = source[k];
166
- }
167
- }
168
- return target;
169
- }
170
- var getLanIp, getPkgVersion, ensureArray, jsonFilter, vCompare, timeFormat, importJsVm;
171
- var init_utils = __esm({
172
- "src/helper/utils.ts"() {
173
- "use strict";
174
- init_esm_shims();
175
- getLanIp = () => {
176
- const { int } = gateway4sync();
177
- return ip(int || "") || "127.0.0.1";
178
- };
179
- getPkgVersion = (pkgPath) => {
180
- try {
181
- const { version } = fs.readJSONSync(pkgPath);
182
- return version;
183
- } catch (err) {
184
- return void 0;
185
- }
186
- };
187
- ensureArray = (params) => {
188
- if (Array.isArray(params)) {
189
- return params;
190
- }
191
- return [params];
192
- };
193
- jsonFilter = (d = {}, notIncludeKeys = []) => Object.keys(d).filter((key) => !notIncludeKeys.includes(key)).reduce((o, key) => {
194
- o[key] = d[key];
195
- return o;
196
- }, {});
197
- vCompare = (preVersion = "", lastVersion = "") => {
198
- const sources = preVersion.replace("^", "").split(".");
199
- const dests = lastVersion.replace("^", "").split(".");
200
- const maxL = Math.max(sources.length, dests.length);
201
- let result = 0;
202
- for (let i = 0; i < maxL; i++) {
203
- const preValue = sources.length > i ? sources[i] : 0;
204
- const preNum = isNaN(Number(preValue)) ? preValue.charCodeAt() : Number(preValue);
205
- const lastValue = dests.length > i ? dests[i] : 0;
206
- const lastNum = isNaN(Number(lastValue)) ? lastValue.charCodeAt() : Number(lastValue);
207
- if (preNum < lastNum) {
208
- result = -1;
209
- break;
210
- } else if (preNum > lastNum) {
211
- result = 1;
212
- break;
213
- }
214
- }
215
- return result;
216
- };
217
- timeFormat = (seconds) => {
218
- seconds = seconds / 1e3;
219
- const format = (time) => chalk2.bold(time);
220
- if (seconds < 1) {
221
- return `${seconds * 1e3} ms`;
222
- }
223
- if (seconds < 10) {
224
- const digits = seconds >= 0.01 ? 2 : 3;
225
- return `${format(seconds.toFixed(digits))} s`;
226
- }
227
- if (seconds < 60) {
228
- return `${format(seconds.toFixed(1))} s`;
229
- }
230
- const minutes = seconds / 60;
231
- return `${format(minutes.toFixed(2))} m`;
232
- };
233
- importJsVm = (content) => `data:text/javascript,${content}`;
234
- }
235
- });
236
-
237
- // src/helper/index.ts
238
- var helper_exports = {};
239
- __export(helper_exports, {
240
- chalk: () => chalk3,
241
- color: () => color_default,
242
- glob: () => glob,
243
- logger: () => logger_default,
244
- utils: () => utils_exports
245
- });
246
- import chalk3 from "chalk";
247
- import { glob } from "glob";
248
- var init_helper = __esm({
249
- "src/helper/index.ts"() {
250
- "use strict";
251
- init_esm_shims();
252
- init_color();
253
- init_utils();
254
- init_logger();
255
- }
256
- });
257
-
258
- // src/helper/loadConfig.ts
259
- import fs2 from "fs";
260
- import path2 from "path";
261
- import jiti from "jiti";
262
- var DEFAULT_CONFIG_FILES, loadConfig, getEmpConfigPath, fsFindByConfigFileName;
263
- var init_loadConfig = __esm({
264
- "src/helper/loadConfig.ts"() {
265
- "use strict";
266
- init_esm_shims();
267
- init_store();
268
- init_logger();
269
- DEFAULT_CONFIG_FILES = [
270
- "emp-config.ts",
271
- "emp-config.js",
272
- "emp.config.ts",
273
- "emp.config.js",
274
- //
275
- "emp-config.mjs",
276
- "emp-config.cjs",
277
- "emp-config.mts",
278
- "emp-config.cts",
279
- //
280
- "emp.config.mjs",
281
- "emp.config.cjs",
282
- "emp.config.mts",
283
- "emp.config.cts"
284
- ];
285
- loadConfig = jiti(__filename, {
286
- esmResolve: true,
287
- // disable require cache to support restart CLI and read the new config
288
- requireCache: false,
289
- interopDefault: true
290
- // debug: true,
291
- });
292
- getEmpConfigPath = async () => {
293
- return fsFindByConfigFileName();
294
- };
295
- fsFindByConfigFileName = () => {
296
- logger_default.time("[store]GetEmpConfigPath");
297
- let resolvedPath;
298
- for (const filename of DEFAULT_CONFIG_FILES) {
299
- const filePath = path2.resolve(store_default.root, filename);
300
- if (!fs2.existsSync(filePath)) continue;
301
- resolvedPath = filePath;
302
- break;
303
- }
304
- logger_default.timeEnd("[store]GetEmpConfigPath");
305
- return resolvedPath;
306
- };
307
- }
308
- });
309
-
310
- // src/helper/getPort.ts
311
- import net from "net";
312
- import os from "os";
313
- async function getPorts(basePort, host = "localhost") {
314
- if (basePort !== httpsPort && (basePort < minPort || basePort > maxPort)) {
315
- throw new Error(`Port number must lie between ${minPort} and ${maxPort}`);
316
- }
317
- let port = basePort;
318
- const localhosts = getLocalHosts();
319
- let hosts;
320
- if (host && !localhosts.has(host)) {
321
- hosts = /* @__PURE__ */ new Set([host]);
322
- } else {
323
- hosts = localhosts;
324
- }
325
- const portUnavailableErrors = /* @__PURE__ */ new Set(["EADDRINUSE", "EACCES"]);
326
- while (port <= maxPort) {
327
- try {
328
- const availablePort = await getAvailablePort(port, hosts);
329
- return availablePort;
330
- } catch (error) {
331
- if (!portUnavailableErrors.has(
332
- /** @type {NodeJS.ErrnoException} */
333
- error.code
334
- )) {
335
- throw error;
336
- }
337
- port += 1;
338
- }
339
- }
340
- throw new Error("No available ports found");
341
- }
342
- var minPort, maxPort, httpsPort, getLocalHosts, checkAvailablePort, getAvailablePort;
343
- var init_getPort = __esm({
344
- "src/helper/getPort.ts"() {
345
- "use strict";
346
- init_esm_shims();
347
- minPort = 1024;
348
- maxPort = 65535;
349
- httpsPort = 443;
350
- getLocalHosts = () => {
351
- const interfaces = os.networkInterfaces();
352
- const results = /* @__PURE__ */ new Set([void 0, "0.0.0.0"]);
353
- for (const _interface of Object.values(interfaces)) {
354
- if (_interface) {
355
- for (const config of _interface) {
356
- results.add(config.address);
357
- }
358
- }
359
- }
360
- return results;
361
- };
362
- checkAvailablePort = (basePort, host) => new Promise((resolve, reject) => {
363
- const server = net.createServer();
364
- server.unref();
365
- server.on("error", reject);
366
- server.listen(basePort, host, () => {
367
- const { port } = server.address();
368
- server.close(() => {
369
- resolve(port);
370
- });
371
- });
372
- });
373
- getAvailablePort = async (port, hosts) => {
374
- const nonExistentInterfaceErrors = /* @__PURE__ */ new Set(["EADDRNOTAVAIL", "EINVAL"]);
375
- for (const host of hosts) {
376
- try {
377
- await checkAvailablePort(port, host);
378
- } catch (error) {
379
- if (!nonExistentInterfaceErrors.has(
380
- /** @type {NodeJS.ErrnoException} */
381
- error.code
382
- )) {
383
- throw error;
384
- }
385
- }
386
- }
387
- return port;
388
- };
389
- }
390
- });
391
-
392
- // src/helper/ipAddress.ts
393
- import url from "url";
394
- import chalk4 from "chalk";
395
- var IpAdress, ipAddress_default;
396
- var init_ipAddress = __esm({
397
- "src/helper/ipAddress.ts"() {
398
- "use strict";
399
- init_esm_shims();
400
- init_color();
401
- init_utils();
402
- IpAdress = class {
403
- imf = {
404
- protocol: "",
405
- port: 8e3,
406
- pathname: "/"
407
- };
408
- host = "0.0.0.0";
409
- urls = {
410
- lanUrlForConfig: "",
411
- lanUrlForTerminal: gray("unavailable"),
412
- localUrlForTerminal: "",
413
- localUrlForBrowser: ""
414
- };
415
- setup(o) {
416
- if (o.host) this.host = o.host;
417
- if (o.protocol) this.imf.protocol = o.protocol;
418
- if (o.pathname) this.imf.pathname = o.pathname;
419
- if (o.port) this.imf.port = o.port;
420
- this.setupUrls();
421
- }
422
- setupUrls() {
423
- const { host } = this;
424
- const isUnspecifiedHost = host === "0.0.0.0" || host === "::";
425
- let prettyHost;
426
- if (isUnspecifiedHost) {
427
- prettyHost = "localhost";
428
- try {
429
- this.urls.lanUrlForConfig = this.getLanIp();
430
- if (this.urls.lanUrlForConfig) {
431
- if (/^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(this.urls.lanUrlForConfig)) {
432
- this.urls.lanUrlForTerminal = this.prettyPrintUrl(this.urls.lanUrlForConfig);
433
- } else {
434
- this.urls.lanUrlForConfig = "";
435
- }
436
- }
437
- } catch (_e) {
438
- }
439
- } else {
440
- prettyHost = host;
441
- this.urls.lanUrlForConfig = host;
442
- this.urls.lanUrlForTerminal = this.prettyPrintUrl(this.urls.lanUrlForConfig);
443
- }
444
- this.urls.localUrlForTerminal = this.prettyPrintUrl(prettyHost);
445
- this.urls.localUrlForBrowser = this.formatUrl(prettyHost);
446
- }
447
- getLanIp = getLanIp;
448
- formatUrl(hostname) {
449
- const { protocol, port, pathname } = this.imf;
450
- return url.format({
451
- protocol,
452
- hostname,
453
- port,
454
- pathname
455
- });
456
- }
457
- prettyPrintUrl(hostname) {
458
- const { protocol, port, pathname } = this.imf;
459
- return url.format({
460
- protocol,
461
- hostname,
462
- port: chalk4.bold(port),
463
- pathname
464
- });
465
- }
466
- };
467
- ipAddress_default = new IpAdress();
468
- }
469
- });
470
-
471
- // src/helper/openBrowser.ts
472
- import { exec } from "child_process";
473
- import { promisify } from "util";
474
- var execAsync, supportedChromiumBrowsers, getTargetBrowser, openBrowser, openBrowser_default;
475
- var init_openBrowser = __esm({
476
- "src/helper/openBrowser.ts"() {
477
- "use strict";
478
- init_esm_shims();
479
- init_store();
480
- init_logger();
481
- execAsync = promisify(exec);
482
- supportedChromiumBrowsers = [
483
- "Google Chrome Canary",
484
- "Google Chrome Dev",
485
- "Google Chrome Beta",
486
- "Google Chrome",
487
- "Microsoft Edge",
488
- "Brave Browser",
489
- "Vivaldi",
490
- "Chromium"
491
- ];
492
- getTargetBrowser = async () => {
493
- let targetBrowser = process.env.BROWSER;
494
- if (!targetBrowser || !supportedChromiumBrowsers.includes(targetBrowser)) {
495
- const { stdout: ps } = await execAsync("ps cax");
496
- targetBrowser = supportedChromiumBrowsers.find((b) => ps.includes(b));
497
- }
498
- return targetBrowser;
499
- };
500
- openBrowser = async (url2) => {
501
- const shouldTryOpenChromeWithAppleScript = process.platform === "darwin";
502
- if (shouldTryOpenChromeWithAppleScript) {
503
- try {
504
- const targetBrowser = await getTargetBrowser();
505
- if (targetBrowser) {
506
- const c = `osascript openChrome.applescript "${encodeURI(url2)}" "${targetBrowser}"`;
507
- await execAsync(c, {
508
- cwd: store_default.resource.dir
509
- });
510
- return true;
511
- }
512
- } catch (err) {
513
- logger_default.debug(err);
514
- }
515
- }
516
- try {
517
- const { default: open } = await import("open");
518
- await open(url2);
519
- return true;
520
- } catch (err) {
521
- logger_default.error("Failed to open start URL.");
522
- logger_default.error(err);
523
- return false;
524
- }
525
- };
526
- openBrowser_default = openBrowser;
527
- }
528
- });
529
-
530
- // src/store/cycle/autoDevBase.ts
531
- var AutoDevBase, autoDevBase_default;
532
- var init_autoDevBase = __esm({
533
- "src/store/cycle/autoDevBase.ts"() {
534
- "use strict";
535
- init_esm_shims();
536
- init_getPort();
537
- init_ipAddress();
538
- init_utils();
539
- init_store();
540
- AutoDevBase = class {
541
- isADB = false;
542
- isHttps = false;
543
- get isHttpBase() {
544
- const base = store_default.empOptions.base || "";
545
- return base.indexOf("http://") > -1 || base.indexOf("https://") > -1;
546
- }
547
- async setup() {
548
- this.isADB = !!store_default.empOptions.autoDevBase && store_default.mode === "development" && !this.isHttpBase;
549
- if (!this.isADB) return;
550
- const { server, https: https2 } = store_default.empOptions.server || {};
551
- this.isHttps = server === "https" || typeof server === "object" && server.type === "https" || https2 === true;
552
- const host = ipAddress_default.getLanIp();
553
- const protocol = this.isHttps ? "https" : "http";
554
- let port = store_default.empOptions.server?.port || 8e3;
555
- port = await getPorts(port, host);
556
- store_default.empOptions.base = `${protocol}://${host}:${port}/`;
557
- store_default.empOptions.server = deepAssign(
558
- {
559
- // host: host,//允许所有host 访问
560
- port,
561
- client: { webSocketURL: `${this.isHttps ? "wss" : "ws"}://${host}:${port}/ws` }
562
- },
563
- store_default.empOptions.server
564
- );
565
- }
566
- };
567
- autoDevBase_default = new AutoDevBase();
568
- }
569
- });
570
-
571
- // src/script/base.ts
572
- import fs3 from "fs/promises";
573
- var BaseScript;
574
- var init_base = __esm({
575
- "src/script/base.ts"() {
576
- "use strict";
577
- init_esm_shims();
578
- init_color();
579
- init_getPort();
580
- init_ipAddress();
581
- init_logger();
582
- init_openBrowser();
583
- init_utils();
584
- init_store();
585
- init_autoDevBase();
586
- BaseScript = class {
587
- sf = {
588
- protocol: "http",
589
- host: "0.0.0.0",
590
- port: 8e3,
591
- publicPath: "",
592
- publicHasHttp: false,
593
- isOpenBrower: false,
594
- url: "",
595
- urls: { localUrlForBrowser: "", localUrlForTerminal: "", lanUrlForTerminal: "", lanUrlForConfig: "" }
596
- };
597
- static httpsType = "default";
598
- //重置服务信息
599
- async adaptServer() {
600
- this.sf.publicPath = store_default.rsConfig.output?.publicPath === "auto" ? "/" : store_default.rsConfig.output?.publicPath || "/";
601
- this.sf.isOpenBrower = !!store_default.empConfig.server.open;
602
- this.sf.protocol = this.isHttps ? "https" : "http";
603
- this.sf.host = store_default.empConfig.server.host ? store_default.empConfig.server.host : this.sf.host;
604
- this.sf.port = store_default.empConfig.server.port;
605
- await this.serverPort();
606
- ipAddress_default.setup(this.sf);
607
- if (this.sf.publicPath && (this.sf.publicPath.indexOf("http://") > -1 || this.sf.publicPath.indexOf("https://") > -1)) {
608
- this.sf.url = this.sf.publicPath;
609
- this.sf.publicHasHttp = true;
610
- this.sf.urls.localUrlForTerminal = ipAddress_default.prettyPrintUrl("localhost");
611
- } else {
612
- this.sf.urls = ipAddress_default.urls;
613
- this.sf.url = this.sf.urls.localUrlForBrowser;
614
- }
615
- }
616
- startOpen() {
617
- const { urls } = this.sf;
618
- if (this.sf.publicHasHttp) {
619
- logger_default.info(`${green("\u279C")} Local: ${logger_default.link(urls.localUrlForTerminal)}`);
620
- logger_default.info(`${green("\u279C")} Network: ${logger_default.link(this.sf.publicPath)}`);
621
- } else {
622
- logger_default.info(`${green("\u279C")} Local: ${logger_default.link(urls.localUrlForTerminal)}`);
623
- logger_default.info(`${green("\u279C")} Network: ${logger_default.link(urls.lanUrlForTerminal)}
624
- `);
625
- }
626
- if (this.sf.isOpenBrower) openBrowser_default(this.sf.url);
627
- }
628
- // 实现整体生命周期运转
629
- async setup(cliName, o) {
630
- logger_default.time(`[${cliName}]Setup`);
631
- await store_default.setup(cliName, o);
632
- if (store_default.debug.clearLog) {
633
- clearConsole();
634
- }
635
- logger_default.title(`${cliName}`);
636
- await this.adaptServer();
637
- logger_default.time(`[${cliName}]Run`);
638
- await this.run();
639
- logger_default.timeEnd(`[${cliName}]Run`);
640
- this.afterRun();
641
- logger_default.timeEnd(`[${cliName}]Setup`);
642
- }
643
- async run() {
644
- }
645
- afterRun() {
646
- process.on("SIGINT", function() {
647
- process.exit();
648
- });
649
- }
650
- get isHttps() {
651
- const { server, https: https2, http2 } = store_default.empConfig.server || {};
652
- return server === "https" || typeof server === "object" && server.type === "https" || https2 === true || http2 === true;
653
- }
654
- getcert() {
655
- return Promise.all([fs3.readFile(store_default.resource.key), fs3.readFile(store_default.resource.cert)]);
656
- }
657
- async serverPort() {
658
- if (autoDevBase_default.isADB) return;
659
- const { port, host } = this.sf;
660
- const serverPort = await getPorts(port, host);
661
- if (serverPort !== port) {
662
- this.sf.port = serverPort;
663
- if (store_default.rsConfig.devServer?.port) store_default.rsConfig.devServer.port = serverPort;
664
- }
665
- }
666
- };
667
- }
668
- });
669
-
670
- // src/store/empShare/index.ts
671
- var EMPShareLib;
672
- var init_empShare = __esm({
673
- "src/store/empShare/index.ts"() {
674
- "use strict";
675
- init_esm_shims();
676
- init_store();
677
- EMPShareLib = class {
678
- externals = {};
679
- externalAssets = { js: [], css: [] };
680
- exp = /^([0-9a-zA-Z_\s]+)@(.*)/;
681
- // 匹配库内容如 React@http://
682
- config;
683
- importMap = { imports: {} };
684
- // public version!: EMPShareType['mfVersion']
685
- isEmpshare = false;
686
- async setup() {
687
- if (store_default.empConfig.empShare.name || store_default.empConfig.empShare.fastMode?.runtimeHost) {
688
- this.isEmpshare = true;
689
- }
690
- this.config = store_default.empConfig.empShare;
691
- this.config.name = this.config.name ? this.config.name : store_default.uniqueName;
692
- if (store_default.empConfig.empShare.fastMode?.runtimeHost || store_default.empConfig.empShare.fastMode?.runtimeLib) {
693
- store_default.empConfig.empShareFastMode.setup();
694
- }
695
- if (this.config.shareLib) {
696
- this.setShareLib();
697
- }
698
- this.prepareEsm();
699
- }
700
- /**
701
- * 是否取用 importMap
702
- */
703
- get useImportMap() {
704
- return this.config.useImportMap && store_default.empConfig.isESM;
705
- }
706
- get pluginConfig() {
707
- const cf = { ...{}, ...this.config };
708
- delete cf.shareLib;
709
- delete cf.useImportMap;
710
- delete cf.fastMode;
711
- const sc = {
712
- manifest: false,
713
- dts: false,
714
- dev: {
715
- disableDynamicRemoteTypeHints: true
716
- },
717
- ...cf
718
- };
719
- return sc;
720
- }
721
- prepareEsm() {
722
- if (store_default.empConfig.isESM) {
723
- this.config.library = { type: "module" };
724
- const remotes = this.config.remotes || {};
725
- for (const [k, v] of Object.entries(remotes)) {
726
- if (typeof v === "string") {
727
- const cb = v.match(this.exp) || [];
728
- if (cb.length > 0) {
729
- remotes[k] = cb[2];
730
- }
731
- }
732
- }
733
- this.config.remotes = remotes;
734
- }
735
- }
736
- async setShareLib() {
737
- const mf = this.config;
738
- const externals = [];
739
- if (typeof mf.shareLib === "object") {
740
- for (const [k, v] of Object.entries(mf.shareLib)) {
741
- let externalsItem = {};
742
- externalsItem.module = k;
743
- if (typeof v === "string") {
744
- const cb = v.match(this.exp) || [];
745
- if (cb.length > 0) {
746
- externalsItem.global = cb[1];
747
- externalsItem.entry = cb[2];
748
- externalsItem.type = "js";
749
- externals.push(externalsItem);
750
- externalsItem = {};
751
- } else {
752
- externalsItem.global = "";
753
- externalsItem.entry = v;
754
- externalsItem.type = "js";
755
- externals.push(externalsItem);
756
- externalsItem = {};
757
- }
758
- } else if (Array.isArray(v)) {
759
- v.map((vo) => {
760
- if (!vo) return;
761
- const isCSS = vo.split("?")[0].endsWith(".css");
762
- if (isCSS) {
763
- externalsItem.entry = vo;
764
- externalsItem.type = "css";
765
- } else {
766
- const cb = vo.match(this.exp) || [];
767
- if (cb.length > 0) {
768
- externalsItem.global = cb[1];
769
- externalsItem.entry = cb[2];
770
- externalsItem.type = "js";
771
- } else {
772
- externalsItem.global = "";
773
- externalsItem.entry = vo;
774
- externalsItem.type = "js";
775
- }
776
- }
777
- externals.push(externalsItem);
778
- externalsItem = {};
779
- });
780
- } else if (typeof v === "object" && v.entry) {
781
- externalsItem.entry = v.entry;
782
- externalsItem.global = v.global;
783
- externalsItem.type = v.type;
784
- externals.push(externalsItem);
785
- externalsItem = {};
786
- }
787
- }
788
- }
789
- await Promise.all([this.setExternalAssets(externals)]);
790
- }
791
- async setExternalAssets(externals = []) {
792
- if (externals.length > 0) {
793
- let list = [];
794
- list = list.concat(externals);
795
- list.map((v) => {
796
- v.type = v.type || "js";
797
- if (v.type === "js" && v.module) {
798
- if (v.global) {
799
- this.externals[v.module] = v.global;
800
- } else if (store_default.empConfig.isESM) {
801
- if (!this.useImportMap) {
802
- this.externals[v.module] = v.entry;
803
- } else {
804
- this.externals[v.module] = v.module;
805
- this.importMap.imports[v.module] = v.entry;
806
- }
807
- }
808
- if (v.entry && !store_default.empConfig.isESM) {
809
- this.externalAssets.js.push(v.entry);
810
- }
811
- } else if (v.type === "css" && v.entry) {
812
- this.externalAssets.css.push(v.entry);
813
- }
814
- });
815
- }
816
- }
817
- };
818
- }
819
- });
820
-
821
- // src/store/empShare/fastMode.ts
822
- var EmpShareFastMode;
823
- var init_fastMode = __esm({
824
- "src/store/empShare/fastMode.ts"() {
825
- "use strict";
826
- init_esm_shims();
827
- init_store();
828
- EmpShareFastMode = class {
829
- fastMode = {
830
- runtimeHost: "",
831
- runtimeLib: "",
832
- externals: {},
833
- globalVal: "EMP_ADAPTER",
834
- framework: "react"
835
- };
836
- externalMF = {
837
- "@module-federation/runtime": `MFRuntime`,
838
- "@module-federation/sdk": `MFSDK`
839
- };
840
- externalReact = {
841
- react: `React`,
842
- "react-dom": `ReactDOM`,
843
- "react-router-dom": `ReactRouterDOM`
844
- };
845
- externals = {};
846
- getRuntimeLib(runtimeHost) {
847
- return `${runtimeHost}/runtime${store_default.mode === "development" ? ".development" : ""}.umd.js`;
848
- }
849
- setup() {
850
- this.fastMode = store_default.deepAssign(this.fastMode, store_default.empConfig.empShare.fastMode);
851
- this.injectLib();
852
- this.setExternals();
853
- }
854
- injectLib() {
855
- const { runtimeHost, runtimeLib } = this.fastMode;
856
- if (runtimeHost || runtimeLib) {
857
- const lib = runtimeLib ? runtimeLib : this.getRuntimeLib(runtimeHost);
858
- store_default.empConfig.empShareLib.externalAssets.js.push(lib);
859
- }
860
- }
861
- setExternals() {
862
- for (const [key, value] of Object.entries(this.externalMF)) {
863
- this.externals[key] = `${this.fastMode.globalVal}.${value}`;
864
- }
865
- if (this.fastMode.framework === "react") {
866
- for (const [key, value] of Object.entries(this.externalReact)) {
867
- this.externals[key] = `${this.fastMode.globalVal}.${value}`;
868
- }
869
- }
870
- if (Object.entries(this.fastMode.externals).length > 0) {
871
- this.externals = store_default.deepAssign(this.externals, this.fastMode.externals);
872
- }
873
- store_default.empConfig.empShareLib.externals = store_default.deepAssign(store_default.empConfig.empShareLib.externals, this.externals);
874
- }
875
- };
876
- }
877
- });
878
-
879
- // src/store/chain.ts
880
- var chainName;
881
- var init_chain = __esm({
882
- "src/store/chain.ts"() {
883
- "use strict";
884
- init_esm_shims();
885
- chainName = {
886
- rule: {
887
- mjs: "mjs",
888
- typescript: "typescript",
889
- javascript: "javascript",
890
- sourceMap: "sourceMapLoader",
891
- inline: "inline",
892
- svg: "svg",
893
- image: "image",
894
- font: "fonts",
895
- svga: "svga",
896
- sass: "sass",
897
- less: "less",
898
- css: "css"
899
- },
900
- use: {
901
- swc: "swc",
902
- sourceMap: "sourceMapLoader",
903
- sass: "sassLoader",
904
- less: "lessLoader"
905
- },
906
- plugin: {
907
- bundleAnalyzer: "bundleAnalyzerPlugin",
908
- define: "definePlugin",
909
- copy: "copyRspackPlugin",
910
- progress: "progressPlugin",
911
- empShare: "empShare",
912
- html: {
913
- prefix: "html-plugin-",
914
- empSharePrefix: "html-plugin-empShare-",
915
- importMapPrefix: "html-plugin-import-map-",
916
- hooks: {
917
- empShareLib: "HtmlEmpShareLibPluginName",
918
- importMap: "HtmlImportMapPlugin"
919
- }
920
- },
921
- rsdoctor: "rsdoctor"
922
- },
923
- minimizer: {
924
- minJs: "minJs",
925
- minCss: "minCss"
926
- }
927
- };
928
- }
929
- });
930
-
931
- // src/store/rspack/hook.ts
932
- import HtmlWebpackPlugin from "html-webpack-plugin";
933
- var HtmlImportMapPluginName, HtmlImportMapPlugin, HtmlEmpShareLibPluginName, HtmlEmpShareLibPlugin, getPolyfillEntry, EmpPolyfillPlugin;
934
- var init_hook = __esm({
935
- "src/store/rspack/hook.ts"() {
936
- "use strict";
937
- init_esm_shims();
938
- init_utils();
939
- init_store();
940
- init_chain();
941
- HtmlImportMapPluginName = chainName.plugin.html.hooks.importMap;
942
- HtmlImportMapPlugin = class {
943
- importMap;
944
- chunk;
945
- constructor(importMap, chunk) {
946
- this.importMap = importMap;
947
- this.chunk = chunk;
948
- }
949
- apply(compiler) {
950
- compiler.hooks.compilation.tap(HtmlImportMapPluginName, (compilation) => {
951
- HtmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tapAsync(HtmlImportMapPluginName, (data, cb) => {
952
- if (!data.plugin.userOptions.chunks?.includes(this.chunk)) return cb(null, data);
953
- data.headTags.push({
954
- tagName: "script",
955
- attributes: { type: "importmap" },
956
- innerHTML: `${JSON.stringify(this.importMap, null, 2)}`,
957
- voidTag: false,
958
- meta: {
959
- plugin: void 0
960
- }
961
- });
962
- cb(null, data);
963
- });
964
- });
965
- }
966
- };
967
- HtmlEmpShareLibPluginName = chainName.plugin.html.hooks.empShareLib;
968
- HtmlEmpShareLibPlugin = class {
969
- chunk;
970
- files;
971
- constructor(files, chunk) {
972
- this.files = deepAssign({ js: [], css: [] }, files);
973
- this.chunk = chunk;
974
- }
975
- apply(compiler) {
976
- compiler.hooks.compilation.tap(HtmlEmpShareLibPluginName, (compilation) => {
977
- const files = this.files;
978
- HtmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tapAsync(HtmlEmpShareLibPluginName, (data, cb) => {
979
- if (!data.plugin.userOptions.chunks?.includes(this.chunk)) return cb(null, data);
980
- files.js.map((js) => {
981
- data.headTags.push({
982
- tagName: "script",
983
- attributes: { src: js },
984
- voidTag: false,
985
- meta: {
986
- plugin: void 0
987
- }
988
- });
989
- });
990
- files.css.map((css) => {
991
- data.headTags.push({
992
- tagName: "link",
993
- attributes: { rel: "stylesheet", href: css },
994
- voidTag: false,
995
- meta: {
996
- plugin: void 0
997
- }
998
- });
999
- });
1000
- cb(null, data);
1001
- });
1002
- });
1003
- }
1004
- };
1005
- getPolyfillEntry = () => {
1006
- const content = [`import 'core-js/${store_default.empConfig.build.coreJsFeatures}'`].join("\n");
1007
- return importJsVm(content);
1008
- };
1009
- EmpPolyfillPlugin = class {
1010
- constructor() {
1011
- }
1012
- apply(compiler) {
1013
- const { webpack } = compiler;
1014
- new webpack.EntryPlugin(compiler.context, getPolyfillEntry(), {
1015
- name: void 0
1016
- }).apply(compiler);
1017
- }
1018
- };
1019
- }
1020
- });
1021
-
1022
- // src/store/lifeCycle.ts
1023
- var LifeCycle;
1024
- var init_lifeCycle = __esm({
1025
- "src/store/lifeCycle.ts"() {
1026
- "use strict";
1027
- init_esm_shims();
1028
- init_store();
1029
- init_autoDevBase();
1030
- init_hook();
1031
- LifeCycle = class {
1032
- op = {};
1033
- constructor(op = {}) {
1034
- this.op = op;
1035
- }
1036
- /**
1037
- * 获取 empOptions 之后、初始化 empConfig 之前
1038
- */
1039
- async afterGetEmpOptions() {
1040
- await autoDevBase_default.setup();
1041
- if (this.op.afterGetEmpOptions) await this.op.afterGetEmpOptions();
1042
- }
1043
- /**
1044
- * RspackPlugin 插件执行之前
1045
- */
1046
- async beforePlugin() {
1047
- if (store_default.empConfig.build.polyfill === "entry") {
1048
- store_default.chain.plugin("empPolyfill").use(EmpPolyfillPlugin);
1049
- }
1050
- if (this.op.beforePlugin) await this.op.beforePlugin();
1051
- }
1052
- /**
1053
- * RspackPlugin 插件执行之后
1054
- */
1055
- async afterPlugin() {
1056
- if (this.op.afterPlugin) await this.op.afterPlugin();
1057
- }
1058
- /**
1059
- * RspackModule 插件执行之后
1060
- */
1061
- async beforeModule() {
1062
- if (this.op.beforeModule) await this.op.beforeModule();
1063
- }
1064
- /**
1065
- * RspackModule 插件执行之后
1066
- */
1067
- async afterModule() {
1068
- if (this.op.afterModule) await this.op.afterModule();
1069
- }
1070
- /**
1071
- * empPlugin 插件执行之前
1072
- */
1073
- async beforeEmpPlugin() {
1074
- if (this.op.beforeEmpPlugin) await this.op.beforeEmpPlugin();
1075
- }
1076
- /**
1077
- * empPlugin 插件执行之后
1078
- */
1079
- async afterEmpPlugin() {
1080
- if (this.op.afterEmpPlugin) await this.op.afterEmpPlugin();
1081
- }
1082
- /**
1083
- * 产物构建完成前
1084
- */
1085
- async beforeBuild() {
1086
- if (this.op.beforeBuild) await this.op.beforeBuild();
1087
- }
1088
- /**
1089
- * 产物构建完成后
1090
- */
1091
- async afterBulid() {
1092
- if (this.op.afterBulid) await this.op.afterBulid();
1093
- }
1094
- /**
1095
- * devServer启动前
1096
- */
1097
- async beforeDevServe() {
1098
- if (this.op.beforeDevServe) await this.op.beforeDevServe();
1099
- }
1100
- /**
1101
- * devServer启动后
1102
- */
1103
- async afterDevServe() {
1104
- if (this.op.afterDevServe) await this.op.afterDevServe();
1105
- }
1106
- /**
1107
- * server启动前
1108
- */
1109
- async beforeServe() {
1110
- if (this.op.beforeServe) await this.op.beforeServe();
1111
- }
1112
- /**
1113
- * server启动后
1114
- */
1115
- async afterServe() {
1116
- if (this.op.afterServe) await this.op.afterServe();
1117
- }
1118
- };
1119
- }
1120
- });
1121
-
1122
- // src/store/empConfig.ts
1123
- import fs4 from "fs";
1124
- var EmpConfig, empConfig_default;
1125
- var init_empConfig = __esm({
1126
- "src/store/empConfig.ts"() {
1127
- "use strict";
1128
- init_esm_shims();
1129
- init_helper();
1130
- init_loadConfig();
1131
- init_utils();
1132
- init_base();
1133
- init_empShare();
1134
- init_fastMode();
1135
- init_lifeCycle();
1136
- EmpConfig = class {
1137
- store;
1138
- /**
1139
- * 项目代码路径
1140
- * @default 'src'
1141
- */
1142
- appSrc = "src";
1143
- /**
1144
- * 项目代码入口文件 如 `src/index.js`
1145
- * (*)entries 设置后 该选项失效
1146
- * @default 'index.js'
1147
- */
1148
- appEntry = "";
1149
- /**
1150
- * publicPath 根路径 可参考webpack,业务模式默认为 auto
1151
- * html 部分 publicPath 默认为 undefined,可设置全量域名或子目录适配,也可以单独在html设置 Public
1152
- *
1153
- * @default undefined
1154
- */
1155
- base = "";
1156
- target = [];
1157
- assign(t, s) {
1158
- s = s || {};
1159
- return deepAssign(t, s);
1160
- }
1161
- //
1162
- empShareFastMode = new EmpShareFastMode();
1163
- empShareLib = new EMPShareLib();
1164
- /**
1165
- * 是否启动 esm 模块
1166
- * @default true
1167
- */
1168
- isESM = false;
1169
- async autoDevSet() {
1170
- if (this.store.mode === "development" && this.store.empOptions.autoDevBase) {
1171
- }
1172
- }
1173
- checkIsESM(target) {
1174
- return ["es3", "es5"].indexOf(target) === -1;
1175
- }
1176
- lifeCycle;
1177
- async setup(store) {
1178
- this.store = store;
1179
- await this.syncEmpOptions();
1180
- this.lifeCycle = new LifeCycle(this.store.empOptions.lifeCycle);
1181
- await this.lifeCycle.afterGetEmpOptions();
1182
- this.isESM = this.checkIsESM(this.build.target);
1183
- if (this.store.empOptions.target) {
1184
- this.target = this.store.empOptions.target;
1185
- if (Array.isArray(this.target) && !this.target.includes(this.build.target)) {
1186
- this.target.push(this.build.target);
1187
- }
1188
- } else {
1189
- this.target = ["web", this.build.target];
1190
- }
1191
- const { appSrc, base, appEntry } = this.store.empOptions;
1192
- if (appSrc) this.appSrc = appSrc;
1193
- if (base) this.base = base;
1194
- if (appEntry) this.appEntry = appEntry;
1195
- if (this.store.empConfig.empShare) {
1196
- await this.empShareLib.setup();
1197
- }
1198
- }
1199
- async chain() {
1200
- if (this.store.empOptions.chain) {
1201
- await this.store.empOptions.chain(this.store.chain);
1202
- }
1203
- }
1204
- async plugins() {
1205
- const runPromiseFuns = [];
1206
- if (this.store.empOptions.plugins && Array.isArray(this.store.empOptions.plugins) && this.store.empOptions.plugins.length > 0) {
1207
- this.store.empOptions.plugins.map((fn) => {
1208
- runPromiseFuns.push(fn.rsConfig(this.store));
1209
- });
1210
- await Promise.all(runPromiseFuns);
1211
- }
1212
- }
1213
- get debug() {
1214
- let rsdoctor = false;
1215
- if (this.store.cliOptions.doctor) {
1216
- rsdoctor = {
1217
- supports: {
1218
- generateTileGraph: true
1219
- }
1220
- };
1221
- }
1222
- return this.assign(
1223
- {
1224
- loggerLevel: "info",
1225
- clearLog: true,
1226
- progress: true,
1227
- showRsconfig: false,
1228
- showPerformance: false,
1229
- rspackCache: true,
1230
- rsdoctor,
1231
- infrastructureLogging: {
1232
- appendOnly: true,
1233
- level: "warn"
1234
- },
1235
- newTreeshaking: this.store.empConfig.isESM
1236
- },
1237
- this.store.empOptions.debug
1238
- );
1239
- }
1240
- get build() {
1241
- const staticDir = this.store.empOptions.build?.staticDir ? `${this.store.empOptions.build?.staticDir}/` : "";
1242
- return this.assign(
1243
- {
1244
- outDir: "dist",
1245
- staticDir,
1246
- assetsDir: "assets",
1247
- publicDir: "public",
1248
- chunkIds: this.store.isDev ? "named" : "deterministic",
1249
- moduleIds: this.store.isDev ? "named" : "deterministic",
1250
- sourcemap: this.store.isDev,
1251
- minify: !this.store.isDev,
1252
- minOptions: {},
1253
- cssminOptions: {},
1254
- target: "es5",
1255
- polyfill: false,
1256
- // polyfillInclude: ['es.object.values', 'es.object.entries', 'es.array.flat'],
1257
- polyfillInclude: [],
1258
- coreJsFeatures: "stable",
1259
- externalHelpers: false,
1260
- browserslist: this.store.browserslistOptions.default,
1261
- swcConfig: {},
1262
- devtool: "source-map"
1263
- },
1264
- { ...this.store.empOptions.build, staticDir }
1265
- );
1266
- }
1267
- get html() {
1268
- const meta = this.store.empOptions.html?.template ? {} : {
1269
- charset: { charset: "utf-8" },
1270
- "http-equiv": { "http-equiv": "X-UA-Compatible", content: "IE=edge" },
1271
- viewport: {
1272
- name: "viewport",
1273
- content: "width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0"
1274
- },
1275
- keywords: { keywords: "" },
1276
- description: { description: "" }
1277
- };
1278
- const op = this.assign(
1279
- {
1280
- lang: "zh-CN",
1281
- title: "EMP",
1282
- inject: "body",
1283
- minify: !this.store.isDev,
1284
- scriptLoading: !this.isESM ? "defer" : "module",
1285
- meta,
1286
- files: {
1287
- css: [],
1288
- js: []
1289
- },
1290
- tags: {
1291
- headTags: [],
1292
- bodyTags: []
1293
- }
1294
- },
1295
- this.store.empOptions.html
1296
- );
1297
- return op;
1298
- }
1299
- get entries() {
1300
- return this.store.empOptions.entries ? this.store.empOptions.entries : {};
1301
- }
1302
- get server() {
1303
- const sf = {
1304
- host: `0.0.0.0`,
1305
- port: 8e3,
1306
- open: process.platform === "darwin",
1307
- // open: false,
1308
- // liveReload: false,
1309
- hot: true,
1310
- watchFiles: ["src/**/*.html"],
1311
- static: [
1312
- {
1313
- directory: this.store.publicDir,
1314
- watch: this.store.isDev
1315
- }
1316
- // 暴露 d.ts 文件
1317
- /* {
1318
- directory: this.store.outDir,
1319
- watch: this.store.isDev,
1320
- publicPath: this.base,
1321
- staticOptions: {
1322
- setHeaders: function (res: any, path: string) {
1323
- if (path.toString().endsWith('.d.ts')) res?.set('Content-Type', 'application/javascript; charset=utf-8')
1324
- },
1325
- },
1326
- }, */
1327
- ],
1328
- allowedHosts: ["all"],
1329
- historyApiFallback: true,
1330
- headers: {
1331
- "Access-Control-Allow-Origin": "*",
1332
- "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS",
1333
- "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization"
1334
- }
1335
- // client: {
1336
- // webSocketURL: 'ws://172.29.104.208:8000/ws',
1337
- // },
1338
- };
1339
- if (this.store.empOptions.server?.http2) {
1340
- BaseScript.httpsType = "h2";
1341
- delete this.store.empOptions.server.http2;
1342
- }
1343
- return this.assign(sf, this.store.empOptions.server);
1344
- }
1345
- get empShare() {
1346
- return this.assign({ name: "", filename: "emp.js", shared: {} }, this.store.empOptions.empShare);
1347
- }
1348
- get css() {
1349
- return this.assign({ sass: { mode: "modern", warnRuleAsWarning: false } }, this.store.empOptions.css);
1350
- }
1351
- get output() {
1352
- const contenthashName = !this.store.isDev ? ".[contenthash:8]" : ".[contenthash:8]";
1353
- const cssContentHashName = !this.store.isDev ? ".[contenthash:8]" : "";
1354
- const { assetsDir, staticDir } = this.store.empConfig.build;
1355
- const output = {
1356
- publicPath: this.store.empConfig.base ? this.store.empConfig.base : "auto",
1357
- // publicPath: this.base,
1358
- crossOriginLoading: "anonymous",
1359
- filename: `${staticDir}js/[name]${contenthashName}.js`,
1360
- cssFilename: `${staticDir}css/[name]${cssContentHashName}.css`,
1361
- cssChunkFilename: `${staticDir}css/[name]${cssContentHashName}.css`,
1362
- assetModuleFilename: `${staticDir}${assetsDir}/[name]${contenthashName}[ext][query]`,
1363
- path: this.store.outDir,
1364
- clean: true,
1365
- uniqueName: this.store.uniqueName
1366
- };
1367
- return this.assign(output, this.store.empOptions.output);
1368
- }
1369
- get define() {
1370
- let dlist = { mode: this.store.mode, env: this.store.cliOptions.env };
1371
- if (this.store.empOptions.define) {
1372
- dlist = { ...dlist, ...this.store.empOptions.define };
1373
- }
1374
- return this.setDefine(dlist);
1375
- }
1376
- setDefine(o) {
1377
- const defineFix = this.store.empOptions.defineFix ? this.store.empOptions.defineFix : this.isESM ? "esm" : "cjs";
1378
- const options = {};
1379
- Object.keys(o).map((key) => {
1380
- if (defineFix === "all") {
1381
- options[`import.meta.env.${key}`] = JSON.stringify(o[key]);
1382
- options[`process.env.${key}`] = JSON.stringify(o[key]);
1383
- } else if (defineFix === "esm") {
1384
- options[`import.meta.env.${key}`] = JSON.stringify(o[key]);
1385
- } else if (defineFix === "cjs") {
1386
- options[`process.env.${key}`] = JSON.stringify(o[key]);
1387
- } else if (defineFix === "none") {
1388
- options[`${key}`] = JSON.stringify(o[key]);
1389
- }
1390
- });
1391
- return options;
1392
- }
1393
- get externals() {
1394
- const o = this.assign(this.empShareLib.externals, this.store.empOptions.externals);
1395
- return o;
1396
- }
1397
- get resolve() {
1398
- const rl = deepAssign(
1399
- {
1400
- alias: {
1401
- src: this.store.resolve("src"),
1402
- "@": this.store.resolve("src")
1403
- },
1404
- extensions: [
1405
- "...",
1406
- ".js",
1407
- ".jsx",
1408
- ".mjs",
1409
- ".ts",
1410
- ".tsx",
1411
- ".css",
1412
- ".less",
1413
- ".scss",
1414
- ".sass",
1415
- ".json",
1416
- ".wasm",
1417
- ".vue",
1418
- ".svg",
1419
- ".svga"
1420
- ]
1421
- },
1422
- this.store.empOptions.resolve
1423
- );
1424
- return rl;
1425
- }
1426
- async syncEmpOptions() {
1427
- logger_default.time("[store][empConfig]SyncEmpOptions");
1428
- const empConfigPath = await getEmpConfigPath();
1429
- if (!empConfigPath || !fs4.existsSync(empConfigPath)) return;
1430
- const empOptionsFn = await loadConfig(empConfigPath);
1431
- if (typeof empOptionsFn === "function") {
1432
- this.store.empOptions = await empOptionsFn(this.store);
1433
- } else {
1434
- this.store.empOptions = empOptionsFn || {};
1435
- }
1436
- logger_default.timeEnd("[store][empConfig]SyncEmpOptions");
1437
- }
1438
- get moduleTransformRule() {
1439
- const { moduleTransform } = this.store.empOptions;
1440
- const tf = this.assign({ defaultExclude: false }, moduleTransform);
1441
- const moduleTransformExclude = { and: [], not: [] };
1442
- if (tf.defaultExclude === true) {
1443
- moduleTransformExclude.and.push(/(node_modules|bower_components)/);
1444
- }
1445
- if (tf?.exclude) {
1446
- moduleTransformExclude.and = moduleTransformExclude.and.concat(tf.exclude);
1447
- }
1448
- if (moduleTransform?.include) {
1449
- moduleTransformExclude.not = tf.include;
1450
- }
1451
- return moduleTransformExclude;
1452
- }
1453
- get cacheDir() {
1454
- return this.store.empOptions.cacheDir ? this.store.empOptions.cacheDir : "node_modules/.emp-cache";
1455
- }
1456
- get ignoreWarnings() {
1457
- return this.store.empOptions.ignoreWarnings ? this.store.empOptions.ignoreWarnings : [/Conflicting order/];
1458
- }
1459
- get autoPages() {
1460
- let autoPages = void 0;
1461
- if (this.store.empOptions.autoPages) {
1462
- autoPages = typeof this.store.empOptions.autoPages === "boolean" ? {} : this.store.empOptions.autoPages;
1463
- autoPages = this.assign({ path: "pages" }, autoPages);
1464
- }
1465
- return autoPages;
1466
- }
1467
- };
1468
- empConfig_default = new EmpConfig();
1469
- }
1470
- });
1471
-
1472
- // src/store/rspack/common.ts
1473
- import fs5 from "fs-extra";
1474
- var RspackCommon, common_default;
1475
- var init_common = __esm({
1476
- "src/store/rspack/common.ts"() {
1477
- "use strict";
1478
- init_esm_shims();
1479
- RspackCommon = class {
1480
- store;
1481
- async setup(store) {
1482
- this.store = store;
1483
- const runFuns = [
1484
- this.common(),
1485
- this.stats(),
1486
- this.devServer(),
1487
- // this.assets(),
1488
- this.optimization(),
1489
- this.checkTsconfig()
1490
- ];
1491
- await Promise.all(runFuns);
1492
- }
1493
- async common() {
1494
- this.store.merge({
1495
- node: {
1496
- global: true
1497
- },
1498
- experiments: {
1499
- // rspackFuture: {
1500
- // // disableTransformByDefault: false, // 开启默认转换
1501
- // // 移除 experiments.rspackFuture.disableApplyEntryLazily
1502
- // // disableApplyEntryLazily: true,
1503
- // // rspack 0.6 默认开启新版 tree shaking
1504
- // newTreeshaking: this.store.empConfig.debug.newTreeshaking, // 该功能启用了与 webpack 相同的新摇树优化实现,可以生成更高效和更小的代码。
1505
- // },
1506
- outputModule: this.store.empConfig.isESM,
1507
- //将尽可能输出符合 ECMAScript 语法的代码
1508
- topLevelAwait: true,
1509
- // lazyCompilation: this.store.isDev, // 开启懒编译功能
1510
- // lazyCompilation: {
1511
- // imports: true,
1512
- // entries: true,
1513
- // test(module: any) {
1514
- // console.log(module)
1515
- // const isMyClient = module.nameForCondition().endsWith('reactRefreshEntry.js')
1516
- // console.log(module, isMyClient)
1517
- // return !isMyClient
1518
- // },
1519
- // },
1520
- css: true
1521
- },
1522
- target: this.store.empConfig.target,
1523
- // default [web,es5]
1524
- infrastructureLogging: this.store.empConfig.debug.infrastructureLogging,
1525
- context: this.store.root,
1526
- mode: this.store.mode,
1527
- cache: this.store.empConfig.debug.rspackCache,
1528
- // devtool: this.store.empConfig.build.sourcemap ? 'source-map' : false, //Recommended
1529
- devtool: this.store.empConfig.build.sourcemap ? this.store.empConfig.build.devtool : false,
1530
- //Recommended
1531
- // builtins: {
1532
- // /**
1533
- // 'builtins.devFriendlySplitChunks = true' has been deprecated, please switch to 'builtins.devFriendlySplitChunks = false' to use webpack's behavior.
1534
- // Set env `RSPACK_DEP_WARNINGS` to 'false' to temporarily disable deprecation warnings.
1535
- // */
1536
- // // devFriendlySplitChunks: true,
1537
- // // css: {
1538
- // // modules: {
1539
- // // // exportsOnly: false,
1540
- // // localIdentName: this.store.isDev ? '[path][name]-[local]-[hash:5]' : '[local]-[hash:5]',
1541
- // // },
1542
- // // },
1543
- // },
1544
- output: this.store.empConfig.output,
1545
- resolve: this.store.empConfig.resolve,
1546
- externals: this.store.empConfig.externals,
1547
- ignoreWarnings: this.store.empConfig.ignoreWarnings,
1548
- watchOptions: {
1549
- ignored: ["**/node_modules/**", "**/@mf-types/**"]
1550
- }
1551
- });
1552
- }
1553
- async checkTsconfig() {
1554
- const tsconfigPath = this.store.resolve("tsconfig.json");
1555
- const isExist = await fs5.exists(tsconfigPath);
1556
- if (isExist) {
1557
- const resolve = {
1558
- // tsconfig: {
1559
- // configFile: tsconfigPath,
1560
- // references: 'auto',
1561
- // },
1562
- // tsConfigPath: tsconfigPath,
1563
- tsConfig: tsconfigPath
1564
- };
1565
- this.store.merge({ resolve });
1566
- }
1567
- }
1568
- async stats() {
1569
- this.store.merge({
1570
- stats: {
1571
- colors: true,
1572
- all: false,
1573
- assets: false,
1574
- chunks: false,
1575
- timings: true,
1576
- version: true
1577
- }
1578
- });
1579
- }
1580
- async devServer() {
1581
- this.store.merge({
1582
- devServer: this.store.empConfig.server
1583
- });
1584
- }
1585
- /* async assets() {
1586
- this.store.chain.merge({
1587
- module: {
1588
- rule: {
1589
- assets: {
1590
- test: /\.(png|jpe?g|gif|webp|ico|otf|ttf|eot|woff|woff2|svga)$/i,
1591
- type: 'asset/resource',
1592
- },
1593
- },
1594
- },
1595
- })
1596
- } */
1597
- async optimization() {
1598
- const optimization = {
1599
- // moduleIds: 'named',
1600
- // chunkIds: 'named',
1601
- moduleIds: this.store.empConfig.build.moduleIds,
1602
- chunkIds: this.store.empConfig.build.chunkIds,
1603
- minimize: this.store.empConfig.build.minify,
1604
- splitChunks: {
1605
- chunks: "async",
1606
- // chunks: 'all',
1607
- cacheGroups: {
1608
- // defaultVendors: {
1609
- // filename: 'vendors-[name].js',
1610
- // enforce: true,
1611
- // },
1612
- }
1613
- }
1614
- };
1615
- if (this.store.empConfig.build.polyfill) {
1616
- optimization.splitChunks.cacheGroups = {
1617
- // empShare: {
1618
- // test: /[\\/]node_modules[\\/](@module-federation)[\\/]/,
1619
- // name: 'empShare',
1620
- // chunks: 'all',
1621
- // },
1622
- // coreJs: {
1623
- // test: /[\\/]node_modules[\\/](core-js)[\\/]/,
1624
- // name: 'coreJs',
1625
- // chunks: 'all',
1626
- // enforce: true,
1627
- // },
1628
- };
1629
- }
1630
- this.store.chain.merge({
1631
- optimization
1632
- });
1633
- }
1634
- };
1635
- common_default = new RspackCommon();
1636
- }
1637
- });
1638
-
1639
- // src/store/rspack/css.ts
1640
- var RspackCss, css_default;
1641
- var init_css = __esm({
1642
- "src/store/rspack/css.ts"() {
1643
- "use strict";
1644
- init_esm_shims();
1645
- RspackCss = class {
1646
- store;
1647
- async setup(store) {
1648
- this.store = store;
1649
- const runFuns = [this.sass(), this.less(), this.css()];
1650
- await Promise.all(runFuns);
1651
- }
1652
- async sass() {
1653
- const { rule, use } = this.store.chainName;
1654
- const options = {};
1655
- const { sass } = this.store.empConfig.css || { sass: {} };
1656
- if (sass.mode === "modern") {
1657
- options.implementation = sass.implementation ? sass.implementation : __require.resolve("sass-embedded");
1658
- options.api = sass.api ? sass.api : "legacy";
1659
- options.sourceMap = this.store.empConfig.build.sourcemap;
1660
- if (sass.sassOptions) options.sassOptions = sass.sassOptions;
1661
- }
1662
- if (typeof sass.warnRuleAsWarning !== "undefined") {
1663
- options.warnRuleAsWarning = sass.warnRuleAsWarning;
1664
- }
1665
- if (typeof sass.webpackImporter !== "undefined") {
1666
- options.webpackImporter = sass.webpackImporter;
1667
- }
1668
- this.store.chain.merge({
1669
- module: {
1670
- rule: {
1671
- [rule.sass]: {
1672
- test: /\.(sass|scss)$/,
1673
- use: {
1674
- [use.sass]: {
1675
- loader: __require.resolve("sass-loader"),
1676
- options
1677
- }
1678
- },
1679
- type: "css/auto"
1680
- }
1681
- }
1682
- }
1683
- });
1684
- }
1685
- async less() {
1686
- const { rule, use } = this.store.chainName;
1687
- const lessLoader = {
1688
- loader: __require.resolve("less-loader"),
1689
- options: {
1690
- lessOptions: {
1691
- javascriptEnabled: true
1692
- }
1693
- }
1694
- };
1695
- this.store.chain.merge({
1696
- module: {
1697
- rule: {
1698
- [rule.less]: {
1699
- test: /\.less$/,
1700
- use: {
1701
- [use.less]: lessLoader
1702
- },
1703
- type: "css/auto"
1704
- }
1705
- }
1706
- }
1707
- });
1708
- }
1709
- async css() {
1710
- const { rule } = this.store.chainName;
1711
- this.store.chain.merge({
1712
- module: {
1713
- rule: {
1714
- [rule.css]: {
1715
- test: /\.css$/,
1716
- use: {},
1717
- type: "css/auto"
1718
- }
1719
- }
1720
- }
1721
- });
1722
- }
1723
- };
1724
- css_default = new RspackCss();
1725
- }
1726
- });
1727
-
1728
- // src/store/rspack/entries.ts
1729
- import path3 from "path";
1730
- import HtmlWebpackPlugin2 from "html-webpack-plugin";
1731
- var RspackEntries, entries_default;
1732
- var init_entries = __esm({
1733
- "src/store/rspack/entries.ts"() {
1734
- "use strict";
1735
- init_esm_shims();
1736
- init_helper();
1737
- init_utils();
1738
- init_hook();
1739
- RspackEntries = class {
1740
- store;
1741
- entriesConfig = {};
1742
- async setup(store) {
1743
- this.store = store;
1744
- await this.init();
1745
- this.toConfig();
1746
- }
1747
- setHtmlConfig(c, chunks) {
1748
- c.template = this.setTemplate(c.template);
1749
- c.favicon = this.setFavicion(c.favicon);
1750
- c.chunks = chunks;
1751
- c.filename = `${chunks[0]}.html`;
1752
- if (this.store.empConfig.base) c.publicPath = this.store.empConfig.base;
1753
- c.tags = c.tags || {};
1754
- return c;
1755
- }
1756
- /**
1757
- * chunk name 格式化 去除 后缀
1758
- * @param filename
1759
- * @returns
1760
- */
1761
- setChunk(filename) {
1762
- return filename.replace(path3.extname(filename), "").replace(`${this.store.empConfig.appSrc}${path3.sep}`, "");
1763
- }
1764
- setTemplate(template) {
1765
- return template ? this.store.resolve(template) : this.store.empResolve(path3.join("template", "index.html"));
1766
- }
1767
- setFavicion(favicon) {
1768
- return favicon ? this.store.resolve(favicon) : this.store.empResolve(path3.join("template", "favicon.ico"));
1769
- }
1770
- /**
1771
- *
1772
- * @param filename 文件名
1773
- * @param op html plugin 配置
1774
- * @param absPath 文件 绝对路径
1775
- */
1776
- setEntryItem(filename, op, absPath) {
1777
- absPath = absPath ? absPath : this.store.resolve(path3.join(this.store.empConfig.appSrc, filename));
1778
- const chunkName = this.setChunk(filename);
1779
- const chunks = [absPath];
1780
- this.entriesConfig[chunkName] = {
1781
- entry: { [chunkName]: chunks },
1782
- html: this.setHtmlConfig(op, [chunkName])
1783
- };
1784
- this.store.entries[chunkName] = chunks;
1785
- }
1786
- setRspackHtmlPlugin(config, chunk) {
1787
- this.store.chain.plugin(`${this.store.chainName.plugin.html.prefix}${chunk}`).use(HtmlWebpackPlugin2, [config]);
1788
- if (this.store.empConfig.empShareLib)
1789
- config.files = deepAssign(config.files, this.store.empConfig.empShareLib.externalAssets);
1790
- this.store.chain.plugin(`${this.store.chainName.plugin.html.empSharePrefix}${chunk}`).use(HtmlEmpShareLibPlugin, [config.files, chunk]);
1791
- if (this.store.empConfig.empShareLib.useImportMap) {
1792
- this.store.chain.plugin(`${this.store.chainName.plugin.html.importMapPrefix}${chunk}`).use(HtmlImportMapPlugin, [this.store.empConfig.empShareLib.importMap, chunk]);
1793
- }
1794
- }
1795
- setRspackEntry(entry) {
1796
- this.store.merge({ entry });
1797
- }
1798
- async init() {
1799
- if (this.store.empConfig.autoPages) {
1800
- await this.setAutoPage();
1801
- } else {
1802
- await this.setDefaultEntry();
1803
- this.setEntryByConfig();
1804
- }
1805
- }
1806
- async setAutoPage() {
1807
- logger_default.time("setAutoPage");
1808
- const pathFolder = this.store.empConfig.autoPages?.path || "pages";
1809
- const autoPath = path3.join(this.store.appSrc, pathFolder);
1810
- const exp = path3.join(autoPath, "**", `*.{ts,tsx,jsx,js}`);
1811
- let entries = await glob([exp], { windowsPathsNoEscape: true });
1812
- entries = entries.map((d) => d.replace(`${autoPath}${path3.sep}`, ""));
1813
- entries.map((filename) => {
1814
- const op = this.store.empConfig.entries[filename] || {};
1815
- this.setEntryItem(filename, { ...this.store.empConfig.html, ...op }, path3.join(autoPath, filename));
1816
- });
1817
- logger_default.timeEnd("setAutoPage");
1818
- }
1819
- async setDefaultEntry() {
1820
- logger_default.time("[store][empConfig]SetDefaultEntry");
1821
- const appEntry = path3.join(
1822
- this.store.appSrc,
1823
- this.store.empConfig.appEntry ? this.store.empConfig.appEntry : `index.{ts,tsx,jsx,js}`
1824
- );
1825
- const elist = await glob([appEntry], { windowsPathsNoEscape: true });
1826
- if (elist[0]) {
1827
- const filename = path3.join(
1828
- this.store.empConfig.appSrc,
1829
- Object.keys(this.store.empConfig.entries).length > 0 && this.store.empConfig.appEntry ? this.store.empConfig.appEntry : "index"
1830
- );
1831
- this.setEntryItem(filename, this.store.empConfig.html, elist[0]);
1832
- }
1833
- logger_default.timeEnd("[store][empConfig]SetDefaultEntry");
1834
- }
1835
- setEntryByConfig() {
1836
- if (Object.keys(this.store.empConfig.entries).length > 0) {
1837
- for (const [filename, op] of Object.entries(this.store.empConfig.entries)) {
1838
- this.setEntryItem(filename, { ...this.store.empConfig.html, ...op });
1839
- }
1840
- }
1841
- }
1842
- toConfig() {
1843
- for (const [chunk, op] of Object.entries(this.entriesConfig)) {
1844
- this.setRspackHtmlPlugin(op.html, chunk);
1845
- this.setRspackEntry(op.entry);
1846
- }
1847
- }
1848
- };
1849
- entries_default = new RspackEntries();
1850
- }
1851
- });
1852
-
1853
- // src/store/rspack/module.ts
1854
- import path4 from "path";
1855
- var RspackModule, module_default;
1856
- var init_module = __esm({
1857
- "src/store/rspack/module.ts"() {
1858
- "use strict";
1859
- init_esm_shims();
1860
- init_utils();
1861
- RspackModule = class {
1862
- store;
1863
- swcJsOptions = {};
1864
- swcTsOptions = {};
1865
- coreJs = {
1866
- version: "3",
1867
- alias: "",
1868
- path: ""
1869
- };
1870
- async setup(store) {
1871
- this.store = store;
1872
- this.swcInitOptions();
1873
- await this.run();
1874
- }
1875
- async run() {
1876
- const runFuns = [this.jsDataUrl(), this.files(), this.scripts(), this.rspackGenerator(), this.rspackParser()];
1877
- await this.store.empConfig.lifeCycle.beforeModule();
1878
- await Promise.all(runFuns);
1879
- await this.store.empConfig.lifeCycle.afterModule();
1880
- }
1881
- rspackGenerator() {
1882
- const localIdentName = this.store.isDev ? "[path][name]-[local]-[hash:5]" : "[local]-[hash:5]";
1883
- this.store.chain.merge({
1884
- module: {
1885
- generator: {
1886
- css: { localIdentName },
1887
- "css/auto": { localIdentName },
1888
- "css/module": { localIdentName }
1889
- }
1890
- }
1891
- });
1892
- }
1893
- rspackParser() {
1894
- const namedExports = false;
1895
- this.store.chain.merge({
1896
- module: {
1897
- parser: {
1898
- css: { namedExports },
1899
- "css/auto": { namedExports },
1900
- "css/module": { namedExports }
1901
- }
1902
- }
1903
- });
1904
- }
1905
- get isPolyfill() {
1906
- return this.store.empConfig.build.polyfill;
1907
- }
1908
- swcParser(lang) {
1909
- switch (lang) {
1910
- case "js":
1911
- return {
1912
- syntax: "ecmascript",
1913
- jsx: true,
1914
- decorators: true,
1915
- decoratorsBeforeExport: false
1916
- };
1917
- case "ts":
1918
- return {
1919
- syntax: "typescript",
1920
- decorators: true,
1921
- tsx: true,
1922
- dynamicImport: true
1923
- };
1924
- }
1925
- }
1926
- swcJsc(lang) {
1927
- const { target, externalHelpers } = this.store.empConfig.build;
1928
- return {
1929
- parser: this.swcParser(lang),
1930
- transform: {},
1931
- target,
1932
- externalHelpers,
1933
- // Requires v1.2.50 or upper and requires target to be es2016 or upper.
1934
- // keepClassNames: true,
1935
- // https://github.com/swc-project/swc/issues/6403 Avoid the webpack magic comment to be removed
1936
- preserveAllComments: true
1937
- };
1938
- }
1939
- get swcCoreVersion() {
1940
- const [major, minor] = this.coreJs.version.split(".");
1941
- return `${major}.${minor}`;
1942
- }
1943
- swcOptions(lang) {
1944
- const op = {
1945
- jsc: deepAssign(this.swcJsc(lang), { ...this.store.empConfig.build.swcConfig }),
1946
- /**
1947
- * externalHelpers *
1948
- * mode usage *
1949
- */
1950
- // Source Type
1951
- isModule: "unknown"
1952
- };
1953
- if (this.isPolyfill) {
1954
- delete op.jsc.target;
1955
- op.env = {
1956
- coreJs: this.swcCoreVersion,
1957
- // modules: false,
1958
- // loose: true,
1959
- // debug: true,
1960
- targets: this.store.empConfig.build.browserslist
1961
- };
1962
- if (!this.store.empConfig.isESM) {
1963
- op.env.mode = this.store.empConfig.build.polyfill;
1964
- }
1965
- if (this.store.empConfig.build.polyfill === "usage") {
1966
- op.env.shippedProposals = true;
1967
- op.env.include = this.store.empConfig.build.polyfillInclude;
1968
- }
1969
- }
1970
- return op;
1971
- }
1972
- swcInitOptions() {
1973
- const { externalHelpers } = this.store.empConfig.build;
1974
- if (externalHelpers) {
1975
- this.store.chain.resolve.alias.set("@swc/helpers", path4.dirname(__require.resolve("@swc/helpers/package.json")));
1976
- }
1977
- this.coreJs.path = __require.resolve("core-js/package.json");
1978
- const version = getPkgVersion(this.coreJs.path);
1979
- if (version) this.coreJs.version = version;
1980
- this.coreJs.alias = path4.dirname(this.coreJs.path);
1981
- if (this.store.empConfig.build.polyfill) {
1982
- this.store.chain.resolve.alias.set("core-js", this.coreJs.alias);
1983
- this.store.chain.module.rule("javascript").exclude.add(/core-js/);
1984
- this.store.chain.module.rule("typescript").exclude.add(/core-js/);
1985
- }
1986
- this.swcTsOptions = this.swcOptions("ts");
1987
- this.swcJsOptions = this.swcOptions("js");
1988
- }
1989
- jsDataUrl() {
1990
- this.store.chain.module.rule("jsDataUrl").merge({ mimetype: { or: ["text/javascript", "application/javascript"] } }).resolve.set("fullySpecified", false).end().use("swcJsParser").loader("builtin:swc-loader").options(this.swcJsOptions);
1991
- }
1992
- async scripts() {
1993
- const exclude = [];
1994
- const { rule, use } = this.store.chainName;
1995
- this.store.chain.merge({
1996
- module: {
1997
- parser: {
1998
- javascript: {
1999
- exportsPresence: "error",
2000
- importExportsPresence: "error"
2001
- }
2002
- },
2003
- rule: {
2004
- [rule.mjs]: {
2005
- test: /\.m?js/,
2006
- resolve: {
2007
- fullySpecified: false
2008
- }
2009
- },
2010
- [rule.typescript]: {
2011
- test: /\.(ts|tsx)$/,
2012
- exclude,
2013
- // sideEffects, // 标记模块是否存在副作用。
2014
- use: {
2015
- [use.swc]: {
2016
- loader: "builtin:swc-loader",
2017
- options: this.swcTsOptions
2018
- }
2019
- }
2020
- },
2021
- [rule.javascript]: {
2022
- test: /\.((m|c)?js|jsx)$/,
2023
- exclude,
2024
- // sideEffects, // 标记模块是否存在副作用。
2025
- use: {
2026
- [use.swc]: {
2027
- loader: "builtin:swc-loader",
2028
- options: this.swcJsOptions
2029
- }
2030
- }
2031
- },
2032
- [rule.sourceMap]: {
2033
- test: /\.[tj]sx?$/,
2034
- enforce: "pre",
2035
- use: {
2036
- [use.sourceMap]: {
2037
- loader: __require.resolve("source-map-loader")
2038
- }
2039
- }
2040
- }
2041
- }
2042
- }
2043
- });
2044
- }
2045
- async files() {
2046
- const { rule } = this.store.chainName;
2047
- this.store.chain.merge({
2048
- module: {
2049
- rule: {
2050
- [rule.svg]: {
2051
- test: /\.svg$/,
2052
- type: "asset/resource"
2053
- }
2054
- }
2055
- }
2056
- });
2057
- this.store.chain.merge({
2058
- module: {
2059
- rule: {
2060
- [rule.inline]: {
2061
- resourceQuery: /inline/,
2062
- type: "asset/inline"
2063
- }
2064
- }
2065
- }
2066
- });
2067
- this.store.chain.merge({
2068
- module: {
2069
- rule: {
2070
- [rule.image]: {
2071
- test: /\.(png|jpe?g|gif|webp|ico)$/i,
2072
- type: "asset/resource"
2073
- },
2074
- [rule.font]: {
2075
- test: /\.(|otf|ttf|eot|woff|woff2)$/i,
2076
- type: "asset/resource"
2077
- },
2078
- [rule.svga]: {
2079
- test: /\.(svga)$/i,
2080
- type: "asset/resource"
2081
- }
2082
- }
2083
- }
2084
- });
2085
- }
2086
- };
2087
- module_default = new RspackModule();
2088
- }
2089
- });
2090
-
2091
- // src/store/rspack/plugin.ts
2092
- import fs6 from "fs";
2093
- import { ModuleFederationPlugin } from "@module-federation/enhanced/rspack";
2094
- import rspack from "@rspack/core";
2095
- var RspackPlugin, plugin_default;
2096
- var init_plugin = __esm({
2097
- "src/store/rspack/plugin.ts"() {
2098
- "use strict";
2099
- init_esm_shims();
2100
- RspackPlugin = class {
2101
- store;
2102
- async setup(store) {
2103
- this.store = store;
2104
- const runFuns = [
2105
- this.define(),
2106
- this.anylayze(),
2107
- this.progress(),
2108
- this.copy(),
2109
- this.empShare(),
2110
- // this.html()
2111
- ///////////////////////
2112
- this.minify(),
2113
- this.redoctor()
2114
- ];
2115
- await this.store.empConfig.lifeCycle.beforePlugin();
2116
- await Promise.all(runFuns);
2117
- await this.store.empConfig.lifeCycle.afterPlugin();
2118
- }
2119
- async anylayze() {
2120
- if (!this.store.cliOptions.analyze) return;
2121
- const {
2122
- default: { BundleAnalyzerPlugin }
2123
- } = await import("webpack-bundle-analyzer");
2124
- this.store.chain.plugin(this.store.chainName.plugin.bundleAnalyzer).use(BundleAnalyzerPlugin, [
2125
- {
2126
- analyzerPort: this.store.empConfig.server.port,
2127
- defaultSizes: "gzip",
2128
- analyzerHost: this.store.getLanIp() || "127.0.0.1"
2129
- }
2130
- ]);
2131
- }
2132
- // async html() {
2133
- // const htmlPlugin: any = await import('@rspack/plugin-html')
2134
- // //TODO 修正 两个 default
2135
- // const HtmlRspackPlugin = htmlPlugin.default.default
2136
- // const op = this.store.empConfig.html
2137
- // this.store.chain.plugin('htmlPlugin').use(HtmlRspackPlugin, [op])
2138
- // }
2139
- async define() {
2140
- this.store.chain.plugin(this.store.chainName.plugin.define).use(rspack.DefinePlugin, [this.store.empConfig.define]);
2141
- }
2142
- async copy() {
2143
- const publicFrom = this.store.resolve("public");
2144
- if (fs6.existsSync(publicFrom) && fs6.readdirSync(publicFrom).length > 0)
2145
- this.store.chain.plugin(this.store.chainName.plugin.copy).use(rspack.CopyRspackPlugin, [
2146
- {
2147
- patterns: [
2148
- {
2149
- from: publicFrom,
2150
- to: this.store.resolve(this.store.empConfig.build.outDir),
2151
- noErrorOnMissing: true,
2152
- globOptions: {
2153
- // 禁止 MACOS .DS_Store 复制到代码里
2154
- ignore: ["**/.DS_Store"]
2155
- }
2156
- }
2157
- ]
2158
- }
2159
- ]);
2160
- }
2161
- async progress() {
2162
- if (!this.store.empConfig.debug.progress) return;
2163
- this.store.chain.plugin(this.store.chainName.plugin.progress).use(rspack.ProgressPlugin, [
2164
- {
2165
- prefix: "EMP"
2166
- }
2167
- ]);
2168
- }
2169
- async empShare() {
2170
- const { isEmpshare } = this.store.empConfig.empShareLib;
2171
- if (!isEmpshare) return;
2172
- const mfp = ModuleFederationPlugin;
2173
- this.store.chain.plugin(this.store.chainName.plugin.empShare).use(mfp, [this.store.empConfig.empShareLib.pluginConfig]);
2174
- }
2175
- // production plugin
2176
- minify() {
2177
- this.store.chain.optimization.minimize(this.store.mode === "production");
2178
- this.store.chain.optimization.minimizer(this.store.chainName.minimizer.minJs).use(rspack.SwcJsMinimizerRspackPlugin, [this.store.empConfig.build.minOptions]);
2179
- this.store.chain.optimization.minimizer(this.store.chainName.minimizer.minCss).use(rspack.LightningCssMinimizerRspackPlugin, [this.store.empConfig.build.cssminOptions]);
2180
- }
2181
- redoctor() {
2182
- if (!this.store.empConfig.debug.rsdoctor) return;
2183
- const { RsdoctorRspackPlugin } = __require("@rsdoctor/rspack-plugin");
2184
- let op = {};
2185
- if (typeof this.store.empConfig.debug.rsdoctor === "object") op = this.store.empConfig.debug.rsdoctor;
2186
- this.store.chain.plugin(this.store.chainName.plugin.rsdoctor).use(RsdoctorRspackPlugin, [op]);
2187
- }
2188
- };
2189
- plugin_default = new RspackPlugin();
2190
- }
2191
- });
2192
-
2193
- // src/store/rspack/index.ts
2194
- var RspackStore, rspack_default;
2195
- var init_rspack = __esm({
2196
- "src/store/rspack/index.ts"() {
2197
- "use strict";
2198
- init_esm_shims();
2199
- init_common();
2200
- init_css();
2201
- init_entries();
2202
- init_module();
2203
- init_plugin();
2204
- RspackStore = class {
2205
- store;
2206
- async setup(store) {
2207
- this.store = store;
2208
- const runFuns = [
2209
- common_default.setup(this.store),
2210
- module_default.setup(this.store),
2211
- plugin_default.setup(this.store),
2212
- entries_default.setup(this.store),
2213
- css_default.setup(this.store)
2214
- ];
2215
- await Promise.all(runFuns);
2216
- await this.store.empConfig.lifeCycle.beforeEmpPlugin();
2217
- await this.store.empConfig.plugins();
2218
- await this.store.empConfig.lifeCycle.afterEmpPlugin();
2219
- await this.store.empConfig.chain();
2220
- }
2221
- };
2222
- rspack_default = new RspackStore();
2223
- }
2224
- });
2225
-
2226
- // src/store/index.ts
2227
- import fs7 from "fs/promises";
2228
- import path5 from "path";
2229
- import util from "util";
2230
- import WPChain from "webpack-chain";
2231
- var GlobalStore, store_default;
2232
- var init_store = __esm({
2233
- "src/store/index.ts"() {
2234
- "use strict";
2235
- init_esm_shims();
2236
- init_logger();
2237
- init_utils();
2238
- init_empConfig();
2239
- init_rspack();
2240
- init_chain();
2241
- GlobalStore = class {
2242
- /**
2243
- * EMP Version
2244
- * @default package version
2245
- */
2246
- empPkg = { dependencies: {}, devDependencies: {}, version: "2.0.0", name: "" };
2247
- /**
2248
- * 项目pkg信息
2249
- */
2250
- pkg = { dependencies: {}, devDependencies: {}, version: "0.0.0", name: "" };
2251
- /**
2252
- * 项目根目录绝对路径
2253
- * @default process.cwd()
2254
- */
2255
- root = process.cwd();
2256
- /**
2257
- * emp 内部根路径
2258
- * @default empRoot
2259
- */
2260
- empRoot = path5.resolve(__dirname, __filename).replace(`${path5.sep}dist${path5.sep}index.js`, "");
2261
- /**
2262
- * emp 执行代码路径
2263
- */
2264
- empSource = path5.resolve(this.empRoot, "dist");
2265
- /**
2266
- * 获取项目 根目录绝对路径
2267
- * (*) relativePath 可以是绝对路径
2268
- * @param relativePath
2269
- * @returns
2270
- */
2271
- resolve = (relativePath) => path5.isAbsolute(relativePath) ? relativePath : path5.resolve(this.root, relativePath);
2272
- /**
2273
- * 获取项目 emp内部根目录绝对路径
2274
- * @param relativePath
2275
- * @returns
2276
- */
2277
- empResolve = (relativePath) => path5.resolve(this.empRoot, relativePath);
2278
- /**
2279
- * 源码地址 绝对路径
2280
- */
2281
- appSrc = "";
2282
- /**
2283
- * 源码生成目录 绝对路径
2284
- */
2285
- outDir = "";
2286
- /**
2287
- * 静态文件目录 绝对路径
2288
- */
2289
- publicDir = "";
2290
- /**
2291
- * 静态资源
2292
- */
2293
- resource = {
2294
- dir: "",
2295
- key: "",
2296
- cert: ""
2297
- };
2298
- chainName = chainName;
2299
- /**
2300
- * 缓存目录 绝对路径
2301
- */
2302
- cacheDir = "";
2303
- mode = "development";
2304
- cliMode = "dev";
2305
- isDev = true;
2306
- /**
2307
- * 项目配置
2308
- */
2309
- cliOptions;
2310
- chain;
2311
- rsConfig;
2312
- empOptions = {};
2313
- empConfig;
2314
- // utils
2315
- vCompare = vCompare;
2316
- deepAssign = deepAssign;
2317
- getLanIp = getLanIp;
2318
- // 拓展
2319
- entries = {};
2320
- // 获取所有入口名称
2321
- debug;
2322
- //
2323
- async setup(mode, cliOptions) {
2324
- logger_default.time("[store]Setup");
2325
- await this.initVars(mode, cliOptions);
2326
- this.empConfig = empConfig_default;
2327
- await this.empConfig.setup(this);
2328
- this.debug = { ...{}, ...this.empConfig.debug };
2329
- this.initPaths();
2330
- this.chain = new WPChain();
2331
- await rspack_default.setup(this);
2332
- this.setLogger();
2333
- this.toConfig();
2334
- this.logConfig();
2335
- logger_default.timeEnd("[store]Setup");
2336
- }
2337
- /**
2338
- * 初始化 基础变量
2339
- * @param mode cli名称
2340
- * @param cliOptions cli配置
2341
- */
2342
- async initVars(mode, cliOptions) {
2343
- this.cliOptions = cliOptions || {};
2344
- this.cliMode = "dev";
2345
- this.mode = mode === "dev" ? "development" : "production";
2346
- this.isDev = this.mode === "development";
2347
- process.env["NODE_ENV"] = mode === "dev" ? "development" : "production";
2348
- const empPkg = __require(this.empResolve("package.json"));
2349
- const pkg = __require(this.resolve("package.json"));
2350
- this.empPkg = { ...this.empPkg, ...empPkg };
2351
- this.pkg = { ...this.pkg, ...pkg };
2352
- this.resource.dir = path5.join(this.empRoot, "resource");
2353
- this.resource.cert = path5.join(this.resource.dir, "emp.cert");
2354
- this.resource.key = path5.join(this.resource.dir, "emp.key");
2355
- }
2356
- /**
2357
- * 初始化 基础路径
2358
- */
2359
- initPaths() {
2360
- this.appSrc = this.resolve(this.empConfig.appSrc);
2361
- this.outDir = this.resolve(this.empConfig.build.outDir);
2362
- this.publicDir = this.resolve(this.empConfig.build.publicDir);
2363
- this.cacheDir = this.resolve(this.empConfig.cacheDir);
2364
- }
2365
- /**
2366
- * 设置 日志等级
2367
- */
2368
- setLogger() {
2369
- let logLevel = this.cliMode === "dev" ? "debug" : "info";
2370
- if (this.debug.loggerLevel) logLevel = this.debug.loggerLevel;
2371
- logger_default.setup({
2372
- fullName: `EMP\u26A1${this.empPkg.version}${this.cliMode === "dev" ? ".DEV" : ""}`,
2373
- brandName: `EMP`,
2374
- logLevel
2375
- });
2376
- }
2377
- merge(o) {
2378
- this.chain.merge(o);
2379
- }
2380
- /**
2381
- * 同步 chain 配置到 rsConfig
2382
- */
2383
- toConfig() {
2384
- this.rsConfig = this.chain.toConfig();
2385
- }
2386
- /**
2387
- * 打印 config
2388
- */
2389
- logConfig() {
2390
- if (this.debug.showRsconfig) {
2391
- if (typeof this.debug.showRsconfig === "string") {
2392
- const rsconfigPath = path5.join(this.root, this.debug.showRsconfig);
2393
- fs7.writeFile(rsconfigPath, JSON.stringify(this.rsConfig, null, 2));
2394
- } else {
2395
- this.debug.clearLog = false;
2396
- const defaultOp = { colors: true, depth: null };
2397
- const op = typeof this.debug.showRsconfig === "object" ? deepAssign(defaultOp, this.debug.showRsconfig) : defaultOp;
2398
- console.log(logger_default.link(`[Compile Config]`));
2399
- console.log(util.inspect(this.rsConfig, op));
2400
- }
2401
- }
2402
- }
2403
- get browserslistOptions() {
2404
- return {
2405
- default: ["chrome >= 87", "edge >= 88", "firefox >= 78", "safari >= 14"],
2406
- h5: ["iOS >= 9", "Android >= 4.4", "last 2 versions", "> 0.2%", "not dead"],
2407
- node: ["node >= 16"]
2408
- };
2409
- }
2410
- get uniqueName() {
2411
- return this.pkg.name.replaceAll("/", "_").replaceAll("@", "_").replaceAll("-", "_");
2412
- }
2413
- };
2414
- store_default = new GlobalStore();
2415
- }
2416
- });
2417
-
2418
- // src/helper/buildPrint.ts
2419
- import fs8 from "fs";
2420
- import path6 from "path";
2421
- import { gzipSizeSync } from "gzip-size";
2422
- function printHeader(longestFileLength, longestLabelLength) {
2423
- const longestLengths = [longestFileLength, longestLabelLength];
2424
- const headerRow = ["File", "Size", "Gzipped"].reduce((prev, cur, index) => {
2425
- const length = longestLengths[index];
2426
- let curLabel = cur;
2427
- if (length) {
2428
- curLabel = cur.length < length ? cur + " ".repeat(length - cur.length) : cur;
2429
- }
2430
- return `${prev + curLabel} `;
2431
- }, " ");
2432
- console.log(blue.bold(headerRow));
2433
- }
2434
- async function printFileSizes(stats) {
2435
- const origin = stats.toJson({
2436
- all: false,
2437
- assets: true,
2438
- timings: true
2439
- });
2440
- const filteredAssets = origin.assets.filter((asset) => filterAsset(asset.name));
2441
- const assets = filteredAssets.map(formatAsset);
2442
- assets.sort((a, b) => a.size - b.size);
2443
- const longestLabelLength = Math.max(...assets.map((a) => a.sizeLabel.length));
2444
- const longestFileLength = Math.max(...assets.map((a) => (a.folder + path6.sep + a.name).length));
2445
- printHeader(longestFileLength, longestLabelLength);
2446
- let totalSize = 0;
2447
- let totalGzipSize = 0;
2448
- assets.forEach((asset) => {
2449
- let { sizeLabel } = asset;
2450
- const { name, folder, gzipSizeLabel } = asset;
2451
- const fileNameLength = (folder + path6.sep + name).length;
2452
- const sizeLength = sizeLabel.length;
2453
- totalSize += asset.size;
2454
- totalGzipSize += asset.gzippedSize;
2455
- if (sizeLength < longestLabelLength) {
2456
- const rightPadding = " ".repeat(longestLabelLength - sizeLength);
2457
- sizeLabel += rightPadding;
2458
- }
2459
- let fileNameLabel = gray(asset.folder + path6.sep) + coloringAssetName(asset.name);
2460
- if (fileNameLength < longestFileLength) {
2461
- const rightPadding = " ".repeat(longestFileLength - fileNameLength);
2462
- fileNameLabel += rightPadding;
2463
- }
2464
- logger_default.info(` ${fileNameLabel} ${gray(sizeLabel)} ${gzipSizeLabel}`);
2465
- });
2466
- const totalSizeLabel = `${blue.bold("Total size:")} ${calcFileSize(totalSize)}`;
2467
- const gzippedSizeLabel = `${blue.bold("Gzipped size:")} ${calcFileSize(totalGzipSize)}`;
2468
- logger_default.info(`
2469
- ${totalSizeLabel}
2470
- ${gzippedSizeLabel}
2471
- `);
2472
- logger_default.info(`${green("\u2713")} Ready in ${timeFormat(Number(origin.time))}
2473
- `);
2474
- }
2475
- function timeDone(mis = 0) {
2476
- logger_default.info(`${green("\u2713")} Ready in ${timeFormat(Number(mis))}`);
2477
- }
2478
- var HTML_REGEX, JS_REGEX, CSS_REGEX, filterAsset, getAssetColor, formatAsset, calcFileSize, coloringAssetName;
2479
- var init_buildPrint = __esm({
2480
- "src/helper/buildPrint.ts"() {
2481
- "use strict";
2482
- init_esm_shims();
2483
- init_color();
2484
- init_store();
2485
- init_logger();
2486
- init_utils();
2487
- HTML_REGEX = /\.html$/;
2488
- JS_REGEX = /\.(?:js|mjs|cjs|jsx)$/;
2489
- CSS_REGEX = /\.css$/;
2490
- filterAsset = (asset) => !/\.map$/.test(asset) && !/\.LICENSE\.txt$/.test(asset);
2491
- getAssetColor = (size) => {
2492
- if (size > 300 * 1e3) {
2493
- return red;
2494
- }
2495
- if (size > 100 * 1e3) {
2496
- return yellow;
2497
- }
2498
- return white;
2499
- };
2500
- formatAsset = (asset) => {
2501
- const fileName = asset.name.split("?")[0];
2502
- const sizeLabel = calcFileSize(asset.size);
2503
- const name = path6.basename(fileName);
2504
- const folder = path6.join(path6.basename(store_default.empConfig.build.outDir), path6.dirname(fileName));
2505
- const contents = fs8.readFileSync(path6.join(store_default.empConfig.build.outDir, fileName));
2506
- const size = contents.length;
2507
- const gzippedSize = gzipSizeSync(contents);
2508
- const gzipSizeLabel = getAssetColor(gzippedSize)(calcFileSize(gzippedSize));
2509
- return {
2510
- size,
2511
- folder,
2512
- name,
2513
- gzippedSize,
2514
- sizeLabel,
2515
- gzipSizeLabel
2516
- };
2517
- };
2518
- calcFileSize = (len) => {
2519
- const val = len / 1e3;
2520
- return `${val.toFixed(val < 1 ? 2 : 1)} kB`;
2521
- };
2522
- coloringAssetName = (assetName) => {
2523
- if (JS_REGEX.test(assetName)) {
2524
- return yellow(assetName);
2525
- }
2526
- if (CSS_REGEX.test(assetName)) {
2527
- return green(assetName);
2528
- }
2529
- if (HTML_REGEX.test(assetName)) {
2530
- return blue(assetName);
2531
- }
2532
- return magenta(assetName);
2533
- };
2534
- }
2535
- });
2536
-
2537
- // src/script/dev.ts
2538
- var dev_exports = {};
2539
- __export(dev_exports, {
2540
- default: () => dev_default
2541
- });
2542
- import { rspack as rspack2 } from "@rspack/core";
2543
- import { RspackDevServer } from "@rspack/dev-server";
2544
- var DevScript, dev_default;
2545
- var init_dev = __esm({
2546
- "src/script/dev.ts"() {
2547
- "use strict";
2548
- init_esm_shims();
2549
- init_buildPrint();
2550
- init_logger();
2551
- init_utils();
2552
- init_base();
2553
- init_store();
2554
- DevScript = class extends BaseScript {
2555
- get rspackDevConfig() {
2556
- const cf = deepAssign(store_default.rsConfig, {
2557
- stats: {
2558
- all: false,
2559
- colors: true,
2560
- assets: false,
2561
- chunks: false,
2562
- entrypoints: false,
2563
- timings: false,
2564
- version: false,
2565
- errors: true,
2566
- warnings: true
2567
- },
2568
- devServer: {
2569
- open: false,
2570
- setupExitSignals: true
2571
- // app: () => app,
2572
- // setupMiddlewares: wdm.setupMiddlewares,
2573
- }
2574
- });
2575
- return cf;
2576
- }
2577
- async devServerConfig() {
2578
- const devServer = Object.assign({}, store_default.rsConfig.devServer);
2579
- if (this.isHttps) {
2580
- if (devServer.https === true) {
2581
- delete devServer.https;
2582
- }
2583
- if (!devServer.server) {
2584
- const [key, cert] = await this.getcert();
2585
- devServer.server = {
2586
- type: "https",
2587
- options: {
2588
- key,
2589
- cert
2590
- // minVersion: 'TLSv1.1',
2591
- // key: fs.readFileSync(path.join(__dirname, './server.key')),
2592
- // pfx: fs.readFileSync(path.join(__dirname, './server.pfx')),
2593
- // cert: fs.readFileSync(path.join(__dirname, './server.crt')),
2594
- // ca: fs.readFileSync(path.join(__dirname, './ca.pem')),
2595
- // passphrase: 'webpack-dev-server',
2596
- // requestCert: true,
2597
- }
2598
- };
2599
- }
2600
- }
2601
- return devServer;
2602
- }
2603
- async run() {
2604
- const compiler = rspack2(this.rspackDevConfig);
2605
- if (!store_default.rsConfig.devServer) {
2606
- logger_default.error("devServer is not defined in config");
2607
- return;
2608
- }
2609
- const devServer = await this.devServerConfig();
2610
- const serverApp = new RspackDevServer(devServer, compiler);
2611
- this.startOpen();
2612
- if (store_default.empConfig.lifeCycle.beforeDevServe) await store_default.empConfig.lifeCycle.beforeDevServe();
2613
- await serverApp.start();
2614
- const showTimeDone = (s) => {
2615
- const d = s?.toJson({ all: false, colors: false, assets: false, chunks: false, timings: true });
2616
- timeDone(d.time);
2617
- };
2618
- if (store_default.debug.showPerformance) compiler.hooks.afterDone.tap("done", showTimeDone);
2619
- serverApp.middleware?.waitUntilValid((s) => {
2620
- if (!store_default.debug.showPerformance) showTimeDone(s);
2621
- if (store_default.empConfig.lifeCycle.afterDevServe) store_default.empConfig.lifeCycle.afterDevServe();
2622
- });
2623
- }
2624
- };
2625
- dev_default = new DevScript();
2626
- }
2627
- });
2628
-
2629
- // src/script/httpBase.ts
2630
- import https from "https";
2631
- import compression from "compression";
2632
- import cors from "cors";
2633
- import express from "express";
2634
- var HttpServer;
2635
- var init_httpBase = __esm({
2636
- "src/script/httpBase.ts"() {
2637
- "use strict";
2638
- init_esm_shims();
2639
- init_base();
2640
- HttpServer = class extends BaseScript {
2641
- app;
2642
- async init() {
2643
- const app = express();
2644
- app.use(compression());
2645
- app.use(cors());
2646
- this.app = app;
2647
- }
2648
- async server() {
2649
- if (this.isHttps) {
2650
- const [key, cert] = await this.getcert();
2651
- const httpsServer = https.createServer(
2652
- typeof this.isHttps !== "boolean" ? this.isHttps : {
2653
- key,
2654
- cert
2655
- },
2656
- this.app
2657
- );
2658
- httpsServer.listen(this.sf.port, async () => {
2659
- this.startOpen();
2660
- await this.onReady();
2661
- });
2662
- } else {
2663
- this.app.listen(this.sf.port, async () => {
2664
- this.startOpen();
2665
- await this.onReady();
2666
- });
2667
- }
2668
- }
2669
- async onReady() {
2670
- }
2671
- async middleware() {
2672
- }
2673
- async start() {
2674
- await this.init();
2675
- await this.middleware();
2676
- await this.server();
2677
- }
2678
- };
2679
- }
2680
- });
2681
-
2682
- // src/script/serve.ts
2683
- var serve_exports = {};
2684
- __export(serve_exports, {
2685
- ServeScript: () => ServeScript,
2686
- default: () => serve_default
2687
- });
2688
- import fs9 from "fs";
2689
- import fsp from "fs/promises";
2690
- import path7 from "path";
2691
- import express2 from "express";
2692
- var ServeScript, serve_default;
2693
- var init_serve = __esm({
2694
- "src/script/serve.ts"() {
2695
- "use strict";
2696
- init_esm_shims();
2697
- init_buildPrint();
2698
- init_logger();
2699
- init_store();
2700
- init_httpBase();
2701
- ServeScript = class extends HttpServer {
2702
- timing = 0;
2703
- async run() {
2704
- this.timing = Date.now();
2705
- if (!fs9.existsSync(store_default.outDir)) {
2706
- return logger_default.sysError(`emp serve must be executed after emp build,${store_default.outDir} not exist!`);
2707
- }
2708
- if (store_default.empConfig.lifeCycle.beforeServe) await store_default.empConfig.lifeCycle.beforeServe();
2709
- this.start();
2710
- }
2711
- async middleware() {
2712
- const staticRoot = store_default.resolve(store_default.rsConfig.output?.path);
2713
- this.app.use(express2.static(staticRoot));
2714
- const html = await fsp.readFile(path7.join(staticRoot, "index.html"), "utf8");
2715
- this.app.get("*", (req, res) => res.send(html));
2716
- }
2717
- async onReady() {
2718
- timeDone(Date.now() - this.timing);
2719
- if (store_default.empConfig.lifeCycle.afterServe) await store_default.empConfig.lifeCycle.afterServe();
2720
- }
2721
- };
2722
- serve_default = new ServeScript();
2723
- }
2724
- });
2725
-
2726
- // src/script/build.ts
2727
- var build_exports = {};
2728
- __export(build_exports, {
2729
- default: () => build_default
2730
- });
2731
- import { rspack as rspack3 } from "@rspack/core";
2732
- var BuildScript, build_default;
2733
- var init_build = __esm({
2734
- "src/script/build.ts"() {
2735
- "use strict";
2736
- init_esm_shims();
2737
- init_buildPrint();
2738
- init_logger();
2739
- init_base();
2740
- init_store();
2741
- BuildScript = class extends BaseScript {
2742
- isWatchMode = false;
2743
- rspackConfig;
2744
- isuseServe = false;
2745
- isStartServe = false;
2746
- /**
2747
- * 解决 watch mode 报错问题
2748
- */
2749
- watchMode() {
2750
- if (this.isWatchMode) {
2751
- if (this.rspackConfig.optimization) {
2752
- this.rspackConfig.optimization.moduleIds = "named";
2753
- this.rspackConfig.optimization.chunkIds = "named";
2754
- this.rspackConfig.watch = true;
2755
- }
2756
- }
2757
- }
2758
- async startServe() {
2759
- if (!this.isuseServe || this.isStartServe) return;
2760
- this.isStartServe = true;
2761
- const { default: serveScript } = await Promise.resolve().then(() => (init_serve(), serve_exports));
2762
- await serveScript.setup("serve", store_default.cliOptions);
2763
- }
2764
- async run() {
2765
- await store_default.empConfig.lifeCycle.beforeBuild();
2766
- this.isWatchMode = !!store_default.cliOptions.watch;
2767
- this.isuseServe = !!store_default.cliOptions.serve;
2768
- this.rspackConfig = store_default.rsConfig;
2769
- if (this.isWatchMode) this.watchMode();
2770
- rspack3(this.rspackConfig, async (err, stats) => {
2771
- if (err !== null) {
2772
- logger_default.error(err.stack || err);
2773
- if (err.message) {
2774
- logger_default.error(err.message);
2775
- }
2776
- return;
2777
- }
2778
- if (!stats) {
2779
- logger_default.red("Stats is Undefined.");
2780
- return;
2781
- }
2782
- if (stats.hasErrors()) {
2783
- logger_default.error(
2784
- stats.toString({
2785
- all: false,
2786
- colors: true,
2787
- // children: true,
2788
- errors: true
2789
- })
2790
- );
2791
- logger_default.red("Failed to compile.");
2792
- process.exit(1);
2793
- }
2794
- if (stats.hasWarnings()) {
2795
- logger_default.yellow(`Compiled with warnings.`);
2796
- logger_default.warn(
2797
- stats.toString({
2798
- all: false,
2799
- chunks: false,
2800
- assets: false,
2801
- colors: true,
2802
- // children: true,
2803
- errors: true,
2804
- warnings: true
2805
- })
2806
- );
2807
- }
2808
- await printFileSizes(stats);
2809
- this.startServe();
2810
- await store_default.empConfig.lifeCycle.afterBulid();
2811
- });
2812
- }
2813
- };
2814
- build_default = new BuildScript();
2815
- }
2816
- });
2817
-
2818
- // src/index.ts
2819
- init_esm_shims();
2820
- import { rspack as rspack4 } from "@rspack/core";
2821
- import HtmlWebpackPlugin3 from "html-webpack-plugin";
2822
-
2823
- // src/script/index.ts
2824
- init_esm_shims();
2825
- init_store();
2826
- import process2 from "process";
2827
- import { program } from "commander";
2828
- function runScript() {
2829
- program.version(store_default.empPkg.version, "-v, --version").usage("<command> [options]");
2830
- program.command("dev").description("Dev \u6A21\u5F0F").option("-e, --env <env>", "\u90E8\u7F72\u73AF\u5883 dev\u3001test\u3001prod").option("-rd, --doctor", "\u5F00\u542Frsdoctor,\u53EF\u901A\u8FC7debug.rsdoctor\u64CD\u4F5C").option("-h, --hot", "\u662F\u5426\u4F7F\u7528\u70ED\u66F4\u65B0 \u9ED8\u8BA4\u542F\u52A8").option("-o, --open", "\u662F\u5426\u6253\u5F00\u8C03\u8BD5\u9875\u9762 \u9ED8\u8BA4\u4E0D\u6253\u5F00").option("-t, --ts", "\u751F\u6210\u7C7B\u578B\u6587\u4EF6 \u9ED8\u8BA4\u4E3A false").option("-pr, --profile", "\u7EDF\u8BA1\u6A21\u5757\u6D88\u8017").option("-cl, --clearLog <clearLog>", "\u6E05\u7A7A\u65E5\u5FD7 \u9ED8\u8BA4\u4E3A true").option(
2831
- "-ev, --env-vars <key=value>",
2832
- "\u5B9A\u4E49\u4E00\u4E2A\u73AF\u5883\u53D8\u91CF -ev key=value \u591A\u4E2A\u73AF\u5883\u53D8\u91CF\u91CD\u590D\u8C03\u7528 -ev key=value -ev key=value",
2833
- (ovalue, memo) => {
2834
- const [key, value] = ovalue.split("=");
2835
- memo[key] = value;
2836
- return memo;
2837
- },
2838
- {}
2839
- ).action(async (o) => {
2840
- const { default: devScript } = await Promise.resolve().then(() => (init_dev(), dev_exports));
2841
- await devScript.setup("dev", o);
2842
- });
2843
- program.command("build").description("Build \u6A21\u5F0F").option("-e, --env <env>", "\u90E8\u7F72\u73AF\u5883 dev\u3001test\u3001prod").option("-rd, --doctor", "\u5F00\u542Frsdoctor,\u53EF\u901A\u8FC7debug.rsdoctor\u64CD\u4F5C").option("-a, --analyze", "\u751F\u6210\u5206\u6790\u62A5\u544A \u9ED8\u8BA4\u4E3A false").option("-t, --ts", "\u751F\u6210\u7C7B\u578B\u6587\u4EF6 \u9ED8\u8BA4\u4E3A false").option("-pr, --profile", "\u7EDF\u8BA1\u6A21\u5757\u6D88\u8017").option("-cl, --clearLog <clearLog>", "\u6E05\u7A7A\u65E5\u5FD7 \u9ED8\u8BA4\u4E3A true").option("-w, --watch", "watch \u6A21\u5F0F").option("-sv, --serve", "watch \u6A21\u5F0F\u4E0B\u542F\u52A8serve").option(
2844
- "-ev, --env-vars <key=value>",
2845
- "\u5B9A\u4E49\u4E00\u4E2A\u73AF\u5883\u53D8\u91CF -ev key=value \u591A\u4E2A\u73AF\u5883\u53D8\u91CF\u91CD\u590D\u8C03\u7528 -ev key=value -ev key=value",
2846
- (ovalue, memo) => {
2847
- const [key, value] = ovalue.split("=");
2848
- memo[key] = value;
2849
- return memo;
2850
- },
2851
- {}
2852
- ).action(async (o) => {
2853
- const { default: buildScript } = await Promise.resolve().then(() => (init_build(), build_exports));
2854
- await buildScript.setup("build", o);
2855
- });
2856
- program.command("serve").description("Server \u6A21\u5F0F").option("-cl, --clearLog <clearLog>", "\u6E05\u7A7A\u65E5\u5FD7 \u9ED8\u8BA4\u4E3A true").action(async (o) => {
2857
- const { default: serveScript } = await Promise.resolve().then(() => (init_serve(), serve_exports));
2858
- await serveScript.setup("serve", o);
2859
- });
2860
- program.command("dts").description("\u62C9\u53D6 remote \u9879\u76EE\u7684 d.ts").option("-p, --typingsPath <typingsPath>", "\u4E0B\u8F7D\u76EE\u5F55").option("-e, --env <env>", "\u90E8\u7F72\u73AF\u5883 dev\u3001test\u3001prod").action((o) => {
2861
- });
2862
- program.command("init").description("\u521D\u59CB\u5316 emp \u9879\u76EE").option("-d, --data [data]", "JSON\u6570\u636E http\u5730\u5740 \u6216\u8005 \u6587\u4EF6\u8DEF\u5F84\u76F8\u5BF9\u3001\u7EDD\u5BF9\u8DEF\u5F84").action((o) => {
2863
- });
2864
- program.parse(process2.argv);
2865
- }
2866
-
2867
- // src/script/dts.ts
2868
- init_esm_shims();
2869
- init_helper();
2870
- init_store();
2871
- import fs10 from "fs/promises";
2872
- import path8 from "path";
2873
- var globalImportRE = /(?:(?:import|export)\s?(?:type)?\s?(?:(?:\{[^;\n]+\})|(?:[^;\n]+))\s?from\s?['"][^;\n]+['"])|(?:import\(['"][^;\n]+?['"]\))/g;
2874
- var staticImportRE = /(?:import|export)\s?(?:type)?\s?\{?.+\}?\s?from\s?['"](.+)['"]/;
2875
- var dynamicImportRE = /import\(['"]([^;\n]+?)['"]\)/;
2876
- var DTSBundle = class {
2877
- list = [];
2878
- outDir = store_default.resolve("dist");
2879
- aliasName = "@empjs/cli";
2880
- async setup(outDir, aliasName) {
2881
- if (outDir) this.outDir = outDir;
2882
- if (aliasName) this.aliasName = aliasName;
2883
- const bs = await this.readDts();
2884
- await this.writeCode(bs);
2885
- }
2886
- async readDts() {
2887
- this.list = await glob([`${store_default.empConfig.build.outDir}/**/*.d.ts`], { windowsPathsNoEscape: true });
2888
- const p = [];
2889
- this.list.map((d) => {
2890
- d = store_default.resolve(d);
2891
- p.push(this.readFile(d));
2892
- });
2893
- let bs = await Promise.all(p);
2894
- bs = bs.map((d) => this.replaceAliasPath(d));
2895
- return bs;
2896
- }
2897
- async readFile(src) {
2898
- const code = await fs10.readFile(src, { encoding: "utf-8" });
2899
- return { src, code };
2900
- }
2901
- replaceAliasPath({ src, code }) {
2902
- code = code.replace(globalImportRE, (str) => {
2903
- let matchResult = str.match(staticImportRE);
2904
- if (!matchResult) {
2905
- matchResult = str.match(dynamicImportRE);
2906
- }
2907
- if (matchResult && matchResult[1]) {
2908
- const rs = matchResult[1];
2909
- if (!rs.startsWith(".")) return str;
2910
- const filename = path8.resolve(path8.dirname(src), rs).replace(this.outDir, this.aliasName);
2911
- return str.replace(matchResult[1], filename);
2912
- }
2913
- return str;
2914
- });
2915
- let mod = src.replace(this.outDir, this.aliasName).replace(".d.ts", "");
2916
- if (mod.endsWith("/index")) {
2917
- mod = mod.replace("/index", "");
2918
- }
2919
- code = this.warpDeclareModule(mod, code);
2920
- return { code, src, mod };
2921
- }
2922
- warpDeclareModule(mod, code) {
2923
- return `declare module '${mod}' {\r
2924
- ${code}}\r
2925
- `;
2926
- }
2927
- async writeCode(bs) {
2928
- let c = "";
2929
- bs.map((d) => {
2930
- c += d.code;
2931
- });
2932
- await fs10.writeFile(path8.join(this.outDir.replace("dist", "types"), "type.d.ts"), c);
2933
- }
2934
- };
2935
- var dts_default = new DTSBundle();
2936
-
2937
- // src/index.ts
2938
- init_store();
2939
- init_helper();
2940
- function defineConfig(config) {
2941
- return config;
2942
- }
2943
- export {
2944
- HtmlWebpackPlugin3 as HtmlWebpackPlugin,
2945
- defineConfig,
2946
- dts_default as dts,
2947
- helper_exports as empHelper,
2948
- rspack4 as rspack,
2949
- runScript,
2950
- store_default as store
2951
- };
2952
- //# sourceMappingURL=index.js.map
2
+ var wt=Object.defineProperty;var b=(i=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(i,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):i)(function(i){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+i+'" is not supported')});var m=(i,e)=>()=>(i&&(e=i(i=0)),e);var N=(i,e)=>{for(var t in e)wt(i,t,{get:e[t],enumerable:!0})};import{fileURLToPath as Ct}from"url";import xt from"path";var Re,St,c,l,n=m(()=>{"use strict";Re=()=>Ct(import.meta.url),St=()=>xt.dirname(Re()),c=St(),l=Re()});import d from"chalk";var Et,S,Ot,Pt,kt,Z,U,$t,Dt,D,ee,jt,te,j,h,R=m(()=>{"use strict";n();Et=d.hex("#1abc9c"),S=d.hex("#16a085"),Ot=d.hex("#2ecc71"),Pt=d.hex("#27ae60"),kt=d.hex("#e74c3c"),Z=d.hex("#c0392b"),U=d.hex("#f1c40f"),$t=d.hex("#f39c12"),Dt=d.hex("#3498db"),D=d.hex("#2980b9"),ee=d.hex("#ecf0f1"),jt=d.hex("#fd79a8"),te=d.hex("#e84393"),j=d.hex("#7f8c8d"),h={lightGreen:Et,green:S,lightCyan:Ot,cyan:Pt,lightRed:kt,red:Z,yellow:U,orange:$t,lightBlue:Dt,blue:D,white:ee,lightMagenta:jt,magenta:te,gray:j}});var se,a,E=m(()=>{"use strict";n();R();se=class{brandName="";fullName="";logLevel="debug";isLogTime=!1;setup({brandName:e,logLevel:t,fullName:s}){this.brandName=` [${e}] `,this.fullName=` ${s} `,this.fullName=h.green.bold(this.fullName),t&&(this.logLevel=t)}time=(...e)=>this.isLogTime&&console.time(...e);timeEnd=(...e)=>this.isLogTime&&console.timeEnd(...e);debug=(...e)=>["debug"].includes(this.logLevel)&&console.log(...e);info=(...e)=>["debug","info"].includes(this.logLevel)&&console.log(...e);warn=(...e)=>["debug","info","warn"].includes(this.logLevel)&&console.warn(...e);error=(...e)=>["debug","info","warn","error"].includes(this.logLevel)&&console.error(...e);blue=e=>{console.log(`${h.lightBlue(this.brandName)}${h.blue(` ${e} `)}
3
+ `)};cyan=e=>{console.log(`${h.lightCyan(this.brandName)}${h.cyan(` ${e} `)}
4
+ `)};magenta=e=>{console.log(`${h.lightMagenta(this.brandName)}${h.magenta(` ${e} `)}
5
+ `)};green=e=>{console.log(`${h.lightGreen(this.brandName)}${h.green(` ${e} `)}
6
+ `)};yellow=e=>{console.log(`${h.yellow(this.brandName)}${h.orange(` ${e} `)}
7
+ `)};red=e=>{console.log(`${h.lightRed(this.brandName)}${h.red(` ${e} `)}
8
+ `)};sysError=e=>{console.log(`${h.lightRed(" System Error Tips ")}${h.red(` ${e} `)}
9
+ `)};link=e=>h.blue(e);title=e=>{console.log(`${this.fullName}${h.yellow.underline(`${e}`)}
10
+ `)}},a=new se});var ae={};N(ae,{clearConsole:()=>re,deepAssign:()=>y,ensureArray:()=>Tt,getLanIp:()=>M,getPkgVersion:()=>ie,importJsVm:()=>ne,jsonFilter:()=>Nt,timeFormat:()=>I,vCompare:()=>oe});import{ip as Rt}from"address";import Lt from"chalk";import{gateway4sync as At}from"default-gateway";import Ft from"fs-extra";function re(){process.stdout.write(process.platform==="win32"?"\x1B[2J\x1B[0f":"\x1B[2J\x1B[3J\x1B[H")}function y(i,...e){for(let t of e)for(let s in t){let r=t[s],p=i[s];if(Object(r)==r&&Object(p)===p){i[s]=y(p,r);continue}i[s]=t[s]}return i}var M,ie,Tt,Nt,oe,I,ne,w=m(()=>{"use strict";n();M=()=>{let{int:i}=At();return Rt(i||"")||"127.0.0.1"},ie=i=>{try{let{version:e}=Ft.readJSONSync(i);return e}catch{return}};Tt=i=>Array.isArray(i)?i:[i],Nt=(i={},e=[])=>Object.keys(i).filter(t=>!e.includes(t)).reduce((t,s)=>(t[s]=i[s],t),{}),oe=(i="",e="")=>{let t=i.replace("^","").split("."),s=e.replace("^","").split("."),r=Math.max(t.length,s.length),p=0;for(let f=0;f<r;f++){let g=t.length>f?t[f]:0,P=isNaN(Number(g))?g.charCodeAt():Number(g),F=s.length>f?s[f]:0,u=isNaN(Number(F))?F.charCodeAt():Number(F);if(P<u){p=-1;break}else if(P>u){p=1;break}}return p},I=i=>{i=i/1e3;let e=s=>Lt.bold(s);if(i<1)return`${i*1e3} ms`;if(i<10){let s=i>=.01?2:3;return`${e(i.toFixed(s))} s`}if(i<60)return`${e(i.toFixed(1))} s`;let t=i/60;return`${e(t.toFixed(2))} m`},ne=i=>`data:text/javascript,${i}`});var Le={};N(Le,{chalk:()=>Mt,color:()=>h,glob:()=>L,logger:()=>a,utils:()=>ae});import Mt from"chalk";import{glob as L}from"glob";var z=m(()=>{"use strict";n();R();w();E()});import zt from"fs";import Gt from"path";import Bt from"jiti";var Ut,Ae,Fe,It,Te=m(()=>{"use strict";n();v();E();Ut=["emp-config.ts","emp-config.js","emp.config.ts","emp.config.js","emp-config.mjs","emp-config.cjs","emp-config.mts","emp-config.cts","emp.config.mjs","emp.config.cjs","emp.config.mts","emp.config.cts"],Ae=Bt(l,{esmResolve:!0,requireCache:!1,interopDefault:!0}),Fe=async()=>It(),It=()=>{a.time("[store]GetEmpConfigPath");let i;for(let e of Ut){let t=Gt.resolve(o.root,e);if(zt.existsSync(t)){i=t;break}}return a.timeEnd("[store]GetEmpConfigPath"),i}});import Ht from"net";import Jt from"os";async function H(i,e="localhost"){if(i!==_t&&(i<Ne||i>pe))throw new Error(`Port number must lie between ${Ne} and ${pe}`);let t=i,s=Wt(),r;e&&!s.has(e)?r=new Set([e]):r=s;let p=new Set(["EADDRINUSE","EACCES"]);for(;t<=pe;)try{return await Vt(t,r)}catch(f){if(!p.has(f.code))throw f;t+=1}throw new Error("No available ports found")}var Ne,pe,_t,Wt,qt,Vt,le=m(()=>{"use strict";n();Ne=1024,pe=65535,_t=443,Wt=()=>{let i=Jt.networkInterfaces(),e=new Set([void 0,"0.0.0.0"]);for(let t of Object.values(i))if(t)for(let s of t)e.add(s.address);return e},qt=(i,e)=>new Promise((t,s)=>{let r=Ht.createServer();r.unref(),r.on("error",s),r.listen(i,e,()=>{let{port:p}=r.address();r.close(()=>{t(p)})})}),Vt=async(i,e)=>{let t=new Set(["EADDRNOTAVAIL","EINVAL"]);for(let s of e)try{await qt(i,s)}catch(r){if(!t.has(r.code))throw r}return i}});import Me from"url";import Xt from"chalk";var ce,A,me=m(()=>{"use strict";n();R();w();ce=class{imf={protocol:"",port:8e3,pathname:"/"};host="0.0.0.0";urls={lanUrlForConfig:"",lanUrlForTerminal:j("unavailable"),localUrlForTerminal:"",localUrlForBrowser:""};setup(e){e.host&&(this.host=e.host),e.protocol&&(this.imf.protocol=e.protocol),e.pathname&&(this.imf.pathname=e.pathname),e.port&&(this.imf.port=e.port),this.setupUrls()}setupUrls(){let{host:e}=this,t=e==="0.0.0.0"||e==="::",s;if(t){s="localhost";try{this.urls.lanUrlForConfig=this.getLanIp(),this.urls.lanUrlForConfig&&(/^10[.]|^172[.](1[6-9]|2[0-9]|3[0-1])[.]|^192[.]168[.]/.test(this.urls.lanUrlForConfig)?this.urls.lanUrlForTerminal=this.prettyPrintUrl(this.urls.lanUrlForConfig):this.urls.lanUrlForConfig="")}catch{}}else s=e,this.urls.lanUrlForConfig=e,this.urls.lanUrlForTerminal=this.prettyPrintUrl(this.urls.lanUrlForConfig);this.urls.localUrlForTerminal=this.prettyPrintUrl(s),this.urls.localUrlForBrowser=this.formatUrl(s)}getLanIp=M;formatUrl(e){let{protocol:t,port:s,pathname:r}=this.imf;return Me.format({protocol:t,hostname:e,port:s,pathname:r})}prettyPrintUrl(e){let{protocol:t,port:s,pathname:r}=this.imf;return Me.format({protocol:t,hostname:e,port:Xt.bold(s),pathname:r})}},A=new ce});import{exec as Qt}from"child_process";import{promisify as Kt}from"util";var Ge,ze,Yt,Zt,Be,Ue=m(()=>{"use strict";n();v();E();Ge=Kt(Qt),ze=["Google Chrome Canary","Google Chrome Dev","Google Chrome Beta","Google Chrome","Microsoft Edge","Brave Browser","Vivaldi","Chromium"],Yt=async()=>{let i=process.env.BROWSER;if(!i||!ze.includes(i)){let{stdout:e}=await Ge("ps cax");i=ze.find(t=>e.includes(t))}return i},Zt=async i=>{if(process.platform==="darwin")try{let t=await Yt();if(t){let s=`osascript openChrome.applescript "${encodeURI(i)}" "${t}"`;return await Ge(s,{cwd:o.resource.dir}),!0}}catch(t){a.debug(t)}try{let{default:t}=await import("open");return await t(i),!0}catch(t){return a.error("Failed to open start URL."),a.error(t),!1}},Be=Zt});var fe,J,he=m(()=>{"use strict";n();le();me();w();v();fe=class{isADB=!1;isHttps=!1;get isHttpBase(){let e=o.empOptions.base||"";return e.indexOf("http://")>-1||e.indexOf("https://")>-1}async setup(){if(this.isADB=!!o.empOptions.autoDevBase&&o.mode==="development"&&!this.isHttpBase,!this.isADB)return;let{server:e,https:t}=o.empOptions.server||{};this.isHttps=e==="https"||typeof e=="object"&&e.type==="https"||t===!0;let s=A.getLanIp(),r=this.isHttps?"https":"http",p=o.empOptions.server?.port||8e3;p=await H(p,s),o.empOptions.base=`${r}://${s}:${p}/`,o.empOptions.server=y({port:p,client:{webSocketURL:`${this.isHttps?"wss":"ws"}://${s}:${p}/ws`}},o.empOptions.server)}},J=new fe});import Ie from"fs/promises";var O,G=m(()=>{"use strict";n();R();le();me();E();Ue();w();v();he();O=class{sf={protocol:"http",host:"0.0.0.0",port:8e3,publicPath:"",publicHasHttp:!1,isOpenBrower:!1,url:"",urls:{localUrlForBrowser:"",localUrlForTerminal:"",lanUrlForTerminal:"",lanUrlForConfig:""}};static httpsType="default";async adaptServer(){this.sf.publicPath=o.rsConfig.output?.publicPath==="auto"?"/":o.rsConfig.output?.publicPath||"/",this.sf.isOpenBrower=!!o.empConfig.server.open,this.sf.protocol=this.isHttps?"https":"http",this.sf.host=o.empConfig.server.host?o.empConfig.server.host:this.sf.host,this.sf.port=o.empConfig.server.port,await this.serverPort(),A.setup(this.sf),this.sf.publicPath&&(this.sf.publicPath.indexOf("http://")>-1||this.sf.publicPath.indexOf("https://")>-1)?(this.sf.url=this.sf.publicPath,this.sf.publicHasHttp=!0,this.sf.urls.localUrlForTerminal=A.prettyPrintUrl("localhost")):(this.sf.urls=A.urls,this.sf.url=this.sf.urls.localUrlForBrowser)}startOpen(){let{urls:e}=this.sf;this.sf.publicHasHttp?(a.info(`${S("\u279C")} Local: ${a.link(e.localUrlForTerminal)}`),a.info(`${S("\u279C")} Network: ${a.link(this.sf.publicPath)}`)):(a.info(`${S("\u279C")} Local: ${a.link(e.localUrlForTerminal)}`),a.info(`${S("\u279C")} Network: ${a.link(e.lanUrlForTerminal)}
11
+ `)),this.sf.isOpenBrower&&Be(this.sf.url)}async setup(e,t){a.time(`[${e}]Setup`),await o.setup(e,t),o.debug.clearLog&&re(),a.title(`${e}`),await this.adaptServer(),a.time(`[${e}]Run`),await this.run(),a.timeEnd(`[${e}]Run`),this.afterRun(),a.timeEnd(`[${e}]Setup`)}async run(){}afterRun(){process.on("SIGINT",function(){process.exit()})}get isHttps(){let{server:e,https:t,http2:s}=o.empConfig.server||{};return e==="https"||typeof e=="object"&&e.type==="https"||t===!0||s===!0}getcert(){return Promise.all([Ie.readFile(o.resource.key),Ie.readFile(o.resource.cert)])}async serverPort(){if(J.isADB)return;let{port:e,host:t}=this.sf,s=await H(e,t);s!==e&&(this.sf.port=s,o.rsConfig.devServer?.port&&(o.rsConfig.devServer.port=s))}}});var _,He=m(()=>{"use strict";n();w();v();_=class{constructor(){}getPolyfillEntry(){let e=[`import 'core-js/${o.empConfig.build.coreJsFeatures}'`].join(`
12
+ `);return ne(e)}apply(e){let{webpack:t}=e;new t.EntryPlugin(e.context,this.getPolyfillEntry(),{name:void 0}).apply(e)}}});var W,Je=m(()=>{"use strict";n();v();he();He();W=class{op={};constructor(e={}){this.op=e}async afterGetEmpOptions(){await J.setup(),this.op.afterGetEmpOptions&&await this.op.afterGetEmpOptions()}async beforePlugin(){o.empConfig.build.polyfill==="entry"&&o.chain.plugin("empPolyfill").use(_),this.op.beforePlugin&&await this.op.beforePlugin()}async afterPlugin(){this.op.afterPlugin&&await this.op.afterPlugin()}async beforeModule(){this.op.beforeModule&&await this.op.beforeModule()}async afterModule(){this.op.afterModule&&await this.op.afterModule()}async beforeEmpPlugin(){this.op.beforeEmpPlugin&&await this.op.beforeEmpPlugin()}async afterEmpPlugin(){this.op.afterEmpPlugin&&await this.op.afterEmpPlugin()}async beforeBuild(){this.op.beforeBuild&&await this.op.beforeBuild()}async afterBulid(){this.op.afterBulid&&await this.op.afterBulid()}async beforeDevServe(){this.op.beforeDevServe&&await this.op.beforeDevServe()}async afterDevServe(){this.op.afterDevServe&&await this.op.afterDevServe()}async beforeServe(){this.op.beforeServe&&await this.op.beforeServe()}async afterServe(){this.op.afterServe&&await this.op.afterServe()}}});import es from"fs";var ue,_e,We=m(()=>{"use strict";n();z();Te();w();G();Je();ue=class{store;appSrc="src";appEntry="";base="";target=[];assign(e,t){return t=t||{},y(e,t)}isESM=!1;async autoDevSet(){this.store.mode==="development"&&this.store.empOptions.autoDevBase}checkIsESM(e){return["es3","es5"].indexOf(e)===-1}lifeCycle;async setup(e){this.store=e,await this.syncEmpOptions(),this.lifeCycle=new W(this.store.empOptions.lifeCycle),await this.lifeCycle.afterGetEmpOptions(),this.isESM=this.checkIsESM(this.build.target),this.store.empOptions.target?(this.target=this.store.empOptions.target,Array.isArray(this.target)&&!this.target.includes(this.build.target)&&this.target.push(this.build.target)):this.target=["web",this.build.target];let{appSrc:t,base:s,appEntry:r}=this.store.empOptions;t&&(this.appSrc=t),s&&(this.base=s),r&&(this.appEntry=r)}async chain(){this.store.empOptions.chain&&await this.store.empOptions.chain(this.store.chain)}async plugins(){let e=[];this.store.empOptions.plugins&&Array.isArray(this.store.empOptions.plugins)&&this.store.empOptions.plugins.length>0&&(this.store.empOptions.plugins.map(t=>{e.push(t.rsConfig(this.store))}),await Promise.all(e))}get debug(){let e=!1;return this.store.cliOptions.doctor&&(e={supports:{generateTileGraph:!0}}),this.assign({loggerLevel:"info",clearLog:!0,progress:!0,showRsconfig:!1,showPerformance:!1,rspackCache:!0,rsdoctor:e,infrastructureLogging:{appendOnly:!0,level:"warn"},newTreeshaking:this.store.empConfig.isESM,devShowAllLog:!1},this.store.empOptions.debug)}get build(){let e=this.store.empOptions.build?.staticDir?`${this.store.empOptions.build?.staticDir}/`:"";return this.assign({outDir:"dist",staticDir:e,assetsDir:"assets",publicDir:"public",chunkIds:this.store.isDev?"named":"deterministic",moduleIds:this.store.isDev?"named":"deterministic",sourcemap:this.store.isDev,minify:!this.store.isDev,minOptions:{},cssminOptions:{},target:"es5",polyfill:!1,polyfillInclude:[],coreJsFeatures:"stable",externalHelpers:!1,browserslist:this.store.browserslistOptions.default,swcConfig:{},devtool:"source-map"},{...this.store.empOptions.build,staticDir:e})}get html(){let e=this.store.empOptions.html?.template?{}:{charset:{charset:"utf-8"},"http-equiv":{"http-equiv":"X-UA-Compatible",content:"IE=edge"},viewport:{name:"viewport",content:"width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0"},keywords:{keywords:""},description:{description:""}};return this.assign({title:"EMP",inject:"body",minify:!this.store.isDev,scriptLoading:this.isESM?"module":"defer",meta:e},this.store.empOptions.html)}get entries(){return this.store.empOptions.entries?this.store.empOptions.entries:{}}get server(){let e={host:"0.0.0.0",port:8e3,open:process.platform==="darwin",hot:!0,watchFiles:["src/**/*.html"],static:[{directory:this.store.publicDir,watch:this.store.isDev}],allowedHosts:["all"],historyApiFallback:!0,headers:{"Access-Control-Allow-Origin":"*","Access-Control-Allow-Methods":"GET, POST, PUT, DELETE, PATCH, OPTIONS","Access-Control-Allow-Headers":"X-Requested-With, content-type, Authorization"}};return this.store.empOptions.server?.http2&&(O.httpsType="h2",delete this.store.empOptions.server.http2),this.assign(e,this.store.empOptions.server)}get css(){return this.assign({sass:{mode:"modern",warnRuleAsWarning:!1}},this.store.empOptions.css)}get output(){let e=(this.store.isDev,".[contenthash:8]"),t=this.store.isDev?"":".[contenthash:8]",{assetsDir:s,staticDir:r}=this.store.empConfig.build,p={publicPath:this.store.empConfig.base?this.store.empConfig.base:"auto",crossOriginLoading:"anonymous",filename:`${r}js/[name]${e}.js`,cssFilename:`${r}css/[name]${t}.css`,cssChunkFilename:`${r}css/[name]${t}.css`,assetModuleFilename:`${r}${s}/[name]${e}[ext][query]`,path:this.store.outDir,clean:!0,uniqueName:this.store.uniqueName};return this.assign(p,this.store.empOptions.output)}get define(){let e={mode:this.store.mode,env:this.store.cliOptions.env};return this.store.empOptions.define&&(e={...e,...this.store.empOptions.define}),this.setDefine(e)}setDefine(e){let t=this.store.empOptions.defineFix?this.store.empOptions.defineFix:this.isESM?"esm":"cjs",s={};return Object.keys(e).map(r=>{t==="all"?(s[`import.meta.env.${r}`]=JSON.stringify(e[r]),s[`process.env.${r}`]=JSON.stringify(e[r])):t==="esm"?s[`import.meta.env.${r}`]=JSON.stringify(e[r]):t==="cjs"?s[`process.env.${r}`]=JSON.stringify(e[r]):t==="none"&&(s[`${r}`]=JSON.stringify(e[r]))}),s}get externals(){return this.assign({},this.store.empOptions.externals)}get resolve(){return y({alias:{src:this.store.resolve("src"),"@":this.store.resolve("src")},extensions:["...",".js",".jsx",".mjs",".ts",".tsx",".css",".less",".scss",".sass",".json",".wasm",".vue",".svg",".svga"]},this.store.empOptions.resolve)}async syncEmpOptions(){a.time("[store][empConfig]SyncEmpOptions");let e=await Fe();if(!e||!es.existsSync(e))return;let t=await Ae(e);typeof t=="function"?this.store.empOptions=await t(this.store):this.store.empOptions=t||{},a.timeEnd("[store][empConfig]SyncEmpOptions")}get moduleTransformRule(){let{moduleTransform:e}=this.store.empOptions,t=this.assign({defaultExclude:!1},e),s={and:[],not:[]};return t.defaultExclude===!0&&s.and.push(/(node_modules|bower_components)/),t?.exclude&&(s.and=s.and.concat(t.exclude)),e?.include&&(s.not=t.include),s}get cacheDir(){return this.store.empOptions.cacheDir?this.store.empOptions.cacheDir:"node_modules/.emp-cache"}get ignoreWarnings(){return this.store.empOptions.ignoreWarnings?this.store.empOptions.ignoreWarnings:[/Conflicting order/]}get autoPages(){let e;return this.store.empOptions.autoPages&&(e=typeof this.store.empOptions.autoPages=="boolean"?{}:this.store.empOptions.autoPages,e=this.assign({path:"pages"},e)),e}},_e=new ue});import ts from"fs-extra";var ge,qe,Ve=m(()=>{"use strict";n();ge=class{store;async setup(e){this.store=e;let t=[this.common(),this.stats(),this.devServer(),this.optimization(),this.checkTsconfig()];await Promise.all(t)}async common(){this.store.merge({node:{global:!0},experiments:{outputModule:this.store.empConfig.isESM,topLevelAwait:!0,css:!0},target:this.store.empConfig.target,infrastructureLogging:this.store.empConfig.debug.infrastructureLogging,context:this.store.root,mode:this.store.mode,cache:this.store.empConfig.debug.rspackCache,devtool:this.store.empConfig.build.sourcemap?this.store.empConfig.build.devtool:!1,output:this.store.empConfig.output,resolve:this.store.empConfig.resolve,externals:this.store.empConfig.externals,ignoreWarnings:this.store.empConfig.ignoreWarnings,watchOptions:{ignored:["**/node_modules/**","**/@mf-types/**"]}})}async checkTsconfig(){let e=this.store.resolve("tsconfig.json");if(await ts.exists(e)){let s={tsConfig:e};this.store.merge({resolve:s})}}async stats(){this.store.merge({stats:{colors:!0,all:!1,assets:!1,chunks:!1,timings:!0,version:!0}})}async devServer(){this.store.merge({devServer:this.store.empConfig.server})}async optimization(){let e={moduleIds:this.store.empConfig.build.moduleIds,chunkIds:this.store.empConfig.build.chunkIds,minimize:this.store.empConfig.build.minify,splitChunks:{chunks:"async",cacheGroups:{}}};this.store.empConfig.build.polyfill&&(e.splitChunks.cacheGroups={}),this.store.chain.merge({optimization:e})}},qe=new ge});var de,Xe,Qe=m(()=>{"use strict";n();de=class{store;async setup(e){this.store=e;let t=[this.sass(),this.less(),this.css()];await Promise.all(t)}async sass(){let{rule:e,use:t}=this.store.chainName,s={},{sass:r}=this.store.empConfig.css||{sass:{}};r.mode==="modern"&&(s.implementation=r.implementation?r.implementation:b.resolve("sass-embedded"),s.api=r.api?r.api:"legacy",s.sourceMap=this.store.empConfig.build.sourcemap,r.sassOptions&&(s.sassOptions=r.sassOptions)),typeof r.warnRuleAsWarning<"u"&&(s.warnRuleAsWarning=r.warnRuleAsWarning),typeof r.webpackImporter<"u"&&(s.webpackImporter=r.webpackImporter),this.store.chain.merge({module:{rule:{[e.sass]:{test:/\.(sass|scss)$/,use:{[t.sass]:{loader:b.resolve("sass-loader"),options:s}},type:"css/auto"}}}})}async less(){let{rule:e,use:t}=this.store.chainName,s={loader:b.resolve("less-loader"),options:{lessOptions:{javascriptEnabled:!0}}};this.store.chain.merge({module:{rule:{[e.less]:{test:/\.less$/,use:{[t.less]:s},type:"css/auto"}}}})}async css(){let{rule:e}=this.store.chainName;this.store.chain.merge({module:{rule:{[e.css]:{test:/\.css$/,use:{},type:"css/auto"}}}})}},Xe=new de});import C from"path";import{rspack as ss}from"@rspack/core";var is,ye,Ke,Ye=m(()=>{"use strict";n();z();is=ss.HtmlRspackPlugin,ye=class{store;entriesConfig={};async setup(e){this.store=e,await this.init(),this.toConfig()}setHtmlConfig(e,t){return e.template=this.setTemplate(e.template),e.favicon=this.setFavicion(e.favicon),e.chunks=t,e.filename=`${t[0]}.html`,this.store.empConfig.base&&(e.publicPath=this.store.empConfig.base),e}setChunk(e){return e.replace(C.extname(e),"").replace(`${this.store.empConfig.appSrc}${C.sep}`,"")}setTemplate(e){return e?this.store.resolve(e):this.store.empResolve(C.join("template","index.html"))}setFavicion(e){return e?this.store.resolve(e):this.store.empResolve(C.join("template","favicon.ico"))}setEntryItem(e,t,s){s=s||this.store.resolve(C.join(this.store.empConfig.appSrc,e));let r=this.setChunk(e),p=[s];this.entriesConfig[r]={entry:{[r]:p},html:this.setHtmlConfig(t,[r])},this.store.entries[r]=p}setRspackHtmlPlugin(e,t){this.store.chain.plugin(`${this.store.chainName.plugin.html.prefix}${t}`).use(is,[e])}setRspackEntry(e){this.store.merge({entry:e})}async init(){this.store.empConfig.autoPages?await this.setAutoPage():(await this.setDefaultEntry(),this.setEntryByConfig())}async setAutoPage(){a.time("setAutoPage");let e=this.store.empConfig.autoPages?.path||"pages",t=C.join(this.store.appSrc,e),s=C.join(t,"**","*.{ts,tsx,jsx,js}"),r=await L([s],{windowsPathsNoEscape:!0});r=r.map(p=>p.replace(`${t}${C.sep}`,"")),r.map(p=>{let f=this.store.empConfig.entries[p]||{};this.setEntryItem(p,{...this.store.empConfig.html,...f},C.join(t,p))}),a.timeEnd("setAutoPage")}async setDefaultEntry(){a.time("[store][empConfig]SetDefaultEntry");let e=C.join(this.store.appSrc,this.store.empConfig.appEntry?this.store.empConfig.appEntry:"index.{ts,tsx,jsx,js}"),t=await L([e],{windowsPathsNoEscape:!0});if(t[0]){let s=C.join(this.store.empConfig.appSrc,Object.keys(this.store.empConfig.entries).length>0&&this.store.empConfig.appEntry?this.store.empConfig.appEntry:"index");this.setEntryItem(s,this.store.empConfig.html,t[0])}a.timeEnd("[store][empConfig]SetDefaultEntry")}setEntryByConfig(){if(Object.keys(this.store.empConfig.entries).length>0)for(let[e,t]of Object.entries(this.store.empConfig.entries))this.setEntryItem(e,{...this.store.empConfig.html,...t})}toConfig(){for(let[e,t]of Object.entries(this.entriesConfig))this.setRspackHtmlPlugin(t.html,e),this.setRspackEntry(t.entry)}},Ke=new ye});import Ze from"path";var ve,et,tt=m(()=>{"use strict";n();w();ve=class{store;swcJsOptions={};swcTsOptions={};coreJs={version:"3",alias:"",path:""};async setup(e){this.store=e,this.swcInitOptions(),await this.run()}async run(){let e=[this.jsDataUrl(),this.files(),this.scripts(),this.rspackGenerator(),this.rspackParser()];await this.store.empConfig.lifeCycle.beforeModule(),await Promise.all(e),await this.store.empConfig.lifeCycle.afterModule()}rspackGenerator(){let e=this.store.isDev?"[path][name]-[local]-[hash:5]":"[local]-[hash:5]";this.store.chain.merge({module:{generator:{css:{localIdentName:e},"css/auto":{localIdentName:e},"css/module":{localIdentName:e}}}})}rspackParser(){this.store.chain.merge({module:{parser:{css:{namedExports:!1},"css/auto":{namedExports:!1},"css/module":{namedExports:!1}}}})}get isPolyfill(){return this.store.empConfig.build.polyfill}swcParser(e){switch(e){case"js":return{syntax:"ecmascript",jsx:!0,decorators:!0,decoratorsBeforeExport:!1};case"ts":return{syntax:"typescript",decorators:!0,tsx:!0,dynamicImport:!0}}}swcJsc(e){let{target:t,externalHelpers:s}=this.store.empConfig.build;return{parser:this.swcParser(e),transform:{},target:t,externalHelpers:s,preserveAllComments:!0}}get swcCoreVersion(){let[e,t]=this.coreJs.version.split(".");return`${e}.${t}`}swcOptions(e){let t={jsc:y(this.swcJsc(e),{...this.store.empConfig.build.swcConfig}),isModule:"unknown"};return this.isPolyfill&&(delete t.jsc.target,t.env={coreJs:this.swcCoreVersion,targets:this.store.empConfig.build.browserslist},this.store.empConfig.isESM||(t.env.mode=this.store.empConfig.build.polyfill),this.store.empConfig.build.polyfill==="usage"&&(t.env.shippedProposals=!0,t.env.include=this.store.empConfig.build.polyfillInclude)),t}swcInitOptions(){let{externalHelpers:e}=this.store.empConfig.build;e&&this.store.chain.resolve.alias.set("@swc/helpers",Ze.dirname(b.resolve("@swc/helpers/package.json"))),this.coreJs.path=b.resolve("core-js/package.json");let t=ie(this.coreJs.path);t&&(this.coreJs.version=t),this.coreJs.alias=Ze.dirname(this.coreJs.path),this.store.empConfig.build.polyfill&&(this.store.chain.resolve.alias.set("core-js",this.coreJs.alias),this.store.chain.module.rule("javascript").exclude.add(/core-js/),this.store.chain.module.rule("typescript").exclude.add(/core-js/)),this.swcTsOptions=this.swcOptions("ts"),this.swcJsOptions=this.swcOptions("js")}jsDataUrl(){this.store.chain.module.rule("jsDataUrl").merge({mimetype:{or:["text/javascript","application/javascript"]}}).resolve.set("fullySpecified",!1).end().use("swcJsParser").loader("builtin:swc-loader").options(this.swcJsOptions)}async scripts(){let e=[],{rule:t,use:s}=this.store.chainName;this.store.chain.merge({module:{parser:{javascript:{exportsPresence:"error",importExportsPresence:"error"}},rule:{[t.mjs]:{test:/\.m?js/,resolve:{fullySpecified:!1}},[t.typescript]:{test:/\.(ts|tsx)$/,exclude:e,use:{[s.swc]:{loader:"builtin:swc-loader",options:this.swcTsOptions}}},[t.javascript]:{test:/\.((m|c)?js|jsx)$/,exclude:e,use:{[s.swc]:{loader:"builtin:swc-loader",options:this.swcJsOptions}}},[t.sourceMap]:{test:/\.[tj]sx?$/,enforce:"pre",use:{[s.sourceMap]:{loader:b.resolve("source-map-loader")}}}}}})}async files(){let{rule:e}=this.store.chainName;this.store.chain.merge({module:{rule:{[e.svg]:{test:/\.svg$/,type:"asset/resource"}}}}),this.store.chain.merge({module:{rule:{[e.inline]:{resourceQuery:/inline/,type:"asset/inline"}}}}),this.store.chain.merge({module:{rule:{[e.image]:{test:/\.(png|jpe?g|gif|webp|ico)$/i,type:"asset/resource"},[e.font]:{test:/\.(|otf|ttf|eot|woff|woff2)$/i,type:"asset/resource"},[e.svga]:{test:/\.(svga)$/i,type:"asset/resource"}}}})}},et=new ve});import st from"fs";import B from"@rspack/core";var be,it,rt=m(()=>{"use strict";n();be=class{store;async setup(e){this.store=e;let t=[this.define(),this.anylayze(),this.progress(),this.copy(),this.minify(),this.redoctor()];await this.store.empConfig.lifeCycle.beforePlugin(),await Promise.all(t),await this.store.empConfig.lifeCycle.afterPlugin()}async anylayze(){if(!this.store.cliOptions.analyze)return;let{default:{BundleAnalyzerPlugin:e}}=await import("webpack-bundle-analyzer");this.store.chain.plugin(this.store.chainName.plugin.bundleAnalyzer).use(e,[{analyzerPort:this.store.empConfig.server.port,defaultSizes:"gzip",analyzerHost:this.store.getLanIp()||"127.0.0.1"}])}async define(){this.store.chain.plugin(this.store.chainName.plugin.define).use(B.DefinePlugin,[this.store.empConfig.define])}async copy(){let e=this.store.resolve("public");st.existsSync(e)&&st.readdirSync(e).length>0&&this.store.chain.plugin(this.store.chainName.plugin.copy).use(B.CopyRspackPlugin,[{patterns:[{from:e,to:this.store.resolve(this.store.empConfig.build.outDir),noErrorOnMissing:!0,globOptions:{ignore:["**/.DS_Store"]}}]}])}async progress(){this.store.empConfig.debug.progress&&this.store.chain.plugin(this.store.chainName.plugin.progress).use(B.ProgressPlugin,[{prefix:"EMP"}])}minify(){this.store.chain.optimization.minimize(this.store.mode==="production"),this.store.chain.optimization.minimizer(this.store.chainName.minimizer.minJs).use(B.SwcJsMinimizerRspackPlugin,[this.store.empConfig.build.minOptions]),this.store.chain.optimization.minimizer(this.store.chainName.minimizer.minCss).use(B.LightningCssMinimizerRspackPlugin,[this.store.empConfig.build.cssminOptions])}redoctor(){if(!this.store.empConfig.debug.rsdoctor)return;let{RsdoctorRspackPlugin:e}=b("@rsdoctor/rspack-plugin"),t={};typeof this.store.empConfig.debug.rsdoctor=="object"&&(t=this.store.empConfig.debug.rsdoctor),this.store.chain.plugin(this.store.chainName.plugin.rsdoctor).use(e,[t])}},it=new be});var we,ot,nt=m(()=>{"use strict";n();Ve();Qe();Ye();tt();rt();we=class{store;async setup(e){this.store=e;let t=[qe.setup(this.store),et.setup(this.store),it.setup(this.store),Ke.setup(this.store),Xe.setup(this.store)];await Promise.all(t),await this.store.empConfig.lifeCycle.beforeEmpPlugin(),await this.store.empConfig.plugins(),await this.store.empConfig.lifeCycle.afterEmpPlugin(),await this.store.empConfig.chain()}},ot=new we});var at,pt=m(()=>{"use strict";n();at={rule:{mjs:"mjs",typescript:"typescript",javascript:"javascript",sourceMap:"sourceMapLoader",inline:"inline",svg:"svg",image:"image",font:"fonts",svga:"svga",sass:"sass",less:"less",css:"css"},use:{swc:"swc",sourceMap:"sourceMapLoader",sass:"sassLoader",less:"lessLoader"},plugin:{bundleAnalyzer:"bundleAnalyzerPlugin",define:"definePlugin",copy:"copyRspackPlugin",progress:"progressPlugin",html:{prefix:"html-plugin-"},rsdoctor:"rsdoctor"},minimizer:{minJs:"minJs",minCss:"minCss"}}});import rs from"fs/promises";import x from"path";import os from"util";import ns from"webpack-chain";var Ce,o,v=m(()=>{"use strict";n();E();w();We();nt();pt();Ce=class{empPkg={dependencies:{},devDependencies:{},version:"2.0.0",name:""};pkg={dependencies:{},devDependencies:{},version:"0.0.0",name:""};root=process.cwd();empRoot=x.resolve(c,l).replace(`${x.sep}dist${x.sep}index.js`,"");empSource=x.resolve(this.empRoot,"dist");resolve=e=>x.isAbsolute(e)?e:x.resolve(this.root,e);empResolve=e=>x.resolve(this.empRoot,e);appSrc="";outDir="";publicDir="";resource={dir:"",key:"",cert:""};chainName=at;cacheDir="";mode="development";cliMode="dev";isDev=!0;cliOptions;chain;rsConfig;empOptions={};empConfig;vCompare=oe;deepAssign=y;getLanIp=M;entries={};debug;async setup(e,t){a.time("[store]Setup"),await this.initVars(e,t),this.empConfig=_e,await this.empConfig.setup(this),this.debug={...this.empConfig.debug},this.initPaths(),this.chain=new ns,await ot.setup(this),this.setLogger(),this.toConfig(),this.logConfig(),a.timeEnd("[store]Setup")}async initVars(e,t){this.cliOptions=t||{},this.cliMode="prod",this.mode=e==="dev"?"development":"production",this.isDev=this.mode==="development",process.env.NODE_ENV=e==="dev"?"development":"production";let s=b(this.empResolve("package.json")),r=b(this.resolve("package.json"));this.empPkg={...this.empPkg,...s},this.pkg={...this.pkg,...r},this.resource.dir=x.join(this.empRoot,"resource"),this.resource.cert=x.join(this.resource.dir,"emp.cert"),this.resource.key=x.join(this.resource.dir,"emp.key")}initPaths(){this.appSrc=this.resolve(this.empConfig.appSrc),this.outDir=this.resolve(this.empConfig.build.outDir),this.publicDir=this.resolve(this.empConfig.build.publicDir),this.cacheDir=this.resolve(this.empConfig.cacheDir)}setLogger(){let e=this.cliMode==="dev"?"debug":"info";this.debug.loggerLevel&&(e=this.debug.loggerLevel),a.setup({fullName:`EMP\u26A1${this.empPkg.version}${this.cliMode==="dev"?".DEV":""}`,brandName:"EMP",logLevel:e})}merge(e){this.chain.merge(e)}toConfig(){this.rsConfig=this.chain.toConfig()}logConfig(){if(this.debug.showRsconfig)if(typeof this.debug.showRsconfig=="string"){let e=x.join(this.root,this.debug.showRsconfig);rs.writeFile(e,JSON.stringify(this.rsConfig,null,2))}else{this.debug.clearLog=!1;let e={colors:!0,depth:null},t=typeof this.debug.showRsconfig=="object"?y(e,this.debug.showRsconfig):e;console.log(a.link("[Compile Config]")),console.log(os.inspect(this.rsConfig,t))}}get browserslistOptions(){return{default:["chrome >= 87","edge >= 88","firefox >= 78","safari >= 14"],h5:["iOS >= 9","Android >= 4.4","last 2 versions","> 0.2%","not dead"],node:["node >= 16"]}}get uniqueName(){return this.pkg.name.replaceAll("/","_").replaceAll("@","_").replaceAll("-","_")}},o=new Ce});import as from"fs";import k from"path";import{gzipSizeSync as ps}from"gzip-size";function gs(i,e){let t=[i,e],s=["File","Size","Gzipped"].reduce((r,p,f)=>{let g=t[f],P=p;return g&&(P=p.length<g?p+" ".repeat(g-p.length):p),`${r+P} `}," ");console.log(D.bold(s))}async function lt(i){let e=i.toJson({all:!1,assets:!0,timings:!0}),s=e.assets.filter(u=>fs(u.name)).map(us);s.sort((u,T)=>u.size-T.size);let r=Math.max(...s.map(u=>u.sizeLabel.length)),p=Math.max(...s.map(u=>(u.folder+k.sep+u.name).length));gs(p,r);let f=0,g=0;s.forEach(u=>{let{sizeLabel:T}=u,{name:yt,folder:vt,gzipSizeLabel:bt}=u,$e=(vt+k.sep+yt).length,De=T.length;if(f+=u.size,g+=u.gzippedSize,De<r){let Y=" ".repeat(r-De);T+=Y}let je=j(u.folder+k.sep)+ds(u.name);if($e<p){let Y=" ".repeat(p-$e);je+=Y}a.info(` ${je} ${j(T)} ${bt}`)});let P=`${D.bold("Total size:")} ${q(f)}`,F=`${D.bold("Gzipped size:")} ${q(g)}`;a.info(`
13
+ ${P}
14
+ ${F}
15
+ `),a.info(`${S("\u2713")} Ready in ${I(Number(e.time))}
16
+ `)}function V(i=0){a.info(`${S("\u2713")} Ready in ${I(Number(i))}`)}var ls,cs,ms,fs,hs,us,q,ds,X=m(()=>{"use strict";n();R();v();E();w();ls=/\.html$/,cs=/\.(?:js|mjs|cjs|jsx)$/,ms=/\.css$/,fs=i=>!/\.map$/.test(i)&&!/\.LICENSE\.txt$/.test(i),hs=i=>i>300*1e3?Z:i>100*1e3?U:ee,us=i=>{let e=i.name.split("?")[0],t=q(i.size),s=k.basename(e),r=k.join(k.basename(o.empConfig.build.outDir),k.dirname(e)),p=as.readFileSync(k.join(o.empConfig.build.outDir,e)),f=p.length,g=ps(p),P=hs(g)(q(g));return{size:f,folder:r,name:s,gzippedSize:g,sizeLabel:t,gzipSizeLabel:P}};q=i=>{let e=i/1e3;return`${e.toFixed(e<1?2:1)} kB`},ds=i=>cs.test(i)?U(i):ms.test(i)?S(i):ls.test(i)?D(i):te(i)});var ct={};N(ct,{default:()=>bs});import{rspack as ys}from"@rspack/core";import{RspackDevServer as vs}from"@rspack/dev-server";var xe,bs,mt=m(()=>{"use strict";n();X();E();w();G();v();xe=class extends O{get rspackDevConfig(){return y(o.rsConfig,{stats:{all:o.empConfig.debug.devShowAllLog,colors:!0,assets:!1,chunks:!1,entrypoints:!1,timings:!1,version:!1,errors:!0,warnings:!0},devServer:{open:!1,setupExitSignals:!0}})}async devServerConfig(){let e=Object.assign({},o.rsConfig.devServer);if(this.isHttps&&(e.https===!0&&delete e.https,!e.server)){let[t,s]=await this.getcert();e.server={type:"https",options:{key:t,cert:s}}}return e}async run(){let e=ys(this.rspackDevConfig);if(!o.rsConfig.devServer){a.error("devServer is not defined in config");return}let t=await this.devServerConfig(),s=new vs(t,e);this.startOpen(),o.empConfig.lifeCycle.beforeDevServe&&await o.empConfig.lifeCycle.beforeDevServe(),await s.start();let r=p=>{let f=p?.toJson({all:!1,colors:!1,assets:!1,chunks:!1,timings:!0});V(f.time)};o.debug.showPerformance&&e.hooks.afterDone.tap("done",r),s.middleware?.waitUntilValid(p=>{o.debug.showPerformance||r(p),o.empConfig.lifeCycle.afterDevServe&&o.empConfig.lifeCycle.afterDevServe()})}},bs=new xe});import ws from"https";import Cs from"compression";import xs from"cors";import Ss from"express";var Q,ft=m(()=>{"use strict";n();G();Q=class extends O{app;async init(){let e=Ss();e.use(Cs()),e.use(xs()),this.app=e}async server(){if(this.isHttps){let[e,t]=await this.getcert();ws.createServer(typeof this.isHttps!="boolean"?this.isHttps:{key:e,cert:t},this.app).listen(this.sf.port,async()=>{this.startOpen(),await this.onReady()})}else this.app.listen(this.sf.port,async()=>{this.startOpen(),await this.onReady()})}async onReady(){}async middleware(){}async start(){await this.init(),await this.middleware(),await this.server()}}});var Se={};N(Se,{ServeScript:()=>K,default:()=>$s});import Es from"fs";import Os from"fs/promises";import Ps from"path";import ks from"express";var K,$s,Ee=m(()=>{"use strict";n();X();E();v();ft();K=class extends Q{timing=0;async run(){if(this.timing=Date.now(),!Es.existsSync(o.outDir))return a.sysError(`emp serve must be executed after emp build,${o.outDir} not exist!`);o.empConfig.lifeCycle.beforeServe&&await o.empConfig.lifeCycle.beforeServe(),this.start()}async middleware(){let e=o.resolve(o.rsConfig.output?.path);this.app.use(ks.static(e));let t=await Os.readFile(Ps.join(e,"index.html"),"utf8");this.app.get("*",(s,r)=>r.send(t))}async onReady(){V(Date.now()-this.timing),o.empConfig.lifeCycle.afterServe&&await o.empConfig.lifeCycle.afterServe()}},$s=new K});var ht={};N(ht,{default:()=>js});import{rspack as Ds}from"@rspack/core";var Oe,js,ut=m(()=>{"use strict";n();X();E();G();v();Oe=class extends O{isWatchMode=!1;rspackConfig;isuseServe=!1;isStartServe=!1;watchMode(){this.isWatchMode&&this.rspackConfig.optimization&&(this.rspackConfig.optimization.moduleIds="named",this.rspackConfig.optimization.chunkIds="named",this.rspackConfig.watch=!0)}async startServe(){if(!this.isuseServe||this.isStartServe)return;this.isStartServe=!0;let{default:e}=await Promise.resolve().then(()=>(Ee(),Se));await e.setup("serve",o.cliOptions)}async run(){await o.empConfig.lifeCycle.beforeBuild(),this.isWatchMode=!!o.cliOptions.watch,this.isuseServe=!!o.cliOptions.serve,this.rspackConfig=o.rsConfig,this.isWatchMode&&this.watchMode(),Ds(this.rspackConfig,async(e,t)=>{if(e!==null){a.error(e.stack||e),e.message&&a.error(e.message);return}if(!t){a.red("Stats is Undefined.");return}t.hasErrors()&&(a.error(t.toString({all:!1,colors:!0,errors:!0})),a.red("Failed to compile."),process.exit(1)),t.hasWarnings()&&(a.yellow("Compiled with warnings."),a.warn(t.toString({all:!1,chunks:!1,assets:!1,colors:!0,errors:!0,warnings:!0}))),await lt(t),this.startServe(),await o.empConfig.lifeCycle.afterBulid()})}},js=new Oe});n();import{rspack as Jo}from"@rspack/core";n();v();import Rs from"process";import{program as $}from"commander";function gt(){$.version(o.empPkg.version,"-v, --version").usage("<command> [options]"),$.command("dev").description("Dev \u6A21\u5F0F").option("-e, --env <env>","\u90E8\u7F72\u73AF\u5883 dev\u3001test\u3001prod").option("-rd, --doctor","\u5F00\u542Frsdoctor,\u53EF\u901A\u8FC7debug.rsdoctor\u64CD\u4F5C").option("-h, --hot","\u662F\u5426\u4F7F\u7528\u70ED\u66F4\u65B0 \u9ED8\u8BA4\u542F\u52A8").option("-o, --open","\u662F\u5426\u6253\u5F00\u8C03\u8BD5\u9875\u9762 \u9ED8\u8BA4\u4E0D\u6253\u5F00").option("-t, --ts","\u751F\u6210\u7C7B\u578B\u6587\u4EF6 \u9ED8\u8BA4\u4E3A false").option("-pr, --profile","\u7EDF\u8BA1\u6A21\u5757\u6D88\u8017").option("-cl, --clearLog <clearLog>","\u6E05\u7A7A\u65E5\u5FD7 \u9ED8\u8BA4\u4E3A true").option("-ev, --env-vars <key=value>","\u5B9A\u4E49\u4E00\u4E2A\u73AF\u5883\u53D8\u91CF -ev key=value \u591A\u4E2A\u73AF\u5883\u53D8\u91CF\u91CD\u590D\u8C03\u7528 -ev key=value -ev key=value",(i,e)=>{let[t,s]=i.split("=");return e[t]=s,e},{}).action(async i=>{let{default:e}=await Promise.resolve().then(()=>(mt(),ct));await e.setup("dev",i)}),$.command("build").description("Build \u6A21\u5F0F").option("-e, --env <env>","\u90E8\u7F72\u73AF\u5883 dev\u3001test\u3001prod").option("-rd, --doctor","\u5F00\u542Frsdoctor,\u53EF\u901A\u8FC7debug.rsdoctor\u64CD\u4F5C").option("-a, --analyze","\u751F\u6210\u5206\u6790\u62A5\u544A \u9ED8\u8BA4\u4E3A false").option("-t, --ts","\u751F\u6210\u7C7B\u578B\u6587\u4EF6 \u9ED8\u8BA4\u4E3A false").option("-pr, --profile","\u7EDF\u8BA1\u6A21\u5757\u6D88\u8017").option("-cl, --clearLog <clearLog>","\u6E05\u7A7A\u65E5\u5FD7 \u9ED8\u8BA4\u4E3A true").option("-w, --watch","watch \u6A21\u5F0F").option("-sv, --serve","watch \u6A21\u5F0F\u4E0B\u542F\u52A8serve").option("-ev, --env-vars <key=value>","\u5B9A\u4E49\u4E00\u4E2A\u73AF\u5883\u53D8\u91CF -ev key=value \u591A\u4E2A\u73AF\u5883\u53D8\u91CF\u91CD\u590D\u8C03\u7528 -ev key=value -ev key=value",(i,e)=>{let[t,s]=i.split("=");return e[t]=s,e},{}).action(async i=>{let{default:e}=await Promise.resolve().then(()=>(ut(),ht));await e.setup("build",i)}),$.command("serve").description("Server \u6A21\u5F0F").option("-cl, --clearLog <clearLog>","\u6E05\u7A7A\u65E5\u5FD7 \u9ED8\u8BA4\u4E3A true").action(async i=>{let{default:e}=await Promise.resolve().then(()=>(Ee(),Se));await e.setup("serve",i)}),$.command("dts").description("\u62C9\u53D6 remote \u9879\u76EE\u7684 d.ts").option("-p, --typingsPath <typingsPath>","\u4E0B\u8F7D\u76EE\u5F55").option("-e, --env <env>","\u90E8\u7F72\u73AF\u5883 dev\u3001test\u3001prod").action(i=>{}),$.command("init").description("\u521D\u59CB\u5316 emp \u9879\u76EE").option("-d, --data [data]","JSON\u6570\u636E http\u5730\u5740 \u6216\u8005 \u6587\u4EF6\u8DEF\u5F84\u76F8\u5BF9\u3001\u7EDD\u5BF9\u8DEF\u5F84").action(i=>{}),$.parse(Rs.argv)}n();z();v();import dt from"fs/promises";import Pe from"path";var Ls=/(?:(?:import|export)\s?(?:type)?\s?(?:(?:\{[^;\n]+\})|(?:[^;\n]+))\s?from\s?['"][^;\n]+['"])|(?:import\(['"][^;\n]+?['"]\))/g,As=/(?:import|export)\s?(?:type)?\s?\{?.+\}?\s?from\s?['"](.+)['"]/,Fs=/import\(['"]([^;\n]+?)['"]\)/,ke=class{list=[];outDir=o.resolve("dist");aliasName="@empjs/cli";async setup(e,t){e&&(this.outDir=e),t&&(this.aliasName=t);let s=await this.readDts();await this.writeCode(s)}async readDts(){this.list=await L([`${o.empConfig.build.outDir}/**/*.d.ts`],{windowsPathsNoEscape:!0});let e=[];this.list.map(s=>{s=o.resolve(s),e.push(this.readFile(s))});let t=await Promise.all(e);return t=t.map(s=>this.replaceAliasPath(s)),t}async readFile(e){let t=await dt.readFile(e,{encoding:"utf-8"});return{src:e,code:t}}replaceAliasPath({src:e,code:t}){t=t.replace(Ls,r=>{let p=r.match(As);if(p||(p=r.match(Fs)),p&&p[1]){let f=p[1];if(!f.startsWith("."))return r;let g=Pe.resolve(Pe.dirname(e),f).replace(this.outDir,this.aliasName);return r.replace(p[1],g)}return r});let s=e.replace(this.outDir,this.aliasName).replace(".d.ts","");return s.endsWith("/index")&&(s=s.replace("/index","")),t=this.warpDeclareModule(s,t),{code:t,src:e,mod:s}}warpDeclareModule(e,t){return`declare module '${e}' {\r
17
+ ${t}}\r
18
+ `}async writeCode(e){let t="";e.map(s=>{t+=s.code}),await dt.writeFile(Pe.join(this.outDir.replace("dist","types"),"type.d.ts"),t)}},Ts=new ke;v();z();function Vo(i){return i}export{Vo as defineConfig,Ts as dts,Le as empHelper,Jo as rspack,gt as runScript,o as store};