"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.getDevSourceMap=getDevSourceMap;const tslib_1=require("tslib"),fs_1=tslib_1.__importDefault(require("fs")),path_1=tslib_1.__importDefault(require("path")),log=tslib_1.__importStar(require("../utils/log")),request_1=require("../utils/request"),url_config_1=require("../config/url.config"),sign_1=require("../utils/sign"),JsZip=require("jszip"),ERR_MSG_PREFIX="download source map failed:";async function getExtAppId(r){let e,t={};try{e=await r.getFile(r.miniprogramRoot,"ext.json"),t=JSON.parse(e.toString("utf-8"))}catch(r){}if(null==t?void 0:t.extEnable)return t.extAppid}async function getDevSourceMap(r){const{project:e,robot:t,streaming:o}=r;let{sourceMapSavePath:a}=r;if(!e){const r="params project is requried";throw log.error(r),r}if("number"!=typeof t||Math.round(t)>30||Math.round(t)<=0){const r="params robot is invalid";throw log.error(r),r}if(!a){const r="params sourceMapSavePath is invalid";throw log.error(r),r}path_1.default.isAbsolute(a)||(a=path_1.default.join(process.cwd(),a));const i=await(0,sign_1.getSignature)(e.privateKey,e.appid),s=await getExtAppId(e),{body:p}=await(0,request_1.request)({url:url_config_1.GET_DEV_SOURCE_MAP,method:"post",gzip:!0,body:JSON.stringify({appid:e.appid,signature:i,robot:t,extAppId:s,streaming:o}),headers:{"content-type":"application/json"}});let l,n;try{l=JSON.parse(p)}catch(r){const e=ERR_MSG_PREFIX+" resp body is not a valid json";throw log.error(e),e}if(o)n=l.sourcemap_list;else{if(0!==l.errCode)throw new Error(`request failed, errCode: ${l.errCode}, errMsg: ${l.errMsg}`);const r=l.data;if(!Array.isArray(r.sourcemap_list)){const e=`${ERR_MSG_PREFIX} respData.sourcemap_list, respData: ${JSON.stringify(r)}`;throw log.error(e),e}n=r.sourcemap_list}const u=n,c=new JsZip;try{u.forEach(r=>{c.folder(path_1.default.dirname(r.fullpath)).file(path_1.default.basename(r.fullpath),r.sourcemap)})}catch(r){const e=ERR_MSG_PREFIX+" source map add folder or add file error";throw log.error(e),e}let _;try{_=await c.generateAsync({type:"nodebuffer"})}catch(r){const e=ERR_MSG_PREFIX+" source map generate zip error";throw log.error(e),e}try{fs_1.default.writeFileSync(a,_)}catch(r){const e=`${ERR_MSG_PREFIX} save source map to ${a} failed. Error detail: ${JSON.stringify(r)}`;throw log.error(e),e}return _}