hina-cloud-js-sdk 4.0.3 → 4.0.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/hina.iife.js CHANGED
@@ -1 +1 @@
1
- var hinaDataStatistic=function(t){"use strict";var e=function(t,o){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&(t[o]=e[o])},e(t,o)};function o(t,o){if("function"!=typeof o&&null!==o)throw new TypeError("Class extends value "+String(o)+" is not a constructor or null");function r(){this.constructor=t}e(t,o),t.prototype=null===o?Object.create(o):(r.prototype=o.prototype,new r)}var r,n,i,a=function(){return a=Object.assign||function(t){for(var e,o=1,r=arguments.length;o<r;o++)for(var n in e=arguments[o])Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n]);return t},a.apply(this,arguments)};function s(t,e,o,r){return new(o||(o=Promise))((function(n,i){function a(t){try{c(r.next(t))}catch(t){i(t)}}function s(t){try{c(r.throw(t))}catch(t){i(t)}}function c(t){var e;t.done?n(t.value):(e=t.value,e instanceof o?e:new o((function(t){t(e)}))).then(a,s)}c((r=r.apply(t,e||[])).next())}))}function c(t,e){var o,r,n,i={label:0,sent:function(){if(1&n[0])throw n[1];return n[1]},trys:[],ops:[]},a=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return a.next=s(0),a.throw=s(1),a.return=s(2),"function"==typeof Symbol&&(a[Symbol.iterator]=function(){return this}),a;function s(s){return function(c){return function(s){if(o)throw new TypeError("Generator is already executing.");for(;a&&(a=0,s[0]&&(i=0)),i;)try{if(o=1,r&&(n=2&s[0]?r.return:s[0]?r.throw||((n=r.return)&&n.call(r),0):r.next)&&!(n=n.call(r,s[1])).done)return n;switch(r=0,n&&(s=[2&s[0],n.value]),s[0]){case 0:case 1:n=s;break;case 4:return i.label++,{value:s[1],done:!1};case 5:i.label++,r=s[1],s=[0];continue;case 7:s=i.ops.pop(),i.trys.pop();continue;default:if(!(n=i.trys,(n=n.length>0&&n[n.length-1])||6!==s[0]&&2!==s[0])){i=0;continue}if(3===s[0]&&(!n||s[1]>n[0]&&s[1]<n[3])){i.label=s[1];break}if(6===s[0]&&i.label<n[1]){i.label=n[1],n=s;break}if(n&&i.label<n[2]){i.label=n[2],i.ops.push(s);break}n[2]&&i.ops.pop(),i.trys.pop();continue}s=e.call(t,i)}catch(t){s=[6,t],r=0}finally{o=n=0}if(5&s[0])throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}([s,c])}}}function u(t){var e="function"==typeof Symbol&&Symbol.iterator,o=e&&t[e],r=0;if(o)return o.call(t);if(t&&"number"==typeof t.length)return{next:function(){return t&&r>=t.length&&(t=void 0),{value:t&&t[r++],done:!t}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function l(t,e){var o="function"==typeof Symbol&&t[Symbol.iterator];if(!o)return t;var r,n,i=o.call(t),a=[];try{for(;(void 0===e||e-- >0)&&!(r=i.next()).done;)a.push(r.value)}catch(t){n={error:t}}finally{try{r&&!r.done&&(o=i.return)&&o.call(i)}finally{if(n)throw n.error}}return a}function h(t,e,o){if(o||2===arguments.length)for(var r,n=0,i=e.length;n<i;n++)!r&&n in e||(r||(r=Array.prototype.slice.call(e,0,n)),r[n]=e[n]);return t.concat(r||Array.prototype.slice.call(e))}"function"==typeof SuppressedError&&SuppressedError,t.ConsoleTypes=void 0,(r=t.ConsoleTypes||(t.ConsoleTypes={})).LOG="log",r.INFO="info",r.WARN="warn",r.ERROR="error",r.ASSERT="assert",t.ReportTypes=void 0,(n=t.ReportTypes||(t.ReportTypes={})).BEACON="beacon",n.IMAGE="image",n.AJAX="ajax",t.VariablesTypes=void 0,(i=t.VariablesTypes||(t.VariablesTypes={})).INTEGER="INTEGER",i.STRING="STRING",i.BOOLEAN="BOOLEAN";var p=function(t,e){this.options=t,this.context=e,this.disabled=!1},f=["utm_source","utm_medium","utm_campaign","utm_content","utm_term"];h(h([],l(f),!1),l(["ha_utm"]),!1);var d=["www.baidu.","m.baidu.","m.sm.cn","so.com","sogou.com","youdao.com","google.","yahoo.com/","bing.com/","ask.com/"],g=["weibo.com","renren.com","kaixin001.com","douban.com","qzone.qq.com","zhihu.com","tieba.baidu.com","weixin.qq.com"],v={baidu:["wd","word","kw","keyword"],google:"q",bing:"q",yahoo:"p",sogou:["query","keyword"],so:"q",sm:"q"},m="hinasdk_domain_test",y=Object.prototype.toString;function b(t){return"[object Object]"===y.call(t)}function w(t){return null!=t}function _(t){return Array.isArray(t)}function T(t){return"function"==typeof t}function S(t){return"string"==typeof t}function x(t){return"number"==typeof t&&!Number.isNaN(t)}function k(t){return"boolean"==typeof t}function C(){}function H(t){try{return JSON.parse(t)}catch(t){}return t}function A(t){return 0===Object.keys(t).length}function R(){return Date.now&&T(Date.now)?Date.now():(new Date).getTime()}function I(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var o=Object.create(null);return t.forEach((function(t){t&&Object.keys(t).forEach((function(e){var r=t[e];b(r)?b(o[e])?o[e]=I(o[e],r):o[e]=I(r):o[e]=r}))})),o}function P(t){var e={};try{e=new URL(t)}catch(t){}return e}function N(t,e){if(!t)return t;var o=t.toString(),r=o.indexOf(".");return o=-1!==r?o.substring(0,r+e+1):o.substring(0),parseFloat(o)}function L(t){t=t||window.location.hostname,/^[a-zA-Z0-9\u4e00-\u9fa5\-\\.]+$/.exec(t)||(t="");var e=t.split(".");if(e.length>=2&&!/^(\d+\.)+\d+$/.test(t))for(var o=".".concat(e.splice(e.length-1,1));e.length>0;)if(o=".".concat(e.splice(e.length-1,1)).concat(o),document.cookie="".concat(m,"=true; path=/; domain=").concat(o),-1!==document.cookie.indexOf("".concat(m,"=true")))return document.cookie="".concat(m,"=true; path=/; domain=").concat(o,"; max-age=0"),o;return""}function E(){var t=L();return""===t?"url解析失败":t}function O(t){var e=t||document.referrer;return"string"!=typeof e?"referrer exception".concat(String(e)):(e.startsWith("https://www.baidu.com/")&&(e=e.split("?")[0]),"string"==typeof(e=e.slice(0,200))?e:"")}function D(t,e){return e&&"string"==typeof e||(e="hostname解析异常"),t&&(P(t).hostname||"")||e}function U(){var t=R(),e=Math.floor(1e6*Math.random());return Number(String(t).slice(-5)+String(e).slice(0,4))}function B(t,e){e=e.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]"),t=decodeURIComponent(t);var o=new RegExp("[\\?&]".concat(e,"=([^&#]*)")).exec(t);return null===o||o&&"string"!=typeof o[1]&&o[1].length?"":decodeURIComponent(o[1])}function W(t){try{return btoa(encodeURIComponent(t).replace(/%([0-9A-F]{2})/g,(function(t,e){return String.fromCharCode(Number("0x".concat(e)))})))}catch(e){return t}}function M(t,e,o,r){if(void 0!==t&&(e in t||r)){var n=o(t[e]);T(n)&&(t[e]=n)}}var j=function(){function t(){this.name="CookieStorage"}return t.prototype.isSupport=function(t,e){var o=this;void 0===t&&(t="cookie_support_test"),void 0===e&&(e="1");return navigator.cookieEnabled&&(o.set(t,e),o.get(t)===e&&(o.remove(t),!0))},t.prototype.get=function(t){var e,o,r=document.cookie.split(";");try{for(var n=u(r),i=n.next();!i.done;i=n.next()){var a=i.value.split("=");if(a[0].trim()===t)return decodeURIComponent(a[1])}}catch(t){e={error:t}}finally{try{i&&!i.done&&(o=n.return)&&o.call(n)}finally{if(e)throw e.error}}return null},t.prototype.set=function(t,e,o,r,n,i,a){r=r||"/",t=t.trim(),e=e.trim();var s="".concat(t,"=").concat(encodeURIComponent(e),"; path=").concat(r,";");o=w(o)?o:63072e8,s+=" max-age=".concat(o,";"),a&&(s+=" secure;"),n&&(s+=" domain=".concat(n,";")),["Strict","Lax","None"].includes(i)&&(s+=" SameSite=".concat(i,";")),document.cookie=s},t.prototype.remove=function(t,e){void 0===e&&(e="/"),this.set(t,"1",0,e)},t.prototype.setDomain=function(t,e,o){var r=E();"url解析失败"===r&&(r=""),this.set(t,e,o,"/",r)},t}(),q=function(){function t(){this.name="LocalStorage"}return t.prototype.isSupport=function(){var t=!0;try{var e="__localStorageSupport__",o="testIsSupportStorage";this.set(e,o),this.get(e)!==o&&(t=!1),this.remove(e)}catch(e){t=!1}return t},t.prototype.key=function(t){return window.localStorage.key(t)},t.prototype.get=function(t){return window.localStorage.getItem(t)},t.prototype.length=function(){return window.localStorage.length},t.prototype.set=function(t,e){try{window.localStorage.setItem(t,e)}catch(t){}},t.prototype.remove=function(t){window.localStorage.removeItem(t)},t.prototype.parse=function(t){var e=this.get(t);try{e=JSON.parse(e)}catch(t){e=""}return e},t}(),F=function(){function t(){this.name="MemoryStorage",this.data={}}return t.prototype.get=function(t){var e=this.data[t];return w(null==e?void 0:e.expireTime)?e.expireTime<R()?null:e.value:null==e?void 0:e.value},t.prototype.set=function(t,e,o){if(w(o)){var r=R()+1e3*o;this.data[t]={value:e,expireTime:r}}this.data[t]={value:e}},t.prototype.setDomain=function(t,e,o){this.set(t,e,o)},t}();function V(e,o){if(void 0===o&&(o=t.ConsoleTypes.LOG),"undefined"!=typeof console){var r=console[o]||console.log;"function"==typeof r&&r(e)}}var z,K={all:z=z||new Map,on:function(t,e){var o=z.get(t);o?o.push(e):z.set(t,[e])},emit:function(t,e){var o=z.get(t);o&&o.forEach((function(t){t(e)}))},off:function(t,e){var o=z.get(t);if(o)if(e){var r=o.indexOf(e);r>=0&&o.splice(r,1)}else z.set(t,[])}},J=function(){function e(t,e){this.options=t,this.isFirstTime=!1,this.isFirstDay=!1,this.state=e}return e.prototype.log=function(e,o){void 0===o&&(o=t.ConsoleTypes.LOG),this.options.showLog&&V(e,o)},e.prototype.checkSetValue=function(e,o){return!(!x(o=null!=o?o:"")&&!S(o))||(this.log("".concat(e,": id must be string or number"),t.ConsoleTypes.WARN),!1)},e.prototype.setDeviceId=function(t){void 0===t&&(t=""),this.checkSetValue("deviceId",t)&&this.set("deviceId",t)},e.prototype.setAccountId=function(t){void 0===t&&(t=""),this.checkSetValue("accountId",t)&&(this.set("accountId",t),K.emit("changeAccountId"))},e.prototype.setAnonymousId=function(e){this.state.anonymousId?this.log("Current anonymousId is ".concat(this.getAnonymousId(),", it has been set"),t.ConsoleTypes.WARN):this.checkSetValue("anonymousId",e)&&this.set("anonymousId",e)},e.prototype.setProps=function(t){var e=I(this.state.props||{},t);for(var o in e)"string"==typeof e[o]&&(e[o]=e[o].slice(0,200));this.set("props",e)},e.prototype.getAnonymousId=function(){return this.state.anonymousId},e.prototype.getDeviceId=function(){return this.state.deviceId},e.prototype.getAccountId=function(){return this.state.accountId},e.prototype.clear=function(){this.state={},this.save()},e.prototype.set=function(t,e){this.state[t]=e,this.save()},e.prototype.afterInit=function(t){t?(this.isFirstDay=function(t){var e;try{var o=new Date,r=o.getFullYear(),n=o.getMonth()+1,i=o.getDate(),a=new Date(t),s=a.getFullYear(),c=a.getMonth()+1,u=a.getDate();e=r===s&&n===c&&i===u}catch(t){e=!1}return e}(this.state.firstVisitTime),this.save()):(this.isFirstDay=!0,this.isFirstTime=!0);var e="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(t){var e=16*Math.random()|0;return"x"===t?e.toString(16):(3&e|8).toString(16)}));this.getAnonymousId()||this.setAnonymousId(e),this.getDeviceId()||this.setDeviceId(e)},e}(),G=function(e){function r(t){var o=this,r={accountId:null,deviceId:null,anonymousId:null,sessionId:null,firstVisitTime:R(),props:{}};return(o=e.call(this,t,r)||this).options=t,o.storeName="hinasdk_crossdata",o.hLatestUtm={},o.hUtm={},o.customUtm={},o}return o(r,e),r.prototype.getUtmFromProps=function(t){for(var e in this.state.props){var o=this.state.props[e];e.startsWith("H_latest_")?this.hLatestUtm[e]=o:e.startsWith("H_")&&(this.hUtm[e]=o),t.includes(e)&&(this.customUtm[e]=o)}},r.prototype.init=function(){var e,o=new j,r=new F,n=new q;o.isSupport()?this.storage=o:(this.log("Cookie storage is not supported, SDK internal cache has been enabled",t.ConsoleTypes.WARN),this.storage=r),n.isSupport()?this.localStorage=n:this.log("localStorage is not supported, SDK internal cache has been enabled",t.ConsoleTypes.WARN),!(e=this.storage.get(this.storeName))&&this.localStorage&&(e=this.localStorage.get(this.storeName)),e&&function(t){try{JSON.parse(t)}catch(t){return!1}return!0}(e)?this.state=H(e):e=null,this.afterInit(e)},r.prototype.save=function(){this.storage.setDomain(this.storeName,JSON.stringify(this.state)),this.localStorage&&this.localStorage.set(this.storeName,JSON.stringify(this.state))},r.prototype.getCookie=function(){return this.storage.get(this.storeName)},r.prototype.setSessionId=function(t){this.set("sessionId",t)},r.prototype.getSessionId=function(){return this.state.sessionId||""},r.prototype.getSessionIdCreateTime=function(){var t=this.getSessionId().split("_")[0],e=Number(t);return Number.isNaN(e)?0:e},r}(J),$=function(){function t(){this.isReady=!1,this.isReady||this.init(),this.isReady=!0}return t.prototype.init=function(){this.os=this.getOs(),this.osVersion=this.getOsVersion();var t=this.getBrowser(),e=t.type,o=t.version;this.browserName=e,this.browserVersion=o,this.model=this.getModel()},t.prototype.getOs=function(){var t=navigator.userAgent;return/Windows/i.test(t)?/Phone/.test(t)||/WPDesktop/.test(t)?"Windows Phone":"Windows":/(iPhone|iPad|iPod)/.test(t)&&!window.MSStream?"iOS":/Android/.test(t)?"Android":/(BlackBerry|PlayBook|BB10)/i.test(t)?"BlackBerry":/Mac/i.test(t)?"Mac OS X":/Linux/.test(t)?"Linux":/CrOS/.test(t)?"Chrome OS":"取值异常"},t.prototype.getOsVersion=function(){var t=navigator.userAgent;if(/Windows/i.test(t)){var e=/Windows NT ([\d.]+)/;return t.match(e)?t.match(e)[1]:""}if(/(iPhone|iPad|iPod)/.test(t)&&!window.MSStream){e=/OS ([\d_]+)/;return t.match(e)?t.match(e)[1].replace(/_/g,"."):""}if(/Android/.test(t)){e=/Android ([\d.]+)/;return t.match(e)?t.match(e)[1]:""}if(/Mac/i.test(t)){e=/Mac OS X ([\d_]+)/;return t.match(e)?t.match(e)[1].replace(/_/g,"."):""}return""},t.prototype.getBrowser=function(){var t,e={type:"",version:""};try{var o=null===(t=navigator.userAgent)||void 0===t?void 0:t.toLowerCase(),r=[];if(null!==o.match(/baidubrowser/)?(e.type="baidu",r.push(/baidubrowser\/([\d.]+)/)):null!==o.match(/bidubrowser/)?(e.type="baidu",r.push(/bidubrowser\/([\d.]+)/)):null!==o.match(/edg/)?(e.type="edge",r.push(/edg\/([\d.]+)/)):null!==o.match(/edgios/)?(e.type="edge",r.push(/edgios\/([\d.]+)/)):null!==o.match(/liebaofast/)?(e.type="liebao",r.push(/liebaofast\/([\d.]+)/)):null!==o.match(/sogoumobilebrowser/)?(e.type="sogou",r.push(/sogoumobilebrowser\/([\d.]+)/)):null!==o.match(/lbbrowser/)?(e.type="liebao",r.push(/lbbrowser\/([\d.]+)/)):null!==o.match(/crios/)?(e.type="chrome",r.push(/crios\/([\d.]+)/)):null!==o.match(/qihoobrowser/)?(e.type="360",r.push(/qihoobrowser\/([\d.]+)/)):null!==o.match(/mxios/)?(e.type="maxthon",r.push(/mxios\/([\d.]+)/)):null!==o.match(/fxios/)?(e.type="firefox",r.push(/fxios\/([\d.\w]+)/)):null!==o.match(/edge/)?(e.type="edge",r.push(/edge\/([\d.]+)/)):null!==o.match(/metasr/)?(e.type="sogou",r.push(/metasr ([\d.]+)/)):null!==o.match(/micromessenger/)?(e.type="micromessenger",r.push(/micromessenger\/([\d.]+)/)):null!==o.match(/mqqbrowser/)?(e.type="qq",r.push(/mqqbrowser\/([\d.]+)/)):null!==o.match(/qqbrowserlite/)?(e.type="qq",r.push(/qqbrowserlite\/([\d.]+)/)):null!==o.match(/tencenttraveler/)?(e.type="qq",r.push(/tencenttraveler\/([\d.]+)/)):null!==o.match(/qqbrowser/)?(e.type="qq",r.push(/qqbrowser\/([\d.]+)/)):null!==o.match(/maxthon/)?(e.type="maxthon",r.push(/maxthon\/([\d.]+)/)):null!==o.match(/ubrowser/)?(e.type="uc",r.push(/ubrowser\/([\d.]+)/)):null!==o.match(/ucbrowser/)?(e.type="uc",r.push(/ucbrowser\/([\d.]+)/)):null!==o.match(/firefox/)?(e.type="firefox",r.push(/firefox\/([\d.]+)/)):null!==o.match(/opera/)?(e.type="opera",r.push(/opera\/([\d.]+)/)):null!==o.match(/opr/)?(e.type="opera",r.push(/opr\/([\d.]+)/)):null!==o.match(/chrome/)?(e.type="chrome",r.push(/chrome\/([\d.]+)/)):null!==o.match(/safari/)?(e.type="safari",r.push(/version\/([\d.]+)/)):null===o.match(/trident/)&&null===o.match(/msie/)||(e.type="ie"),"ie"===e.type){var n=o.match(/trident\/([\d.]+)/)?o.match(/trident\/([\d.]+)/)[1]:"",i=o.match(/msie ([\d.]+)/)?o.match(/msie ([\d.]+)/)[1]:"";""!==n?e.version=String(parseInt(n,10)+4):""!==i&&(e.version=i)}else r&&(e.version=o.match(r[0])?o.match(r[0])[1]:"")}catch(t){e.type="取值异常"}return e},t.prototype.getModel=function(){var t=navigator.userAgent;if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(t)){if(/iPhone|iPad|iPod/i.test(t))return t.match(/iPhone|iPad|iPod/i)[0];if(/Android/i.test(t))return t.match(/Android/i)[0]}var e=t.match(/Mac/);if(e)return e[0];var o=t.match(/Windows/);if(o)return o[0];var r=t.match(/Linux/);return r?r[0]:"取值异常"},t}();function X(){return document.documentElement.scrollTop||document.body.scrollTop||0}function Z(){return window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight||0}function Y(){return window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth||0}var Q=function(){function t(t){this.visibleHandler=function(){},this.hiddenHandler=function(){};var e=t.visible,o=t.hidden;T(e)&&(this.visibleHandler=e),T(o)&&(this.hiddenHandler=o),this.init()}return t.prototype.isSupport=function(){return void 0!==document.hidden},t.prototype.init=function(){var t=this;this.isSupport()?document.addEventListener("visibilitychange",(function(){document.hidden?t.hiddenHandler():t.visibleHandler()})):(window.addEventListener("focus",this.visibleHandler),window.addEventListener("blur",this.hiddenHandler))},t}();var tt=function(){function t(t){this.options=t}return t.prototype.run=function(){var t=this;return new Promise((function(e){var o=t.options,r=o.imgUseCrossOrigin,n=o.url,i=o.data,a=new Image;r&&(a.crossOrigin="anonymous");var s=-1===n.indexOf("?")?"?":"&";a.src="".concat(n).concat(s).concat(i);var c=function(t){a=null,e({type:t})};a.onload=function(){c("success")},a.onerror=function(){c("success")}}))},t}(),et=function(){function t(t){this.options=t}return t.prototype.run=function(){var t=this;return new Promise((function(e){var o=t.options,r=o.url,n=o.data,i=o.timeout,a=o.credentials,s=o.contentType,c=o.customHeaders,u=void 0===c?{}:c,l=new XMLHttpRequest;l.open("POST",r,!0),l.timeout=i||2e4,l.isMonitor=!0,a&&(l.withCredentials=!0),l.setRequestHeader("Content-Type",s||"application/x-www-form-urlencoded"),b(u)&&!A(u)&&Object.keys(u).forEach((function(t){l.setRequestHeader(t,u[t])})),l.send(n||null),l.ontimeout=function(){l.abort()},l.onreadystatechange=function(){4===l.readyState&&(l.status>=200&&l.status<300||304===l.status?e({data:JSON.parse(l.responseText)||{},type:"success"}):e({type:"fail",msg:"网络异常, 请求失败,状态码=".concat(l.status)}))}}))},t}(),ot=function(){function t(t){this.options=t}return t.prototype.run=function(){var t=this;return new Promise((function(e){var o=t.options,r=o.url,n=o.data;navigator.sendBeacon&&e(navigator.sendBeacon(r,n)?{type:"success"}:{type:"fail",msg:"sendBeacon 请求失败"})}))},t}(),rt=function(){function e(t,e,o){void 0===e&&(e="hinasdk_tab"),void 0===o&&(o="hinasdk_data_"),this.options=t,this.batchKey=e,this.batchDataKey=o,this.isSending=!1,this.init()}return e.prototype.log=function(e,o){void 0===o&&(o=t.ConsoleTypes.LOG),this.options.showLog&&V(e,o)},e.prototype.init=function(){var e=new q;e.isSupport()?(this.localStorage=e,this.isSupport=!0):(this.isSupport=!1,this.log("批量发送功能需要使用localstorage存储数据,但是您的浏览器不支持localstorage,所以不能使用该功能",t.ConsoleTypes.WARN)),this.batchInterval()},e.prototype.getBatchConfig=function(){return this.options.batchSend},e.prototype.getStorageList=function(){if(!this.isSupport)return[];var t=[],e=this.localStorage.get(this.batchKey);return e&&(_(t=H(e))||(t=[])),t},e.prototype.batchInterval=function(){var t=this;if(this.isSupport){var e=this.getBatchConfig().sendInterval;setTimeout((function(){t.send().then((function(){t.batchInterval()}))}),e)}},e.prototype.send=function(){var t=this;return new Promise((function(e){var o=t.getStorageList();if(o.length>0&&t.isSupport){for(var r=t.getBatchConfig().dataSendTimeout,n=R(),i=[],a={},s=o.length,c=0;c<s;c++){var u=o[c],l=u.dataKey,h=u.expireTime;if(h>=n)a[l]={dataKey:l,expireTime:h},(y=t.localStorage.get(l))&&i.push(H(y));else t.localStorage.remove(l),o.splice(c,1),s--,c--}if(t.localStorage.set(t.batchKey,JSON.stringify(o)),0===i.length)e();else{var p=t.options,f=p.serverUrl,d=p.customHeaders,g=p.credentials,v=p.globalCallback,m=JSON.stringify(i),y=encodeURIComponent(W(m));t.isSending=!0,new et({url:f,data:"data_list=".concat(y),timeout:r,credentials:g,customHeaders:d}).run().then((function(o){T(v)&&v(f,i,o.type,o.msg||""),"success"===o.type&&t.remove(a),e(),t.isSending=!1}))}}else e()}))},e.prototype.remove=function(t){var e=this;if(this.isSupport){var o=this.getStorageList(),r=Object.keys(t);if(r.forEach((function(t){e.localStorage.remove(t)})),o.length===r.length)this.localStorage.set(this.batchKey,JSON.stringify([]));else{var n=o.filter((function(e){return!t[e.dataKey]}));this.localStorage.set(this.batchKey,JSON.stringify(n))}}},e.prototype.add=function(t){if(this.isSupport){var e,o,r=this.getBatchConfig(),n=r.sendInterval,i=r.storageLimit,a=this.batchDataKey+(e=R(),o=Math.floor(1e6*Math.random()),"".concat(e,"_").concat(o)),s=this.getStorageList();s.unshift({dataKey:a,expireTime:R()+2*n}),this.localStorage.set(this.batchKey,JSON.stringify(s)),this.localStorage.set(a,JSON.stringify(t)),!this.isSending&&(s.length>i||"track_signup"===t.type||"H_pageview"===t.event)&&this.send()}},e}();function nt(e,o){Object.keys(e).forEach((function(r){var n=e[r];if(S(n)&&n.length>o)V("属性 ".concat(r," 已经做截取")),e[r]=n.slice(0,o);else if(b(n))nt(n,o);else if(T(n))try{e[r]=n(e),T(e[r])?(V("属性--".concat(r," 格式不满足要求, 已被删除"),t.ConsoleTypes.WARN),delete e[r]):b(e[r])?nt(e[r],o):S(e[r])&&e[r].length>o&&(e[r]=e[r].slice(0,o))}catch(o){V("属性--".concat(r," 格式不满足要求, 已被删除"),t.ConsoleTypes.WARN),delete e[r]}}))}var it=["abtestExperimentId","paramName","valueType","defaultValue","callback","timeoutMilliseconds","customProperties","customIds"],at=function(e){function r(t,o,r,n,i){var a=e.call(this,t,o)||this;return a.options=t,a.context=o,a.name="AbtestBasePlugin",a.isReady=!1,a.platform="",a.storageName="",a.version="",a.projectKey="",a.platform=r,a.storageName=n,a.version=i,a}return o(r,e),r.prototype.init=function(){var e=this;if(this.context.store.localStorage){var o=this.options.abTestingPluginConfig,r=null==o?void 0:o.url;if(S(r)){var n=B(r,"project-key");if(n){if(this.projectKey=n,["Web","H5"].includes(this.platform)){var i=P(r).protocol,a=P(window.location.href).protocol;i&&i!==a&&this.context.log("A/B Testing 初始化失败,".concat(a," 页面必须使用 ").concat(a," 的 URL"),t.ConsoleTypes.WARN)}if(this.isReady)this.context.log("A/B Testing 插件已经运行,无需重复执行",t.ConsoleTypes.WARN);else{var s=this.context.getUserUid();this.context.log("当前accountId为:".concat(s),t.ConsoleTypes.INFO),K.on("changeAccountId",(function(){e.context.store.localStorage.set(e.storageName,"")})),this.isReady=!0}}else this.context.log("A/B Testing 初始化失败,请使用正确的 URL(必须包含 project-key)")}else this.context.log("A/B Testing 初始化失败,请使用正确的 URL!",t.ConsoleTypes.WARN)}else this.context.log("A/B Testing 初始化失败,浏览器不支持localStorage",t.ConsoleTypes.WARN)},r.prototype.transform=function(){},r.prototype.valueMatchType=function(e,o){switch(o){case t.VariablesTypes.INTEGER:return x(e);case t.VariablesTypes.STRING:return S(e);case t.VariablesTypes.BOOLEAN:return k(e);default:return!1}},r.prototype.normalizeParams=function(e,o,r){var n,i;void 0===r&&(r=it);var a={verify_success:!0,para:o};try{for(var s=u(r),c=s.next();!c.done;c=s.next()){var l=c.value;if(!a.verify_success)break;switch(l){case"abtestExperimentId":S(o.abtestExperimentId)&&o.abtestExperimentId.trim()||(this.context.log("".concat(e,"方法调用失败,").concat(l,"参数未正确配置!").concat(l,": ").concat(o.abtestExperimentId),t.ConsoleTypes.WARN),a.verify_success=!1);break;case"paramName":S(o.paramName)&&o.paramName.trim()||(this.context.log("".concat(e,"方法调用失败,").concat(l,"参数未正确配置!").concat(l,": ").concat(o.paramName),t.ConsoleTypes.WARN),a.verify_success=!1);break;case"valueType":[t.VariablesTypes.BOOLEAN,t.VariablesTypes.INTEGER,t.VariablesTypes.STRING].includes(o.valueType)||(this.context.log("".concat(e,"方法调用失败,").concat(l,"参数未正确配置!").concat(l,": ").concat(o.valueType),t.ConsoleTypes.WARN),a.verify_success=!1);break;case"defaultValue":this.valueMatchType(o.defaultValue,o.valueType)||(this.context.log("".concat(e,"方法调用失败,").concat(l,"类型必须与valueType一致!"),t.ConsoleTypes.WARN),a.verify_success=!1);break;case"callback":T(o.callback)||(this.context.log("".concat(e,"方法调用失败,").concat(l,"参数未正确配置")),o.callback=C,a.verify_success=!1);break;case"timeoutMilliseconds":(!x(o.timeoutMilliseconds)||o.timeoutMilliseconds<=0)&&(this.context.log("".concat(l,"参数错误:").concat(o.timeoutMilliseconds),t.ConsoleTypes.WARN),o.timeoutMilliseconds=3e3),o.timeoutMilliseconds<200&&(o.timeoutMilliseconds=200);break;case"customProperties":o.customProperties=b(o.customProperties)?o.customProperties:{};break;case"customIds":var h=o.customIds||{},p={};for(var f in h)(S(h[f])||x(h[f]))&&(p[f]=h[f]);o.customIds=p}}}catch(t){n={error:t}}finally{try{c&&!c.done&&(i=s.return)&&i.call(s)}finally{if(n)throw n.error}}return a},r.prototype.sendTriggerEvent=function(t){var e=t.abtest_experiment_group_id,o=t.abtest_experiment_id;this.context.track("H_ABTestTrigger",{H_abtest_experiment_id:o,H_abtest_experiment_group_id:e})},r.prototype.getExpResult=function(t){return s(this,arguments,void 0,(function(t,e){var o,r,n,i,a,s,l,h,p,f,d,g,v,m,y;return void 0===e&&(e=[]),c(this,(function(c){switch(c.label){case 0:return o=t.abtestExperimentId,r=t.paramName,n=t.valueType,0!==e.length?[3,2]:[4,this.getStorageData()];case 1:b(a=c.sent())&&(e=a.result||[]),c.label=2;case 2:try{for(s=u(e),l=s.next();!l.done;l=s.next())if(h=l.value,p=h.abtest_experiment_id,f=h.abtest_experiment_group_id,d=h.is_white_list,g=h.variables,p===o&&(v=g.find((function(t){return t.name===r&&t.type===n})),v)){d||this.sendTriggerEvent({abtest_experiment_id:p,abtest_experiment_group_id:f}),i=v.value;break}}catch(t){m={error:t}}finally{try{l&&!l.done&&(y=s.return)&&y.call(s)}finally{if(m)throw m.error}}return[2,i]}}))}))},r.prototype.getStorageData=function(){return s(this,void 0,void 0,(function(){var t;return c(this,(function(e){switch(e.label){case 0:return[4,this.context.store.localStorage.get(this.storageName)];case 1:return(t=e.sent())?[2,H(t)]:[2,null]}}))}))},r.prototype.saveResponseData=function(t){return s(this,void 0,void 0,(function(){var e,o,r,n;return c(this,(function(i){switch(i.label){case 0:return[4,this.getStorageData()];case 1:return e=i.sent(),o={updateTime:R()},e&&b(e)?(r=[],n=e.result||[],t.forEach((function(t){var e=t.abtest_experiment_group_id,o=t.abtest_experiment_id,i=t.variables,a=n.find((function(t){return t.abtest_experiment_id===o&&t.abtest_experiment_group_id===e}));if(a){var s=[];i.forEach((function(t){var e=t.name,o=t.type,r=a.variables.findIndex((function(t){return t.name===e&&t.type===o}));r>=0?a.variables[r]=t:s.push(t)})),a.variables=h(h([],l(a.variables),!1),l(s),!1)}else r.push(t)})),o.result=h(h([],l(n),!1),l(r),!1)):o.result=t,this.context.store.localStorage.set(this.storageName,JSON.stringify(o)),[2]}}))}))},r.prototype.createRequestData=function(t){var e=t.paramName,o=t.customProperties,r=t.customIds,n={anonymous_id:this.context.store.getAnonymousId(),platform:this.platform,abtest_lib_version:this.version,param_name:e,properties:this.context.getPresetProperties()};return b(o)&&!A(o)&&(n.custom_properties=o),b(r)&&!A(r)&&(n.custom_ids=r),this.context.getUserUid()&&(n.login_id=this.context.getUserUid()),n},r.prototype.preFetch=function(e,o){return this.isReady?!!b(o)||(this.context.log("".concat(e," 方法参数必须是对象"),t.ConsoleTypes.WARN),!1):(this.context.log("A/B Testing 插件尚未运行,请先执行该插件",t.ConsoleTypes.WARN),!1)},r.prototype.asyncFetch=function(t){var e=this;return new Promise((function(o){e.getResultFromServer(t).then((function(t){o(t)})).catch((function(){t.callback(t.defaultValue)}))}))},r.prototype.asyncFetchABTest=function(t){var e=this;if(this.preFetch("asyncFetchABTest",t)){var o=this.normalizeParams("asyncFetchABTest",t),r=o.verify_success,n=o.para;r?this.asyncFetch(n).then((function(t){return s(e,void 0,void 0,(function(){var e;return c(this,(function(o){switch(o.label){case 0:return[4,this.getExpResult(n,t.results)];case 1:return e=o.sent(),n.callback(e||n.defaultValue),[2]}}))}))})):n.callback(n.defaultValue)}},r.prototype.fetchCacheABTest=function(t){return s(this,void 0,void 0,(function(){var e,o,r,n;return c(this,(function(i){switch(i.label){case 0:return this.preFetch("fetchCacheABTest",t)?(e=this.normalizeParams("fetchCacheABTest",t),o=e.verify_success,r=e.para,o?[4,this.getExpResult(r)]:[3,2]):[2];case 1:return n=i.sent(),r.callback(n||r.defaultValue),[3,3];case 2:r.callback(r.defaultValue),i.label=3;case 3:return[2]}}))}))},r.prototype.fastFetchABTest=function(t){return s(this,void 0,void 0,(function(){var e,o,r,n,i=this;return c(this,(function(a){switch(a.label){case 0:return this.preFetch("fastFetchABTest",t)?(e=this.normalizeParams("fastFetchABTest",t),o=e.verify_success,r=e.para,o?[4,this.getExpResult(r)]:[3,2]):[2];case 1:return w(n=a.sent())?r.callback(n):this.asyncFetch(r).then((function(){return s(i,void 0,void 0,(function(){var t;return c(this,(function(e){switch(e.label){case 0:return[4,this.getExpResult(r)];case 1:return t=e.sent(),r.callback(t||r.defaultValue),[2]}}))}))})),[3,3];case 2:r.callback(r.defaultValue),a.label=3;case 3:return[2]}}))}))},r}(p),st=function(){function e(t,e){void 0===e&&(e=!0),this.isReady=!1,this.consolePrefix="埋点SDK",this.useInstancing=!0,this.plugins=[],this.options=t,this.useInstancing=e}return e.prototype.log=function(e,o){void 0===o&&(o=t.ConsoleTypes.LOG),this.options.showLog&&("string"==typeof e&&this.consolePrefix&&(e="".concat(this.consolePrefix,":").concat(e)),V(e,o))},e.prototype.runPlugins=function(t){var e=this;t.forEach((function(t){t.disabled||t.init((function(o){if(t.transform){var r=t.transform(o);r&&e.report(r)}}))}))},e.prototype.applyPlugins=function(e){var o=this;if(this.isReady){_(e)||(e=[e]);var r=[];e.forEach((function(t){var e=new t(o.options,o);o.plugins.push(e),r.push(e)})),this.runPlugins(r)}else this.log("请先初始化SDK实例",t.ConsoleTypes.WARN)},e}(),ct=function(e){function r(){return null!==e&&e.apply(this,arguments)||this}return o(r,e),r.prototype.sendReportData=function(e,o,r){var n=this.options,i=n.batchSend,a=n.globalCallback,s=n.serverUrl,c=n.dataSendTimeout,u=n.sendType,l=n.customHeaders,h=n.credentials,p=n.imgUseCrossOrigin;if(u=r||u,s){if(b(e)&&!A(e))if(i)this.batchSender.add(e);else{var f=e;S(e)||(f=function(t){try{return JSON.stringify(t)}catch(e){return t}}(e));var d=W(f),g={data:"data=".concat(encodeURIComponent(d)),url:s,timeout:c,imgUseCrossOrigin:p,customHeaders:l,credentials:h};(u===t.ReportTypes.BEACON&&navigator.sendBeacon?new ot(g):u===t.ReportTypes.IMAGE&&g.data.length<2048?new tt(g):new et(g)).run().then((function(t){return T(a)&&a(s,e,t.type,t.msg||""),T(o)&&o(s,e,t.type,t.msg||""),t}))}}else this.log("当前 serverUrl 为空,network 中不会发数据,请配置正确的 serverUrl!",t.ConsoleTypes.WARN)},r}(st);function ut(t){return 1===(null==t?void 0:t.nodeType)}function lt(t,e){var o;if("input"===(null===(o=t.tagName)||void 0===o?void 0:o.toLowerCase()))return(["button","submit"].includes(t.type)||e)&&t.value||"";var r="";return t.textContent?r=t.textContent.trim():t.innerText&&(r=t.innerText.trim()),r&&(r=r.replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)),r||""}function ht(t,e){var o;if(!ut(t))return{};var r,n={H_element_type:null===(o=t.tagName)||void 0===o?void 0:o.toLowerCase(),H_element_name:t.getAttribute("name"),H_element_id:t.getAttribute("id"),H_element_target_url:t.getAttribute("href"),H_element_class_name:t.classList.value||t.className,H_element_content:lt(t,e)};return r=n,Object.keys(r).reduce((function(t,e){return w(r[e])&&""!==r[e]&&(t[e]=r[e]),t}),{})}function pt(t,e){if(!t)return{};var o=document.documentElement.scrollLeft||document.body.scrollLeft||0,r=X(),n=e.getBoundingClientRect(),i=t.pageX||t.clientX+o||t.offsetX+((null==n?void 0:n.left)||0)+o,a=t.pageY||t.clientY+r||t.offsetY+((null==n?void 0:n.top)||0)+r;return{H_page_x:N(i,3),H_page_y:N(a,3)}}var ft=["mark","/mark","strong","b","em","i","u","abbr","ins","del","s","sup"],dt=["a","input","button","textarea"],gt=function(e){function r(t,o){var r=e.call(this,t,o)||this;return r.options=t,r.context=o,r.name="ClickTrackPlugin",r.isReady=!1,r.isTrackList={a:!0,button:!0},r}return o(r,e),r.prototype.init=function(e){var o=this,r=this.options.autoTrackConfig,n=r.clickAutoTrack,i=r.isCollectUrl,a=r.isCollectElement,s=r.addCustomProperty;!0===n&&(this.isReady?this.context.log("ClickTrack plugin:插件已经运行,无需重复执行",t.ConsoleTypes.WARN):(this.isReady=!0,document.addEventListener("click",(function(t){if(i()){var r=t||window.event;if(r){var n=r.target||r.srcElement,c=o.getTargetElement(n);if(c){if(T(a)&&!a(c))return!1;var u=o.getClickElementInfo(c),l=pt(r,c),h=l.H_page_x,p=l.H_page_y;u.H_page_x=h,u.H_page_y=p;var f=o.getElementPosition(c,u.H_element_path);if(x(f)&&f>=0&&(u.H_element_position=f),T(s)){var d=s(c);b(d)&&(u=I(u,d))}e(u)}}}}),!0)))},r.prototype.transform=function(t){return this.context.getReportData("track","H_WebClick",t)},r.prototype.hasAttribute=function(t,e){var o;return t.hasAttribute?t.hasAttribute(e):t.attributes?!!(null===(o=t.attributes[e])||void 0===o?void 0:o.value):void 0},r.prototype.hasAttributes=function(t,e){if(_(e))for(var o=0;o<e.length;o++)if(this.hasAttribute(t,e[o]))return!0;return!1},r.prototype.hasElement=function(t){var e,o,r,n=function(t){var e=[t];try{if(!ut(t))return e;if(null===t||null===t.parentElement)return e;for(;null!==t.parentElement;)t=t.parentElement,e.push(t);return e}catch(t){}return e}(t),i=this.options.autoTrackConfig.trackAttr||[];if(_(n)&&n.length>0)try{for(var a=u(n),s=a.next();!s.done;s=a.next()){var c=s.value,l=c.tagName&&(null===(r=c.tagName)||void 0===r?void 0:r.toLowerCase());if(ut(c)&&(this.isTrackList[l]||this.hasAttributes(c,i)))return c}}catch(t){e={error:t}}finally{try{s&&!s.done&&(o=a.return)&&o.call(a)}finally{if(e)throw e.error}}},r.prototype.getDivMaxLevel=function(){var t;return(null===(t=this.options.autoTrackConfig.collectTags.div)||void 0===t?void 0:t.maxLevel)||1},r.prototype.isStyleTag=function(t){var e,o=(null===(e=this.options.autoTrackConfig.collectTags.div)||void 0===e?void 0:e.ignoreTags)||[];return null==o?void 0:o.includes(t)},r.prototype.getCollectableParent=function(e){var o;try{var r=e.parentNode,n=r?null===(o=r.tagName)||void 0===o?void 0:o.toLowerCase():"";if("body"===n)return!1;var i=this.getDivMaxLevel();if("div"===n&&(i>1||this.isCollectableDiv(r)))return r;if(r&&this.isStyleTag(n))return this.getCollectableParent(r)}catch(e){this.context.log(e,t.ConsoleTypes.ERROR)}return!1},r.prototype.isCollectableDiv=function(e){var o;try{var r=e.children||[];if(0===r.length)return!0;for(var n=0;n<r.length;n++){var i=r[n];if(ut(i)){var a=null===(o=i.tagName)||void 0===o?void 0:o.toLowerCase(),s=this.getDivMaxLevel();if(!("div"===a&&s>1||this.isStyleTag(a)))return!1;if(!this.isCollectableDiv(i))return!1}}return!0}catch(e){this.context.log(e,t.ConsoleTypes.ERROR)}return!1},r.prototype.isDivLevelValid=function(t){for(var e=this.getDivMaxLevel(),o=t.getElementsByTagName("div"),r=o.length-1;r>=0;r--)if(this.getDivLevels(o[r],t)>e)return!1;return!0},r.prototype.getElementPath=function(t,e,o){for(var r,n,i=[];ut(t)&&t.parentNode;){if(t.id&&!e&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.id)){var a=t.tagName||"";i.unshift("".concat(a.toLowerCase(),"#").concat(t.id));break}if(o&&t===o){i.unshift(null===(r=t.tagName)||void 0===r?void 0:r.toLowerCase());break}if(t===document.body){i.unshift("body");break}i.unshift(null===(n=t.tagName)||void 0===n?void 0:n.toLowerCase()),t=t.parentNode}return i.join(" > ")},r.prototype.getDivLevels=function(t,e){var o=this.getElementPath(t,!0,e).split(" > "),r=0;return o.forEach((function(t){"div"===t&&r++})),r},r.prototype.getTargetElement=function(t){var e;if(!ut(t))return null;var o=null===(e=t.tagName)||void 0===e?void 0:e.toLowerCase();if(!S(o))return null;if(["body","html"].includes(o))return null;if(this.context.trackTags.includes(o)&&"div"!==o)return t;if("div"===o&&this.options.autoTrackConfig.collectTags.div&&(this.isDivLevelValid(t)&&(this.getDivMaxLevel()>1||this.isCollectableDiv(t))))return t;if(this.options.autoTrackConfig.collectTags.div&&this.isStyleTag(o)){var r=this.getCollectableParent(t);if(r&&this.isDivLevelValid(r))return r}return this.hasElement(t)||null},r.prototype.getClickElementInfo=function(t){var e=this.options.autoTrackConfig.isCollectInput,o=!1;T(e)&&(o=e(t));var r=this.getDomSelector(t),n=ht(t,o);return n.H_element_selector=r,n.H_element_path=this.getElementPath(t,!1),n},r.prototype.getDomSelector=function(t){for(var e,o=[];t;){if("body"===(null===(e=t.tagName)||void 0===e?void 0:e.toLowerCase())||!ut(t)){o.unshift("body");break}if(o.unshift(this.getSelector(t)),(null==t?void 0:t.getAttribute("id"))&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(t.getAttribute("id")))break;t=t.parentNode}return o.join(" > ")},r.prototype.getSelector=function(t){var e,o,r=null===(e=t.tagName)||void 0===e?void 0:e.toLowerCase(),n=-1;9!==(null===(o=t.parentNode)||void 0===o?void 0:o.nodeType)&&(n=this.getDomIndex(t));var i=t.getAttribute("id");return i&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(i)?"#".concat(i):r+(n>-1?":nth-of-type(".concat(n+1,")"):"")},r.prototype.getDomIndex=function(t){var e,o;if(t.parentNode)for(var r=0,n=null===(e=t.tagName)||void 0===e?void 0:e.toLowerCase(),i=t.parentNode.children,a=0;a<i.length;a++){var s=i[a];if((null===(o=s.tagName)||void 0===o?void 0:o.toLowerCase())===n){if(s===t)return r;r++}}return-1},r.prototype.getClosestLi=function(t){for(;t&&t!==document&&ut(t);){if("li"===t.tagName.toLowerCase())return t;t=t.parentNode}return null},r.prototype.getSameTypeSiblings=function(t){for(var e,o,r=t.parentNode,n=null===(e=t.tagName)||void 0===e?void 0:e.toLowerCase(),i=[],a=0;a<r.children.length;a++){var s=r.children[a];ut(s)&&(null===(o=s.tagName)||void 0===o?void 0:o.toLowerCase())===n&&i.push(s)}return i},r.prototype.getElementPosition=function(t,e){var o,r=this.getClosestLi(t);if(!r||!ut(t)||!S(t.tagName))return null;var n=null===(o=t.tagName)||void 0===o?void 0:o.toLowerCase(),i=r.getElementsByTagName(n),a=i.length;if(a>1){for(var s=[],c=0;c<a;c++){this.getElementPath(i[c],!1)===e&&s.push(i[c])}if(s.length>0)return s.findIndex((function(e){return e===t}))}if(!r.parentNode)return-1;var u=this.getSameTypeSiblings(r);return 1===u.length?0:u.findIndex((function(t){return t===r}))},r}(p),vt=function(e){function r(t,o){var r=e.call(this,t,o)||this;return r.options=t,r.context=o,r.name="StayTrackPlugin",r.isReady=!1,r.timer=null,r.previousTime=R(),r.previousOffsetTop=0,r}return o(r,e),r.prototype.init=function(e){var o=this,r=this.options,n=r.autoTrackConfig,i=r.stayAutoTrackConfig;if(!0===n.stayAutoTrack)if(this.isReady)this.context.log("StayTrack plugin:插件已经运行,无需重复执行",t.ConsoleTypes.WARN);else{this.isReady=!0;var a=i.isCollectUrl;T(a)||(a=function(){return!0}),this.timer&&(clearTimeout(this.timer),this.timer=null),this.previousTime=R(),window.addEventListener("load",(function(){o.previousOffsetTop=X()})),window.addEventListener("scroll",(function(){a()&&(o.timer||(o.timer=setTimeout((function(){o.run(e),clearTimeout(o.timer),o.timer=null}),1e3)))})),window.addEventListener("unload",(function(){a()&&o.run(e,!0)}))}},r.prototype.transform=function(t){return this.context.getReportData("track","H_WebStay",t)},r.prototype.run=function(t,e){void 0===e&&(e=!1);var o=this.options.autoTrackConfig,r=o.stayDelayTime,n=o.maxStayPageDuration,i=X(),a=R(),s=a-this.previousTime;(e||s>r&&i!==this.previousOffsetTop)&&t({H_viewport_width:Y(),H_viewport_height:Z(),H_viewport_position:this.previousOffsetTop,event_duration:Math.min(s/1e3,n),H_url_path:window.location.pathname});this.previousTime=a,this.previousOffsetTop=i},r}(p),mt=function(e){function r(t,o){var r=e.call(this,t,o)||this;return r.options=t,r.context=o,r.name="PageLeave",r.isReady=!1,r.pageId=U(),r.storageName="hinasdk_pageleave_",r.heartbeatIntervalTime=5e3,r.maxDuration=432e3,r.heartbeatIntervalTimer=null,r.startTime=R(),r.url=window.location.href,r.pageShowStatus=!0,r}return o(r,e),r.prototype.init=function(){if(this.options.autoTrackConfig.pageLeaveAutoTrack)if(this.context.store.localStorage)if(this.isReady)this.context.log("PageLeave plugin:插件已经运行,无需重复执行",t.ConsoleTypes.WARN);else{this.isReady=!0;var e=this.normalizePageLeaveAutoTrack(),o=e.heartbeat_interval_time,r=e.max_duration;o&&o>0&&(this.heartbeatIntervalTime=1e3*o),r&&r>0&&(this.maxDuration=Number(r)),this.startTime=R(),this.addPageLeaveEventListener(),document.hidden?this.pageShowStatus=!1:this.startHeartBeatInterval()}else this.context.log("PageLeave plugin需要使用localstorage存储数据,但是您的浏览器不支持localstorage,所以不能使用该功能",t.ConsoleTypes.WARN)},r.prototype.transform=function(){},r.prototype.normalizePageLeaveAutoTrack=function(){var t=this.options.autoTrackConfig.pageLeaveAutoTrack;return b(t)?t:{}},r.prototype.addPageLeaveEventListener=function(){this.addPageStartListener(),this.addPageSwitchListener(),this.addSinglePageListener(),this.addPageEndListener()},r.prototype.addPageStartListener=function(){var t=this;"onpageshow"in window&&window.addEventListener("pageshow",(function(){t.pageStartHandler()}))},r.prototype.addPageSwitchListener=function(){var t=this;new Q({visible:function(){t.pageStartHandler(),t.startHeartBeatInterval()},hidden:function(){t.url=window.location.href,t.pageEndHandler(),t.stopHeartBeatInterval()}})},r.prototype.addSinglePageListener=function(){var t=this;K.on("urlChange",(function(e){var o=e.fromHref;o!==e.toHref&&(t.url=o,t.pageEndHandler(),t.stopHeartBeatInterval(),t.pageStartHandler(),t.startHeartBeatInterval())}))},r.prototype.addPageEndListener=function(){var t=this,e=["pagehide","beforeunload","unload"];e.forEach((function(o){"on".concat(e)in window&&window.addEventListener(o,(function(){t.pageEndHandler(),t.stopHeartBeatInterval()}))}))},r.prototype.pageStartHandler=function(){this.startTime=R(),this.pageShowStatus=!document.hidden,this.url=window.location.href},r.prototype.pageEndHandler=function(){if(this.pageShowStatus){if(this.pageShowStatus=!1,this.isCollectUrl()){var t=this.getPageLeaveProperties(),e=this.context.getReportData("track","H_WebPageLeave",t);this.context.report(e)}this.delHeartBeatData()}},r.prototype.startHeartBeatInterval=function(){var t=this;this.heartbeatIntervalTimer&&this.stopHeartBeatInterval(),this.isCollectUrl()&&(this.heartbeatIntervalTimer=setInterval((function(){t.saveHeartBeatData()}),this.heartbeatIntervalTime),this.saveHeartBeatData("first_heartbeat")),this.reissueHeartBeatData()},r.prototype.reissueHeartBeatData=function(){for(var t=this.context.store.localStorage,e=t.length(),o=0;o<e;o++){var r=t.key(o);if(r&&r!==this.storageName+this.pageId&&r.includes(this.storageName)){var n=H(t.get(r));b(n)&&R()-n.time>n.heartbeat_interval_time+5e3&&(delete n.heartbeat_interval_time,this.context.report(n)),this.delHeartBeatData(r)}}},r.prototype.stopHeartBeatInterval=function(){this.heartbeatIntervalTimer&&(clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null)},r.prototype.delHeartBeatData=function(t){this.context.store.localStorage.remove(t||this.storageName+this.pageId)},r.prototype.isCollectUrl=function(){var t=this.normalizePageLeaveAutoTrack().isCollectUrl;return!T(t)||t(this.url)},r.prototype.saveHeartBeatData=function(t){var e=this.getPageLeaveProperties();e.H_time=R(),"first_heartbeat"===t&&(e.event_duration=3);var o=this.context.getReportData("track","H_WebPageLeave",e);o.heartbeat_interval_time=this.heartbeatIntervalTime,this.context.store.localStorage.set(this.storageName+this.pageId,JSON.stringify(o))},r.prototype.getPageLeaveProperties=function(){var t=(R()-this.startTime)/1e3;t=t<=0||t>this.maxDuration?0:N(t,3);var e=P(this.url),o=e.pathname,r=e.hash,n=O(),i={H_url:this.url,H_url_path:o,H_url_hash:r,H_viewport_position:X(),H_referrer:n,H_referrer_host:n?D(n):"",event_duration:t},s=this.normalizePageLeaveAutoTrack().custom_props;return b(s)&&(i=a(a({},i),s||{})),i},r}(p),yt=function(e){function r(t,o){var r=e.call(this,t,o)||this;return r.options=t,r.context=o,r.name="SiteLinker",r.isReady=!1,r.linker=[],r}return o(r,e),r.prototype.init=function(){if(this.options.siteLinkerConfig){var e=this.getLinkerConfig().linker;_(e)&&e.length>0?this.isReady?this.context.log("SiteLinker plugin:插件已经运行,无需重复执行",t.ConsoleTypes.WARN):(this.isReady=!0,this.resolveOption(),this.setRefferId(),this.addClickListen()):this.context.log("siteLinker plugin: 请配置正确的linker参数",t.ConsoleTypes.WARN)}},r.prototype.transform=function(){},r.prototype.getLinkerConfig=function(){var t=this.options.siteLinkerConfig||{},e=t.linker;return{linker:(void 0===e?[]:e)||[],re_login:t.re_login}},r.prototype.resolveOption=function(){for(var e=this.getLinkerConfig().linker,o=e.length,r=[],n=0;n<o;n++){var i=e[n],a=i.part_url,s=i.after_hash;/[A-Za-z0-9]+\./.test(a)&&k(s)?r.push({part_url:a,after_hash:s}):this.context.log("The configuration of linker ".concat(n+1," is not supported.Please check format"),t.ConsoleTypes.WARN)}this.linker=r},r.prototype.setRefferId=function(){var t=this.getLinkerConfig().re_login,e=this.getUrlId(),o=e.startsWith("a");if(""!==(e=e.substring(1))){var r=this.context.store.getAnonymousId(),n=this.context.store.getAccountId();if(o){if(e!==r&&(this.context.store.state.anonymousId=e,this.context.store.save()),n){var i=this.context.getReportData("track_signup","H_SignUp",{});this.context.report(i)}}else(!n||t&&n!==e)&&this.context.setUserUId(e)}},r.prototype.getUrlId=function(){var t=window.location.href.match(/_hnsdk=([au][^\?\#\&\=]+)/);return _(t)&&t[1]?function(t){var e=t;try{e=decodeURIComponent(t)}catch(t){}return e}(t[1]):""},r.prototype.getPartUrl=function(t){for(var e=this.linker.length,o=0;o<e;o++)if(t.includes(this.linker[o].part_url))return!0;return!1},r.prototype.getPartHash=function(t){for(var e=this.linker.length,o=0;o<e;o++)if(t.includes(this.linker[o].part_url))return this.linker[o].after_hash;return!1},r.prototype.getCurrentId=function(){var t=this.context.store.getAccountId(),e=this.context.store.getAnonymousId();return function(t){var e=t;try{e=encodeURIComponent(t)}catch(t){}return e}(t?"u".concat(t):"a".concat(e))},r.prototype.rewriteUrl=function(t,e){var o=function(t,e,o){var r=/([^?#]+)(\?[^#]*)?(#.*)?/.exec(t),n="";if(r){var i=r[1]||"",a=r[2]||"",s=r[3]||"",c="_hnsdk=".concat(e),u=function(t){var e=t.split("&"),o=[];return e.forEach((function(t){t.includes("_hnsdk")?o.push(c):o.push(t)})),o.join("&")};if(o){var l=s.includes("?"),h=s.indexOf("_hnsdk");n=l?h>=0?"".concat(i).concat(a,"#").concat(s.substring(1,h)).concat(u(s.substring(h,s.length))):"".concat(i).concat(a,"#").concat(s.substring(1),"&").concat(c):"".concat(i).concat(a,"#").concat(s.substring(1),"?").concat(c)}else n=(l=/^\?(\w)+/.test(a))?a.includes("_hnsdk")?"".concat(i,"?").concat(u(a.substring(1))).concat(s):"".concat(i).concat(a,"&").concat(c).concat(s):"".concat(i,"?").concat(c).concat(s);return n}}(t,this.getCurrentId(),this.getPartHash(t));return e&&(e.href=o),o},r.prototype.addClickListen=function(){var t=this,e=function(e){var o,r,n=e.target;if(n){var i=null===(o=n.tagName)||void 0===o?void 0:o.toLowerCase(),a=n.parentNode,s=null===(r=null==a?void 0:a.tagName)||void 0===r?void 0:r.toLowerCase();if("a"===i&&n.href||"a"===s&&a.href){var c=void 0,u=void 0;"a"===i&&n.href?(c=n.href,u=n):(c=a.href,u=a);var l=P(c).protocol;"http:"!==l&&"https:"!==l||t.getPartUrl(c)&&t.rewriteUrl(c,u)}}};"PointerEvent"in window?document.addEventListener("pointerdown",e):document.addEventListener("mousedown",e)},r}(p),bt=function(e){function r(t,o){var r=e.call(this,t,o)||this;return r.options=t,r.context=o,r.name="HistoryPlugin",r.isReady=!1,r.lastHref=window.location.href,r.lastPath=window.location.pathname,r}return o(r,e),r.prototype.init=function(){if(window&&window.history.pushState&&window.history.replaceState)if(this.isReady)this.context.log("History plugin:插件已经运行,无需重复执行",t.ConsoleTypes.WARN);else{this.isReady=!0;var e=this,o=window.onpopstate,r=function(t,o){var r={fromPath:e.lastPath,fromHref:e.lastHref,toPath:t,toHref:o};e.lastPath=t,e.lastHref=o,K.emit("urlChange",a(a({},r),{mode:"history"}))};window.onpopstate=function(){for(var t=[],e=0;e<arguments.length;e++)t[e]=arguments[e];var n=window.location.pathname,i=window.location.href;r(n,i),o&&o.apply(this,t)},M(window.history,"pushState",n),M(window.history,"replaceState",n)}function n(t){return function(){for(var e=[],o=0;o<arguments.length;o++)e[o]=arguments[o];t.apply(this,e);var n=window.location.pathname,i=window.location.href;r(n,i)}}},r.prototype.transform=function(){},r}(p),wt=function(e){function r(t,o){var r=e.call(this,t,o)||this;return r.options=t,r.context=o,r.name="HashPlugin",r.isReady=!1,r.lastHref=window.location.href,r.lastPath=window.location.hash,r}return o(r,e),r.prototype.init=function(){var e=this;this.isReady?this.context.log("Hash plugin:插件已经运行,无需重复执行",t.ConsoleTypes.WARN):(this.isReady=!0,window.addEventListener("hashchange",(function(t){var o=t.newURL,r=P(o).hash,n={fromPath:e.lastPath,fromHref:e.lastHref,toPath:r,toHref:o};e.lastHref=o,e.lastPath=r,K.emit("urlChange",a(a({},n),{mode:"hash"}))})))},r.prototype.transform=function(){},r}(p),_t="4.0.4",Tt=function(t){function e(e,o){var r,n,i=this,a=(n=null===(r=navigator.userAgent)||void 0===r?void 0:r.toLowerCase(),/android|webos|iphone|ipod|blackberry/i.test(n)?"H5":"Web");return(i=t.call(this,e,o,a,"hina_webjs_sdk_abtest",_t)||this).options=e,i.context=o,i.name="HinaABTest",i}return o(e,t),e.prototype.getResultFromServer=function(t){var e=this;return new Promise((function(o,r){var n=e.createRequestData(t);new et({url:e.options.abTestingPluginConfig.url,data:JSON.stringify(n),contentType:"application/json",customHeaders:{"project-key":e.projectKey},timeout:t.timeoutMilliseconds}).run().then((function(t){var n=t.data;"SUCCESS"===(null==n?void 0:n.status)?e.saveResponseData(n.results).then((function(){o(n)})):r()}))}))},e}(at),St=function(){function t(){}return t.getSourceFromReferrer=function(){var t=function(t,e){for(var o=0;o<t.length;o++)if(-1!==e.split("?")[0].indexOf(t[o]))return!0},e="(".concat(f.join("|"),")\\=[^&]+"),o=document.referrer||"",r=window.location.href;if(r){var n=r.match(new RegExp(e));return n&&n[0]?"付费广告流量":t(d,o)?"自然搜索流量":t(g,o)?"社交网站流量":""===o?"直接流量":"引荐流量"}return"获取url异常"},t.getReferSearchEngine=function(t){var e,o,r=D(t);if(!r||"hostname解析异常"===r)return"";var n={baidu:[/^.*\.baidu\.com$/],bing:[/^.*\.bing\.com$/],google:[/^www\.google\.com$/,/^www\.google\.com\.[a-z]{2}$/,/^www\.google\.[a-z]{2}$/],sm:[/^m\.sm\.cn$/],so:[/^.+\.so\.com$/],sogou:[/^.*\.sogou\.com$/],yahoo:[/^.*\.yahoo\.com$/]};for(var i in n){var a=n[i];try{for(var s=(e=void 0,u(a)),c=s.next();!c.done;c=s.next()){if(c.value.test(r))return i}}catch(t){e={error:t}}finally{try{c&&!c.done&&(o=s.return)&&o.call(s)}finally{if(e)throw e.error}}}return"未知搜索引擎"},t.getKeywordFromReferrer=function(){var t=document.referrer||"";if(0===t.indexOf("http")){var e=this.getReferSearchEngine(t),o=function(t){t=t||"";var e={};return new URLSearchParams(t).forEach((function(t,o){e[o]=t})),e}(P(t).search);if(A(o))return"未取到值";for(var r in v){var n=v[r];if(r===e)if(_(n))for(var i=0;i<n.length;i++){var a=o[n[i]];if(a)return a}else if(o[n])return o[n]}return"未取到值"}return""===t?"未取到值_直接打开":"未取到值_非http的url"},t}();function xt(t){void 0===t&&(t="");var e,o=(e={},f.forEach((function(t){var o=B(window.location.href,t);o.length&&(e[t]=o)})),e),r={};return Object.keys(o).forEach((function(e){r[t+e]=o[e]})),r}var kt=function(e){function r(t,o){void 0===o&&(o=!0);var r=e.call(this,t,o)||this;return r.trackTags=dt,r.customProperties={},r.generalProperties={H_lib_version:_t,H_lib:"js",H_lib_method:"code",H_timezone_offset:(new Date).getTimezoneOffset()},r.useInstancing&&r.init(t),r}return o(r,e),r.prototype.init=function(e){if(this.isReady)this.log("hinaSDK has been initialized",t.ConsoleTypes.ERROR);else{var o={name:"",serverUrl:"",showLog:!1,autoTrackConfig:{clickAutoTrack:!0,stayAutoTrack:!0,isCollectUrl:function(){return!0},isCollectElement:function(){return!0},isCollectInput:function(){return!1},addCustomProperty:function(){},stayDelayTime:4e3,maxStayPageDuration:18e3,collectTags:{div:!1},trackAttr:["hn-click"],pageviewAutoTrack:!1,pageLeaveAutoTrack:!1},stayAutoTrackConfig:{isCollectUrl:function(){return!0}},maxStringLength:1024,imgUseCrossOrigin:!1,isSinglePage:!1,batchSend:!1,appJsBridge:!1,sendType:t.ReportTypes.BEACON,customHeaders:{},credentials:!1,dataSendTimeout:3e3,presetProperties:{latest_utm:!0,latest_traffic_source_type:!0,latest_search_keyword:!0,latest_referrer:!0},sourceChannel:[],plugins:[]},r=e.performanceErrorConfig,n=e.plugins,i=function(t,e){var o={};for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&e.indexOf(r)<0&&(o[r]=t[r]);if(null!=t&&"function"==typeof Object.getOwnPropertySymbols){var n=0;for(r=Object.getOwnPropertySymbols(t);n<r.length;n++)e.indexOf(r[n])<0&&Object.prototype.propertyIsEnumerable.call(t,r[n])&&(o[r[n]]=t[r[n]])}return o}(e,["performanceErrorConfig","plugins"]);this.options=I(o,i),this.options=a(a({},this.options),{performanceErrorConfig:r,plugins:n}),this.initState(),this.initAdvProps(),this.normalizeConfig(),this.initPlugins(),this.isReady=!0}},r.prototype.normalizeConfig=function(){var e=this,o=this.options,r=o.serverUrl,n=o.sendType,i=o.batchSend,s=o.maxStringLength,c=o.isSinglePage,u=o.autoTrackConfig,l=void 0===u?{}:u,h=l.trackAttr,p=void 0===h?[]:h,f=l.collectTags,d=l.pageLeaveAutoTrack,g=l.pageviewAutoTrack;if(""===(r=(r=r||"").trim()))this.log("当前 serverUrl 为空,network 中不会发数据,请配置正确的 serverUrl!",t.ConsoleTypes.WARN);else{var v=P(window.location.href).protocol||"";(P(r).protocol||"")!==v&&this.log("SDK 检测到您的数据发送地址和当前页面地址的协议不一致,建议您修改成一致的协议。因为:https 下面发送 http 的图片请求会失败。",t.ConsoleTypes.WARN)}if([t.ReportTypes.IMAGE,t.ReportTypes.AJAX,t.ReportTypes.BEACON].includes(n)||this.setConfig({sendType:t.ReportTypes.AJAX}),this.options.maxStringLength=function(t){var e=t;return!x(t)||t<0?e=1024:t>5120&&(e=5120),e}(s),(!0===d||b(d)&&A(d))&&(this.options.autoTrackConfig.pageLeaveAutoTrack={heartbeat_interval_time:5e3,max_duration:432e3}),_(p)?(p=p.filter((function(t){return S(t)}))).includes("hn-click")||p.push("hn-click"):p=["hn-click"],this.options.autoTrackConfig.trackAttr=p,b(f))if(!0===f.div)this.options.autoTrackConfig.collectTags.div={ignoreTags:ft,maxLevel:1};else if(b(f.div)){var m=1,y=f.div;x(y.maxLevel)&&[1,2,3].includes(y.maxLevel)&&(m=y.maxLevel),this.options.autoTrackConfig.collectTags.div={ignoreTags:ft,maxLevel:m}}else this.options.autoTrackConfig.collectTags.div=!1;else this.options.autoTrackConfig.collectTags={div:!1};this.updateTrackTags(),(!0===i||b(i)&&!A(i))&&(this.options.batchSend=a({dataSendTimeout:6e3,sendInterval:6e3,storageLimit:200},i),this.batchSender=new rt(this.options,"hinasdk_tab","hinasdk_data_")),"auto"===g?this.autoTrack():("singlePage"===g||c)&&(this.autoTrack(),K.on("urlChange",(function(t){var o=t.fromHref;if(o!==t.toHref){var r={};if(T(c)){var n=c();b(n)&&(r=a(a({},r),n))}e.autoTrack(a(a({},r),{H_referrer:o}))}})))},r.prototype.updateTrackTags=function(){var t=this.options.autoTrackConfig.collectTags,e=h([],l(dt),!1);Object.keys(t||{}).forEach((function(o){var r=t[o];!0!==r&&!b(r)||e.includes(o)||e.push(o)})),this.trackTags=e},r.prototype.initState=function(){this.store=new G(this.options),this.store.init()},r.prototype.initAdvProps=function(){var t,e={},o=this.options,r=o.presetProperties,n=o.sourceChannel;if(b(r))for(var i in r){var s=r[i];if(i.includes("latest_")&&(i=i.slice(7),s)){var c=E();if("utm"!==i&&"url解析失败"===c)e["H_latest_".concat(i)]="url的domain解析失败";else if(""===(t=(t=void 0)||document.referrer)||L(D(t))!==L())switch(i){case"traffic_source_type":e.H_latest_traffic_source_type=St.getSourceFromReferrer();break;case"search_keyword":var u=St.getKeywordFromReferrer();u&&(e.H_latest_search_keyword=u);break;case"referrer":e.H_latest_referrer=O()}}}var l=this.store.state.props||{},h={};r.latest_utm&&(h=xt("H_latest_"));var p={};l.H_utm_source||(p=xt("H_"));var d=[],g={};_(n)&&n.length>0&&(d=n.filter((function(t){return!f.includes(t)}))).length>0&&(g=a(a({},g),function(t,e){void 0===e&&(e=[]);var o={};return e.forEach((function(e){var r=B(window.location.href,e);r&&(o[e]=r,o["".concat(t).concat(e)]=r)})),o}("H_latest_",d))),this.store.state.props=a(a(a(a(a({},this.store.state.props),e),h),g),p),this.store.setProps(this.store.state.props),this.store.getUtmFromProps(d)},r.prototype.getGeneralProperties=function(){var t=new $;return this.generalProperties=a(a(a({},this.generalProperties),{H_screen_width:window.screen.width,H_screen_height:window.screen.height,H_viewport_width:Y(),H_viewport_height:Z(),H_page_height:document.documentElement.scrollHeight||document.body.scrollHeight,H_browser:t.browserName,H_browser_version:t.browserVersion,H_os:t.os,H_os_version:t.osVersion,H_model:t.model,H_is_first_day:this.store.isFirstDay,H_url:window.location.href,H_url_host:D(window.location.href,"url_host取值异常"),H_title:document.title}),this.store.hLatestUtm),this.generalProperties.H_latest_referrer&&(this.generalProperties.H_latest_referrer_host=D(this.generalProperties.H_latest_referrer,"hostname解析异常")),this.generalProperties},r.prototype.initPlugins=function(){var t=this,e=this.options,o=e.serverUrl,r=e.name,n=e.showLog,i=e.sendType,s=e.customHeaders,c=e.credentials,u=e.dataSendTimeout,l=e.batchSend,h=e.imgUseCrossOrigin,p=e.globalCallback,f=e.plugins,d=void 0===f?[]:f,g=e.performanceErrorConfig,v=e.autoTrackConfig,m=e.siteLinkerConfig,y=e.abTestingPluginConfig;d=d||[];var w=v.pageLeaveAutoTrack,T=new gt(this.options,this),S=new vt(this.options,this),x=new bt(this.options,this),k=new wt(this.options,this),C=new mt(this.options,this),H=new yt(this.options,this),R=new Tt(this.options,this);C.disabled=!(b(w)&&!A(w));var I=(m||{}).linker;H.disabled=!(_(I)&&I.length>0),R.disabled=!(b(y)&&!A(y)),this.plugins=[T,S,x,k,C,H,R],_(d)&&d.forEach((function(e){if("Monitor"===e.componentName){if(b(g)&&!A(g))new e(a({serverUrl:o,name:r,showLog:n,sendType:i,customHeaders:s,credentials:c,dataSendTimeout:u,batchSend:l,imgUseCrossOrigin:h,globalCallback:p},g),!0)}else{var f=new e(t.options,t);t.plugins.push(f)}})),this.runPlugins(this.plugins)},r.prototype.use=function(e,o){if(this.isReady){if(b(o)){"PageLeave"===e?this.options.autoTrackConfig.pageLeaveAutoTrack=o:"SiteLinker"===e?this.options.siteLinkerConfig=o:"HinaABTest"===e&&(this.options.abTestingPluginConfig=o);var r=this.plugins.find((function(t){return t.name===e}));return r&&(r.disabled=!1,r.isReady?this.log("".concat(e,"插件已运行,无需重复执行"),t.ConsoleTypes.WARN):r.init()),this.getPluginInstance(e)}this.log("".concat(e,"插件配置项必须是一个对象类型"),t.ConsoleTypes.WARN)}else this.log("请先初始化埋点SDK",t.ConsoleTypes.WARN)},r.prototype.getPluginInstance=function(t){return this.plugins.find((function(e){return e.name===t}))},r.prototype.setConfig=function(t){this.options=I(this.options,t),this.normalizeConfig()},r.prototype.getConfig=function(t){return t?this.options[t]:this.options},r.prototype.setUserUId=function(e,o){var r=this;!function(e,o,r){x(e=null!=e?e:"")||S(e)?o!==(e=String(e).trim())?r(e):V("setUserUId: uid is equal to account_id, failed to execute setUserUId",t.ConsoleTypes.WARN):V("setUserUId: uid must be string or number",t.ConsoleTypes.WARN)}(e,this.store.getAccountId(),(function(t){r.store.setAccountId(t);var e=r.getReportData("track_signup","H_SignUp",{});r.report(e,o)}))},r.prototype.cleanUserUId=function(){this.store.setAccountId("")},r.prototype.getUserUid=function(){return this.store.state.accountId},r.prototype.setDeviceUId=function(t){this.store.setDeviceId(t)},r.prototype.getDeviceUId=function(){return this.store.getDeviceId()},r.prototype.userSet=function(t,e){if(b(t)&&!A(t)){var o=this.getReportData("user_set","",t);this.report(o,e)}},r.prototype.userSetOnce=function(t,e){if(b(t)&&!A(t)){var o=this.getReportData("user_setOnce","",t);this.report(o,e)}},r.prototype.userAdd=function(e,o){var r=this;!function(e,o){var r;S(e)&&((r={})[e]=1,e=r),b(e)&&!A(e)&&function(e){for(var o in e)if(!/-*\d+/.test(String(e[o])))return V("userAdd属性的值只能是数字",t.ConsoleTypes.WARN),!1;return!0}(e)&&o(e)}(e,(function(t){var e=r.getReportData("user_add","",t);r.report(e,o)}))},r.prototype.userAppend=function(t,e){var o=this;!function(t,e){var o={};b(t)&&(Object.keys(t).forEach((function(e){var r=t[e];_(r)?o[e]=r:o[e]=[r]})),A(o)||e(o))}(t,(function(t){var r=o.getReportData("user_append","",t);o.report(r,e)}))},r.prototype.userUnset=function(e,o){var r=this;!function(e,o){var r={};S(e)&&(e=[e]),_(e)?(e.forEach((function(e){S(e)?r[e]=!0:V("userUnset参数数组里面的值必须是string,已经过滤掉".concat(e),t.ConsoleTypes.WARN)})),A(r)||o(r)):V("userUnset参数必须是数组或字符串",t.ConsoleTypes.WARN)}(e,(function(t){var e=r.getReportData("user_unset","",t);r.report(e,o)}))},r.prototype.userDelete=function(t){var e=this.getReportData("user_delete","",{});this.report(e,t),this.store.setAccountId("")},r.prototype.registerCommonProperties=function(t){this.customProperties=I(this.customProperties,t)},r.prototype.getPresetProperties=function(){return a(a({},this.getGeneralProperties()),this.customProperties)},r.prototype.clearPageRegister=function(t){var e=this;void 0===t&&(t=!0),!0===t?this.customProperties={}:_(t)&&t.forEach((function(t){t in e.customProperties&&delete e.customProperties[t]}))},r.prototype.track=function(e,o,r){if(r=r||function(){},S(e)){o=b(o)?o:{};var n=this.getReportData("track",e,o);this.report(n,r)}else this.log("track事件名必须是字符串,属性必须是是一个对象",t.ConsoleTypes.WARN)},r.prototype.quick=function(t,e,o){if(!this.isReady)return this.log("请先初始化SDK");var r={};o=T(o)?o:C,b(e)?r=e:T(e)&&(o=e),this.autoTrack(r,o)},r.prototype.autoTrack=function(t,e){void 0===t&&(t={}),void 0===e&&(e=C);var o=(null==t?void 0:t.H_referrer)||O(),r=a(a(a({H_is_first_time:this.store.isFirstTime,H_url_path:window.location.pathname,H_referrer:o,H_referrer_host:o?D(o):""},this.store.hUtm),this.store.customUtm),t||{}),n=this.getReportData("track","H_pageview",r);if(this.report(n,e),this.store.isFirstTime){this.store.isFirstTime=!1;var i=O(),s=a(a({H_first_visit_time:R(),H_first_referrer:i,H_first_referrer_host:i?D(i,"取值异常"):"",H_first_traffic_source_type:St.getSourceFromReferrer(),H_first_search_keyword:St.getKeywordFromReferrer(),H_first_browser_language:S(navigator.language)?navigator.language.toLowerCase():"取值异常",H_first_browser_charset:document.characterSet||document.inputEncoding||"UTF-8"},this.store.hUtm),this.store.customUtm);this.userSetOnce(s)}},r.prototype.report=function(e,o,r){var n,i,a=this.options,s=a.appJsBridge,c=a.serverUrl;if(this.log(e),s){var u=!0,l=null===window||void 0===window?void 0:window.Hina_Cloud_H5_Bridge;if(b(l)&&l.track)u=!1,l.track(e.event,e.type,JSON.stringify(e));else{var h=null===(i=null===(n=null===window||void 0===window?void 0:window.webkit)||void 0===n?void 0:n.messageHandlers)||void 0===i?void 0:i.hinaNativeTracker;if(null==h?void 0:h.postMessage){u=!1;var p=JSON.stringify({eventName:e.event,eventType:e.type,properties:e});h.postMessage(p)}}if(u)return void this.log("JSBridge 发送数据失败",t.ConsoleTypes.WARN);T(o)&&o(c,e)}else this.sendReportData(e,o,r)},r.prototype.getReportData=function(t,e,o){var r,n=this.store.getAnonymousId(),i=this.store.getAccountId(),s=R(),c=I(this.customProperties),u=this.getGeneralProperties();if("user"===t.slice(0,4)){var l=u.H_lib,h=u.H_lib_method,p=u.H_lib_version;r=a({device_id:this.store.getDeviceId(),H_lib:l,H_lib_method:h,H_lib_version:p},o||{})}else r=a(a(a({device_id:this.store.getDeviceId()},u),c),o||{});nt(r,this.options.maxStringLength);var f={anonymous_id:n,type:t,event:e,time:s,_track_id:U(),properties:r};return i&&!/^[0-9a-f]{8,}-[0-9a-f]{4,}-[0-9a-f]{4,}-[0-9a-f]{4,}-[0-9a-f]{12,}$/.test(i)&&(f.account_id=i),f.send_time=R(),f},r}(ct);var Ct=new kt({},!1);return t.HinaTrack=kt,t.PluginBase=p,t.default=Ct,Object.defineProperty(t,"__esModule",{value:!0}),t}({});
1
+ var hinaDataStatistic=function(exports){"use strict";var extendStatics=function(d,b){return extendStatics=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(d,b){d.__proto__=b}||function(d,b){for(var p in b)Object.prototype.hasOwnProperty.call(b,p)&&(d[p]=b[p])},extendStatics(d,b)};function __extends(d,b){if("function"!=typeof b&&null!==b)throw new TypeError("Class extends value "+String(b)+" is not a constructor or null");function __(){this.constructor=d}extendStatics(d,b),d.prototype=null===b?Object.create(b):(__.prototype=b.prototype,new __)}var ConsoleTypes,ReportTypes,VariablesTypes,__assign=function(){return __assign=Object.assign||function(t){for(var s,i=1,n=arguments.length;i<n;i++)for(var p in s=arguments[i])Object.prototype.hasOwnProperty.call(s,p)&&(t[p]=s[p]);return t},__assign.apply(this,arguments)};function __awaiter(thisArg,_arguments,P,generator){return new(P||(P=Promise))((function(resolve,reject){function fulfilled(value){try{step(generator.next(value))}catch(e){reject(e)}}function rejected(value){try{step(generator.throw(value))}catch(e){reject(e)}}function step(result){var value;result.done?resolve(result.value):(value=result.value,value instanceof P?value:new P((function(resolve){resolve(value)}))).then(fulfilled,rejected)}step((generator=generator.apply(thisArg,_arguments||[])).next())}))}function __generator(thisArg,body){var f,y,t,_={label:0,sent:function(){if(1&t[0])throw t[1];return t[1]},trys:[],ops:[]},g=Object.create(("function"==typeof Iterator?Iterator:Object).prototype);return g.next=verb(0),g.throw=verb(1),g.return=verb(2),"function"==typeof Symbol&&(g[Symbol.iterator]=function(){return this}),g;function verb(n){return function(v){return function(op){if(f)throw new TypeError("Generator is already executing.");for(;g&&(g=0,op[0]&&(_=0)),_;)try{if(f=1,y&&(t=2&op[0]?y.return:op[0]?y.throw||((t=y.return)&&t.call(y),0):y.next)&&!(t=t.call(y,op[1])).done)return t;switch(y=0,t&&(op=[2&op[0],t.value]),op[0]){case 0:case 1:t=op;break;case 4:return _.label++,{value:op[1],done:!1};case 5:_.label++,y=op[1],op=[0];continue;case 7:op=_.ops.pop(),_.trys.pop();continue;default:if(!(t=_.trys,(t=t.length>0&&t[t.length-1])||6!==op[0]&&2!==op[0])){_=0;continue}if(3===op[0]&&(!t||op[1]>t[0]&&op[1]<t[3])){_.label=op[1];break}if(6===op[0]&&_.label<t[1]){_.label=t[1],t=op;break}if(t&&_.label<t[2]){_.label=t[2],_.ops.push(op);break}t[2]&&_.ops.pop(),_.trys.pop();continue}op=body.call(thisArg,_)}catch(e){op=[6,e],y=0}finally{f=t=0}if(5&op[0])throw op[1];return{value:op[0]?op[1]:void 0,done:!0}}([n,v])}}}function __values(o){var s="function"==typeof Symbol&&Symbol.iterator,m=s&&o[s],i=0;if(m)return m.call(o);if(o&&"number"==typeof o.length)return{next:function(){return o&&i>=o.length&&(o=void 0),{value:o&&o[i++],done:!o}}};throw new TypeError(s?"Object is not iterable.":"Symbol.iterator is not defined.")}function __read(o,n){var m="function"==typeof Symbol&&o[Symbol.iterator];if(!m)return o;var r,e,i=m.call(o),ar=[];try{for(;(void 0===n||n-- >0)&&!(r=i.next()).done;)ar.push(r.value)}catch(error){e={error:error}}finally{try{r&&!r.done&&(m=i.return)&&m.call(i)}finally{if(e)throw e.error}}return ar}function __spreadArray(to,from,pack){if(pack||2===arguments.length)for(var ar,i=0,l=from.length;i<l;i++)!ar&&i in from||(ar||(ar=Array.prototype.slice.call(from,0,i)),ar[i]=from[i]);return to.concat(ar||Array.prototype.slice.call(from))}"function"==typeof SuppressedError&&SuppressedError,exports.ConsoleTypes=void 0,(ConsoleTypes=exports.ConsoleTypes||(exports.ConsoleTypes={})).LOG="log",ConsoleTypes.INFO="info",ConsoleTypes.WARN="warn",ConsoleTypes.ERROR="error",ConsoleTypes.ASSERT="assert",exports.ReportTypes=void 0,(ReportTypes=exports.ReportTypes||(exports.ReportTypes={})).BEACON="beacon",ReportTypes.IMAGE="image",ReportTypes.AJAX="ajax",exports.VariablesTypes=void 0,(VariablesTypes=exports.VariablesTypes||(exports.VariablesTypes={})).INTEGER="INTEGER",VariablesTypes.STRING="STRING",VariablesTypes.BOOLEAN="BOOLEAN";var PluginBase=function(options,context){this.options=options,this.context=context,this.disabled=!1},utmTypes=["utm_source","utm_medium","utm_campaign","utm_content","utm_term"];__spreadArray(__spreadArray([],__read(utmTypes),!1),__read(["ha_utm"]),!1);var searchTypes=["www.baidu","baidu.com","m.sm.cn","so.com","sogou.com","youdao.com","google.com","yahoo.com","bing.com","ask.com"],socialTypes=["weibo.com","renren.com","kaixin001.com","douban.com","qzone.qq.com","zhihu.com","tieba.baidu.com","weixin.qq.com"],searchKeywords={baidu:["wd","word","kw","keyword"],google:"q",bing:"q",yahoo:"p",sogou:["query","keyword"],so:"q",sm:"q"},toString=Object.prototype.toString;function isObject(val){return"[object Object]"===toString.call(val)}function isValid(val){return null!=val}function isArray(val){return Array.isArray(val)}function isFunction(val){return"function"==typeof val}function isString(val){return"string"==typeof val}function isNumber(val){return"number"==typeof val&&!Number.isNaN(val)}function isBoolean(val){return"boolean"==typeof val}function noop(){}function safeJSONParse(val){try{return JSON.parse(val)}catch(e){}return val}function isEmptyObject(obj){return 0===Object.keys(obj).length}function nowStamp(){return Date.now&&isFunction(Date.now)?Date.now():(new Date).getTime()}function merge(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];var result=Object.create(null);return args.forEach((function(obj){obj&&Object.keys(obj).forEach((function(key){var val=obj[key];isObject(val)?isObject(result[key])?result[key]=merge(result[key],val):result[key]=merge(val):result[key]=val}))})),result}function getURL(url){var urlObj={};try{urlObj=new URL(url)}catch(e){}return urlObj}function formatDecimal(num,decimal){if(!num)return num;var str=num.toString(),index=str.indexOf(".");return str=-1!==index?str.substring(0,index+decimal+1):str.substring(0),parseFloat(str)}function getCookieTopLevelDomain(hostname){hostname=hostname||window.location.hostname,/^[a-zA-Z0-9\u4e00-\u9fa5\-\\.]+$/.exec(hostname)||(hostname="");var splitResult=hostname.split(".");if(splitResult.length>=2&&!/^(\d+\.)+\d+$/.test(hostname))for(var domainStr=".".concat(splitResult.splice(splitResult.length-1,1));splitResult.length>0;)if(domainStr=".".concat(splitResult.splice(splitResult.length-1,1)).concat(domainStr),document.cookie="".concat("hinasdk_domain_test","=true; path=/; domain=").concat(domainStr),-1!==document.cookie.indexOf("".concat("hinasdk_domain_test","=true")))return document.cookie="".concat("hinasdk_domain_test","=true; path=/; domain=").concat(domainStr,"; max-age=0"),domainStr;return""}function getCurrentDomain(){var cookieDomain=getCookieTopLevelDomain();return""===cookieDomain?"url解析失败":cookieDomain}function getReferrer(value){var referrer=value||document.referrer;return"string"!=typeof referrer?"referrer exception".concat(String(referrer)):(referrer.startsWith("https://www.baidu.com/")&&(referrer=referrer.split("?")[0]),"string"==typeof(referrer=referrer.slice(0,200))?referrer:"")}function getHostname(url,defaultValue){return defaultValue&&"string"==typeof defaultValue||(defaultValue="hostname解析异常"),url&&(getURL(url).hostname||"")||defaultValue}function generatorTrackId(){var now=nowStamp(),num=Math.floor(1e6*Math.random());return Number(String(now).slice(-5)+String(num).slice(0,4))}function getQueryParam(url,key){key=key.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]"),url=decodeURIComponent(url);var results=new RegExp("[\\?&]".concat(key,"=([^&#]*)")).exec(url);return null===results||results&&"string"!=typeof results[1]&&results[1].length?"":decodeURIComponent(results[1])}function base64Encode(str){try{return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g,(function(e,t){return String.fromCharCode(Number("0x".concat(t)))})))}catch(e){return str}}function replaceOld(source,name,replacement,isForced){if(void 0!==source&&(name in source||isForced)){var wrapped=replacement(source[name]);isFunction(wrapped)&&(source[name]=wrapped)}}var CookieStorage=function(){function CookieStorage(){this.name="CookieStorage"}return CookieStorage.prototype.isSupport=function(testKey,testValue){var _this=this;void 0===testKey&&(testKey="cookie_support_test"),void 0===testValue&&(testValue="1");return navigator.cookieEnabled&&(_this.set(testKey,testValue),_this.get(testKey)===testValue&&(_this.remove(testKey),!0))},CookieStorage.prototype.get=function(name){var e_1,_a,cookieList=document.cookie.split(";");try{for(var cookieList_1=__values(cookieList),cookieList_1_1=cookieList_1.next();!cookieList_1_1.done;cookieList_1_1=cookieList_1.next()){var cookiePair=cookieList_1_1.value.split("=");if(cookiePair[0].trim()===name)return decodeURIComponent(cookiePair[1])}}catch(e_1_1){e_1={error:e_1_1}}finally{try{cookieList_1_1&&!cookieList_1_1.done&&(_a=cookieList_1.return)&&_a.call(cookieList_1)}finally{if(e_1)throw e_1.error}}return null},CookieStorage.prototype.set=function(name,value,timeStamp,path,domain,sameSite,secure){path=path||"/",name=name.trim(),value=value.trim();var cookieStr="".concat(name,"=").concat(encodeURIComponent(value),"; path=").concat(path,";");timeStamp=isValid(timeStamp)?timeStamp:63072e8,cookieStr+=" max-age=".concat(timeStamp,";"),secure&&(cookieStr+=" secure;"),domain&&(cookieStr+=" domain=".concat(domain,";")),["Strict","Lax","None"].includes(sameSite)&&(cookieStr+=" SameSite=".concat(sameSite,";")),document.cookie=cookieStr},CookieStorage.prototype.remove=function(name,path){void 0===path&&(path="/"),this.set(name,"1",0,path)},CookieStorage.prototype.setDomain=function(name,value,timeStamp){var domain=getCurrentDomain();"url解析失败"===domain&&(domain=""),this.set(name,value,timeStamp,"/",domain)},CookieStorage}(),LocalStorage=function(){function LocalStorage(){this.name="LocalStorage"}return LocalStorage.prototype.isSupport=function(){var supported=!0;try{var supportName="__localStorageSupport__",val="testIsSupportStorage";this.set(supportName,val),this.get(supportName)!==val&&(supported=!1),this.remove(supportName)}catch(e){supported=!1}return supported},LocalStorage.prototype.key=function(index){return window.localStorage.key(index)},LocalStorage.prototype.get=function(key){return window.localStorage.getItem(key)},LocalStorage.prototype.length=function(){return window.localStorage.length},LocalStorage.prototype.set=function(key,value){try{window.localStorage.setItem(key,value)}catch(e){}},LocalStorage.prototype.remove=function(key){window.localStorage.removeItem(key)},LocalStorage.prototype.parse=function(key){var result=this.get(key);try{result=JSON.parse(result)}catch(e){result=""}return result},LocalStorage}(),MemoryStorage=function(){function MemoryStorage(){this.name="MemoryStorage",this.data={}}return MemoryStorage.prototype.get=function(key){var result=this.data[key];return isValid(null==result?void 0:result.expireTime)?result.expireTime<nowStamp()?null:result.value:null==result?void 0:result.value},MemoryStorage.prototype.set=function(key,value,expires){if(isValid(expires)){var expireTime=nowStamp()+1e3*expires;this.data[key]={value:value,expireTime:expireTime}}this.data[key]={value:value}},MemoryStorage.prototype.setDomain=function(name,value,timeStamp){this.set(name,value,timeStamp)},MemoryStorage}();function log(message,type){if(void 0===type&&(type=exports.ConsoleTypes.LOG),"undefined"!=typeof console){var func=console[type]||console.log;"function"==typeof func&&func(message)}}var all,mitt={all:all=all||new Map,on:function(type,handler){var handlers=all.get(type);handlers?handlers.push(handler):all.set(type,[handler])},emit:function(type,event){var handlers=all.get(type);handlers&&handlers.forEach((function(handler){handler(event)}))},off:function(type,handler){var handlers=all.get(type);if(handlers)if(handler){var index=handlers.indexOf(handler);index>=0&&handlers.splice(index,1)}else all.set(type,[])}},State=function(){function State(options,state){this.options=options,this.isFirstTime=!1,this.isFirstDay=!1,this.state=state}return State.prototype.log=function(message,type){void 0===type&&(type=exports.ConsoleTypes.LOG),this.options.showLog&&log(message,type)},State.prototype.checkSetValue=function(name,value){return!(!isNumber(value=null!=value?value:"")&&!isString(value))||(this.log("".concat(name,": id must be string or number"),exports.ConsoleTypes.WARN),!1)},State.prototype.setDeviceId=function(id){void 0===id&&(id=""),this.checkSetValue("deviceId",id)&&this.set("deviceId",id)},State.prototype.setAccountId=function(id){void 0===id&&(id=""),this.checkSetValue("accountId",id)&&(this.set("accountId",id),mitt.emit("changeAccountId"))},State.prototype.setAnonymousId=function(id){this.state.anonymousId?this.log("Current anonymousId is ".concat(this.getAnonymousId(),", it has been set"),exports.ConsoleTypes.WARN):this.checkSetValue("anonymousId",id)&&this.set("anonymousId",id)},State.prototype.setProps=function(props){var newProps=merge(this.state.props||{},props);for(var key in newProps)"string"==typeof newProps[key]&&(newProps[key]=newProps[key].slice(0,200));this.set("props",newProps)},State.prototype.getAnonymousId=function(){return this.state.anonymousId},State.prototype.getDeviceId=function(){return this.state.deviceId},State.prototype.getAccountId=function(){return this.state.accountId},State.prototype.clear=function(){this.state={},this.save()},State.prototype.set=function(name,value){this.state[name]=value,this.save()},State.prototype.afterInit=function(cacheData){cacheData?(this.isFirstDay=function(timestamp){var result;try{var oDate=new Date,oYear=oDate.getFullYear(),oMonth=oDate.getMonth()+1,oDay=oDate.getDate(),prevDate=new Date(timestamp),prevYear=prevDate.getFullYear(),prevMonth=prevDate.getMonth()+1,prevDay=prevDate.getDate();result=oYear===prevYear&&oMonth===prevMonth&&oDay===prevDay}catch(e){result=!1}return result}(this.state.firstVisitTime),this.save()):(this.isFirstDay=!0,this.isFirstTime=!0);var uuid="xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,(function(c){var r=16*Math.random()|0;return"x"===c?r.toString(16):(3&r|8).toString(16)}));this.getAnonymousId()||this.setAnonymousId(uuid),this.getDeviceId()||this.setDeviceId(uuid)},State}(),WebState=function(_super){function WebState(options){var _this=this,state={accountId:null,deviceId:null,anonymousId:null,sessionId:null,firstVisitTime:nowStamp(),props:{}};return(_this=_super.call(this,options,state)||this).options=options,_this.storeName="hinasdk_crossdata",_this.hLatestUtm={},_this.hUtm={},_this.customUtm={},_this}return __extends(WebState,_super),WebState.prototype.getUtmFromProps=function(sourceChannel){for(var key in this.state.props){var value=this.state.props[key];key.startsWith("H_latest_")?this.hLatestUtm[key]=value:key.startsWith("H_")&&(this.hUtm[key]=value),sourceChannel.includes(key)&&(this.customUtm[key]=value)}},WebState.prototype.init=function(){var oldState,cookieStorage=new CookieStorage,memoryStorage=new MemoryStorage,localStorage=new LocalStorage;cookieStorage.isSupport()?this.storage=cookieStorage:(this.log("Cookie storage is not supported, SDK internal cache has been enabled",exports.ConsoleTypes.WARN),this.storage=memoryStorage),localStorage.isSupport()?this.localStorage=localStorage:this.log("localStorage is not supported, SDK internal cache has been enabled",exports.ConsoleTypes.WARN),!(oldState=this.storage.get(this.storeName))&&this.localStorage&&(oldState=this.localStorage.get(this.storeName)),oldState&&function(val){try{JSON.parse(val)}catch(e){return!1}return!0}(oldState)?this.state=safeJSONParse(oldState):oldState=null,this.afterInit(oldState)},WebState.prototype.save=function(){this.storage.setDomain(this.storeName,JSON.stringify(this.state)),this.localStorage&&this.localStorage.set(this.storeName,JSON.stringify(this.state))},WebState.prototype.getCookie=function(){return this.storage.get(this.storeName)},WebState.prototype.setSessionId=function(id){this.set("sessionId",id)},WebState.prototype.getSessionId=function(){return this.state.sessionId||""},WebState.prototype.getSessionIdCreateTime=function(){var timeStr=this.getSessionId().split("_")[0],time=Number(timeStr);return Number.isNaN(time)?0:time},WebState}(State),Browser=function(){function Browser(){this.isReady=!1,this.isReady||this.init(),this.isReady=!0}return Browser.prototype.init=function(){this.os=this.getOs(),this.osVersion=this.getOsVersion();var _a=this.getBrowser(),type=_a.type,version=_a.version;this.browserName=type,this.browserVersion=version,this.model=this.getModel()},Browser.prototype.getOs=function(){var a=navigator.userAgent;return/Windows/i.test(a)?/Phone/.test(a)||/WPDesktop/.test(a)?"Windows Phone":"Windows":/(iPhone|iPad|iPod)/.test(a)&&!window.MSStream?"iOS":/Android/.test(a)?"Android":/(BlackBerry|PlayBook|BB10)/i.test(a)?"BlackBerry":/Mac/i.test(a)?"Mac OS X":/Linux/.test(a)?"Linux":/CrOS/.test(a)?"Chrome OS":"取值异常"},Browser.prototype.getOsVersion=function(){var a=navigator.userAgent;if(/Windows/i.test(a)){var reg=/Windows NT ([\d.]+)/;return a.match(reg)?a.match(reg)[1]:""}if(/(iPhone|iPad|iPod)/.test(a)&&!window.MSStream){reg=/OS ([\d_]+)/;return a.match(reg)?a.match(reg)[1].replace(/_/g,"."):""}if(/Android/.test(a)){reg=/Android ([\d.]+)/;return a.match(reg)?a.match(reg)[1]:""}if(/Mac/i.test(a)){reg=/Mac OS X ([\d_]+)/;return a.match(reg)?a.match(reg)[1].replace(/_/g,"."):""}return""},Browser.prototype.getBrowser=function(){var _a,browser={type:"",version:""};try{var ua=null===(_a=navigator.userAgent)||void 0===_a?void 0:_a.toLowerCase(),versionMatch=[];if(null!==ua.match(/baidubrowser/)?(browser.type="baidu",versionMatch.push(/baidubrowser\/([\d.]+)/)):null!==ua.match(/bidubrowser/)?(browser.type="baidu",versionMatch.push(/bidubrowser\/([\d.]+)/)):null!==ua.match(/edg/)?(browser.type="edge",versionMatch.push(/edg\/([\d.]+)/)):null!==ua.match(/edgios/)?(browser.type="edge",versionMatch.push(/edgios\/([\d.]+)/)):null!==ua.match(/liebaofast/)?(browser.type="liebao",versionMatch.push(/liebaofast\/([\d.]+)/)):null!==ua.match(/sogoumobilebrowser/)?(browser.type="sogou",versionMatch.push(/sogoumobilebrowser\/([\d.]+)/)):null!==ua.match(/lbbrowser/)?(browser.type="liebao",versionMatch.push(/lbbrowser\/([\d.]+)/)):null!==ua.match(/crios/)?(browser.type="chrome",versionMatch.push(/crios\/([\d.]+)/)):null!==ua.match(/qihoobrowser/)?(browser.type="360",versionMatch.push(/qihoobrowser\/([\d.]+)/)):null!==ua.match(/mxios/)?(browser.type="maxthon",versionMatch.push(/mxios\/([\d.]+)/)):null!==ua.match(/fxios/)?(browser.type="firefox",versionMatch.push(/fxios\/([\d.\w]+)/)):null!==ua.match(/edge/)?(browser.type="edge",versionMatch.push(/edge\/([\d.]+)/)):null!==ua.match(/metasr/)?(browser.type="sogou",versionMatch.push(/metasr ([\d.]+)/)):null!==ua.match(/micromessenger/)?(browser.type="micromessenger",versionMatch.push(/micromessenger\/([\d.]+)/)):null!==ua.match(/mqqbrowser/)?(browser.type="qq",versionMatch.push(/mqqbrowser\/([\d.]+)/)):null!==ua.match(/qqbrowserlite/)?(browser.type="qq",versionMatch.push(/qqbrowserlite\/([\d.]+)/)):null!==ua.match(/tencenttraveler/)?(browser.type="qq",versionMatch.push(/tencenttraveler\/([\d.]+)/)):null!==ua.match(/qqbrowser/)?(browser.type="qq",versionMatch.push(/qqbrowser\/([\d.]+)/)):null!==ua.match(/maxthon/)?(browser.type="maxthon",versionMatch.push(/maxthon\/([\d.]+)/)):null!==ua.match(/ubrowser/)?(browser.type="uc",versionMatch.push(/ubrowser\/([\d.]+)/)):null!==ua.match(/ucbrowser/)?(browser.type="uc",versionMatch.push(/ucbrowser\/([\d.]+)/)):null!==ua.match(/firefox/)?(browser.type="firefox",versionMatch.push(/firefox\/([\d.]+)/)):null!==ua.match(/opera/)?(browser.type="opera",versionMatch.push(/opera\/([\d.]+)/)):null!==ua.match(/opr/)?(browser.type="opera",versionMatch.push(/opr\/([\d.]+)/)):null!==ua.match(/chrome/)?(browser.type="chrome",versionMatch.push(/chrome\/([\d.]+)/)):null!==ua.match(/safari/)?(browser.type="safari",versionMatch.push(/version\/([\d.]+)/)):null===ua.match(/trident/)&&null===ua.match(/msie/)||(browser.type="ie"),"ie"===browser.type){var tridentVersion=ua.match(/trident\/([\d.]+)/)?ua.match(/trident\/([\d.]+)/)[1]:"",msieVersion=ua.match(/msie ([\d.]+)/)?ua.match(/msie ([\d.]+)/)[1]:"";""!==tridentVersion?browser.version=String(parseInt(tridentVersion,10)+4):""!==msieVersion&&(browser.version=msieVersion)}else versionMatch&&(browser.version=ua.match(versionMatch[0])?ua.match(versionMatch[0])[1]:"")}catch(e){browser.type="取值异常"}return browser},Browser.prototype.getModel=function(){var userAgent=navigator.userAgent;if(/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent)){if(/iPhone|iPad|iPod/i.test(userAgent))return userAgent.match(/iPhone|iPad|iPod/i)[0];if(/Android/i.test(userAgent))return userAgent.match(/Android/i)[0]}var mac=userAgent.match(/Mac/);if(mac)return mac[0];var windows=userAgent.match(/Windows/);if(windows)return windows[0];var linux=userAgent.match(/Linux/);return linux?linux[0]:"取值异常"},Browser}();function getScrollTop(){return document.documentElement.scrollTop||document.body.scrollTop||0}function getScreenHeight(){return window.innerHeight||document.documentElement.clientHeight||document.body.clientHeight||0}function getScreenWidth(){return window.innerWidth||document.documentElement.clientWidth||document.body.clientWidth||0}var ListenPageState=function(){function ListenPageState(payload){this.visibleHandler=function(){},this.hiddenHandler=function(){};var visible=payload.visible,hidden=payload.hidden;isFunction(visible)&&(this.visibleHandler=visible),isFunction(hidden)&&(this.hiddenHandler=hidden),this.init()}return ListenPageState.prototype.isSupport=function(){return void 0!==document.hidden},ListenPageState.prototype.init=function(){var _this=this;this.isSupport()?document.addEventListener("visibilitychange",(function(){document.hidden?_this.hiddenHandler():_this.visibleHandler()})):(window.addEventListener("focus",this.visibleHandler),window.addEventListener("blur",this.hiddenHandler))},ListenPageState}();var ImageRequest=function(){function ImageRequest(options){this.options=options}return ImageRequest.prototype.run=function(){var _this=this;return new Promise((function(resolve){var _a=_this.options,imgUseCrossOrigin=_a.imgUseCrossOrigin,url=_a.url,data=_a.data,img=new Image;imgUseCrossOrigin&&(img.crossOrigin="anonymous");var spliceStr=-1===url.indexOf("?")?"?":"&";img.src="".concat(url).concat(spliceStr).concat(data);var callback=function(type){img=null,resolve({type:type})};img.onload=function(){callback("success")},img.onerror=function(){callback("success")}}))},ImageRequest}(),AjaxRequest=function(){function AjaxRequest(options){this.options=options}return AjaxRequest.prototype.run=function(){var _this=this;return new Promise((function(resolve){var _a=_this.options,url=_a.url,data=_a.data,timeout=_a.timeout,credentials=_a.credentials,contentType=_a.contentType,_b=_a.customHeaders,customHeaders=void 0===_b?{}:_b,xhr=new XMLHttpRequest;xhr.open("POST",url,!0),xhr.timeout=timeout||2e4,xhr.isMonitor=!0,credentials&&(xhr.withCredentials=!0),xhr.setRequestHeader("Content-Type",contentType||"application/x-www-form-urlencoded"),isObject(customHeaders)&&!isEmptyObject(customHeaders)&&Object.keys(customHeaders).forEach((function(key){xhr.setRequestHeader(key,customHeaders[key])})),xhr.send(data||null),xhr.onreadystatechange=function(){4===xhr.readyState&&(xhr.status>=200&&xhr.status<300||304===xhr.status?resolve({data:JSON.parse(xhr.responseText)||{},type:"success"}):resolve({type:"fail",msg:"网络异常, 请求失败,状态码=".concat(xhr.status)}))}}))},AjaxRequest}(),BeaconRequest=function(){function BeaconRequest(options){this.options=options}return BeaconRequest.prototype.run=function(){var _this=this;return new Promise((function(resolve){var _a=_this.options,url=_a.url,data=_a.data;navigator.sendBeacon&&resolve(navigator.sendBeacon(url,data)?{type:"success"}:{type:"fail",msg:"sendBeacon 请求失败"})}))},BeaconRequest}(),BatchSend=function(){function BatchSend(options,batchKey,batchDataKey){void 0===batchKey&&(batchKey="hinasdk_tab"),void 0===batchDataKey&&(batchDataKey="hinasdk_data_"),this.options=options,this.batchKey=batchKey,this.batchDataKey=batchDataKey,this.isSending=!1,this.init()}return BatchSend.prototype.log=function(message,type){void 0===type&&(type=exports.ConsoleTypes.LOG),this.options.showLog&&log(message,type)},BatchSend.prototype.init=function(){var localStorage=new LocalStorage;localStorage.isSupport()?(this.localStorage=localStorage,this.isSupport=!0):(this.isSupport=!1,this.log("批量发送功能需要使用localstorage存储数据,但是您的浏览器不支持localstorage,所以不能使用该功能",exports.ConsoleTypes.WARN)),this.batchInterval()},BatchSend.prototype.getBatchConfig=function(){return this.options.batchSend},BatchSend.prototype.getStorageList=function(){if(!this.isSupport)return[];var list=[],tabStorage=this.localStorage.get(this.batchKey);return tabStorage&&(isArray(list=safeJSONParse(tabStorage))||(list=[])),list},BatchSend.prototype.batchInterval=function(){var _this=this;if(this.isSupport){var sendInterval=this.getBatchConfig().sendInterval;setTimeout((function(){_this.send().then((function(){_this.batchInterval()}))}),sendInterval)}},BatchSend.prototype.send=function(){var _this=this;return new Promise((function(resolve){var tabStorageList=_this.getStorageList();if(tabStorageList.length>0&&_this.isSupport){for(var dataSendTimeout=_this.getBatchConfig().dataSendTimeout,now=nowStamp(),list_1=[],removeKeyToValues_1={},len=tabStorageList.length,i=0;i<len;i++){var _a=tabStorageList[i],dataKey=_a.dataKey,expireTime=_a.expireTime;if(expireTime>=now)removeKeyToValues_1[dataKey]={dataKey:dataKey,expireTime:expireTime},(data=_this.localStorage.get(dataKey))&&list_1.push(safeJSONParse(data));else _this.localStorage.remove(dataKey),tabStorageList.splice(i,1),len--,i--}if(_this.localStorage.set(_this.batchKey,JSON.stringify(tabStorageList)),0===list_1.length)resolve();else{var _b=_this.options,serverUrl_1=_b.serverUrl,customHeaders=_b.customHeaders,credentials=_b.credentials,globalCallback_1=_b.globalCallback,listStr=JSON.stringify(list_1),data=encodeURIComponent(base64Encode(listStr));_this.isSending=!0,new AjaxRequest({url:serverUrl_1,data:"data_list=".concat(data),timeout:dataSendTimeout,credentials:credentials,customHeaders:customHeaders}).run().then((function(res){isFunction(globalCallback_1)&&globalCallback_1(serverUrl_1,list_1,res.type,res.msg||""),"success"===res.type&&_this.remove(removeKeyToValues_1),resolve(),_this.isSending=!1}))}}else resolve()}))},BatchSend.prototype.remove=function(removeKeyToValues){var _this=this;if(this.isSupport){var tabStorageList=this.getStorageList(),removeKeys=Object.keys(removeKeyToValues);if(removeKeys.forEach((function(key){_this.localStorage.remove(key)})),tabStorageList.length===removeKeys.length)this.localStorage.set(this.batchKey,JSON.stringify([]));else{var list=tabStorageList.filter((function(item){return!removeKeyToValues[item.dataKey]}));this.localStorage.set(this.batchKey,JSON.stringify(list))}}},BatchSend.prototype.add=function(data){if(this.isSupport){var now,num,_a=this.getBatchConfig(),sendInterval=_a.sendInterval,storageLimit=_a.storageLimit,dataKey=this.batchDataKey+(now=nowStamp(),num=Math.floor(1e6*Math.random()),"".concat(now,"_").concat(num)),tabStorage=this.getStorageList();tabStorage.unshift({dataKey:dataKey,expireTime:nowStamp()+2*sendInterval}),this.localStorage.set(this.batchKey,JSON.stringify(tabStorage)),this.localStorage.set(dataKey,JSON.stringify(data)),!this.isSending&&(tabStorage.length>storageLimit||"track_signup"===data.type||"H_pageview"===data.event)&&this.send()}},BatchSend}();function checkReportProperties(props,maxStringLength){Object.keys(props).forEach((function(key){var value=props[key];if(isString(value)&&value.length>maxStringLength)log("属性 ".concat(key," 已经做截取")),props[key]=value.slice(0,maxStringLength);else if(isObject(value))checkReportProperties(value,maxStringLength);else if(isFunction(value))try{props[key]=value(props),isFunction(props[key])?(log("属性--".concat(key," 格式不满足要求, 已被删除"),exports.ConsoleTypes.WARN),delete props[key]):isObject(props[key])?checkReportProperties(props[key],maxStringLength):isString(props[key])&&props[key].length>maxStringLength&&(props[key]=props[key].slice(0,maxStringLength))}catch(e){log("属性--".concat(key," 格式不满足要求, 已被删除"),exports.ConsoleTypes.WARN),delete props[key]}}))}var DEFAULT_ABTEST_VALIDATE_KEYS=["abtestExperimentId","paramName","valueType","defaultValue","callback","timeoutMilliseconds","customProperties","customIds"],AbtestBasePlugin=function(_super){function AbtestBasePlugin(options,context,platform,storageName,version){var _this=_super.call(this,options,context)||this;return _this.options=options,_this.context=context,_this.name="AbtestBasePlugin",_this.isReady=!1,_this.platform="",_this.storageName="",_this.version="",_this.projectKey="",_this.platform=platform,_this.storageName=storageName,_this.version=version,_this}return __extends(AbtestBasePlugin,_super),AbtestBasePlugin.prototype.init=function(){var _this=this;if(this.context.store.localStorage){var abTestingPluginConfig=this.options.abTestingPluginConfig,url=null==abTestingPluginConfig?void 0:abTestingPluginConfig.url;if(isString(url)){var projectKey=getQueryParam(url,"project-key");if(projectKey){if(this.projectKey=projectKey,["Web","H5"].includes(this.platform)){var protocol=getURL(url).protocol,websiteProtocol=getURL(window.location.href).protocol;protocol&&protocol!==websiteProtocol&&this.context.log("A/B Testing 初始化失败,".concat(websiteProtocol," 页面必须使用 ").concat(websiteProtocol," 的 URL"),exports.ConsoleTypes.WARN)}if(this.isReady)this.context.log("A/B Testing 插件已经运行,无需重复执行",exports.ConsoleTypes.WARN);else{var accountId=this.context.getUserUid();this.context.log("当前accountId为:".concat(accountId),exports.ConsoleTypes.INFO),mitt.on("changeAccountId",(function(){_this.context.store.localStorage.set(_this.storageName,"")})),this.isReady=!0}}else this.context.log("A/B Testing 初始化失败,请使用正确的 URL(必须包含 project-key)")}else this.context.log("A/B Testing 初始化失败,请使用正确的 URL!",exports.ConsoleTypes.WARN)}else this.context.log("A/B Testing 初始化失败,浏览器不支持localStorage",exports.ConsoleTypes.WARN)},AbtestBasePlugin.prototype.transform=function(){},AbtestBasePlugin.prototype.valueMatchType=function(value,type){switch(type){case exports.VariablesTypes.INTEGER:return isNumber(value);case exports.VariablesTypes.STRING:return isString(value);case exports.VariablesTypes.BOOLEAN:return isBoolean(value);default:return!1}},AbtestBasePlugin.prototype.normalizeParams=function(prefixLog,params,validateKeys){var e_1,_a;void 0===validateKeys&&(validateKeys=DEFAULT_ABTEST_VALIDATE_KEYS);var result={verify_success:!0,para:params};try{for(var validateKeys_1=__values(validateKeys),validateKeys_1_1=validateKeys_1.next();!validateKeys_1_1.done;validateKeys_1_1=validateKeys_1.next()){var key=validateKeys_1_1.value;if(!result.verify_success)break;switch(key){case"abtestExperimentId":isString(params.abtestExperimentId)&&params.abtestExperimentId.trim()||(this.context.log("".concat(prefixLog,"方法调用失败,").concat(key,"参数未正确配置!").concat(key,": ").concat(params.abtestExperimentId),exports.ConsoleTypes.WARN),result.verify_success=!1);break;case"paramName":isString(params.paramName)&&params.paramName.trim()||(this.context.log("".concat(prefixLog,"方法调用失败,").concat(key,"参数未正确配置!").concat(key,": ").concat(params.paramName),exports.ConsoleTypes.WARN),result.verify_success=!1);break;case"valueType":[exports.VariablesTypes.BOOLEAN,exports.VariablesTypes.INTEGER,exports.VariablesTypes.STRING].includes(params.valueType)||(this.context.log("".concat(prefixLog,"方法调用失败,").concat(key,"参数未正确配置!").concat(key,": ").concat(params.valueType),exports.ConsoleTypes.WARN),result.verify_success=!1);break;case"defaultValue":this.valueMatchType(params.defaultValue,params.valueType)||(this.context.log("".concat(prefixLog,"方法调用失败,").concat(key,"类型必须与valueType一致!"),exports.ConsoleTypes.WARN),result.verify_success=!1);break;case"callback":isFunction(params.callback)||(this.context.log("".concat(prefixLog,"方法调用失败,").concat(key,"参数未正确配置")),params.callback=noop,result.verify_success=!1);break;case"timeoutMilliseconds":(!isNumber(params.timeoutMilliseconds)||params.timeoutMilliseconds<=0)&&(this.context.log("".concat(key,"参数错误:").concat(params.timeoutMilliseconds),exports.ConsoleTypes.WARN),params.timeoutMilliseconds=3e3),params.timeoutMilliseconds<200&&(params.timeoutMilliseconds=200);break;case"customProperties":params.customProperties=isObject(params.customProperties)?params.customProperties:{};break;case"customIds":var customIds=params.customIds||{},resultIds={};for(var key_1 in customIds)(isString(customIds[key_1])||isNumber(customIds[key_1]))&&(resultIds[key_1]=customIds[key_1]);params.customIds=resultIds}}}catch(e_1_1){e_1={error:e_1_1}}finally{try{validateKeys_1_1&&!validateKeys_1_1.done&&(_a=validateKeys_1.return)&&_a.call(validateKeys_1)}finally{if(e_1)throw e_1.error}}return result},AbtestBasePlugin.prototype.sendTriggerEvent=function(data){var abtest_experiment_group_id=data.abtest_experiment_group_id,abtest_experiment_id=data.abtest_experiment_id;this.context.track("H_ABTestTrigger",{H_abtest_experiment_id:abtest_experiment_id,H_abtest_experiment_group_id:abtest_experiment_group_id})},AbtestBasePlugin.prototype.getExpResult=function(params_1){return __awaiter(this,arguments,void 0,(function(params,list){var abtestExperimentId,paramName,valueType,result,storageData,list_1,list_1_1,item,abtest_experiment_id,abtest_experiment_group_id,is_white_list,variables,detail,e_2,_a;return void 0===list&&(list=[]),__generator(this,(function(_b){switch(_b.label){case 0:return abtestExperimentId=params.abtestExperimentId,paramName=params.paramName,valueType=params.valueType,0!==list.length?[3,2]:[4,this.getStorageData()];case 1:isObject(storageData=_b.sent())&&(list=storageData.result||[]),_b.label=2;case 2:try{for(list_1=__values(list),list_1_1=list_1.next();!list_1_1.done;list_1_1=list_1.next())if(item=list_1_1.value,abtest_experiment_id=item.abtest_experiment_id,abtest_experiment_group_id=item.abtest_experiment_group_id,is_white_list=item.is_white_list,variables=item.variables,abtest_experiment_id===abtestExperimentId&&(detail=variables.find((function(item){return item.name===paramName&&item.type===valueType})),detail)){is_white_list||this.sendTriggerEvent({abtest_experiment_id:abtest_experiment_id,abtest_experiment_group_id:abtest_experiment_group_id}),result=detail.value;break}}catch(e_2_1){e_2={error:e_2_1}}finally{try{list_1_1&&!list_1_1.done&&(_a=list_1.return)&&_a.call(list_1)}finally{if(e_2)throw e_2.error}}return[2,result]}}))}))},AbtestBasePlugin.prototype.getStorageData=function(){return __awaiter(this,void 0,void 0,(function(){var data;return __generator(this,(function(_a){switch(_a.label){case 0:return[4,this.context.store.localStorage.get(this.storageName)];case 1:return(data=_a.sent())?[2,safeJSONParse(data)]:[2,null]}}))}))},AbtestBasePlugin.prototype.saveResponseData=function(list){return __awaiter(this,void 0,void 0,(function(){var storageData,data,newList_1,oldList_1;return __generator(this,(function(_a){switch(_a.label){case 0:return[4,this.getStorageData()];case 1:return storageData=_a.sent(),data={updateTime:nowStamp()},storageData&&isObject(storageData)?(newList_1=[],oldList_1=storageData.result||[],list.forEach((function(item){var abtest_experiment_group_id=item.abtest_experiment_group_id,abtest_experiment_id=item.abtest_experiment_id,variables=item.variables,existsDetail=oldList_1.find((function(it){return it.abtest_experiment_id===abtest_experiment_id&&it.abtest_experiment_group_id===abtest_experiment_group_id}));if(existsDetail){var newVariables_1=[];variables.forEach((function(it){var name=it.name,type=it.type,index=existsDetail.variables.findIndex((function(t){return t.name===name&&t.type===type}));index>=0?existsDetail.variables[index]=it:newVariables_1.push(it)})),existsDetail.variables=__spreadArray(__spreadArray([],__read(existsDetail.variables),!1),__read(newVariables_1),!1)}else newList_1.push(item)})),data.result=__spreadArray(__spreadArray([],__read(oldList_1),!1),__read(newList_1),!1)):data.result=list,this.context.store.localStorage.set(this.storageName,JSON.stringify(data)),[2]}}))}))},AbtestBasePlugin.prototype.createRequestData=function(params){var paramName=params.paramName,customProperties=params.customProperties,customIds=params.customIds,requestData={anonymous_id:this.context.store.getAnonymousId(),platform:this.platform,abtest_lib_version:this.version,param_name:paramName,properties:this.context.getPresetProperties()};return isObject(customProperties)&&!isEmptyObject(customProperties)&&(requestData.custom_properties=customProperties),isObject(customIds)&&!isEmptyObject(customIds)&&(requestData.custom_ids=customIds),this.context.getUserUid()&&(requestData.login_id=this.context.getUserUid()),requestData},AbtestBasePlugin.prototype.preFetch=function(prefixLog,params){return this.isReady?!!isObject(params)||(this.context.log("".concat(prefixLog," 方法参数必须是对象"),exports.ConsoleTypes.WARN),!1):(this.context.log("A/B Testing 插件尚未运行,请先执行该插件",exports.ConsoleTypes.WARN),!1)},AbtestBasePlugin.prototype.asyncFetch=function(params){var _this=this;return new Promise((function(resolve){_this.getResultFromServer(params).then((function(res){resolve(res)})).catch((function(){params.callback(params.defaultValue)}))}))},AbtestBasePlugin.prototype.asyncFetchABTest=function(params){var _this=this;if(this.preFetch("asyncFetchABTest",params)){var _a=this.normalizeParams("asyncFetchABTest",params),verify_success=_a.verify_success,para=_a.para;verify_success?this.asyncFetch(para).then((function(res){return __awaiter(_this,void 0,void 0,(function(){var result;return __generator(this,(function(_a){switch(_a.label){case 0:return[4,this.getExpResult(para,res.results)];case 1:return result=_a.sent(),para.callback(result||para.defaultValue),[2]}}))}))})):para.callback(para.defaultValue)}},AbtestBasePlugin.prototype.fetchCacheABTest=function(params){return __awaiter(this,void 0,void 0,(function(){var _a,verify_success,para,result;return __generator(this,(function(_b){switch(_b.label){case 0:return this.preFetch("fetchCacheABTest",params)?(_a=this.normalizeParams("fetchCacheABTest",params),verify_success=_a.verify_success,para=_a.para,verify_success?[4,this.getExpResult(para)]:[3,2]):[2];case 1:return result=_b.sent(),para.callback(result||para.defaultValue),[3,3];case 2:para.callback(para.defaultValue),_b.label=3;case 3:return[2]}}))}))},AbtestBasePlugin.prototype.fastFetchABTest=function(params){return __awaiter(this,void 0,void 0,(function(){var _a,verify_success,para,result,_this=this;return __generator(this,(function(_b){switch(_b.label){case 0:return this.preFetch("fastFetchABTest",params)?(_a=this.normalizeParams("fastFetchABTest",params),verify_success=_a.verify_success,para=_a.para,verify_success?[4,this.getExpResult(para)]:[3,2]):[2];case 1:return isValid(result=_b.sent())?para.callback(result):this.asyncFetch(para).then((function(){return __awaiter(_this,void 0,void 0,(function(){var result;return __generator(this,(function(_a){switch(_a.label){case 0:return[4,this.getExpResult(para)];case 1:return result=_a.sent(),para.callback(result||para.defaultValue),[2]}}))}))})),[3,3];case 2:para.callback(para.defaultValue),_b.label=3;case 3:return[2]}}))}))},AbtestBasePlugin}(PluginBase);function isElement(val){return 1===(null==val?void 0:val.nodeType)}function getInputElementContent(element,isCollectInput){var _a;if("input"===(null===(_a=element.tagName)||void 0===_a?void 0:_a.toLowerCase())){var type=element.type||element.getAttribute("type");return(["button","submit"].includes(type)||isCollectInput)&&(element.textContent||element.value)||""}var textContent="";return element.textContent?textContent=element.textContent.trim():element.innerText&&(textContent=element.innerText.trim()),textContent&&(textContent=textContent.replace(/[\r\n]/g," ").replace(/[ ]+/g," ").substring(0,255)),textContent||""}function getElementProperties(element,isCollectInput){var _a;if(!isElement(element))return{};var obj,props={H_element_type:null===(_a=element.tagName)||void 0===_a?void 0:_a.toLowerCase(),H_element_name:element.getAttribute("name"),H_element_id:element.getAttribute("id"),H_element_target_url:element.getAttribute("href"),H_element_class_name:element.classList.value||element.className,H_element_content:getInputElementContent(element,isCollectInput)};return obj=props,Object.keys(obj).reduce((function(acc,key){return isValid(obj[key])&&""!==obj[key]&&(acc[key]=obj[key]),acc}),{})}function getPageXYInfo(event,target){if(!event)return{};var scrollLeft=document.documentElement.scrollLeft||document.body.scrollLeft||0,scrollTop=getScrollTop(),rect=target.getBoundingClientRect(),pageX=event.pageX||event.clientX+scrollLeft||event.offsetX+((null==rect?void 0:rect.left)||0)+scrollLeft,pageY=event.pageY||event.clientY+scrollTop||event.offsetY+((null==rect?void 0:rect.top)||0)+scrollTop;return{H_page_x:formatDecimal(pageX,3),H_page_y:formatDecimal(pageY,3)}}var BaseCore=function(){function BaseCore(options,useInstancing){void 0===useInstancing&&(useInstancing=!0),this.isReady=!1,this.consolePrefix="埋点SDK",this.useInstancing=!0,this.plugins=[],this.options=options,this.useInstancing=useInstancing}return BaseCore.prototype.log=function(message,type){void 0===type&&(type=exports.ConsoleTypes.LOG),this.options.showLog&&("string"==typeof message&&this.consolePrefix&&(message="".concat(this.consolePrefix,":").concat(message)),log(message,type))},BaseCore.prototype.runPlugins=function(plugins){var _this=this;plugins.forEach((function(plugin){plugin.disabled||plugin.init((function(data){if(plugin.transform){var result=plugin.transform(data);result&&_this.report(result)}}))}))},BaseCore.prototype.applyPlugins=function(plugins){var _this=this;if(this.isReady){isArray(plugins)||(plugins=[plugins]);var currentPlugins=[];plugins.forEach((function(Plugin){var instance=new Plugin(_this.options,_this);_this.plugins.push(instance),currentPlugins.push(instance)})),this.runPlugins(currentPlugins)}else this.log("请先初始化SDK实例",exports.ConsoleTypes.WARN)},BaseCore}(),WebClient=function(_super){function WebClient(){return null!==_super&&_super.apply(this,arguments)||this}return __extends(WebClient,_super),WebClient.prototype.sendReportData=function(data,callback,type){var _a=this.options,batchSend=_a.batchSend,globalCallback=_a.globalCallback,serverUrl=_a.serverUrl,dataSendTimeout=_a.dataSendTimeout,sendType=_a.sendType,customHeaders=_a.customHeaders,credentials=_a.credentials,imgUseCrossOrigin=_a.imgUseCrossOrigin;if(sendType=type||sendType,serverUrl){if(isObject(data)&&!isEmptyObject(data))if(batchSend)this.batchSender.add(data);else{var dataStr=data;isString(data)||(dataStr=function(obj){try{return JSON.stringify(obj)}catch(e){return obj}}(data));var base64Data=base64Encode(dataStr),params={data:"data=".concat(encodeURIComponent(base64Data)),url:serverUrl,timeout:dataSendTimeout,imgUseCrossOrigin:imgUseCrossOrigin,customHeaders:customHeaders,credentials:credentials};(sendType===exports.ReportTypes.BEACON&&navigator.sendBeacon?new BeaconRequest(params):sendType===exports.ReportTypes.IMAGE&&params.data.length<2048?new ImageRequest(params):new AjaxRequest(params)).run().then((function(res){return isFunction(globalCallback)&&globalCallback(serverUrl,data,res.type,res.msg||""),isFunction(callback)&&callback(serverUrl,data,res.type,res.msg||""),res}))}}else this.log("当前 serverUrl 为空,network 中不会发数据,请配置正确的 serverUrl!",exports.ConsoleTypes.WARN)},WebClient}(BaseCore);var ignoreTags=["mark","/mark","strong","b","em","i","u","abbr","ins","del","s","sup"],defaultTags=["a","input","button","textarea"],ClickTrackPlugin=function(_super){function ClickTrackPlugin(options,context){var _this=_super.call(this,options,context)||this;return _this.options=options,_this.context=context,_this.name="ClickTrackPlugin",_this.isReady=!1,_this.isTrackList={a:!0,button:!0},_this}return __extends(ClickTrackPlugin,_super),ClickTrackPlugin.prototype.init=function(notify){var _this=this,_a=this.options.autoTrackConfig,clickAutoTrack=_a.clickAutoTrack,isCollectUrl=_a.isCollectUrl,isCollectElement=_a.isCollectElement,addCustomProperty=_a.addCustomProperty;!0===clickAutoTrack&&(this.isReady?this.context.log("ClickTrack plugin:插件已经运行,无需重复执行",exports.ConsoleTypes.WARN):(this.isReady=!0,document.addEventListener("click",(function(e){if(isCollectUrl()){var event=e||window.event;if(event){var eventTarget=event.target||event.srcElement,target=_this.getTargetElement(eventTarget);if(target){if(isFunction(isCollectElement)&&!isCollectElement(target))return!1;var props=_this.getClickElementInfo(target),_a=getPageXYInfo(event,target),H_page_x=_a.H_page_x,H_page_y=_a.H_page_y,pathname=getURL(window.location.href).pathname;props.H_url_path=pathname,props.H_page_x=H_page_x,props.H_page_y=H_page_y;var element_position=_this.getElementPosition(target,props.H_element_path);if(isNumber(element_position)&&element_position>=0&&(props.H_element_position=element_position),isFunction(addCustomProperty)){var customProperty=addCustomProperty(target);isObject(customProperty)&&(props=merge(props,customProperty))}notify(props)}}}}),!0)))},ClickTrackPlugin.prototype.transform=function(data){return this.context.getReportData("track","H_WebClick",data)},ClickTrackPlugin.prototype.hasAttribute=function(element,attrName){var _a;return element.hasAttribute?element.hasAttribute(attrName):element.attributes?!!(null===(_a=element.attributes[attrName])||void 0===_a?void 0:_a.value):void 0},ClickTrackPlugin.prototype.hasAttributes=function(element,attrNames){if(isArray(attrNames))for(var i=0;i<attrNames.length;i++)if(this.hasAttribute(element,attrNames[i]))return!0;return!1},ClickTrackPlugin.prototype.hasElement=function(element){var e_1,_a,_b,elementsList=function(element){var pathArr=[element];try{if(!isElement(element))return pathArr;if(null===element||null===element.parentElement)return pathArr;for(;null!==element.parentElement;)element=element.parentElement,pathArr.push(element);return pathArr}catch(error){}return pathArr}(element),trackAttr=this.options.autoTrackConfig.trackAttr||[];if(isArray(elementsList)&&elementsList.length>0)try{for(var elementsList_1=__values(elementsList),elementsList_1_1=elementsList_1.next();!elementsList_1_1.done;elementsList_1_1=elementsList_1.next()){var ele=elementsList_1_1.value,tagName=ele.tagName&&(null===(_b=ele.tagName)||void 0===_b?void 0:_b.toLowerCase());if(isElement(ele)&&(this.isTrackList[tagName]||this.hasAttributes(ele,trackAttr)))return ele}}catch(e_1_1){e_1={error:e_1_1}}finally{try{elementsList_1_1&&!elementsList_1_1.done&&(_a=elementsList_1.return)&&_a.call(elementsList_1)}finally{if(e_1)throw e_1.error}}},ClickTrackPlugin.prototype.getDivMaxLevel=function(){var _a;return(null===(_a=this.options.autoTrackConfig.collectTags.div)||void 0===_a?void 0:_a.maxLevel)||1},ClickTrackPlugin.prototype.isStyleTag=function(tagName){var _a,ignoreTags=(null===(_a=this.options.autoTrackConfig.collectTags.div)||void 0===_a?void 0:_a.ignoreTags)||[];return null==ignoreTags?void 0:ignoreTags.includes(tagName)},ClickTrackPlugin.prototype.getCollectableParent=function(target){var _a;try{var parentNode=target.parentNode,parentTagName=parentNode?null===(_a=parentNode.tagName)||void 0===_a?void 0:_a.toLowerCase():"";if("body"===parentTagName)return!1;var maxLevel=this.getDivMaxLevel();if("div"===parentTagName&&(maxLevel>1||this.isCollectableDiv(parentNode)))return parentNode;if(parentNode&&this.isStyleTag(parentTagName))return this.getCollectableParent(parentNode)}catch(error){this.context.log(error,exports.ConsoleTypes.ERROR)}return!1},ClickTrackPlugin.prototype.isCollectableDiv=function(element){var _a;try{var children=element.children||[];if(0===children.length)return!0;for(var i=0;i<children.length;i++){var child=children[i];if(isElement(child)){var tagName=null===(_a=child.tagName)||void 0===_a?void 0:_a.toLowerCase(),maxLevel=this.getDivMaxLevel();if(!("div"===tagName&&maxLevel>1||this.isStyleTag(tagName)))return!1;if(!this.isCollectableDiv(child))return!1}}return!0}catch(error){this.context.log(error,exports.ConsoleTypes.ERROR)}return!1},ClickTrackPlugin.prototype.isDivLevelValid=function(rootElement){for(var maxLevel=this.getDivMaxLevel(),htmlCollection=rootElement.getElementsByTagName("div"),i=htmlCollection.length-1;i>=0;i--)if(this.getDivLevels(htmlCollection[i],rootElement)>maxLevel)return!1;return!0},ClickTrackPlugin.prototype.getElementPath=function(element,ignoreId,rootElement){for(var _a,_b,names=[];isElement(element)&&element.parentNode;){if(element.id&&!ignoreId&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(element.id)){var tagName=element.tagName||"";names.unshift("".concat(tagName.toLowerCase(),"#").concat(element.id));break}if(rootElement&&element===rootElement){names.unshift(null===(_a=element.tagName)||void 0===_a?void 0:_a.toLowerCase());break}if(element===document.body){names.unshift("body");break}names.unshift(null===(_b=element.tagName)||void 0===_b?void 0:_b.toLowerCase()),element=element.parentNode}return names.join(" > ")},ClickTrackPlugin.prototype.getDivLevels=function(element,rootElement){var pathArr=this.getElementPath(element,!0,rootElement).split(" > "),level=0;return pathArr.forEach((function(tag){"div"===tag&&level++})),level},ClickTrackPlugin.prototype.getTargetElement=function(eventTarget){var _a;if(!isElement(eventTarget))return null;var tagName=null===(_a=eventTarget.tagName)||void 0===_a?void 0:_a.toLowerCase();if(!isString(tagName))return null;if(["body","html"].includes(tagName))return null;if(this.context.trackTags.includes(tagName)&&"div"!==tagName)return eventTarget;if("div"===tagName&&this.options.autoTrackConfig.collectTags.div&&(this.isDivLevelValid(eventTarget)&&(this.getDivMaxLevel()>1||this.isCollectableDiv(eventTarget))))return eventTarget;if(this.options.autoTrackConfig.collectTags.div&&this.isStyleTag(tagName)){var parentTrackDiv=this.getCollectableParent(eventTarget);if(parentTrackDiv&&this.isDivLevelValid(parentTrackDiv))return parentTrackDiv}return this.hasElement(eventTarget)||null},ClickTrackPlugin.prototype.getClickElementInfo=function(element){var isCollectInput=this.options.autoTrackConfig.isCollectInput,isCollectInputValue=!1;isFunction(isCollectInput)&&(isCollectInputValue=isCollectInput(element));var selector=this.getDomSelector(element),props=getElementProperties(element,isCollectInputValue);return props.H_element_selector=selector,props.H_element_path=this.getElementPath(element,!1),props},ClickTrackPlugin.prototype.getDomSelector=function(element){for(var _a,paths=[];element;){if("body"===(null===(_a=element.tagName)||void 0===_a?void 0:_a.toLowerCase())||!isElement(element)){paths.unshift("body");break}if(paths.unshift(this.getSelector(element)),(null==element?void 0:element.getAttribute("id"))&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(element.getAttribute("id")))break;element=element.parentNode}return paths.join(" > ")},ClickTrackPlugin.prototype.getSelector=function(element){var _a,_b,tagName=null===(_a=element.tagName)||void 0===_a?void 0:_a.toLowerCase(),i=-1;9!==(null===(_b=element.parentNode)||void 0===_b?void 0:_b.nodeType)&&(i=this.getDomIndex(element));var idValue=element.getAttribute("id");return idValue&&/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(idValue)?"#".concat(idValue):tagName+(i>-1?":nth-of-type(".concat(i+1,")"):"")},ClickTrackPlugin.prototype.getDomIndex=function(element){var _a,_b;if(element.parentNode)for(var index=0,tagName=null===(_a=element.tagName)||void 0===_a?void 0:_a.toLowerCase(),children=element.parentNode.children,i=0;i<children.length;i++){var child=children[i];if((null===(_b=child.tagName)||void 0===_b?void 0:_b.toLowerCase())===tagName){if(child===element)return index;index++}}return-1},ClickTrackPlugin.prototype.getClosestLi=function(element){for(;element&&element!==document&&isElement(element);){if("li"===element.tagName.toLowerCase())return element;element=element.parentNode}return null},ClickTrackPlugin.prototype.getSameTypeSiblings=function(element){for(var _a,_b,parentNode=element.parentNode,tagName=null===(_a=element.tagName)||void 0===_a?void 0:_a.toLowerCase(),list=[],i=0;i<parentNode.children.length;i++){var child=parentNode.children[i];isElement(child)&&(null===(_b=child.tagName)||void 0===_b?void 0:_b.toLowerCase())===tagName&&list.push(child)}return list},ClickTrackPlugin.prototype.getElementPosition=function(element,path){var _a,liElm=this.getClosestLi(element);if(!liElm||!isElement(element)||!isString(element.tagName))return null;var tagName=null===(_a=element.tagName)||void 0===_a?void 0:_a.toLowerCase(),targetElementCollection=liElm.getElementsByTagName(tagName),len=targetElementCollection.length;if(len>1){for(var clickElms=[],i=0;i<len;i++){this.getElementPath(targetElementCollection[i],!1)===path&&clickElms.push(targetElementCollection[i])}if(clickElms.length>0)return clickElms.findIndex((function(el){return el===element}))}if(!liElm.parentNode)return-1;var siblings=this.getSameTypeSiblings(liElm);return 1===siblings.length?0:siblings.findIndex((function(el){return el===liElm}))},ClickTrackPlugin}(PluginBase),StayTrackPlugin=function(_super){function StayTrackPlugin(options,context){var _this=_super.call(this,options,context)||this;return _this.options=options,_this.context=context,_this.name="StayTrackPlugin",_this.isReady=!1,_this.timer=null,_this.previousTime=nowStamp(),_this.previousOffsetTop=0,_this}return __extends(StayTrackPlugin,_super),StayTrackPlugin.prototype.init=function(notify){var _this=this,_a=this.options,autoTrackConfig=_a.autoTrackConfig,stayAutoTrackConfig=_a.stayAutoTrackConfig;if(!0===autoTrackConfig.stayAutoTrack)if(this.isReady)this.context.log("StayTrack plugin:插件已经运行,无需重复执行",exports.ConsoleTypes.WARN);else{this.isReady=!0;var isCollectUrl=stayAutoTrackConfig.isCollectUrl;isFunction(isCollectUrl)||(isCollectUrl=function(){return!0}),this.timer&&(clearTimeout(this.timer),this.timer=null),this.previousTime=nowStamp(),window.addEventListener("load",(function(){_this.previousOffsetTop=getScrollTop()})),window.addEventListener("scroll",(function(){isCollectUrl()&&(_this.timer||(_this.timer=setTimeout((function(){_this.run(notify),clearTimeout(_this.timer),_this.timer=null}),1e3)))})),window.addEventListener("unload",(function(){isCollectUrl()&&_this.run(notify,!0)}))}},StayTrackPlugin.prototype.transform=function(data){return this.context.getReportData("track","H_WebStay",data)},StayTrackPlugin.prototype.run=function(notify,isClosePage){void 0===isClosePage&&(isClosePage=!1);var autoTrackConfig=this.options.autoTrackConfig,stayDelayTime=autoTrackConfig.stayDelayTime,maxStayPageDuration=autoTrackConfig.maxStayPageDuration,offsetTop=getScrollTop(),nowTime=nowStamp(),duration=nowTime-this.previousTime;(isClosePage||duration>stayDelayTime&&offsetTop!==this.previousOffsetTop)&&notify({H_viewport_width:getScreenWidth(),H_viewport_height:getScreenHeight(),H_viewport_position:this.previousOffsetTop,event_duration:Math.min(duration/1e3,maxStayPageDuration),H_url_path:window.location.pathname});this.previousTime=nowTime,this.previousOffsetTop=offsetTop},StayTrackPlugin}(PluginBase),PageLeavePlugin=function(_super){function PageLeavePlugin(options,context){var _this=_super.call(this,options,context)||this;return _this.options=options,_this.context=context,_this.name="PageLeave",_this.isReady=!1,_this.pageId=generatorTrackId(),_this.storageName="hinasdk_pageleave_",_this.heartbeatIntervalTime=5e3,_this.maxDuration=432e3,_this.heartbeatIntervalTimer=null,_this.startTime=nowStamp(),_this.url=window.location.href,_this.pageShowStatus=!0,_this}return __extends(PageLeavePlugin,_super),PageLeavePlugin.prototype.init=function(){if(this.options.autoTrackConfig.pageLeaveAutoTrack)if(this.context.store.localStorage)if(this.isReady)this.context.log("PageLeave plugin:插件已经运行,无需重复执行",exports.ConsoleTypes.WARN);else{this.isReady=!0;var _a=this.normalizePageLeaveAutoTrack(),heartbeat_interval_time=_a.heartbeat_interval_time,max_duration=_a.max_duration;heartbeat_interval_time&&heartbeat_interval_time>0&&(this.heartbeatIntervalTime=1e3*heartbeat_interval_time),max_duration&&max_duration>0&&(this.maxDuration=Number(max_duration)),this.startTime=nowStamp(),this.addPageLeaveEventListener(),document.hidden?this.pageShowStatus=!1:this.startHeartBeatInterval()}else this.context.log("PageLeave plugin需要使用localstorage存储数据,但是您的浏览器不支持localstorage,所以不能使用该功能",exports.ConsoleTypes.WARN)},PageLeavePlugin.prototype.transform=function(){},PageLeavePlugin.prototype.normalizePageLeaveAutoTrack=function(){var pageLeaveAutoTrack=this.options.autoTrackConfig.pageLeaveAutoTrack;return isObject(pageLeaveAutoTrack)?pageLeaveAutoTrack:{}},PageLeavePlugin.prototype.addPageLeaveEventListener=function(){this.addPageStartListener(),this.addPageSwitchListener(),this.addSinglePageListener(),this.addPageEndListener()},PageLeavePlugin.prototype.addPageStartListener=function(){var _this=this;"onpageshow"in window&&window.addEventListener("pageshow",(function(){_this.pageStartHandler()}))},PageLeavePlugin.prototype.addPageSwitchListener=function(){var _this=this;new ListenPageState({visible:function(){_this.pageStartHandler(),_this.startHeartBeatInterval()},hidden:function(){_this.url=window.location.href,_this.pageEndHandler(),_this.stopHeartBeatInterval()}})},PageLeavePlugin.prototype.addSinglePageListener=function(){var _this=this;mitt.on("urlChange",(function(params){var fromHref=params.fromHref;fromHref!==params.toHref&&(_this.url=fromHref,_this.pageEndHandler(),_this.stopHeartBeatInterval(),_this.pageStartHandler(),_this.startHeartBeatInterval())}))},PageLeavePlugin.prototype.addPageEndListener=function(){var _this=this,events=["pagehide","beforeunload","unload"];events.forEach((function(event){"on".concat(events)in window&&window.addEventListener(event,(function(){_this.pageEndHandler(),_this.stopHeartBeatInterval()}))}))},PageLeavePlugin.prototype.pageStartHandler=function(){this.startTime=nowStamp(),this.pageShowStatus=!document.hidden,this.url=window.location.href},PageLeavePlugin.prototype.pageEndHandler=function(){if(this.pageShowStatus){if(this.pageShowStatus=!1,this.isCollectUrl()){var properties=this.getPageLeaveProperties(),data=this.context.getReportData("track","H_WebPageLeave",properties);this.context.report(data)}this.delHeartBeatData()}},PageLeavePlugin.prototype.startHeartBeatInterval=function(){var _this=this;this.heartbeatIntervalTimer&&this.stopHeartBeatInterval(),this.isCollectUrl()&&(this.heartbeatIntervalTimer=setInterval((function(){_this.saveHeartBeatData()}),this.heartbeatIntervalTime),this.saveHeartBeatData("first_heartbeat")),this.reissueHeartBeatData()},PageLeavePlugin.prototype.reissueHeartBeatData=function(){for(var localStorage=this.context.store.localStorage,storageLen=localStorage.length(),i=0;i<storageLen;i++){var itemKey=localStorage.key(i);if(itemKey&&itemKey!==this.storageName+this.pageId&&itemKey.includes(this.storageName)){var result=safeJSONParse(localStorage.get(itemKey));isObject(result)&&nowStamp()-result.time>result.heartbeat_interval_time+5e3&&(delete result.heartbeat_interval_time,this.context.report(result)),this.delHeartBeatData(itemKey)}}},PageLeavePlugin.prototype.stopHeartBeatInterval=function(){this.heartbeatIntervalTimer&&(clearInterval(this.heartbeatIntervalTimer),this.heartbeatIntervalTimer=null)},PageLeavePlugin.prototype.delHeartBeatData=function(storageKey){this.context.store.localStorage.remove(storageKey||this.storageName+this.pageId)},PageLeavePlugin.prototype.isCollectUrl=function(){var isCollectUrl=this.normalizePageLeaveAutoTrack().isCollectUrl;return!isFunction(isCollectUrl)||isCollectUrl(this.url)},PageLeavePlugin.prototype.saveHeartBeatData=function(type){var properties=this.getPageLeaveProperties();properties.H_time=nowStamp(),"first_heartbeat"===type&&(properties.event_duration=3);var props=this.context.getReportData("track","H_WebPageLeave",properties);props.heartbeat_interval_time=this.heartbeatIntervalTime,this.context.store.localStorage.set(this.storageName+this.pageId,JSON.stringify(props))},PageLeavePlugin.prototype.getPageLeaveProperties=function(){var duration=(nowStamp()-this.startTime)/1e3;duration=duration<=0||duration>this.maxDuration?0:formatDecimal(duration,3);var _a=getURL(this.url),pathname=_a.pathname,hash=_a.hash,referrer=getReferrer(),properties={H_url:this.url,H_url_path:pathname,H_url_hash:hash,H_viewport_position:getScrollTop(),H_referrer:referrer,H_referrer_host:referrer?getHostname(referrer):"",event_duration:duration},custom_props=this.normalizePageLeaveAutoTrack().custom_props;return isObject(custom_props)&&(properties=__assign(__assign({},properties),custom_props||{})),properties},PageLeavePlugin}(PluginBase),SiteLinkerPlugin=function(_super){function SiteLinkerPlugin(options,context){var _this=_super.call(this,options,context)||this;return _this.options=options,_this.context=context,_this.name="SiteLinker",_this.isReady=!1,_this.linker=[],_this}return __extends(SiteLinkerPlugin,_super),SiteLinkerPlugin.prototype.init=function(){if(this.options.siteLinkerConfig){var linker=this.getLinkerConfig().linker;isArray(linker)&&linker.length>0?this.isReady?this.context.log("SiteLinker plugin:插件已经运行,无需重复执行",exports.ConsoleTypes.WARN):(this.isReady=!0,this.resolveOption(),this.setRefferId(),this.addClickListen()):this.context.log("siteLinker plugin: 请配置正确的linker参数",exports.ConsoleTypes.WARN)}},SiteLinkerPlugin.prototype.transform=function(){},SiteLinkerPlugin.prototype.getLinkerConfig=function(){var _a=this.options.siteLinkerConfig||{},_b=_a.linker;return{linker:(void 0===_b?[]:_b)||[],re_login:_a.re_login}},SiteLinkerPlugin.prototype.resolveOption=function(){for(var linker=this.getLinkerConfig().linker,len=linker.length,arr=[],i=0;i<len;i++){var _a=linker[i],part_url=_a.part_url,after_hash=_a.after_hash;/[A-Za-z0-9]+\./.test(part_url)&&isBoolean(after_hash)?arr.push({part_url:part_url,after_hash:after_hash}):this.context.log("The configuration of linker ".concat(i+1," is not supported.Please check format"),exports.ConsoleTypes.WARN)}this.linker=arr},SiteLinkerPlugin.prototype.setRefferId=function(){var re_login=this.getLinkerConfig().re_login,urlId=this.getUrlId(),isAnonymousId=urlId.startsWith("a");if(""!==(urlId=urlId.substring(1))){var anonymousId=this.context.store.getAnonymousId(),accountId=this.context.store.getAccountId();if(isAnonymousId){if(urlId!==anonymousId&&(this.context.store.state.anonymousId=urlId,this.context.store.save()),accountId){var props=this.context.getReportData("track_signup","H_SignUp",{});this.context.report(props)}}else(!accountId||re_login&&accountId!==urlId)&&this.context.setUserUId(urlId)}},SiteLinkerPlugin.prototype.getUrlId=function(){var hnId=window.location.href.match(/_hnsdk=([au][^\?\#\&\=]+)/);return isArray(hnId)&&hnId[1]?function(val){var result=val;try{result=decodeURIComponent(val)}catch(e){}return result}(hnId[1]):""},SiteLinkerPlugin.prototype.getPartUrl=function(url){for(var len=this.linker.length,i=0;i<len;i++)if(url.includes(this.linker[i].part_url))return!0;return!1},SiteLinkerPlugin.prototype.getPartHash=function(url){for(var len=this.linker.length,i=0;i<len;i++)if(url.includes(this.linker[i].part_url))return this.linker[i].after_hash;return!1},SiteLinkerPlugin.prototype.getCurrentId=function(){var accountId=this.context.store.getAccountId(),anonymousId=this.context.store.getAnonymousId();return function(val){var result=val;try{result=encodeURIComponent(val)}catch(e){}return result}(accountId?"u".concat(accountId):"a".concat(anonymousId))},SiteLinkerPlugin.prototype.rewriteUrl=function(url,dom){var normalizeUrl=function(url,sdkId,after_hash){var arr=/([^?#]+)(\?[^#]*)?(#.*)?/.exec(url),normalizeUrl="";if(arr){var host=arr[1]||"",search=arr[2]||"",hash=arr[3]||"",hnId="_hnsdk=".concat(sdkId),changeHnId=function(str){var list=str.split("&"),result=[];return list.forEach((function(value){value.includes("_hnsdk")?result.push(hnId):result.push(value)})),result.join("&")};if(after_hash){var hasQuery=hash.includes("?"),index=hash.indexOf("_hnsdk");normalizeUrl=hasQuery?index>=0?"".concat(host).concat(search,"#").concat(hash.substring(1,index)).concat(changeHnId(hash.substring(index,hash.length))):"".concat(host).concat(search,"#").concat(hash.substring(1),"&").concat(hnId):"".concat(host).concat(search,"#").concat(hash.substring(1),"?").concat(hnId)}else normalizeUrl=(hasQuery=/^\?(\w)+/.test(search))?search.includes("_hnsdk")?"".concat(host,"?").concat(changeHnId(search.substring(1))).concat(hash):"".concat(host).concat(search,"&").concat(hnId).concat(hash):"".concat(host,"?").concat(hnId).concat(hash);return normalizeUrl}}(url,this.getCurrentId(),this.getPartHash(url));return dom&&(dom.href=normalizeUrl),normalizeUrl},SiteLinkerPlugin.prototype.addClickListen=function(){var _this=this,handleClick=function(event){var _a,_b,target=event.target;if(target){var tagName=null===(_a=target.tagName)||void 0===_a?void 0:_a.toLowerCase(),parentNode=target.parentNode,parentTagName=null===(_b=null==parentNode?void 0:parentNode.tagName)||void 0===_b?void 0:_b.toLowerCase();if("a"===tagName&&target.href||"a"===parentTagName&&parentNode.href){var sdkUrl=void 0,sdkTarget=void 0;"a"===tagName&&target.href?(sdkUrl=target.href,sdkTarget=target):(sdkUrl=parentNode.href,sdkTarget=parentNode);var protocol=getURL(sdkUrl).protocol;"http:"!==protocol&&"https:"!==protocol||_this.getPartUrl(sdkUrl)&&_this.rewriteUrl(sdkUrl,sdkTarget)}}};"PointerEvent"in window?document.addEventListener("pointerdown",handleClick):document.addEventListener("mousedown",handleClick)},SiteLinkerPlugin}(PluginBase),HistoryPlugin=function(_super){function HistoryPlugin(options,context){var _this=_super.call(this,options,context)||this;return _this.options=options,_this.context=context,_this.name="HistoryPlugin",_this.isReady=!1,_this.lastHref=window.location.href,_this.lastPath=window.location.pathname,_this}return __extends(HistoryPlugin,_super),HistoryPlugin.prototype.init=function(){if(window&&window.history.pushState&&window.history.replaceState)if(this.isReady)this.context.log("History plugin:插件已经运行,无需重复执行",exports.ConsoleTypes.WARN);else{this.isReady=!0;var self=this,originalOnpopstate=window.onpopstate,handleRouterChange=function(currentPath,currentHref){var params={fromPath:self.lastPath,fromHref:self.lastHref,toPath:currentPath,toHref:currentHref};self.lastPath=currentPath,self.lastHref=currentHref,mitt.emit("urlChange",__assign(__assign({},params),{mode:"history"}))};window.onpopstate=function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];var currentPath=window.location.pathname,currentHref=window.location.href;handleRouterChange(currentPath,currentHref),originalOnpopstate&&originalOnpopstate.apply(this,args)},replaceOld(window.history,"pushState",historyReplaceFn),replaceOld(window.history,"replaceState",historyReplaceFn)}function historyReplaceFn(originalHistoryFn){return function(){for(var args=[],_i=0;_i<arguments.length;_i++)args[_i]=arguments[_i];originalHistoryFn.apply(this,args);var currentPath=window.location.pathname,currentHref=window.location.href;handleRouterChange(currentPath,currentHref)}}},HistoryPlugin.prototype.transform=function(){},HistoryPlugin}(PluginBase),HashPlugin=function(_super){function HashPlugin(options,context){var _this=_super.call(this,options,context)||this;return _this.options=options,_this.context=context,_this.name="HashPlugin",_this.isReady=!1,_this.lastHref=window.location.href,_this.lastPath=window.location.hash,_this}return __extends(HashPlugin,_super),HashPlugin.prototype.init=function(){var _this=this;this.isReady?this.context.log("Hash plugin:插件已经运行,无需重复执行",exports.ConsoleTypes.WARN):(this.isReady=!0,window.addEventListener("hashchange",(function(event){var newURL=event.newURL,currentPath=getURL(newURL).hash,params={fromPath:_this.lastPath,fromHref:_this.lastHref,toPath:currentPath,toHref:newURL};_this.lastHref=newURL,_this.lastPath=currentPath,mitt.emit("urlChange",__assign(__assign({},params),{mode:"hash"}))})))},HashPlugin.prototype.transform=function(){},HashPlugin}(PluginBase),AbTestingPlugin=function(_super){function AbTestingPlugin(options,context){var _a,ua,_this=this,platform=(ua=null===(_a=navigator.userAgent)||void 0===_a?void 0:_a.toLowerCase(),/android|webos|iphone|ipod|blackberry/i.test(ua)?"H5":"Web");return(_this=_super.call(this,options,context,platform,"hina_webjs_sdk_abtest","4.0.7")||this).options=options,_this.context=context,_this.name="HinaABTest",_this}return __extends(AbTestingPlugin,_super),AbTestingPlugin.prototype.getResultFromServer=function(params){var _this=this;return new Promise((function(resolve,reject){var requestData=_this.createRequestData(params);new AjaxRequest({url:_this.options.abTestingPluginConfig.url,data:JSON.stringify(requestData),contentType:"application/json",customHeaders:{"project-key":_this.projectKey},timeout:params.timeoutMilliseconds}).run().then((function(res){var data=res.data;"SUCCESS"===(null==data?void 0:data.status)?_this.saveResponseData(data.results).then((function(){resolve(data)})):reject()}))}))},AbTestingPlugin}(AbtestBasePlugin),SearchKeyword=function(){function SearchKeyword(){}return SearchKeyword.getSourceFromReferrer=function(){var getMatchStrFromArr=function(arr,str){for(var i=0;i<arr.length;i++)if(-1!==str.split("?")[0].indexOf(arr[i]))return!0},utm_reg="(".concat(utmTypes.join("|"),")\\=[^&]+"),referrer=document.referrer||"",url=window.location.href;if(url){var utm_match=url.match(new RegExp(utm_reg));return utm_match&&utm_match[0]?"付费广告流量":getMatchStrFromArr(searchTypes,referrer)?"自然搜索流量":getMatchStrFromArr(socialTypes,referrer)?"社交网站流量":""===referrer?"直接流量":"引荐流量"}return"获取url异常"},SearchKeyword.getReferSearchEngine=function(referrerUrl){var e_1,_a,hostname=getHostname(referrerUrl);if(!hostname||"hostname解析异常"===hostname)return"";var regexps={baidu:[/^.*\.baidu\.com$/],bing:[/^.*\.bing\.com$/],google:[/^www\.google\.com$/,/^www\.google\.com\.[a-z]{2}$/,/^www\.google\.[a-z]{2}$/],sm:[/^m\.sm\.cn$/],so:[/^.+\.so\.com$/],sogou:[/^.*\.sogou\.com$/],yahoo:[/^.*\.yahoo\.com$/]};for(var regexp in regexps){var regexList=regexps[regexp];try{for(var regexList_1=(e_1=void 0,__values(regexList)),regexList_1_1=regexList_1.next();!regexList_1_1.done;regexList_1_1=regexList_1.next()){if(regexList_1_1.value.test(hostname))return regexp}}catch(e_1_1){e_1={error:e_1_1}}finally{try{regexList_1_1&&!regexList_1_1.done&&(_a=regexList_1.return)&&_a.call(regexList_1)}finally{if(e_1)throw e_1.error}}}return"未知搜索引擎"},SearchKeyword.getKeywordFromReferrer=function(){var referrerUrl=document.referrer||"";if(0===referrerUrl.indexOf("http")){var searchEngine=this.getReferSearchEngine(referrerUrl),query=function(queryString){queryString=queryString||"";var args={};return new URLSearchParams(queryString).forEach((function(value,key){args[key]=value})),args}(getURL(referrerUrl).search);if(isEmptyObject(query))return"未取到值";for(var key in searchKeywords){var value=searchKeywords[key];if(key===searchEngine)if(isArray(value))for(var i=0;i<value.length;i++){var val=query[value[i]];if(val)return val}else if(query[value])return query[value]}return"未取到值"}return""===referrerUrl?"未取到值_直接打开":"未取到值_非http的url"},SearchKeyword}();function getUmtsParams(prefix){void 0===prefix&&(prefix="");var params,utms=(params={},utmTypes.forEach((function(key){var result=getQueryParam(window.location.href,key);result.length&&(params[key]=result)})),params),allUtms={};return Object.keys(utms).forEach((function(key){allUtms[prefix+key]=utms[key]})),allUtms}var HinaTrack=function(_super){function HinaTrack(options,useInstancing){void 0===useInstancing&&(useInstancing=!0);var _this=_super.call(this,options,useInstancing)||this;return _this.trackTags=defaultTags,_this.customProperties={},_this.generalProperties={H_lib_version:"4.0.7",H_lib:"js",H_lib_method:"code",H_timezone_offset:(new Date).getTimezoneOffset()},_this.useInstancing&&_this.init(options),_this}return __extends(HinaTrack,_super),HinaTrack.prototype.init=function(options){if(this.isReady)this.log("hinaSDK has been initialized",exports.ConsoleTypes.ERROR);else{var default_config={name:"",serverUrl:"",showLog:!1,autoTrackConfig:{clickAutoTrack:!0,stayAutoTrack:!0,isCollectUrl:function(){return!0},isCollectElement:function(){return!0},isCollectInput:function(){return!1},addCustomProperty:function(){},stayDelayTime:4e3,maxStayPageDuration:18e3,collectTags:{div:!1},trackAttr:["hn-click"],pageviewAutoTrack:!1,pageLeaveAutoTrack:!1},stayAutoTrackConfig:{isCollectUrl:function(){return!0}},maxStringLength:1024,imgUseCrossOrigin:!1,isSinglePage:!1,batchSend:!1,appJsBridge:!1,sendType:exports.ReportTypes.AJAX,customHeaders:{},credentials:!1,dataSendTimeout:3e3,presetProperties:{latest_utm:!0,latest_traffic_source_type:!0,latest_search_keyword:!0,latest_referrer:!0},sourceChannel:[],plugins:[]},performanceErrorConfig=options.performanceErrorConfig,plugins=options.plugins,others=function(s,e){var t={};for(var p in s)Object.prototype.hasOwnProperty.call(s,p)&&e.indexOf(p)<0&&(t[p]=s[p]);if(null!=s&&"function"==typeof Object.getOwnPropertySymbols){var i=0;for(p=Object.getOwnPropertySymbols(s);i<p.length;i++)e.indexOf(p[i])<0&&Object.prototype.propertyIsEnumerable.call(s,p[i])&&(t[p[i]]=s[p[i]])}return t}(options,["performanceErrorConfig","plugins"]);this.options=merge(default_config,others),this.options=__assign(__assign({},this.options),{performanceErrorConfig:performanceErrorConfig,plugins:plugins}),this.initState(),this.initAdvProps(),this.normalizeConfig(),this.initPlugins(),this.isReady=!0}},HinaTrack.prototype.normalizeConfig=function(){var _this=this,_a=this.options,serverUrl=_a.serverUrl,sendType=_a.sendType,batchSend=_a.batchSend,maxStringLength=_a.maxStringLength,isSinglePage=_a.isSinglePage,_b=_a.autoTrackConfig,_c=void 0===_b?{}:_b,_d=_c.trackAttr,trackAttr=void 0===_d?[]:_d,collectTags=_c.collectTags,pageLeaveAutoTrack=_c.pageLeaveAutoTrack,pageviewAutoTrack=_c.pageviewAutoTrack;if(""===(serverUrl=(serverUrl=serverUrl||"").trim()))this.log("当前 serverUrl 为空,network 中不会发数据,请配置正确的 serverUrl!",exports.ConsoleTypes.WARN);else{var currentProtocol=getURL(window.location.href).protocol||"";(getURL(serverUrl).protocol||"")!==currentProtocol&&this.log("SDK 检测到您的数据发送地址和当前页面地址的协议不一致,建议您修改成一致的协议。因为:https 下面发送 http 的图片请求会失败。",exports.ConsoleTypes.WARN)}if([exports.ReportTypes.IMAGE,exports.ReportTypes.AJAX,exports.ReportTypes.BEACON].includes(sendType)||this.setConfig({sendType:exports.ReportTypes.AJAX}),this.options.maxStringLength=function(maxStringLength){var maxLength=maxStringLength;return!isNumber(maxStringLength)||maxStringLength<0?maxLength=1024:maxStringLength>5120&&(maxLength=5120),maxLength}(maxStringLength),(!0===pageLeaveAutoTrack||isObject(pageLeaveAutoTrack)&&isEmptyObject(pageLeaveAutoTrack))&&(this.options.autoTrackConfig.pageLeaveAutoTrack={heartbeat_interval_time:5e3,max_duration:432e3}),isArray(trackAttr)?(trackAttr=trackAttr.filter((function(v){return isString(v)}))).includes("hn-click")||trackAttr.push("hn-click"):trackAttr=["hn-click"],this.options.autoTrackConfig.trackAttr=trackAttr,isObject(collectTags))if(!0===collectTags.div)this.options.autoTrackConfig.collectTags.div={ignoreTags:ignoreTags,maxLevel:1};else if(isObject(collectTags.div)){var maxLevel=1,oDiv=collectTags.div;isNumber(oDiv.maxLevel)&&[1,2,3].includes(oDiv.maxLevel)&&(maxLevel=oDiv.maxLevel),this.options.autoTrackConfig.collectTags.div={ignoreTags:ignoreTags,maxLevel:maxLevel}}else this.options.autoTrackConfig.collectTags.div=!1;else this.options.autoTrackConfig.collectTags={div:!1};this.updateTrackTags(),(!0===batchSend||isObject(batchSend)&&!isEmptyObject(batchSend))&&(this.options.batchSend=__assign({dataSendTimeout:6e3,sendInterval:6e3,storageLimit:200},batchSend),this.batchSender=new BatchSend(this.options,"hinasdk_tab","hinasdk_data_")),"auto"===pageviewAutoTrack?this.autoTrack():("singlePage"===pageviewAutoTrack||isSinglePage)&&(this.autoTrack(),mitt.on("urlChange",(function(data){var fromHref=data.fromHref;if(fromHref!==data.toHref){var payload={};if(isFunction(isSinglePage)){var extra=isSinglePage();isObject(extra)&&(payload=__assign(__assign({},payload),extra))}_this.autoTrack(__assign(__assign({},payload),{H_referrer:fromHref}))}})))},HinaTrack.prototype.updateTrackTags=function(){var collectTags=this.options.autoTrackConfig.collectTags,tags=__spreadArray([],__read(defaultTags),!1);Object.keys(collectTags||{}).forEach((function(key){var value=collectTags[key];!0!==value&&!isObject(value)||tags.includes(key)||tags.push(key)})),this.trackTags=tags},HinaTrack.prototype.initState=function(){this.store=new WebState(this.options),this.store.init()},HinaTrack.prototype.initAdvProps=function(){var referrer,advProps={},_a=this.options,presetProperties=_a.presetProperties,sourceChannel=_a.sourceChannel;if(isObject(presetProperties))for(var key in presetProperties){var value=presetProperties[key];if(key.includes("latest_")&&(key=key.slice(7),value)){var url_domain=getCurrentDomain();if("utm"!==key&&"url解析失败"===url_domain)advProps["H_latest_".concat(key)]="url的domain解析失败";else if(""===(referrer=(referrer=void 0)||document.referrer)||getCookieTopLevelDomain(getHostname(referrer))!==getCookieTopLevelDomain())switch(key){case"traffic_source_type":advProps.H_latest_traffic_source_type=SearchKeyword.getSourceFromReferrer();break;case"search_keyword":var searchKeyword=SearchKeyword.getKeywordFromReferrer();searchKeyword&&(advProps.H_latest_search_keyword=searchKeyword);break;case"referrer":advProps.H_latest_referrer=getReferrer()}}}var props=this.store.state.props||{},latestAllUtms={};presetProperties.latest_utm&&(latestAllUtms=getUmtsParams("H_latest_"));var firstAllUtms={};props.H_utm_source||(firstAllUtms=getUmtsParams("H_"));var source=[],customUtm={};isArray(sourceChannel)&&sourceChannel.length>0&&(source=sourceChannel.filter((function(val){return!utmTypes.includes(val)}))).length>0&&(customUtm=__assign(__assign({},customUtm),function(prefix,utms){void 0===utms&&(utms=[]);var allUtms={};return utms.forEach((function(key){var result=getQueryParam(window.location.href,key);result&&(allUtms[key]=result,allUtms["".concat(prefix).concat(key)]=result)})),allUtms}("H_latest_",source))),this.store.state.props=__assign(__assign(__assign(__assign(__assign({},this.store.state.props),advProps),latestAllUtms),customUtm),firstAllUtms),this.store.setProps(this.store.state.props),this.store.getUtmFromProps(source)},HinaTrack.prototype.getGeneralProperties=function(){var browserInfo=new Browser;return this.generalProperties=__assign(__assign(__assign({},this.generalProperties),{H_screen_width:window.screen.width,H_screen_height:window.screen.height,H_viewport_width:getScreenWidth(),H_viewport_height:getScreenHeight(),H_page_height:document.documentElement.scrollHeight||document.body.scrollHeight,H_browser:browserInfo.browserName,H_browser_version:browserInfo.browserVersion,H_os:browserInfo.os,H_os_version:browserInfo.osVersion,H_model:browserInfo.model,H_is_first_day:this.store.isFirstDay,H_url:window.location.href,H_url_host:getHostname(window.location.href,"url_host取值异常"),H_title:document.title}),this.store.hLatestUtm),this.generalProperties.H_latest_referrer&&(this.generalProperties.H_latest_referrer_host=getHostname(this.generalProperties.H_latest_referrer,"hostname解析异常")),this.generalProperties},HinaTrack.prototype.initPlugins=function(){var _this=this,_a=this.options,serverUrl=_a.serverUrl,name=_a.name,showLog=_a.showLog,sendType=_a.sendType,customHeaders=_a.customHeaders,credentials=_a.credentials,dataSendTimeout=_a.dataSendTimeout,batchSend=_a.batchSend,imgUseCrossOrigin=_a.imgUseCrossOrigin,globalCallback=_a.globalCallback,_b=_a.plugins,plugins=void 0===_b?[]:_b,performanceErrorConfig=_a.performanceErrorConfig,autoTrackConfig=_a.autoTrackConfig,siteLinkerConfig=_a.siteLinkerConfig,abTestingPluginConfig=_a.abTestingPluginConfig;plugins=plugins||[];var pageLeaveAutoTrack=autoTrackConfig.pageLeaveAutoTrack,clickCrackPlugin=new ClickTrackPlugin(this.options,this),stayTrackPlugin=new StayTrackPlugin(this.options,this),historyPlugin=new HistoryPlugin(this.options,this),hashPlugin=new HashPlugin(this.options,this),pageLeavePlugin=new PageLeavePlugin(this.options,this),siteLinkerPlugin=new SiteLinkerPlugin(this.options,this),abTestingPlugin=new AbTestingPlugin(this.options,this);pageLeavePlugin.disabled=!(isObject(pageLeaveAutoTrack)&&!isEmptyObject(pageLeaveAutoTrack));var linker=(siteLinkerConfig||{}).linker;siteLinkerPlugin.disabled=!(isArray(linker)&&linker.length>0),abTestingPlugin.disabled=!(isObject(abTestingPluginConfig)&&!isEmptyObject(abTestingPluginConfig)),this.plugins=[clickCrackPlugin,stayTrackPlugin,historyPlugin,hashPlugin,pageLeavePlugin,siteLinkerPlugin,abTestingPlugin],isArray(plugins)&&plugins.forEach((function(Plugin){if("Monitor"===Plugin.componentName){if(isObject(performanceErrorConfig)&&!isEmptyObject(performanceErrorConfig))new Plugin(__assign({serverUrl:serverUrl,name:name,showLog:showLog,sendType:sendType,customHeaders:customHeaders,credentials:credentials,dataSendTimeout:dataSendTimeout,batchSend:batchSend,imgUseCrossOrigin:imgUseCrossOrigin,globalCallback:globalCallback},performanceErrorConfig),!0)}else{var instance=new Plugin(_this.options,_this);_this.plugins.push(instance)}})),this.runPlugins(this.plugins)},HinaTrack.prototype.use=function(pluginName,options){if(this.isReady){if(isObject(options)){"PageLeave"===pluginName?this.options.autoTrackConfig.pageLeaveAutoTrack=options:"SiteLinker"===pluginName?this.options.siteLinkerConfig=options:"HinaABTest"===pluginName&&(this.options.abTestingPluginConfig=options);var instance=this.plugins.find((function(plugin){return plugin.name===pluginName}));return instance&&(instance.disabled=!1,instance.isReady?this.log("".concat(pluginName,"插件已运行,无需重复执行"),exports.ConsoleTypes.WARN):instance.init()),this.getPluginInstance(pluginName)}this.log("".concat(pluginName,"插件配置项必须是一个对象类型"),exports.ConsoleTypes.WARN)}else this.log("请先初始化埋点SDK",exports.ConsoleTypes.WARN)},HinaTrack.prototype.getPluginInstance=function(pluginName){return this.plugins.find((function(plugin){return plugin.name===pluginName}))},HinaTrack.prototype.setConfig=function(options){this.options=merge(this.options,options),this.normalizeConfig()},HinaTrack.prototype.getConfig=function(key){return key?this.options[key]:this.options},HinaTrack.prototype.setUserUId=function(uid,callback){var _this=this;!function(uid,accountId,callback){isNumber(uid=null!=uid?uid:"")||isString(uid)?accountId!==(uid=String(uid).trim())?callback(uid):log("setUserUId: uid is equal to account_id, failed to execute setUserUId",exports.ConsoleTypes.WARN):log("setUserUId: uid must be string or number",exports.ConsoleTypes.WARN)}(uid,this.store.getAccountId(),(function(id){_this.store.setAccountId(id);var props=_this.getReportData("track_signup","H_SignUp",{});_this.report(props,callback)}))},HinaTrack.prototype.cleanUserUId=function(){this.store.setAccountId("")},HinaTrack.prototype.getUserUid=function(){return this.store.state.accountId},HinaTrack.prototype.setDeviceUId=function(uid){this.store.setDeviceId(uid)},HinaTrack.prototype.getDeviceUId=function(){return this.store.getDeviceId()},HinaTrack.prototype.userSet=function(data,callback){if(isObject(data)&&!isEmptyObject(data)){var props=this.getReportData("user_set","",data);this.report(props,callback)}},HinaTrack.prototype.userSetOnce=function(data,callback){if(isObject(data)&&!isEmptyObject(data)){var props=this.getReportData("user_setOnce","",data);this.report(props,callback)}},HinaTrack.prototype.userAdd=function(data,callback){var _this=this;!function(data,callback){var _a;isString(data)&&((_a={})[data]=1,data=_a),isObject(data)&&!isEmptyObject(data)&&function(params){for(var key in params)if(!/-*\d+/.test(String(params[key])))return log("userAdd属性的值只能是数字",exports.ConsoleTypes.WARN),!1;return!0}(data)&&callback(data)}(data,(function(result){var props=_this.getReportData("user_add","",result);_this.report(props,callback)}))},HinaTrack.prototype.userAppend=function(data,callback){var _this=this;!function(data,callback){var result={};isObject(data)&&(Object.keys(data).forEach((function(key){var value=data[key];isArray(value)?result[key]=value:result[key]=[value]})),isEmptyObject(result)||callback(result))}(data,(function(result){var props=_this.getReportData("user_append","",result);_this.report(props,callback)}))},HinaTrack.prototype.userUnset=function(data,callback){var _this=this;!function(data,callback){var obj={};isString(data)&&(data=[data]),isArray(data)?(data.forEach((function(value){isString(value)?obj[value]=!0:log("userUnset参数数组里面的值必须是string,已经过滤掉".concat(value),exports.ConsoleTypes.WARN)})),isEmptyObject(obj)||callback(obj)):log("userUnset参数必须是数组或字符串",exports.ConsoleTypes.WARN)}(data,(function(result){var props=_this.getReportData("user_unset","",result);_this.report(props,callback)}))},HinaTrack.prototype.userDelete=function(callback){var props=this.getReportData("user_delete","",{});this.report(props,callback),this.store.setAccountId("")},HinaTrack.prototype.registerCommonProperties=function(params){this.customProperties=merge(this.customProperties,params)},HinaTrack.prototype.getPresetProperties=function(){return __assign(__assign({},this.getGeneralProperties()),this.customProperties)},HinaTrack.prototype.clearPageRegister=function(payload){var _this=this;void 0===payload&&(payload=!0),!0===payload?this.customProperties={}:isArray(payload)&&payload.forEach((function(key){key in _this.customProperties&&delete _this.customProperties[key]}))},HinaTrack.prototype.track=function(event,properties,callback){if(callback=callback||function(){},isString(event)){properties=isObject(properties)?properties:{};var props=this.getReportData("track",event,properties);this.report(props,callback)}else this.log("track事件名必须是字符串,属性必须是是一个对象",exports.ConsoleTypes.WARN)},HinaTrack.prototype.quick=function(name,data,callback){if(!this.isReady)return this.log("请先初始化SDK");var params={};callback=isFunction(callback)?callback:noop,isObject(data)?params=data:isFunction(data)&&(callback=data),this.autoTrack(params,callback)},HinaTrack.prototype.autoTrack=function(data,callback){void 0===data&&(data={}),void 0===callback&&(callback=noop);var referrer=(null==data?void 0:data.H_referrer)||getReferrer(),options=__assign(__assign(__assign({H_is_first_time:this.store.isFirstTime,H_url_path:window.location.pathname,H_referrer:referrer,H_referrer_host:referrer?getHostname(referrer):""},this.store.hUtm),this.store.customUtm),data||{}),props=this.getReportData("track","H_pageview",options);if(this.report(props,callback),this.store.isFirstTime){this.store.isFirstTime=!1;var referrer_1=getReferrer(),data_1=__assign(__assign({H_first_visit_time:nowStamp(),H_first_referrer:referrer_1,H_first_referrer_host:referrer_1?getHostname(referrer_1,"取值异常"):"",H_first_traffic_source_type:SearchKeyword.getSourceFromReferrer(),H_first_search_keyword:SearchKeyword.getKeywordFromReferrer(),H_first_browser_language:isString(navigator.language)?navigator.language.toLowerCase():"取值异常",H_first_browser_charset:document.characterSet||document.inputEncoding||"UTF-8"},this.store.hUtm),this.store.customUtm);this.userSetOnce(data_1)}},HinaTrack.prototype.report=function(data,callback,type){var _a,_b,_c=this.options,appJsBridge=_c.appJsBridge,serverUrl=_c.serverUrl;if(this.log(data),appJsBridge){var isError=!0,jsBridge=null===window||void 0===window?void 0:window.Hina_Cloud_H5_Bridge;if(isObject(jsBridge)&&jsBridge.track)isError=!1,jsBridge.track(data.event,data.type,JSON.stringify(data));else{var Tracker=null===(_b=null===(_a=null===window||void 0===window?void 0:window.webkit)||void 0===_a?void 0:_a.messageHandlers)||void 0===_b?void 0:_b.hinaNativeTracker;if(null==Tracker?void 0:Tracker.postMessage){isError=!1;var params=JSON.stringify({eventName:data.event,eventType:data.type,properties:data});Tracker.postMessage(params)}}if(isError)return void this.log("JSBridge 发送数据失败",exports.ConsoleTypes.WARN);isFunction(callback)&&callback(serverUrl,data)}else this.sendReportData(data,callback,type)},HinaTrack.prototype.getReportData=function(type,event,data){var properties,anonymous_id=this.store.getAnonymousId(),accountId=this.store.getAccountId(),time=nowStamp(),customProperties=merge(this.customProperties),generalProperties=this.getGeneralProperties();if("user"===type.slice(0,4)){var H_lib=generalProperties.H_lib,H_lib_method=generalProperties.H_lib_method,H_lib_version=generalProperties.H_lib_version;properties=__assign({device_id:this.store.getDeviceId(),H_lib:H_lib,H_lib_method:H_lib_method,H_lib_version:H_lib_version},data||{})}else properties=__assign(__assign(__assign({device_id:this.store.getDeviceId()},generalProperties),customProperties),data||{});checkReportProperties(properties,this.options.maxStringLength);var isLogin=accountId&&!/^[0-9a-f]{8,}-[0-9a-f]{4,}-[0-9a-f]{4,}-[0-9a-f]{4,}-[0-9a-f]{12,}$/.test(accountId),props={anonymous_id:anonymous_id,type:type,event:event,time:time,_track_id:generatorTrackId(),properties:__assign(__assign({},properties),{H_is_login_id:!!isLogin})};return isLogin&&(props.account_id=accountId),props.send_time=nowStamp(),props},HinaTrack}(WebClient);var hinaSdk=new HinaTrack({},!1);return exports.HinaTrack=HinaTrack,exports.PluginBase=PluginBase,exports.default=hinaSdk,Object.defineProperty(exports,"__esModule",{value:!0}),exports}({});
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { WebClient } from 'hina-cloud-js-core';
2
- import { FetchParams, ResponseData, PluginBase, ReportDataType, WebOptions, AbTestingOptions, IAnyObject, PluginConstructor, CommonGeneralProperties, HLatestUtmOptions, HUtmOptions, VoidFn, UnKnownFn, AnyFn, ReportTypes } from 'hina-cloud-type';
2
+ import { FetchParams, ResponseData, PluginBase, ReportDataType, PageLeaveAutoTrackObject, LinkerItem, SiteLinkerOptions, AbTestingOptions, WebOptions, IAnyObject, PluginConstructor, CommonGeneralProperties, HLatestUtmOptions, HUtmOptions, VoidFn, UnKnownFn, AnyFn, ReportTypes, ReportTypesName, ReportEventsName } from 'hina-cloud-type';
3
3
  export * from 'hina-cloud-type';
4
4
  import { AbtestBasePlugin, WebState } from 'hina-cloud-util';
5
5
  import { PerformanceOptions } from 'hina-cloud-js-monitor';
@@ -101,13 +101,40 @@ declare class SiteLinkerPlugin extends PluginBase<TrackOptions> {
101
101
  }
102
102
 
103
103
  /**
104
- * 上报数据事件
104
+ * 内置插件实例
105
105
  */
106
- type ReportEventsName = 'H_SignUp' | 'H_pageview' | 'H_WebClick' | 'H_WebStay' | 'H_WebPageLeave' | string;
106
+ interface BuiltPluginsInstanceMap {
107
+ /**
108
+ * 页面浏览时长插件
109
+ */
110
+ PageLeave: PageLeavePlugin;
111
+ /**
112
+ * 多域名打通插件
113
+ */
114
+ SiteLinker: SiteLinkerPlugin;
115
+ /**
116
+ * abTest插件
117
+ */
118
+ HinaABTest: AbTestingPlugin;
119
+ }
107
120
  /**
108
- * 上报数据类型
121
+ * 内置插件配置
109
122
  */
110
- type ReportTypesName = 'user_set' | 'user_unset' | 'user_delete' | 'user_set_once' | 'user_append' | 'user_add' | 'track_signup' | 'track' | string;
123
+ interface BuiltPluginsConfig {
124
+ /**
125
+ * 页面浏览时长插件
126
+ */
127
+ PageLeave: PageLeaveAutoTrackObject;
128
+ /**
129
+ * 多域名打通插件
130
+ */
131
+ SiteLinker?: SiteLinkerOptions;
132
+ /**
133
+ * abTest插件
134
+ */
135
+ HinaABTest?: AbTestingOptions;
136
+ }
137
+
111
138
  /**
112
139
  * 埋点配置
113
140
  */
@@ -249,53 +276,6 @@ interface PresetProperties {
249
276
  */
250
277
  latest_referrer?: boolean;
251
278
  }
252
- /**
253
- * PageLeavePlugin插件参数
254
- */
255
- interface PageLeaveAutoTrackObject {
256
- /**
257
- * 心跳记录刷新时间 单位秒(s) 默认值 5s
258
- */
259
- heartbeat_interval_time?: number;
260
- /**
261
- * 最大页面浏览时长 单位秒(s) 默认值 432000s (5天)
262
- */
263
- max_duration?: number;
264
- /**
265
- * 设置是否采集当前页面浏览时长, 返回 true 为需要采集,返回 false 或者不返回则为不采集
266
- */
267
- isCollectUrl?: (url?: string) => boolean;
268
- /**
269
- * 页面浏览时长自定义属性
270
- */
271
- custom_props?: {
272
- [key: string]: any;
273
- };
274
- }
275
- /**
276
- * SiteLinker插件参数
277
- */
278
- interface LinkerItem {
279
- /**
280
- * 配置值为打通网站网址的一部分。建议配置时配置为打通网站的域名。
281
- */
282
- part_url?: string;
283
- /**
284
- * 配置 _hnsdk 参数在 URL 的 hash 部分(即 # 后部分)还是在 URL 的 search 部分(即 # 前的 ?部分)。
285
- * 必填属性,且属性值必须为布尔类型,即 true 或 false(默认建议填 false)。
286
- */
287
- after_hash?: boolean;
288
- }
289
- interface SiteLinkerOptions {
290
- /**
291
- * 该配置设置为 true 后,如果从已登录的页面跳转过来,即使当前网页已经登录,当前网页仍然会以之前网页的登录 id 再次登录。
292
- */
293
- re_login?: boolean;
294
- /**
295
- * 具体网站链接配置项
296
- */
297
- linker?: LinkerItem[];
298
- }
299
279
  /**
300
280
  * 公共事件属性/预置属性
301
281
  */
@@ -501,41 +481,6 @@ interface WebPageLeaveOptions {
501
481
  */
502
482
  type ReportProperties = (PageViewOptions | WebClickOptions | WebStayOptions | WebPageLeaveOptions) & GeneralProperties & HUtmOptions;
503
483
 
504
- /**
505
- * 内置插件实例
506
- */
507
- interface BuiltPluginsInstanceMap {
508
- /**
509
- * 页面浏览时长插件
510
- */
511
- PageLeave: PageLeavePlugin;
512
- /**
513
- * 多域名打通插件
514
- */
515
- SiteLinker: SiteLinkerPlugin;
516
- /**
517
- * abTest插件
518
- */
519
- HinaABTest: AbTestingPlugin;
520
- }
521
- /**
522
- * 内置插件配置
523
- */
524
- interface BuiltPluginsConfig {
525
- /**
526
- * 页面浏览时长插件
527
- */
528
- PageLeave: PageLeaveAutoTrackObject;
529
- /**
530
- * 多域名打通插件
531
- */
532
- SiteLinker?: SiteLinkerOptions;
533
- /**
534
- * abTest插件
535
- */
536
- HinaABTest?: AbTestingOptions;
537
- }
538
-
539
484
  declare class HinaTrack extends WebClient<TrackOptions> {
540
485
  /**
541
486
  * 存储对象
@@ -719,4 +664,4 @@ type TrackInstance = InstanceType<typeof HinaTrack>;
719
664
 
720
665
  declare const hinaSdk: HinaTrack;
721
666
 
722
- export { type BuiltPluginsConfig, type BuiltPluginsInstanceMap, type GeneralProperties, HinaTrack, type LinkerItem, type PageLeaveAutoTrackObject, type PageViewOptions, type PresetProperties, type ReportEventsName, type ReportProperties, type ReportTypesName, type SiteLinkerOptions, type TrackInstance, type TrackOptions, type UserSetOnceOptions, type WebClickOptions, type WebPageLeaveOptions, type WebStayOptions, hinaSdk as default };
667
+ export { type BuiltPluginsConfig, type BuiltPluginsInstanceMap, type GeneralProperties, HinaTrack, type PageViewOptions, type PresetProperties, type ReportProperties, type TrackInstance, type TrackOptions, type UserSetOnceOptions, type WebClickOptions, type WebPageLeaveOptions, type WebStayOptions, hinaSdk as default };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "hina-cloud-js-sdk",
3
- "version": "4.0.3",
3
+ "version": "4.0.7",
4
4
  "description": "WEB埋点SDK",
5
5
  "main": "dist/hina.full.js",
6
6
  "module": "dist/hina.esm.js",
@@ -17,12 +17,12 @@
17
17
  "sideEffects": false,
18
18
  "license": "ISC",
19
19
  "dependencies": {
20
- "hina-cloud-js-core": "4.0.1",
21
- "hina-cloud-type": "2.0.1",
22
- "hina-cloud-util": "2.0.1"
20
+ "hina-cloud-js-core": "4.0.5",
21
+ "hina-cloud-type": "2.0.4",
22
+ "hina-cloud-util": "2.0.5"
23
23
  },
24
24
  "devDependencies": {
25
- "hina-cloud-js-monitor": "4.0.1"
25
+ "hina-cloud-js-monitor": "4.0.5"
26
26
  },
27
27
  "buildOptions": [
28
28
  {