"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getUploadOptions=getUploadOptions,exports.buildProjectArchive=buildProjectArchive;const tslib_1=require("tslib"),tools_1=require("../../utils/tools"),log=tslib_1.__importStar(require("../../utils/log")),upload_1=require("./upload"),url_config_1=require("../../config/url.config"),sign_1=require("../../utils/sign"),jsonParse_1=require("../../utils/jsonParse"),unpack_1=tslib_1.__importDefault(require("../utils/unpack")),app_1=require("../../modules/fullcompiler/app/app"),miniappJson_1=require("../../utils/miniappJson"),path=require("path"),fse=require("fs-extra"),request=require("request"),QueryString=require("querystring");function getUploadOptions(){return{appLaunchInfo:{},uploadType:"build",autoTestMock:!1,onProgressUpdate:(...e)=>{log.info(...e)},onFilesIgnored:()=>{},onFilesMissing:()=>{},remoteDebug:!1,remoteProxyPort:void 0,disableUrlCheck:!1,autoPreview:!1,cdpEnabled:!1,remoteAppservice:!1,remoteAppserviceType:"ios",noMaps:!1,showProgress:!1}}async function downloadWxapkg(e,o,n,r,i,t,s){const{project:a,robot:p}=e,l=await(0,sign_1.getSignature)(a.privateKey,a.appid),c={appid:a.appid,pkg_source:"Release"===i?4:3,pkg_type:n?4:0,use_cloud_sync:t?1:0,os_type:"mini-android"===r?2:1,need_client_js_ext_info:"mini-android"===r?s:1,signature:l,robot:p},u=fse.createWriteStream(o,{mode:511});return new Promise((e,o)=>{const n=request({url:`${url_config_1.getPkgWxapkg}?${QueryString.stringify(c)}`,method:"get"},e=>{e&&o(e)});n.on("response",r=>{const i=r.headers["content-type"];if(null==i?void 0:i.toLocaleLowerCase().includes("text/plain")){let e="";r.on("data",o=>{e+=o}),r.on("end",()=>{var n,r,i;try{e=(0,jsonParse_1.jsonRespParse)(e,url_config_1.getPkgWxapkg);const t=null!==(n=e.baseresponse)&&void 0!==n?n:{},s=null!==(r=t.errcode)&&void 0!==r?r:-1,a=null!==(i=t.errmsg)&&void 0!==i?i:"request fail";o(`errcode ${s}, errmsg ${a}`)}catch(e){o(e)}})}else n.pipe(u),u.on("error",e=>{log.error("download miniapp wxapkg error:"+e.message),o(e)}),u.on("close",()=>{e({})});r.on("error",e=>{o(e)})})}).catch(e=>{throw new Error(`${url_config_1.getPkgWxapkg} fail ${e}`)})}async function extractWxapkgToAppDir(e){const o=e.replace(".wxapkg","");fse.ensureDirSync(o),fse.emptyDirSync(o);const n=fse.readFileSync(e);try{await(0,unpack_1.default)(n,o)}catch(e){let o=n.toString("utf8");o.length>100&&(o=o.slice(0,100));const r=`Download pkg error: ${o} (${e.msg})`;throw new Error(r)}return o}async function genSubPkgAppInfo(e,o,n,r,i,t,s){var a;const{project:p,targetPlatform:l}=this,c=(0,miniappJson_1.getMiniappJson)(p.projectPath,l),u=c.icon,g=c.name,d=(0,miniappJson_1.getRawAppJSON)(p.projectPath),f=(null===(a=null==d?void 0:d.window)||void 0===a?void 0:a.pageOrientation)||"portrait",m=await(0,app_1.generateSubPkgAppInfoJson)({miniModuleId:e,nickName:g,brandIconURL:u,pageOrientation:f,buildVersion:r,subpkgs:o,contact:i,cpfWxaAttrSyncResponse:t,miniappPkgType:s});fse.ensureDirSync(path.dirname(n)),fse.writeJSONSync(n,m)}async function buildProjectArchive(e,o){var n;let r,i="";try{const t=e.project,{module_info:s={}}=await t.miniappAttr()||{};if(!s.module_id)throw new Error("project.miniapp.json 尚未配置 miniModuleId");log.info("构建项目资源包中...");const a=null!==(n=(await(0,upload_1.upload)(Object.assign(Object.assign(Object.assign({},e),o),getUploadOptions()))).useSubPkg)&&void 0!==n&&n,{miniappOptions:p,outputDir:l}=o,{miniappPkgType:c,useCloudSync:u,needClientJsExtInfo:g}=p;log.info("下载项目资源包中..."),r=path.join(e.resourceDir,"app.wxapkg"),await downloadWxapkg(e,r,a,o.targetPlatform,c,u,g),log.info("下载项目资源包成功"),log.info("生成项目资源包中..."),i=await extractWxapkgToAppDir(r);const d=fse.readJsonSync(path.join(i,"info.json"));if(0===d.wxapkgs.length)throw new Error("构建项目资源包失败: 获取不到 wxapkg");fse.ensureDirSync(l),fse.emptyDirSync(l),d.wxapkgs.forEach(e=>{const o=path.join(l,e.file),n=o+".sign";fse.moveSync(path.join(i,e.file),o),fse.moveSync(path.join(i,e.signFile),n);const r=fse.readFileSync(o);e.md5=(0,tools_1.generateMD5)(r),e.versionType=null==p?void 0:p.miniappPkgType});const f=path.join(l,"buildinfo.json");await genSubPkgAppInfo.call(Object.assign(Object.assign({},e),o),s.module_id,d.wxapkgs,f,d.buildVersion,d.contact,d.cpfWxaAttrSyncResponse,p.miniappPkgType),log.info("生成项目资源包成功")}catch(e){throw new Error("build project archive error: "+e.message)}finally{i&&fse.existsSync(i)&&fse.removeSync(i)}}