"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.buildProjectArchive=exports.getUploadOptions=void 0;const tslib_1=require("tslib"),getcompiler_1=require("../getcompiler"),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,r,i,t,n,s){const{project:a,robot:p}=e,l=await(0,sign_1.getSignature)(a.privateKey,a.appid),c={appid:a.appid,pkg_source:"Release"===t?4:3,pkg_type:r?4:0,use_cloud_sync:n?1:0,os_type:"mini-android"===i?2:1,need_client_js_ext_info:"mini-android"===i?s:1,signature:l,robot:p},u=fse.createWriteStream(o,{mode:511});return new Promise((e,o)=>{const r=request({url:`${url_config_1.getPkgWxapkg}?${QueryString.stringify(c)}`,method:"get"},e=>{e&&o(e)});r.on("response",i=>{const t=i.headers["content-type"];if(null==t?void 0:t.toLocaleLowerCase().includes("text/plain")){let e="";i.on("data",o=>{e+=o}),i.on("end",()=>{var r,i,t;try{e=(0,jsonParse_1.jsonRespParse)(e,url_config_1.getPkgWxapkg);const n=null!==(r=e.baseresponse)&&void 0!==r?r:{},s=null!==(i=n.errcode)&&void 0!==i?i:-1,a=null!==(t=n.errmsg)&&void 0!==t?t:"request fail";o(`errcode ${s}, errmsg ${a}`)}catch(e){o(e)}})}else r.pipe(u),u.on("error",e=>{log.error("download miniapp wxapkg error:"+e.message),o(e)}),u.on("close",()=>{e({})});i.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 r=fse.readFileSync(e);try{await(0,unpack_1.default)(r,o)}catch(e){let o=r.toString("utf8");o.length>100&&(o=o.slice(0,100));const i=`Download pkg error: ${o} (${e.msg})`;throw new Error(i)}return o}async function genSubPkgAppInfo(e,o,r,i,t,n,s){var a;const{setting:p={useProjectConfig:!1},project:l,targetPlatform:c}=this,u=(0,miniappJson_1.getMiniappJson)(l.projectPath,c),g=u.icon,d=u.name,f=(await(0,getcompiler_1.getCompiler)(l,p)).getAppJSON(),m=(null===(a=null==f?void 0:f.window)||void 0===a?void 0:a.pageOrientation)||"portrait",_=await(0,app_1.generateSubPkgAppInfoJson)({miniModuleId:e,nickName:d,brandIconURL:g,pageOrientation:m,buildVersion:i,subpkgs:o,contact:t,cpfWxaAttrSyncResponse:n,miniappPkgType:s});fse.ensureDirSync(path.dirname(r)),fse.writeJSONSync(r,_)}async function buildProjectArchive(e,o){var r;let i,t="";try{const n=e.project,{module_info:s={}}=await n.miniappAttr()||{};if(!s.module_id)throw new Error("project.miniapp.json 尚未配置 miniModuleId");log.info("构建项目资源包中...");const a=null!==(r=(await(0,upload_1.upload)(Object.assign(Object.assign(Object.assign({},e),o),getUploadOptions()))).useSubPkg)&&void 0!==r&&r,{miniappOptions:p,outputDir:l}=o,{miniappPkgType:c,useCloudSync:u,needClientJsExtInfo:g}=p;log.info("下载项目资源包中..."),i=path.join(e.resourceDir,"app.wxapkg"),await downloadWxapkg(e,i,a,o.targetPlatform,c,u,g),log.info("下载项目资源包成功"),log.info("生成项目资源包中..."),t=await extractWxapkgToAppDir(i);const d=fse.readJsonSync(path.join(t,"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),r=o+".sign";fse.moveSync(path.join(t,e.file),o),fse.moveSync(path.join(t,e.signFile),r);const i=fse.readFileSync(o);e.md5=(0,tools_1.generateMD5)(i),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{t&&fse.existsSync(t)&&fse.removeSync(t);(await(0,getcompiler_1.getCompiler)(e.project,e.setting||{useProjectConfig:!1})).destroy()}}exports.getUploadOptions=getUploadOptions,exports.buildProjectArchive=buildProjectArchive;