@dd-code/uni-tools 1.0.8 → 1.0.10

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.mjs.js CHANGED
@@ -1,14 +1,15 @@
1
1
  import path from 'path';
2
2
  import fs from 'fs';
3
3
  import crypto from 'crypto';
4
+ import chokidar from 'chokidar';
4
5
  import { MultiBar, Presets } from 'cli-progress';
5
6
  import chalk from 'chalk';
6
7
  import fsExtra from 'fs-extra';
7
- import chokidar from 'chokidar';
8
8
  import WebSocket, { WebSocketServer } from 'ws';
9
9
  import express from 'express';
10
10
  import http from 'http';
11
11
  import cors from 'cors';
12
+ import 'child_process';
12
13
 
13
14
  /******************************************************************************
14
15
  Copyright (c) Microsoft Corporation.
@@ -151,6 +152,23 @@ function uniReadFile(filaPath) {
151
152
  }
152
153
  return "";
153
154
  }
155
+ /**
156
+ * 读取文件内容
157
+ * 支持JSON文件的自动解析
158
+ * @param {string} filaPath - 文件路径
159
+ * @returns {string|Object} 返回文件内容,JSON文件返回对象,其他返回字符串
160
+ */
161
+ function uniFsReadJSONFile(filaPath) {
162
+ try {
163
+ var res = fs.readFileSync(filaPath, "utf-8");
164
+ return JSON.parse(res);
165
+ }
166
+ catch (e) {
167
+ // console.error(`${filaPath} notfound`);
168
+ // console.log(e);
169
+ }
170
+ return {};
171
+ }
154
172
  /**
155
173
  * 写入文件内容
156
174
  * 自动创建目录结构,支持对象和字符串内容
@@ -182,6 +200,7 @@ var loadViteConfig = function (mode) {
182
200
  return loadEnv(mode, ROOT, "MFE_");
183
201
  };
184
202
  var walkDir = function (outDir, emitted) {
203
+ if (emitted === void 0) { emitted = new Set(); }
185
204
  var root = path.isAbsolute(outDir)
186
205
  ? outDir
187
206
  : path.resolve(process.cwd(), outDir);
@@ -195,6 +214,7 @@ var walkDir = function (outDir, emitted) {
195
214
  walk(p);
196
215
  else
197
216
  all.push(path.relative(root, p));
217
+ // path.relative(root, p)
198
218
  });
199
219
  };
200
220
  walk(root);
@@ -226,6 +246,20 @@ function generateHash(content, algorithm, encoding) {
226
246
  function generateSHA256(content) {
227
247
  return generateHash(content, "sha256");
228
248
  }
249
+ var genreFileInfoRow = function (row) {
250
+ var fileName = row.fileName, source = row.source;
251
+ var name = path.basename(fileName);
252
+ var dir = path.dirname(fileName);
253
+ var suffix = dir === "." ? "" : "".concat(dir, "/");
254
+ return {
255
+ fileName: fileName,
256
+ fileUrl: "".concat(suffix).concat(generateSHA256((source === null || source === void 0 ? void 0 : source.toString()) || "").slice(0, 8), "_").concat(name),
257
+ };
258
+ };
259
+ var createFileWatcher = function (filePath, opt) {
260
+ var watcher = chokidar.watch(filePath, __assign({ persistent: true, ignoreInitial: true, usePolling: true, interval: 100, awaitWriteFinish: { stabilityThreshold: 200, pollInterval: 100 }, followSymlinks: true, depth: 99 }, opt));
261
+ return watcher;
262
+ };
229
263
 
230
264
  var UniCdnManager = /** @class */ (function () {
231
265
  function UniCdnManager() {
@@ -258,10 +292,19 @@ var cdn = new UniCdnManager();
258
292
 
259
293
  // CDN 文件保存路径
260
294
  var SAVE_CDN_FILE_PATH = path.join(process.cwd(), "node_modules/@dd-code/uni-files");
295
+ path.join(process.cwd(), "node_modules/@dd-code/__main-pwd.txt");
296
+ path.join(process.cwd(), "node_modules/@dd-code/manifest-list.json");
261
297
  path.join(process.cwd(), "node_modules/@dd-code/current-files");
298
+ // 发布目录路径
299
+ var PUBLISH_PATH = path.join(process.cwd(), "dist/publish");
262
300
  // Manifest 文件名
263
301
  var MANIFEST_NAME = "mfe-uni-manifest.json";
264
- var ROOT_APP_CODE = "main"; //"__MFE_APP_ROOT__";
302
+ var ROOT_APP_CODE = "__MFE_APP_ROOT__";
303
+ var EBuildMode;
304
+ (function (EBuildMode) {
305
+ EBuildMode["BUILD"] = "build";
306
+ EBuildMode["SERVE"] = "serve";
307
+ })(EBuildMode || (EBuildMode = {}));
265
308
  // Manifest CDN 目录 URL 模板
266
309
  var MANIFEST_CND_DIR_URL = "{mode}/static-repository/mfe-uni/{code}/{appCode}";
267
310
  var getManifestCdnDirUrl = function (_a) {
@@ -352,6 +395,7 @@ var formatCliCommandConfig = function (mode) {
352
395
  code: viteEnv.MFE_UNI_CODE,
353
396
  mode: mode,
354
397
  cdn: viteEnv.MFE_CDN_HOST,
398
+ serve: viteEnv.MFE_UNI_SERVE, // 是否开启 serve 功能
355
399
  };
356
400
  };
357
401
  var checkIsRootManifest = function (manifest) {
@@ -359,12 +403,13 @@ var checkIsRootManifest = function (manifest) {
359
403
  };
360
404
  var WS_PORT = 3560;
361
405
  var WS_PATH = "/__mfe__ws__";
406
+ var HTTP_PATH = "/__mfe__http__";
362
407
  var E_WS_TYPE;
363
408
  (function (E_WS_TYPE) {
364
409
  E_WS_TYPE["INIT"] = "init_files";
365
410
  E_WS_TYPE["CHANGE"] = "change_files";
366
411
  })(E_WS_TYPE || (E_WS_TYPE = {}));
367
- var getMainAppJSon = function (mode, appCode) {
412
+ var getNodeModuleMainAppJSon = function (mode, appCode) {
368
413
  return path.join(SAVE_CDN_FILE_PATH, mode || "dev", appCode, "app.json");
369
414
  };
370
415
  var getMainAppJsonPath = function () {
@@ -420,10 +465,17 @@ var CliProgressManager = /** @class */ (function () {
420
465
  var CliProgressManager$1 = new CliProgressManager();
421
466
 
422
467
  var getDownloadedFilePath = function (conf) {
423
- return path.resolve(SAVE_CDN_FILE_PATH, conf.env, conf.appCode);
468
+ if (!conf.mode && !conf.env) {
469
+ throw new Error("appCode: ".concat(conf.appCode, " mode or env is required"));
470
+ }
471
+ if (!conf.appCode) {
472
+ throw new Error("appCode is required");
473
+ }
474
+ return path.resolve(SAVE_CDN_FILE_PATH, conf.mode || conf.env, conf.appCode);
424
475
  };
425
476
  var getNodeModulesEnvAppCodeFilePath = function (conf, fileName) {
426
- return path.resolve(getDownloadedFilePath(conf), fileName);
477
+ var savePath = getDownloadedFilePath(conf);
478
+ return path.resolve(savePath, fileName);
427
479
  };
428
480
  /**
429
481
  * 获取清单文件 URL 列表
@@ -592,19 +644,20 @@ var downloadProjectFiles = function (manifestList) { return __awaiter(void 0, vo
592
644
  }); };
593
645
 
594
646
  var checkDownloadFilesIsExpired = function (manifestList) {
595
- return manifestList.filter(function (conf) {
647
+ var filterList = manifestList.filter(function (conf) {
596
648
  var targetPath = getNodeModulesEnvAppCodeFilePath(conf, MANIFEST_NAME);
597
649
  var oldJson = uniReadFile(targetPath);
598
650
  var flag = !oldJson || (oldJson === null || oldJson === void 0 ? void 0 : oldJson.hash) !== conf.hash;
599
651
  return flag;
600
652
  });
653
+ return filterList;
601
654
  };
602
655
  var createManifestManager = function () {
603
656
  var envObj = process.env;
604
657
  var row = {
605
658
  code: "",
606
659
  mode: "",
607
- cdn: '',
660
+ cdn: "",
608
661
  hash: "",
609
662
  publicPath: "",
610
663
  appCode: "",
@@ -616,26 +669,29 @@ var createManifestManager = function () {
616
669
  get value() {
617
670
  return row;
618
671
  },
619
- setFiles: function (outDir, all) {
620
- var files = all.map(function (i) {
621
- var filePath = path.resolve(outDir, i);
622
- var content = fs.readFileSync(filePath, "utf-8");
623
- var contentHash = generateSHA256(content);
624
- return {
625
- fileName: i,
626
- fileUrl: "".concat(contentHash.slice(0, 8), "_").concat(path.basename(i)),
627
- };
628
- });
672
+ setFiles: function (files) {
673
+ // const files = all.map((i) => {
674
+ // const filePath = path.resolve(outDir, i);
675
+ // const content = fs.readFileSync(filePath, "utf-8");
676
+ // const contentHash = generateSHA256(content).slice(0, 8);
677
+ // const dirName = path.dirname(i);
678
+ // const fileName = path.basename(i)
679
+ // const suffixName = dirName === "." ? "" : `${dirName}/`;
680
+ // return {
681
+ // fileName: i,
682
+ // fileUrl: `${suffixName}${contentHash}_${fileName}`,
683
+ // };
684
+ // });
629
685
  row.files = files;
630
686
  },
631
687
  setPagesJson: function (pagesJson) {
632
688
  row.pagesJson = pagesJson;
633
689
  },
634
- saveFile: function (outDir) {
635
- var files = row.files.filter(function (i) { return i.fileName !== MANIFEST_NAME; });
636
- row.hash = generateSHA256(JSON.stringify(__assign(__assign({}, row), { files: files })));
637
- var filePath = path.resolve(outDir, MANIFEST_NAME);
638
- writeFiles(filePath, JSON.stringify(row, null, 2));
690
+ saveFile: function (filePath) {
691
+ // const files = row.files.filter((i) => i.fileName !== MANIFEST_NAME);
692
+ var newManifest = __assign(__assign({}, row), { isServe: undefined });
693
+ newManifest.hash = generateSHA256(JSON.stringify(__assign({}, newManifest)));
694
+ writeFiles(filePath, JSON.stringify(newManifest, null, 2));
639
695
  },
640
696
  setEnv: function (mode) {
641
697
  // const env = loadViteConfig(mode);
@@ -650,6 +706,7 @@ var createManifestManager = function () {
650
706
  row.isRoot = true;
651
707
  row.apps = mfeJson.apps;
652
708
  }
709
+ row.isServe = env.serve;
653
710
  row.publicPath = getManifestCdnDirUrl(row);
654
711
  },
655
712
  dependencies: [],
@@ -664,15 +721,86 @@ var createManifestManager = function () {
664
721
  };
665
722
  };
666
723
 
667
- var resetOutDir = function (currentManifestJson, config) {
724
+ var getMainProcess = function () { return __awaiter(void 0, void 0, void 0, function () {
725
+ var URL, mainProcess, result;
726
+ return __generator(this, function (_a) {
727
+ switch (_a.label) {
728
+ case 0:
729
+ URL = "http://localhost:".concat(WS_PORT).concat(HTTP_PATH, "/root-path");
730
+ return [4 /*yield*/, fetch(URL)];
731
+ case 1:
732
+ mainProcess = _a.sent();
733
+ return [4 /*yield*/, mainProcess.json()];
734
+ case 2:
735
+ result = _a.sent();
736
+ console.log(result, "mainProcess");
737
+ return [2 /*return*/, result];
738
+ }
739
+ });
740
+ }); };
741
+ var getMainProcessLoop = function () { return __awaiter(void 0, void 0, void 0, function () {
742
+ var mainProcess;
743
+ return __generator(this, function (_a) {
744
+ switch (_a.label) {
745
+ case 0:
746
+ _a.trys.push([0, 2, , 3]);
747
+ return [4 /*yield*/, getMainProcess()];
748
+ case 1:
749
+ mainProcess = _a.sent();
750
+ return [2 /*return*/, mainProcess];
751
+ case 2:
752
+ _a.sent();
753
+ return [3 /*break*/, 3];
754
+ case 3: return [2 /*return*/, new Promise(function (resolve) {
755
+ setTimeout(function () {
756
+ resolve(getMainProcessLoop());
757
+ }, 1000);
758
+ })];
759
+ }
760
+ });
761
+ }); };
762
+ var resetOutDir = function (currentManifestJson, config) { return __awaiter(void 0, void 0, void 0, function () {
763
+ var childBuild, currentManifest, mainProcess, exp;
668
764
  var _a;
669
- var exp = new RegExp("/(".concat(currentManifestJson.value.appCode, ")/?"));
670
- process.env.MFE_SOURCE_OUTPUT_DIR = config.build.outDir;
671
- process.env.MFE_ROOT_OUTPUT_DIR = (_a = process.env.MFE_SOURCE_OUTPUT_DIR) === null || _a === void 0 ? void 0 : _a.replace(exp, "/").replace(/\/$/, "");
672
- // if (!currentManifestJson.value.isRoot)
673
- process.env.UNI_OUTPUT_DIR = process.env.MFE_ROOT_OUTPUT_DIR;
674
- };
765
+ return __generator(this, function (_b) {
766
+ switch (_b.label) {
767
+ case 0:
768
+ childBuild = process.env.MFE_TARGET_DIR === "root";
769
+ currentManifest = currentManifestJson.value;
770
+ if (!(!currentManifest.isRoot && childBuild && !currentManifest.isServe)) return [3 /*break*/, 2];
771
+ return [4 /*yield*/, getMainProcessLoop()];
772
+ case 1:
773
+ mainProcess = _b.sent();
774
+ // mainProcess.UNI_OUTPUT_DIR
775
+ config.build.outDir = "".concat(mainProcess.UNI_OUTPUT_DIR, "/").concat(currentManifest.appCode);
776
+ _b.label = 2;
777
+ case 2:
778
+ exp = new RegExp("/(".concat(currentManifest.appCode, ")/?"));
779
+ // http://localhost:3560/__mfe__http__/root-path
780
+ // if()
781
+ process.env.MFE_SOURCE_OUTPUT_DIR = config.build.outDir;
782
+ process.env.MFE_ROOT_OUTPUT_DIR = (_a = process.env.MFE_SOURCE_OUTPUT_DIR) === null || _a === void 0 ? void 0 : _a.replace(exp, "/").replace(/\/$/, "");
783
+ // if (!currentManifestJson.value.isRoot)
784
+ process.env.UNI_OUTPUT_DIR = process.env.MFE_ROOT_OUTPUT_DIR;
785
+ return [2 /*return*/];
786
+ }
787
+ });
788
+ }); };
675
789
 
790
+ var addUniCopyPluginHook = function (_a) {
791
+ var before = _a.before, after = _a.after;
792
+ var FileWatcher = require("@dcloudio/uni-cli-shared/dist/watcher").FileWatcher;
793
+ var originalCopy = FileWatcher.prototype.copy;
794
+ // Hook copy方法
795
+ FileWatcher.prototype.copy = function (from) {
796
+ var to = this.to(from);
797
+ var fromPath = this.from(from);
798
+ before === null || before === void 0 ? void 0 : before(fromPath, to);
799
+ var result = originalCopy.call(this, from);
800
+ after === null || after === void 0 ? void 0 : after(fromPath, to);
801
+ return result;
802
+ };
803
+ };
676
804
  var copyFilesByTargetPath = function (sourcePath, targetPath) {
677
805
  if (!fs.existsSync(sourcePath))
678
806
  return;
@@ -849,42 +977,140 @@ var transformToWeixinFormat = function (uniPagesConfig) {
849
977
  return weixinConfig;
850
978
  };
851
979
 
980
+ // import { addRunningAppToSave } from "../running-core";
981
+ var CollectFiles = /** @class */ (function () {
982
+ function CollectFiles() {
983
+ this.callbackFiles = [];
984
+ this.callbackFiles = [];
985
+ this.emitted = new Map();
986
+ this.outDir = "";
987
+ }
988
+ Object.defineProperty(CollectFiles.prototype, "collectedBuildFiles", {
989
+ get: function () {
990
+ return Array.from(this.emitted.values());
991
+ },
992
+ enumerable: false,
993
+ configurable: true
994
+ });
995
+ CollectFiles.prototype.collectBoundleFile = function (bundles) {
996
+ var _this = this;
997
+ Object.keys(bundles).forEach(function (key) {
998
+ var boundle = bundles[key];
999
+ var fileName = boundle.fileName, source = boundle.source, code = boundle.code;
1000
+ var fileInfo = genreFileInfoRow({ fileName: fileName, source: code || source });
1001
+ _this.emitted.set(fileName, fileInfo);
1002
+ });
1003
+ };
1004
+ CollectFiles.prototype.addManifestFile = function () {
1005
+ this.emitted.set(MANIFEST_NAME, {
1006
+ fileName: MANIFEST_NAME,
1007
+ fileUrl: MANIFEST_NAME,
1008
+ });
1009
+ };
1010
+ CollectFiles.prototype.collectCopyFiles = function () {
1011
+ var _this = this;
1012
+ this.callbackFiles.forEach(function (_a) {
1013
+ var abs = _a.abs, filePath = _a.filePath;
1014
+ try {
1015
+ var stat = fs.statSync(abs);
1016
+ if (stat.isFile()) {
1017
+ var fileInfo = genreFileInfoRow({
1018
+ fileName: filePath,
1019
+ source: fs.readFileSync(abs, "utf8"),
1020
+ });
1021
+ _this.emitted.set(filePath, fileInfo);
1022
+ }
1023
+ else if (stat.isDirectory()) {
1024
+ var files = walkDir(abs);
1025
+ files.forEach(function (file) {
1026
+ var absFilePath = path.resolve(abs, file);
1027
+ var fullFileName = path.join(filePath, file);
1028
+ _this.emitted.set(fullFileName, genreFileInfoRow({
1029
+ fileName: fullFileName,
1030
+ source: fs.readFileSync(absFilePath, "utf8"),
1031
+ }));
1032
+ });
1033
+ }
1034
+ }
1035
+ catch (e) {
1036
+ console.log(e);
1037
+ }
1038
+ });
1039
+ this.addManifestFile();
1040
+ };
1041
+ CollectFiles.prototype.copyFilesToPublishDir = function () {
1042
+ var _this = this;
1043
+ this.collectedBuildFiles.forEach(function (_a) {
1044
+ var fileName = _a.fileName, fileUrl = _a.fileUrl;
1045
+ var sourcePath = path.resolve(_this.outDir, fileName);
1046
+ var targetPath = path.resolve(PUBLISH_PATH, fileUrl);
1047
+ copyFilesByTargetPath(sourcePath, targetPath);
1048
+ });
1049
+ };
1050
+ return CollectFiles;
1051
+ }());
852
1052
  var createManifestPlugin = function (manifestJson) {
853
- var emitted = new Set();
1053
+ var collectFiles = new CollectFiles();
854
1054
  return {
855
1055
  name: "@dd-code:genre-mainfest-file-list",
856
1056
  enforce: "post",
1057
+ config: function (config) {
1058
+ var _a;
1059
+ var outDir = ((_a = config.build) === null || _a === void 0 ? void 0 : _a.outDir) || "dist";
1060
+ collectFiles.outDir = outDir;
1061
+ addUniCopyPluginHook({
1062
+ after: function (fromPath, to) {
1063
+ collectFiles.callbackFiles.push({
1064
+ abs: fromPath,
1065
+ filePath: path.relative(outDir, to),
1066
+ });
1067
+ },
1068
+ });
1069
+ },
857
1070
  renderStart: function () {
858
1071
  var content = initPrePagesJson();
859
1072
  var json = getPagesJson(content);
860
1073
  manifestJson.setPagesJson(json);
861
1074
  },
862
1075
  writeBundle: function (_outputOptions, bundle) {
863
- Object.values(bundle).forEach(function (item) {
864
- if (item && item.fileName)
865
- emitted.add(item.fileName);
866
- });
1076
+ collectFiles.collectBoundleFile(bundle);
867
1077
  },
868
1078
  closeBundle: function () {
869
- var outDir = process.env.MFE_SOURCE_OUTPUT_DIR || "dist";
870
- var all = walkDir(outDir, emitted);
871
- manifestJson.setFiles(outDir, all);
872
1079
  var sourcePath = manifestJson.value.isRoot
873
1080
  ? process.env.MFE_ROOT_OUTPUT_DIR
874
1081
  : path.resolve(process.env.MFE_ROOT_OUTPUT_DIR, manifestJson.value.appCode);
875
- // debugger;
876
- manifestJson.saveFile(sourcePath);
877
- // const targetPath = path.resolve(TEMP_FILE_PATH, manifestJson.value.appCode);
878
- // copyFilesByTargetPath(sourcePath, targetPath);
1082
+ var filePath = path.resolve(sourcePath, MANIFEST_NAME);
1083
+ collectFiles.collectCopyFiles();
1084
+ manifestJson.setFiles(collectFiles.collectedBuildFiles);
1085
+ manifestJson.saveFile(filePath);
1086
+ // console.log({ filePath }, "sourcePath");
1087
+ // addRunningAppToSave(manifestJson.value.appCode, filePath);
1088
+ setTimeout(function () {
1089
+ collectFiles.copyFilesToPublishDir();
1090
+ }, 0);
879
1091
  },
880
1092
  };
881
1093
  };
882
1094
 
1095
+ var app = null;
883
1096
  var createHttpServer = function () {
884
- var app = express();
1097
+ if (app)
1098
+ return app;
1099
+ app = express();
885
1100
  var server = http.createServer(app);
1101
+ app.get("".concat(HTTP_PATH, "/root-path"), function (req, res) {
1102
+ res.send(process.env);
1103
+ });
886
1104
  app.use(cors({ origin: "*" }));
887
- return server;
1105
+ return {
1106
+ server: server,
1107
+ start: function (type) {
1108
+ var originKey = type || "http";
1109
+ server.listen(WS_PORT, function () {
1110
+ console.log("[uni-".concat(originKey, "] ").concat(originKey, "://localhost:").concat(WS_PORT).concat(HTTP_PATH));
1111
+ });
1112
+ },
1113
+ };
888
1114
  };
889
1115
 
890
1116
  var WsServer = /** @class */ (function () {
@@ -893,19 +1119,25 @@ var WsServer = /** @class */ (function () {
893
1119
  this.httpServer = createHttpServer();
894
1120
  this.clientMap = new Map();
895
1121
  }
1122
+ WsServer.getInstance = function (handleMessage) {
1123
+ if (!WsServer.instance) {
1124
+ WsServer.instance = new WsServer(handleMessage);
1125
+ }
1126
+ else if (handleMessage) {
1127
+ WsServer.instance.handleMessage = handleMessage;
1128
+ }
1129
+ return WsServer.instance;
1130
+ };
896
1131
  WsServer.prototype.createServer = function () {
1132
+ if (this.wss)
1133
+ return; // 避免重复创建
897
1134
  this.wss = new WebSocketServer({
898
- server: this.httpServer, // 绑定到 Vite 的 HTTP 服务器
1135
+ server: this.httpServer.server, // 绑定到 Vite 的 HTTP 服务器
899
1136
  path: WS_PATH, // WS 连接路径,前端连接时用 ws://localhost:5173/__mfe__ws__
900
1137
  });
901
1138
  this.onMessage(this.handleMessage);
902
1139
  this.onConnection();
903
- this.start();
904
- };
905
- WsServer.prototype.start = function () {
906
- this.httpServer.listen(WS_PORT, function () {
907
- console.log("[uni-WS] \u72EC\u7ACB\u670D\u52A1\u5DF2\u542F\u52A8\uFF1Aws://localhost:".concat(WS_PORT).concat(WS_PATH));
908
- });
1140
+ this.httpServer.start('ws');
909
1141
  };
910
1142
  WsServer.prototype.onMessage = function (callback) {
911
1143
  // WebSocketServer 不支持直接监听 message,必须在 connection 后的 socket 上监听
@@ -937,6 +1169,7 @@ var WsServer = /** @class */ (function () {
937
1169
  // 拿到客户端传递的 appCode
938
1170
  var url = new URL(request.url, "http://".concat(request.headers.host));
939
1171
  var appCode = url.searchParams.get("appCode");
1172
+ console.log("[uni-WS] \u5BA2\u6237\u7AEF\u8FDE\u63A5 WS \u670D\u52A1\uFF0CappCode: ".concat(appCode));
940
1173
  if (!appCode)
941
1174
  return;
942
1175
  _this.clientMap.set(appCode, ws);
@@ -957,8 +1190,19 @@ var WsClientServer = /** @class */ (function () {
957
1190
  this.ws = null;
958
1191
  this.isConnected = false;
959
1192
  }
1193
+ WsClientServer.getInstance = function (handleMessage) {
1194
+ if (!WsClientServer.instance) {
1195
+ WsClientServer.instance = new WsClientServer(handleMessage);
1196
+ }
1197
+ else if (handleMessage) {
1198
+ WsClientServer.instance.handleMessage = handleMessage;
1199
+ }
1200
+ return WsClientServer.instance;
1201
+ };
960
1202
  WsClientServer.prototype.connect = function (appCode) {
961
1203
  var _this = this;
1204
+ if (this.isConnected && this.ws)
1205
+ return;
962
1206
  this.ws = new WebSocket("ws://localhost:".concat(WS_PORT).concat(WS_PATH, "?appCode=").concat(appCode));
963
1207
  this.ws.on("open", function () {
964
1208
  // console.log("客户端已连接 WS 服务");
@@ -975,7 +1219,11 @@ var WsClientServer = /** @class */ (function () {
975
1219
  _this.isConnected = false;
976
1220
  _this.retryConnect(appCode);
977
1221
  });
978
- this.onMessage(this.handleMessage);
1222
+ // 监听消息并使用当前的 handleMessage
1223
+ this.ws.on("message", function (message) {
1224
+ var _a;
1225
+ (_a = _this.handleMessage) === null || _a === void 0 ? void 0 : _a.call(_this, JSON.parse(message.toString()));
1226
+ });
979
1227
  };
980
1228
  WsClientServer.prototype.sendMessage = function (type, data) {
981
1229
  if (this.isConnected) {
@@ -991,9 +1239,9 @@ var WsClientServer = /** @class */ (function () {
991
1239
  // // console.log("收到消息", message);
992
1240
  // };
993
1241
  WsClientServer.prototype.onMessage = function (callback) {
994
- this.ws.on("message", function (message) {
995
- callback === null || callback === void 0 ? void 0 : callback(JSON.parse(message.toString()));
996
- });
1242
+ if (callback) {
1243
+ this.handleMessage = callback;
1244
+ }
997
1245
  };
998
1246
  WsClientServer.prototype.retryConnect = function (appCode) {
999
1247
  var _this = this;
@@ -1019,9 +1267,37 @@ var WsClientServer = /** @class */ (function () {
1019
1267
  // export const mfeServer = new WsServer();
1020
1268
  // export const mfeClientServer = new WsClientServer();
1021
1269
 
1022
- /**
1023
- * 过滤 Manifest 列表并获取主应用 app.json 路径
1024
- */
1270
+ // export const addRunningAppToSave = (appCode, filePath: string) => {
1271
+ // const content = uniReadFile(SERVE_MPWEIXIN_MANIFEST);
1272
+ // if (content) {
1273
+ // content[appCode] = filePath;
1274
+ // }
1275
+ // writeFiles(SERVE_MPWEIXIN_MANIFEST, JSON.stringify(content, null, 2));
1276
+ // };
1277
+ var getAppsManifestList = function (mode) {
1278
+ var _a;
1279
+ var manifest = formatCliCommandConfig(mode);
1280
+ if (!manifest.isRoot) {
1281
+ return [];
1282
+ }
1283
+ if (manifest.serve) {
1284
+ return [];
1285
+ }
1286
+ var mfeJson = getMfeJson();
1287
+ if (!((_a = mfeJson === null || mfeJson === void 0 ? void 0 : mfeJson.apps) === null || _a === void 0 ? void 0 : _a.length)) {
1288
+ throw new Error("mfeJson.apps is empty");
1289
+ }
1290
+ var apps = ((mfeJson === null || mfeJson === void 0 ? void 0 : mfeJson.apps) || []).map(function (_a) {
1291
+ var appCode = _a.appCode;
1292
+ return {
1293
+ appCode: appCode,
1294
+ filePath: "".concat(process.env.UNI_OUTPUT_DIR, "/").concat(appCode, "/").concat(MANIFEST_NAME),
1295
+ };
1296
+ });
1297
+ // console.log(apps);
1298
+ return apps;
1299
+ };
1300
+
1025
1301
  var filterManifestJsonListAndMainPageJson = function (manifestJsonList) {
1026
1302
  var outputPageJsonPath = getMainAppJsonPath();
1027
1303
  return {
@@ -1029,9 +1305,6 @@ var filterManifestJsonListAndMainPageJson = function (manifestJsonList) {
1029
1305
  manifestList: manifestJsonList.filter(function (item) { return !checkIsRootManifest(item); }),
1030
1306
  };
1031
1307
  };
1032
- /**
1033
- * 根据 Manifest 列表渲染 app.json 的 subPackages
1034
- */
1035
1308
  var renderPagesJsonByArray = function (appPages, pageJson) {
1036
1309
  var _loop_1 = function (app) {
1037
1310
  var _a = getPagesJson(JSON.stringify((app === null || app === void 0 ? void 0 : app.pagesJson) || {}), true).pages, pages = _a === void 0 ? [] : _a;
@@ -1039,7 +1312,6 @@ var renderPagesJsonByArray = function (appPages, pageJson) {
1039
1312
  root: app.appCode,
1040
1313
  pages: __spreadArray([], pages, true),
1041
1314
  };
1042
- // 移除旧的 subPackage 配置并添加新的
1043
1315
  pageJson.subPackages = pageJson.subPackages.filter(function (i) { return i.root !== currentTemp.root; });
1044
1316
  pageJson.subPackages.push(currentTemp);
1045
1317
  pageJson.subPackages = pageJson.subPackages.filter(function (i) { return i.pages.length; });
@@ -1053,62 +1325,43 @@ var renderPagesJsonByArray = function (appPages, pageJson) {
1053
1325
  }
1054
1326
  return pageJson;
1055
1327
  };
1056
- /**
1057
- * 生成完整的主应用 app.json
1058
- */
1059
1328
  var genreFullMainAppJsonByManifestList = function (appJson, manifestList) {
1060
1329
  return renderPagesJsonByArray(manifestList, appJson);
1061
1330
  };
1062
- /**
1063
- * 监听 dist 目录变化并同步文件
1064
- */
1065
- var watchDistChangeAndSyncFile = function (mainPwd, onReady, onChange) {
1066
- var root = process.env.MFE_SOURCE_OUTPUT_DIR;
1067
- if (!root) {
1068
- console.error("[Watcher] MFE_SOURCE_OUTPUT_DIR not set");
1069
- return;
1331
+ var DistWatcher = /** @class */ (function () {
1332
+ function DistWatcher() {
1070
1333
  }
1071
- var filePath = path.resolve(root);
1072
- // 确保目录存在,避免监听失效
1073
- checkAndgenreDir(filePath);
1074
- // 监听父级目录,过滤出目标目录下的变化,解决目录重建导致监听失效的问题
1075
- var parentDir = path.dirname(filePath);
1076
- var watcher = chokidar.watch(parentDir, {
1077
- persistent: true,
1078
- ignoreInitial: true,
1079
- usePolling: true,
1080
- interval: 100,
1081
- awaitWriteFinish: { stabilityThreshold: 200, pollInterval: 100 },
1082
- followSymlinks: true,
1083
- depth: 99
1084
- });
1085
- var isTargetFile = function (p) {
1086
- return p.startsWith(filePath + path.sep) || p === filePath;
1087
- };
1088
- watcher.on("ready", onReady);
1089
- ["add", "change", "unlink"].forEach(function (evt) {
1090
- // @ts-ignore
1091
- watcher.on(evt, function (p) {
1092
- if (!isTargetFile(p))
1093
- return;
1094
- var rel = path.relative(filePath, p);
1095
- var sourcePath = p;
1096
- var targetPath = path.join(mainPwd, rel);
1097
- // 仅文件内容变化才执行复制操作,目录变化由构建工具处理
1098
- if (["add", "change"].includes(evt)) {
1099
- copyFilesByTargetPath(sourcePath, targetPath);
1100
- }
1101
- onChange === null || onChange === void 0 ? void 0 : onChange({ type: evt, p: p, sourcePath: sourcePath, targetPath: targetPath });
1334
+ DistWatcher.prototype.start = function (mainPwd, onReady, onChange) {
1335
+ var root = process.env.MFE_SOURCE_OUTPUT_DIR;
1336
+ if (!root)
1337
+ return;
1338
+ var filePath = path.resolve(root);
1339
+ checkAndgenreDir(filePath);
1340
+ var parentDir = path.dirname(filePath);
1341
+ var watcher = createFileWatcher(parentDir);
1342
+ var isTargetFile = function (p) {
1343
+ return p.startsWith(filePath + path.sep) || p === filePath;
1344
+ };
1345
+ watcher.on("ready", onReady);
1346
+ ["add", "change", "unlink"].forEach(function (evt) {
1347
+ // @ts-ignore
1348
+ watcher.on(evt, function (p) {
1349
+ if (!isTargetFile(p))
1350
+ return;
1351
+ var rel = path.relative(filePath, p);
1352
+ var sourcePath = p;
1353
+ var targetPath = path.join(mainPwd, rel);
1354
+ if (["add", "change"].includes(evt)) {
1355
+ copyFilesByTargetPath(sourcePath, targetPath);
1356
+ }
1357
+ onChange === null || onChange === void 0 ? void 0 : onChange({ type: evt, p: p, sourcePath: sourcePath, targetPath: targetPath });
1358
+ });
1102
1359
  });
1103
- });
1104
- watcher.on('error', function (err) { return console.error('[Watcher] error:', err); });
1105
- };
1106
- /**
1107
- * 生成新的 app.json 文件
1108
- */
1109
- var genreNewAppJson = function (outputPageJsonPath, mainAppJsonPath, manifestList) {
1360
+ };
1361
+ return DistWatcher;
1362
+ }());
1363
+ var genreNewAppJson = function (outputPageJsonPath, appJson, manifestList) {
1110
1364
  try {
1111
- var appJson = uniReadFile(mainAppJsonPath);
1112
1365
  var newAppJSon = genreFullMainAppJsonByManifestList(__assign({ subPackages: [] }, appJson), manifestList);
1113
1366
  writeFiles(outputPageJsonPath, newAppJSon);
1114
1367
  }
@@ -1116,20 +1369,16 @@ var genreNewAppJson = function (outputPageJsonPath, mainAppJsonPath, manifestLis
1116
1369
  console.error("[AppJSON] Genre failed:", error);
1117
1370
  }
1118
1371
  };
1119
- /**
1120
- * 处理主应用服务端逻辑
1121
- */
1122
1372
  var createMainAppServer = function (manifestJson) {
1123
- var mfeServer = new WsServer(function (opt) {
1373
+ var mfeServer = WsServer.getInstance(function (opt) {
1124
1374
  var type = opt.type, data = opt.data;
1125
1375
  if (type === E_WS_TYPE.CHANGE) {
1126
1376
  var outputPageJsonPath = getMainAppJsonPath();
1127
1377
  var manifestPath = path.join(process.env.UNI_OUTPUT_DIR, data.appCode, MANIFEST_NAME);
1128
1378
  try {
1129
1379
  var manifestChildJson = uniReadFile(manifestPath);
1130
- genreNewAppJson(outputPageJsonPath, outputPageJsonPath, [
1131
- manifestChildJson,
1132
- ]);
1380
+ var mainAppJson = uniReadFile(outputPageJsonPath);
1381
+ genreNewAppJson(outputPageJsonPath, mainAppJson, [manifestChildJson]);
1133
1382
  }
1134
1383
  catch (e) {
1135
1384
  console.error("[Server] Handle child change failed:", e);
@@ -1139,11 +1388,8 @@ var createMainAppServer = function (manifestJson) {
1139
1388
  mfeServer.createServer();
1140
1389
  return mfeServer;
1141
1390
  };
1142
- /**
1143
- * 处理子应用客户端逻辑
1144
- */
1145
1391
  var createMainAppClient = function (manifestJson, onInit) {
1146
- var client = new WsClientServer(function (opt) {
1392
+ var client = WsClientServer.getInstance(function (opt) {
1147
1393
  if (opt.type === E_WS_TYPE.INIT) {
1148
1394
  onInit(opt.data);
1149
1395
  }
@@ -1151,19 +1397,44 @@ var createMainAppClient = function (manifestJson, onInit) {
1151
1397
  client.connect(manifestJson.value.appCode);
1152
1398
  return client;
1153
1399
  };
1154
- /**
1155
- * 创建主应用插件
1156
- */
1157
1400
  var createMainAppPlugin = function (manifestJson) {
1158
1401
  var mainPwd = "";
1159
1402
  var isWatcherReady = false;
1160
1403
  var mfeClientServer;
1161
1404
  var fn = null;
1405
+ var isBuild = function () { return process.env.MFE_BUILD_MODE === EBuildMode.BUILD; };
1406
+ var isServe = function () { return manifestJson.value.isServe; };
1407
+ var isStartServer = function () {
1408
+ if (isBuild())
1409
+ return false;
1410
+ return isServe();
1411
+ };
1412
+ var watchFile = function () {
1413
+ var allManifest = getAppsManifestList(manifestJson.value.mode);
1414
+ var watchFileList = allManifest.map(function (item) { return item.filePath; });
1415
+ var watcher = createFileWatcher(watchFileList);
1416
+ watcher.on("change", function (path) {
1417
+ var manifestJson = uniFsReadJSONFile(path);
1418
+ var outputPageJsonPath = getMainAppJsonPath();
1419
+ var mainAppJson = uniFsReadJSONFile(outputPageJsonPath);
1420
+ genreNewAppJson(outputPageJsonPath, mainAppJson, [manifestJson]);
1421
+ });
1422
+ };
1423
+ var distWatcher = new DistWatcher();
1162
1424
  var serverPlugin = {
1163
1425
  name: "@dd-code:main-app:serve",
1164
1426
  config: function () {
1165
1427
  return __awaiter(this, void 0, void 0, function () {
1166
- return __generator(this, function (_a) {
1428
+ var isServe, _a, start;
1429
+ return __generator(this, function (_b) {
1430
+ isServe = isStartServer();
1431
+ if (!isServe) {
1432
+ if (!isBuild() && manifestJson.value.isRoot) {
1433
+ _a = createHttpServer(), _a.server, start = _a.start;
1434
+ start();
1435
+ }
1436
+ return [2 /*return*/];
1437
+ }
1167
1438
  if (manifestJson.value.isRoot) {
1168
1439
  createMainAppServer();
1169
1440
  }
@@ -1177,6 +1448,9 @@ var createMainAppPlugin = function (manifestJson) {
1177
1448
  });
1178
1449
  },
1179
1450
  closeBundle: function () {
1451
+ var isServe = isStartServer();
1452
+ if (!isServe)
1453
+ return;
1180
1454
  if (!manifestJson.value.isRoot) {
1181
1455
  serverPlugin.initWatchChange();
1182
1456
  fn === null || fn === void 0 ? void 0 : fn();
@@ -1186,9 +1460,8 @@ var createMainAppPlugin = function (manifestJson) {
1186
1460
  initWatchChange: function () {
1187
1461
  if (isWatcherReady)
1188
1462
  return;
1189
- watchDistChangeAndSyncFile(mainPwd, function () {
1463
+ distWatcher.start(mainPwd, function () {
1190
1464
  isWatcherReady = true;
1191
- // console.log(`[Watcher] Ready watching: ${process.env.MFE_SOURCE_OUTPUT_DIR}`);
1192
1465
  }, function (change) {
1193
1466
  fn = function () {
1194
1467
  return mfeClientServer.sendMessage(E_WS_TYPE.CHANGE, __assign(__assign({}, change), { appCode: manifestJson.value.appCode }));
@@ -1209,18 +1482,38 @@ var createMainAppPlugin = function (manifestJson) {
1209
1482
  };
1210
1483
  return [
1211
1484
  serverPlugin,
1485
+ {
1486
+ name: "@dd-code:main-app:watch",
1487
+ closeBundle: function () {
1488
+ return __awaiter(this, void 0, void 0, function () {
1489
+ return __generator(this, function (_a) {
1490
+ if (isBuild())
1491
+ return [2 /*return*/];
1492
+ if (isServe())
1493
+ return [2 /*return*/];
1494
+ // if (!isServe) return;
1495
+ watchFile === null || watchFile === void 0 ? void 0 : watchFile();
1496
+ watchFile = null;
1497
+ return [2 /*return*/];
1498
+ });
1499
+ });
1500
+ },
1501
+ },
1212
1502
  {
1213
1503
  name: "@dd-code:main-app",
1214
1504
  enforce: "post",
1215
1505
  closeBundle: function () {
1216
1506
  return __awaiter(this, void 0, void 0, function () {
1217
- var _a, outputPageJsonPath, manifestList, mainAppJsonPath;
1507
+ var _a, outputPageJsonPath, manifestList, mainAppJsonPath, mainAppJson;
1218
1508
  return __generator(this, function (_b) {
1219
1509
  _a = filterManifestJsonListAndMainPageJson(__spreadArray(__spreadArray([], manifestJson.dependencies, true), [
1220
1510
  manifestJson.value,
1221
1511
  ], false)), outputPageJsonPath = _a.outputPageJsonPath, manifestList = _a.manifestList;
1222
- mainAppJsonPath = getMainAppJSon(manifestJson.value.mode, ROOT_APP_CODE);
1223
- genreNewAppJson(outputPageJsonPath, mainAppJsonPath, manifestList);
1512
+ mainAppJsonPath = !manifestJson.value.isRoot
1513
+ ? getNodeModuleMainAppJSon(manifestJson.value.mode, ROOT_APP_CODE)
1514
+ : getMainAppJsonPath();
1515
+ mainAppJson = uniReadFile(mainAppJsonPath);
1516
+ genreNewAppJson(outputPageJsonPath, mainAppJson, manifestList);
1224
1517
  return [2 /*return*/];
1225
1518
  });
1226
1519
  });
@@ -1236,8 +1529,18 @@ var createMpWeixinUniPlugin = function (options) {
1236
1529
  name: "@dd-code:genre-params",
1237
1530
  enforce: "pre",
1238
1531
  config: function (config) {
1239
- currentManifestJson.setEnv(config.mode);
1240
- resetOutDir(currentManifestJson, config);
1532
+ return __awaiter(this, void 0, void 0, function () {
1533
+ return __generator(this, function (_a) {
1534
+ switch (_a.label) {
1535
+ case 0:
1536
+ currentManifestJson.setEnv(config.mode);
1537
+ return [4 /*yield*/, resetOutDir(currentManifestJson, config)];
1538
+ case 1:
1539
+ _a.sent();
1540
+ return [2 /*return*/];
1541
+ }
1542
+ });
1543
+ });
1241
1544
  },
1242
1545
  },
1243
1546
  createAppsAssetsPlugin(currentManifestJson),