@dd-code/uni-tools 1.0.9 → 1.0.11

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,22 @@ 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
+ };
263
+ var checkIsBuildInChild = function () { return process.env.MFE_TARGET_DIR === "root"; };
264
+ var checkIsInnerBuild = function () { return process.env.MFE_INNER_BUILD === "true"; };
229
265
 
230
266
  var UniCdnManager = /** @class */ (function () {
231
267
  function UniCdnManager() {
@@ -258,10 +294,19 @@ var cdn = new UniCdnManager();
258
294
 
259
295
  // CDN 文件保存路径
260
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");
261
299
  path.join(process.cwd(), "node_modules/@dd-code/current-files");
300
+ // 发布目录路径
301
+ var PUBLISH_PATH = path.join(process.cwd(), "dist/publish");
262
302
  // Manifest 文件名
263
303
  var MANIFEST_NAME = "mfe-uni-manifest.json";
264
- 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 = {}));
265
310
  // Manifest CDN 目录 URL 模板
266
311
  var MANIFEST_CND_DIR_URL = "{mode}/static-repository/mfe-uni/{code}/{appCode}";
267
312
  var getManifestCdnDirUrl = function (_a) {
@@ -352,6 +397,7 @@ var formatCliCommandConfig = function (mode) {
352
397
  code: viteEnv.MFE_UNI_CODE,
353
398
  mode: mode,
354
399
  cdn: viteEnv.MFE_CDN_HOST,
400
+ serve: viteEnv.MFE_UNI_SERVE, // 是否开启 serve 功能
355
401
  };
356
402
  };
357
403
  var checkIsRootManifest = function (manifest) {
@@ -359,12 +405,13 @@ var checkIsRootManifest = function (manifest) {
359
405
  };
360
406
  var WS_PORT = 3560;
361
407
  var WS_PATH = "/__mfe__ws__";
408
+ var HTTP_PATH = "/__mfe__http__";
362
409
  var E_WS_TYPE;
363
410
  (function (E_WS_TYPE) {
364
411
  E_WS_TYPE["INIT"] = "init_files";
365
412
  E_WS_TYPE["CHANGE"] = "change_files";
366
413
  })(E_WS_TYPE || (E_WS_TYPE = {}));
367
- var getMainAppJSon = function (mode, appCode) {
414
+ var getNodeModuleMainAppJSon = function (mode, appCode) {
368
415
  return path.join(SAVE_CDN_FILE_PATH, mode || "dev", appCode, "app.json");
369
416
  };
370
417
  var getMainAppJsonPath = function () {
@@ -420,10 +467,17 @@ var CliProgressManager = /** @class */ (function () {
420
467
  var CliProgressManager$1 = new CliProgressManager();
421
468
 
422
469
  var getDownloadedFilePath = function (conf) {
423
- 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);
424
477
  };
425
478
  var getNodeModulesEnvAppCodeFilePath = function (conf, fileName) {
426
- return path.resolve(getDownloadedFilePath(conf), fileName);
479
+ var savePath = getDownloadedFilePath(conf);
480
+ return path.resolve(savePath, fileName);
427
481
  };
428
482
  /**
429
483
  * 获取清单文件 URL 列表
@@ -592,19 +646,20 @@ var downloadProjectFiles = function (manifestList) { return __awaiter(void 0, vo
592
646
  }); };
593
647
 
594
648
  var checkDownloadFilesIsExpired = function (manifestList) {
595
- return manifestList.filter(function (conf) {
649
+ var filterList = manifestList.filter(function (conf) {
596
650
  var targetPath = getNodeModulesEnvAppCodeFilePath(conf, MANIFEST_NAME);
597
651
  var oldJson = uniReadFile(targetPath);
598
652
  var flag = !oldJson || (oldJson === null || oldJson === void 0 ? void 0 : oldJson.hash) !== conf.hash;
599
653
  return flag;
600
654
  });
655
+ return filterList;
601
656
  };
602
657
  var createManifestManager = function () {
603
658
  var envObj = process.env;
604
659
  var row = {
605
660
  code: "",
606
661
  mode: "",
607
- cdn: '',
662
+ cdn: "",
608
663
  hash: "",
609
664
  publicPath: "",
610
665
  appCode: "",
@@ -616,26 +671,29 @@ var createManifestManager = function () {
616
671
  get value() {
617
672
  return row;
618
673
  },
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
- });
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
+ // });
629
687
  row.files = files;
630
688
  },
631
689
  setPagesJson: function (pagesJson) {
632
690
  row.pagesJson = pagesJson;
633
691
  },
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));
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));
639
697
  },
640
698
  setEnv: function (mode) {
641
699
  // const env = loadViteConfig(mode);
@@ -650,6 +708,7 @@ var createManifestManager = function () {
650
708
  row.isRoot = true;
651
709
  row.apps = mfeJson.apps;
652
710
  }
711
+ row.isServe = env.serve;
653
712
  row.publicPath = getManifestCdnDirUrl(row);
654
713
  },
655
714
  dependencies: [],
@@ -664,15 +723,103 @@ var createManifestManager = function () {
664
723
  };
665
724
  };
666
725
 
667
- var resetOutDir = function (currentManifestJson, config) {
726
+ var num = 5;
727
+ var getMainProcess = function () { return __awaiter(void 0, void 0, void 0, function () {
728
+ var URL, mainProcess, result;
729
+ return __generator(this, function (_a) {
730
+ switch (_a.label) {
731
+ case 0:
732
+ URL = "http://localhost:".concat(WS_PORT).concat(HTTP_PATH, "/root-path");
733
+ return [4 /*yield*/, fetch(URL)];
734
+ case 1:
735
+ mainProcess = _a.sent();
736
+ return [4 /*yield*/, mainProcess.json()];
737
+ case 2:
738
+ result = _a.sent();
739
+ console.log(result, "mainProcess");
740
+ return [2 /*return*/, result];
741
+ }
742
+ });
743
+ }); };
744
+ var getMainProcessLoop = function () { return __awaiter(void 0, void 0, void 0, function () {
745
+ var mainProcess;
746
+ return __generator(this, function (_a) {
747
+ switch (_a.label) {
748
+ case 0:
749
+ _a.trys.push([0, 2, , 3]);
750
+ return [4 /*yield*/, getMainProcess()];
751
+ case 1:
752
+ mainProcess = _a.sent();
753
+ return [2 /*return*/, mainProcess];
754
+ case 2:
755
+ _a.sent();
756
+ return [3 /*break*/, 3];
757
+ case 3: return [2 /*return*/, new Promise(function (resolve) {
758
+ setTimeout(function () {
759
+ num--;
760
+ if (num <= 0) {
761
+ resolve(null);
762
+ num = 5;
763
+ }
764
+ resolve(getMainProcessLoop());
765
+ }, 100);
766
+ })];
767
+ }
768
+ });
769
+ }); };
770
+ var resetOutDir = function (currentManifestJson, config) { return __awaiter(void 0, void 0, void 0, function () {
771
+ var currentManifest, mainProcess, exp;
668
772
  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
- };
773
+ return __generator(this, function (_b) {
774
+ switch (_b.label) {
775
+ case 0:
776
+ currentManifest = currentManifestJson.value;
777
+ if (!(!currentManifest.isRoot &&
778
+ checkIsBuildInChild() &&
779
+ !currentManifest.isServe)) return [3 /*break*/, 2];
780
+ return [4 /*yield*/, getMainProcessLoop()];
781
+ case 1:
782
+ mainProcess = _b.sent();
783
+ if (mainProcess) {
784
+ config.build.outDir = "".concat(mainProcess.UNI_OUTPUT_DIR, "/").concat(currentManifest.appCode);
785
+ process.env.MFE_INNER_BUILD = "true";
786
+ }
787
+ else {
788
+ process.env.MFE_TARGET_DIR = "";
789
+ }
790
+ _b.label = 2;
791
+ case 2:
792
+ exp = new RegExp("/(".concat(currentManifest.appCode, ")/?"));
793
+ // http://localhost:3560/__mfe__http__/root-path
794
+ // if()
795
+ process.env.MFE_SOURCE_OUTPUT_DIR = config.build.outDir;
796
+ process.env.MFE_ROOT_OUTPUT_DIR = (_a = process.env.MFE_SOURCE_OUTPUT_DIR) === null || _a === void 0 ? void 0 : _a.replace(exp, "/").replace(/\/$/, "");
797
+ // if (!currentManifestJson.value.isRoot)
798
+ // console.log(config);
799
+ if (!checkIsInnerBuild()) {
800
+ // setTimeout(() => {
801
+ process.env.UNI_OUTPUT_DIR = process.env.MFE_ROOT_OUTPUT_DIR;
802
+ // }, 500);
803
+ }
804
+ return [2 /*return*/];
805
+ }
806
+ });
807
+ }); };
675
808
 
809
+ var addUniCopyPluginHook = function (_a) {
810
+ var before = _a.before, after = _a.after;
811
+ var FileWatcher = require("@dcloudio/uni-cli-shared/dist/watcher").FileWatcher;
812
+ var originalCopy = FileWatcher.prototype.copy;
813
+ // Hook copy方法
814
+ FileWatcher.prototype.copy = function (from) {
815
+ var to = this.to(from);
816
+ var fromPath = this.from(from);
817
+ before === null || before === void 0 ? void 0 : before(fromPath, to);
818
+ var result = originalCopy.call(this, from);
819
+ after === null || after === void 0 ? void 0 : after(fromPath, to);
820
+ return result;
821
+ };
822
+ };
676
823
  var copyFilesByTargetPath = function (sourcePath, targetPath) {
677
824
  if (!fs.existsSync(sourcePath))
678
825
  return;
@@ -741,6 +888,8 @@ var createAppsAssetsPlugin = function (manifestJson) {
741
888
  buildStart: function () {
742
889
  if (isMoved)
743
890
  return;
891
+ if (checkIsBuildInChild() && !manifestJson.value.isRoot)
892
+ return;
744
893
  var basePath = path.resolve(SAVE_CDN_FILE_PATH, manifestJson.value.mode || "dev");
745
894
  moveOtherApps({
746
895
  base: basePath,
@@ -849,42 +998,140 @@ var transformToWeixinFormat = function (uniPagesConfig) {
849
998
  return weixinConfig;
850
999
  };
851
1000
 
1001
+ // import { addRunningAppToSave } from "../running-core";
1002
+ var CollectFiles = /** @class */ (function () {
1003
+ function CollectFiles() {
1004
+ this.callbackFiles = [];
1005
+ this.callbackFiles = [];
1006
+ this.emitted = new Map();
1007
+ this.outDir = "";
1008
+ }
1009
+ Object.defineProperty(CollectFiles.prototype, "collectedBuildFiles", {
1010
+ get: function () {
1011
+ return Array.from(this.emitted.values());
1012
+ },
1013
+ enumerable: false,
1014
+ configurable: true
1015
+ });
1016
+ CollectFiles.prototype.collectBoundleFile = function (bundles) {
1017
+ var _this = this;
1018
+ Object.keys(bundles).forEach(function (key) {
1019
+ var boundle = bundles[key];
1020
+ var fileName = boundle.fileName, source = boundle.source, code = boundle.code;
1021
+ var fileInfo = genreFileInfoRow({ fileName: fileName, source: code || source });
1022
+ _this.emitted.set(fileName, fileInfo);
1023
+ });
1024
+ };
1025
+ CollectFiles.prototype.addManifestFile = function () {
1026
+ this.emitted.set(MANIFEST_NAME, {
1027
+ fileName: MANIFEST_NAME,
1028
+ fileUrl: MANIFEST_NAME,
1029
+ });
1030
+ };
1031
+ CollectFiles.prototype.collectCopyFiles = function () {
1032
+ var _this = this;
1033
+ this.callbackFiles.forEach(function (_a) {
1034
+ var abs = _a.abs, filePath = _a.filePath;
1035
+ try {
1036
+ var stat = fs.statSync(abs);
1037
+ if (stat.isFile()) {
1038
+ var fileInfo = genreFileInfoRow({
1039
+ fileName: filePath,
1040
+ source: fs.readFileSync(abs, "utf8"),
1041
+ });
1042
+ _this.emitted.set(filePath, fileInfo);
1043
+ }
1044
+ else if (stat.isDirectory()) {
1045
+ var files = walkDir(abs);
1046
+ files.forEach(function (file) {
1047
+ var absFilePath = path.resolve(abs, file);
1048
+ var fullFileName = path.join(filePath, file);
1049
+ _this.emitted.set(fullFileName, genreFileInfoRow({
1050
+ fileName: fullFileName,
1051
+ source: fs.readFileSync(absFilePath, "utf8"),
1052
+ }));
1053
+ });
1054
+ }
1055
+ }
1056
+ catch (e) {
1057
+ console.log(e);
1058
+ }
1059
+ });
1060
+ this.addManifestFile();
1061
+ };
1062
+ CollectFiles.prototype.copyFilesToPublishDir = function () {
1063
+ var _this = this;
1064
+ this.collectedBuildFiles.forEach(function (_a) {
1065
+ var fileName = _a.fileName, fileUrl = _a.fileUrl;
1066
+ var sourcePath = path.resolve(_this.outDir, fileName);
1067
+ var targetPath = path.resolve(PUBLISH_PATH, fileUrl);
1068
+ copyFilesByTargetPath(sourcePath, targetPath);
1069
+ });
1070
+ };
1071
+ return CollectFiles;
1072
+ }());
852
1073
  var createManifestPlugin = function (manifestJson) {
853
- var emitted = new Set();
1074
+ var collectFiles = new CollectFiles();
854
1075
  return {
855
1076
  name: "@dd-code:genre-mainfest-file-list",
856
1077
  enforce: "post",
1078
+ config: function (config) {
1079
+ var _a;
1080
+ var outDir = ((_a = config.build) === null || _a === void 0 ? void 0 : _a.outDir) || "dist";
1081
+ collectFiles.outDir = outDir;
1082
+ addUniCopyPluginHook({
1083
+ after: function (fromPath, to) {
1084
+ collectFiles.callbackFiles.push({
1085
+ abs: fromPath,
1086
+ filePath: path.relative(outDir, to),
1087
+ });
1088
+ },
1089
+ });
1090
+ },
857
1091
  renderStart: function () {
858
1092
  var content = initPrePagesJson();
859
1093
  var json = getPagesJson(content);
860
1094
  manifestJson.setPagesJson(json);
861
1095
  },
862
1096
  writeBundle: function (_outputOptions, bundle) {
863
- Object.values(bundle).forEach(function (item) {
864
- if (item && item.fileName)
865
- emitted.add(item.fileName);
866
- });
1097
+ collectFiles.collectBoundleFile(bundle);
867
1098
  },
868
1099
  closeBundle: function () {
869
- var outDir = process.env.MFE_SOURCE_OUTPUT_DIR || "dist";
870
- var all = walkDir(outDir, emitted);
871
- manifestJson.setFiles(outDir, all);
872
1100
  var sourcePath = manifestJson.value.isRoot
873
1101
  ? process.env.MFE_ROOT_OUTPUT_DIR
874
1102
  : 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);
1103
+ var filePath = path.resolve(sourcePath, MANIFEST_NAME);
1104
+ collectFiles.collectCopyFiles();
1105
+ manifestJson.setFiles(collectFiles.collectedBuildFiles);
1106
+ manifestJson.saveFile(filePath);
1107
+ // console.log({ filePath }, "sourcePath");
1108
+ // addRunningAppToSave(manifestJson.value.appCode, filePath);
1109
+ setTimeout(function () {
1110
+ collectFiles.copyFilesToPublishDir();
1111
+ }, 0);
879
1112
  },
880
1113
  };
881
1114
  };
882
1115
 
1116
+ var app = null;
883
1117
  var createHttpServer = function () {
884
- var app = express();
1118
+ if (app)
1119
+ return app;
1120
+ app = express();
885
1121
  var server = http.createServer(app);
1122
+ app.get("".concat(HTTP_PATH, "/root-path"), function (req, res) {
1123
+ res.send(process.env);
1124
+ });
886
1125
  app.use(cors({ origin: "*" }));
887
- return server;
1126
+ return {
1127
+ server: server,
1128
+ start: function (type) {
1129
+ var originKey = type || "http";
1130
+ server.listen(WS_PORT, function () {
1131
+ console.log("[uni-".concat(originKey, "] ").concat(originKey, "://localhost:").concat(WS_PORT).concat(HTTP_PATH));
1132
+ });
1133
+ },
1134
+ };
888
1135
  };
889
1136
 
890
1137
  var WsServer = /** @class */ (function () {
@@ -906,17 +1153,12 @@ var WsServer = /** @class */ (function () {
906
1153
  if (this.wss)
907
1154
  return; // 避免重复创建
908
1155
  this.wss = new WebSocketServer({
909
- server: this.httpServer, // 绑定到 Vite 的 HTTP 服务器
1156
+ server: this.httpServer.server, // 绑定到 Vite 的 HTTP 服务器
910
1157
  path: WS_PATH, // WS 连接路径,前端连接时用 ws://localhost:5173/__mfe__ws__
911
1158
  });
912
1159
  this.onMessage(this.handleMessage);
913
1160
  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
- });
1161
+ this.httpServer.start('ws');
920
1162
  };
921
1163
  WsServer.prototype.onMessage = function (callback) {
922
1164
  // WebSocketServer 不支持直接监听 message,必须在 connection 后的 socket 上监听
@@ -1046,9 +1288,37 @@ var WsClientServer = /** @class */ (function () {
1046
1288
  // export const mfeServer = new WsServer();
1047
1289
  // export const mfeClientServer = new WsClientServer();
1048
1290
 
1049
- /**
1050
- * 过滤 Manifest 列表并获取主应用 app.json 路径
1051
- */
1291
+ // export const addRunningAppToSave = (appCode, filePath: string) => {
1292
+ // const content = uniReadFile(SERVE_MPWEIXIN_MANIFEST);
1293
+ // if (content) {
1294
+ // content[appCode] = filePath;
1295
+ // }
1296
+ // writeFiles(SERVE_MPWEIXIN_MANIFEST, JSON.stringify(content, null, 2));
1297
+ // };
1298
+ var getAppsManifestList = function (mode) {
1299
+ var _a;
1300
+ var manifest = formatCliCommandConfig(mode);
1301
+ if (!manifest.isRoot) {
1302
+ return [];
1303
+ }
1304
+ if (manifest.serve) {
1305
+ return [];
1306
+ }
1307
+ var mfeJson = getMfeJson();
1308
+ if (!((_a = mfeJson === null || mfeJson === void 0 ? void 0 : mfeJson.apps) === null || _a === void 0 ? void 0 : _a.length)) {
1309
+ throw new Error("mfeJson.apps is empty");
1310
+ }
1311
+ var apps = ((mfeJson === null || mfeJson === void 0 ? void 0 : mfeJson.apps) || []).map(function (_a) {
1312
+ var appCode = _a.appCode;
1313
+ return {
1314
+ appCode: appCode,
1315
+ filePath: "".concat(process.env.UNI_OUTPUT_DIR, "/").concat(appCode, "/").concat(MANIFEST_NAME),
1316
+ };
1317
+ });
1318
+ // console.log(apps);
1319
+ return apps;
1320
+ };
1321
+
1052
1322
  var filterManifestJsonListAndMainPageJson = function (manifestJsonList) {
1053
1323
  var outputPageJsonPath = getMainAppJsonPath();
1054
1324
  return {
@@ -1056,9 +1326,6 @@ var filterManifestJsonListAndMainPageJson = function (manifestJsonList) {
1056
1326
  manifestList: manifestJsonList.filter(function (item) { return !checkIsRootManifest(item); }),
1057
1327
  };
1058
1328
  };
1059
- /**
1060
- * 根据 Manifest 列表渲染 app.json 的 subPackages
1061
- */
1062
1329
  var renderPagesJsonByArray = function (appPages, pageJson) {
1063
1330
  var _loop_1 = function (app) {
1064
1331
  var _a = getPagesJson(JSON.stringify((app === null || app === void 0 ? void 0 : app.pagesJson) || {}), true).pages, pages = _a === void 0 ? [] : _a;
@@ -1066,7 +1333,6 @@ var renderPagesJsonByArray = function (appPages, pageJson) {
1066
1333
  root: app.appCode,
1067
1334
  pages: __spreadArray([], pages, true),
1068
1335
  };
1069
- // 移除旧的 subPackage 配置并添加新的
1070
1336
  pageJson.subPackages = pageJson.subPackages.filter(function (i) { return i.root !== currentTemp.root; });
1071
1337
  pageJson.subPackages.push(currentTemp);
1072
1338
  pageJson.subPackages = pageJson.subPackages.filter(function (i) { return i.pages.length; });
@@ -1080,62 +1346,43 @@ var renderPagesJsonByArray = function (appPages, pageJson) {
1080
1346
  }
1081
1347
  return pageJson;
1082
1348
  };
1083
- /**
1084
- * 生成完整的主应用 app.json
1085
- */
1086
1349
  var genreFullMainAppJsonByManifestList = function (appJson, manifestList) {
1087
1350
  return renderPagesJsonByArray(manifestList, appJson);
1088
1351
  };
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;
1352
+ var DistWatcher = /** @class */ (function () {
1353
+ function DistWatcher() {
1097
1354
  }
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 });
1355
+ DistWatcher.prototype.start = function (mainPwd, onReady, onChange) {
1356
+ var root = process.env.MFE_SOURCE_OUTPUT_DIR;
1357
+ if (!root)
1358
+ return;
1359
+ var filePath = path.resolve(root);
1360
+ checkAndgenreDir(filePath);
1361
+ var parentDir = path.dirname(filePath);
1362
+ var watcher = createFileWatcher(parentDir);
1363
+ var isTargetFile = function (p) {
1364
+ return p.startsWith(filePath + path.sep) || p === filePath;
1365
+ };
1366
+ watcher.on("ready", onReady);
1367
+ ["add", "change", "unlink"].forEach(function (evt) {
1368
+ // @ts-ignore
1369
+ watcher.on(evt, function (p) {
1370
+ if (!isTargetFile(p))
1371
+ return;
1372
+ var rel = path.relative(filePath, p);
1373
+ var sourcePath = p;
1374
+ var targetPath = path.join(mainPwd, rel);
1375
+ if (["add", "change"].includes(evt)) {
1376
+ copyFilesByTargetPath(sourcePath, targetPath);
1377
+ }
1378
+ onChange === null || onChange === void 0 ? void 0 : onChange({ type: evt, p: p, sourcePath: sourcePath, targetPath: targetPath });
1379
+ });
1129
1380
  });
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) {
1381
+ };
1382
+ return DistWatcher;
1383
+ }());
1384
+ var genreNewAppJson = function (outputPageJsonPath, appJson, manifestList) {
1137
1385
  try {
1138
- var appJson = uniReadFile(mainAppJsonPath);
1139
1386
  var newAppJSon = genreFullMainAppJsonByManifestList(__assign({ subPackages: [] }, appJson), manifestList);
1140
1387
  writeFiles(outputPageJsonPath, newAppJSon);
1141
1388
  }
@@ -1143,9 +1390,6 @@ var genreNewAppJson = function (outputPageJsonPath, mainAppJsonPath, manifestLis
1143
1390
  console.error("[AppJSON] Genre failed:", error);
1144
1391
  }
1145
1392
  };
1146
- /**
1147
- * 处理主应用服务端逻辑
1148
- */
1149
1393
  var createMainAppServer = function (manifestJson) {
1150
1394
  var mfeServer = WsServer.getInstance(function (opt) {
1151
1395
  var type = opt.type, data = opt.data;
@@ -1154,9 +1398,8 @@ var createMainAppServer = function (manifestJson) {
1154
1398
  var manifestPath = path.join(process.env.UNI_OUTPUT_DIR, data.appCode, MANIFEST_NAME);
1155
1399
  try {
1156
1400
  var manifestChildJson = uniReadFile(manifestPath);
1157
- genreNewAppJson(outputPageJsonPath, outputPageJsonPath, [
1158
- manifestChildJson,
1159
- ]);
1401
+ var mainAppJson = uniReadFile(outputPageJsonPath);
1402
+ genreNewAppJson(outputPageJsonPath, mainAppJson, [manifestChildJson]);
1160
1403
  }
1161
1404
  catch (e) {
1162
1405
  console.error("[Server] Handle child change failed:", e);
@@ -1166,9 +1409,6 @@ var createMainAppServer = function (manifestJson) {
1166
1409
  mfeServer.createServer();
1167
1410
  return mfeServer;
1168
1411
  };
1169
- /**
1170
- * 处理子应用客户端逻辑
1171
- */
1172
1412
  var createMainAppClient = function (manifestJson, onInit) {
1173
1413
  var client = WsClientServer.getInstance(function (opt) {
1174
1414
  if (opt.type === E_WS_TYPE.INIT) {
@@ -1178,20 +1418,48 @@ var createMainAppClient = function (manifestJson, onInit) {
1178
1418
  client.connect(manifestJson.value.appCode);
1179
1419
  return client;
1180
1420
  };
1181
- /**
1182
- * 创建主应用插件
1183
- */
1184
1421
  var createMainAppPlugin = function (manifestJson) {
1185
1422
  var mainPwd = "";
1186
1423
  var isWatcherReady = false;
1187
1424
  var mfeClientServer;
1188
1425
  var fn = null;
1426
+ var isBuild = function () { return process.env.MFE_BUILD_MODE === EBuildMode.BUILD; };
1427
+ var isServe = function () { return manifestJson.value.isServe; };
1428
+ var isRoot = function () { return manifestJson.value.isRoot; };
1429
+ var isStartServer = function () {
1430
+ if (isBuild())
1431
+ return false;
1432
+ return isServe();
1433
+ };
1434
+ var watchFile = function () {
1435
+ var allManifest = getAppsManifestList(manifestJson.value.mode);
1436
+ var watchFileList = allManifest.map(function (item) { return item.filePath; });
1437
+ var watcher = createFileWatcher(watchFileList);
1438
+ watcher.on("change", function (path) {
1439
+ var manifestJson = uniFsReadJSONFile(path);
1440
+ var outputPageJsonPath = getMainAppJsonPath();
1441
+ var mainAppJson = uniFsReadJSONFile(outputPageJsonPath);
1442
+ genreNewAppJson(outputPageJsonPath, mainAppJson, [manifestJson]);
1443
+ });
1444
+ };
1445
+ var distWatcher = new DistWatcher();
1189
1446
  var serverPlugin = {
1190
1447
  name: "@dd-code:main-app:serve",
1191
1448
  config: function () {
1192
1449
  return __awaiter(this, void 0, void 0, function () {
1193
- return __generator(this, function (_a) {
1194
- if (manifestJson.value.isRoot) {
1450
+ var isServe, _a, start;
1451
+ return __generator(this, function (_b) {
1452
+ isServe = isStartServer();
1453
+ if (isBuild())
1454
+ return [2 /*return*/];
1455
+ if (!isServe) {
1456
+ if (!isBuild() && isRoot()) {
1457
+ _a = createHttpServer(), _a.server, start = _a.start;
1458
+ start();
1459
+ }
1460
+ return [2 /*return*/];
1461
+ }
1462
+ if (isRoot()) {
1195
1463
  createMainAppServer();
1196
1464
  }
1197
1465
  else {
@@ -1204,7 +1472,10 @@ var createMainAppPlugin = function (manifestJson) {
1204
1472
  });
1205
1473
  },
1206
1474
  closeBundle: function () {
1207
- if (!manifestJson.value.isRoot) {
1475
+ var isServe = isStartServer();
1476
+ if (!isServe)
1477
+ return;
1478
+ if (!isRoot()) {
1208
1479
  serverPlugin.initWatchChange();
1209
1480
  fn === null || fn === void 0 ? void 0 : fn();
1210
1481
  fn = null;
@@ -1213,9 +1484,8 @@ var createMainAppPlugin = function (manifestJson) {
1213
1484
  initWatchChange: function () {
1214
1485
  if (isWatcherReady)
1215
1486
  return;
1216
- watchDistChangeAndSyncFile(mainPwd, function () {
1487
+ distWatcher.start(mainPwd, function () {
1217
1488
  isWatcherReady = true;
1218
- // console.log(`[Watcher] Ready watching: ${process.env.MFE_SOURCE_OUTPUT_DIR}`);
1219
1489
  }, function (change) {
1220
1490
  fn = function () {
1221
1491
  return mfeClientServer.sendMessage(E_WS_TYPE.CHANGE, __assign(__assign({}, change), { appCode: manifestJson.value.appCode }));
@@ -1236,18 +1506,43 @@ var createMainAppPlugin = function (manifestJson) {
1236
1506
  };
1237
1507
  return [
1238
1508
  serverPlugin,
1509
+ {
1510
+ name: "@dd-code:main-app:watch",
1511
+ closeBundle: function () {
1512
+ return __awaiter(this, void 0, void 0, function () {
1513
+ return __generator(this, function (_a) {
1514
+ if (isBuild())
1515
+ return [2 /*return*/];
1516
+ if (isServe())
1517
+ return [2 /*return*/];
1518
+ if (!checkIsBuildInChild())
1519
+ return [2 /*return*/];
1520
+ // if (!isServe) return;
1521
+ watchFile === null || watchFile === void 0 ? void 0 : watchFile();
1522
+ watchFile = null;
1523
+ return [2 /*return*/];
1524
+ });
1525
+ });
1526
+ },
1527
+ },
1239
1528
  {
1240
1529
  name: "@dd-code:main-app",
1241
1530
  enforce: "post",
1242
1531
  closeBundle: function () {
1243
1532
  return __awaiter(this, void 0, void 0, function () {
1244
- var _a, outputPageJsonPath, manifestList, mainAppJsonPath;
1533
+ var _a, outputPageJsonPath, manifestList, mainAppJsonPath, mainAppJson;
1245
1534
  return __generator(this, function (_b) {
1246
1535
  _a = filterManifestJsonListAndMainPageJson(__spreadArray(__spreadArray([], manifestJson.dependencies, true), [
1247
1536
  manifestJson.value,
1248
1537
  ], false)), outputPageJsonPath = _a.outputPageJsonPath, manifestList = _a.manifestList;
1249
- mainAppJsonPath = getMainAppJSon(manifestJson.value.mode, ROOT_APP_CODE);
1250
- genreNewAppJson(outputPageJsonPath, mainAppJsonPath, manifestList);
1538
+ if (!isRoot() && !isServe() && checkIsBuildInChild()) {
1539
+ return [2 /*return*/];
1540
+ }
1541
+ mainAppJsonPath = !isRoot()
1542
+ ? getNodeModuleMainAppJSon(manifestJson.value.mode, ROOT_APP_CODE)
1543
+ : getMainAppJsonPath();
1544
+ mainAppJson = uniReadFile(mainAppJsonPath);
1545
+ genreNewAppJson(outputPageJsonPath, mainAppJson, manifestList);
1251
1546
  return [2 /*return*/];
1252
1547
  });
1253
1548
  });
@@ -1263,8 +1558,18 @@ var createMpWeixinUniPlugin = function (options) {
1263
1558
  name: "@dd-code:genre-params",
1264
1559
  enforce: "pre",
1265
1560
  config: function (config) {
1266
- currentManifestJson.setEnv(config.mode);
1267
- resetOutDir(currentManifestJson, config);
1561
+ return __awaiter(this, void 0, void 0, function () {
1562
+ return __generator(this, function (_a) {
1563
+ switch (_a.label) {
1564
+ case 0:
1565
+ currentManifestJson.setEnv(config.mode);
1566
+ return [4 /*yield*/, resetOutDir(currentManifestJson, config)];
1567
+ case 1:
1568
+ _a.sent();
1569
+ return [2 /*return*/];
1570
+ }
1571
+ });
1572
+ });
1268
1573
  },
1269
1574
  },
1270
1575
  createAppsAssetsPlugin(currentManifestJson),