"use strict";var ex,WxmpRsa=(ex=require("wxmp-rsa"))&&"object"==typeof ex&&"default"in ex?ex.default:ex;function __awaiter(e,t,n,i){return new(n||(n=Promise))(function(r,o){function a(e){try{c(i.next(e))}catch(e){o(e)}}function s(e){try{c(i.throw(e))}catch(e){o(e)}}function c(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n(function(e){e(t)})).then(a,s)}c((i=i.apply(e,t||[])).next())})}const JGCons={Host:"https://smartop-sdkapi.jiguang.cn",ReportHost:"https://mini-stats.jpush.cn",RegisterHost:"https://user.jpush.cn",KEY_JIGUANG_UID:"jg_uid",KEY_JIGUANG_PASSWORD:"jg_password",KEY_JIGUANG_REGISTRATIONID:"jg_registrtionid",KEY_JIGUANG_CUID:"jg_cuid",KEY_JIGUANG_ORGID:"jg_orgid",KEY_JIGUANG_DATASOURCEID:"jg_datasourceid",KEY_JIGUANG_INSTALLDATE:"jg_installdate",SDK_VERSION:"2.0.7",DEFAULT_CHANNEL:"default-channel",LOG_TAG_PREFIX:"[JIGUANG-JOperate]",LOCAL:{DEVICEID:"DEVICEID",APPKEY:"APPKEY",CACHE_FAIL:"FAILCACHE",CACHE_QUEUE:"QUEUECACHE",LOC_LAST_REPORT:"LOC_LR",PREFIX:{PUBLIC:"JG_Operate_"}},CUSTOM_EVENT:{EXT_KEY_COUNT_LIMIT:500,KEY_VALUE_SIZE_LIMIT:256,REG_EXP:/^[a-z][0-9a-z_]*$/,LOCAL_COMMON_ATTRIBUTES:"LOCAL_COMMON_ATTRIBUTES_KEY"},USER_PROPERTIES:{KEY_COUNT_LIMIT:100},LOC:{LIMIT_INTERVAL:9e5}};var Log;!function(e){let t=!1;const n=JGCons.LOG_TAG_PREFIX;e.setDebugMode=function(i){e.dd(n,`setDebugMode:${t}`),t=i},e.d=function(e,i){t&&console.log(n+"["+e+"]"+i)},e.w=function(e,i){t&&console.warn(n+"["+e+"]"+i)},e.dd=function(e,i){t&&console.log(n+"["+e+"]"+i)},e.ww=function(e,t){console.warn(n+"["+e+"]"+t)},e.ee=function(e,t){console.error(n+"["+e+"]"+t)}}(Log||(Log={}));const JG_Pub=JGCons.LOCAL.PREFIX.PUBLIC;function set(e,t){try{wx.setStorageSync(JG_Pub+e,t),JSON.stringify(t)}catch(e){}}function get(e){let t=null;try{t=wx.getStorageSync(JG_Pub+e)}catch(e){}return t}function remove(e){try{wx.removeStorageSync(JG_Pub+e)}catch(e){}}const CryptoJS=require("crypto-js");function http(e){return new Promise((t,n)=>{e.success=function(e){t(e)},e.fail=function(e){n(e)},wx.request(e)})}function uuid(){return S()+S()+"-"+S()+"-"+S()+"-"+S()+"-"+S()+S()+S()}function S(){return(65536*(1+Math.random())|0).toString(16).substring(1)}class MPromise{constructor(){this.callbackList=[],this.errorCallList=[],this.PromiseStatus="pending"}resolve(e){"pending"===this.PromiseStatus&&(this.PromiseStatus="resolved",this.PromiseValue=e,this.callbackList.forEach(t=>{setTimeout(function(){t(e)},0)}))}reject(e){if("pending"===this.PromiseStatus)return this.PromiseStatus="rejected",this.PromiseValue=e,this.errorCallList.forEach(t=>{t(e)}),this}then(e){if("resolved"!==this.PromiseStatus)return this.callbackList.push(e),this;e(this.PromiseValue)}catch(e){if("rejected"!==this.PromiseStatus)return this.errorCallList.push(e),this;e(this.PromiseValue)}toPromise(){return new Promise((e,t)=>{this.then(e),this.catch(t)})}}function getNetWorkInfo(){return new Promise((e,t)=>{wx.getNetworkType({success(t){e(t)},fail(e){t(e)}})})}function getSystemInfo(){return new Promise((e,t)=>{wx.getSystemInfo({success(t){e(t)},fail(e){t(e)}})})}function randomWord(e,t,n){var i="",r=t,o=["0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];e&&(r=Math.round(Math.random()*(n-t))+t);for(var a=0;a<r;a++){i+=o[Math.round(Math.random()*(o.length-1))]}return i}function rsaOpreateEncrypt(e){return function(e,t){var n=t,i=new WxmpRsa;i.setPublicKey(n);var r=i.encrypt(e);return 0==r?"":r}(e,"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDDgbrARVtZ1SutoBfJNGsVvONQ6/wcvlJuey09CDbV1HViTUvlxECMPFcXldtGBPOraixVivZSRYlwvjYUKsnULFLAJO9kJCxVa2FhLPDdzN7cpnf5wh0KT78vW/rG0LLg6FVqhXOclTXEd4xp8bDqdmVzJlJOY5xpz9bEVNM5/QIDAQAB")}function aesEncrypt(e,t,n){const i=CryptoJS.enc.Utf8.parse(t),r=CryptoJS.enc.Utf8.parse(e),o=CryptoJS.enc.Utf8.parse(n);return CryptoJS.AES.encrypt(r,i,{iv:o,mode:CryptoJS.mode.CBC,padding:CryptoJS.pad.Pkcs7}).toString()}function isEmpty(e){return!e||0==e.length}function byteCount(e){return e.replace(/[^\x00-\xff]/g,"**").length}function getAppPath(){let e=getCurrentPages();return e.length<1?"onload":e[e.length-1].route}function getRegId(){return get(JGCons.KEY_JIGUANG_REGISTRATIONID)}function getPassword(){return get(JGCons.KEY_JIGUANG_PASSWORD)}function getUid(){return get(JGCons.KEY_JIGUANG_UID)}function setCuid(e){set(JGCons.KEY_JIGUANG_CUID,e)}let mInitConfig;function setInitConfig(e){mInitConfig=e}function getInitConfig(){return mInitConfig}const TAG$1="ReportCache";const reportFailCache=new class{constructor(){this.cacheload=new MPromise,this.maxCacheCount=50}init(){return __awaiter(this,void 0,void 0,function*(){yield this.loadData(),this.cacheload.resolve(this)})}loadData(){return __awaiter(this,void 0,void 0,function*(){let e=get(JGCons.LOCAL.CACHE_FAIL);this.obj=e?JSON.parse(e):{}})}reportCache(){if(this.obj){let e=this.obj;this.obj={},this.sync();let t=[];if(Object.keys(e).length>0){for(let n in e){let i=e[n];if(Array.isArray(i))for(const e of i)t.push(e);else t.push(i)}t.length>0&&ReportHelper.report(t)}}}add(e,t){this.cacheload.then(n=>{n.addInternal(e,t)})}addInternal(e,t){Log.dd(TAG$1,"report fail cache size: "+Object.keys(this.obj).length),Object.keys(this.obj).length>=this.maxCacheCount?Log.ww(TAG$1,"report fail cache is over size "+this.maxCacheCount+", stop cache"):(this.obj[e]=t,this.sync())}delete(e){this.cacheload.then(t=>{t.deleteInternal(e)})}deleteInternal(e){delete this.obj[e],this.sync()}sync(){return __awaiter(this,void 0,void 0,function*(){set(JGCons.LOCAL.CACHE_FAIL,JSON.stringify(this.obj))})}setMaxCacheCount(e){"number"==typeof e&&e>=0&&e<=500&&(this.maxCacheCount=e)}};var ReportHelper;!function(e){const t="ReportHelper";e.report=function(e){return __awaiter(this,void 0,void 0,function*(){let n=uuid()+Date.now();reportFailCache.add(n,e);const i=getInitConfig();if("none"==(yield getNetWorkInfo()).networkType)return;let r=yield function(e){return __awaiter(this,void 0,void 0,function*(){let t=getInitConfig(),n=t.sysInfo;n||(n.version="");let i=yield getNetWorkInfo(),r={platform:"m",device_id:t.deviceId,app_key:t.appKey,sdk_ver:"",uid:t.uid,channel:t.channel,app_version:n.version,statistics_sdk_ver:t.sdkVersion,from_type:t.fromType,resolution:n.screenWidth+"*"+n.screenHeight,os_version:n.system,model:n.model,generation:i.networkType,content:Array.isArray(e)?e:[e]};return r})}(e);JSON.stringify(r);var o=JGCons.ReportHost+"/v1/mini/report",a=yield http({url:o,header:{Accept:"application/jason","X-App-Key":i.appKey,"X-Jpush-UID":i.uid},method:"POST",data:r}).catch(e=>{JSON.stringify(e)});return a&&200==a.statusCode?(reportFailCache.delete(n),Log.dd(t,"JOperateInterface,report success.")):a&&a.statusCode&&Log.ww(t,"report failed.statusCode:"+a.statusCode),a})}}(ReportHelper||(ReportHelper={}));const TAG$2="EventManager",KEY_JIGUANG_OPERATE_CONFIG="jg_OPERATE_CONFIG",KEY_JIGUANG_OPERATE_CONFIG_RequestInterval="jg_OPERATE_CONFIG_RequestInterval",KEY_JIGUANG_OPERATE_CONFIG_RequestDate="jg_OPERATE_CONFIG_RequestDate",KEY_JIGUANG_OPERATE_TMP_EVENT="jg_OPERATE_TMP_EVENT",KEY_JIGUANG_OPERATE_EVENT="jg_OPERATE_TMP_EVENT",SIZE_LIMIT=JGCons.CUSTOM_EVENT.KEY_VALUE_SIZE_LIMIT,REG_EXP=JGCons.CUSTOM_EVENT.REG_EXP,KEY_JIGUANG_OPERATE_CONFIG_STATE="jg_OPERATE_CONFIG_STATE";var ConfigState;!function(e){e[e.Unknown=0]="Unknown",e[e.Open=1]="Open",e[e.Closed=2]="Closed"}(ConfigState||(ConfigState={}));class Event{constructor(){this.name="",this.attributes={}}}class TimeKeepingEvent{constructor(){this.startTime=0,this.duration=0,this.eventName=""}}let config,jtoken,demoCompletion,isSetup=!1,tmpCacheCount=0,jIsDebugMode=!1,timeKeepingMap={};var EventManager,timeKeepingCount=0,curLat=-1,curLng=-1;!function(e){function t(){return __awaiter(this,void 0,void 0,function*(){const e=yield getSystemInfo(),t=getInitConfig();t.deviceId;let r=e.platform;r="ios"==r?"i":"android"==r?"a":"windows"==r?"w":"mac"==r?"m":"unknown";var o="0";e.system.split(" ").length>0&&(o=o[1]);let a={userVersion:config.userVersion?config.userVersion:0,eventVersion:config.eventVersion?config.eventVersion:0,cuid:t.cuid?t.cuid:"",appkey:t.appKey,rid:t.registrationID,resolution:e.screenWidth+"x"+e.screenHeight,os:r,platform:"m",manufacturer:e.brand,sysver:o,model_num:e.model,time:Date.now(),app_version:e.version,joperate_sdk_version:JGCons.SDK_VERSION},s=JSON.stringify(a),c=JGCons.Host+"/v1/visual-bury-sdk-api/smartop/4/getEvent",u=randomWord(!1,32),p=aesEncrypt(s,u,"q5bfn8msyozljacg"),d=rsaOpreateEncrypt(u);var l,g,m=yield http({url:c,header:{Authorization:d,"Content-Length":""+p.length,"X-Jpush-AuthType":"operate-js"},method:"POST",data:p}).catch(e=>{JSON.stringify(e)});if(set(KEY_JIGUANG_OPERATE_CONFIG_RequestDate,Date.now()),JSON.stringify(m),m&&200==m.statusCode){var E=m.data;if(set(KEY_JIGUANG_OPERATE_CONFIG_RequestInterval,E.intervals),0==E.code){Log.dd(TAG$2,"load config success"),demoCompletion&&demoCompletion(0,""),f(ConfigState.Open);let e=E.data;t.cuid=e.cuid,t.orgid=e.orgId,t.dataSourceId=e.dataSourceId,setCuid(e.cuid),g=e.orgId,set(JGCons.KEY_JIGUANG_ORGID,g),l=e.dataSourceId,set(JGCons.KEY_JIGUANG_DATASOURCEID,l),setInitConfig(t),e.isNew&&i();var _=!1;config.userVersion?(config.userVersion<e.userVersion&&(config.userProperties=e.userProperties,config.userVersion=e.userVersion,_=!0),config.eventVersion<e.eventVersion&&(config.reservedEvents=e.reservedEvents,config.eventVersion=e.eventVersion,_=!0)):(config=e,_=!0),_?(Log.dd(TAG$2,"update local events"),set(KEY_JIGUANG_OPERATE_CONFIG,config)):Log.dd(TAG$2,"events don't need to update"),n()}else demoCompletion&&demoCompletion(-1,"sdk is not open operate server"),4001==E.code&&(config={},remove(KEY_JIGUANG_OPERATE_CONFIG),n(),remove(KEY_JIGUANG_OPERATE_EVENT),f(ConfigState.Closed)),Log.dd(TAG$2,"opreate config request fail, "+E.code+": "+E.msg)}else Log.dd(TAG$2,"opreate config request fail"),demoCompletion&&demoCompletion(-1,"opreate config request fail")})}function n(){let e=get(KEY_JIGUANG_OPERATE_TMP_EVENT);Log.dd(TAG$2,"opreate history data:"+JSON.stringify(e));let t=[];for(let n=0;n<e.length;n++){const i=e[n];let r=i[0];config.reservedEvents||r.name!=Preset.AppActive&&r.name!=Preset.AppRegid||(t.push(i),Log.dd(TAG$2,"event will not be remove"+r.name));const o=getInitConfig();i[1].peripheralProperty.jg_org_id=o.orgid,a(i)}set(KEY_JIGUANG_OPERATE_TMP_EVENT,t),tmpCacheCount=0}function i(){PresetEventManager.reportDidRegister()}function r(e,t,n){let i=new Event;i.name=e,i.attributes=t,function(e,t,n){__awaiter(this,void 0,void 0,function*(){Log.dd(TAG$2,"onEvent name:"+e.name),function(e,t){if(!e)return p("event"),!1;let n=Object.assign({},c);if(s){let e=s();for(let t in e)n[t]=e[t]}for(let t in e.attributes)n[t]=e.attributes[t];e.attributes=n;let i=e.name;if(!i)return p("event name"),!1;if("string"!=typeof i)return d("name must be string."),!1;if(byteCount(i)>SIZE_LIMIT)return d(`name must be less than ${SIZE_LIMIT} bytes`),!1;if(-1!=i.indexOf("jg")&&-1==t.indexOf(i))return d("This event will not record, because event name: "+e.name+" is invalid, you can't use jg as a prefix"),!1;if(e.attributes.length<1)return!0;if(e.attributes.length>500)return d("This event will not record, since you have more than 500 pairs of custom key/value."),!1;let r=g(e.attributes,t);if(2==r.code)return!1;return e.attributes=r.attrs,!0}(e,t)&&o(e,n)})}(i,n,1)}function o(e,t){return __awaiter(this,void 0,void 0,function*(){const n=yield getNetWorkInfo(),i=yield getSystemInfo(),r=getInitConfig();let o={};o.jg_wifi="wifi"==n.networkType?1:0,o.jg_app_key=r.appKey,o.jg_org_id=r.orgid,o.jg_network_type=n.networkType,o.jg_event_duration=(Date.now()-r.initTime)/1e3,o.jg_launch_first=r.first_time,o.jg_devices_model=i.model;var s=(new Date).getTimezoneOffset()/-60;o.jg_time_zone=(s>0?"+":"")+s,o.jg_os_language=i.language,o.jg_os_version=i.system,o.jg_platform_type="miniprogram",o.jg_channel_source=r.channel,o.jg_app_version=i.version,o.jg_operate_sdk_ver=r.sdkVersion,o.jg_os=i.platform,o.jg_manufacturer=i.brand,o.jg_screen_size=i.screenWidth+"x"+i.screenHeight,o.jg_screen_width=i.screenWidth,o.jg_screen_height=i.screenHeight,o.jg_device_id=r.deviceId,o.jg_latitude=curLat,o.jg_longitude=curLng,o.jg_url_path=getAppPath(),o.jg_url=getAppPath(),o.jg_app_version=i.version;let c={time:Date.now(),peripheralProperty:o};if(config&&config.userVersion)a([e,c,t]);else{if(Log.dd(TAG$2,"config is not vaild, save tmp event"+e.name),tmpCacheCount>100)return Log.dd(TAG$2,"tmp event count is over size , max size 100"),null;let n=get(KEY_JIGUANG_OPERATE_TMP_EVENT);n||(n=[]),n.push([e,c,t]),set(KEY_JIGUANG_OPERATE_TMP_EVENT,n),tmpCacheCount++}})}function a(e){return __awaiter(this,void 0,void 0,function*(){let t=e[0];if(!("jg_debug"==t.name||config.userVersion&&-1!=config.reservedEvents.data.indexOf(t.name)))return void t.name;let n=e[1];const i=getInitConfig();var r;n.uid=i.uid,n.type=e[2],n.cuid=i.cuid,n.random_id=Math.random().toString(36).substr(2,r||8);let o={};for(let e=0;e<config.userProperties.data.length;e++){let t=config.userProperties.data[e];o[t.key]=t.value}var a;n.userProperties={value:o},t.attributes.jg_data_source="miniprogram",t.attributes.jg_data_source_id=i.dataSourceId,t.attributes.jg_is_first_day=((a=get(JGCons.KEY_JIGUANG_INSTALLDATE))&&a>0?(a+=864e5,a-=a%864e5,Date.now()<a):(a=Date.now(),set(JGCons.KEY_JIGUANG_INSTALLDATE,a),1))?1:0;const s=yield getSystemInfo();t.attributes.jg_brand=s.brand,t.attributes.jg_mp_so_version=s.SDKVersion,t.attributes.jg_referer_fulldomain="",t.attributes.jg_referer_url=i.refererUrl,t.attributes.jg_scene=i.scene,t.attributes.jg_query=function(){let e=getCurrentPages();if(e.length<1)return"";let t=e[e.length-1].options;if(null!=t)return Object.keys(t).map(e=>`${e}=${t[e]}`).join("&");return""}(),t.attributes.jg_wechat_appid=i.appid;for(const e in u)Object.prototype.hasOwnProperty.call(u,e)&&(t.attributes["jg_"+e]=u[e]);n.event={id:t.name,value:t.attributes};let c={type:"operate_event",orgId:i.orgid,platform:"m",appkey:i.appKey,data:[n]};if(jIsDebugMode)c.token=jtoken,function(e){__awaiter(this,void 0,void 0,function*(){let t=JSON.stringify(e),n=JGCons.Host+"/v1/visual-bury-sdk-api/smartop/4/debug/report",i=randomWord(!1,32),r=aesEncrypt(t,i,"q5bfn8msyozljacg"),o=rsaOpreateEncrypt(i);var a=yield http({url:n,header:{Authorization:o,"Content-Length":""+r.length,"X-Jpush-AuthType":"operate-js"},method:"POST",data:r}).catch(e=>{JSON.stringify(e)});a&&a.statusCode})}(c);else{let e=yield ReportHelper.report(c);e&&200==e.statusCode&&reportFailCache.reportCache()}})}e.start=function(){isSetup||(isSetup=!0,Log.dd(TAG$2,"load local operate config"),(config=get(KEY_JIGUANG_OPERATE_CONFIG))||(config={}),getInitConfig().registrationID?function(){let e=get(KEY_JIGUANG_OPERATE_CONFIG_RequestDate),t=get(KEY_JIGUANG_OPERATE_CONFIG_RequestInterval);return Date.now(),Date.now()-t>e}()&&t():Log.dd(TAG$2,"PO_JCORE hasn't registered, cancel load operate config"))},e.setLocation=function(e,t){curLat=e<=0?-1:e,curLng=t<=0?-1:t},e.getLocation=function(){return[curLat,curLng]},e.loadUserProperties=function(){t()},e.onUserEvent=r,e.onPresetEvent=function(e,t){let n=new Event;n.name=e,n.attributes=t,o(n,0)};var s,c={};e.readLocalCommonAttr=function(){let e=get(JGCons.CUSTOM_EVENT.LOCAL_COMMON_ATTRIBUTES);e&&"{}"!==JSON.stringify(e)&&(c=e)},e.setEventCommonAttr=function(e){let t=l(e,[]);1==t.code&&(c=t.attrs,Log.dd(TAG$2,"setEventCommonAttr:"+JSON.stringify(c)),set(JGCons.CUSTOM_EVENT.LOCAL_COMMON_ATTRIBUTES,c))},e.currentEventCommonAttr=function(){return c},e.clearEventCommonAttr=function(){c={},remove(JGCons.CUSTOM_EVENT.LOCAL_COMMON_ATTRIBUTES)},e.setEventDynamicAttr=function(e){e instanceof Function&&(s=e)};var u={};function p(e){Log.ee(TAG$2,e+" cannot be empty")}function d(e){Log.ee(TAG$2,"Parameter invalid,"+e)}function l(e,t){if(!e||"object"!=typeof e)return{code:1,attrs:{}};let n=e;if(Object.keys(e).length>JGCons.USER_PROPERTIES.KEY_COUNT_LIMIT)return d(`This user proproties will not record, since you have more than ${JGCons.USER_PROPERTIES.KEY_COUNT_LIMIT} pairs of custom extra key/value`),{code:2};for(let n in e){if("string"!=typeof n)return d("This property won't be updated, the key "+n+" in user proproties must be String"),{code:2};if(-1!=n.indexOf("jg")&&-1==t.indexOf(n))return d("This property won't be updated, because key in user proproties: "+n+" is invalid, you can't use jg as a prefix"),{code:2};if(!n.match(REG_EXP))return d(`This property won't be updated, The key: ${n} must be alphanumeric and underscore, and start with letters`),{code:2};if(byteCount(n)>SIZE_LIMIT)return d(`This property won't be updated, The ${n} size must be less than ${SIZE_LIMIT} bytes`),{code:2};let i=typeof e[n];if(-1==["string","number","boolean","object"].indexOf(i))return d("This property won't be updated, the "+n+" value in extra must be string/number/boolean/array"),{code:2};if("object"===i&&e[n].length)for(let t=0;t<e[n].length;t++)if("string"!=typeof e[n][t])return d("This property won't be updated, the "+n+"  value in array must be string"),{code:2};let r=e[n];if(null!=r&&void 0!==r){if(byteCount(r+"")>SIZE_LIMIT)return d("This property won't be updated, the "+n+"  value must be less than "+SIZE_LIMIT+" bytes"),{code:2}}else Log.ww(TAG$2,`Parameter invalid,value of ${n} is empty`)}return{code:1,attrs:n}}function g(e,t){if(!e||"object"!=typeof e)return{code:1,attrs:{}};let n=e;if(Object.keys(e).length>JGCons.CUSTOM_EVENT.EXT_KEY_COUNT_LIMIT)return d(`This event will not record, since you have more than ${JGCons.CUSTOM_EVENT.EXT_KEY_COUNT_LIMIT} pairs of custom extra key/value`),{code:2};for(let i in e){if("string"!=typeof i){Log.ww(TAG$2,"This property is removed, the key "+i+" in extra must be String"),delete n[i];continue}if(-1!=i.indexOf("jg")&&-1==t.indexOf(i)){d("This property is removed, because key in extra: "+i+" is invalid, you can't use jg as a prefix"),delete n[i];continue}if(!i.match(REG_EXP)){d(`This property is removed, The ${i} must be alphanumeric and underscore, and start with letters`),delete n[i];continue}if(byteCount(i)>SIZE_LIMIT){d(`This property is removed, The ${i} size must be less than ${SIZE_LIMIT} bytes`),delete n[i];continue}let r=typeof e[i];if(-1==["string","number","boolean","object"].indexOf(r)){d("The property "+r+" is removed, the value in extra must be String or Number"),delete n[i];continue}if("object"===r&&e[i].length)for(let t=0;t<e[i].length;t++)if("string"!=typeof e[i][t]){d("This property is removed, the "+i+"  value in extra and in array must be string"),delete n[i];break}let o=e[i];null!=o&&void 0!==o?byteCount(o+"")>SIZE_LIMIT&&(d("This property is removed, the "+i+"  value must be less than "+SIZE_LIMIT+" bytes"),delete n[i]):Log.ww(TAG$2,`Parameter invalid,value of ${i} is empty`)}return{code:1,attrs:n}}function f(e){set(KEY_JIGUANG_OPERATE_CONFIG_STATE,e)}function m(){let e=get(KEY_JIGUANG_OPERATE_CONFIG_STATE);return e||ConfigState.Unknown}e.setUtmProperties=function(e){u={},["utm_source","utm_medium","utm_term","utm_content","utm_campaign"].forEach(t=>{e[t]&&(u[t]=e[t])})},e._checkCommonAttrs=l,e._checkEventAttrs=g,e.updateCUID=function(e,n){let r=getInitConfig();isEmpty(e)||e==r.cuid?Log.dd(TAG$2,"cuid is not updated , cuid: "+e):(r.cuid=e,setCuid(e),setInitConfig(r),n&&i(),remove(KEY_JIGUANG_OPERATE_CONFIG),t())},e.timeKeepingEventStart=function(e){if(!e)return null;let t="JOPERATETimeKeepingEvent"+timeKeepingCount++,n=new TimeKeepingEvent;return n.startTime=Date.now(),n.eventName=e,timeKeepingMap[t]=n,t},e.timeKeepingEventEnd=function(e,t){if(timeKeepingMap[e]){let i=timeKeepingMap[e];i.eventName;let o=t;var n=i.duration;i.startTime>0&&(n+=Date.now()-i.startTime),o.jg_duration=n,r(i.eventName,o,["jg_duration"]),delete timeKeepingMap[e]}},e.timeKeepingEventPause=function(e){if(timeKeepingMap[e]){let t=timeKeepingMap[e];t.eventName,t.startTime>0&&(t.duration+=Date.now()-t.startTime,t.startTime=-1)}},e.timeKeepingEventResume=function(e){if(timeKeepingMap[e]){let t=timeKeepingMap[e];t.eventName,t.startTime<0?t.startTime=Date.now():t.eventName}},e.removeTimeKeepingEvent=function(e){e&&delete timeKeepingMap[e]},e.clearTimeKeepingEvent=function(){timeKeepingMap={}},e.openDebugMode=function(e){if(isEmpty(getInitConfig().cuid))return!1;if(-1!=e.indexOf("token")){let t=e.split("token=");return jtoken=t[1],jIsDebugMode=!0,r("jg_debug",{},["jg_debug"]),!0}return!1},e.isValid=function(e){m()==ConfigState.Unknown?demoCompletion=e:m()==ConfigState.Open?e(0,""):e(-1,"sdk is not open operate server")}}(EventManager||(EventManager={}));const Preset={AppLaunch:"jg_app_launch",AppActive:"jg_app_active",AppRegid:"jg_app_cuid",AppEnd:"jg_app_end",AppShow:"jg_app_show",AppHide:"jg_app_hide"},JOPERATE_SESSION_LEFT_TIME="JOPERATELeft_time";var PresetEventManager,setup=!1;!function(e){e.start=function(){setup||(setup=!0,getInitConfig().first_time&&EventManager.onPresetEvent(Preset.AppActive,{}),function(){EventManager.onPresetEvent(Preset.AppLaunch,{});let e=get(JOPERATE_SESSION_LEFT_TIME);e&&e>0&&(EventManager.onPresetEvent(Preset.AppEnd,{}),set(JOPERATE_SESSION_LEFT_TIME,Date.now()))}())},e.onShow=function(){EventManager.onPresetEvent(Preset.AppShow,{})},e.onHide=function(){set(JOPERATE_SESSION_LEFT_TIME,Date.now()),EventManager.onPresetEvent(Preset.AppHide,{})},e.reportDidRegister=function(){EventManager.onPresetEvent(Preset.AppRegid,{})}}(PresetEventManager||(PresetEventManager={}));const LOCAL_TAG_DEVICEID=JGCons.LOCAL.DEVICEID;let devicdId="";var UserManager;!function(e){function t(e){return __awaiter(this,void 0,void 0,function*(){let t=e.properties,n=e.type,i=e.completion,r=EventManager._checkCommonAttrs(t,[]);if(2==r.code)return void(i&&i(-1,"param is invaild"));let o=r.attrs,a=getInitConfig();if(a.cuid){let e={cuid:a.cuid,time:Date.now(),appkey:a.appKey,type:n};if("del"==n){var s="";Object.keys(o).forEach(e=>{s=e}),e.value=s}else e.value=o;let t=JSON.stringify(e),r=JGCons.Host+"/v1/visual-bury-sdk-api/smartop/4/updateUserProperties";"del"==n&&(r=JGCons.Host+"/v1/visual-bury-sdk-api/smartop/4/switcUserProperties");let p=randomWord(!1,32),d=aesEncrypt(t,p,"q5bfn8msyozljacg"),l=rsaOpreateEncrypt(p);var c=yield http({url:r,header:{Authorization:l,"Content-Length":""+d.length,"X-Jpush-AuthType":"operate-js"},method:"POST",data:d}).catch(e=>{JSON.stringify(e)});if(c&&200==c.statusCode){JSON.stringify(c);var u=c.data;!u||u.code>0?(u.code,u.msg,i&&i(u.code,u.msg)):(EventManager.loadUserProperties(),i&&i(0,"success"))}else i&&i(-1,"oops! update user properties fail, network exception")}else i&&i(-1,"sdk hasn't registered yet, update user properties requset will be cancel")})}e.identifyAccount=function(e){return __awaiter(this,void 0,void 0,function*(){if(!e)return;if(!e.userIDs&&!Object.keys(e.userIDs))return void(e.completion&&e.completion(-1,"identifyAccount fail loginID and mobile are nil"));let t=getInitConfig();if(t.cuid){let r={rid:t.registrationID,cuid:t.cuid,time:Date.now(),appkey:t.appKey,value:e.userIDs},o=JSON.stringify(r),a=JGCons.Host+"/v1/visual-bury-sdk-api/smartop/4/setUserInfo",s=randomWord(!1,32),c=aesEncrypt(o,s,"q5bfn8msyozljacg"),u=rsaOpreateEncrypt(s);var n=yield http({url:a,header:{Authorization:u,"Content-Length":""+c.length,"X-Jpush-AuthType":"operate-js"},method:"POST",data:c}).catch(e=>{JSON.stringify(e)});if(n&&200==n.statusCode){JSON.stringify(n);var i=n.data;!i||i.code>0?(i.code,i.msg,e.completion&&e.completion(i.code,i.msg)):(EventManager.updateCUID(i.data.cuid,i.data.isNew),e.completion&&e.completion(0,"success"))}else e.completion&&e.completion(-1,"oops! identifyAccount fail, network exception")}else e.completion&&e.completion(-1,"sdk hasn't registered yet, identify account requset will be cancel")})},e.setUserChannel=function(e){return __awaiter(this,void 0,void 0,function*(){if(!e)return;if(!e.channels||Object.keys(e).length<1)return void(e.completion&&e.completion(-1,"every channel parameter is nil"));let t=e.channels;Object.keys(t).forEach(n=>{if(n.length<1||n.length>256)return void(e.completion&&e.completion(-1,"channel key/value length can't exceed 256!"));let i=t[n];Object.keys(i).forEach(t=>{(t.length<1||t.length>256||i[t].length>256)&&e.completion&&e.completion(-1,"channel key/value length can't exceed 256!")})});let n=getInitConfig();if(n.cuid){let o=[];Object.keys(t).forEach(e=>{o.push({id:e,contactValues:t[e]})});let a={cuid:n.cuid,time:Date.now(),appkey:n.appKey,channelInfo:o},s=JSON.stringify(a),c=JGCons.Host+"/v1/visual-bury-sdk-api/smartop/4/setChannel",u=randomWord(!1,32),p=aesEncrypt(s,u,"q5bfn8msyozljacg"),d=rsaOpreateEncrypt(u);var i=yield http({url:c,header:{Authorization:d,"Content-Length":""+p.length,"X-Jpush-AuthType":"operate-js"},method:"POST",data:p}).catch(e=>{JSON.stringify(e)});if(i&&200==i.statusCode){JSON.stringify(i);var r=i.data;r.code?(r.code,r.msg,e.completion&&e.completion(r.code,r.msg)):e.completion&&e.completion(0,"success")}else e.completion&&e.completion(-1,"oops! set channel fail, network exception")}else e.completion&&e.completion(-1,"sdk hasn't registered yet, set user channels requset will be cancel")})},e.set=function(e,n){JSON.stringify(e),t({properties:e,completion:n,type:"cover"})},e.setOnce=function(e,n){t({properties:e,completion:n,type:"setOnce"})},e.increment=function(e,n){t({properties:e,completion:n,type:"add"})},e.append=function(e,n,i){let r={};r[e]=n,t({properties:r,completion:i,type:"append"})},e.unset=function(e,n){let i={};i[e]="",t({properties:i,completion:n,type:"del"})}}(UserManager||(UserManager={}));const TAG$5="RegisterHelper";let isConnecting=!1;const reconnectTimeIntervals=[2,5,20,60,120];let registerSuccessCallback,reconnectTimes=0;function register(){return __awaiter(this,void 0,void 0,function*(){if(isConnecting)return;if(isConnecting=!0,"none"==(yield getNetWorkInfo()).networkType)return isConnecting=!1,void Log.dd(TAG$5,"register failed,no network");const e=yield getSystemInfo(),t=getInitConfig();let n=t.deviceId,i=e.platform;i&&""!=i&&null!=i||(i="unknown");let r={ver:16,platform:4,appkey:t.appKey,strApkVersion:e.version,systemversion:e.system,modelnumber:e.model,basebandversion:e.brand,channel:t.channel,StatisticSDKVer:t.sdkVersion,installation:0,resolution:e.screenWidth+"*"+e.screenHeight,DeviceId:n,business:2048,from_type:i,third_appid:t.appid},o=JSON.stringify(r),a=JGCons.RegisterHost+"/v1/register";var s,c,u,p,d=yield http({url:a,header:{"X-Jpush-AuthType":"miniprogram","X-Real-IP":"127.0.0.1"},method:"POST",data:o}).catch(e=>{JSON.stringify(e)});if(d){JSON.stringify(d);var l=d.data;0==l.code&&l.uid&&l.password&&l.RegistrationID?(Log.dd(TAG$5,"register success,registerId:"+l.RegistrationID),p=l.uid,set(JGCons.KEY_JIGUANG_UID,p),u=l.password,set(JGCons.KEY_JIGUANG_PASSWORD,u),c=l.RegistrationID,set(JGCons.KEY_JIGUANG_REGISTRATIONID,c),t.uid=l.uid,t.password=l.password,t.registrationID=l.RegistrationID,setInitConfig(t),registerSuccessCallback(0,l.RegistrationID),reportFailCache.reportCache()):(s=l.code,Log.ee(TAG$5,"Register Failed with server error - code:"+s),registerSuccessCallback(l.code,""),retry())}else registerSuccessCallback(-1,""),Log.ww(TAG$5,"Register Failed:no reponse"),retry();return isConnecting=!1,d})}function retry(){setTimeout(()=>{register()},1e3*reconnectTimeIntervals[reconnectTimes]),++reconnectTimes==reconnectTimeIntervals.length&&(reconnectTimes=reconnectTimeIntervals.length-1)}var DemoInterface,requestFinCnt=0,requestSuccCnt=0,isRequesting=!1;!function(e){var t={};function n(e,t){return __awaiter(this,void 0,void 0,function*(){let n=getInitConfig(),i={cuid:n.cuid,appkey:n.appKey},r=JSON.stringify(i),o="project";switch(e){case 1:o="custom-event";break;case 2:o="user-tag";break;case 3:o="channel";break;case 4:o="user-attribute"}let a=JGCons.Host+"/v1/visual-bury-sdk-api/smartop/4/"+o,s=randomWord(!1,32),c=aesEncrypt(r,s,"q5bfn8msyozljacg"),u=rsaOpreateEncrypt(s);var p=yield http({url:a,header:{Authorization:u,"Content-Length":""+c.length,"X-Jpush-AuthType":"operate-js"},method:"POST",data:c}).catch(e=>{JSON.stringify(e)});p&&200==p.statusCode?(JSON.stringify(p),t(0,p.data)):t(-1,"数据拉取失败")})}function i(e,n,i,r){if(requestFinCnt++,!e&&n&&(requestSuccCnt++,0==n.code)){var o=null;"events"==i?o=n.data:"tag"==i||"user"==i?o=n.data.list:"channels"==i&&(o=n.data.channelinfo[0].detail),o&&(t[i]=o)}4==requestFinCnt&&(requestSuccCnt>0?(JSON.stringify(t),r&&r(0,t)):r&&r(-2,null),isRequesting=!1)}e.userData=function(e){isRequesting?e(-1,null):(isRequesting=!0,requestFinCnt=0,requestSuccCnt=0,t={},n(1,(t,n)=>{i(t,n,"events",e)}),n(2,(t,n)=>{i(t,n,"tag",e)}),n(3,(t,n)=>{i(t,n,"channels",e)}),n(4,(t,n)=>{i(t,n,"user",e)}))},e.appInfo=function(e){n(0,(t,n)=>{t?e&&e(-2,null):e&&e(0,n.data)})}}(DemoInterface||(DemoInterface={}));const TAG$7="JOperate";const jOperate=new class{constructor(){this.mIsInited=!1}init(e){const t=require("./joperate-conf.js");if(Log.setDebugMode(t.debugMode),this.mIsInited)return void Log.dd(TAG$7,"need not init multi times");if(isEmpty(t.appid)||isEmpty(t.appKey))return void Log.ee(TAG$7,"init failed,appKey or appid is empty");Log.dd(TAG$7,"action:init - sdkVersion:"+JGCons.SDK_VERSION+"release version"),this.mIsInited=!0,EventManager.readLocalCommonAttr();let n={appKey:"",debugMode:!1,channel:"",loc:!1,sdkVersion:"",fromType:"",appid:"",sysInfo:void 0,deviceId:"",first_time:!1,uid:0,password:"",registrationID:"",cuid:"",orgid:"",dataSourceId:"",initTime:0,scene:0,refererUrl:""};return n.appKey=t.appKey,n.channel=t.channel,n.debugMode=t.debugMode,n.appid=t.appid,this._initConfig(n),this._addPageShowHide(e),this._initUser(),reportFailCache.init(),PresetEventManager.start(),this}_initConfig(e){let t=get(JGCons.LOCAL.APPKEY);var n;e.appKey!=t&&(Log.dd(TAG$7,"last appKey:"+t+",current appkey:"+e.appKey+", appkey changed, will clear cache"),remove(JGCons.LOCAL.CACHE_FAIL),remove(JGCons.LOCAL.LOC_LAST_REPORT),n=e.appKey,set(JGCons.LOCAL.APPKEY,n)),e.channel=isEmpty(e.channel)?JGCons.DEFAULT_CHANNEL:e.channel,e.sdkVersion=JGCons.SDK_VERSION,e.deviceId=isEmpty(devicdId)&&isEmpty(devicdId=get(LOCAL_TAG_DEVICEID))?"":devicdId,e.first_time=isEmpty(e.deviceId),e.initTime=Date.now();try{e.fromType=wx.getLaunchOptionsSync().scene+"",e.sysInfo=wx.getSystemInfoSync()}catch(e){Log.ww(TAG$7,"getSystemInfo failed:"+e)}Log.dd(TAG$7,"init config appId:"+e.appid+",appKey:"+e.appKey+",channel:"+e.channel+",debugEnable:"+e.debugMode+",loc:"+e.loc),JSON.stringify(e.deviceId);let i=e.deviceId;isEmpty(i)&&(i=uuid()+Date.now(),set(LOCAL_TAG_DEVICEID,i)),e.deviceId=i,e.registrationID=getRegId(),e.uid=getUid(),e.password=getPassword(),e.cuid=get(JGCons.KEY_JIGUANG_CUID),e.orgid=get(JGCons.KEY_JIGUANG_ORGID),e.dataSourceId=get(JGCons.KEY_JIGUANG_DATASOURCEID),setInitConfig(e)}_addPageShowHide(e){let t=e;if(t.onShow){let e=t.onShow;t.onShow=function(n){let i=n.path,r=n.scene,o=getInitConfig();return o.scene=r,o.refererUrl=i,setInitConfig(o),PresetEventManager.onShow(),reportFailCache.reportCache(),e.apply(t,arguments)}}if(t.onHide){let e=t.onHide;t.onHide=function(n){return PresetEventManager.onHide(),e.apply(t,arguments)}}}_initUser(){var e;e=this.registerSuccess,registerSuccessCallback=e,function(){return __awaiter(this,void 0,void 0,function*(){const e=getInitConfig();if(e.uid>0)return!0;const t=getUid(),n=getPassword(),i=getRegId();return!!t&&(e.uid=t,e.password=n,e.registrationID=i,setInitConfig(e),!0)})}().then(e=>{e?EventManager.start():register()})}registerSuccess(e,t){0==e&&EventManager.start()}identifyAccount(e){UserManager.identifyAccount(e)}setUserChannel(e){UserManager.setUserChannel(e)}onEvent(e){return __awaiter(this,void 0,void 0,function*(){this.mIsInited?EventManager.onUserEvent(e.name,e.attributes,[]):Log.ee(TAG$7,"call onEvent failed:please call init correctly first")})}setEventCommonAttr(e){this.mIsInited?EventManager.setEventCommonAttr(e):Log.ee(TAG$7,"call setEventCommonAttr failed:please call init correctly first")}currentEventCommonAttr(){return EventManager.currentEventCommonAttr()}clearEventCommonAttr(){this.mIsInited?EventManager.clearEventCommonAttr():Log.ee(TAG$7,"call clearEventCommonAttr failed:please call init correctly first")}setEventDynamicAttr(e){this.mIsInited?EventManager.setEventDynamicAttr(e):Log.ee(TAG$7,"call setEventDynamicAttr failed:please call init correctly first")}setUtmProperties(e){this.mIsInited?(EventManager.setUtmProperties(e),this.set(e,(e,t)=>{})):Log.ee(TAG$7,"call setUtmProperties failed:please call init correctly first")}set(e,t){UserManager.set(e,t)}setOnce(e,t){UserManager.setOnce(e,t)}increment(e,t){UserManager.increment(e,t)}append(e,t,n){UserManager.append(e,t,n)}unset(e,t){UserManager.unset(e,t)}timeKeepingEventStart(e){return EventManager.timeKeepingEventStart(e)}timeKeepingEventEnd(e,t){EventManager.timeKeepingEventEnd(e,t)}timeKeepingEventPause(e){EventManager.timeKeepingEventPause(e)}timeKeepingEventResume(e){EventManager.timeKeepingEventResume(e)}removeTimeKeepingEvent(e){EventManager.removeTimeKeepingEvent(e)}clearTimeKeepingEvent(){EventManager.clearTimeKeepingEvent()}setMaxCacheCount(e){reportFailCache.setMaxCacheCount(e)}openDebugMode(e){return EventManager.openDebugMode(e)}isValid(e){EventManager.isValid(e)}userData(e){DemoInterface.userData(e)}appInfo(e){DemoInterface.appInfo(e)}CUID(){return getInitConfig().cuid}peripheralData(){return __awaiter(this,void 0,void 0,function*(){const e=yield getNetWorkInfo(),t=yield getSystemInfo();return[{name:"设备厂商",value:t.brand},{name:"系统语言",value:t.language},{name:"平台类型",value:"miniprogram"},{name:"设备型号",value:t.model},{name:"是否使用wifi",value:"wifi"==e.networkType?"是":"否"},{name:"屏幕宽度",value:t.screenWidth},{name:"屏幕高度",value:t.screenHeight},{name:"操作系统",value:t.platform},{name:"网络类型",value:e.networkType},{name:"GPS纬度",value:EventManager.getLocation()[0]},{name:"GPS经度",value:EventManager.getLocation()[1]}]})}setLocation(e,t){EventManager.setLocation(e,t)}},JOperate={init:function(e){jOperate.init(e),e&&(e.PJOperateInterface=this)},identifyAccount(e){jOperate.identifyAccount(e)},setUserChannel(e){jOperate.setUserChannel(e)},onEvent:function(e){jOperate.onEvent(e)},setEventCommonAttr:function(e){jOperate.setEventCommonAttr(e)},clearEventCommonAttr:function(){jOperate.clearEventCommonAttr()},setEventDynamicAttr:function(e){jOperate.setEventDynamicAttr(e)},currentEventCommonAttr:()=>jOperate.currentEventCommonAttr(),setUtmProperties(e){jOperate.setUtmProperties(e)},set(e,t){jOperate.set(e,t)},setOnce(e,t){jOperate.setOnce(e,t)},increment(e,t){jOperate.increment(e,t)},append(e,t,n){jOperate.append(e,t,n)},unset(e,t){jOperate.unset(e,t)},timeKeepingEventStart:e=>jOperate.timeKeepingEventStart(e),timeKeepingEventEnd(e,t){jOperate.timeKeepingEventEnd(e,t)},timeKeepingEventPause(e){jOperate.timeKeepingEventPause(e)},timeKeepingEventResume(e){jOperate.timeKeepingEventResume(e)},removeTimeKeepingEvent(e){jOperate.removeTimeKeepingEvent(e)},clearTimeKeepingEvent(){jOperate.clearTimeKeepingEvent()},setMaxCacheCount(e){jOperate.setMaxCacheCount(e)},openDebugMode:e=>jOperate.openDebugMode(e),isValid(e){jOperate.isValid(e)},userData(e){jOperate.userData(e)},appInfo(e){jOperate.appInfo(e)},CUID:()=>jOperate.CUID(),peripheralData(){return __awaiter(this,void 0,void 0,function*(){return yield jOperate.peripheralData()})},setLocation(e,t){jOperate.setLocation(e,t)}};module.exports=JOperate;
