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