const path=require("path"),BaseController=require("./base"),localPath=process.env.UNICLOUD_DEBUGGER_PATH,{isUniAppCli:isUniAppCli,getRealWorkspace:getRealWorkspace,getRealFunctionPath:getRealFunctionPath,getFunctionType:shareGetFunctionType,ErrorWithCode:ErrorWithCode}=require("../utils/index"),{VmManager:VmManager}=require("../utils/index"),chokidar=require("chokidar");function getSingleCommandMsg({action:e,command:t}={}){const n=t.$db,o=n&&n.find((e=>"collection"===e.$method)),c=o&&o.$param&&o.$param;let r;return r=1===c.length?c[0]:c.map((e=>"string"==typeof e?e:e&&e.$db&&e.$db[0]&&e.$db[0].$param&&e.$db[0].$param[0])),`表名：${r}`+(e?`，action：${e}`:"")}function formatClientDBInputMessage(e){const{action:t,command:n,multiCommand:o}=e;let c="";return o?(c+="[clientDB multiSend请求]",c+=o.map((e=>getSingleCommandMsg(e))).join("；")):(c+="[clientDB请求]",c+=getSingleCommandMsg({action:t,command:n})),c}function formatCallFunctionParam(e){const t=JSON.parse(JSON.stringify(e||{}));return delete t.clientInfo,delete t.uniCloudDeviceId,delete t.uniCloudClientInfo,t}function getFunctionType(){const e=this.ctx.data.provider,t=this.ctx.service,n=this.ctx.realWorkspace,o=getRealFunctionPath(n,e,t);return shareGetFunctionType(o)}function isIgnoreRequest(e,t){return"DCloud-clientDB"===e&&t&&t.redirectTo}function parseInputMessage(e,t){if(isIgnoreRequest(e,t))return;const n=this.ctx.logger;if("DCloud-clientDB"===e)n.log(formatClientDBInputMessage(t));else if("object"===this.ctx.functionType){const{method:o,params:c=[]}=t||{};0===c.length?n.log(`[云对象：${e}]调用方法：[${o}]，请求参数：无`):n.log(`[云对象：${e}]调用方法：[${o}]，请求参数：`,...c)}else n.log(`[云函数：${e}]请求参数：`,formatCallFunctionParam(t))}function parseOutputMessage(e,t,n){if(isIgnoreRequest(e,t))return;const o=this.ctx.logger;"DCloud-clientDB"===e?n.code||o.log(`${formatClientDBInputMessage(t)}，返回数据：`,n):"object"===this.ctx.functionType?o.log(`[云对象：${e}]返回结果：`,n):o.log(`[云函数：${e}]返回结果：`,n)}async function getSecret(){try{const{value:e}=await this.ctx.jsonRpcClient.call("getSecret");if(!e)throw new ErrorWithCode({code:"REQUEST_ERROR",message:"获取本地运行参数失败"});process.env.UNICLOUD_SECRET=JSON.stringify(e)}catch(e){console.error(e),this.ctx.throw("请求云函数出错："+e.message,e.code||"INTERNAL_ERROR")}}async function getServiceSecret(){try{const{value:e}=await this.ctx.jsonRpcClient.call("getServiceSecret");if(!e)throw new ErrorWithCode({code:"REQUEST_ERROR",message:"获取uniCloud服务参数失败"});process.env.UNICLOUD_SERVICE_SECRET=JSON.stringify(e)}catch(e){console.error(e),this.ctx.throw("请求云函数出错："+e.message,e.code||"INTERNAL_ERROR")}}const vmManager=new VmManager,realWorkspace=getRealWorkspace(),uniAppCliProject=isUniAppCli(realWorkspace),watcher=chokidar.watch(["uniCloud-tcb/**/*.js","uniCloud-tcb/**/*.json","uniCloud-aliyun/**/*.js","uniCloud-aliyun/**/*.json","uniCloud-alipay/**/*.js","uniCloud-alipay/**/*.json","uniCloud-dcloud/**/*.js","uniCloud-dcloud/**/*.json",(uniAppCliProject?"src/":"")+"uni_modules/*/uniCloud/**/*.js",(uniAppCliProject?"src/":"")+"uni_modules/*/uniCloud/**/*.json"],{ignored:"node_modules",cwd:realWorkspace});function deleteCache(e){const t=path.resolve(realWorkspace,e);vmManager.deleteCache(t),delete require.cache[t]}watcher.on("change",(function(e){deleteCache(e)})),watcher.on("unlink",(function(e){deleteCache(e)})),module.exports=class extends BaseController{constructor(){super(),this.name="cloudfunctions"}async exec(){const{service:e,data:t}=this.ctx,{provider:n,param:o,source:c="client"}=t;this.ctx.realWorkspace=realWorkspace,this.ctx.functionType=getFunctionType.call(this),await getSecret.call(this),await getServiceSecret.call(this),parseInputMessage.call(this,e,o);const r=[e,o,{clientIP:this.ctx.req.connection.remoteAddress,userAgent:this.ctx.req.headers["user-agent"],source:c}];try{const t=await vmManager.exec({entryPath:path.resolve(localPath,n,"serve.js"),args:r,uniCloudUniqueTag:process.env.UNICLOUD_SECRET+"\n"+process.env.UNICLOUD_SERVICE_SECRET});return parseOutputMessage.call(this,e,o,t),t}catch(e){console.error(e),this.ctx.throw(e.message||"请求云函数出错",e.code||"FUNCTION_EXCUTE_ERROR")}}};