@dd-code/uni-tools 1.0.6 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1 +1,1269 @@
1
- "use strict";var path=require("path"),fs=require("fs"),crypto=require("crypto"),cliProgress=require("cli-progress"),chalk=require("chalk"),fsExtra=require("fs-extra"),chokidar=require("chokidar"),WebSocket=require("ws"),express=require("express"),http=require("http"),cors=require("cors"),__assign=function(){return __assign=Object.assign||function(e){for(var n,t=1,r=arguments.length;t<r;t++)for(var a in n=arguments[t])Object.prototype.hasOwnProperty.call(n,a)&&(e[a]=n[a]);return e},__assign.apply(this,arguments)};function __awaiter(e,n,t,r){return new(t||(t=Promise))(function(a,o){function i(e){try{c(r.next(e))}catch(e){o(e)}}function s(e){try{c(r.throw(e))}catch(e){o(e)}}function c(e){var n;e.done?a(e.value):(n=e.value,n instanceof t?n:new t(function(e){e(n)})).then(i,s)}c((r=r.apply(e,n||[])).next())})}function __generator(e,n){var t,r,a,o={label:0,sent:function(){if(1&a[0])throw a[1];return a[1]},trys:[],ops:[]},i=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return i.next=s(0),i.throw=s(1),i.return=s(2),"function"==typeof Symbol&&(i[Symbol.iterator]=function(){return this}),i;function s(s){return function(c){return function(s){if(t)throw new TypeError("Generator is already executing.");for(;i&&(i=0,s[0]&&(o=0)),o;)try{if(t=1,r&&(a=2&s[0]?r.return:s[0]?r.throw||((a=r.return)&&a.call(r),0):r.next)&&!(a=a.call(r,s[1])).done)return a;switch(r=0,a&&(s=[2&s[0],a.value]),s[0]){case 0:case 1:a=s;break;case 4:return o.label++,{value:s[1],done:!1};case 5:o.label++,r=s[1],s=[0];continue;case 7:s=o.ops.pop(),o.trys.pop();continue;default:if(!(a=o.trys,(a=a.length>0&&a[a.length-1])||6!==s[0]&&2!==s[0])){o=0;continue}if(3===s[0]&&(!a||s[1]>a[0]&&s[1]<a[3])){o.label=s[1];break}if(6===s[0]&&o.label<a[1]){o.label=a[1],a=s;break}if(a&&o.label<a[2]){o.label=a[2],o.ops.push(s);break}a[2]&&o.ops.pop(),o.trys.pop();continue}s=n.call(e,o)}catch(e){s=[6,e],r=0}finally{t=a=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}}function __spreadArray(e,n,t){if(t||2===arguments.length)for(var r,a=0,o=n.length;a<o;a++)!r&&a in n||(r||(r=Array.prototype.slice.call(n,0,a)),r[a]=n[a]);return e.concat(r||Array.prototype.slice.call(n))}"function"==typeof SuppressedError&&SuppressedError;var MFE_NAME="mfe.json";function fetchFileByPath(e){return __awaiter(this,void 0,void 0,function(){var n;return __generator(this,function(t){switch(t.label){case 0:return t.trys.push([0,7,,8]),[4,fetch(e)];case 1:if(n=t.sent(),!e.split("?")[0].endsWith(".json"))return[3,5];t.label=2;case 2:return t.trys.push([2,4,,5]),[4,n.json()];case 3:return[2,t.sent()];case 4:return t.sent(),[3,5];case 5:return[4,n.text()];case 6:return[2,t.sent()];case 7:return t.sent(),[3,8];case 8:return[2]}})})}function uniReadFile(e){try{return e.endsWith(".json")?require(e):fs.readFileSync(e,"utf-8")}catch(e){}return""}function writeFiles(e,n){"object"==typeof n&&n&&(n=JSON.stringify(n,null,2));var t=path.dirname(e);return fs.existsSync(t)||fs.mkdirSync(t,{recursive:!0}),fs.writeFileSync(e,n,"utf-8")}var checkAndgenreDir=function(e){fs.existsSync(e)||fs.mkdirSync(e,{recursive:!0})},loadViteConfig=function(e){return(0,require("vite").loadEnv)(e,process.cwd(),"MFE_")},walkDir=function(e,n){var t=path.isAbsolute(e)?e:path.resolve(process.cwd(),e),r=[],a=function(e){(fs.existsSync(e)?fs.readdirSync(e):[]).forEach(function(n){var o=path.join(e,n);fs.statSync(o).isDirectory()?a(o):r.push(path.relative(t,o))})};return a(t),Array.from(new Set(Array.from(n).concat(r))).sort()};function generateHash(e,n,t){if(void 0===e&&(e=""),void 0===t&&(t="hex"),"string"!=typeof e)throw new Error("Content must be a string");var r=crypto.createHash(n);return r.update(e,"utf8"),r.digest(t)}function generateSHA256(e){return generateHash(e,"sha256")}var UniCdnManager=function(){function e(){this.HOST=""}return e.prototype.setCdnHost=function(e){this.HOST=e},e.prototype.getCdnUrl=function(e){var n=e.code,t=e.mode,r=e.appCode;return["".concat(this.HOST),getManifestCdnDirUrl({mode:t,code:n,appCode:r})]},e.prototype.getManifestUrl=function(e){var n=e.code,t=e.appCode,r=e.mode;return __spreadArray(__spreadArray([],this.getCdnUrl({code:n,mode:r,appCode:t}),!0),["".concat(MANIFEST_NAME)],!1).join("/")},e}(),cdn=new UniCdnManager,SAVE_CDN_FILE_PATH=path.join(process.cwd(),"node_modules/@dd-code/uni-files");path.join(process.cwd(),"node_modules/@dd-code/current-files");var MANIFEST_NAME="mfe-uni-manifest.json",ROOT_APP_CODE="main",MANIFEST_CND_DIR_URL="{mode}/static-repository/mfe-uni/{code}/{appCode}",getManifestCdnDirUrl=function(e){var n=e.mode,t=e.code,r=e.appCode;return MANIFEST_CND_DIR_URL.replace("{mode}",n).replace("{code}",t).replace("{appCode}",r)},getMfeJson=function(){var e=uniReadFile(path.resolve(process.cwd(),MFE_NAME))||{};return e.platform=process.env.UNI_PLATFORM||"h5",e},getMainAppJson=function(e){return __awaiter(void 0,void 0,void 0,function(){var n;return __generator(this,function(t){switch(t.label){case 0:return n=formatCliCommandConfig(e),[4,fetchFileByPath(cdn.getManifestUrl({code:n.code,appCode:ROOT_APP_CODE,mode:e}))];case 1:return[2,t.sent()]}})})},getMainAppPages=function(e){return __awaiter(void 0,void 0,void 0,function(){return __generator(this,function(n){switch(n.label){case 0:return[4,getMainAppJson(e)];case 1:return[2,n.sent().apps||[{appCode:"modules/bwzb"},{appCode:"modules/manage"},{appCode:"login"}]]}})})},getPlatform=function(){return process.env.UNI_PLATFORM||"h5"},formatCliCommandConfig=function(e){var n=loadViteConfig(e||"dev"),t=n.MFE_UNI_IS_ROOT;return{isRoot:t,appCode:t?ROOT_APP_CODE:n.MFE_APP_CODE,code:n.MFE_UNI_CODE,mode:e,cdn:n.MFE_CDN_HOST}},checkIsRootManifest=function(e){return e.isRoot||e.appCode===ROOT_APP_CODE},WS_PORT=3560,WS_PATH="/__mfe__ws__",E_WS_TYPE;!function(e){e.INIT="init_files",e.CHANGE="change_files"}(E_WS_TYPE||(E_WS_TYPE={}));var getMainAppJSon=function(e,n){return path.join(SAVE_CDN_FILE_PATH,e||"dev",n,"app.json")},getMainAppJsonPath=function(){return path.join(process.env.UNI_OUTPUT_DIR,"app.json")},EPlaform;!function(e){e.H5="h5",e.MP_WEIXIN="mp-weixin"}(EPlaform||(EPlaform={}));var CliProgressManager=function(){function e(){this.barMap=new Map}return e.prototype.initMultiBar=function(e){this.multiBar=new cliProgress.MultiBar({clearOnComplete:!1,hideCursor:!0,format:e||"".concat(chalk.yellow("{name}"),": ").concat(chalk.blue("{bar}")," | ").concat(chalk.green("{percentage}%")," | {value}/{total}"),barCompleteChar:"█",barIncompleteChar:"░",barGlue:"",stopOnComplete:!0},cliProgress.Presets.shades_grey)},e.prototype.createProgressBar=function(e){var n=this;e.forEach(function(e){var t=n.multiBar.create(e.total,0,{name:e.name});n.barMap.set(e.name,t)})},e.prototype.updateProgressBar=function(e,n){var t=this.barMap.get(e);if(t){var r=t.getTotal();t.update(n),n>=r&&t.stop()}},e.prototype.stopAll=function(){this.multiBar.stop()},e}(),CliProgressManager$1=new CliProgressManager,getDownloadedFilePath=function(e){return path.resolve(SAVE_CDN_FILE_PATH,e.env,e.appCode)},getNodeModulesEnvAppCodeFilePath=function(e,n){return path.resolve(getDownloadedFilePath(e),n)},getManifestJsonUrl=function(e){return __awaiter(void 0,void 0,void 0,function(){var n,t,r,a,o,i,s,c;return __generator(this,function(u){switch(u.label){case 0:n=formatCliCommandConfig(e),t=n.isRoot,r=void 0!==t&&t,a=n.code,o=void 0===a?"mfe-uni":a,i=[],s=getMfeJson(),u.label=1;case 1:return u.trys.push([1,5,,6]),c=[],r?(c=s.apps||[],[3,4]):[3,2];case 2:return[4,getMainAppPages(e)];case 3:c=__spreadArray(__spreadArray([],c=u.sent(),!0),[{appCode:ROOT_APP_CODE}],!1),u.label=4;case 4:return i=Array.from(new Set(__spreadArray([],(c||[]).map(function(e){return e.appCode}),!0))),[3,6];case 5:return u.sent(),i=[],[3,6];case 6:return[2,i.map(function(n){return{url:cdn.getManifestUrl({code:o,appCode:n,mode:e}),appCode:n,code:o}})]}})})},downloadManifestJson=function(e){return __awaiter(void 0,void 0,void 0,function(){var n,t;return __generator(this,function(r){switch(r.label){case 0:return n=e.map(function(e){return __awaiter(void 0,void 0,void 0,function(){return __generator(this,function(n){switch(n.label){case 0:return[4,fetchFileByPath(e).catch(function(e){})];case 1:return[2,n.sent()]}})})}),[4,Promise.all(n)];case 1:return t=r.sent(),[2,t.filter(function(e){return e})]}})})};function downloadFilesByManifestJson(e,n,t){return __awaiter(this,void 0,void 0,function(){var r,a,o,i,s,c,u,p,l,d,f,h,g;return __generator(this,function(v){switch(v.label){case 0:for(u in r=e.cdn,a=e.appCode,o=e.publicPath,i=e.files,c=[],s=i)c.push(u);p=0,v.label=1;case 1:return p<c.length?(u=c[p])in s?(d=i[l=u],f=d.fileUrl,h=d.fileName,[4,fetchFileByPath("".concat(r,"/").concat(o,"/").concat(f))]):[3,3]:[3,4];case 2:g=v.sent(),writeFiles(path.join(n,a||"",h),g),t&&t(Number(l),d.length),v.label=3;case 3:return p++,[3,1];case 4:return[2]}})})}var downloadProjectFiles=function(e){return __awaiter(void 0,void 0,void 0,function(){var n,t,r;return __generator(this,function(a){switch(a.label){case 0:for(r in n=[],CliProgressManager$1.initMultiBar(),CliProgressManager$1.createProgressBar(e.map(function(e){return{name:e.appCode,total:e.files.length}})),t=function(t){var r=e[t],a=downloadFilesByManifestJson(r,path.resolve(SAVE_CDN_FILE_PATH,r.mode||"dev"),function(e,n){CliProgressManager$1.updateProgressBar(r.appCode,e+1)});n.push(a)},e)t(r);return[4,Promise.all(n)];case 1:return a.sent(),CliProgressManager$1.stopAll(),[2]}})})},checkDownloadFilesIsExpired=function(e){return e.filter(function(e){var n=uniReadFile(getNodeModulesEnvAppCodeFilePath(e,MANIFEST_NAME));return!n||(null==n?void 0:n.hash)!==e.hash})},createManifestManager=function(){var e={code:"",mode:"",cdn:"",hash:"",publicPath:"",appCode:"",platform:process.env.UNI_PLATFORM||"h5",pagesJson:{},files:[]};return{get value(){return e},setFiles:function(n,t){var r=t.map(function(e){var t=path.resolve(n,e),r=generateSHA256(fs.readFileSync(t,"utf-8"));return{fileName:e,fileUrl:"".concat(r.slice(0,8),"_").concat(path.basename(e))}});e.files=r},setPagesJson:function(n){e.pagesJson=n},saveFile:function(n){var t=e.files.filter(function(e){return e.fileName!==MANIFEST_NAME});e.hash=generateSHA256(JSON.stringify(__assign(__assign({},e),{files:t}))),writeFiles(path.resolve(n,MANIFEST_NAME),JSON.stringify(e,null,2))},setEnv:function(n){var t=formatCliCommandConfig(n),r=getMfeJson();e.cdn=t.cdn,e.mode=n,e.code=t.code,e.appCode=t.appCode,cdn.setCdnHost(t.cdn),t.isRoot&&(e.isRoot=!0,e.apps=r.apps),e.publicPath=getManifestCdnDirUrl(e)},dependencies:[],setDependencies:function(e){this.dependencies=e}}},resetOutDir=function(e,n){var t,r=new RegExp("/(".concat(e.value.appCode,")/?"));process.env.MFE_SOURCE_OUTPUT_DIR=n.build.outDir,process.env.MFE_ROOT_OUTPUT_DIR=null===(t=process.env.MFE_SOURCE_OUTPUT_DIR)||void 0===t?void 0:t.replace(r,"/").replace(/\/$/,""),process.env.UNI_OUTPUT_DIR=process.env.MFE_ROOT_OUTPUT_DIR},copyFilesByTargetPath=function(e,n){if(fs.existsSync(e)){try{var t=path.dirname(n);fsExtra.ensureDirSync(t)}catch(e){}fsExtra.copySync(e,n,{overwrite:!0})}},downloadFullApps=function(e){return __awaiter(void 0,void 0,void 0,function(){var n,t,r,a;return __generator(this,function(o){switch(o.label){case 0:return[4,getManifestJsonUrl(e.mode)];case 1:return n=o.sent(),t=n.filter(function(n){return n.appCode!==e.appCode}),[4,downloadManifestJson(t.map(function(e){return e.url}))];case 2:return r=o.sent(),(a=checkDownloadFilesIsExpired(r)).length?[4,downloadProjectFiles(a)]:[3,4];case 3:o.sent(),o.label=4;case 4:return[2,r]}})})},moveOtherApps=function(e){var n=e.base,t=e.manifestList,r=process.env.MFE_ROOT_OUTPUT_DIR;t.forEach(function(e){var t=e.appCode,a=checkIsRootManifest(e)?r:path.resolve(r,t),o=path.resolve(n,t);try{copyFilesByTargetPath(o,a)}catch(e){}})},createAppsAssetsPlugin=function(e){var n=[],t=!1;return{name:"@dd-code:apps-assets",enforce:"pre",options:function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){switch(t.label){case 0:return[4,downloadFullApps(e.value)];case 1:return n=t.sent(),e.setDependencies(n),[2]}})})},buildStart:function(){if(!t){var r=path.resolve(SAVE_CDN_FILE_PATH,e.value.mode||"dev");moveOtherApps({base:r,manifestList:n}),t=!0}}}},initPreContext=require("@dcloudio/uni-cli-shared/dist/preprocess").initPreContext,preprocess=require("@dcloudio/uni-cli-shared/lib/preprocess").preprocess,getPreVueContext=require("@dcloudio/uni-cli-shared/dist/preprocess/context").getPreVueContext,initPrePagesJson=function(){var e=path.resolve(process.cwd(),"src/pages.json");return fs.readFileSync(e,"utf-8")},getPagesJson=function(jsonFile,isFormat){void 0===isFormat&&(isFormat=!1);var platform=process.env.UNI_PLATFORM;initPreContext(platform);var context=getPreVueContext(),processedJsonStr=preprocess(jsonFile,context,{type:"js"}),pagesConfig=eval("(".concat(processedJsonStr,")"));return isFormat&&"mp-weixin"===platform?transformToWeixinFormat(pagesConfig):pagesConfig},transformToWeixinFormat=function(e){var n,t=__assign({pages:[],window:{},tabBar:null,subPackages:[],usingComponents:{}},e);if(e.globalStyle){var r=e.globalStyle;t.window={navigationBarBackgroundColor:r.navigationBarBackgroundColor||"#000000",navigationBarTextStyle:r.navigationBarTextStyle||"white",navigationBarTitleText:r.navigationBarTitleText||"",backgroundColor:r.backgroundColor||"#ffffff",backgroundTextStyle:r.backgroundTextStyle||"dark",enablePullDownRefresh:r.enablePullDownRefresh||!1,onReachBottomDistance:r.onReachBottomDistance||50},r.pageOrientation&&(t.window.pageOrientation=r.pageOrientation),r.renderingMode&&(t.window.renderingMode=r.renderingMode),r.usingComponents&&(t.usingComponents=r.usingComponents),r["mp-weixin"]&&Object.assign(t.window,r["mp-weixin"])}return e.pages&&(t.pages=e.pages.map(function(e){return e.path})),e.tabBar&&(t.tabBar=__assign(__assign({},e.tabBar),{list:null===(n=e.tabBar.list)||void 0===n?void 0:n.map(function(e){return{pagePath:e.pagePath,text:e.text,iconPath:e.iconPath,selectedIconPath:e.selectedIconPath}})})),e.subPackages&&(t.subPackages=e.subPackages.map(function(e){var n;return{root:e.root,pages:(null===(n=e.pages)||void 0===n?void 0:n.map(function(e){return e.path||e}))||[]}})),e.preloadRule&&(t.preloadRule=e.preloadRule),delete t.globalStyle,delete t.easycom,delete t.condition,delete t.leftWindow,delete t.topWindow,delete t.rightWindow,delete t.uniIdRouter,delete t.entryPagePath,t},createManifestPlugin=function(e){var n=new Set;return{name:"@dd-code:genre-mainfest-file-list",enforce:"post",renderStart:function(){var n=initPrePagesJson(),t=getPagesJson(n);e.setPagesJson(t)},writeBundle:function(e,t){Object.values(t).forEach(function(e){e&&e.fileName&&n.add(e.fileName)})},closeBundle:function(){var t=process.env.MFE_SOURCE_OUTPUT_DIR||"dist",r=walkDir(t,n);e.setFiles(t,r);var a=e.value.isRoot?process.env.MFE_ROOT_OUTPUT_DIR:path.resolve(process.env.MFE_ROOT_OUTPUT_DIR,e.value.appCode);e.saveFile(a)}}},createHttpServer=function(){var e=express(),n=http.createServer(e);return e.use(cors({origin:"*"})),n},WsServer=function(){function e(e){this.handleMessage=e,this.httpServer=createHttpServer(),this.clientMap=new Map}return e.prototype.createServer=function(){this.wss=new WebSocket.WebSocketServer({server:this.httpServer,path:WS_PATH}),this.onMessage(this.handleMessage),this.onConnection(),this.start()},e.prototype.start=function(){this.httpServer.listen(WS_PORT,function(){})},e.prototype.onMessage=function(e){e&&(this.handleMessage=e)},e.prototype.sendMessageToApp=function(e,n){var t=this.clientMap.get(e);t&&t.send("string"==typeof n?n:JSON.stringify(n))},e.prototype.onConnection=function(){var e=this;this.wss.on("connection",function(n,t){n.on("message",function(n){var t;try{var r=JSON.parse(n.toString());null===(t=e.handleMessage)||void 0===t||t.call(e,r)}catch(e){}});var r=new URL(t.url,"http://".concat(t.headers.host)).searchParams.get("appCode");r&&(e.clientMap.set(r,n),e.sendMessageToApp(r,{type:E_WS_TYPE.INIT,data:{pwd:process.env.UNI_OUTPUT_DIR}}))})},e}(),WsClientServer=function(){function e(e){this.handleMessage=e,this.handleMessage=e,this.ws=null,this.isConnected=!1}return e.prototype.connect=function(e){var n=this;this.ws=new WebSocket("ws://localhost:".concat(WS_PORT).concat(WS_PATH,"?appCode=").concat(e)),this.ws.on("open",function(){n.isConnected=!0}),this.ws.on("close",function(){n.isConnected=!1,n.retryConnect(e)}),this.ws.on("error",function(){n.isConnected=!1,n.retryConnect(e)}),this.onMessage(this.handleMessage)},e.prototype.sendMessage=function(e,n){this.isConnected&&this.ws.send(JSON.stringify({type:e,data:n}))},e.prototype.onMessage=function(e){this.ws.on("message",function(n){null==e||e(JSON.parse(n.toString()))})},e.prototype.retryConnect=function(e){var n=this;this.isConnected||(this.isConnected=!0,setTimeout(function(){n.connect(e)},3e3))},e}(),filterManifestJsonListAndMainPageJson=function(e){return{outputPageJsonPath:getMainAppJsonPath(),manifestList:e.filter(function(e){return!checkIsRootManifest(e)})}},renderPagesJsonByArray=function(e,n){for(var t=function(e){var t=getPagesJson(JSON.stringify((null==e?void 0:e.pagesJson)||{}),!0).pages,r=void 0===t?[]:t,a={root:e.appCode,pages:__spreadArray([],r,!0)};n.subPackages=n.subPackages.filter(function(e){return e.root!==a.root}),n.subPackages.push(a),n.subPackages=n.subPackages.filter(function(e){return e.pages.length})},r=0,a=e;r<a.length;r++){t(a[r])}return n.tabBar||delete n.tabBar,n},genreFullMainAppJsonByManifestList=function(e,n){return renderPagesJsonByArray(n,e)},watchDistChangeAndSyncFile=function(e,n,t){var r=process.env.MFE_SOURCE_OUTPUT_DIR;if(r){var a=path.resolve(r);checkAndgenreDir(a);var o=path.dirname(a),i=chokidar.watch(o,{persistent:!0,ignoreInitial:!0,usePolling:!0,interval:100,awaitWriteFinish:{stabilityThreshold:200,pollInterval:100},followSymlinks:!0,depth:99});i.on("ready",n),["add","change","unlink"].forEach(function(n){i.on(n,function(r){if(function(e){return e.startsWith(a+path.sep)||e===a}(r)){var o=path.relative(a,r),i=r,s=path.join(e,o);["add","change"].includes(n)&&copyFilesByTargetPath(i,s),null==t||t({type:n,p:r,sourcePath:i,targetPath:s})}})}),i.on("error",function(e){})}},genreNewAppJson=function(e,n,t){try{var r=uniReadFile(n);writeFiles(e,genreFullMainAppJsonByManifestList(__assign({subPackages:[]},r),t))}catch(e){}},createMainAppServer=function(e){var n=new WsServer(function(e){var n=e.type,t=e.data;if(n===E_WS_TYPE.CHANGE){var r=getMainAppJsonPath(),a=path.join(process.env.UNI_OUTPUT_DIR,t.appCode,MANIFEST_NAME);try{var o=uniReadFile(a);genreNewAppJson(r,r,[o])}catch(e){}}});return n.createServer(),n},createMainAppClient=function(e,n){var t=new WsClientServer(function(e){e.type===E_WS_TYPE.INIT&&n(e.data)});return t.connect(e.value.appCode),t},createMainAppPlugin=function(e){var n,t="",r=!1,a=null,o={name:"@dd-code:main-app:serve",config:function(){return __awaiter(this,void 0,void 0,function(){return __generator(this,function(t){return e.value.isRoot?createMainAppServer():n=createMainAppClient(e,function(e){o.copyAppDistModule(e)}),[2]})})},closeBundle:function(){e.value.isRoot||(o.initWatchChange(),null==a||a(),a=null)},initWatchChange:function(){r||watchDistChangeAndSyncFile(t,function(){r=!0},function(t){a=function(){return n.sendMessage(E_WS_TYPE.CHANGE,__assign(__assign({},t),{appCode:e.value.appCode}))}})},copyAppDistModule:function(n){var r=n.pwd;if(process.env.MFE_SOURCE_OUTPUT_DIR){var a=t=path.join(r,e.value.appCode),o=process.env.MFE_SOURCE_OUTPUT_DIR;copyFilesByTargetPath(o,a)}}};return[o,{name:"@dd-code:main-app",enforce:"post",closeBundle:function(){return __awaiter(this,void 0,void 0,function(){var n,t,r,a;return __generator(this,function(o){return n=filterManifestJsonListAndMainPageJson(__spreadArray(__spreadArray([],e.dependencies,!0),[e.value],!1)),t=n.outputPageJsonPath,r=n.manifestList,a=getMainAppJSon(e.value.mode,ROOT_APP_CODE),genreNewAppJson(t,a,r),[2]})})}}]},createMpWeixinUniPlugin=function(e){var n=createManifestManager();return[{name:"@dd-code:genre-params",enforce:"pre",config:function(e){n.setEnv(e.mode),resetOutDir(n,e)}},createAppsAssetsPlugin(n),createManifestPlugin(n),createMainAppPlugin(n)]},index=function(e){return getPlatform()===EPlaform.MP_WEIXIN?createMpWeixinUniPlugin():[]};module.exports=index;
1
+ 'use strict';
2
+
3
+ var path = require('path');
4
+ var fs = require('fs');
5
+ var crypto = require('crypto');
6
+ var cliProgress = require('cli-progress');
7
+ var chalk = require('chalk');
8
+ var fsExtra = require('fs-extra');
9
+ var chokidar = require('chokidar');
10
+ var WebSocket = require('ws');
11
+ var express = require('express');
12
+ var http = require('http');
13
+ var cors = require('cors');
14
+
15
+ /******************************************************************************
16
+ Copyright (c) Microsoft Corporation.
17
+
18
+ Permission to use, copy, modify, and/or distribute this software for any
19
+ purpose with or without fee is hereby granted.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
22
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
23
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
24
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
25
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
26
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
27
+ PERFORMANCE OF THIS SOFTWARE.
28
+ ***************************************************************************** */
29
+ /* global Reflect, Promise, SuppressedError, Symbol, Iterator */
30
+
31
+
32
+ var __assign = function() {
33
+ __assign = Object.assign || function __assign(t) {
34
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
35
+ s = arguments[i];
36
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
37
+ }
38
+ return t;
39
+ };
40
+ return __assign.apply(this, arguments);
41
+ };
42
+
43
+ function __awaiter(thisArg, _arguments, P, generator) {
44
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
45
+ return new (P || (P = Promise))(function (resolve, reject) {
46
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
47
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
48
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
49
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
50
+ });
51
+ }
52
+
53
+ function __generator(thisArg, body) {
54
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
55
+ return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
56
+ function verb(n) { return function (v) { return step([n, v]); }; }
57
+ function step(op) {
58
+ if (f) throw new TypeError("Generator is already executing.");
59
+ while (g && (g = 0, op[0] && (_ = 0)), _) try {
60
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
61
+ if (y = 0, t) op = [op[0] & 2, t.value];
62
+ switch (op[0]) {
63
+ case 0: case 1: t = op; break;
64
+ case 4: _.label++; return { value: op[1], done: false };
65
+ case 5: _.label++; y = op[1]; op = [0]; continue;
66
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
67
+ default:
68
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
69
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
70
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
71
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
72
+ if (t[2]) _.ops.pop();
73
+ _.trys.pop(); continue;
74
+ }
75
+ op = body.call(thisArg, _);
76
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
77
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
78
+ }
79
+ }
80
+
81
+ function __spreadArray(to, from, pack) {
82
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
83
+ if (ar || !(i in from)) {
84
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
85
+ ar[i] = from[i];
86
+ }
87
+ }
88
+ return to.concat(ar || Array.prototype.slice.call(from));
89
+ }
90
+
91
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
92
+ var e = new Error(message);
93
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
94
+ };
95
+
96
+ var MFE_NAME = "mfe.json";
97
+
98
+ /**
99
+ * 通过URL获取文件内容
100
+ * 支持JSON和文本文件的自动解析
101
+ * @param {string} src - 文件URL
102
+ * @returns {Promise<Object|string>} 返回文件内容,JSON文件返回对象,其他返回字符串
103
+ */
104
+ function fetchFileByPath(src) {
105
+ return __awaiter(this, void 0, void 0, function () {
106
+ var res, noQuerySrc;
107
+ return __generator(this, function (_a) {
108
+ switch (_a.label) {
109
+ case 0:
110
+ _a.trys.push([0, 7, , 8]);
111
+ return [4 /*yield*/, fetch(src)];
112
+ case 1:
113
+ res = _a.sent();
114
+ noQuerySrc = src.split("?")[0];
115
+ if (!noQuerySrc.endsWith(".json")) return [3 /*break*/, 5];
116
+ _a.label = 2;
117
+ case 2:
118
+ _a.trys.push([2, 4, , 5]);
119
+ return [4 /*yield*/, res.json()];
120
+ case 3: return [2 /*return*/, _a.sent()];
121
+ case 4:
122
+ _a.sent();
123
+ console.error("".concat(src, " download error"));
124
+ return [3 /*break*/, 5];
125
+ case 5: return [4 /*yield*/, res.text()];
126
+ case 6: return [2 /*return*/, _a.sent()];
127
+ case 7:
128
+ _a.sent();
129
+ console.error("".concat(src, " download error"));
130
+ return [3 /*break*/, 8];
131
+ case 8: return [2 /*return*/];
132
+ }
133
+ });
134
+ });
135
+ }
136
+ /**
137
+ * 读取文件内容
138
+ * 支持JSON文件的自动解析
139
+ * @param {string} filaPath - 文件路径
140
+ * @returns {string|Object} 返回文件内容,JSON文件返回对象,其他返回字符串
141
+ */
142
+ function uniReadFile(filaPath) {
143
+ try {
144
+ if (filaPath.endsWith(".json")) {
145
+ return require(filaPath);
146
+ }
147
+ var res = fs.readFileSync(filaPath, "utf-8");
148
+ return res;
149
+ }
150
+ catch (e) {
151
+ // console.error(`${filaPath} notfound`);
152
+ // console.log(e);
153
+ }
154
+ return "";
155
+ }
156
+ /**
157
+ * 写入文件内容
158
+ * 自动创建目录结构,支持对象和字符串内容
159
+ * @param {string} filaPath - 文件路径
160
+ * @param {string|Object} content - 文件内容
161
+ * @returns {void}
162
+ */
163
+ function writeFiles(filaPath, content) {
164
+ if (typeof content === "object" && content) {
165
+ content = JSON.stringify(content, null, 2);
166
+ }
167
+ // 检查文件路径是否存在
168
+ var dir = path.dirname(filaPath);
169
+ if (!fs.existsSync(dir)) {
170
+ // 如果路径不存在,创建路径
171
+ fs.mkdirSync(dir, { recursive: true });
172
+ }
173
+ return fs.writeFileSync(filaPath, content, "utf-8");
174
+ }
175
+ var checkAndgenreDir = function (dir) {
176
+ if (!fs.existsSync(dir)) {
177
+ // 如果路径不存在,创建路径
178
+ fs.mkdirSync(dir, { recursive: true });
179
+ }
180
+ };
181
+ var loadViteConfig = function (mode) {
182
+ var loadEnv = require("vite").loadEnv;
183
+ var ROOT = process.cwd();
184
+ return loadEnv(mode, ROOT, "MFE_");
185
+ };
186
+ var walkDir = function (outDir, emitted) {
187
+ var root = path.isAbsolute(outDir)
188
+ ? outDir
189
+ : path.resolve(process.cwd(), outDir);
190
+ var all = [];
191
+ var walk = function (dir) {
192
+ var entries = fs.existsSync(dir) ? fs.readdirSync(dir) : [];
193
+ entries.forEach(function (name) {
194
+ var p = path.join(dir, name);
195
+ var stat = fs.statSync(p);
196
+ if (stat.isDirectory())
197
+ walk(p);
198
+ else
199
+ all.push(path.relative(root, p));
200
+ });
201
+ };
202
+ walk(root);
203
+ var merged = Array.from(new Set(Array.from(emitted).concat(all))).sort();
204
+ return merged;
205
+ };
206
+ /**
207
+ * 根据内容生成hash值
208
+ * @param {string} content - 要生成hash的内容
209
+ * @param {string} algorithm - hash算法,默认为'sha256'
210
+ * @param {string} encoding - 输出编码,默认为'hex'
211
+ * @returns {string} 生成的hash值
212
+ */
213
+ function generateHash(content, algorithm, encoding) {
214
+ if (content === void 0) { content = ""; }
215
+ if (encoding === void 0) { encoding = "hex"; }
216
+ if (typeof content !== "string") {
217
+ throw new Error("Content must be a string");
218
+ }
219
+ var hash = crypto.createHash(algorithm);
220
+ hash.update(content, "utf8");
221
+ return hash.digest(encoding);
222
+ }
223
+ /**
224
+ * 根据内容生成SHA256 hash值
225
+ * @param {string} content - 要生成hash的内容
226
+ * @returns {string} 生成的SHA256 hash值
227
+ */
228
+ function generateSHA256(content) {
229
+ return generateHash(content, "sha256");
230
+ }
231
+
232
+ var UniCdnManager = /** @class */ (function () {
233
+ function UniCdnManager() {
234
+ // 初始化 CDN 管理器
235
+ this.HOST = "";
236
+ }
237
+ UniCdnManager.prototype.setCdnHost = function (host) {
238
+ this.HOST = host;
239
+ };
240
+ UniCdnManager.prototype.getCdnUrl = function (_a) {
241
+ var code = _a.code, mode = _a.mode, appCode = _a.appCode;
242
+ if (!this.HOST) {
243
+ throw Error('请先设置环境变量 MFE_CDN_HOST');
244
+ }
245
+ // this.HOST = this.HOST || loadViteConfig(mode || "dev").MFE_CDN_HOST;
246
+ // const viteEnv = loadViteConfig(mode || "dev").MFE_CDN_HOST;
247
+ // const HOST = process.env.MFE_CDN_HOST || "";
248
+ return ["".concat(this.HOST), getManifestCdnDirUrl({ mode: mode, code: code, appCode: appCode })];
249
+ };
250
+ UniCdnManager.prototype.getManifestUrl = function (_a) {
251
+ var code = _a.code, appCode = _a.appCode, mode = _a.mode;
252
+ var url = __spreadArray(__spreadArray([], this.getCdnUrl({ code: code, mode: mode, appCode: appCode }), true), [
253
+ "".concat(MANIFEST_NAME),
254
+ ], false).join("/");
255
+ return url;
256
+ };
257
+ return UniCdnManager;
258
+ }());
259
+ var cdn = new UniCdnManager();
260
+
261
+ // CDN 文件保存路径
262
+ var SAVE_CDN_FILE_PATH = path.join(process.cwd(), "node_modules/@dd-code/uni-files");
263
+ path.join(process.cwd(), "node_modules/@dd-code/current-files");
264
+ // Manifest 文件名
265
+ var MANIFEST_NAME = "mfe-uni-manifest.json";
266
+ var ROOT_APP_CODE = "main"; //"__MFE_APP_ROOT__";
267
+ // Manifest CDN 目录 URL 模板
268
+ var MANIFEST_CND_DIR_URL = "{mode}/static-repository/mfe-uni/{code}/{appCode}";
269
+ var getManifestCdnDirUrl = function (_a) {
270
+ var mode = _a.mode, code = _a.code, appCode = _a.appCode;
271
+ return MANIFEST_CND_DIR_URL.replace("{mode}", mode)
272
+ .replace("{code}", code)
273
+ .replace("{appCode}", appCode);
274
+ };
275
+ /**
276
+ * 获取微前端配置 JSON
277
+ * @description 读取并解析 mfe.json 配置文件,同时从环境变量中获取相关配置
278
+ * @returns {Object} 包含微前端配置的对象
279
+ * @returns {boolean} returns.isRoot - 是否为根应用
280
+ * @returns {string} returns.code - 项目代码
281
+ * @returns {string} returns.appCode - 应用代码
282
+ * @example
283
+ * // 返回: { isRoot: true, code: 'myapp', appCode: 'main', ... }
284
+ */
285
+ var getMfeJson = function () {
286
+ // 读取 mfe.json 配置文件
287
+ var jsonPath = path.resolve(process.cwd(), MFE_NAME);
288
+ var json = uniReadFile(jsonPath) || {};
289
+ // const root = process.cwd();
290
+ // const { loadEnv } = require("vite");
291
+ // const viteEnv = loadEnv(mode || "dev", root, "");
292
+ // const envObj = {
293
+ // ...viteEnv,
294
+ // platform: process.env.UNI_PLATFORM || "h5",
295
+ // };
296
+ // console.log("-----", process.env, mode, "viteEnv");
297
+ // // 从环境变量中获取配置
298
+ // json.isRoot = envObj.UNI_IS_ROOT;
299
+ // json.code = envObj.UNI_CODE;
300
+ // json.appCode = envObj.MFE_APP_CODE;
301
+ json.platform = process.env.UNI_PLATFORM || "h5";
302
+ // json.mode = envObj.MODE || "dev";
303
+ return json;
304
+ };
305
+ var getMainAppJson = function (mode) { return __awaiter(void 0, void 0, void 0, function () {
306
+ var env, baseUrl, mainJson;
307
+ return __generator(this, function (_a) {
308
+ switch (_a.label) {
309
+ case 0:
310
+ env = formatCliCommandConfig(mode);
311
+ baseUrl = cdn.getManifestUrl({
312
+ code: env.code,
313
+ appCode: ROOT_APP_CODE,
314
+ mode: mode,
315
+ });
316
+ return [4 /*yield*/, fetchFileByPath(baseUrl)];
317
+ case 1:
318
+ mainJson = _a.sent();
319
+ return [2 /*return*/, mainJson];
320
+ }
321
+ });
322
+ }); };
323
+ var getMainAppPages = function (mode) { return __awaiter(void 0, void 0, void 0, function () {
324
+ var mainJson;
325
+ return __generator(this, function (_a) {
326
+ switch (_a.label) {
327
+ case 0: return [4 /*yield*/, getMainAppJson(mode)];
328
+ case 1:
329
+ mainJson = _a.sent();
330
+ return [2 /*return*/, (mainJson.apps || [
331
+ {
332
+ appCode: "modules/bwzb",
333
+ },
334
+ {
335
+ appCode: "modules/manage",
336
+ },
337
+ {
338
+ appCode: "login",
339
+ },
340
+ ])];
341
+ }
342
+ });
343
+ }); };
344
+ var getPlatform = function () {
345
+ return process.env.UNI_PLATFORM || "h5";
346
+ };
347
+ var formatCliCommandConfig = function (mode) {
348
+ var viteEnv = loadViteConfig(mode || "dev");
349
+ var isRoot = viteEnv.MFE_UNI_IS_ROOT;
350
+ // MFE_CDN_HOST
351
+ return {
352
+ isRoot: isRoot,
353
+ appCode: isRoot ? ROOT_APP_CODE : viteEnv.MFE_APP_CODE,
354
+ code: viteEnv.MFE_UNI_CODE,
355
+ mode: mode,
356
+ cdn: viteEnv.MFE_CDN_HOST,
357
+ };
358
+ };
359
+ var checkIsRootManifest = function (manifest) {
360
+ return manifest.isRoot || manifest.appCode === ROOT_APP_CODE;
361
+ };
362
+ var WS_PORT = 3560;
363
+ var WS_PATH = "/__mfe__ws__";
364
+ var E_WS_TYPE;
365
+ (function (E_WS_TYPE) {
366
+ E_WS_TYPE["INIT"] = "init_files";
367
+ E_WS_TYPE["CHANGE"] = "change_files";
368
+ })(E_WS_TYPE || (E_WS_TYPE = {}));
369
+ var getMainAppJSon = function (mode, appCode) {
370
+ return path.join(SAVE_CDN_FILE_PATH, mode || "dev", appCode, "app.json");
371
+ };
372
+ var getMainAppJsonPath = function () {
373
+ return path.join(process.env.UNI_OUTPUT_DIR, "app.json");
374
+ };
375
+
376
+ var EPlaform;
377
+ (function (EPlaform) {
378
+ EPlaform["H5"] = "h5";
379
+ EPlaform["MP_WEIXIN"] = "mp-weixin";
380
+ })(EPlaform || (EPlaform = {}));
381
+
382
+ var CliProgressManager = /** @class */ (function () {
383
+ function CliProgressManager() {
384
+ this.barMap = new Map();
385
+ }
386
+ CliProgressManager.prototype.initMultiBar = function (fotmat) {
387
+ this.multiBar = new cliProgress.MultiBar({
388
+ clearOnComplete: false, // 完成后不清空
389
+ hideCursor: true, // 隐藏终端光标
390
+ format: fotmat ||
391
+ "".concat(chalk.yellow("{name}"), ": ").concat(chalk.blue("{bar}"), " | ").concat(chalk.green("{percentage}%"), " | {value}/{total}"),
392
+ barCompleteChar: "\u2588", // 已完成部分(实心方块)
393
+ barIncompleteChar: "\u2591", // 未完成部分(空心方块)
394
+ barGlue: "",
395
+ stopOnComplete: true,
396
+ }, cliProgress.Presets.shades_grey);
397
+ };
398
+ CliProgressManager.prototype.createProgressBar = function (tasks) {
399
+ var _this = this;
400
+ tasks.forEach(function (task) {
401
+ var taskBar = _this.multiBar.create(task.total, 0, {
402
+ name: task.name,
403
+ });
404
+ _this.barMap.set(task.name, taskBar);
405
+ });
406
+ };
407
+ CliProgressManager.prototype.updateProgressBar = function (name, value) {
408
+ var taskBar = this.barMap.get(name);
409
+ if (taskBar) {
410
+ var total = taskBar.getTotal();
411
+ taskBar.update(value);
412
+ if (value >= total) {
413
+ taskBar.stop();
414
+ }
415
+ }
416
+ };
417
+ CliProgressManager.prototype.stopAll = function () {
418
+ this.multiBar.stop();
419
+ };
420
+ return CliProgressManager;
421
+ }());
422
+ var CliProgressManager$1 = new CliProgressManager();
423
+
424
+ var getDownloadedFilePath = function (conf) {
425
+ return path.resolve(SAVE_CDN_FILE_PATH, conf.env, conf.appCode);
426
+ };
427
+ var getNodeModulesEnvAppCodeFilePath = function (conf, fileName) {
428
+ return path.resolve(getDownloadedFilePath(conf), fileName);
429
+ };
430
+ /**
431
+ * 获取清单文件 URL 列表
432
+ * @description 根据环境和配置生成所有应用的清单文件 URL
433
+ * @param {string} mode - 环境标识,默认为 'dev'
434
+ * @returns {Array<Object>} 清单 URL 对象数组
435
+ * @returns {string} returns[].url - 清单文件 URL
436
+ * @returns {string} returns[].appCode - 应用代码
437
+ * @returns {string} returns[].code - 项目代码
438
+ * @example
439
+ * const urls = getManifestJsonUrl('prod');
440
+ * // 返回: [{ url: '...', appCode: 'main', code: 'my-project' }]
441
+ */
442
+ var getManifestJsonUrl = function (mode) { return __awaiter(void 0, void 0, void 0, function () {
443
+ var _a, _b, isRoot, _c, code, apps, mfeJson, configApps, result;
444
+ return __generator(this, function (_d) {
445
+ switch (_d.label) {
446
+ case 0:
447
+ _a = formatCliCommandConfig(mode), _b = _a.isRoot, isRoot = _b === void 0 ? false : _b, _c = _a.code, code = _c === void 0 ? "mfe-uni" : _c;
448
+ apps = [];
449
+ mfeJson = getMfeJson();
450
+ _d.label = 1;
451
+ case 1:
452
+ _d.trys.push([1, 5, , 6]);
453
+ configApps = [];
454
+ if (!isRoot) return [3 /*break*/, 2];
455
+ configApps = mfeJson.apps || [];
456
+ return [3 /*break*/, 4];
457
+ case 2: return [4 /*yield*/, getMainAppPages(mode)];
458
+ case 3:
459
+ configApps = _d.sent();
460
+ configApps = __spreadArray(__spreadArray([], configApps, true), [{ appCode: ROOT_APP_CODE }], false);
461
+ _d.label = 4;
462
+ case 4:
463
+ // console.log(JSON, isRoot, "JSON");
464
+ // debugger
465
+ // const configApps = JSON.apps; // isRoot ? JSON.apps : [{ appCode: ROOT_APP_CODE }];
466
+ apps = Array.from(new Set(__spreadArray([], (configApps || []).map(function (i) { return i.appCode; }), true)));
467
+ return [3 /*break*/, 6];
468
+ case 5:
469
+ _d.sent();
470
+ apps = []; // BASE_APP_CODE_LIST;
471
+ return [3 /*break*/, 6];
472
+ case 6:
473
+ result = apps.map(function (appCode) {
474
+ return {
475
+ url: cdn.getManifestUrl({
476
+ code: code,
477
+ appCode: appCode,
478
+ mode: mode,
479
+ }),
480
+ appCode: appCode,
481
+ code: code,
482
+ };
483
+ });
484
+ return [2 /*return*/, result];
485
+ }
486
+ });
487
+ }); };
488
+ var downloadManifestJson = function (urls) { return __awaiter(void 0, void 0, void 0, function () {
489
+ var downloadList, downloadRes, manifestList;
490
+ return __generator(this, function (_a) {
491
+ switch (_a.label) {
492
+ case 0:
493
+ downloadList = urls.map(function (url) { return __awaiter(void 0, void 0, void 0, function () {
494
+ var jsonData;
495
+ return __generator(this, function (_a) {
496
+ switch (_a.label) {
497
+ case 0: return [4 /*yield*/, fetchFileByPath(url).catch(function (e) { })];
498
+ case 1:
499
+ jsonData = _a.sent();
500
+ return [2 /*return*/, jsonData];
501
+ }
502
+ });
503
+ }); });
504
+ return [4 /*yield*/, Promise.all(downloadList)];
505
+ case 1:
506
+ downloadRes = _a.sent();
507
+ manifestList = downloadRes.filter(function (i) { return i; });
508
+ return [2 /*return*/, manifestList];
509
+ }
510
+ });
511
+ }); };
512
+ /**
513
+ * 下载项目文件
514
+ * @description 根据清单列表并行下载所有项目文件到指定目录
515
+ * @param {Array<Object>} manifestList - 清单数据数组
516
+ * @param {string} manifestList[].env - 环境标识
517
+ * @returns {Promise<void>} 下载完成
518
+ * @example
519
+ * await downloadProjectFiles([
520
+ * { env: 'prod', files: [...] },
521
+ * { env: 'test', files: [...] }
522
+ * ]);
523
+ */
524
+ /**
525
+ * 根据manifest文件下载所有相关文件
526
+ * 用于微前端架构中的模块文件下载
527
+ * @param {Object} manifestJson - manifest文件内容
528
+ * @param {string} outDir - 输出目录
529
+ */
530
+ function downloadFilesByManifestJson(manifestJson, outDir, onDownload) {
531
+ return __awaiter(this, void 0, void 0, function () {
532
+ var cdn, appCode, publicPath, files, _a, _b, _c, _i, i, file, fileUrl, fileName, downloadUrl, content;
533
+ return __generator(this, function (_d) {
534
+ switch (_d.label) {
535
+ case 0:
536
+ cdn = manifestJson.cdn, appCode = manifestJson.appCode, publicPath = manifestJson.publicPath, files = manifestJson.files;
537
+ _a = files;
538
+ _b = [];
539
+ for (_c in _a)
540
+ _b.push(_c);
541
+ _i = 0;
542
+ _d.label = 1;
543
+ case 1:
544
+ if (!(_i < _b.length)) return [3 /*break*/, 4];
545
+ _c = _b[_i];
546
+ if (!(_c in _a)) return [3 /*break*/, 3];
547
+ i = _c;
548
+ file = files[i];
549
+ fileUrl = file.fileUrl, fileName = file.fileName;
550
+ downloadUrl = "".concat(cdn, "/").concat(publicPath, "/").concat(fileUrl);
551
+ return [4 /*yield*/, fetchFileByPath(downloadUrl)];
552
+ case 2:
553
+ content = _d.sent();
554
+ // console.log(path.join(outDir, appCode || "", fileName), 'path.join(outDir, appCode || "", fileName)');
555
+ writeFiles(path.join(outDir, appCode || "", fileName), content);
556
+ onDownload && onDownload(Number(i), file.length);
557
+ _d.label = 3;
558
+ case 3:
559
+ _i++;
560
+ return [3 /*break*/, 1];
561
+ case 4: return [2 /*return*/];
562
+ }
563
+ });
564
+ });
565
+ }
566
+ var downloadProjectFiles = function (manifestList) { return __awaiter(void 0, void 0, void 0, function () {
567
+ var downloadList, _loop_1, i;
568
+ return __generator(this, function (_a) {
569
+ switch (_a.label) {
570
+ case 0:
571
+ downloadList = [];
572
+ CliProgressManager$1.initMultiBar();
573
+ CliProgressManager$1.createProgressBar(manifestList.map(function (i) { return ({
574
+ name: i.appCode,
575
+ total: i.files.length,
576
+ }); }));
577
+ _loop_1 = function (i) {
578
+ var manifestJson = manifestList[i];
579
+ var fn = downloadFilesByManifestJson(manifestJson, path.resolve(SAVE_CDN_FILE_PATH, manifestJson.mode || "dev"), function (index, total) {
580
+ CliProgressManager$1.updateProgressBar(manifestJson.appCode, index + 1);
581
+ });
582
+ downloadList.push(fn);
583
+ };
584
+ for (i in manifestList) {
585
+ _loop_1(i);
586
+ }
587
+ return [4 /*yield*/, Promise.all(downloadList)];
588
+ case 1:
589
+ _a.sent();
590
+ CliProgressManager$1.stopAll();
591
+ return [2 /*return*/];
592
+ }
593
+ });
594
+ }); };
595
+
596
+ var checkDownloadFilesIsExpired = function (manifestList) {
597
+ return manifestList.filter(function (conf) {
598
+ var targetPath = getNodeModulesEnvAppCodeFilePath(conf, MANIFEST_NAME);
599
+ var oldJson = uniReadFile(targetPath);
600
+ var flag = !oldJson || (oldJson === null || oldJson === void 0 ? void 0 : oldJson.hash) !== conf.hash;
601
+ return flag;
602
+ });
603
+ };
604
+ var createManifestManager = function () {
605
+ var envObj = process.env;
606
+ var row = {
607
+ code: "",
608
+ mode: "",
609
+ cdn: '',
610
+ hash: "",
611
+ publicPath: "",
612
+ appCode: "",
613
+ platform: envObj.UNI_PLATFORM || "h5",
614
+ pagesJson: {},
615
+ files: [],
616
+ };
617
+ return {
618
+ get value() {
619
+ return row;
620
+ },
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
+ });
631
+ row.files = files;
632
+ },
633
+ setPagesJson: function (pagesJson) {
634
+ row.pagesJson = pagesJson;
635
+ },
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));
641
+ },
642
+ setEnv: function (mode) {
643
+ // const env = loadViteConfig(mode);
644
+ var env = formatCliCommandConfig(mode);
645
+ var mfeJson = getMfeJson();
646
+ row.cdn = env.cdn;
647
+ row.mode = mode;
648
+ row.code = env.code;
649
+ row.appCode = env.appCode;
650
+ cdn.setCdnHost(env.cdn);
651
+ if (env.isRoot) {
652
+ row.isRoot = true;
653
+ row.apps = mfeJson.apps;
654
+ }
655
+ row.publicPath = getManifestCdnDirUrl(row);
656
+ },
657
+ dependencies: [],
658
+ setDependencies: function (list) {
659
+ this.dependencies = list;
660
+ },
661
+ // getFullManifestJsonList() {
662
+ // const files = import.meta.globEager("./**/*.json");
663
+ // console.log(files);
664
+ // // return [...this.dependencies, this.value];
665
+ // },
666
+ };
667
+ };
668
+
669
+ var resetOutDir = function (currentManifestJson, config) {
670
+ 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
+ };
677
+
678
+ var copyFilesByTargetPath = function (sourcePath, targetPath) {
679
+ if (!fs.existsSync(sourcePath))
680
+ return;
681
+ try {
682
+ var targetDir = path.dirname(targetPath);
683
+ fsExtra.ensureDirSync(targetDir);
684
+ }
685
+ catch (err) { }
686
+ fsExtra.copySync(sourcePath, targetPath, { overwrite: true });
687
+ };
688
+
689
+ var downloadFullApps = function (manifestJson) { return __awaiter(void 0, void 0, void 0, function () {
690
+ var _appsUrls, appsUrls, manifestList, expiredList;
691
+ return __generator(this, function (_a) {
692
+ switch (_a.label) {
693
+ case 0: return [4 /*yield*/, getManifestJsonUrl(manifestJson.mode)];
694
+ case 1:
695
+ _appsUrls = _a.sent();
696
+ appsUrls = _appsUrls.filter(function (i) { return i.appCode !== manifestJson.appCode; });
697
+ return [4 /*yield*/, downloadManifestJson(appsUrls.map(function (i) { return i.url; }))];
698
+ case 2:
699
+ manifestList = _a.sent();
700
+ expiredList = checkDownloadFilesIsExpired(manifestList);
701
+ if (!expiredList.length) return [3 /*break*/, 4];
702
+ return [4 /*yield*/, downloadProjectFiles(expiredList)];
703
+ case 3:
704
+ _a.sent();
705
+ _a.label = 4;
706
+ case 4: return [2 /*return*/, manifestList];
707
+ }
708
+ });
709
+ }); };
710
+ var moveOtherApps = function (_a) {
711
+ var base = _a.base, manifestList = _a.manifestList;
712
+ var source = process.env.MFE_ROOT_OUTPUT_DIR;
713
+ manifestList.forEach(function (manifestJson) {
714
+ var appCode = manifestJson.appCode;
715
+ var targetPath = checkIsRootManifest(manifestJson) ? source : path.resolve(source, appCode);
716
+ var sourcePath = path.resolve(base, appCode);
717
+ try {
718
+ copyFilesByTargetPath(sourcePath, targetPath);
719
+ }
720
+ catch (error) { }
721
+ });
722
+ };
723
+
724
+ var createAppsAssetsPlugin = function (manifestJson) {
725
+ var manifestList = [];
726
+ var isMoved = false;
727
+ return {
728
+ name: "@dd-code:apps-assets",
729
+ enforce: "pre",
730
+ options: function () {
731
+ return __awaiter(this, void 0, void 0, function () {
732
+ return __generator(this, function (_a) {
733
+ switch (_a.label) {
734
+ case 0: return [4 /*yield*/, downloadFullApps(manifestJson.value)];
735
+ case 1:
736
+ manifestList = _a.sent();
737
+ manifestJson.setDependencies(manifestList);
738
+ return [2 /*return*/];
739
+ }
740
+ });
741
+ });
742
+ },
743
+ buildStart: function () {
744
+ if (isMoved)
745
+ return;
746
+ var basePath = path.resolve(SAVE_CDN_FILE_PATH, manifestJson.value.mode || "dev");
747
+ moveOtherApps({
748
+ base: basePath,
749
+ manifestList: manifestList,
750
+ });
751
+ isMoved = true;
752
+ },
753
+ };
754
+ };
755
+
756
+ // @ts-ignore
757
+ var initPreContext = require("@dcloudio/uni-cli-shared/dist/preprocess").initPreContext;
758
+ var preprocess = require("@dcloudio/uni-cli-shared/lib/preprocess").preprocess;
759
+ var getPreVueContext = require("@dcloudio/uni-cli-shared/dist/preprocess/context").getPreVueContext;
760
+ var initPrePagesJson = function () {
761
+ var pagesPath = path.resolve(process.cwd(), "src/pages.json");
762
+ return fs.readFileSync(pagesPath, "utf-8");
763
+ };
764
+ var getPagesJson = function (jsonFile, isFormat) {
765
+ if (isFormat === void 0) { isFormat = false; }
766
+ var platform = process.env.UNI_PLATFORM;
767
+ initPreContext(platform);
768
+ var context = getPreVueContext();
769
+ // 使用uni的预处理器处理pages.json
770
+ var processedJsonStr = preprocess(jsonFile, context, { type: "js" });
771
+ // 解析为JSON对象
772
+ var pagesConfig = eval("(".concat(processedJsonStr, ")"));
773
+ // 针对微信小程序平台,处理特有的配置项
774
+ if (isFormat && platform === "mp-weixin") {
775
+ return transformToWeixinFormat(pagesConfig);
776
+ }
777
+ return pagesConfig;
778
+ };
779
+ // 将uni-app的pages.json转换为微信小程序格式
780
+ var transformToWeixinFormat = function (uniPagesConfig) {
781
+ var _a;
782
+ var weixinConfig = __assign({ pages: [], window: {}, tabBar: null, subPackages: [], usingComponents: {} }, uniPagesConfig);
783
+ // 处理globalStyle -> window
784
+ if (uniPagesConfig.globalStyle) {
785
+ var globalStyle = uniPagesConfig.globalStyle;
786
+ // 基础窗口配置
787
+ weixinConfig.window = {
788
+ navigationBarBackgroundColor: globalStyle.navigationBarBackgroundColor || "#000000",
789
+ navigationBarTextStyle: globalStyle.navigationBarTextStyle || "white",
790
+ navigationBarTitleText: globalStyle.navigationBarTitleText || "",
791
+ backgroundColor: globalStyle.backgroundColor || "#ffffff",
792
+ backgroundTextStyle: globalStyle.backgroundTextStyle || "dark",
793
+ enablePullDownRefresh: globalStyle.enablePullDownRefresh || false,
794
+ onReachBottomDistance: globalStyle.onReachBottomDistance || 50,
795
+ };
796
+ // 处理微信小程序特有配置
797
+ if (globalStyle.pageOrientation) {
798
+ weixinConfig.window.pageOrientation = globalStyle.pageOrientation;
799
+ }
800
+ if (globalStyle.renderingMode) {
801
+ weixinConfig.window.renderingMode = globalStyle.renderingMode;
802
+ }
803
+ // 处理usingComponents
804
+ if (globalStyle.usingComponents) {
805
+ weixinConfig.usingComponents = globalStyle.usingComponents;
806
+ }
807
+ // 处理微信小程序平台特定配置
808
+ if (globalStyle["mp-weixin"]) {
809
+ Object.assign(weixinConfig.window, globalStyle["mp-weixin"]);
810
+ }
811
+ }
812
+ // 处理pages配置
813
+ if (uniPagesConfig.pages) {
814
+ weixinConfig.pages = uniPagesConfig.pages.map(function (page) {
815
+ var weixinPage = page.path;
816
+ return weixinPage;
817
+ });
818
+ }
819
+ // 处理tabBar配置
820
+ if (uniPagesConfig.tabBar) {
821
+ weixinConfig.tabBar = __assign(__assign({}, uniPagesConfig.tabBar), { list: (_a = uniPagesConfig.tabBar.list) === null || _a === void 0 ? void 0 : _a.map(function (item) { return ({
822
+ pagePath: item.pagePath,
823
+ text: item.text,
824
+ iconPath: item.iconPath,
825
+ selectedIconPath: item.selectedIconPath,
826
+ }); }) });
827
+ }
828
+ // 处理分包配置
829
+ if (uniPagesConfig.subPackages) {
830
+ weixinConfig.subPackages = uniPagesConfig.subPackages.map(function (subPackage) {
831
+ var _a;
832
+ return ({
833
+ root: subPackage.root,
834
+ pages: ((_a = subPackage.pages) === null || _a === void 0 ? void 0 : _a.map(function (page) { return page.path || page; })) || [],
835
+ });
836
+ });
837
+ }
838
+ // 处理预下载规则
839
+ if (uniPagesConfig.preloadRule) {
840
+ weixinConfig.preloadRule = uniPagesConfig.preloadRule;
841
+ }
842
+ // 移除uni-app特有的配置项
843
+ delete weixinConfig.globalStyle;
844
+ delete weixinConfig.easycom;
845
+ delete weixinConfig.condition;
846
+ delete weixinConfig.leftWindow;
847
+ delete weixinConfig.topWindow;
848
+ delete weixinConfig.rightWindow;
849
+ delete weixinConfig.uniIdRouter;
850
+ delete weixinConfig.entryPagePath;
851
+ return weixinConfig;
852
+ };
853
+
854
+ var createManifestPlugin = function (manifestJson) {
855
+ var emitted = new Set();
856
+ return {
857
+ name: "@dd-code:genre-mainfest-file-list",
858
+ enforce: "post",
859
+ renderStart: function () {
860
+ var content = initPrePagesJson();
861
+ var json = getPagesJson(content);
862
+ manifestJson.setPagesJson(json);
863
+ },
864
+ writeBundle: function (_outputOptions, bundle) {
865
+ Object.values(bundle).forEach(function (item) {
866
+ if (item && item.fileName)
867
+ emitted.add(item.fileName);
868
+ });
869
+ },
870
+ closeBundle: function () {
871
+ var outDir = process.env.MFE_SOURCE_OUTPUT_DIR || "dist";
872
+ var all = walkDir(outDir, emitted);
873
+ manifestJson.setFiles(outDir, all);
874
+ var sourcePath = manifestJson.value.isRoot
875
+ ? process.env.MFE_ROOT_OUTPUT_DIR
876
+ : 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);
881
+ },
882
+ };
883
+ };
884
+
885
+ var createHttpServer = function () {
886
+ var app = express();
887
+ var server = http.createServer(app);
888
+ app.use(cors({ origin: "*" }));
889
+ return server;
890
+ };
891
+
892
+ var WsServer = /** @class */ (function () {
893
+ function WsServer(handleMessage) {
894
+ this.handleMessage = handleMessage;
895
+ this.httpServer = createHttpServer();
896
+ this.clientMap = new Map();
897
+ }
898
+ WsServer.prototype.createServer = function () {
899
+ this.wss = new WebSocket.WebSocketServer({
900
+ server: this.httpServer, // 绑定到 Vite 的 HTTP 服务器
901
+ path: WS_PATH, // WS 连接路径,前端连接时用 ws://localhost:5173/__mfe__ws__
902
+ });
903
+ this.onMessage(this.handleMessage);
904
+ this.onConnection();
905
+ this.start();
906
+ };
907
+ WsServer.prototype.start = function () {
908
+ this.httpServer.listen(WS_PORT, function () {
909
+ console.log("[uni-WS] \u72EC\u7ACB\u670D\u52A1\u5DF2\u542F\u52A8\uFF1Aws://localhost:".concat(WS_PORT).concat(WS_PATH));
910
+ });
911
+ };
912
+ WsServer.prototype.onMessage = function (callback) {
913
+ // WebSocketServer 不支持直接监听 message,必须在 connection 后的 socket 上监听
914
+ // 这里仅更新回调引用
915
+ if (callback) {
916
+ this.handleMessage = callback;
917
+ }
918
+ };
919
+ WsServer.prototype.sendMessageToApp = function (appCode, message) {
920
+ var ws = this.clientMap.get(appCode);
921
+ if (ws) {
922
+ ws.send(typeof message === "string" ? message : JSON.stringify(message));
923
+ }
924
+ };
925
+ WsServer.prototype.onConnection = function () {
926
+ var _this = this;
927
+ this.wss.on("connection", function (ws, request) {
928
+ // console.log("客户端已连接 WS 服务");
929
+ ws.on("message", function (message) {
930
+ var _a;
931
+ try {
932
+ var data = JSON.parse(message.toString());
933
+ (_a = _this.handleMessage) === null || _a === void 0 ? void 0 : _a.call(_this, data);
934
+ }
935
+ catch (e) {
936
+ console.error("WS消息解析失败:", e);
937
+ }
938
+ });
939
+ // 拿到客户端传递的 appCode
940
+ var url = new URL(request.url, "http://".concat(request.headers.host));
941
+ var appCode = url.searchParams.get("appCode");
942
+ if (!appCode)
943
+ return;
944
+ _this.clientMap.set(appCode, ws);
945
+ _this.sendMessageToApp(appCode, {
946
+ type: E_WS_TYPE.INIT,
947
+ data: {
948
+ pwd: process.env.UNI_OUTPUT_DIR,
949
+ },
950
+ });
951
+ });
952
+ };
953
+ return WsServer;
954
+ }());
955
+ var WsClientServer = /** @class */ (function () {
956
+ function WsClientServer(handleMessage) {
957
+ this.handleMessage = handleMessage;
958
+ this.handleMessage = handleMessage;
959
+ this.ws = null;
960
+ this.isConnected = false;
961
+ }
962
+ WsClientServer.prototype.connect = function (appCode) {
963
+ var _this = this;
964
+ this.ws = new WebSocket("ws://localhost:".concat(WS_PORT).concat(WS_PATH, "?appCode=").concat(appCode));
965
+ this.ws.on("open", function () {
966
+ // console.log("客户端已连接 WS 服务");
967
+ _this.isConnected = true;
968
+ });
969
+ this.ws.on("close", function () {
970
+ // console.log("客户端已关闭 WS 服务");
971
+ _this.isConnected = false;
972
+ _this.retryConnect(appCode);
973
+ });
974
+ // 重试连接
975
+ this.ws.on("error", function () {
976
+ // console.log("连接失败,重试连接...");
977
+ _this.isConnected = false;
978
+ _this.retryConnect(appCode);
979
+ });
980
+ this.onMessage(this.handleMessage);
981
+ };
982
+ WsClientServer.prototype.sendMessage = function (type, data) {
983
+ if (this.isConnected) {
984
+ this.ws.send(JSON.stringify({ type: type, data: data }));
985
+ }
986
+ };
987
+ // handleMessage = (message: any) => {
988
+ // const { type, data } = message;
989
+ // if (type === E_WS_TYPE.INIT) {
990
+ // // console.log("收到初始化消息", data);
991
+ // this.serverPlugin.copyAppDistModule(data);
992
+ // }
993
+ // // console.log("收到消息", message);
994
+ // };
995
+ WsClientServer.prototype.onMessage = function (callback) {
996
+ this.ws.on("message", function (message) {
997
+ callback === null || callback === void 0 ? void 0 : callback(JSON.parse(message.toString()));
998
+ });
999
+ };
1000
+ WsClientServer.prototype.retryConnect = function (appCode) {
1001
+ var _this = this;
1002
+ if (this.isConnected)
1003
+ return;
1004
+ this.isConnected = true;
1005
+ setTimeout(function () {
1006
+ _this.connect(appCode);
1007
+ }, 3000);
1008
+ };
1009
+ return WsClientServer;
1010
+ }());
1011
+ // export const createWsServer = (server: ViteDevServer) => {
1012
+ // const wss = new WebSocketServer({
1013
+ // server: server.httpServer, // 绑定到 Vite 的 HTTP 服务器
1014
+ // path: "/__mfe__ws__", // WS 连接路径,前端连接时用 ws://localhost:5173/__mfe__ws__
1015
+ // });
1016
+ // wss.on("connection", (ws: WebSocket) => {
1017
+ // console.log("客户端已连接 WS 服务");
1018
+ // });
1019
+ // };
1020
+ // export const con
1021
+ // export const mfeServer = new WsServer();
1022
+ // export const mfeClientServer = new WsClientServer();
1023
+
1024
+ /**
1025
+ * 过滤 Manifest 列表并获取主应用 app.json 路径
1026
+ */
1027
+ var filterManifestJsonListAndMainPageJson = function (manifestJsonList) {
1028
+ var outputPageJsonPath = getMainAppJsonPath();
1029
+ return {
1030
+ outputPageJsonPath: outputPageJsonPath,
1031
+ manifestList: manifestJsonList.filter(function (item) { return !checkIsRootManifest(item); }),
1032
+ };
1033
+ };
1034
+ /**
1035
+ * 根据 Manifest 列表渲染 app.json 的 subPackages
1036
+ */
1037
+ var renderPagesJsonByArray = function (appPages, pageJson) {
1038
+ var _loop_1 = function (app) {
1039
+ var _a = getPagesJson(JSON.stringify((app === null || app === void 0 ? void 0 : app.pagesJson) || {}), true).pages, pages = _a === void 0 ? [] : _a;
1040
+ var currentTemp = {
1041
+ root: app.appCode,
1042
+ pages: __spreadArray([], pages, true),
1043
+ };
1044
+ // 移除旧的 subPackage 配置并添加新的
1045
+ pageJson.subPackages = pageJson.subPackages.filter(function (i) { return i.root !== currentTemp.root; });
1046
+ pageJson.subPackages.push(currentTemp);
1047
+ pageJson.subPackages = pageJson.subPackages.filter(function (i) { return i.pages.length; });
1048
+ };
1049
+ for (var _i = 0, appPages_1 = appPages; _i < appPages_1.length; _i++) {
1050
+ var app = appPages_1[_i];
1051
+ _loop_1(app);
1052
+ }
1053
+ if (!pageJson.tabBar) {
1054
+ delete pageJson.tabBar;
1055
+ }
1056
+ return pageJson;
1057
+ };
1058
+ /**
1059
+ * 生成完整的主应用 app.json
1060
+ */
1061
+ var genreFullMainAppJsonByManifestList = function (appJson, manifestList) {
1062
+ return renderPagesJsonByArray(manifestList, appJson);
1063
+ };
1064
+ /**
1065
+ * 监听 dist 目录变化并同步文件
1066
+ */
1067
+ var watchDistChangeAndSyncFile = function (mainPwd, onReady, onChange) {
1068
+ var root = process.env.MFE_SOURCE_OUTPUT_DIR;
1069
+ if (!root) {
1070
+ console.error("[Watcher] MFE_SOURCE_OUTPUT_DIR not set");
1071
+ return;
1072
+ }
1073
+ var filePath = path.resolve(root);
1074
+ // 确保目录存在,避免监听失效
1075
+ checkAndgenreDir(filePath);
1076
+ // 监听父级目录,过滤出目标目录下的变化,解决目录重建导致监听失效的问题
1077
+ var parentDir = path.dirname(filePath);
1078
+ var watcher = chokidar.watch(parentDir, {
1079
+ persistent: true,
1080
+ ignoreInitial: true,
1081
+ usePolling: true,
1082
+ interval: 100,
1083
+ awaitWriteFinish: { stabilityThreshold: 200, pollInterval: 100 },
1084
+ followSymlinks: true,
1085
+ depth: 99
1086
+ });
1087
+ var isTargetFile = function (p) {
1088
+ return p.startsWith(filePath + path.sep) || p === filePath;
1089
+ };
1090
+ watcher.on("ready", onReady);
1091
+ ["add", "change", "unlink"].forEach(function (evt) {
1092
+ // @ts-ignore
1093
+ watcher.on(evt, function (p) {
1094
+ if (!isTargetFile(p))
1095
+ return;
1096
+ var rel = path.relative(filePath, p);
1097
+ var sourcePath = p;
1098
+ var targetPath = path.join(mainPwd, rel);
1099
+ // 仅文件内容变化才执行复制操作,目录变化由构建工具处理
1100
+ if (["add", "change"].includes(evt)) {
1101
+ copyFilesByTargetPath(sourcePath, targetPath);
1102
+ }
1103
+ onChange === null || onChange === void 0 ? void 0 : onChange({ type: evt, p: p, sourcePath: sourcePath, targetPath: targetPath });
1104
+ });
1105
+ });
1106
+ watcher.on('error', function (err) { return console.error('[Watcher] error:', err); });
1107
+ };
1108
+ /**
1109
+ * 生成新的 app.json 文件
1110
+ */
1111
+ var genreNewAppJson = function (outputPageJsonPath, mainAppJsonPath, manifestList) {
1112
+ try {
1113
+ var appJson = uniReadFile(mainAppJsonPath);
1114
+ var newAppJSon = genreFullMainAppJsonByManifestList(__assign({ subPackages: [] }, appJson), manifestList);
1115
+ writeFiles(outputPageJsonPath, newAppJSon);
1116
+ }
1117
+ catch (error) {
1118
+ console.error("[AppJSON] Genre failed:", error);
1119
+ }
1120
+ };
1121
+ /**
1122
+ * 处理主应用服务端逻辑
1123
+ */
1124
+ var createMainAppServer = function (manifestJson) {
1125
+ var mfeServer = new WsServer(function (opt) {
1126
+ var type = opt.type, data = opt.data;
1127
+ if (type === E_WS_TYPE.CHANGE) {
1128
+ var outputPageJsonPath = getMainAppJsonPath();
1129
+ var manifestPath = path.join(process.env.UNI_OUTPUT_DIR, data.appCode, MANIFEST_NAME);
1130
+ try {
1131
+ var manifestChildJson = uniReadFile(manifestPath);
1132
+ genreNewAppJson(outputPageJsonPath, outputPageJsonPath, [
1133
+ manifestChildJson,
1134
+ ]);
1135
+ }
1136
+ catch (e) {
1137
+ console.error("[Server] Handle child change failed:", e);
1138
+ }
1139
+ }
1140
+ });
1141
+ mfeServer.createServer();
1142
+ return mfeServer;
1143
+ };
1144
+ /**
1145
+ * 处理子应用客户端逻辑
1146
+ */
1147
+ var createMainAppClient = function (manifestJson, onInit) {
1148
+ var client = new WsClientServer(function (opt) {
1149
+ if (opt.type === E_WS_TYPE.INIT) {
1150
+ onInit(opt.data);
1151
+ }
1152
+ });
1153
+ client.connect(manifestJson.value.appCode);
1154
+ return client;
1155
+ };
1156
+ /**
1157
+ * 创建主应用插件
1158
+ */
1159
+ var createMainAppPlugin = function (manifestJson) {
1160
+ var mainPwd = "";
1161
+ var isWatcherReady = false;
1162
+ var mfeClientServer;
1163
+ var fn = null;
1164
+ var serverPlugin = {
1165
+ name: "@dd-code:main-app:serve",
1166
+ config: function () {
1167
+ return __awaiter(this, void 0, void 0, function () {
1168
+ return __generator(this, function (_a) {
1169
+ if (manifestJson.value.isRoot) {
1170
+ createMainAppServer();
1171
+ }
1172
+ else {
1173
+ mfeClientServer = createMainAppClient(manifestJson, function (data) {
1174
+ serverPlugin.copyAppDistModule(data);
1175
+ });
1176
+ }
1177
+ return [2 /*return*/];
1178
+ });
1179
+ });
1180
+ },
1181
+ closeBundle: function () {
1182
+ if (!manifestJson.value.isRoot) {
1183
+ serverPlugin.initWatchChange();
1184
+ fn === null || fn === void 0 ? void 0 : fn();
1185
+ fn = null;
1186
+ }
1187
+ },
1188
+ initWatchChange: function () {
1189
+ if (isWatcherReady)
1190
+ return;
1191
+ watchDistChangeAndSyncFile(mainPwd, function () {
1192
+ isWatcherReady = true;
1193
+ // console.log(`[Watcher] Ready watching: ${process.env.MFE_SOURCE_OUTPUT_DIR}`);
1194
+ }, function (change) {
1195
+ fn = function () {
1196
+ return mfeClientServer.sendMessage(E_WS_TYPE.CHANGE, __assign(__assign({}, change), { appCode: manifestJson.value.appCode }));
1197
+ };
1198
+ });
1199
+ },
1200
+ copyAppDistModule: function (_a) {
1201
+ var pwd = _a.pwd;
1202
+ if (!process.env.MFE_SOURCE_OUTPUT_DIR) {
1203
+ console.error("[Plugin] MFE_SOURCE_OUTPUT_DIR not defined");
1204
+ return;
1205
+ }
1206
+ mainPwd = path.join(pwd, manifestJson.value.appCode);
1207
+ var targetPath = mainPwd;
1208
+ var sourcePath = process.env.MFE_SOURCE_OUTPUT_DIR;
1209
+ copyFilesByTargetPath(sourcePath, targetPath);
1210
+ },
1211
+ };
1212
+ return [
1213
+ serverPlugin,
1214
+ {
1215
+ name: "@dd-code:main-app",
1216
+ enforce: "post",
1217
+ closeBundle: function () {
1218
+ return __awaiter(this, void 0, void 0, function () {
1219
+ var _a, outputPageJsonPath, manifestList, mainAppJsonPath;
1220
+ return __generator(this, function (_b) {
1221
+ _a = filterManifestJsonListAndMainPageJson(__spreadArray(__spreadArray([], manifestJson.dependencies, true), [
1222
+ manifestJson.value,
1223
+ ], false)), outputPageJsonPath = _a.outputPageJsonPath, manifestList = _a.manifestList;
1224
+ mainAppJsonPath = getMainAppJSon(manifestJson.value.mode, ROOT_APP_CODE);
1225
+ genreNewAppJson(outputPageJsonPath, mainAppJsonPath, manifestList);
1226
+ return [2 /*return*/];
1227
+ });
1228
+ });
1229
+ },
1230
+ },
1231
+ ];
1232
+ };
1233
+
1234
+ var createMpWeixinUniPlugin = function (options) {
1235
+ var currentManifestJson = createManifestManager();
1236
+ return [
1237
+ {
1238
+ name: "@dd-code:genre-params",
1239
+ enforce: "pre",
1240
+ config: function (config) {
1241
+ currentManifestJson.setEnv(config.mode);
1242
+ resetOutDir(currentManifestJson, config);
1243
+ },
1244
+ },
1245
+ createAppsAssetsPlugin(currentManifestJson),
1246
+ createManifestPlugin(currentManifestJson),
1247
+ createMainAppPlugin(currentManifestJson),
1248
+ ];
1249
+ };
1250
+
1251
+ /**
1252
+ * 创建 dd-code Uni 插件
1253
+ * @description 根据配置文件和传入选项创建插件实例
1254
+ * @param {Object} options - 插件配置选项
1255
+ * @returns {Object} 插件实例
1256
+ * @example
1257
+ * const plugin = createPlugin({
1258
+ * env: 'production',
1259
+ * customOption: 'value'
1260
+ * });
1261
+ */
1262
+ var index = (function (options) {
1263
+ var platform = getPlatform();
1264
+ return platform === EPlaform.MP_WEIXIN
1265
+ ? createMpWeixinUniPlugin()
1266
+ : [];
1267
+ });
1268
+
1269
+ module.exports = index;