"use strict";functione(e){returne&&"object"==typeofe&&"default"ine?e.default:e}vart=e(require("crypto")),r=e(require("buffer")),n=e(require("stream")),i=e(require("util"));consto={PARAM_ERROR:{errCode:"param-error"},PARAM_REQUIRED:{errCode:"param-required"},USER_NOT_EXIST:{errCode:"user-not-exist"},ROLE_NOT_EXIST:{errCode:"role-not-exist"},PERMISSION_NOT_EXIST:{errCode:"permission-not-exist"},MULTI_USER_MATCHED:{errCode:"multi-user-matched"},USER_INFO_ERROR:{errCode:"user-info-error"},USER_ACCOUNT_CONFLICT:{errCode:"user-account-conflict"},USER_ACCOUNT_CLOSED:{errCode:"user-account-closed"},ACCOUNT_EXISTS:{errCode:"account-exists"},ACCOUNT_NOT_EXISTS:{errCode:"account-not-exists"},ACCOUNT_BOUND:{errCode:"account-bound"},UNBIND_FAILED:{errCode:"unbind-failed"},INVALID_INVITE_CODE:{errCode:"invalid-invite-code"},SET_INVITE_CODE_FAILED:{errCode:"set-invite-code-failed"},GET_THIRD_PARTY_ACCOUNT_FAILED:{errCode:"get-third-party-account-failed"},GET_THIRD_PARTY_USER_INFO_FAILED:{errCode:"get-third-party-user-info-failed"}},s={0:{errCode:0,errMsg:""},10001:{errCode:"account-banned"},10002:o.USER_NOT_EXIST,10003:o.MULTI_USER_MATCHED,10004:o.USER_INFO_ERROR,10005:o.USER_ACCOUNT_CONFLICT,10006:o.USER_ACCOUNT_CLOSED,10102:{errCode:"password-error"},10103:{errCode:"password-error-exceed-limit"},10201:o.ACCOUNT_EXISTS,10202:o.ACCOUNT_NOT_EXISTS,10203:o.INVALID_INVITE_CODE,10301:o.ACCOUNT_EXISTS,10302:o.ACCOUNT_NOT_EXISTS,10401:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10402:o.ACCOUNT_EXISTS,10403:o.ACCOUNT_NOT_EXISTS,10501:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10502:o.ACCOUNT_EXISTS,10503:o.ACCOUNT_NOT_EXISTS,10601:o.ACCOUNT_EXISTS,10602:o.ACCOUNT_NOT_EXISTS,10701:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10702:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10703:o.ACCOUNT_EXISTS,10704:o.ACCOUNT_NOT_EXISTS,10705:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10706:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10801:o.GET_THIRD_PARTY_ACCOUNT_FAILED,10802:o.ACCOUNT_EXISTS,10803:o.ACCOUNT_NOT_EXISTS,20101:o.PARAM_REQUIRED,20102:o.ACCOUNT_EXISTS,30101:o.PARAM_REQUIRED,30201:{errCode:"check-device-feature-failed"},30202:{errCode:"token-not-exist"},30203:{errCode:"token-expired"},30204:{errCode:"check-token-failed"},40201:o.USER_NOT_EXIST,40202:{errCode:"invalid-old-password"},50101:o.PARAM_REQUIRED,50102:o.PARAM_ERROR,50201:o.PARAM_REQUIRED,50203:o.PARAM_ERROR,50202:{errCode:"invalid-verify-code"},50301:{errCode:"send-sms-code-failed"},60101:o.ACCOUNT_BOUND,60201:o.ACCOUNT_BOUND,60301:o.GET_THIRD_PARTY_ACCOUNT_FAILED,60302:o.ACCOUNT_BOUND,60401:o.GET_THIRD_PARTY_ACCOUNT_FAILED,60402:o.ACCOUNT_BOUND,60501:o.GET_THIRD_PARTY_ACCOUNT_FAILED,60502:o.ACCOUNT_BOUND,70101:o.UNBIND_FAILED,70201:o.UNBIND_FAILED,70301:o.UNBIND_FAILED,70401:o.UNBIND_FAILED,70501:o.UNBIND_FAILED,80301:o.USER_NOT_EXIST,80401:o.SET_INVITE_CODE_FAILED,80402:o.SET_INVITE_CODE_FAILED,80501:o.INVALID_INVITE_CODE,80502:o.USER_NOT_EXIST,80503:{errCode:"modify-invite-code-is-not-allowed"},80601:o.GET_THIRD_PARTY_ACCOUNT_FAILED,80602:o.GET_THIRD_PARTY_ACCOUNT_FAILED,80701:o.GET_THIRD_PARTY_ACCOUNT_FAILED,80702:o.GET_THIRD_PARTY_ACCOUNT_FAILED,80801:{errCode:"decrypt-weixin-data-failed"},80802:{errCode:"decrypt-weixin-data-failed"},80803:{errCode:"invalid-weixin-appid"},80804:o.PARAM_REQUIRED,80805:o.PARAM_REQUIRED,80806:o.PARAM_REQUIRED,80901:o.GET_THIRD_PARTY_USER_INFO_FAILED,90001:{errCode:"database-operation-failed"},90002:o.PARAM_REQUIRED,90003:o.PARAM_ERROR,90004:o.USER_NOT_EXIST,90005:o.ROLE_NOT_EXIST,90006:o.PERMISSION_NOT_EXIST};classaextendsError{constructor(e){super(e.message),this.errMsg=e.message||"",Object.defineProperties(this,{message:{get(){return`errCode: ${e.code||""} | errMsg: `+this.errMsg},set(e){this.errMsg=e}}})}}constc=Object.prototype.toString,u=Object.prototype.hasOwnProperty;functiond(e,t){returnu.call(e,t)}functionp(e){return"[object Object]"===c.call(e)}functionl(e){return"function"==typeofe}functionf(e){return!!e&&("object"==typeofe||"function"==typeofe)&&"function"==typeofe.then}functionm(e){returnObject.prototype.toString.call(e).slice(8,-1).toLowerCase()}consth=/_(\w)/g,g=/[A-Z]/g;functiony(e){returne.replace(h,(e,t)=>t?t.toUpperCase():"")}functionw(e){returne.replace(g,e=>"_"+e.toLowerCase())}functionv(e,t){letr,n;switch(t){case"snake2camel":n=y,r=h;break;case"camel2snake":n=w,r=g}for(constiine)if(d(e,i)&&r.test(i)){constr=n(i);e[r]=e[i],deletee[i],p(e[r])?e[r]=v(e[r],t):Array.isArray(e[r])&&(e[r]=e[r].map(e=>v(e,t)))}returne}function_(e){returnv(e,"snake2camel")}functionb(e){returnv(e,"camel2snake")}functionT(e){returnfunction(e,t="-"){e=e||newDate;constr=[];returnr.push(e.getFullYear()),r.push(("00"+(e.getMonth()+1)).substr(-2)),r.push(("00"+e.getDate()).substr(-2)),r.join(t)}(e=e||newDate)+""+function(e,t=":"){e=e||newDate;constr=[];returnr.push(("00"+e.getHours()).substr(-2)),r.push(("00"+e.getMinutes()).substr(-2)),r.push(("00"+e.getSeconds()).substr(-2)),r.join(t)}(e)}functionE(){"development"===process.env.NODE_ENV&&console.log(...arguments)}functionC(e=6){lett="";for(letr=0;r<e;r++)t+=Math.floor(10*Math.random());returnt}functionA(e){returnArray.from(newSet(e))}functionx(e={},t){if(!t||!e)returne;constr=["_pre","_purify","_post"];t._pre&&(e=t._pre(e));letn={shouldDelete:newSet([])};if(t._purify){conste=t._purify;for(consttine)e[t]=newSet(e[t]);n=Object.assign(n,e)}if(p(t))for(constiint){consto=t[i];l(o)&&-1===r.indexOf(i)?e[i]=o(e):"string"==typeofo&&-1===r.indexOf(i)&&(e[i]=e[o],n.shouldDelete.add(o))}elsel(t)&&(e=t(e));if(n.shouldDelete)for(consttofn.shouldDelete)deletee[t];returnt._post&&(e=t._post(e)),e}functionI(e,t){constr=newe(t);returnnewProxy(r,{get:function(e,t){if("function"==typeofe[t]&&0!==t.indexOf("_")&&e._protocols&&e._protocols[t]){constr=e._protocols[t];returnasyncfunction(n){n=x(n,r.args);leti=awaite[t](n);returni=x(i,r.returnValue),i}}returne[t]}})}functionS(e){if(p(e))if(0===e.code)e.errCode=e.code,e.message=e.errMsg=e.msg,deletee.messageValues;elseif(d(s,e.code)){constt=s[e.code];e.errCode="uni-id-"+t.errCode,e.errMsg=this.t(t.errCode,e.messageValues||{})||e.msg,e.message=e.msg=e.errMsg,deletee.messageValues}elsee.code&&console.warn(`error code not found, error code: ${e.code}, please contact us`)}vark={"zh-Hans":{alipay:"支付宝",wechat:"微信",user:"用户","user-id":"用户ID","dcloud-appid":"应用Appid","dcloud-appid-list":"应用列表",account:"账号",username:"用户名",email:"邮箱",mobile:"手机号",sms:"短信","wechat-openid":"微信openid","wechat-account":"微信账号","alipay-account":"支付宝账号","qq-openid":"QQ openid","qq-account":"QQ账号","apple-account":"苹果账号",password:"密码","verify-code":"验证码","verify-code-type":"验证码类型","user-unique-param":"用户名、邮箱或手机号","role-id":"角色ID","permission-id":"权限ID",login:"登录","verify-mobile":"验证手机","context-param-required":"context内缺少{param},请使用uniID.createInstance传入客户端信息","config-param-require":"uni-id的配置内缺少{param}","uni-verify-config-required":"请在config.json中配置service.univerify下一键登录相关参数","login-with-invite-type-required":"强制使用邀请码注册时,需指明type为register还是login","type-array-required":"{param}应为数组形式","query-field-warning":"检测到当前使用queryField匹配多字段进行登录操作,需要注意:uni-id并未限制用户名不能是手机号或邮箱,需要开发者自行限制。否则可能出现用户输入abc@xx.com会同时匹配到邮箱为此值的用户和用户名为此值的用户,导致登录失败","add-role-admin-is-not-allowed":"不可新增roleID为admin的角色","password-secret-type-error":"config内passwordSecret类型错误,只可设置string类型和array类型","token-expires-config-warning":"tokenExpiresIn不可小于或等于tokenExpiresThreshold","type-function-required":"{param}应为function类型","dev-warning":"当前正在使用uniID.dev属性,注意此属性仅可用于开发调试","config-file-invalid":"请确保公用模块uni-id对应的配置文件(common/uni-config-center/uni-id/config.json)格式正确(不可包含注释)","config-file-not-found":"请在common/uni-config-center/uni-id/config.json内添加uni-id相关配置信息","hx-version-warning":"当前使用的HBuilderX版本过低,请升级HBuilderX到最新版本","account-banned":"账号已禁用","user-not-exist":"用户不存在","multi-user-matched":"匹配到多个账号","user-info-error":"用户信息不正确","user-account-conflict":"用户账号冲突","user-account-closed":"此账号已注销","password-error":"密码错误","password-error-exceed-limit":"密码错误次数过多,请稍后再试","account-exists":"此账号已注册","account-not-exists":"此账号尚未注册","invalid-invite-code":"邀请码无效","get-third-party-account-failed":"获取{account}失败","get-third-party-user-info-failed":"获取用户信息失败","param-required":"{param}不可为空","check-device-feature-failed":"设备特征校验未通过","token-not-exist":"登录状态无效,云端已不包含此token","token-expired":"token已过期","check-token-failed":"token校验未通过","invalid-old-password":"旧密码错误","param-error":"{param}参数错误,{reason}","invalid-verify-code":"{type}验证码错误或已失效","send-sms-code-failed":"短信验证码发送失败","account-bound":"此账号已被绑定","unbind-failed":"解绑失败","set-invite-code-failed":"邀请码设置失败","modify-invite-code-is-not-allowed":"邀请码不可修改","decrypt-weixin-data-failed":"解密失败","invalid-weixin-appid":"appid不匹配","database-operation-failed":"数据库读写异常","role-not-exist":"角色不存在","permission-not-exist":"权限不存在","context-required":"uni-id无法获取context.{key},请使用uniID.createInstance方法传入","limit-client-platform":"当前客户端平台不支持此接口"},en:{alipay:"alipay",wechat:"wechat",user:"user","user-id":"user id","dcloud-appid":"DCloud appid","dcloud-appid-list":"DCloud appid list",account:"account",username:"username",email:"email",mobile:"phone number",sms:"sms","wechat-openid":"wechat openid","wechat-account":"wechat account","alipay-account":"alipay account","qq-openid":"QQ openid","qq-account":"QQ account","apple-account":"apple account",password:"password","verify-code":"verify code","verify-code-type":"verify code type","user-unique-param":"username, email or mobile phone number","role-id":"role id","permission-id":"permission id",login:"login","verify-mobile":"verify mobile phone number","context-param-required":"You should pass {param} in context using uniID.createInstance","config-param-require":"{param} is required in uni-id's config","uni-verify-config-required":"Univerify config required: service.univerify","login-with-invite-type-required":"Parameter type is required when forceInviteCode set to true","type-array-required":"Type of {param} must be array","query-field-warning":"You are using multi query field to login, be aware that uni-id will not check username's fromat, eg: abc@xx.com is a valid username for uni-id. You should check username in your code.","add-role-admin-is-not-allowed":'Add role with an id of "admin" is not allowed',"password-secret-type-error":'"passwordSecret" in config must be string or array',"token-expires-config-warning":'"tokenExpiresIn" must be greater than "tokenExpiresThreshold"',"type-function-required":"{param} must be a function","dev-warning":"warning: uniID.dev is only for development","config-file-invalid":"Invalid config file (common/uni-config-center/uni-id/config.json), please note that comment is not allowed","config-file-not-found":"Config file (common/uni-config-center/uni-id/config.json) not found","hx-version-warning":"The HBuilderX you are using is too old, please upgrade to the latest version of HBuilderX","account-banned":"Account is banned","user-not-exist":"User does not exist","multi-user-matched":"Multiple users are matched","user-info-error":"User info error","user-account-conflict":"User account conflict","user-account-closed":"User account has been closed","password-error":"The password is incorrect","password-error-exceed-limit":"The number of password errors exceeded the limit","account-exists":"Account exists","account-not-exists":"Account does not exists","invalid-invite-code":"Invalid invite code","get-third-party-account-failed":"Get {account} failed","get-third-party-user-info-failed":"Get user info failed","param-required":"{param} is required","check-device-feature-failed":"Check device feature failed","token-not-exist":"The login status is invalid, token does not exist","token-expired":"The login status is invalid, token has expired","check-token-failed":"Check token failed","invalid-old-password":"Invalid old password","param-error":"{param} error, {reason}","invalid-verify-code":"Invalid {type} verify code","send-sms-code-failed":"Send sms code failed","account-bound":"Account has been bound","unbind-failed":"Unbind failed","set-invite-code-failed":"Set invite code failed","modify-invite-code-is-not-allowed":"Modifying the invitation code is prohibited","decrypt-weixin-data-failed":"Decrypt weixin data failed","invalid-weixin-appid":"Invalid weixin appid","database-operation-failed":"Database operation failed","role-not-exist":"Role does not exist","permission-not-exist":"Permission does not exist","context-required":'"context.{key}" is required, you should pass context using uniID.createInstance',"limit-client-platform":"Unsupported client platform"}};constO=uniCloud.database(),P=O.collection("uni-id-users"),R=O.collection("opendb-verify-codes"),j=O.collection("uni-id-roles"),D=O.collection("uni-id-permissions"),q={username:"username",mobile:"mobile",email:"email",wx_unionid:"wechat-account","wx_openid.app-plus":"wechat-account","wx_openid.app":"wechat-account","wx_openid.mp-weixin":"wechat-account",qq_unionid:"qq-account","qq_openid.app-plus":"qq-account","qq_openid.app":"qq-account","qq_openid.mp-weixin":"qq-account",ali_openid:"alipay-account",apple_openid:"alipay-account"},N=90002,U=90003,L=90004,V=90005,M=0,B=1,F=4;asyncfunction$({uid:e,status:t}={}){returne?(awaitP.doc(e).update({status:t,status_update_date:Date.now()}),{code:0}):{code:N,messageValues:{param:this.t("user-id")}}}asyncfunctionH({name:e,url:t,data:r,options:n,defaultOptions:i}){leto={};consts=b(Object.assign({},r));s&&s.access_token&&deletes.access_token;try{n=Object.assign({},i,n,{data:s}),o=awaituniCloud.httpclient.request(t,n)}catch(t){returnfunction(e,t){thrownewa({code:t.code||-2,message:t.message||e+" fail"})}(e,t)}letc=o.data;constu=o.headers["content-type"];if(!Buffer.isBuffer(c)||0!==u.indexOf("text/plain")&&0!==u.indexOf("application/json"))Buffer.isBuffer(c)&&(c={buffer:c,contentType:u});elsetry{c=JSON.parse(c.toString())}catch(e){c=c.toString()}return_(function(e,t){if(t.errcode)thrownewa({code:t.errcode||-2,message:t.errmsg||e+" fail"});returndeletet.errcode,deletet.errmsg,{...t,errMsg:e+" ok",errCode:0}}(e,c||{errCode:-2,errMsg:"Request failed"}))}functionK(e,t){letr="";if(t&&t.accessToken){r=`${e.indexOf("?")>-1?"&":"?"}access_token=${t.accessToken}`}return`${e}${r}`}classG{constructor(e){this.options=Object.assign({baseUrl:"https://api.weixin.qq.com",timeout:5e3},e)}async_requestWxOpenapi({name:e,url:t,data:r,options:n}){consti={method:"GET",dataType:"json",dataAsQueryString:!0,timeout:this.options.timeout};returnawaitH({name:"auth."+e,url:`${this.options.baseUrl}${K(t,r)}`,data:r,options:n,defaultOptions:i})}asynccode2Session(e){returnawaitthis._requestWxOpenapi({name:"code2Session",url:"/sns/jscode2session",data:{grant_type:"authorization_code",appid:this.options.appId,secret:this.options.secret,js_code:e}})}asyncgetOauthAccessToken(e){constt=awaitthis._requestWxOpenapi({name:"getOauthAccessToken",url:"/sns/oauth2/access_token",data:{grant_type:"authorization_code",appid:this.options.appId,secret:this.options.secret,code:e}});returnt.expiresIn&&(t.expired=Date.now()+1e3*t.expiresIn),t}asyncgetUserInfo({accessToken:e,openid:t}={}){const{nickname:r,headimgurl:n}=awaitthis._requestWxOpenapi({name:"getUserInfo",url:"/sns/userinfo",data:{accessToken:e,openid:t,appid:this.options.appId,secret:this.options.secret,scope:"snsapi_userinfo"}});return{nickname:r,avatar:n}}}asyncfunctionQ({name:e,url:t,data:r,options:n,defaultOptions:i}){leto;n=Object.assign({},i,n,{data:b(Object.assign({},r))});try{o=awaituniCloud.httpclient.request(t,n)}catch(t){returnfunction(e,t){thrownewa({code:t.code||-2,message:t.message||e+" fail"})}(e,t)}lets=o.data;constc=o.headers["content-type"];if(!Buffer.isBuffer(s)||0!==c.indexOf("text/plain")&&0!==c.indexOf("application/json"))Buffer.isBuffer(s)&&(s={buffer:s,contentType:c});elsetry{s=JSON.parse(s.toString())}catch(e){s=s.toString()}return_(function(e,t){if(t.ret||t.error){constr=t.ret||t.error||t.errcode||-2,n=t.msg||t.error_description||t.errmsg||e+" fail";thrownewa({code:r,message:n})}returndeletet.ret,deletet.msg,deletet.error,deletet.error_description,deletet.errcode,deletet.errmsg,{...t,errMsg:e+" ok",errCode:0}}(e,s||{errCode:-2,errMsg:"Request failed"}))}classX{constructor(e){this.options=Object.assign({baseUrl:"https://graph.qq.com",timeout:5e3},e)}async_requestQQOpenapi({name:e,url:t,data:r,options:n}){consti={method:"GET",dataType:"json",dataAsQueryString:!0,timeout:this.options.timeout};varo,s;returnawaitQ({name:"auth."+e,url:(o=this.options.baseUrl,s=t,/^https?:/.test(s)?s:o+s),data:r,options:n,defaultOptions:i})}asyncgetOpenidByToken({accessToken:e}={}){constt=awaitthis._requestQQOpenapi({name:"getOpenidByToken",url:"/oauth2.0/me",data:{accessToken:e,unionid:1,fmt:"json"}});if(t.clientId!==this.options.appId)thrownewa({code:"APPID_NOT_MATCH",message:"appid not match"});return{openid:t.openid,unionid:t.unionid}}asynccode2Session({code:e}={}){returnawaitthis._requestQQOpenapi({name:"getOpenidByToken",url:"https://api.q.qq.com/sns/jscode2session",data:{grant_type:"authorization_code",appid:this.options.appId,secret:this.options.secret,js_code:e}})}}constY={RSA:"RSA-SHA1",RSA2:"RSA-SHA256"};varz={code2Session:{returnValue:{openid:"userId"}}};classWextendsclass{constructor(e={}){if(!e.appId)thrownewError("appId required");if(!e.privateKey)thrownewError("privateKey required");constt={gateway:"https://openapi.alipay.com/gateway.do",timeout:5e3,charset:"utf-8",version:"1.0",signType:"RSA2",timeOffset:-(newDate).getTimezoneOffset()/60,keyType:"PKCS8"};e.sandbox&&(e.gateway="https://openapi.alipaydev.com/gateway.do"),this.options=Object.assign({},t,e);constr="PKCS8"===this.options.keyType?"PRIVATE KEY":"RSA PRIVATE KEY";this.options.privateKey=this._formatKey(this.options.privateKey,r),this.options.alipayPublicKey&&(this.options.alipayPublicKey=this._formatKey(this.options.alipayPublicKey,"PUBLIC KEY"))}_formatKey(e,t){return`-----BEGIN ${t}-----\n${e}\n-----END ${t}-----`}_formatUrl(e,t){letr=e;constn=["app_id","method","format","charset","sign_type","sign","timestamp","version","notify_url","return_url","auth_token","app_auth_token"];for(consteint)if(n.indexOf(e)>-1){constn=encodeURIComponent(t[e]);r=`${r}${r.includes("?")?"&":"?"}${e}=${n}`,deletet[e]}return{execParams:t,url:r}}_getSign(e,r){constn=r.bizContent||null;deleter.bizContent;consti=Object.assign({method:e,appId:this.options.appId,charset:this.options.charset,version:this.options.version,signType:this.options.signType,timestamp:T((o=this.options.timeOffset,newDate(Date.now()+6e4*((newDate).getTimezoneOffset()+60*(o||0)))))},r);varo;n&&(i.bizContent=JSON.stringify(b(n)));consts=b(i),a=Object.keys(s).sort().map(e=>{lett=s[e];return"[object String]"!==Array.prototype.toString.call(t)&&(t=JSON.stringify(t)),`${e}=${t}`}).join("&"),c=t.createSign(Y[this.options.signType]).update(a,"utf8").sign(this.options.privateKey,"base64");returnObject.assign(s,{sign:c})}async_exec(e,t={},r={}){constn=this._getSign(e,t),{url:i,execParams:o}=this._formatUrl(this.options.gateway,n),{status:s,data:a}=awaituniCloud.httpclient.request(i,{method:"POST",data:o,dataType:"text",timeout:this.options.timeout});if(200!==s)thrownewError("request fail");constc=JSON.parse(a),u=e.replace(/\./g,"_")+"_response",d=c[u],p=c.error_response;if(d){if(!r.validateSign||this._checkResponseSign(a,u)){if(!d.code||"10000"===d.code){return{errCode:0,errMsg:d.msg||"",..._(d)}}conste=d.sub_code?`${d.sub_code}${d.sub_msg}`:""+(d.msg||"unkonwn error");thrownewError(e)}thrownewError("check sign error")}if(p)thrownewError(p.sub_msg||p.msg||"request fail");thrownewError("request fail")}_checkResponseSign(e,r){if(!this.options.alipayPublicKey||""===this.options.alipayPublicKey)returnconsole.warn("options.alipayPublicKey is empty"),!0;if(!e)return!1;constn=this._getSignStr(e,r),i=JSON.parse(e).sign,o=t.createVerify(Y[this.options.signType]);returno.update(n,"utf8"),o.verify(this.options.alipayPublicKey,i,"base64")}_getSignStr(e,t){letr=e.trim();constn=e.indexOf(t+'"'),i=e.lastIndexOf('"sign"');returnr=r.substr(n+t.length+1),r=r.substr(0,i),r=r.replace(/^[^{]*{/g,"{"),r=r.replace(/\}([^}]*)$/g,"}"),r}}{constructor(e){super(e),this._protocols=z}asynccode2Session(e){returnawaitthis._exec("alipay.system.oauth.token",{grantType:"authorization_code",code:e})}}functionJ(e){vart=e[0];returnt<"0"||t>"7"?"00"+e:e}functionZ(e){vart=e.toString(16);returnt.length%2?"0"+t:t}functionee(e){if(e<=127)returnZ(e);vart=Z(e);returnZ(128+t.length/2)+t}functionte(e,t){returne(t={exports:{}},t.exports),t.exports}varre=te((function(e,t){varn=r.Buffer;functioni(e,t){for(varrine)t[r]=e[r]}functiono(e,t,r){returnn(e,t,r)}n.from&&n.alloc&&n.allocUnsafe&&n.allocUnsafeSlow?e.exports=r:(i(r,t),t.Buffer=o),o.prototype=Object.create(n.prototype),i(n,o),o.from=function(e,t,r){if("number"==typeofe)thrownewTypeError("Argument must not be a number");returnn(e,t,r)},o.alloc=function(e,t,r){if("number"!=typeofe)thrownewTypeError("Argument must be a number");vari=n(e);returnvoid0!==t?"string"==typeofr?i.fill(t,r):i.fill(t):i.fill(0),i},o.allocUnsafe=function(e){if("number"!=typeofe)thrownewTypeError("Argument must be a number");returnn(e)},o.allocUnsafeSlow=function(e){if("number"!=typeofe)thrownewTypeError("Argument must be a number");returnr.SlowBuffer(e)}})),ne=(re.Buffer,re.Buffer);functionie(e){if(this.buffer=null,this.writable=!0,this.readable=!0,!e)returnthis.buffer=ne.alloc(0),this;if("function"==typeofe.pipe)returnthis.buffer=ne.alloc(0),e.pipe(this),this;if(e.length||"object"==typeofe)returnthis.buffer=e,this.writable=!1,process.nextTick(function(){this.emit("end",e),this.readable=!1,this.emit("close")}.bind(this)),this;thrownewTypeError("Unexpected data type ("+typeofe+")")}i.inherits(ie,n),ie.prototype.write=function(e){this.buffer=ne.concat([this.buffer,ne.from(e)]),this.emit("data",e)},ie.prototype.end=function(e){e&&this.write(e),this.emit("end",e),this.emit("close"),this.writable=!1,this.readable=!1};varoe=ie,se=r.Buffer,ae=r.SlowBuffer,ce=ue;functionue(e,t){if(!se.isBuffer(e)||!se.isBuffer(t))return!1;if(e.length!==t.length)return!1;for(varr=0,n=0;n<e.length;n++)r|=e[n]^t[n];return0===r}ue.install=function(){se.prototype.equal=ae.prototype.equal=function(e){returnue(this,e)}};varde=se.prototype.equal,pe=ae.prototype.equal;functionle(e){return(e/8|0)+(e%8==0?0:1)}ue.restore=function(){se.prototype.equal=de,ae.prototype.equal=pe};varfe={ES256:le(256),ES384:le(384),ES512:le(521)};varme=function(e){vart=fe[e];if(t)returnt;thrownewError('Unknown algorithm "'+e+'"')},he=re.Buffer;functionge(e){if(he.isBuffer(e))returne;if("string"==typeofe)returnhe.from(e,"base64");thrownewTypeError("ECDSA signature must be a Base64 string or a Buffer")}functionye(e,t,r){for(varn=0;t+n<r&&0===e[t+n];)++n;returne[t+n]>=128&&--n,n}varwe={derToJose:function(e,t){e=ge(e);varr=me(t),n=r+1,i=e.length,o=0;if(48!==e[o++])thrownewError('Could not find expected "seq"');vars=e[o++];if(129===s&&(s=e[o++]),i-o<s)thrownewError('"seq" specified length of "'+s+'", only "'+(i-o)+'" remaining');if(2!==e[o++])thrownewError('Could not find expected "int" for "r"');vara=e[o++];if(i-o-2<a)thrownewError('"r" specified length of "'+a+'", only "'+(i-o-2)+'" available');if(n<a)thrownewError('"r" specified length of "'+a+'", max of "'+n+'" is acceptable');varc=o;if(o+=a,2!==e[o++])thrownewError('Could not find expected "int" for "s"');varu=e[o++];if(i-o!==u)thrownewError('"s" specified length of "'+u+'", expected "'+(i-o)+'"');if(n<u)thrownewError('"s" specified length of "'+u+'", max of "'+n+'" is acceptable');vard=o;if((o+=u)!==i)thrownewError('Expected to consume entire buffer, but "'+(i-o)+'" bytes remain');varp=r-a,l=r-u,f=he.allocUnsafe(p+a+l+u);for(o=0;o<p;++o)f[o]=0;e.copy(f,o,c+Math.max(-p,0),c+a);for(varm=o=r;o<m+l;++o)f[o]=0;returne.copy(f,o,d+Math.max(-l,0),d+u),f=(f=f.toString("base64")).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")},joseToDer:function(e,t){e=ge(e);varr=me(t),n=e.length;if(n!==2*r)thrownewTypeError('"'+t+'" signatures must be "'+2*r+'" bytes, saw "'+n+'"');vari=ye(e,0,r),o=ye(e,r,e.length),s=r-i,a=r-o,c=2+s+1+1+a,u=c<128,d=he.allocUnsafe((u?2:3)+c),p=0;returnd[p++]=48,u?d[p++]=c:(d[p++]=129,d[p++]=255&c),d[p++]=2,d[p++]=s,i<0?(d[p++]=0,p+=e.copy(d,p,0,r)):p+=e.copy(d,p,i,r),d[p++]=2,d[p++]=a,o<0?(d[p++]=0,e.copy(d,p,r)):e.copy(d,p,r+o),d}},ve=re.Buffer,_e="secret must be a string or buffer",be="key must be a string or a buffer",Te="function"==typeoft.createPublicKey;functionEe(e){if(!ve.isBuffer(e)&&"string"!=typeofe){if(!Te)throwIe(be);if("object"!=typeofe)throwIe(be);if("string"!=typeofe.type)throwIe(be);if("string"!=typeofe.asymmetricKeyType)throwIe(be);if("function"!=typeofe.export)throwIe(be)}}functionCe(e){if(!ve.isBuffer(e)&&"string"!=typeofe&&"object"!=typeofe)throwIe("key must be a string, a buffer or an object")}functionAe(e){returne.replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}functionxe(e){vart=4-(e=e.toString()).length%4;if(4!==t)for(varr=0;r<t;++r)e+="=";returne.replace(/\-/g,"+").replace(/_/g,"/")}functionIe(e){vart=[].slice.call(arguments,1),r=i.format.bind(i,e).apply(null,t);returnnewTypeError(r)}functionSe(e){vart;returnt=e,ve.isBuffer(t)||"string"==typeoft||(e=JSON.stringify(e)),e}functionke(e){returnfunction(r,n){!function(e){if(!ve.isBuffer(e)){if("string"==typeofe)returne;if(!Te)throwIe(_e);if("object"!=typeofe)throwIe(_e);if("secret"!==e.type)throwIe(_e);if("function"!=typeofe.export)throwIe(_e)}}(n),r=Se(r);vari=t.createHmac("sha"+e,n);returnAe((i.update(r),i.digest("base64")))}}functionOe(e){returnfunction(t,r,n){vari=ke(e)(t,n);returnce(ve.from(r),ve.from(i))}}functionPe(e){returnfunction(r,n){Ce(n),r=Se(r);vari=t.createSign("RSA-SHA"+e);returnAe((i.update(r),i.sign(n,"base64")))}}functionRe(e){returnfunction(r,n,i){Ee(i),r=Se(r),n=xe(n);varo=t.createVerify("RSA-SHA"+e);returno.update(r),o.verify(i,n,"base64")}}functionje(e){returnfunction(r,n){Ce(n),r=Se(r);vari=t.createSign("RSA-SHA"+e);returnAe((i.update(r),i.sign({key:n,padding:t.constants.RSA_PKCS1_PSS_PADDING,saltLength:t.constants.RSA_PSS_SALTLEN_DIGEST},"base64")))}}functionDe(e){returnfunction(r,n,i){Ee(i),r=Se(r),n=xe(n);varo=t.createVerify("RSA-SHA"+e);returno.update(r),o.verify({key:i,padding:t.constants.RSA_PKCS1_PSS_PADDING,saltLength:t.constants.RSA_PSS_SALTLEN_DIGEST},n,"base64")}}functionqe(e){vart=Pe(e);returnfunction(){varr=t.apply(null,arguments);returnr=we.derToJose(r,"ES"+e)}}functionNe(e){vart=Re(e);returnfunction(r,n,i){returnn=we.joseToDer(n,"ES"+e).toString("base64"),t(r,n,i)}}functionUe(){returnfunction(){return""}}functionLe(){returnfunction(e,t){return""===t}}Te&&(be+=" or a KeyObject",_e+="or a KeyObject");varVe=function(e){vart={hs:ke,rs:Pe,ps:je,es:qe,none:Ue},r={hs:Oe,rs:Re,ps:De,es:Ne,none:Le},n=e.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/i);if(!n)throwIe('"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".',e);vari=(n[1]||n[3]).toLowerCase(),o=n[2];return{sign:t[i](o),verify:r[i](o)}},Me=r.Buffer,Be=function(e){return"string"==typeofe?e:"number"==typeofe||Me.isBuffer(e)?e.toString():JSON.stringify(e)},Fe=re.Buffer;function$e(e,t){returnFe.from(e,t).toString("base64").replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_")}functionHe(e){vart=e.header,r=e.payload,n=e.secret||e.privateKey,o=e.encoding,s=Ve(t.alg),a=function(e,t,r){r=r||"utf8";varn=$e(Be(e),"binary"),o=$e(Be(t),r);returni.format("%s.%s",n,o)}(t,r,o),c=s.sign(a,n);returni.format("%s.%s",a,c)}functionKe(e){vart=e.secret||e.privateKey||e.key,r=newoe(t);this.readable=!0,this.header=e.header,this.encoding=e.encoding,this.secret=this.privateKey=this.key=r,this.payload=newoe(e.payload),this.secret.once("close",function(){!this.payload.writable&&this.readable&&this.sign()}.bind(this)),this.payload.once("close",function(){!this.secret.writable&&this.readable&&this.sign()}.bind(this))}i.inherits(Ke,n),Ke.prototype.sign=function(){try{vare=He({header:this.header,payload:this.payload.buffer,secret:this.secret.buffer,encoding:this.encoding});returnthis.emit("done",e),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}},Ke.sign=He;varGe=Ke,Qe=re.Buffer,Xe=/^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/;functionYe(e){if(function(e){return"[object Object]"===Object.prototype.toString.call(e)}(e))returne;try{returnJSON.parse(e)}catch(e){return}}functionze(e){vart=e.split(".",1)[0];returnYe(Qe.from(t,"base64").toString("binary"))}functionWe(e){returne.split(".")[2]}functionJe(e){returnXe.test(e)&&!!ze(e)}functionZe(e,t,r){if(!t){varn=newError("Missing algorithm parameter for jws.verify");thrown.code="MISSING_ALGORITHM",n}vari=We(e=Be(e)),o=function(e){returne.split(".",2).join(".")}(e);returnVe(t).verify(o,i,r)}functionet(e,t){if(t=t||{},!Je(e=Be(e)))returnnull;varr=ze(e);if(!r)returnnull;varn=function(e,t){t=t||"utf8";varr=e.split(".")[1];returnQe.from(r,"base64").toString(t)}(e);return("JWT"===r.typ||t.json)&&(n=JSON.parse(n,t.encoding)),{header:r,payload:n,signature:We(e)}}functiontt(e){vart=(e=e||{}).secret||e.publicKey||e.key,r=newoe(t);this.readable=!0,this.algorithm=e.algorithm,this.encoding=e.encoding,this.secret=this.publicKey=this.key=r,this.signature=newoe(e.signature),this.secret.once("close",function(){!this.signature.writable&&this.readable&&this.verify()}.bind(this)),this.signature.once("close",function(){!this.secret.writable&&this.readable&&this.verify()}.bind(this))}i.inherits(tt,n),tt.prototype.verify=function(){try{vare=Ze(this.signature.buffer,this.algorithm,this.key.buffer),t=et(this.signature.buffer,this.encoding);returnthis.emit("done",e,t),this.emit("data",e),this.emit("end"),this.readable=!1,e}catch(e){this.readable=!1,this.emit("error",e),this.emit("close")}},tt.decode=et,tt.isValid=Je,tt.verify=Ze;varrt=tt,nt={ALGORITHMS:["HS256","HS384","HS512","RS256","RS384","RS512","PS256","PS384","PS512","ES256","ES384","ES512"],sign:Ge.sign,verify:rt.verify,decode:rt.decode,isValid:rt.isValid,createSign:function(e){returnnewGe(e)},createVerify:function(e){returnnewrt(e)}},it=function(e,t){t=t||{};varr=nt.decode(e,t);if(!r)returnnull;varn=r.payload;if("string"==typeofn)try{vari=JSON.parse(n);null!==i&&"object"==typeofi&&(n=i)}catch(e){}return!0===t.complete?{header:r.header,payload:n,signature:r.signature}:n},ot=function(e,t){Error.call(this,e),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor),this.name="JsonWebTokenError",this.message=e,t&&(this.inner=t)};(ot.prototype=Object.create(Error.prototype)).constructor=ot;varst=ot,at=function(e,t){st.call(this,e),this.name="NotBeforeError",this.date=t};(at.prototype=Object.create(st.prototype)).constructor=at;varct=at,ut=function(e,t){st.call(this,e),this.name="TokenExpiredError",this.expiredAt=t};(ut.prototype=Object.create(st.prototype)).constructor=ut;vardt=ut,pt=1e3,lt=60*pt,ft=60*lt,mt=24*ft,ht=function(e,t){t=t||{};varr=typeofe;if("string"===r&&e.length>0)returnfunction(e){if((e=String(e)).length>100)return;vart=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(!t)return;varr=parseFloat(t[1]);switch((t[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return315576e5*r;case"weeks":case"week":case"w":return6048e5*r;case"days":case"day":case"d":returnr*mt;case"hours":case"hour":case"hrs":case"hr":case"h":returnr*ft;case"minutes":case"minute":case"mins":case"min":case"m":returnr*lt;case"seconds":case"second":case"secs":case"sec":case"s":returnr*pt;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":returnr;default:return}}(e);if("number"===r&&isFinite(e))returnt.long?function(e){vart=Math.abs(e);if(t>=mt)returngt(e,t,mt,"day");if(t>=ft)returngt(e,t,ft,"hour");if(t>=lt)returngt(e,t,lt,"minute");if(t>=pt)returngt(e,t,pt,"second");returne+" ms"}(e):function(e){vart=Math.abs(e);if(t>=mt)returnMath.round(e/mt)+"d";if(t>=ft)returnMath.round(e/ft)+"h";if(t>=lt)returnMath.round(e/lt)+"m";if(t>=pt)returnMath.round(e/pt)+"s";returne+"ms"}(e);thrownewError("val is not a non-empty string or a valid number. val="+JSON.stringify(e))};functiongt(e,t,r,n){vari=t>=1.5*r;returnMath.round(e/r)+""+n+(i?"s":"")}varyt=function(e,t){varr=t||Math.floor(Date.now()/1e3);if("string"==typeofe){varn=ht(e);if(void0===n)return;returnMath.floor(r+n/1e3)}return"number"==typeofe?r+e:void0},wt=te((function(e,t){varr;t=e.exports=G,r="object"==typeofprocess&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?function(){vare=Array.prototype.slice.call(arguments,0);e.unshift("SEMVER"),console.log.apply(console,e)}:function(){},t.SEMVER_SPEC_VERSION="2.0.0";varn=Number.MAX_SAFE_INTEGER||9007199254740991,i=t.re=[],o=t.src=[],s=0,a=s++;o[a]="0|[1-9]\\d*";varc=s++;o[c]="[0-9]+";varu=s++;o[u]="\\d*[a-zA-Z-][a-zA-Z0-9-]*";vard=s++;o[d]="("+o[a]+")\\.("+o[a]+")\\.("+o[a]+")";varp=s++;o[p]="("+o[c]+")\\.("+o[c]+")\\.("+o[c]+")";varl=s++;o[l]="(?:"+o[a]+"|"+o[u]+")";varf=s++;o[f]="(?:"+o[c]+"|"+o[u]+")";varm=s++;o[m]="(?:-("+o[l]+"(?:\\."+o[l]+")*))";varh=s++;o[h]="(?:-?("+o[f]+"(?:\\."+o[f]+")*))";varg=s++;o[g]="[0-9A-Za-z-]+";vary=s++;o[y]="(?:\\+("+o[g]+"(?:\\."+o[g]+")*))";varw=s++,v="v?"+o[d]+o[m]+"?"+o[y]+"?";o[w]="^"+v+"$";var_="[v=\\s]*"+o[p]+o[h]+"?"+o[y]+"?",b=s++;o[b]="^"+_+"$";varT=s++;o[T]="((?:<|>)?=?)";varE=s++;o[E]=o[c]+"|x|X|\\*";varC=s++;o[C]=o[a]+"|x|X|\\*";varA=s++;o[A]="[v=\\s]*("+o[C]+")(?:\\.("+o[C]+")(?:\\.("+o[C]+")(?:"+o[m]+")?"+o[y]+"?)?)?";varx=s++;o[x]="[v=\\s]*("+o[E]+")(?:\\.("+o[E]+")(?:\\.("+o[E]+")(?:"+o[h]+")?"+o[y]+"?)?)?";varI=s++;o[I]="^"+o[T]+"\\s*"+o[A]+"$";varS=s++;o[S]="^"+o[T]+"\\s*"+o[x]+"$";vark=s++;o[k]="(?:^|[^\\d])(\\d{1,16})(?:\\.(\\d{1,16}))?(?:\\.(\\d{1,16}))?(?:$|[^\\d])";varO=s++;o[O]="(?:~>?)";varP=s++;o[P]="(\\s*)"+o[O]+"\\s+",i[P]=newRegExp(o[P],"g");varR=s++;o[R]="^"+o[O]+o[A]+"$";varj=s++;o[j]="^"+o[O]+o[x]+"$";varD=s++;o[D]="(?:\\^)";varq=s++;o[q]="(\\s*)"+o[D]+"\\s+",i[q]=newRegExp(o[q],"g");varN=s++;o[N]="^"+o[D]+o[A]+"$";varU=s++;o[U]="^"+o[D]+o[x]+"$";varL=s++;o[L]="^"+o[T]+"\\s*("+_+")$|^$";varV=s++;o[V]="^"+o[T]+"\\s*("+v+")$|^$";varM=s++;o[M]="(\\s*)"+o[T]+"\\s*("+_+"|"+o[A]+")",i[M]=newRegExp(o[M],"g");varB=s++;o[B]="^\\s*("+o[A]+")\\s+-\\s+("+o[A]+")\\s*$";varF=s++;o[F]="^\\s*("+o[x]+")\\s+-\\s+("+o[x]+")\\s*$";var$=s++;o[$]="(<|>)?=?\\s*\\*";for(varH=0;H<35;H++)r(H,o[H]),i[H]||(i[H]=newRegExp(o[H]));functionK(e,t){if(t&&"object"==typeoft||(t={loose:!!t,includePrerelease:!1}),einstanceofG)returne;if("string"!=typeofe)returnnull;if(e.length>256)returnnull;if(!(t.loose?i[b]:i[w]).test(e))returnnull;try{returnnewG(e,t)}catch(e){returnnull}}functionG(e,t){if(t&&"object"==typeoft||(t={loose:!!t,includePrerelease:!1}),einstanceofG){if(e.loose===t.loose)returne;e=e.version}elseif("string"!=typeofe)thrownewTypeError("Invalid Version: "+e);if(e.length>256)thrownewTypeError("version is longer than 256 characters");if(!(thisinstanceofG))returnnewG(e,t);r("SemVer",e,t),this.options=t,this.loose=!!t.loose;varo=e.trim().match(t.loose?i[b]:i[w]);if(!o)thrownewTypeError("Invalid Version: "+e);if(this.raw=e,this.major=+o[1],this.minor=+o[2],this.patch=+o[3],this.major>n||this.major<0)thrownewTypeError("Invalid major version");if(this.minor>n||this.minor<0)thrownewTypeError("Invalid minor version");if(this.patch>n||this.patch<0)thrownewTypeError("Invalid patch version");o[4]?this.prerelease=o[4].split(".").map((function(e){if(/^[0-9]+$/.test(e)){vart=+e;if(t>=0&&t<n)returnt}returne})):this.prerelease=[],this.build=o[5]?o[5].split("."):[],this.format()}t.parse=K,t.valid=function(e,t){varr=K(e,t);returnr?r.version:null},t.clean=function(e,t){varr=K(e.trim().replace(/^[=v]+/,""),t);returnr?r.version:null},t.SemVer=G,G.prototype.format=function(){returnthis.version=this.major+"."+this.minor+"."+this.patch,this.prerelease.length&&(this.version+="-"+this.prerelease.join(".")),this.version},G.prototype.toString=function(){returnthis.version},G.prototype.compare=function(e){returnr("SemVer.compare",this.version,this.options,e),einstanceofG||(e=newG(e,this.options)),this.compareMain(e)||this.comparePre(e)},G.prototype.compareMain=function(e){returneinstanceofG||(e=newG(e,this.options)),X(this.major,e.major)||X(this.minor,e.minor)||X(this.patch,e.patch)},G.prototype.comparePre=function(e){if(einstanceofG||(e=newG(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return1;if(!this.prerelease.length&&!e.prerelease.length)return0;vart=0;do{varn=this.prerelease[t],i=e.prerelease[t];if(r("prerelease compare",t,n,i),void0===n&&void0===i)return0;if(void0===i)return1;if(void0===n)return-1;if(n!==i)returnX(n,i)}while(++t)},G.prototype.inc=function(e,t){switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",t);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",t);break;case"prepatch":this.prerelease.length=0,this.inc("patch",t),this.inc("pre",t);break;case"prerelease":0===this.prerelease.length&&this.inc("patch",t),this.inc("pre",t);break;case"major":0===this.minor&&0===this.patch&&0!==this.prerelease.length||this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":0===this.patch&&0!==this.prerelease.length||this.minor++,this.patch=0,this.prerelease=[];break;case"patch":0===this.prerelease.length&&this.patch++,this.prerelease=[];break;case"pre":if(0===this.prerelease.length)this.prerelease=[0];else{for(varr=this.prerelease.length;--r>=0;)"number"==typeofthis.prerelease[r]&&(this.prerelease[r]++,r=-2);-1===r&&this.prerelease.push(0)}t&&(this.prerelease[0]===t?isNaN(this.prerelease[1])&&(this.prerelease=[t,0]):this.prerelease=[t,0]);break;default:thrownewError("invalid increment argument: "+e)}returnthis.format(),this.raw=this.version,this},t.inc=function(e,t,r,n){"string"==typeofr&&(n=r,r=void0);try{returnnewG(e,r).inc(t,n).version}catch(e){returnnull}},t.diff=function(e,t){if(J(e,t))returnnull;varr=K(e),n=K(t),i="";if(r.prerelease.length||n.prerelease.length){i="pre";varo="prerelease"}for(varsinr)if(("major"===s||"minor"===s||"patch"===s)&&r[s]!==n[s])returni+s;returno},t.compareIdentifiers=X;varQ=/^[0-9]+$/;functionX(e,t){varr=Q.test(e),n=Q.test(t);returnr&&n&&(e=+e,t=+t),e===t?0:r&&!n?-1:n&&!r?1:e<t?-1:1}functionY(e,t,r){returnnewG(e,r).compare(newG(t,r))}functionz(e,t,r){returnY(e,t,r)>0}functionW(e,t,r){returnY(e,t,r)<0}functionJ(e,t,r){return0===Y(e,t,r)}functionZ(e,t,r){return0!==Y(e,t,r)}functionee(e,t,r){returnY(e,t,r)>=0}functionte(e,t,r){returnY(e,t,r)<=0}functionre(e,t,r,n){switch(t){case"===":return"object"==typeofe&&(e=e.version),"object"==typeofr&&(r=r.version),e===r;case"!==":return"object"==typeofe&&(e=e.version),"object"==typeofr&&(r=r.version),e!==r;case"":case"=":case"==":returnJ(e,r,n);case"!=":returnZ(e,r,n);case">":returnz(e,r,n);case">=":returnee(e,r,n);case"<":returnW(e,r,n);case"<=":returnte(e,r,n);default:thrownewTypeError("Invalid operator: "+t)}}functionne(e,t){if(t&&"object"==typeoft||(t={loose:!!t,includePrerelease:!1}),einstanceofne){if(e.loose===!!t.loose)returne;e=e.value}if(!(thisinstanceofne))returnnewne(e,t);r("comparator",e,t),this.options=t,this.loose=!!t.loose,this.parse(e),this.semver===ie?this.value="":this.value=this.operator+this.semver.version,r("comp",this)}t.rcompareIdentifiers=function(e,t){returnX(t,e)},t.major=function(e,t){returnnewG(e,t).major},t.minor=function(e,t){returnnewG(e,t).minor},t.patch=function(e,t){returnnewG(e,t).patch},t.compare=Y,t.compareLoose=function(e,t){returnY(e,t,!0)},t.rcompare=function(e,t,r){returnY(t,e,r)},t.sort=function(e,r){returne.sort((function(e,n){returnt.compare(e,n,r)}))},t.rsort=function(e,r){returne.sort((function(e,n){returnt.rcompare(e,n,r)}))},t.gt=z,t.lt=W,t.eq=J,t.neq=Z,t.gte=ee,t.lte=te,t.cmp=re,t.Comparator=ne;varie={};functionoe(e,t){if(t&&"object"==typeoft||(t={loose:!!t,includePrerelease:!1}),einstanceofoe)returne.loose===!!t.loose&&e.includePrerelease===!!t.includePrerelease?e:newoe(e.raw,t);if(einstanceofne)returnnewoe(e.value,t);if(!(thisinstanceofoe))returnnewoe(e,t);if(this.options=t,this.loose=!!t.loose,this.includePrerelease=!!t.includePrerelease,this.raw=e,this.set=e.split(/\s*\|\|\s*/).map((function(e){returnthis.parseRange(e.trim())}),this).filter((function(e){returne.length})),!this.set.length)thrownewTypeError("Invalid SemVer Range: "+e);this.format()}functionse(e){return!e||"x"===e.toLowerCase()||"*"===e}functionae(e,t,r,n,i,o,s,a,c,u,d,p,l){return((t=se(r)?"":se(n)?">="+r+".0.0":se(i)?">="+r+"."+n+".0":">="+t)+""+(a=se(c)?"":se(u)?"<"+(+c+1)+".0.0":se(d)?"<"+c+"."+(+u+1)+".0":p?"<="+c+"."+u+"."+d+"-"+p:"<="+a)).trim()}functionce(e,t,n){for(vari=0;i<e.length;i++)if(!e[i].test(t))return!1;if(t.prerelease.length&&!n.includePrerelease){for(i=0;i<e.length;i++)if(r(e[i].semver),e[i].semver!==ie&&e[i].semver.prerelease.length>0){varo=e[i].semver;if(o.major===t.major&&o.minor===t.minor&&o.patch===t.patch)return!0}return!1}return!0}functionue(e,t,r){try{t=newoe(t,r)}catch(e){return!1}returnt.test(e)}functionde(e,t,r,n){vari,o,s,a,c;switch(e=newG(e,n),t=newoe(t,n),r){case">":i=z,o=te,s=W,a=">",c=">=";break;case"<":i=W,o=ee,s=z,a="<",c="<=";break;default:thrownewTypeError('Must provide a hilo val of "<" or ">"')}if(ue(e,t,n))return!1;for(varu=0;u<t.set.length;++u){vard=t.set[u],p=null,l=null;if(d.forEach((function(e){e.semver===ie&&(e=newne(">=0.0.0")),p=p||e,l=l||e,i(e.semver,p.semver,n)?p=e:s(e.semver,l.semver,n)&&(l=e)})),p.operator===a||p.operator===c)return!1;if((!l.operator||l.operator===a)&&o(e,l.semver))return!1;if(l.operator===c&&s(e,l.semver))return!1}return!0}ne.prototype.parse=function(e){vart=this.options.loose?i[L]:i[V],r=e.match(t);if(!r)thrownewTypeError("Invalid comparator: "+e);this.operator=r[1],"="===this.operator&&(this.operator=""),r[2]?this.semver=newG(r[2],this.options.loose):this.semver=ie},ne.prototype.toString=function(){returnthis.value},ne.prototype.test=function(e){returnr("Comparator.test",e,this.options.loose),this.semver===ie||("string"==typeofe&&(e=newG(e,this.options)),re(e,this.operator,this.semver,this.options))},ne.prototype.intersects=function(e,t){if(!(einstanceofne))thrownewTypeError("a Comparator is required");varr;if(t&&"object"==typeoft||(t={loose:!!t,includePrerelease:!1}),""===this.operator)returnr=newoe(e.value,t),ue(this.value,r,t);if(""===e.operator)returnr=newoe(this.value,t),ue(e.semver,r,t);varn=!(">="!==this.operator&&">"!==this.operator||">="!==e.operator&&">"!==e.operator),i=!("<="!==this.operator&&"<"!==this.operator||"<="!==e.operator&&"<"!==e.operator),o=this.semver.version===e.semver.version,s=!(">="!==this.operator&&"<="!==this.operator||">="!==e.operator&&"<="!==e.operator),a=re(this.semver,"<",e.semver,t)&&(">="===this.operator||">"===this.operator)&&("<="===e.operator||"<"===e.operator),c=re(this.semver,">",e.semver,t)&&("<="===this.operator||"<"===this.operator)&&(">="===e.operator||">"===e.operator);returnn||i||o&&s||a||c},t.Range=oe,oe.prototype.format=function(){returnthis.range=this.set.map((function(e){returne.join("").trim()})).join("||").trim(),this.range},oe.prototype.toString=function(){returnthis.range},oe.prototype.parseRange=function(e){vart=this.options.loose;e=e.trim();varn=t?i[F]:i[B];e=e.replace(n,ae),r("hyphen replace",e),e=e.replace(i[M],"$1$2$3"),r("comparator trim",e,i[M]),e=(e=(e=e.replace(i[P],"$1~")).replace(i[q],"$1^")).split(/\s+/).join("");varo=t?i[L]:i[V],s=e.split("").map((function(e){returnfunction(e,t){returnr("comp",e,t),e=function(e,t){returne.trim().split(/\s+/).map((function(e){returnfunction(e,t){r("caret",e,t);varn=t.loose?i[U]:i[N];returne.replace(n,(function(t,n,i,o,s){vara;returnr("caret",e,t,n,i,o,s),se(n)?a="":se(i)?a=">="+n+".0.0 <"+(+n+1)+".0.0":se(o)?a="0"===n?">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":">="+n+"."+i+".0 <"+(+n+1)+".0.0":s?(r("replaceCaret pr",s),a="0"===n?"0"===i?">="+n+"."+i+"."+o+"-"+s+" <"+n+"."+i+"."+(+o+1):">="+n+"."+i+"."+o+"-"+s+" <"+n+"."+(+i+1)+".0":">="+n+"."+i+"."+o+"-"+s+" <"+(+n+1)+".0.0"):(r("no pr"),a="0"===n?"0"===i?">="+n+"."+i+"."+o+" <"+n+"."+i+"."+(+o+1):">="+n+"."+i+"."+o+" <"+n+"."+(+i+1)+".0":">="+n+"."+i+"."+o+" <"+(+n+1)+".0.0"),r("caret return",a),a}))}(e,t)})).join("")}(e,t),r("caret",e),e=function(e,t){returne.trim().split(/\s+/).map((function(e){returnfunction(e,t){varn=t.loose?i[j]:i[R];returne.replace(n,(function(t,n,i,o,s){vara;returnr("tilde",e,t,n,i,o,s),se(n)?a="":se(i)?a=">="+n+".0.0 <"+(+n+1)+".0.0":se(o)?a=">="+n+"."+i+".0 <"+n+"."+(+i+1)+".0":s?(r("replaceTilde pr",s),a=">="+n+"."+i+"."+o+"-"+s+" <"+n+"."+(+i+1)+".0"):a=">="+n+"."+i+"."+o+" <"+n+"."+(+i+1)+".0",r("tilde return",a),a}))}(e,t)})).join("")}(e,t),r("tildes",e),e=function(e,t){returnr("replaceXRanges",e,t),e.split(/\s+/).map((function(e){returnfunction(e,t){e=e.trim();varn=t.loose?i[S]:i[I];returne.replace(n,(function(t,n,i,o,s,a){r("xRange",e,t,n,i,o,s,a);varc=se(i),u=c||se(o),d=u||se(s);return"="===n&&d&&(n=""),c?t=">"===n||"<"===n?"<0.0.0":"*":n&&d?(u&&(o=0),s=0,">"===n?(n=">=",u?(i=+i+1,o=0,s=0):(o=+o+1,s=0)):"<="===n&&(n="<",u?i=+i+1:o=+o+1),t=n+i+"."+o+"."+s):u?t=">="+i+".0.0 <"+(+i+1)+".0.0":d&&(t=">="+i+"."+o+".0 <"+i+"."+(+o+1)+".0"),r("xRange return",t),t}))}(e,t)})).join("")}(e,t),r("xrange",e),e=function(e,t){returnr("replaceStars",e,t),e.trim().replace(i[$],"")}(e,t),r("stars",e),e}(e,this.options)}),this).join("").split(/\s+/);returnthis.options.loose&&(s=s.filter((function(e){return!!e.match(o)}))),s=s.map((function(e){returnnewne(e,this.options)}),this)},oe.prototype.intersects=function(e,t){if(!(einstanceofoe))thrownewTypeError("a Range is required");returnthis.set.some((function(r){returnr.every((function(r){returne.set.some((function(e){returne.every((function(e){returnr.intersects(e,t)}))}))}))}))},t.toComparators=function(e,t){returnnewoe(e,t).set.map((function(e){returne.map((function(e){returne.value})).join("").trim().split("")}))},oe.prototype.test=function(e){if(!e)return!1;"string"==typeofe&&(e=newG(e,this.options));for(vart=0;t<this.set.length;t++)if(ce(this.set[t],e,this.options))return!0;return!1},t.satisfies=ue,t.maxSatisfying=function(e,t,r){varn=null,i=null;try{varo=newoe(t,r)}catch(e){returnnull}returne.forEach((function(e){o.test(e)&&(n&&-1!==i.compare(e)||(i=newG(n=e,r)))})),n},t.minSatisfying=function(e,t,r){varn=null,i=null;try{varo=newoe(t,r)}catch(e){returnnull}returne.forEach((function(e){o.test(e)&&(n&&1!==i.compare(e)||(i=newG(n=e,r)))})),n},t.minVersion=function(e,t){e=newoe(e,t);varr=newG("0.0.0");if(e.test(r))returnr;if(r=newG("0.0.0-0"),e.test(r))returnr;r=null;for(varn=0;n<e.set.length;++n){e.set[n].forEach((function(e){vart=newG(e.semver.version);switch(e.operator){case">":0===t.prerelease.length?t.patch++:t.prerelease.push(0),t.raw=t.format();case"":case">=":r&&!z(r,t)||(r=t);break;case"<":case"<=":break;default:thrownewError("Unexpected operation: "+e.operator)}}))}if(r&&e.test(r))returnr;returnnull},t.validRange=function(e,t){try{returnnewoe(e,t).range||"*"}catch(e){returnnull}},t.ltr=function(e,t,r){returnde(e,t,"<",r)},t.gtr=function(e,t,r){returnde(e,t,">",r)},t.outside=de,t.prerelease=function(e,t){varr=K(e,t);returnr&&r.prerelease.length?r.prerelease:null},t.intersects=function(e,t,r){returne=newoe(e,r),t=newoe(t,r),e.intersects(t)},t.coerce=function(e){if(einstanceofG)returne;if("string"!=typeofe)returnnull;vart=e.match(i[k]);if(null==t)returnnull;returnK(t[1]+"."+(t[2]||"0")+"."+(t[3]||"0"))}})),vt=(wt.SEMVER_SPEC_VERSION,wt.re,wt.src,wt.parse,wt.valid,wt.clean,wt.SemVer,wt.inc,wt.diff,wt.compareIdentifiers,wt.rcompareIdentifiers,wt.major,wt.minor,wt.patch,wt.compare,wt.compareLoose,wt.rcompare,wt.sort,wt.rsort,wt.gt,wt.lt,wt.eq,wt.neq,wt.gte,wt.lte,wt.cmp,wt.Comparator,wt.Range,wt.toComparators,wt.satisfies,wt.maxSatisfying,wt.minSatisfying,wt.minVersion,wt.validRange,wt.ltr,wt.gtr,wt.outside,wt.prerelease,wt.intersects,wt.coerce,wt.satisfies(process.version,"^6.12.0 || >=8.0.0")),_t=["RS256","RS384","RS512","ES256","ES384","ES512"],bt=["RS256","RS384","RS512"],Tt=["HS256","HS384","HS512"];vt&&(_t.splice(3,0,"PS256","PS384","PS512"),bt.splice(3,0,"PS256","PS384","PS512"));varEt=/^\s+|\s+$/g,Ct=/^[-+]0x[0-9a-f]+$/i,At=/^0b[01]+$/i,xt=/^0o[0-7]+$/i,It=/^(?:0|[1-9]\d*)$/,St=parseInt;functionkt(e){returne!=e}functionOt(e,t){returnfunction(e,t){for(varr=-1,n=e?e.length:0,i=Array(n);++r<n;)i[r]=t(e[r],r,e);returni}(t,(function(t){returne[t]}))}varPt,Rt,jt=Object.prototype,Dt=jt.hasOwnProperty,qt=jt.toString,Nt=jt.propertyIsEnumerable,Ut=(Pt=Object.keys,Rt=Object,function(e){returnPt(Rt(e))}),Lt=Math.max;functionVt(e,t){varr=Ft(e)||function(e){returnfunction(e){returnKt(e)&&$t(e)}(e)&&Dt.call(e,"callee")&&(!Nt.call(e,"callee")||"[object Arguments]"==qt.call(e))}(e)?function(e,t){for(varr=-1,n=Array(e);++r<e;)n[r]=t(r);returnn}(e.length,String):[],n=r.length,i=!!n;for(varoine)!t&&!Dt.call(e,o)||i&&("length"==o||Bt(o,n))||r.push(o);returnr}functionMt(e){if(r=(t=e)&&t.constructor,n="function"==typeofr&&r.prototype||jt,t!==n)returnUt(e);vart,r,n,i=[];for(varoinObject(e))Dt.call(e,o)&&"constructor"!=o&&i.push(o);returni}functionBt(e,t){return!!(t=null==t?9007199254740991:t)&&("number"==typeofe||It.test(e))&&e>-1&&e%1==0&&e<t}varFt=Array.isArray;function$t(e){returnnull!=e&&function(e){return"number"==typeofe&&e>-1&&e%1==0&&e<=9007199254740991}(e.length)&&!function(e){vart=Ht(e)?qt.call(e):"";return"[object Function]"==t||"[object GeneratorFunction]"==t}(e)}functionHt(e){vart=typeofe;return!!e&&("object"==t||"function"==t)}functionKt(e){return!!e&&"object"==typeofe}varGt=function(e,t,r,n){vari;e=$t(e)?e:(i=e)?Ot(i,function(e){return$t(e)?Vt(e):Mt(e)}(i)):[],r=r&&!n?function(e){vart=function(e){if(!e)return0===e?e:0;if((e=function(e){if("number"==typeofe)returne;if(function(e){return"symbol"==typeofe||Kt(e)&&"[object Symbol]"==qt.call(e)}(e))returnNaN;if(Ht(e)){vart="function"==typeofe.valueOf?e.valueOf():e;e=Ht(t)?t+"":t}if("string"!=typeofe)return0===e?e:+e;e=e.replace(Et,"");varr=At.test(e);returnr||xt.test(e)?St(e.slice(2),r?2:8):Ct.test(e)?NaN:+e}(e))===1/0||e===-1/0){return17976931348623157e292*(e<0?-1:1)}returne==e?e:0}(e),r=t%1;returnt==t?r?t-r:t:0}(r):0;varo=e.length;returnr<0&&(r=Lt(o+r,0)),function(e){return"string"==typeofe||!Ft(e)&&Kt(e)&&"[object String]"==qt.call(e)}(e)?r<=o&&e.indexOf(t,r)>-1:!!o&&function(e,t,r){if(t!=t)returnfunction(e,t,r,n){for(vari=e.length,o=r+(n?1:-1);n?o--:++o<i;)if(t(e[o],o,e))returno;return-1}(e,kt,r);for(varn=r-1,i=e.length;++n<i;)if(e[n]===t)returnn;return-1}(e,t,r)>-1},Qt=Object.prototype.toString;varXt=function(e){return!0===e||!1===e||function(e){return!!e&&"object"==typeofe}(e)&&"[object Boolean]"==Qt.call(e)},Yt=/^\s+|\s+$/g,zt=/^[-+]0x[0-9a-f]+$/i,Wt=/^0b[01]+$/i,Jt=/^0o[0-7]+$/i,Zt=parseInt,er=Object.prototype.toString;functiontr(e){vart=typeofe;return!!e&&("object"==t||"function"==t)}varrr=function(e){return"number"==typeofe&&e==function(e){vart=function(e){if(!e)return0===e?e:0;if((e=function(e){if("number"==typeofe)returne;if(function(e){return"symbol"==typeofe||function(e){return!!e&&"object"==typeofe}(e)&&"[object Symbol]"==er.call(e)}(e))returnNaN;if(tr(e)){vart="function"==typeofe.valueOf?e.valueOf():e;e=tr(t)?t+"":t}if("string"!=typeofe)return0===e?e:+e;e=e.replace(Yt,"");varr=Wt.test(e);returnr||Jt.test(e)?Zt(e.slice(2),r?2:8):zt.test(e)?NaN:+e}(e))===1/0||e===-1/0){return17976931348623157e292*(e<0?-1:1)}returne==e?e:0}(e),r=t%1;returnt==t?r?t-r:t:0}(e)},nr=Object.prototype.toString;varir=function(e){return"number"==typeofe||function(e){return!!e&&"object"==typeofe}(e)&&"[object Number]"==nr.call(e)};varor=Function.prototype,sr=Object.prototype,ar=or.toString,cr=sr.hasOwnProperty,ur=ar.call(Object),dr=sr.toString,pr=function(e,t){returnfunction(r){returne(t(r))}}(Object.getPrototypeOf,Object);varlr=function(e){if(!function(e){return!!e&&"object"==typeofe}(e)||"[object Object]"!=dr.call(e)||function(e){vart=!1;if(null!=e&&"function"!=typeofe.toString)try{t=!!(e+"")}catch(e){}returnt}(e))return!1;vart=pr(e);if(null===t)return!0;varr=cr.call(t,"constructor")&&t.constructor;return"function"==typeofr&&rinstanceofr&&ar.call(r)==ur},fr=Object.prototype.toString,mr=Array.isArray;varhr=function(e){return"string"==typeofe||!mr(e)&&function(e){return!!e&&"object"==typeofe}(e)&&"[object String]"==fr.call(e)},gr=/^\s+|\s+$/g,yr=/^[-+]0x[0-9a-f]+$/i,wr=/^0b[01]+$/i,vr=/^0o[0-7]+$/i,_r=parseInt,br=Object.prototype.toString;functionTr(e,t){varr;if("function"!=typeoft)thrownewTypeError("Expected a function");returne=function(e){vart=function(e){if(!e)return0===e?e:0;if((e=function(e){if("number"==typeofe)returne;if(function(e){return"symbol"==typeofe||function(e){return!!e&&"object"==typeofe}(e)&&"[object Symbol]"==br.call(e)}(e))returnNaN;if(Er(e)){vart="function"==typeofe.valueOf?e.valueOf():e;e=Er(t)?t+"":t}if("string"!=typeofe)return0===e?e:+e;e=e.replace(gr,"");varr=wr.test(e);returnr||vr.test(e)?_r(e.slice(2),r?2:8):yr.test(e)?NaN:+e}(e))===1/0||e===-1/0){return17976931348623157e292*(e<0?-1:1)}returne==e?e:0}(e),r=t%1;returnt==t?r?t-r:t:0}(e),function(){return--e>0&&(r=t.apply(this,arguments)),e<=1&&(t=void0),r}}functionEr(e){vart=typeofe;return!!e&&("object"==t||"function"==t)}varCr=function(e){returnTr(2,e)},Ar=["RS256","RS384","RS512","ES256","ES384","ES512","HS256","HS384","HS512","none"];vt&&Ar.splice(3,0,"PS256","PS384","PS512");varxr={expiresIn:{isValid:function(e){returnrr(e)||hr(e)&&e},message:'"expiresIn" should be a number of seconds or string representing a timespan'},notBefore:{isValid:function(e){returnrr(e)||hr(e)&&e},message:'"notBefore" should be a number of seconds or string representing a timespan'},audience:{isValid:function(e){returnhr(e)||Array.isArray(e)},message:'"audience" must be a string or array'},algorithm:{isValid:Gt.bind(null,Ar),message:'"algorithm" must be a valid string enum value'},header:{isValid:lr,message:'"header" must be an object'},encoding:{isValid:hr,message:'"encoding" must be a string'},issuer:{isValid:hr,message:'"issuer" must be a string'},subject:{isValid:hr,message:'"subject" must be a string'},jwtid:{isValid:hr,message:'"jwtid" must be a string'},noTimestamp:{isValid:Xt,message:'"noTimestamp" must be a boolean'},keyid:{isValid:hr,message:'"keyid" must be a string'},mutatePayload:{isValid:Xt,message:'"mutatePayload" must be a boolean'}},Ir={iat:{isValid:ir,message:'"iat" should be a number of seconds'},exp:{isValid:ir,message:'"exp" should be a number of seconds'},nbf:{isValid:ir,message:'"nbf" should be a number of seconds'}};functionSr(e,t,r,n){if(!lr(r))thrownewError('Expected "'+n+'" to be a plain object.');Object.keys(r).forEach((function(i){varo=e[i];if(o){if(!o.isValid(r[i]))thrownewError(o.message)}elseif(!t)thrownewError('"'+i+'" is not allowed in "'+n+'"')}))}varkr={audience:"aud",issuer:"iss",subject:"sub",jwtid:"jti"},Or=["expiresIn","notBefore","noTimestamp","audience","issuer","subject","jwtid"],Pr=function(e,t,r,n){vari;if("function"!=typeofr||n||(n=r,r={}),r||(r={}),r=Object.assign({},r),i=n||function(e,t){if(e)throwe;returnt},r.clockTimestamp&&"number"!=typeofr.clockTimestamp)returni(newst("clockTimestamp must be a number"));if(void0!==r.nonce&&("string"!=typeofr.nonce||""===r.nonce.trim()))returni(newst("nonce must be a non-empty string"));varo=r.clockTimestamp||Math.floor(Date.now()/1e3);if(!e)returni(newst("jwt must be provided"));if("string"!=typeofe)returni(newst("jwt must be a string"));vars,a=e.split(".");if(3!==a.length)returni(newst("jwt malformed"));try{s=it(e,{complete:!0})}catch(e){returni(e)}if(!s)returni(newst("invalid token"));varc,u=s.header;if("function"==typeoft){if(!n)returni(newst("verify must be called asynchronous if secret or public key is provided as a callback"));c=t}elsec=function(e,r){returnr(null,t)};returnc(u,(function(t,n){if(t)returni(newst("error in secret or public key callback: "+t.message));varc,d=""!==a[2].trim();if(!d&&n)returni(newst("jwt signature is required"));if(d&&!n)returni(newst("secret or public key must be provided"));if(d||r.algorithms||(r.algorithms=["none"]),r.algorithms||(r.algorithms=~n.toString().indexOf("BEGIN CERTIFICATE")||~n.toString().indexOf("BEGIN PUBLIC KEY")?_t:~n.toString().indexOf("BEGIN RSA PUBLIC KEY")?bt:Tt),!~r.algorithms.indexOf(s.header.alg))returni(newst("invalid algorithm"));try{c=nt.verify(e,s.header.alg,n)}catch(e){returni(e)}if(!c)returni(newst("invalid signature"));varp=s.payload;if(void0!==p.nbf&&!r.ignoreNotBefore){if("number"!=typeofp.nbf)returni(newst("invalid nbf value"));if(p.nbf>o+(r.clockTolerance||0))returni(newct("jwt not active",newDate(1e3*p.nbf)))}if(void0!==p.exp&&!r.ignoreExpiration){if("number"!=typeofp.exp)returni(newst("invalid exp value"));if(o>=p.exp+(r.clockTolerance||0))returni(newdt("jwt expired",newDate(1e3*p.exp)))}if(r.audience){varl=Array.isArray(r.audience)?r.audience:[r.audience];if(!(Array.isArray(p.aud)?p.aud:[p.aud]).some((function(e){returnl.some((function(t){returntinstanceofRegExp?t.test(e):t===e}))})))returni(newst("jwt audience invalid. expected: "+l.join(" or ")))}if(r.issuer&&("string"==typeofr.issuer&&p.iss!==r.issuer||Array.isArray(r.issuer)&&-1===r.issuer.indexOf(p.iss)))returni(newst("jwt issuer invalid. expected: "+r.issuer));if(r.subject&&p.sub!==r.subject)returni(newst("jwt subject invalid. expected: "+r.subject));if(r.jwtid&&p.jti!==r.jwtid)returni(newst("jwt jwtid invalid. expected: "+r.jwtid));if(r.nonce&&p.nonce!==r.nonce)returni(newst("jwt nonce invalid. expected: "+r.nonce));if(r.maxAge){if("number"!=typeofp.iat)returni(newst("iat required when maxAge is specified"));varf=yt(r.maxAge,p.iat);if(void0===f)returni(newst('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'));if(o>=f+(r.clockTolerance||0))returni(newdt("maxAge exceeded",newDate(1e3*f)))}if(!0===r.complete){varm=s.signature;returni(null,{header:u,payload:p,signature:m})}returni(null,p)}))},Rr=function(e,t,r,n){"function"==typeofr?(n=r,r={}):r=r||{};vari="object"==typeofe&&!Buffer.isBuffer(e),o=Object.assign({alg:r.algorithm||"HS256",typ:i?"JWT":void0,kid:r.keyid},r.header);functions(e){if(n)returnn(e);throwe}if(!t&&"none"!==r.algorithm)returns(newError("secretOrPrivateKey must have a value"));if(void0===e)returns(newError("payload is required"));if(i){try{!function(e){Sr(Ir,!0,e,"payload")}(e)}catch(e){returns(e)}r.mutatePayload||(e=Object.assign({},e))}else{vara=Or.filter((function(e){returnvoid0!==r[e]}));if(a.length>0)returns(newError("invalid "+a.join(",")+" option for "+typeofe+" payload"))}if(void0!==e.exp&&void0!==r.expiresIn)returns(newError('Bad "options.expiresIn" option the payload already has an "exp" property.'));if(void0!==e.nbf&&void0!==r.notBefore)returns(newError('Bad "options.notBefore" option the payload already has an "nbf" property.'));try{!function(e){Sr(xr,!1,e,"options")}(r)}catch(e){returns(e)}varc=e.iat||Math.floor(Date.now()/1e3);if(r.noTimestamp?deletee.iat:i&&(e.iat=c),void0!==r.notBefore){try{e.nbf=yt(r.notBefore,c)}catch(e){returns(e)}if(void0===e.nbf)returns(newError('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}if(void0!==r.expiresIn&&"object"==typeofe){try{e.exp=yt(r.expiresIn,c)}catch(e){returns(e)}if(void0===e.exp)returns(newError('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60'))}Object.keys(kr).forEach((function(t){varn=kr[t];if(void0!==r[t]){if(void0!==e[n])returns(newError('Bad "options.'+t+'" option. The payload already has an "'+n+'" property.'));e[n]=r[t]}}));varu=r.encoding||"utf8";if("function"!=typeofn)returnnt.sign({header:o,payload:e,secret:t,encoding:u});n=n&&Cr(n),nt.createSign({header:o,privateKey:t,payload:e,encoding:u}).once("error",n).once("done",(function(e){n(null,e)}))};letjr=[];classDr{constructor(e){this.options=Object.assign({baseUrl:"https://appleid.apple.com",timeout:1e4},e)}async_fetch(e,t){const{baseUrl:r}=this.options;returnuniCloud.httpclient.request(r+e,t)}asyncverifyIdentityToken(e){constt=e.split(".")[0],{kid:r}=JSON.parse(Buffer.from(t,"base64").toString());if(!jr.length)try{jr=awaitthis.getAuthKeys()}catch(e){return{code:10705,msg:e.message}}constn=this.getUsedKey(jr,r);if(!Object.keys(n).length&&!this.fetched)try{jr=awaitthis.getAuthKeys()}catch(e){return{code:10705,msg:e.message}}leti=null;try{i=Pr(e,function(e,t){varr=Buffer.from(e,"base64"),n=Buffer.from(t,"base64"),i=r.toString("hex"),o=n.toString("hex");i=J(i),o=J(o);vars=i.length/2,a=o.length/2,c=ee(s),u=ee(a),d="30"+ee(s+a+c.length/2+u.length/2+2)+"02"+c+i+"02"+u+o;return"-----BEGIN RSA PUBLIC KEY-----\n"+Buffer.from(d,"hex").toString("base64").match(/.{1,64}/g).join("\n")+"\n-----END RSA PUBLIC KEY-----\n"}(n.n,n.e),{algorithms:n.alg})}catch(e){return{code:10705,msg:e.message}}return{code:0,msg:i}}asyncgetAuthKeys(){const{status:e,data:t}=awaitthis._fetch("/auth/keys",{method:"GET",dataType:"json",timeout:this.options.timeout});if(200!==e)thrownewError("request https://appleid.apple.com/auth/keys fail");returnt.keys}getUsedKey(e,t){letr={};for(letn=0;n<e.length;n++){consti=e[n];if(i.kid===t){r=i;break}}returnr}}varqr=function(e={}){returne.appId=e.appid,e.secret=e.appsecret,I(G,e)},Nr=function(e={}){returne.appId=e.appid,e.secret=e.appsecret,I(X,e)},Ur=function(e={}){returne.appId=e.appid,I(W,e)},Lr=function(e={}){returnI(Dr,e)};functionVr(e=6){constt=["2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","J","K","L","M","N","P","Q","R","S","T","U","V","W","X","Y","Z"];letr="";for(letn=0;n<e;n++)r+=t[Math.floor(Math.random()*t.length)];returnr}constMr=O.command;asyncfunctionBr({uid:e,dcloudAppidList:t}={}){if(!e)return{code:N,messageValues:{param:this.t("user-id")}};if(!t||0===t.length||t.some(e=>void0===e))return{code:N,messageValues:{param:this.t("dcloud-appid")}};constr=awaitP.doc(e).get(),n=r&&r.data&&r.data[0];if(!n)return{code:10002};consti=Object.keys(q).reduce((e,t)=>{constr=t,i=function(e,t){returnt.split(".").reduce((e,t)=>e&&e[t],e)}(n,t);returni&&e.push({[r]:i}),e},[]);leto;consts={dcloud_appid:Mr.in(t),_id:Mr.neq(n._id)},a={dcloud_appid:Mr.exists(!1),_id:Mr.neq(n._id)};switch(i.length){case0:return{code:10004};case1:o=Mr.or([Mr.and([i[0],s]),Mr.and([i[0],a])]);break;default:o=Mr.or([Mr.and([Mr.or(i),s]),Mr.and([Mr.or(i),a])])}constc=awaitP.where(o).limit(1).get();returnc&&c.data&&c.data[0]?{code:10005}:{code:0}}constFr=uniCloud.database().command;const$r=uniCloud.database();constHr=uniCloud.database().command;constKr=uniCloud.database();constGr=uniCloud.database();asyncfunctionQr(e){constt=["apiKey","apiSecret"];for(letr=0,n=t.length;r<n;r++){constn=t[r];if(!e[n])thrownewError(this.t("config-param-requred",{param:"service.univerify."+n}))}if(!e.openid||!e.access_token)thrownewError(this.t("config-param-requred",{param:"openid, access_token"}));returnfunction(e,t){constr={0:"",4e3:"缺失参数",4001:"apiKey不存在",4002:"sign校验不通过",4003:"appid不存在",4004:"应用未开通一键登录服务",4005:"应用开通的一键登录服务正在审核中",4006:"服务空间不在白名单中",4100:"账户余额不足",5e3:"获取手机号失败,请稍后重试(或其他未知错误)"};return{...e,msg:r[e.code]?"[getPhoneNumber] 获取手机号: "+r[e.code]:e.errMsg}}(awaituniCloud.getPhoneNumber({provider:"univerify",...e}))}constXr=uniCloud.database();constYr=uniCloud.database();constzr=uniCloud.database();constWr=uniCloud.database().command;constJr=uniCloud.database();constZr=uniCloud.database();consten=uniCloud.database();consttn=uniCloud.database();constrn=uniCloud.database();constnn=uniCloud.database();conston=uniCloud.database();constsn={"mobile-code":function(e){return!!(e.service&&e.service.sms&&e.service.sms.smsKey)},univerify:function(e){return!!(e.service&&e.service.univerify&&e.service.univerify.apiKey)},weixin:function(e){return!!(e.oauth&&e.oauth.weixin&&e.oauth.weixin.appsecret)},qq:function(e){return!!(e.oauth&&e.oauth.qq&&e.oauth.qq.appsecret)},apple:function(e){return!!(e.oauth&&e.oauth.apple&&e.oauth.apple.bundleId)},alipay:function(e){return!!(e.oauth&&e.oauth.alipay&&e.oauth.alipay.privateKey)}};constan=uniCloud.database();varcn=Object.freeze({__proto__:null,addUser:asyncfunction({username:e,nickname:t,password:r,mobile:n,email:i,role:o=[],authorizedApp:s=[]}={}){consta=O.command,c=[];if(!e&&!n&&!i)thrownewError("username, mobile or email required");letu;if(e&&c.push({username:e}),n&&c.push({mobile:n,mobile_confirmed:1}),i&&c.push({email:i,email_confirmed:1}),s.length>0){u=a.and(a.or(c),a.or({dcloud_appid:a.in(s)},{dcloud_appid:a.exists(!1)}));if((awaitP.where(u).limit(1).get()).data.length>0)return{code:10201,messageValues:{type:this.t("username")}}}constd={role:o,nickname:t,dcloud_appid:s,register_date:Date.now()};if(e&&(d.username=e),r){const{passwordHash:e,version:t}=this.encryptPwd(r);d.password=e,t&&(d.password_secret_version=t)}returnn&&(d.mobile=n,d.mobile_confirmed=1),i&&(d.email=i,d.email_confirmed=1),{code:0,uid:(awaitP.add(d)).id}},getUserInfo:asyncfunction({uid:e,field:t}){if(!e)return{code:N,messageValues:{param:this.t("user-id")}};letr;if(t&&t.length){constn={};for(lete=0;e<t.length;e++)n[t[e]]=!0;r=awaitP.doc(e).field(n).get()}elser=awaitP.doc(e).get();return0===r.data.length?{code:80301}:{code:0,msg:"",userInfo:r.data[0]}},getUserInfoByToken:asyncfunction(e){constt=this._verifyToken(e);returnt.code||(deletet.iat,deletet.exp),t},resetPwd:asyncfunction({uid:e,password:t}){const{passwordHash:r,version:n}=this.encryptPwd(t),i={password:r,token:[]};returnn&&(i.password_secret_version=n),E("upRes",awaitP.doc(e).update(i)),{code:0,msg:""}},resetPwdBySms:asyncfunction({mobile:e,code:t,password:r}){constn=awaitthis.verifyCode({mobile:e,code:t,type:"reset-pwd"});if(0!==n.code)returnn;consti=(awaitP.where({mobile:e}).get()).data.filter(e=>void0===e.dcloud_appid||e.dcloud_appid.includes(this.context.APPID));if(0===i.length)return{code:10002};if(i.length>1)return{code:10005};consto=i[0]._id;returnthis.resetPwd({uid:o,password:r})},setAvatar:asyncfunction(e){returnawaitP.doc(e.uid).update({avatar:e.avatar}),{code:0,msg:""}},updatePwd:asyncfunction(e){constt=awaitP.doc(e.uid).get();if(t&&t.data&&t.data.length>0){if(0===this._checkPwd(t.data[0],e.oldPassword).code){const{passwordHash:r,version:n}=this.encryptPwd(e.newPassword),i={password:r,token:[]};n&&(i.password_secret_version=n);returnE("upRes",awaitP.doc(t.data[0]._id).update(i)),{code:0,msg:""}}return{code:40202}}return{code:40201}},updateUser:asyncfunction(e){constt=e.uid;if(!t)return{code:N,messageValues:{param:this.t("user-id")}};deletee.uid;const{username:r,email:n}=e,{usernameToLowerCase:i,emailToLowerCase:o}=this._getConfig();lets=r&&r.trim(),a=n&&n.trim();returns&&(i&&(s=s.toLowerCase()),e.username=s),a&&(o&&(a=a.toLowerCase()),e.email=a),E("update -> upRes",awaitP.doc(t).update(e)),{code:0,msg:""}},banAccount:asyncfunction({uid:e}={}){return$.call(this,{uid:e,status:B})},unbanAccount:asyncfunction({uid:e}={}){return$.call(this,{uid:e,status:M})},closeAccount:asyncfunction({uid:e}={}){return$.call(this,{uid:e,status:F})},openAccount:asyncfunction({uid:e}={}){return$.call(this,{uid:e,status:M})},_getAlipayApi:function(){conste=this.context.PLATFORM,t=this._getConfig();if(!t.oauth||!t.oauth.alipay)thrownewError(this.t("config-param-require",{param:e+".alipay"}));return["appid","privateKey"].forEach(r=>{if(!t.oauth.alipay[r])thrownewError(this.t("config-param-require",{param:`${e}.alipay.${r}`}))}),Ur({...t.oauth.alipay})},_getValidInviteCode:asyncfunction({inviteCode:e}){lett,r=10;e?(r=1,t=e):t=Vr();letn=!1;try{for(;r>0&&!n;){r--;if(0===(awaitP.where({my_invite_code:t}).get()).data.length){n=!0;break}t=Vr()}t=Vr()}catch(e){}returnn?{code:0,inviteCode:t}:e?{code:80401}:{code:80402}},_addUser:asyncfunction(e,{needPermission:t,autoSetDcloudAppid:r=!0}={}){constn=this._getConfig(),i={...e,dcloud_appid:r?[this.context.APPID]:[],register_date:Date.now()},o=(awaitP.add(i)).id;lets;if(n.removePermissionAndRoleFromToken)s=awaitthis.createToken({uid:o,needPermission:t});else{constt=e.role||[];letr;r=0===t.length||t.includes("admin")?[]:awaitthis._getPermissionListByRoleList(t),s=awaitthis.createToken({uid:o,role:t,permission:r})}const{token:a,tokenExpired:c}=s;returnawaitP.doc(o).update({token:[a]}),{token:a,tokenExpired:c,uid:o,type:"register",userInfo:Object.assign({},i,{token:[a]})}},_loginExec:asyncfunction(e,t={}){if(e.status===B)return{code:10001};if(e.status===F)return{code:10006};constr=this._getConfig();letn=e.token||[];"string"==typeofn&&(n=[n]);consti=this._getExpiredToken(n);leto;if(n=n.filter(e=>-1===i.indexOf(e)),r.removePermissionAndRoleFromToken){constr=t.needPermission;o=awaitthis.createToken({uid:e._id,needPermission:r})}else{constt=e.role||[];letr;r=0===t.length||t.includes("admin")?[]:awaitthis._getPermissionListByRoleList(t),o=awaitthis.createToken({uid:e._id,role:t,permission:r})}const{token:s,tokenExpired:a}=o;n.push(s),e.token=n;constc={last_login_date:Date.now(),last_login_ip:this.context.CLIENTIP,token:n,...t.extraData};awaitP.doc(e._id).update(c);constu=Object.assign({},e,c);return{code:0,msg:"",token:s,uid:u._id,username:u.username,type:"login",userInfo:u,tokenExpired:a}},_registerExec:asyncfunction(e,{needPermission:t,autoSetDcloudAppid:r=!0}={}){const{my_invite_code:n}=e;if(this._getConfig().autoSetInviteCode||n){constt=awaitthis._getValidInviteCode({inviteCode:n});if(t.code)returnt;e.my_invite_code=t.inviteCode}const{PLATFORM:i,appId:o,appid:s,APPID:a,uniPlatform:c,appName:u,appVersion:d,appVersionCode:p,channel:l,clientIP:f,CLIENTIP:m,OS:h,osName:g}=this.context;returne.register_env={appid:o||s||a||"",uni_platform:c||i||"",os_name:g||h||"",app_name:u||"",app_version:d||"",app_version_code:p||"",channel:l?l+"":"",client_ip:f||m||""},{code:0,msg:"",...awaitthis._addUser(e,{needPermission:t,autoSetDcloudAppid:r})}},_getWeixinApi:function(){conste=this.context.PLATFORM,t=this._getConfig();if(!t.oauth||!t.oauth.weixin)thrownewError(this.t("config-param-require",{param:e+".weixin"}));return["appid","appsecret"].forEach(r=>{if(!t.oauth.weixin[r])thrownewError(this.t("config-param-require",{param:`${e}.weixin.${r}`}))}),qr({...t.oauth.weixin})},_getQQApi:function(){conste=this.context.PLATFORM,t=this._getConfig();if(!t.oauth||!t.oauth.qq)thrownewError(this.t("config-param-require",{param:e+".qq"}));return["appid","appsecret"].forEach(r=>{if(!t.oauth.qq[r])thrownewError(this.t("config-param-require",{param:`${e}.qq.${r}`}))}),Nr({...t.oauth.qq})},_getMatchedUser:function(e,t){if(0===e.length)return{code:10002};letr;constn={},i={};for(letr=e.length-1;r>=0;r--){consto=e[r];for(lets=0;s<t.length;s++){const{field:a,value:c,fallbackValue:u}=t[s];c&&o[a]===c?(n[a]=o,e.splice(r,1)):u&&o[a]===u&&(n[a]||(n[a]=o),i[a]=!0,e.splice(r,1))}}consto=Object.keys(n);lets;switch(o.length){case0:r=e[0],e.splice(0,1);break;case1:s=o[0],r=n[s];break;default:return{code:10003,messageValues:{target:"用户"}}}returne.length>0?{code:10003,messageValues:{target:"用户"}}:{code:0,msg:"",userMatched:r,fieldMatched:s,isFallbackValueMatched:!!s&&i[s]}},_getCurrentAppUser:function(e){constt=this.context.APPID;returne.filter(e=>void0===e.dcloud_appid||null===e.dcloud_appid||e.dcloud_appid.indexOf(t)>-1||e.dcloud_appid.indexOf(null)>-1)},_checkLoginUserList:function(e){if(e&&1!==e.length)returne[0].status===F?{code:10006}:{code:10005}},setAuthorizedAppLogin:asyncfunction({uid:e,dcloudAppidList:t}={}){if("array"!==m(t))return{code:U,messageValues:{param:"dcloudAppidList",reason:this.t("type-array-required",{param:this.t("dcloud-appid-list")})}};if(t&&0!==t.length){constr=awaitBr.bind(this)({uid:e,dcloudAppidList:t});if(r.code)returnr}returnawaitP.doc(e).update({dcloud_appid:Mr.set(t)}),{code:0}},authorizeAppLogin:asyncfunction({uid:e,dcloudAppid:t}={}){constr=awaitBr.bind(this)({uid:e,dcloudAppidList:[t]});returnr.code?r:(awaitP.doc(e).update({dcloud_appid:Mr.push(t)}),{code:0})},forbidAppLogin:asyncfunction({uid:e,dcloudAppid:t}={}){returne?(awaitP.doc(e).update({dcloud_appid:Mr.pull(t)}),{code:0}):{code:N,messageValues:{param:this.t("user-id")}}},acceptInvite:asyncfunction({uid:e,inviteCode:t}){constr=awaitP.where({_id:Fr.neq(e),inviter_uid:Fr.not(Fr.all([e])),my_invite_code:t}).get();if(1!==r.data.length)return{code:80501,msg:"邀请码无效"};constn=[r.data[0]._id].concat(r.data[0].inviter_uid||[]),i=awaitP.doc(e).field({my_invite_code:!0,inviter_uid:!0}).get();if(0===i.data.length)return{code:80502};if(i.data[0].inviter_uid&&i.data[0].inviter_uid.length>0)return{code:80503,msg:"邀请码不可修改"};consto=Date.now();returnawaitP.doc(e).update({inviter_uid:n,invite_time:o}),awaitP.where({inviter_uid:e}).update({inviter_uid:Fr.push(n)}),{code:0,msg:""}},getInvitedUser:asyncfunction({uid:e,level:t=1,limit:r=20,offset:n=0,needTotal:i=!1}){consto={code:0,msg:"",invitedUser:(awaitP.where({["inviter_uid."+(t-1)]:e}).field({_id:!0,username:!0,mobile:!0,invite_time:!0}).orderBy("invite_time","desc").skip(n).limit(r).get()).data};if(i){constr=awaitP.where({["inviter_uid."+(t-1)]:e}).count();o.total=r.total}returno},setUserInviteCode:asyncfunction({uid:e,myInviteCode:t}){constr=awaitthis._getValidInviteCode({inviteCode:t});returnr.code?r:(awaitP.doc(e).update({my_invite_code:r.inviteCode}),{code:0,msg:"",myInviteCode:r.inviteCode})},loginByAlipay:asyncfunction(e){"string"==typeofe&&(e={code:e});const{needPermission:t,code:r,myInviteCode:n,role:i,type:o}=e,{openid:s}=awaitthis._getAlipayApi().code2Session(r);if(!s)return{code:10501,messageValues:{account:this.t("alipay-account")}};leta=awaitP.where({ali_openid:s}).get();if(a=this._getCurrentAppUser(a.data),a&&a.length>0){if("register"===o)return{code:10502,messageValues:{type:this.t("alipay-account")}};if(1!==a.length)return{code:10005};conste=a[0],r=awaitthis._loginExec(e,{needPermission:t});if(0!==r.code)returnr;const{userInfo:n}=r;return{...r,openid:s,mobileConfirmed:1===n.mobile_confirmed,emailConfirmed:1===n.email_confirmed}}{if("login"===o)return{code:10503,messageValues:{type:this.t("alipay-account")}};conste={ali_openid:s};e.my_invite_code=n,e.role=i;constr=awaitthis._registerExec(e,{needPermission:t});return0!==r.code?r:{...r,openid:s,mobileConfirmed:!1,emailConfirmed:!1}}},loginByEmail:asyncfunction(e){let{email:t,code:r,password:n,myInviteCode:i,type:o,needPermission:s,role:a}=e||{};if(t=t&&t.trim(),!t)return{code:N,messageValues:{param:"邮箱"}};const{emailToLowerCase:c}=this._getConfig();letu=t;c&&(u=t.toLowerCase());constd=awaitthis.verifyCode({email:u,code:r,type:o||"login"});if(0!==d.code)returnd;letp={email:t,email_confirmed:1};constl={field:"email",value:t},f=$r.command;u!==t&&(p=f.or(p,{email:u,email_confirmed:1}),l.fallbackValue=u);letm=awaitP.where(p).get();if(m=this._getCurrentAppUser(m.data),m&&m.length>0){if("register"===o)return{code:10301,messageValues:{type:"邮箱"}};conste=this._getMatchedUser(m,[l]);if(e.code)returne;const{userMatched:t}=e,r=awaitthis._loginExec(t,{needPermission:s});return0!==r.code?r:{...r,email:u}}{if("login"===o)return{code:10302,messageValues:{type:"邮箱"}};conste={email:u,email_confirmed:1},t=n&&n.trim();if(t){const{passwordHash:r,version:n}=this.encryptPwd(t);e.password=r,n&&(e.password_secret_version=n)}e.my_invite_code=i,e.role=a;constr=awaitthis._registerExec(e,{needPermission:s});return0!==r.code?r:{...r,email:u}}},loginBySms:asyncfunction({mobile:e,code:t,password:r,inviteCode:n,myInviteCode:i,type:o,needPermission:s,role:a}){if(!(e=e&&e.trim()))return{code:N,messageValues:{param:this.t("mobile")}};constc=this._getConfig();if(c.forceInviteCode&&!o)thrownewError(this.t("login-with-invite-type-required"));constu=awaitthis.verifyCode({mobile:e,code:t,type:o||"login"});if(0!==u.code)returnu;constd={mobile:e,mobile_confirmed:1};letp=awaitP.where(d).get();if(p=this._getCurrentAppUser(p.data),p&&p.length>0){if("register"===o)return{code:10201,messageValues:{type:this.t("mobile")}};if(1!==p.length)return{code:10005};constt=p[0],r=awaitthis._loginExec(t,{needPermission:s});return0!==r.code?r:{...r,mobile:e}}{constt=Date.now();if("login"===o)return{code:10202,messageValues:{type:this.t("mobile")}};constu={mobile:e,mobile_confirmed:1,register_ip:this.context.CLIENTIP,register_date:t},d=r&&r.trim();if(d){const{passwordHash:e,version:t}=this.encryptPwd(d);u.password=e,t&&(u.password_secret_version=t)}if(n){conste=awaitP.where({my_invite_code:n}).get();if(1!==e.data.length)return{code:10203};u.inviter_uid=[e.data[0]._id].concat(e.data[0].inviter_uid||[]),u.invite_time=t}elseif(c.forceInviteCode)return{code:10203};u.my_invite_code=i,u.role=a;constp=awaitthis._registerExec(u,{needPermission:s});return0!==p.code?p:{...p,mobile:e}}},loginByWeixin:asyncfunction(e){"string"==typeofe&&(e={code:e});const{needPermission:t,platform:r,code:n,myInviteCode:i,role:o,type:s}=e,a=r||this.context.PLATFORM,c=function({clientPlatform:e,userAgent:t}={}){switch(e){case"app":case"app-plus":return"app";case"mp-weixin":return"mp";case"h5":case"web":returnt.indexOf("MicroMessenger")>-1?"h5":"web";default:thrownewError("Unsupported weixin platform")}}({clientPlatform:a,userAgent:this.context.CLIENTUA}),u="mp-weixin"===a,{openid:d,unionid:p,sessionKey:l,accessToken:f,refreshToken:m,expired:h}=awaitthis._getWeixinApi()[u?"code2Session":"getOauthAccessToken"](n);if(!d)return{code:10401,messageValues:{account:"微信openid"}};constg={dcloudAppid:this.context.APPID,openid:d,platform:"weixin-"+c},y=require("uni-open-bridge-common");letw;u?(w={sessionKey:l},awaity.setSessionKey(g,{session_key:l},2592e3)):(w={accessToken:f,refreshToken:m,accessTokenExpired:h},awaity.setUserAccessToken(g,{access_token:f,refresh_token:m,access_token_expired:h},2592e3));constv=Kr.command,_=[{wx_openid:{[a]:d}}];p&&_.push({wx_unionid:p});letb=awaitP.where(v.or(..._)).get();if(b=this._getCurrentAppUser(b.data),b&&b.length>0){if("register"===s)return{code:10402,messageValues:{type:this.t("wechat-account")}};if(1!==b.length)return{code:10005};conste=b[0],r={wx_openid:{[a]:d}};p&&(r.wx_unionid=p);constn=awaitthis._loginExec(e,{needPermission:t,extraData:r});if(0!==n.code)returnn;const{userInfo:i}=n;return{...n,openid:d,unionid:p,...w,mobileConfirmed:1===i.mobile_confirmed,emailConfirmed:1===i.email_confirmed}}{if("login"===s)return{code:10403,messageValues:{type:this.t("wechat-account")}};conste={wx_openid:{[a]:d},wx_unionid:p};e.my_invite_code=i,e.role=o;constr=awaitthis._registerExec(e,{needPermission:t});return0!==r.code?r:{...r,openid:d,unionid:p,...w,mobileConfirmed:!1,emailConfirmed:!1}}},loginByQQ:asyncfunction({code:e,accessToken:t,accessTokenExpired:r,myInviteCode:n,needPermission:i,role:o,type:s}={}){consta=this.context.PLATFORM,c="mp-qq"===a,{openid:u,unionid:d,sessionKey:p}=awaitthis._getQQApi()[c?"code2Session":"getOpenidByToken"]({code:e,accessToken:t});if(!u)return{code:10801,messageValues:{account:"qq openid"}};constl=function({clientPlatform:e}={}){switch(e){case"app":case"app-plus":return"app";case"mp-qq":return"mp";default:thrownewError("Unsupported qq platform")}}({clientPlatform:a}),f={dcloudAppid:this.context.APPID,openid:u,platform:"qq-"+l},m=require("uni-open-bridge-common");leth;c?(h={sessionKey:p},awaitm.setSessionKey(f,{session_key:p},2592e3)):(h={accessToken:t,accessTokenExpired:r},awaitm.setUserAccessToken(f,{access_token:t,access_token_expired:r},r?Math.floor((r-Date.now())/1e3):2592e3));constg=Gr.command,y=[{qq_openid:{[a]:u}}];d&&y.push({qq_unionid:d});letw=awaitP.where(g.or(...y)).get();if(w=this._getCurrentAppUser(w.data),w&&w.length>0){if("register"===s)return{code:10802,messageValues:{type:this.t("qq-account")}};if(1!==w.length)return{code:10005};conste=w[0],t={qq_openid:{[a]:u}};d&&(t.qq_unionid=d);constr=awaitthis._loginExec(e,{needPermission:i,extraData:t});if(0!==r.code)returnr;const{userInfo:n}=r;return{...r,openid:u,unionid:d,...h,mobileConfirmed:1===n.mobile_confirmed,emailConfirmed:1===n.email_confirmed}}{if("login"===s)return{code:10803,messageValues:{type:this.t("qq-account")}};conste={qq_openid:{[a]:u},qq_unionid:d};e.my_invite_code=n,e.role=o;constt=awaitthis._registerExec(e);return0!==t.code?t:{...t,openid:u,unionid:d,...h,mobileConfirmed:!1,emailConfirmed:!1}}},loginByUniverify:asyncfunction({openid:e,access_token:t,password:r,inviteCode:n,myInviteCode:i,type:o,needPermission:s,role:a}){constc=this._getConfig(),u=c&&c.service&&c.service.univerify;if(!u)thrownewError(this.t("uni-verify-config-required"));if(c.forceInviteCode&&!o)thrownewError(this.t("login-with-invite-type-required"));constd=awaitQr.bind(this)({...u,openid:e,access_token:t});if(0!==d.code)returnd;constp=String(d.phoneNumber);letl=awaitP.where({mobile:p,mobile_confirmed:1}).get();if(l=this._getCurrentAppUser(l.data),l&&l.length>0){if("register"===o)return{code:10601,messageValues:{type:this.t("mobile")}};if(1!==l.length)return{code:10005};conste=l[0],t=awaitthis._loginExec(e,{needPermission:s});return0!==t.code?t:{...t,mobile:p}}if("login"===o)return{code:10602,messageValues:{type:this.t("mobile")}};constf=Date.now(),m={mobile:p,my_invite_code:i,mobile_confirmed:1,role:a},h=r&&r.trim();if(h){const{passwordHash:e,version:t}=this.encryptPwd(h);m.password=e,t&&(m.password_secret_version=t)}if(n){lete=awaitP.where({my_invite_code:n}).get();if(1!==e.data.length)return{code:10203};e=e.data[0],m.inviter_uid=[e._id].concat(e.inviter_uid||[]),m.invite_time=f}elseif(c.forceInviteCode)return{code:10203};m.my_invite_code=i;constg=awaitthis._registerExec(m,{needPermission:s});return0!==g.code?g:{...g,mobile:p}},loginByApple:asyncfunction({nickName:e,fullName:t,identityToken:r,myInviteCode:n,type:i,needPermission:o,role:s}){consta=this._getConfig(),c=a&&a.oauth&&a.oauth.apple,u=c&&c.bundleId;if(!u)thrownewError(this.t("config-param-require",{param:"(app || app-plus).apple.bundleId"}));if(!r)return{code:N,messageValues:{param:"identityToken"}};t=e||(t&&Object.keys(t).length>0?t.familyName+t.givenName:"");const{code:d,msg:p}=awaitLr().verifyIdentityToken(r);if(0!==d)return{code:d,msg:p,messageValues:{account:this.t("apple-account")}};const{iss:l,sub:f,aud:m,email:h}=p;if("https://appleid.apple.com"!==l)return{code:10706,messageValues:{account:this.t("apple-account")}};if(!f)return{code:10701,messageValues:{account:this.t("apple-account")}};if(u!==m)return{code:10702,messageValues:{account:this.t("apple-account")}};constg=t||"User-"+(h?h.split("@")[0]:Math.random().toString(32).slice(2));lety=awaitP.where({apple_openid:f}).get();if(y=this._getCurrentAppUser(y.data),y&&y.length>0){if("register"===i)return{code:10703,messageValues:{type:this.t("apple-account")}};if(1!==y.length)return{code:10005};conste=y[0],t=awaitthis._loginExec(e,{needPermission:o});return0!==t.code?t:{...t,openid:f}}if("login"===i)return{code:10704,messageValues:{type:this.t("apple-account")}};constw={nickname:g,apple_openid:f,my_invite_code:n,role:s},v=awaitthis._registerExec(w,{needPermission:o});return0!==v.code?v:{...v,openid:f}},login:asyncfunction({username:e,password:t,queryField:r=[],needPermission:n}){consti=Xr.command,o=[];r&&r.length||(r=["username"]),r.length>1&&console.warn(this.t("query-field-warning"));const{usernameToLowerCase:s,emailToLowerCase:a,passwordErrorLimit:c,passwordErrorRetryTime:u}=this._getConfig(),d={email:{email_confirmed:1},mobile:{mobile_confirmed:1}},p={},l=e&&e.trim();if(!l)return{code:N,messageValues:{param:this.t("username")}};s&&(p.username=l.toLowerCase()),a&&(p.email=l.toLowerCase());constf=[];r.forEach(t=>{o.push({[t]:e,...d[t]});constr={field:t,value:e};"username"===t&&p.username!==e?(o.push({[t]:p.username,...d[t]}),r.fallbackValue=p.username):"email"===t&&p.email!==e&&(o.push({[t]:p.email,...d[t]}),r.fallbackValue=p.email),f.push(r)});letm=awaitP.where(i.or(...o)).get();m=this._getCurrentAppUser(m.data);consth=this.context.CLIENTIP,g=this._getMatchedUser(m,f);if(g.code)returng;const{userMatched:y}=g;letw=y.login_ip_limit||[];w=w.filter(e=>e.last_error_time>Date.now()-1e3*u);letv=w.find(e=>e.ip===h);if(v&&v.error_times>=c)return{code:10103};const_=t&&t.trim();if(!_)return{code:N,messageValues:{param:"密码"}};constb=this._checkPwd(y,_);if(0===b.code){conste=w.indexOf(v);e>-1&&w.splice(e,1);constt={login_ip_limit:w},{passwordHash:r,passwordVersion:i}=b;r&&i&&(t.password=r,t.password_secret_version=i);consto=awaitthis._loginExec(y,{needPermission:n,extraData:t});returno.code,o}returnv?(v.error_times++,v.last_error_time=Date.now()):(v={ip:h,error_times:1,last_error_time:Date.now()},w.push(v)),awaitP.doc(y._id).update({login_ip_limit:w}),{code:10102,msg:"密码错误"}},register:asyncfunction(e){constt=[],r=[{name:"username",desc:this.t("username")},{name:"email",desc:this.t("email"),extraCond:{email_confirmed:1}},{name:"mobile",desc:this.t("mobile"),extraCond:{mobile_confirmed:1}}],{usernameToLowerCase:n,emailToLowerCase:i}=this._getConfig();r.forEach(r=>{consto=r.name;lets=e[o]&&e[o].trim();s?(("username"===r.name&&n||"email"===r.name&&i)&&(s=s.toLowerCase()),e[o]=s,t.push({[o]:s,...r.extraCond})):deletee[o]});const{username:o,email:s,mobile:a,myInviteCode:c,needPermission:u,autoSetDcloudAppid:d=!0}=e;if("needPermission"ine&&deletee.needPermission,"autoSetDcloudAppid"ine&&deletee.autoSetDcloudAppid,0===t.length)return{code:20101,messageValues:{param:this.t("user-unique-param")}};constp=Yr.command;letl=awaitP.where(p.or(...t)).get();if(l=this._getCurrentAppUser(l.data),l&&l.length>0){constt=l[0];if(t.status===F)return{code:10006};for(letn=0;n<r.length;n++){consti=r[n];leto=!0;if(i.extraCond&&(o=Object.keys(i.extraCond).every(e=>t[e]===i.extraCond[e])),t[i.name]===e[i.name]&&o)return{code:20102,messageValues:{type:i.desc}}}}constf=e.password&&e.password.trim();if(!f)return{code:N,messageValues:{param:this.t("password")}};const{passwordHash:m,version:h}=this.encryptPwd(f);e.password=m,h&&(e.password_secret_version=h),e.my_invite_code=c,deletee.myInviteCode;constg=awaitthis._registerExec(e,{needPermission:u,autoSetDcloudAppid:d});return0!==g.code?g:{...g,username:o,email:s,mobile:a}},logout:asyncfunction(e){constt=awaitthis.checkToken(e);if(t.code)returnt;constr=zr.command;returnawaitP.doc(t.uid).update({token:r.pull(e)}),{code:0,msg:""}},getRoleByUid:asyncfunction({uid:e}){if(!e)return{code:N,messageValues:{param:this.t("user-id")}};constt=awaitP.doc(e).get();return0===t.data.length?{code:L}:{code:0,msg:"",role:t.data[0].role||[]}},getPermissionByRole:asyncfunction({roleID:e}){if(!e)return{code:N,messageValues:{param:"roleID"}};if("admin"===e){return{code:0,msg:"",permission:(awaitD.limit(1e3).get()).data.map(e=>e.permission_id)}}constt=awaitj.where({role_id:e}).get();return0===t.data.length?{code:V}:{code:0,msg:"",permission:t.data[0].permission||[]}},getPermissionByUid:asyncfunction({uid:e}={}){constt=awaitP.aggregate().match({_id:e}).project({role:!0}).unwind("$role").lookup({from:"uni-id-roles",localField:"role",foreignField:"role_id",as:"roleDetail"}).unwind("$roleDetail").replaceRoot({newRoot:"$roleDetail"}).end(),r=[],n=[];returnt.data.forEach(e=>{n.push(e.role_id),r.push(...e.permission)}),{code:0,msg:"",role:n,permission:A(r)}},bindRole:asyncfunction({uid:e,roleList:t,reset:r=!1}){constn={};return"string"==typeoft&&(t=[t]),n.role=r?t:Wr.push(t),awaitP.doc(e).update(n),{code:0,msg:""}},bindPermission:asyncfunction({roleID:e,permissionList:t,reset:r=!1}){constn={};return"string"==typeoft&&(t=[t]),n.permission=r?t:Wr.push(t),awaitj.where({role_id:e}).update(n),{code:0,msg:""}},unbindRole:asyncfunction({uid:e,roleList:t}){return"string"==typeoft&&(t=[t]),awaitP.doc(e).update({role:Wr.pull(Wr.in(t))}),{code:0,msg:""}},unbindPermission:asyncfunction({roleID:e,permissionList:t}){return"string"==typeoft&&(t=[t]),awaitj.where({role_id:e}).update({permission:Wr.pull(Wr.in(t))}),{code:0,msg:""}},addRole:asyncfunction({roleID:e,roleName:t,comment:r,permission:n=[]}){returne?"admin"===e?{code:U,messageValues:{param:"roleID",reason:this.t("add-role-admin-is-not-allowed")}}:(awaitj.add({role_id:e,role_name:t,comment:r,permission:n,create_date:Date.now()}),{code:0,msg:""}):{code:N,messageValues:{param:this.t("role-id")}}},addPermission:asyncfunction({permissionID:e,permissionName:t,comment:r}){returne?(awaitD.add({permission_id:e,permission_name:t,comment:r,create_date:Date.now()}),{code:0,msg:""}):{code:N,messageValues:{param:this.t("permission-id")}}},getRoleList:asyncfunction({limit:e=20,offset:t=0,needTotal:r=!0}){constn={code:0,msg:"",roleList:(awaitj.skip(t).limit(e).get()).data};if(r){const{total:e}=awaitj.where({_id:Wr.exists(!0)}).count();n.total=e}returnn},getRoleInfo:asyncfunction(e){constt=awaitj.where({role_id:e}).get();return0===t.data.length?{code:V}:{code:0,...t.data[0]}},updateRole:asyncfunction({roleID:e,roleName:t,comment:r,permission:n}){returne?(awaitj.where({role_id:e}).update({role_name:t,comment:r,permission:n}),{code:0,msg:""}):{code:N,messageValues:{param:this.t("role-id")}}},deleteRole:asyncfunction({roleID:e}){constt=m(e);if("string"===t)e=[e];elseif("array"!==t)thrownewError("typeof roleID must be array or string");returnawaitj.where({role_id:Wr.in(e)}).remove(),awaitP.where({role:Wr.elemMatch(Wr.in(e))}).update({role:Wr.pullAll(e)}),{code:0,msg:""}},getPermissionList:asyncfunction({limit:e=20,offset:t=0,needTotal:r=!0}){constn={code:0,msg:"",permissionList:(awaitD.skip(t).limit(e).get()).data};if(r){const{total:e}=awaitD.where({_id:Wr.exists(!0)}).count();n.total=e}returnn},getPermissionInfo:asyncfunction(e){constt=awaitD.where({permission_id:e}).get();return0===t.data.length?{code:N,messageValues:{param:this.t("permission-id")}}:{code:0,...t.data[0]}},updatePermission:asyncfunction({permissionID:e,permissionName:t,comment:r}){returne?(awaitD.where({permission_id:e}).update({permission_name:t,comment:r}),{code:0,msg:""}):{code:N,messageValues:{param:this.t("permission-id")}}},deletePermission:asyncfunction({permissionID:e}){constt=m(e);if("string"===t)e=[e];elseif("array"!==t)thrownewError("typeof permissionID must be array or string");returnawaitD.where({permission_id:Wr.in(e)}).remove(),awaitj.where({permission:Wr.elemMatch(Wr.in(e))}).update({permission:Wr.pullAll(e)}),{code:0,msg:""}},bindAlipay:asyncfunction({uid:e,code:t,platform:r}){constn=r||this.context.PLATFORM,{openid:i}=awaitthis._getAlipayApi({platform:n}).code2Session(t);if(!i)return{code:60401,messageValues:{account:this.t("alipay-account")}};leto=awaitP.where({ali_openid:i}).get();returno=this._getCurrentAppUser(o.data),o&&o.length>0?{code:60402,messageValues:{type:this.t("alipay-account")}}:(awaitP.doc(e).update({ali_openid:i}),{code:0,openid:i,msg:""})},bindEmail:asyncfunction(e){let{uid:t,email:r,code:n}=e||{};if(r=r&&r.trim(),!r)return{code:N,messageValues:{param:this.t("email")}};if(!n)return{code:N,messageValues:{param:this.t("verify-code")}};const{emailToLowerCase:i}=this._getConfig();i&&(r=r.toLowerCase());leto=awaitP.where({email:r,email_confirmed:1}).get();if(o=this._getCurrentAppUser(o.data),o&&o.length>0)return{code:60201,messageValues:{type:this.t("email")}};consts=awaitthis.verifyCode({email:r,code:n,type:"bind"});return0!==s.code?s:(awaitP.doc(t).update({email:r,email_confirmed:1}),{code:0,msg:"",email:r})},bindMobile:asyncfunction(e){let{uid:t,mobile:r,code:n,openid:i,access_token:o,type:s="sms"}=e||{};if("univerify"===s){conste=this._getConfig(),t=e&&e.service&&e.service.univerify;if(!t)thrownewError("请在config.json中配置service.univerify下一键登录相关参数");constn=awaitQr.bind(this)({...t,openid:i,access_token:o});if(0!==n.code)returnn;r=""+n.phoneNumber}leta=awaitP.where({mobile:r,mobile_confirmed:1}).get();if(a=this._getCurrentAppUser(a.data),a&&a.length>0)return{code:60101,messageValues:{type:"手机号"}};if("sms"===s&&"code"ine){if(!r)return{code:N,messageValues:{param:this.t("mobile")}};if(!n)return{code:N,messageValues:{param:this.t("verify-code")}};conste=awaitthis.verifyCode({mobile:r,code:n,type:"bind"});if(0!==e.code)returne}returnawaitP.doc(t).update({mobile:r,mobile_confirmed:1}),{code:0,msg:"",mobile:r}},bindWeixin:asyncfunction({uid:e,code:t,platform:r}){constn=r||this.context.PLATFORM,i="mp-weixin"===n,{openid:o,unionid:s,sessionKey:a,accessToken:c,refreshToken:u,expired:d}=awaitthis._getWeixinApi({platform:n})[i?"code2Session":"getOauthAccessToken"](t);if(!o)return{code:60301,messageValues:{account:"微信openid"}};constp=Jr.command,l=[{wx_openid:{[n]:o}}];s&&l.push({wx_unionid:s});letf=awaitP.where(p.or(...l)).get();if(f=this._getCurrentAppUser(f.data),f&&f.length>0)return{code:60302,messageValues:{type:this.t("wechat-account")}};constm={wx_openid:{[n]:o}};leth;returns&&(m.wx_unionid=s),awaitP.doc(e).update(m),h=i?{sessionKey:a}:{accessToken:c,refreshToken:u,accessTokenExpired:d},{code:0,msg:"",openid:o,unionid:s,...h}},bindQQ:asyncfunction({uid:e,code:t,accessToken:r,platform:n}={}){consti=n||this.context.PLATFORM,o="mp-qq"===i,{openid:s,unionid:a,sessionKey:c}=awaitthis._getQQApi()[o?"code2Session":"getOpenidByToken"]({code:t,accessToken:r});if(!s)return{code:60501,messageValues:{account:"qq openid"}};constu=Zr.command,d=[{qq_openid:{[i]:s}}];a&&d.push({qq_unionid:a});letp=awaitP.where(u.or(...d)).get();if(p=this._getCurrentAppUser(p.data),p&&p.length>0)return{code:60502,messageValues:{type:this.t("qq-account")}};constl={qq_openid:{[i]:s}};returna&&(l.qq_unionid=a),awaitP.doc(e).update(l),{code:0,msg:"",openid:s,unionid:a,...{accessToken:r,sessionKey:c}}},unbindAlipay:asyncfunction(e){constt=en.command,r=awaitP.doc(e).update({ali_openid:t.remove()});returnE("upRes:",r),1===r.updated?{code:0,msg:""}:{code:70401}},unbindEmail:asyncfunction(e){let{uid:t,email:r,code:n}=e||{};if(r=r&&r.trim(),!t||!r)return{code:N,messageValues:{param:t?this.t("email"):this.t("user-id")}};const{emailToLowerCase:i}=this._getConfig();if("code"ine){conste=awaitthis.verifyCode({email:r,code:n,type:"unbind"});if(0!==e.code)returne}consto=tn.command;lets={_id:t,email:r};if(i){conste=r.toLowerCase();e!==r&&(s=o.or(s,{_id:t,email:e}))}return1===(awaitP.where(s).update({email:o.remove(),email_confirmed:o.remove()})).updated?{code:0,msg:""}:{code:70201}},unbindMobile:asyncfunction(e){const{uid:t,mobile:r,code:n}=e||{};if("code"ine){conste=awaitthis.verifyCode({mobile:r,code:n,type:"unbind"});if(0!==e.code)returne}consti=rn.command;return1===(awaitP.where({_id:t,mobile:r}).update({mobile:i.remove(),mobile_confirmed:i.remove()})).updated?{code:0,msg:""}:{code:70101}},unbindWeixin:asyncfunction(e){constt=nn.command,r=awaitP.doc(e).update({wx_openid:t.remove(),wx_unionid:t.remove()});returnE("upRes:",r),1===r.updated?{code:0,msg:""}:{code:70301}},unbindQQ:asyncfunction(e){constt=on.command,r=awaitP.doc(e).update({qq_openid:t.remove(),qq_unionid:t.remove()});returnE("upRes:",r),1===r.updated?{code:0,msg:""}:{code:70501}},getSupportedLoginType:function({appid:e,platform:t}={}){if(!e||!t)thrownewError("Parameter appid and platform is required");constr=this._getConfig({appid:e,platform:t}),n=["username-password","mobile-password","email-password"];for(consteinsn)sn[e](r)&&n.push(e);return{supportedLoginType:n}},code2SessionAlipay:asyncfunction(e){lett=e;"string"==typeofe&&(t={code:e});try{conste=t.platform||this.context.PLATFORM,r=awaitthis._getAlipayApi({platform:e}).code2Session(t.code);returnr.openid?{code:0,msg:"",...r}:{code:80701,messageValues:{account:this.t("alipay-account")}}}catch(e){returnconsole.error(e),{code:80702,messageValues:{account:this.t("alipay-account")}}}},code2SessionWeixin:asyncfunction(e){lett=e;"string"==typeofe&&(t={code:e});try{conste=t.platform||this.context.PLATFORM,r=awaitthis._getWeixinApi({platform:e})["mp-weixin"===e?"code2Session":"getOauthAccessToken"](t.code);returnr.openid?{code:0,msg:"",...r}:{code:80601,messageValues:{account:"微信openid"}}}catch(e){returnconsole.error(e),{code:80602,messageValues:{account:"微信openid"}}}},verifyAppleIdentityToken:asyncfunction({identityToken:e,platform:t}){constr=t||this.context.PLATFORM,{code:n,msg:i}=awaitLr({clientType:r}).verifyIdentityToken(e);return0!==n?{code:n,msg:i}:{code:n,msg:"验证通过",...i}},wxBizDataCrypt:asyncfunction({code:e,sessionKey:r,encryptedData:n,iv:i}){if(!n)return{code:N,messageValues:{param:"encryptedData"}};if(!i)return{code:N,messageValues:{param:"iv"}};if(!e&&!r)return{code:N,messageValues:{param:"sessionKey"}};consto=this._getWeixinApi();if(!r){constt=awaito.code2Session(e);if(!t.sessionKey)return{code:80801};r=t.sessionKey}r=Buffer.from(r,"base64"),n=Buffer.from(n,"base64"),i=Buffer.from(i,"base64");try{vars=t.createDecipheriv("aes-128-cbc",r,i);s.setAutoPadding(!0);vara=s.update(n,"binary","utf8");a+=s.final("utf8"),a=JSON.parse(a)}catch(e){returnconsole.error(e),{code:80802}}returna.watermark.appid!==o.options.appId?{code:80803}:{code:0,msg:"",...a}},getWeixinUserInfo:asyncfunction({accessToken:e,openid:t}={}){constr=this.context.PLATFORM;if("app"!==r&&"app-plus"!==r)thrownewError(this.t("limit-client-platform"));try{return{code:0,msg:"",...awaitthis._getWeixinApi().getUserInfo({accessToken:e,openid:t})}}catch(e){returnconsole.error(e),{code:80901}}},encryptPwd:function(e,{value:r,version:n}={}){if(!(e=e&&e.trim()))thrownewError(this.t("param-required",{param:this.t("password")}));if(!r){conste=this._getConfig(),{passwordSecret:t}=e;if("array"===m(t)){conste=t.sort((e,t)=>e.version-t.version);r=e[e.length-1].value,n=e[e.length-1].version}elser=t}if(!r)thrownewError(this.t("param-error",{param:"passwordSecret",reason:"invalid passwordSecret"}));consti=t.createHmac("sha1",r.toString("ascii"));returni.update(e),{passwordHash:i.digest("hex"),version:n}},checkToken:asyncfunction(e,{needPermission:t,needUserInfo:r=!0}={}){constn=this._getConfig(),i=this._verifyToken(e);if(i.code)returni;const{uid:o,needPermission:s,role:a,permission:c,exp:u,iat:d,...p}=i,l=a&&c;t=void0===t?s:t;constf=n.removePermissionAndRoleFromToken||!l||r,m=!n.removePermissionAndRoleFromToken&&!l||n.removePermissionAndRoleFromToken&&l||n.tokenExpiresThreshold&&u-Date.now()/1e3<n.tokenExpiresThreshold;leth={};if(f||m){constt=awaitP.doc(o).get();if(!t.data||0===t.data.length||!t.data[0].token)return{code:30202};if(h=t.data[0],h.status===B)return{code:10001};if(h.status===F)return{code:10006};letr=h.token;if(r?"string"==typeofr&&(r=[r]):r=[],-1===r.indexOf(e))return{code:30202}}constg={code:0,uid:o,...p};lety,w;if(l&&(g.role=a,g.permission=c),r&&(g.userInfo=h),(!l&&t||m)&&(y=g.role=h.role||[],w=0===y.length||y.includes("admin")?g.permission=[]:g.permission=awaitthis._getPermissionListByRoleList(g.role),t&&(g.role=y,g.permission=w)),m){lete;e=n.removePermissionAndRoleFromToken?awaitthis.createToken({uid:o,needPermission:s}):awaitthis.createToken({uid:o,role:y,permission:w});constt=h.token;returnawaitthis._updateToken({uid:o,tokenList:t,addToken:[e.token]}),{...g,...e}}returng},createToken:function({uid:e,needPermission:t,role:r,permission:n}){if(!e)return{code:30101,messageValues:{param:this.t("user-id")}};consti={uid:e,needPermission:t,role:r,permission:n},o=this._getConfig();if(!this.interceptorMap.has("customToken")){conste={...i};returnthis._createTokenInternal({signContent:e,config:o})}consts=this.interceptorMap.get("customToken");if("function"!=typeofs)thrownewError(this.t("type-function-required","customToken"));consta=s(i);returnainstanceofPromise?a.then(e=>this._createTokenInternal({signContent:e,config:o})):this._createTokenInternal({signContent:a,config:o})},_updateToken:asyncfunction({uid:e,tokenList:t,removeToken:r=[],addToken:n=[]}={}){if(!t){constr=awaitP.doc(e).get(),n=r.data&&r.data[0];t=n&&n.token||[]}"string"==typeoft&&(t=[t]);consti=this._getExpiredToken(t);(t=t.filter(e=>-1===i.indexOf(e))).push(...n);for(lete=0;e<r.length;e++){constn=t.indexOf(r[e]);t.splice(n,1)}awaitP.doc(e).update({token:t,last_login_date:Date.now(),last_login_ip:this.context.CLIENTIP})},refreshToken:asyncfunction({token:e}={}){constt=this._getConfig(),r=this._verifyToken(e);if(r.code)returnr;const{uid:n,needPermission:i}=r;leto;if(t.removePermissionAndRoleFromToken)o=awaitthis.createToken({uid:n,needPermission:i});else{const{role:e,permission:t}=awaitthis.getPermissionByUid({uid:n});o=awaitthis.createToken({uid:n,role:e,permission:t})}returnawaitthis._updateToken({uid:n,addToken:[o.token],removeToken:[e]}),o},_checkPwd:function(e,t){if(!t)return{code:1};const{password:r,password_secret_version:n}=e,i=this._getConfig(),{passwordSecret:o}=i,s=m(o);if("string"===s){const{passwordHash:e}=this.encryptPwd(t,{value:o});returne===r?{code:0,message:""}:{code:2}}if("array"!==s)thrownewError(this.t("password-secret-type-error"));consta=o.sort((e,t)=>e.version-t.version);letc;if(c=n?a.find(e=>e.version===n):a[0],!c)return{code:3};constu=a[a.length-1],{passwordHash:d}=this.encryptPwd(t,c);if(d===r){conste={code:0};if(c!==u){const{passwordHash:r,version:n}=this.encryptPwd(t,u);e.passwordHash=r,e.passwordVersion=n}returne}return{code:4,message:""}},_verifyToken:function(e){constt=this._getConfig();letr;try{r=Pr(e,t.tokenSecret)}catch(e){return"TokenExpiredError"===e.name?{code:30203,err:e}:{code:30204,err:e}}returnt.bindTokenToDevice&&r.clientId&&r.clientId!==this._getClientUaHash()?{code:30201}:{code:0,message:"",...r}},_getExpiredToken:function(e){constt=this._getConfig(),r=[];returne.forEach(e=>{try{Pr(e,t.tokenSecret)}catch(t){r.push(e)}}),r},_getPermissionListByRoleList:asyncfunction(e){if(!Array.isArray(e))return[];if(0===e.length)return[];if(e.includes("admin")){return(awaitD.limit(500).get()).data.map(e=>e.permission_id)}constt=awaitj.where({role_id:Hr.in(e)}).get(),r=[];returnt.data.forEach(e=>{Array.prototype.push.apply(r,e.permission)}),A(r)},_getClientUaHash:function(){conste=t.createHash("md5"),r=/MicroMessenger/i.test(this.context.CLIENTUA)?this.context.CLIENTUA.replace(/(MicroMessenger\S+).*/i,"$1"):this.context.CLIENTUA;returne.update(r),e.digest("hex")},_createTokenInternal:function({signContent:e,config:t}){if(t.tokenExpiresIn&&t.tokenExpiresThreshold&&t.tokenExpiresIn<=t.tokenExpiresThreshold)thrownewError(this.t("token-expires-config-warning"));return"object"===m(e)&&e.uid?(t.bindTokenToDevice&&(e.clientId=this._getClientUaHash()),{token:Rr(e,t.tokenSecret,{expiresIn:t.tokenExpiresIn}),tokenExpired:Date.now()+1e3*t.tokenExpiresIn}):{code:30101,messageValues:{param:this.t("user-id")}}},setVerifyCode:asyncfunction({mobile:e,email:t,code:r,expiresIn:n,type:i}){if(t=t&&t.trim(),e=e&&e.trim(),t){const{emailToLowerCase:e}=this._getConfig();e&&(t=t.toLowerCase())}if(!e&&!t)return{code:50101,messageValues:{param:"手机号或邮箱"}};if(e&&t)return{code:50102,messageValues:{param:"参数",reason:"手机号和邮箱不可同时存在"}};r||(r=C()),n||(n=180);consto=Date.now(),s={mobile:e,email:t,type:i,code:r,state:0,ip:this.context.CLIENTIP,created_at:o,expired_at:o+1e3*n};returnawaitR.add(s),{code:0,mobile:e,email:t}},verifyCode:asyncfunction({mobile:e,email:t,code:r,type:n}){if(t=t&&t.trim(),e=e&&e.trim(),t){const{emailToLowerCase:e}=this._getConfig();e&&(t=t.toLowerCase())}if(!e&&!t)return{code:50201,messageValues:{param:"手机号或邮箱"}};if(e&&t)return{code:50203,messageValues:{param:"参数",reason:"手机号和邮箱不可同时存在"}};if(!r)return{code:50202,messageValues:{type:this.t(e?"sms":"email")}};consti=an.command,o=Date.now(),s={mobile:e,email:t,type:n,code:r,state:0,expired_at:i.gt(o)},a=awaitR.where(s).orderBy("created_at","desc").limit(1).get();if(a&&a.data&&a.data.length>0){conste=a.data[0];returnawaitR.doc(e._id).update({state:1}),{code:0,msg:"验证通过"}}return{code:50202,messageValues:{type:this.t(e?"sms":"email")}}},sendSmsCode:asyncfunction({mobile:e,code:t,type:r,templateId:n}){if(!e)return{code:N,messageValues:{param:this.t("mobile")}};if(t||(t=C()),!r)return{code:N,messageValues:{param:this.t("verify-code-type")}};consti=this._getConfig();leto=i&&i.service&&i.service.sms;if(!o)thrownewError(this.t("config-param-required",{param:"service.sms"}));o=Object.assign({codeExpiresIn:300},o);consts=["smsKey","smsSecret"];for(lete=0,t=s.length;e<t;e++){constt=s[e];if(!o[t])thrownewError(this.t("config-param-required",{param:"service.sms."+t}))}const{name:a,smsKey:c,smsSecret:u,codeExpiresIn:d}=o;letp;switch(r){case"login":p=this.t("login");break;default:p=this.t("verify-mobile")}try{consti={name:a,code:t,action:p,expMinute:""+Math.round(d/60)};a&&(i.name=a),awaituniCloud.sendSms({smsKey:c,smsSecret:u,phone:e,templateId:n||"uniID_code",data:i});consto=awaitthis.setVerifyCode({mobile:e,code:t,expiresIn:d,type:r});returno.code>=0?o:{code:0,msg:""}}catch(e){returnconsole.error(e),{code:50301}}}});letun;try{un=require("uni-config-center")}catch(e){thrownewError("Plugin[uni-config-center] was not found")}classdn{constructor({context:e,clientInfo:t,config:r}={}){constn=un({pluginId:"uni-id"});this.pluginConfig=n,this.config=r||this._getConfigContent(),this._configCache={},Object.defineProperty(this,"context",{get(){letr;r=t?{OS:t.os,CLIENTIP:t.clientIP,CLIENTUA:t.userAgent,PLATFORM:t.platform,APPID:t.appId,LOCALE:t.locale,DEVICEID:t.deviceId}:Object.assign({},e||global.__ctx__||{});constn=["CLIENTIP","PLATFORM","APPID","LOCALE"];for(lete=0;e<n.length;e++){constt=n[e];void0===r[t]&&console.warn(i.t("context-required",{key:t}))}consto=r.APPID,s=r.PLATFORM,a=this._getAppConfig(this.config,o);if(!a)thrownewError(`Config for current app (${o}) was not found, please check your config file or client appId`);if("app"===s||"app-plus"===s?r.PLATFORM=a.preferedAppPlatform||s:"web"!==s&&"h5"!==s||(r.PLATFORM=a.preferedWebPlatform||s),"app"===r.PLATFORM&&a["app-plus"]||"app-plus"===r.PLATFORM&&a.app)thrownewError(`Client platform is ${r.PLATFORM}, but ${"app"===r.PLATFORM?"app-plus":"app"} was found in config. Please refer to: https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=prefered-app-platform`);if("web"===r.PLATFORM&&a.h5||"h5"===r.PLATFORM&&a.web)thrownewError(`Client platform is ${r.PLATFORM}, but ${"web"===r.PLATFORM?"h5":"web"} was found in config. Please refer to: https://uniapp.dcloud.net.cn/uniCloud/uni-id?id=prefered-web-platform`);returnr}}),this.interceptorMap=newMap,n&&n.hasFile("custom-token.js")&&this.setInterceptor("customToken",require(n.resolve("custom-token.js")));leti,o=k;if(n&&n.hasFile("lang/index.js")){conste=n.requireFile("lang/index.js");o=function(e,t){constr=Object.keys(e);r.push(...Object.keys(t));constn={};for(leti=0;i<r.length;i++){consto=r[i];n[o]=Object.assign({},e[o],t[o])}returnn}(k,e)}if(!uniCloud.initI18n)thrownewError("The HBuilderX version is too old, please upgrade to the latest version of HBuilderX");i=uniCloud.initI18n({locale:"en",fallbackLocale:"zh-Hans",messages:o}),Object.defineProperty(this,"t",{get(){returni.setLocale(this.context.LOCALE||"zh-Hans"),i.t.bind(i)}})}getdev(){returnconsole.warn(this.t("dev-warning")),{getConfig:this._getConfig.bind(this)}}_getAppConfig(e,t){returnArray.isArray(e)?e.find(e=>e.dcloudAppid===t)||e.find(e=>e.isDefaultConfig):e}_parseConfigContent(e){returnArray.isArray(e)?e:e[0]?Object.values(e):e}_getConfigContent(){if(this.pluginConfig&&this.pluginConfig.hasFile("config.json")){lete;try{e=this.pluginConfig.config()}catch(e){thrownewError("Invalid uni-id config file\n"+e.message)}returnthis._parseConfigContent(e)}{lete;try{e=require("./config.json")}catch(e){if("MODULE_NOT_FOUND"===e.code||"ENOENT"===e.code)thrownewError("uni-id config file[uniCloud/cloudfunctions/common/uni-config-center/uni-id/config.json] not found");throwe}returnthis._parseConfigContent(e)}}init(){thrownewError("uniID.init has been deprecated, use uniID.createInstance instead")}setInterceptor(e,t){this.interceptorMap.set(e,t)}_getConfig({appid:e,platform:t}={}){constr=`${e=e||this.context.APPID}_${t=t||this.context.PLATFORM}`;if(this._configCache[r])returnthis._configCache[r];if(!(this.config&&0!==Object.keys(this.config).length))thrownewError(this.t("config-file-not-found"));constn=this._getAppConfig(this.config,e);"app"!==t&&"app-plus"!==t||(t=n.preferedAppPlatform||t),"web"!==t&&"h5"!==t||(t=n.preferedWebPlatform||t);consti=Object.assign(n,n[t])||{},o=Object.assign({bindTokenToDevice:!1,tokenExpiresIn:7200,tokenExpiresThreshold:1200,passwordErrorLimit:6,passwordErrorRetryTime:3600,usernameToLowerCase:!0,emailToLowerCase:!0},i);return["passwordSecret","tokenSecret","tokenExpiresIn","passwordErrorLimit","passwordErrorRetryTime"].forEach(e=>{if(!o||!o[e])thrownewError(this.t("config-param-required",{param:e}))}),this._configCache[r]=o,o}}for(consteincn)dn.prototype[e]=cn[e];functionpn(e){constt=newdn(e);returnnewProxy(t,{get(e,t){if(tine&&0!==t.indexOf("_")){if("function"==typeofe[t])return(r=e[t],function(){conste=r.apply(this,arguments);returnf(e)?e.then(e=>(S.bind(this)(e),e)):(S.bind(this)(e),e)}).bind(e);if("context"!==t&&"config"!==t)returne[t]}varr}})}dn.prototype.createInstance=pn;varln=pn();module.exports=ln;