@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.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 () {
@@ -906,17 +1132,12 @@ var WsServer = /** @class */ (function () {
906
1132
  if (this.wss)
907
1133
  return; // 避免重复创建
908
1134
  this.wss = new WebSocketServer({
909
- server: this.httpServer, // 绑定到 Vite 的 HTTP 服务器
1135
+ server: this.httpServer.server, // 绑定到 Vite 的 HTTP 服务器
910
1136
  path: WS_PATH, // WS 连接路径,前端连接时用 ws://localhost:5173/__mfe__ws__
911
1137
  });
912
1138
  this.onMessage(this.handleMessage);
913
1139
  this.onConnection();
914
- this.start();
915
- };
916
- WsServer.prototype.start = function () {
917
- this.httpServer.listen(WS_PORT, function () {
918
- console.log("[uni-WS] \u72EC\u7ACB\u670D\u52A1\u5DF2\u542F\u52A8\uFF1Aws://localhost:".concat(WS_PORT).concat(WS_PATH));
919
- });
1140
+ this.httpServer.start('ws');
920
1141
  };
921
1142
  WsServer.prototype.onMessage = function (callback) {
922
1143
  // WebSocketServer 不支持直接监听 message,必须在 connection 后的 socket 上监听
@@ -1046,9 +1267,37 @@ var WsClientServer = /** @class */ (function () {
1046
1267
  // export const mfeServer = new WsServer();
1047
1268
  // export const mfeClientServer = new WsClientServer();
1048
1269
 
1049
- /**
1050
- * 过滤 Manifest 列表并获取主应用 app.json 路径
1051
- */
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
+
1052
1301
  var filterManifestJsonListAndMainPageJson = function (manifestJsonList) {
1053
1302
  var outputPageJsonPath = getMainAppJsonPath();
1054
1303
  return {
@@ -1056,9 +1305,6 @@ var filterManifestJsonListAndMainPageJson = function (manifestJsonList) {
1056
1305
  manifestList: manifestJsonList.filter(function (item) { return !checkIsRootManifest(item); }),
1057
1306
  };
1058
1307
  };
1059
- /**
1060
- * 根据 Manifest 列表渲染 app.json 的 subPackages
1061
- */
1062
1308
  var renderPagesJsonByArray = function (appPages, pageJson) {
1063
1309
  var _loop_1 = function (app) {
1064
1310
  var _a = getPagesJson(JSON.stringify((app === null || app === void 0 ? void 0 : app.pagesJson) || {}), true).pages, pages = _a === void 0 ? [] : _a;
@@ -1066,7 +1312,6 @@ var renderPagesJsonByArray = function (appPages, pageJson) {
1066
1312
  root: app.appCode,
1067
1313
  pages: __spreadArray([], pages, true),
1068
1314
  };
1069
- // 移除旧的 subPackage 配置并添加新的
1070
1315
  pageJson.subPackages = pageJson.subPackages.filter(function (i) { return i.root !== currentTemp.root; });
1071
1316
  pageJson.subPackages.push(currentTemp);
1072
1317
  pageJson.subPackages = pageJson.subPackages.filter(function (i) { return i.pages.length; });
@@ -1080,62 +1325,43 @@ var renderPagesJsonByArray = function (appPages, pageJson) {
1080
1325
  }
1081
1326
  return pageJson;
1082
1327
  };
1083
- /**
1084
- * 生成完整的主应用 app.json
1085
- */
1086
1328
  var genreFullMainAppJsonByManifestList = function (appJson, manifestList) {
1087
1329
  return renderPagesJsonByArray(manifestList, appJson);
1088
1330
  };
1089
- /**
1090
- * 监听 dist 目录变化并同步文件
1091
- */
1092
- var watchDistChangeAndSyncFile = function (mainPwd, onReady, onChange) {
1093
- var root = process.env.MFE_SOURCE_OUTPUT_DIR;
1094
- if (!root) {
1095
- console.error("[Watcher] MFE_SOURCE_OUTPUT_DIR not set");
1096
- return;
1331
+ var DistWatcher = /** @class */ (function () {
1332
+ function DistWatcher() {
1097
1333
  }
1098
- var filePath = path.resolve(root);
1099
- // 确保目录存在,避免监听失效
1100
- checkAndgenreDir(filePath);
1101
- // 监听父级目录,过滤出目标目录下的变化,解决目录重建导致监听失效的问题
1102
- var parentDir = path.dirname(filePath);
1103
- var watcher = chokidar.watch(parentDir, {
1104
- persistent: true,
1105
- ignoreInitial: true,
1106
- usePolling: true,
1107
- interval: 100,
1108
- awaitWriteFinish: { stabilityThreshold: 200, pollInterval: 100 },
1109
- followSymlinks: true,
1110
- depth: 99
1111
- });
1112
- var isTargetFile = function (p) {
1113
- return p.startsWith(filePath + path.sep) || p === filePath;
1114
- };
1115
- watcher.on("ready", onReady);
1116
- ["add", "change", "unlink"].forEach(function (evt) {
1117
- // @ts-ignore
1118
- watcher.on(evt, function (p) {
1119
- if (!isTargetFile(p))
1120
- return;
1121
- var rel = path.relative(filePath, p);
1122
- var sourcePath = p;
1123
- var targetPath = path.join(mainPwd, rel);
1124
- // 仅文件内容变化才执行复制操作,目录变化由构建工具处理
1125
- if (["add", "change"].includes(evt)) {
1126
- copyFilesByTargetPath(sourcePath, targetPath);
1127
- }
1128
- 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
+ });
1129
1359
  });
1130
- });
1131
- watcher.on('error', function (err) { return console.error('[Watcher] error:', err); });
1132
- };
1133
- /**
1134
- * 生成新的 app.json 文件
1135
- */
1136
- var genreNewAppJson = function (outputPageJsonPath, mainAppJsonPath, manifestList) {
1360
+ };
1361
+ return DistWatcher;
1362
+ }());
1363
+ var genreNewAppJson = function (outputPageJsonPath, appJson, manifestList) {
1137
1364
  try {
1138
- var appJson = uniReadFile(mainAppJsonPath);
1139
1365
  var newAppJSon = genreFullMainAppJsonByManifestList(__assign({ subPackages: [] }, appJson), manifestList);
1140
1366
  writeFiles(outputPageJsonPath, newAppJSon);
1141
1367
  }
@@ -1143,9 +1369,6 @@ var genreNewAppJson = function (outputPageJsonPath, mainAppJsonPath, manifestLis
1143
1369
  console.error("[AppJSON] Genre failed:", error);
1144
1370
  }
1145
1371
  };
1146
- /**
1147
- * 处理主应用服务端逻辑
1148
- */
1149
1372
  var createMainAppServer = function (manifestJson) {
1150
1373
  var mfeServer = WsServer.getInstance(function (opt) {
1151
1374
  var type = opt.type, data = opt.data;
@@ -1154,9 +1377,8 @@ var createMainAppServer = function (manifestJson) {
1154
1377
  var manifestPath = path.join(process.env.UNI_OUTPUT_DIR, data.appCode, MANIFEST_NAME);
1155
1378
  try {
1156
1379
  var manifestChildJson = uniReadFile(manifestPath);
1157
- genreNewAppJson(outputPageJsonPath, outputPageJsonPath, [
1158
- manifestChildJson,
1159
- ]);
1380
+ var mainAppJson = uniReadFile(outputPageJsonPath);
1381
+ genreNewAppJson(outputPageJsonPath, mainAppJson, [manifestChildJson]);
1160
1382
  }
1161
1383
  catch (e) {
1162
1384
  console.error("[Server] Handle child change failed:", e);
@@ -1166,9 +1388,6 @@ var createMainAppServer = function (manifestJson) {
1166
1388
  mfeServer.createServer();
1167
1389
  return mfeServer;
1168
1390
  };
1169
- /**
1170
- * 处理子应用客户端逻辑
1171
- */
1172
1391
  var createMainAppClient = function (manifestJson, onInit) {
1173
1392
  var client = WsClientServer.getInstance(function (opt) {
1174
1393
  if (opt.type === E_WS_TYPE.INIT) {
@@ -1178,19 +1397,44 @@ var createMainAppClient = function (manifestJson, onInit) {
1178
1397
  client.connect(manifestJson.value.appCode);
1179
1398
  return client;
1180
1399
  };
1181
- /**
1182
- * 创建主应用插件
1183
- */
1184
1400
  var createMainAppPlugin = function (manifestJson) {
1185
1401
  var mainPwd = "";
1186
1402
  var isWatcherReady = false;
1187
1403
  var mfeClientServer;
1188
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();
1189
1424
  var serverPlugin = {
1190
1425
  name: "@dd-code:main-app:serve",
1191
1426
  config: function () {
1192
1427
  return __awaiter(this, void 0, void 0, function () {
1193
- 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
+ }
1194
1438
  if (manifestJson.value.isRoot) {
1195
1439
  createMainAppServer();
1196
1440
  }
@@ -1204,6 +1448,9 @@ var createMainAppPlugin = function (manifestJson) {
1204
1448
  });
1205
1449
  },
1206
1450
  closeBundle: function () {
1451
+ var isServe = isStartServer();
1452
+ if (!isServe)
1453
+ return;
1207
1454
  if (!manifestJson.value.isRoot) {
1208
1455
  serverPlugin.initWatchChange();
1209
1456
  fn === null || fn === void 0 ? void 0 : fn();
@@ -1213,9 +1460,8 @@ var createMainAppPlugin = function (manifestJson) {
1213
1460
  initWatchChange: function () {
1214
1461
  if (isWatcherReady)
1215
1462
  return;
1216
- watchDistChangeAndSyncFile(mainPwd, function () {
1463
+ distWatcher.start(mainPwd, function () {
1217
1464
  isWatcherReady = true;
1218
- // console.log(`[Watcher] Ready watching: ${process.env.MFE_SOURCE_OUTPUT_DIR}`);
1219
1465
  }, function (change) {
1220
1466
  fn = function () {
1221
1467
  return mfeClientServer.sendMessage(E_WS_TYPE.CHANGE, __assign(__assign({}, change), { appCode: manifestJson.value.appCode }));
@@ -1236,18 +1482,38 @@ var createMainAppPlugin = function (manifestJson) {
1236
1482
  };
1237
1483
  return [
1238
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
+ },
1239
1502
  {
1240
1503
  name: "@dd-code:main-app",
1241
1504
  enforce: "post",
1242
1505
  closeBundle: function () {
1243
1506
  return __awaiter(this, void 0, void 0, function () {
1244
- var _a, outputPageJsonPath, manifestList, mainAppJsonPath;
1507
+ var _a, outputPageJsonPath, manifestList, mainAppJsonPath, mainAppJson;
1245
1508
  return __generator(this, function (_b) {
1246
1509
  _a = filterManifestJsonListAndMainPageJson(__spreadArray(__spreadArray([], manifestJson.dependencies, true), [
1247
1510
  manifestJson.value,
1248
1511
  ], false)), outputPageJsonPath = _a.outputPageJsonPath, manifestList = _a.manifestList;
1249
- mainAppJsonPath = getMainAppJSon(manifestJson.value.mode, ROOT_APP_CODE);
1250
- 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);
1251
1517
  return [2 /*return*/];
1252
1518
  });
1253
1519
  });
@@ -1263,8 +1529,18 @@ var createMpWeixinUniPlugin = function (options) {
1263
1529
  name: "@dd-code:genre-params",
1264
1530
  enforce: "pre",
1265
1531
  config: function (config) {
1266
- currentManifestJson.setEnv(config.mode);
1267
- 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
+ });
1268
1544
  },
1269
1545
  },
1270
1546
  createAppsAssetsPlugin(currentManifestJson),