"use strict";var __importDefault=this&&this.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(exports,"__esModule",{value:!0});const protocol_1=require("../../protocol"),compile_1=require("../../protocol/compile"),path_1=__importDefault(require("path")),child_process_1=require("child_process"),utils_1=require("../../utils/utils"),timer_1=__importDefault(require("../../utils/timer")),Logger_1=__importDefault(require("../../common/Logger"));let lastTime=(new Date).getTime();const throttleEmit=(t,e=500)=>{const s=(new Date).getTime();s-lastTime>e&&(t(),lastTime=s)};class Compile{constructor(t,e){this._appId="",this.processList=[],this.errMsgs=[],this.isUpdate=!1,this.module=t,this.options=e}async run(){return await this.start()}getPackVersion(){return"default"}startProcess(t){return this.log.info("Compile","createProcess","start"),new Promise((e,s)=>{var i,o;const r=(0,child_process_1.fork)(path_1.default.join(__dirname,"help/bizpack.js"),[],{execArgv:["--unhandled-rejections=strict"],stdio:"pipe"}),n={process:r,info:{status:"start",progress:0,isUpdate:!1}};this.processList.push(n),null===(i=r.stderr)||void 0===i||i.on("data",t=>this.onError(n,t)),null===(o=r.stdout)||void 0===o||o.on("data",t=>this.onStdout(n,t)),r.on("exit",this.onExit.bind(this)),r.on("message",t=>{try{const s=this.onMessage(n,t);s&&e(s)}catch(t){s(t)}}),this.log.info("Compile","sendCompileStart","start",{options:t}),r.send(t),this.log.info("Compile","createProcess","end",{processArgs:t})})}onMessage(t,e){var s;const{appType:i}=this.options,{type:o,data:r,extra:n={}}=e;if(this.log.info("common","messageListener","start",{type:o,extra:n||"",from:"message"}),"compileStart"===o)this.errMsgs=[],t.info.status="start",t.info.progress=0,("block"===i||this.isUpdate)&&this.emit(compile_1.EventEnum.WatchCompileStart,{data:{appType:i,from:this.compileType,isUpdate:this.isUpdate}}),timer_1.default.start(this.events.compile);else{if("compileEnd"===o){t.info.status="end";const e=Array.from(new Set(this.errMsgs)).join("\n");let o;o=this.isUpdate?this.events.watch:this.events.first,this.emit(compile_1.EventEnum.EventTrack,{event:o,data:Object.assign(Object.assign({},timer_1.default.end(this.events.compile)),{error:e,version:this.getPackVersion()})});const n={errMsg:(null==r?void 0:r.errorMessage)||e||"",data:{appType:i,from:this.compileType,blockTypeID:null===(s=this.options.appInfo)||void 0===s?void 0:s.blockTypeId,productName:(null==r?void 0:r.productName)||"",isUpdate:this.isUpdate}};return this.isUpdate=!0,this.processList.every(t=>"end"===t.info.status||"stop"===t.info.status)&&this.emit(compile_1.EventEnum.WatchCompileEnd,n),n}if("compileStop"===o)throw new Error("stop")}}onStdout(t,e){const s=new RegExp(/bizpack progress is: ([0-9.]+)/),i=e.toString();if(this.log.info("Compile","stdout","end",{from:"stdout",info:i}),/loader.*begin.*end.*/.test(i)){const t=i.replace("[BIZPACK][INFO]","");try{const e=JSON.parse(t);this.emit(compile_1.EventEnum.EventTrack,{event:"compile_pack_result",data:{type:this.options.appType,timeStart:e.loader.begin,timeEnd:e.output.end,duration:e.total,info:i,appId:this.getAppId()}})}catch(e){this.log.error("common","packTimeStr",t)}}if(s.test(i)){const e=i.match(s);e&&2===e.length&&(t.info.progress=100*parseFloat(e[1])),this.emitProgress()}}onError(t,e){const s=e.toString();if(this.log.error("Compile","err","end",s),s.includes("[BIZPACK][ERROR]"))this.errMsgs.push(s);else{s.split("\n").some(e=>!!e.startsWith("Error")&&(this.onMessage(t,{type:"compileEnd",data:{errorMessage:e,productName:""},extra:{}}),!0))}}onExit(t){this.destroy(),this.log.info("compileGadget","end","exitListener")}emitProgress(){throttleEmit(()=>{const t=this.processList.filter(t=>"stop"!==t.info.status);if(0===t.length)return;const e=1/t.length,s=t.reduce((t,s)=>t+s.info.progress*e,0);this.emit(compile_1.EventEnum.CompileProgress,{data:{progress:~~(s>100?100:s),from:this.compileType}})})}destroy(){this.processList.forEach(t=>{t.process.kill()}),this.processList=[],this.log.info(`compile[${this.options.appType}][${this.compileType}]`,"end","invoke stop")}alive(){return this.processList.length>0}get compileType(){return this.options.type}get log(){return new Logger_1.default(protocol_1.ModuleName.compile)}get emit(){return this.module.emit.bind(this.module)}async getAppId(){return this._appId||(this._appId=await(0,utils_1.readFileContent)(this.options.sourcePath,"project.config.json")),this._appId}}exports.default=Compile;