-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathmoesif.min.js
90 lines (90 loc) · 44.5 KB
/
moesif.min.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
(function() {
(function(){var ka,la,ma,na,oa,pa,qa,I,J,K,L,M,N,V,W,X,Y,Z;function ra(a,b,d){p.log("processResponse for"+a._url);var f=(new Date).toISOString();if(d){var g=a._url?a._url.toLowerCase():a._url;if(g&&0>g.indexOf("moesif.com")&&0>g.indexOf("apirequest.io")){a:if((g=a._url)&&"string"===typeof g){var e=c.trim(g);if(0!==e.indexOf("http")){g=Ma+window.location.host+"/"+e.replace(/^\./,"").replace(/^\//,"");break a}}g={uri:g,verb:a._method,time:a._startTime,headers:a._requestHeaders};if(b)if("string"===typeof b)p.log("request post data is string"),
p.log(b),b=$(b),g.transfer_encoding=b.transfer_encoding,g.body=b.body;else if("object"===typeof b||Array.isArray(b)||"number"===typeof b||"boolean"===typeof b)g.body=b;e=a.getAllResponseHeaders();p.log("rawResponseHeaders are "+e);b={};if(e)for(var e=e.split("\r\n"),i=0;i<e.length;i++){var j=e[i],h=j.indexOf(": ");if(0<h){var l=j.substring(0,h);b[l]=j.substring(h+2)}}e=a.status;1223===e&&(e=204);f={status:e,time:f,headers:b};p.log("responseType: "+a.responseType);p.log("responseText: "+a.responseText);
p.log("response: "+a.response);b=a.responseText;e={};if(b)e=$(b),f.body=e.body,f.transfer_encoding=e.transfer_encoding;else if(a.response)if(p.log("no responseText trying with xhr.response"),c.isString(a.response))p.log("response is string. attempt to parse"),e=$(a.response),f.body=e.body,f.transfer_encoding=e.transfer_encoding;else if(c.isArrayBuffer(a.response))p.log("response is arraybuffer. attempt to parse"),e=sa(a.response),f.body=e.body,f.transfer_encoding=e.transfer_encoding;else if(c.isArray(a.response)||
c.isObject(a.response))f.body=a.response;d({request:g,response:f})}}}function Na(a,b){var d=XMLHttpRequest.prototype,f=b&&b.eagerBodyLogging,g=d.open,e=d.send,i=d.setRequestHeader;d.open=function(a,b){p.log("XHR open triggered");this._method=a;this._url=b;this._requestHeaders={};this._startTime=(new Date).toISOString();return g.apply(this,arguments)};d.setRequestHeader=function(a,b){this._requestHeaders[a]=b;return i.apply(this,arguments)};d.send=function(b){p.log("XHR send started for "+this._url);
var d=this;if(f||!this.addEventListener){var g=this.onreadystatechange;this.onreadystatechange=function(){var f=d.readyState;p.log("readyState "+f);f===XMLHttpRequest.DONE&&(p.log("XHR onreadystatechange DONE triggered for "+d._url),ra(d,b,a));if(g&&c.isFunction(g))return p.log("trigger old onreadystatechange"),g.apply(this,arguments)}}else this.addEventListener("loadend",function(){p.log("XHR loadend triggered for "+d._url);ra(d,b,a)});return e.apply(this,arguments)};return function(){d.open=g;d.send=
e;d.setRequestHeader=i}}function ta(a,b,d,f,g,e){b={uri:a&&a.host?a.host:"/",verb:"POST",time:b,headers:{}};if(a.headers){var i={};c.each(a.headers,function(a){i[a.name]=a.value});b.headers=i}if(f)if("string"===typeof f){t.log("request post data is string");t.log(f);try{b.body=c.JSONDecode(f)}catch(j){t.log("JSON decode failed"),t.log(j),b.transfer_encoding="base64",b.body=c.base64Encode(f)}}else if("object"===typeof f||Array.isArray(f)||"number"===typeof f||"boolean"===typeof postData)b.body=f;d=
{status:200,time:d,headers:{}};g?d.body=g:e&&(d.body={error:e});g={request:b,response:d,metadata:{_web3:{via_web3_provider:!0,path:a.path,host:a.host}}};a.isMetaMask&&(g.metadata._web3.is_metamask=!0);return g}function ua(a,b){if(a.currentProvider){t.log("found my currentProvider, patching it");var d=a.currentProvider,c=d.send,g=d.sendAsync;d.send=function(a){t.log("patched send is called");t.log(a);var g=(new Date).toISOString(),j=c.apply(d,arguments);t.log("patch send result is back");t.log(j);
var h=(new Date).toISOString();b&&b(ta(d,g,h,a,j));return j};d.sendAsync=function(a,c){t.log("patched sendAsync is called");t.log(a);var f=(new Date).toISOString();g.apply(d,[a,function(g,l){var m=(new Date).toISOString();t.log("inside patched callback");t.log(l);b&&b(ta(d,f,m,a,l,g));c&&c(g,l)}])};return function(){d.send=c;d.sendAsync=g}}return null}function va(a){var b={};s.log("parseheaders is called");for(var a=a.entries(),d=a.next();!d.done;)s.log(d.value),b[d.value[0]]=d.value[1],d=a.next();
return b}function Oa(a,b,d,c,g){try{setTimeout(function(){s.log("interception is here.");s.log(a);s.log(b);if(a&&b)try{Promise.all([a.arrayBuffer(),b.arrayBuffer()]).then(function(e){var h=e.map(sa),e=Object.assign(h[0],{uri:a.url,verb:a.method,time:d,headers:va(a.headers)}),h=Object.assign(h[1],{status:b.status,time:c,headers:va(b.headers)});s.log(e);s.log(h);g({request:e,response:h})})}catch(e){s.error("error processing body")}else s.log("savedRequest")},50)}catch(e){s.error("error processing saved fetch request and response, but move on anyways."),
s.log(e)}}function Pa(a,b,d,c){var g=null;try{g=new Request(d,c)}catch(e){}var i=(new Date).toISOString(),j=null,h=null,h=b(d,c),l=null;return h=h.then(function(b){l=b.clone();j=(new Date).toISOString();Oa(g,l,i,j,a);return b})}function Qa(a,b){var d=b||window||self;if(d.fetch){s.log("found fetch method.");if(d.fetch.polyfill)return s.log("skip patching fetch since it is polyfilled"),null;var c=d.fetch;s.log("fetch is not polyfilled so instrumenting it");d.fetch=function(b){return function(d,c){return Pa(a,
b,d,c)}}(d.fetch);return function(){d.fetch=c}}s.log("there is no fetch found, so skipping instrumentation.")}function Ra(a,b){var d=a?"?"+a.split(".").slice(-1)[0].replace(/\|/g,"&"):"";wa.log("cookie");wa.log(d);var f=c.getQueryParamByName(V,b)||c.getQueryParamByName("utmcsr",d),g=c.getQueryParamByName(W,b)||c.getQueryParamByName("utmcmd",d),e=c.getQueryParamByName(X,b)||c.getQueryParamByName("utmccn",d),i=c.getQueryParamByName(Y,b)||c.getQueryParamByName("utmctr",d),d=c.getQueryParamByName(Z,b)||
c.getQueryParamByName("utmcct",d),j={},h=function(a,b){c.isEmptyString(b)||(j[a]=b)};h(V,f);h(W,g);h(X,e);h(Y,i);h(Z,d);return j}function q(a,b){return!b?a:0===a.indexOf("moesif_")?a.replace("moesif_",b):a}function Sa(a){var b=a.persistence;if("cookie"!==b&&"localStorage"!==b)k.critical("Unknown persistence type "+b+"; falling back to cookie"),b=D.persistence="localStorage";var d=a.persistence_key_prefix,f=function(b,f){var i=q(b,d);c.localStorage.set(i,f);c.cookie.set(i,f,a.cookie_expiration,a.cross_subdomain_cookie,
a.secure_cookie,a.cross_site_cookie,a.cookie_domain)};if("cookie"===b||!c.localStorage.is_supported())f=function(b,f){var i=q(b,d);c.cookie.set(i,f,a.cookie_expiration,a.cross_subdomain_cookie,a.secure_cookie,a.cross_site_cookie,a.cookie_domain)};"none"===b&&(f=function(){});return f}function aa(a){return"null"===a||"undefined"===a||""===a?null:a}function O(a,b){var d=b&&b.persistence,f=q(a,b&&b.persistence_key_prefix);if(c.localStorage.is_supported()){var g=aa(c.localStorage.get(f)),e=aa(c.cookie.get(f));
!g&&e&&"localStorage"===d&&c.localStorage.set(f,e);return g||e}return aa(c.cookie.get(f))}function xa(a){a=a&&a.persistence_key_prefix;c.cookie.remove(q(I,a));c.cookie.remove(q(J,a));c.cookie.remove(q(K,a));c.cookie.remove(q(L,a));c.cookie.remove(q(M,a));c.cookie.remove(q(N,a))}function ya(a){a=a&&a.persistence_key_prefix;c.localStorage.remove(q(I,a));c.localStorage.remove(q(J,a));c.localStorage.remove(q(K,a));c.localStorage.remove(q(L,a));c.localStorage.remove(q(M,a));c.localStorage.remove(q(N,a))}
function Ta(a){try{var b={};if(!a.disableUtm)var d=void 0,f=void 0,d=c.getUrlParams(),f=c.cookie.get("__utmz"),b=Ra(f,d)||{};if(!a.disableReferer){var g;a:{var e=document&&document.referrer;za.log(e);if(!c.isEmptyString(e))if(0===e.indexOf(location.protocol+"//"+location.host))za.log("referrer is the same so skipping");else{var i;if(c.isEmptyString(e))i=null;else{var j=e.split("/");i=3<=j.length?j[2]:null}g={referrer:e,referring_domain:i};break a}g=void 0}if(g)b.referrer=g.referrer,b.referring_domain=
g.referring_domain}if(!a.disableRGclid){var h,l=c.getUrlParams(),m=c.getQueryParamByName("gclid",l);(h=c.isEmptyString(m)?void 0:m)&&(b.gclid=h)}return b}catch(Ua){E.log(Ua)}}function Aa(a,b,d){try{if(d&&!c.isEmptyObject(d)){var f=c.JSONEncode(d);a(b,f)}}catch(g){E.error("failed to decode campaign data"),E.error(g)}}function ba(a,b){try{var d=O(a,b);if(d&&"null"!==d){var f=c.JSONDecode(d);return f&&!c.isEmptyObject(f)?f:null}}catch(g){return E.error("failed to persist campaign data"),E.error(g),null}}
function Va(a,b,d){var c=M;!ba(c,b)&&a&&Aa(a,c,d);c=N;!ba(c,b)&&a&&Aa(a,c,d)}function Ba(a,b,d){if(b=ba(d,b))try{a(d,"")}catch(c){E.error("failed to clear campaign data")}return b}function ca(a){var b=c.UUID();a&&a(K,b);return b}function Wa(a,b){var d=O(K,b);return d?d:ca(a)}function Ca(a){try{return a.request.headers["X-Moesif-SDK"]}catch(b){return!1}}function Xa(a){if(!a)throw Error("options are required by moesif-browser-js middleware");if(!a.applicationId)throw Error("A moesif application id is required. Please obtain it through your settings at www.moesif.com");
if(a.getTags&&!c.isFunction(a.getTags))throw Error("getTags should be a function");if(a.getMetadata&&!c.isFunction(a.getMetadata))throw Error("getMetadata should be a function");if(a.getApiVersion&&!c.isFunction(a.getApiVersion))throw Error("identifyUser should be a function");if(a.maskContent&&!c.isFunction(a.maskContent))throw Error("maskContent should be a function");if(a.skip&&!c.isFunction(a.skip))throw Error("skip should be a function");}function Da(){k.log("moesif object creator is called");
return{init:function(a){window||k.critical("Warning, this library need to be initiated on the client side");Xa(a);var b={};b.getTags=a.getTags||da;b.maskContent=a.maskContent||function(a){return a};b.getMetadata=a.getMetadata||da;b.skip=a.skip||function(){return!1};b.debug=a.debug;b.callback=a.callback||da;b.applicationId=a.applicationId;b.apiVersion=a.apiVersion;b.disableFetch=a.disableFetch;b.disableReferrer=a.disableReferrer;b.disableGclid=a.disableGclid;b.disableUtm=a.disableUtm;b.eagerBodyLogging=
a.eagerBodyLogging;b.host=a.host||ka;b.batchEnabled=a.batchEnabled||!1;b.batch_size=a.batchSize||25;b.batch_flush_interval_ms=a.batchMaxTime||2500;b.batch_request_timeout_ms=a.batchTimeout||9E4;b.batch_storage_expiration=a.batchStorageExpiration;b.persistence=a.persistence||"localStorage";b.cross_site_cookie=a.crossSiteCookie||!1;b.cross_subdomain_cookie=!1===a.crossSubdomainCookie?!1:!0;b.cookie_expiration=a.cookieExpiration||365;b.secure_cookie=a.secureCookie||!1;b.cookie_domain=a.cookieDomain||
"";b.persistence_key_prefix=a.persistenceKeyPrefix;this.requestBatchers={};this._options=b;this._persist=Sa(b);try{if(this._userId=O(I,b),this._session=O(L,b),this._companyId=O(J,b),this._anonymousId=Wa(this._persist,b),(this._currentCampaign=Ta(b))&&Va(this._persist,b,this._currentCampaign),this._currentCampaign&&!this._userId)a={},a.anonymous_id=this._anonymousId,a.campaign=this._currentCampaign,this.updateUser(a,this._options.applicationId,this._options.host,this._options.callback)}catch(d){k.error("error loading saved data from local storage but continue")}if(b.batchEnabled)if(!P()||
!Ea)b.batchEnabled=!1,k.log("Turning off batch processing because it needs XHR and localStorage");else if(this.initBatching(),Fa&&window.addEventListener){var f=c.bind(function(){c.each(this.requestBatchers,function(a){a.stopped||a.flush({sendBeacon:!0})})},this);window.addEventListener("pagehide",function(){f()});window.addEventListener("visibilitychange",function(){"hidden"===document.visibilityState&&f()})}k.log("moesif initiated");return this},_executeRequest:function(a,b,d,c){var g=d&&d.applicationId||
this._options.applicationId,e=d&&d.method||"POST";try{var i=new XMLHttpRequest;i.open(e,a);i.setRequestHeader("Content-Type","application/json");i.setRequestHeader("X-Moesif-Application-Id",g);i.setRequestHeader("X-Moesif-SDK","moesif-browser-js/"+D.LIB_VERSION);if(d.timeout_ms&&"undefined"!==typeof i.timeout){i.timeout=d.timeout_ms;var j=(new Date).getTime()}i.onreadystatechange=function(){if(4===i.readyState)if(200<=i.status&&300>=i.status)c&&c(XMLHttpRequest.responseText);else{var a;a=i.timeout&&
!i.status&&(new Date).getTime()-j>=i.timeout?"timeout":"Bad HTTP status: "+i.status+" "+i.statusText;k.error(a);c&&c({status:0,error:a,xhr_req:i})}};i.send(B(b))}catch(h){k.error("failed to send to moesif "+(b&&b.request&&b.request.uri)),k.error(h),c&&c({status:0,error:h})}},initBatching:function(){var a=this._options.applicationId,b=this._options.host;k.log("does requestBatch.events exists? "+this.requestBatchers.events);if(!this.requestBatchers.events){var d={libConfig:this._options,sendRequestFunc:c.bind(function(a,
b,d,c){this._executeRequest(a,b,d,c)},this),stopAllBatching:c.bind(function(){this.stopAllBatching()},this)},f=Ga(a),a=new x("__mf_"+f+"_ev",F+b+la,d),b=new x("__mf_"+f+"_ac",F+b+ma,d);this.requestBatchers={events:a,actions:b}}c.each(this.requestBatchers,function(a){a.start()})},stopAllBatching:function(){this._options.batchEnabled=!1;c.each(this.requestBatchers,function(a){a.stop();a.clear()})},_sendOrBatch:function(a,b,d,f,g){var e=this,i=function(){return e._executeRequest(d,a,{applicationId:b},
g)};if(this._options.batchEnabled&&f){k.log("current batcher storage key is "+f.queue.storageKey);var j=c.bind(function(a){a||(k.log("enqueue failed, send immediately"),i())},this);f.enqueue(a,j)}else return i();return!0},start:function(a){function b(a){d.recordEvent(a)}var d=this;if(this._stopRecording||this._stopWeb3Recording)return k.log("recording has already started, please call stop first."),!1;k.log("moesif starting");this._stopRecording=Na(b,this._options);if(!this._options.disableFetch)k.log("also instrumenting fetch API"),
this._stopFetchRecording=Qa(b);this.useWeb3(a);return!0},useWeb3:function(a){function b(a){d.recordEvent(a)}var d=this;try{if(this._stopWeb3Recording)this._stopWeb3Recording(),this._stopWeb3Recording=null;if(a)this._stopWeb3Recording=ua(a,b,this._options);else if(window.web3)k.log("found global web3, will capture from it"),this._stopWeb3Recording=ua(window.web3,b,this._options);if(this._stopWeb3Recording)return!0}catch(c){k.log("error patching web3, moving forward anyways"),this._options.callback&&
this._options.callback({status:0,error:c,message:"failed to instrument web3, but moving forward with other instrumentation"})}return!1},updateUser:function(a,b,d,c){this._executeRequest(F+d+na,a,{applicationId:b},c)},identifyUser:function(a,b){if(c.isNil(a))k.critical("identifyUser called with nil userId");else{this._userId=a;if(!this._options||!this._options.applicationId)throw Error("Init needs to be called with a valid application Id before calling identify User.");var d={user_id:a};b&&(d.metadata=
b);if(this._session)d.session_token=this._session;var f=Ba(this._persist,this._options,M)||this._currentCampaign;f&&(d.campaign=f);if(this._companyId)d.company_id=this._companyId;d.anonymous_id=this._anonymousId;this.updateUser(d,this._options.applicationId,this._options.host,this._options.callback);try{a&&this._persist(I,a)}catch(g){k.error("error saving to local storage")}}},updateCompany:function(a,b,d,c){this._executeRequest(F+d+oa,a,{applicationId:b},c)},identifyCompany:function(a,b,d){if(c.isNil(a))k.critical("identifyCompany called with nil companyId.");
else{this._companyId=a;if(!this._options||!this._options.applicationId)throw Error("Init needs to be called with a valid application Id before calling identify User.");var f={company_id:a};d&&(f.company_domain=d);b&&(f.metadata=b);if(this._session)f.session_token=this._session;(b=Ba(this._persist,this._options,N)||this._currentCampaign)&&(f.campaign=b);this.updateCompany(f,this._options.applicationId,this._options.host,this._options.callback);try{a&&this._persist(J,a)}catch(g){k.error("error saving to local storage")}}},
identifySession:function(a){if(c.isNil(a))k.critical("identifySession called with nil");else if(this._session=a)try{this._persist(L,a)}catch(b){k.error("local storage error")}},track:function(a,b){if(!a)throw Error("track name must have action Name defined");var d={action_name:a};if(this._companyId)d.company_id=this._companyId;this._userId?d.user_id=this._userId:d.anonymous_id=this._anonymousId;if(this._session)d.session_token=this._session;d.request={uri:document.location.href,verb:"GET",user_agent_string:navigator.userAgent};
d.transaction_id=c.uuid4();b&&(d.metadata=b);var f=F+this._options.host+pa;k.log("sending or queuing: "+a);return this._sendOrBatch(d,this._options.applicationId,f,this.requestBatchers.actions,this._options.callback)},recordEvent:function(a){if(Ca(a))k.log("skipped logging for requests to moesif");else{k.log("determining if should log: "+a.request.uri);var b=Object.assign({},a);this._getUserId()?b.user_id=this._getUserId():b.anonymous_id=this._anonymousId;this._getCompanyId()&&(b.company_id=this._getCompanyId());
this._getSession()&&(b.session_token=this._getSession());b.tags=this._options.getTags(a)||"";if(this._options.apiVersion)b.request.api_version=this._options.apiVersion;if(!b.request.headers["User-Agent"])b.request.headers["User-Agent"]=window.navigator.userAgent;b.transaction_id=c.uuid4();this._options.maskContent&&(b=this._options.maskContent(b));if(this._options.getMetadata)if(b.metadata){var d=this._options.getMetadata(b);b.metadata=Object.assign(b.metadata,d)}else b.metadata=this._options.getMetadata(b);
!this._options.skip(a)&&!Ca(a)?(k.log("sending or queuing: "+a.request.uri),this._sendOrBatch(b,this._options.applicationId,F+this._options.host+qa,this.requestBatchers.events,this._options.callback)):k.log("skipped logging for "+a.request.uri)}},_getUserId:function(){return this._userId},_getCompanyId:function(){return this._companyId},_getSession:function(){return this._session},stop:function(){if(this._stopRecording)this._stopRecording(),this._stopRecording=null;if(this._stopWeb3Recording)this._stopWeb3Recording(),
this._stopWeb3Recording=null;if(this._stopFetchRecording)this._stopFetchRecording(),this._stopFetchRecording=null},clearCookies:function(){xa(this._options)},clearStorage:function(){ya(this._options)},resetAnonymousId:function(){return this._anonymousId=ca(this._persist)},reset:function(){xa(this._options);ya(this._options);this._anonymousId=ca(this._persist);this._currentCampaign=this._session=this._userId=this._companyId=null}}}var D={DEBUG:!1,LIB_VERSION:"1.8.13"},z;if("undefined"===typeof window){var y=
{hostname:""};z={navigator:{userAgent:""},document:{location:y,referrer:""},screen:{width:0,height:0},location:y}}else z=window;var y=Array.prototype,u=Object.prototype,G=y.slice,Q=u.toString,S=u.hasOwnProperty,r=z.console,H=z.navigator,v=z.document,R=z.opera,T=z.screen,n=H.userAgent,ea=Function.prototype.bind,Ha=y.forEach,Ia=y.indexOf,Ja=y.map,y=Array.isArray,fa={},c={trim:function(a){return a.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")}},k={log:function(){if(D.DEBUG&&!c.isUndefined(r)&&r)try{r.log.apply(r,
arguments)}catch(a){c.each(arguments,function(a){r.log(a)})}},error:function(){if(D.DEBUG&&!c.isUndefined(r)&&r){var a=["Moesif error:"].concat(c.toArray(arguments));try{r.error.apply(r,a)}catch(b){c.each(a,function(a){r.error(a)})}}},critical:function(){if(!c.isUndefined(r)&&r){var a=["Moesif error:"].concat(c.toArray(arguments));try{r.error.apply(r,a)}catch(b){c.each(a,function(a){r.error(a)})}}}},ga=function(a,b){return function(){arguments[0]="["+b+"] "+arguments[0];return a.apply(k,arguments)}},
u=function(a){return{log:ga(k.log,a),error:ga(k.error,a),critical:ga(k.critical,a)}};c.bind=function(a,b){var d,f;if(ea&&a.bind===ea)return ea.apply(a,G.call(arguments,1));if(!c.isFunction(a))throw new TypeError;d=G.call(arguments,2);return f=function(){if(!(this instanceof f))return a.apply(b,d.concat(G.call(arguments)));var c={};c.prototype=a.prototype;var e=new c;c.prototype=null;c=a.apply(e,d.concat(G.call(arguments)));return Object(c)===c?c:e}};c.bind_instance_methods=function(a){for(var b in a)"function"===
typeof a[b]&&(a[b]=c.bind(a[b],a))};c.each=function(a,b,d){if(!(null===a||void 0===a))if(Ha&&a.forEach===Ha)a.forEach(b,d);else if(a.length===+a.length)for(var c=0,g=a.length;c<g&&!(c in a&&b.call(d,a[c],c,a)===fa);c++);else for(c in a)if(S.call(a,c)&&b.call(d,a[c],c,a)===fa)break};c.escapeHTML=function(a){a&&c.isString(a)&&(a=a.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"));return a};c.extend=function(a){c.each(G.call(arguments,1),function(b){for(var d in b)void 0!==
b[d]&&(a[d]=b[d])});return a};c.isArray=y||function(a){return"[object Array]"===Q.call(a)};c.isFunction=function(a){try{return/^\s*\bfunction\b/.test(a)}catch(b){return!1}};c.isArguments=function(a){return!(!a||!S.call(a,"callee"))};c.toArray=function(a){return!a?[]:a.toArray?a.toArray():c.isArray(a)||c.isArguments(a)?G.call(a):c.values(a)};c.map=function(a,b){if(Ja&&a.map===Ja)return a.map(b);var d=[];c.each(a,function(a){d.push(b(a))});return d};c.keys=function(a){var b=[];if(null===a)return b;
c.each(a,function(a,c){b[b.length]=c});return b};c.values=function(a){var b=[];if(null===a)return b;c.each(a,function(a){b[b.length]=a});return b};c.identity=function(a){return a};c.include=function(a,b){var d=!1;if(null===a)return d;if(Ia&&a.indexOf===Ia)return-1!=a.indexOf(b);c.each(a,function(a){if(d||(d=a===b))return fa});return d};c.includes=function(a,b){return-1!==a.indexOf(b)};c.inherit=function(a,b){a.prototype=new b;a.prototype.constructor=a;a.superclass=b.prototype;return a};c.isArrayBuffer=
function(a){var b=Object.prototype.toString;return"function"===typeof ArrayBuffer&&(a instanceof ArrayBuffer||"[object ArrayBuffer]"===b.call(a))};c.isObject=function(a){return a===Object(a)&&!c.isArray(a)};c.isEmptyObject=function(a){if(c.isObject(a)){for(var b in a)if(S.call(a,b))return!1;return!0}return!1};c.isEmptyString=function(a){return!a||0===a.length};c.isUndefined=function(a){return void 0===a};c.isString=function(a){return"[object String]"==Q.call(a)};c.isDate=function(a){return"[object Date]"==
Q.call(a)};c.isNumber=function(a){return"[object Number]"==Q.call(a)};c.isElement=function(a){return!!(a&&1===a.nodeType)};c.isNil=function(a){return c.isUndefined(a)||null===a};c.encodeDates=function(a){c.each(a,function(b,d){c.isDate(b)?a[d]=c.formatDate(b):c.isObject(b)&&(a[d]=c.encodeDates(b))});return a};c.timestamp=function(){Date.now=Date.now||function(){return+new Date};return Date.now()};c.formatDate=function(a){function b(a){return 10>a?"0"+a:a}return a.getUTCFullYear()+"-"+b(a.getUTCMonth()+
1)+"-"+b(a.getUTCDate())+"T"+b(a.getUTCHours())+":"+b(a.getUTCMinutes())+":"+b(a.getUTCSeconds())};c.safewrap=function(a){return function(){try{return a.apply(this,arguments)}catch(b){k.critical("Implementation error. Please turn on debug and contact [email protected]."),D.DEBUG&&k.critical(b)}}};c.safewrap_class=function(a,b){for(var d=0;d<b.length;d++)a.prototype[b[d]]=c.safewrap(a.prototype[b[d]])};c.safewrap_instance_methods=function(a){for(var b in a)"function"===typeof a[b]&&(a[b]=c.safewrap(a[b]))};
c.strip_empty_properties=function(a){var b={};c.each(a,function(a,f){c.isString(a)&&0<a.length&&(b[f]=a)});return b};c.truncate=function(a,b){var d;"string"===typeof a?d=a.slice(0,b):c.isArray(a)?(d=[],c.each(a,function(a){d.push(c.truncate(a,b))})):c.isObject(a)?(d={},c.each(a,function(a,g){d[g]=c.truncate(a,b)})):d=a;return d};c.JSONEncode=function(){return function(a){var b=function(a){var b=/[\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
c={"\u0008":"\\b","\t":"\\t","\n":"\\n","\u000c":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"};b.lastIndex=0;return b.test(a)?'"'+a.replace(b,function(a){var b=c[a];return"string"===typeof b?b:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+a+'"'},c=function(a,g){var e="",i=0,j=i="",j=0,h=e,l=[],m=g[a];m&&"object"===typeof m&&"function"===typeof m.toJSON&&(m=m.toJSON(a));switch(typeof m){case "string":return b(m);case "number":return isFinite(m)?""+m:"null";case "boolean":case "null":return""+
m;case "object":if(!m)return"null";e+=" ";l=[];if("[object Array]"===Q.apply(m)){j=m.length;for(i=0;i<j;i+=1)l[i]=c(i,m)||"null";return j=0===l.length?"[]":e?"[\n"+e+l.join(",\n"+e)+"\n"+h+"]":"["+l.join(",")+"]"}for(i in m)S.call(m,i)&&(j=c(i,m))&&l.push(b(i)+(e?": ":":")+j);return j=0===l.length?"{}":e?"{"+l.join(",")+""+h+"}":"{"+l.join(",")+"}"}};return c("",{"":a})}}();c.JSONDecode=function(){var a,b,c={'"':'"',"\\":"\\","/":"/",b:"\u0008",f:"\u000c",n:"\n",r:"\r",t:"\t"},f,g=function(b){b=
new SyntaxError(b);b.at=a;b.text=f;throw b;},e=function(c){c&&c!==b&&g("Expected '"+c+"' instead of '"+b+"'");b=f.charAt(a);a+=1;return b},i=function(){var a;a="";"-"===b&&(a="-",e("-"));for(;"0"<=b&&"9">=b;)a+=b,e();if("."===b)for(a+=".";e()&&"0"<=b&&"9">=b;)a+=b;if("e"===b||"E"===b){a+=b;e();if("-"===b||"+"===b)a+=b,e();for(;"0"<=b&&"9">=b;)a+=b,e()}a=+a;if(isFinite(a))return a;g("Bad number")},j=function(){var a,f,h="",i;if('"'===b)for(;e();){if('"'===b)return e(),h;if("\\"===b)if(e(),"u"===b){for(f=
i=0;4>f;f+=1){a=parseInt(e(),16);if(!isFinite(a))break;i=16*i+a}h+=String.fromCharCode(i)}else if("string"===typeof c[b])h+=c[b];else break;else h+=b}g("Bad string")},h=function(){for(;b&&" ">=b;)e()},l=function(){switch(b){case "t":return e("t"),e("r"),e("u"),e("e"),!0;case "f":return e("f"),e("a"),e("l"),e("s"),e("e"),!1;case "n":return e("n"),e("u"),e("l"),e("l"),null}g('Unexpected "'+b+'"')},m;m=function(){h();switch(b){case "{":var a;a:{var c,d={};if("{"===b){e("{");h();if("}"===b){e("}");a=
d;break a}for(;b;){c=j();h();e(":");Object.hasOwnProperty.call(d,c)&&g('Duplicate key "'+c+'"');d[c]=m();h();if("}"===b){e("}");a=d;break a}e(",");h()}}g("Bad object")}return a;case "[":a:{a=[];if("["===b){e("[");h();if("]"===b){e("]");c=a;break a}for(;b;){a.push(m());h();if("]"===b){e("]");c=a;break a}e(",");h()}}g("Bad array")}return c;case '"':return j();case "-":return i();default:return"0"<=b&&"9">=b?i():l()}};return function(c){f=c;a=0;b=" ";c=m();h();b&&g("Syntax error");return c}}();c.base64Encode=
function(a){var b,d,f,g,e=0,i=0,j="",j=[];if(!a)return a;a=c.utf8Encode(a);do b=a.charCodeAt(e++),d=a.charCodeAt(e++),f=a.charCodeAt(e++),g=b<<16|d<<8|f,b=g>>18&63,d=g>>12&63,f=g>>6&63,g&=63,j[i++]="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(b)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(d)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(f)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".charAt(g);
while(e<a.length);j=j.join("");switch(a.length%3){case 1:j=j.slice(0,-2)+"==";break;case 2:j=j.slice(0,-1)+"="}return j};c.utf8Encode=function(a){var a=(a+"").replace(/\r\n/g,"\n").replace(/\r/g,"\n"),b="",c,f,g=0,e;c=f=0;g=a.length;for(e=0;e<g;e++){var i=a.charCodeAt(e),j=null;128>i?f++:j=127<i&&2048>i?String.fromCharCode(i>>6|192,i&63|128):String.fromCharCode(i>>12|224,i>>6&63|128,i&63|128);null!==j&&(f>c&&(b+=a.substring(c,f)),b+=j,c=f=e+1)}f>c&&(b+=a.substring(c,a.length));return b};c.UUID=function(){var a=
function(){function a(b,c){var d,e=0;for(d=0;d<c.length;d++)e|=g[d]<<8*d;return b^e}var c,f,g=[],e=0;for(c=0;c<n.length;c++)f=n.charCodeAt(c),g.unshift(f&255),4<=g.length&&(e=a(e,g),g=[]);0<g.length&&(e=a(e,g));return e.toString(16)};return function(){for(var b=(T.height*T.width).toString(16),c=1*new Date,f=0;c==1*new Date;)f++;return c.toString(16)+f.toString(16)+"-"+Math.random().toString(16).replace(".","")+"-"+a()+"-"+b}}();c.uuid4=function(){var a=URL.createObjectURL(new Blob),b=a.toString();
URL.revokeObjectURL(a);return b.split(/[:\/]/g).pop().toLowerCase()};c.isBlockedUA=function(a){return/(google web preview|baiduspider|yandexbot|bingbot|googlebot|yahoo! slurp)/i.test(a)?!0:!1};c.HTTPBuildQuery=function(a,b){var d,f,g=[];c.isUndefined(b)&&(b="&");c.each(a,function(a,b){d=encodeURIComponent(a.toString());f=encodeURIComponent(b);g[g.length]=f+"="+d});return g.join(b)};c.getUrlParams=function(){var a;if(a=location)if(!(a=location.search))a:{if(a=location.href){var b=a.indexOf("?");if(0<=
b){a=a.substring(b);break a}}a=""}return a};c.getQueryParamByName=function(a,b){var a=a.replace(/[\[]/,"\\[").replace(/[\]]/,"\\]"),c=RegExp("[\\?&]"+a+"=([^&#]*)").exec(b);return null===c?void 0:decodeURIComponent(c[1].replace(/\+/g," "))};c.getQueryParam=function(a,b){var b=b.replace(/[[]/,"\\[").replace(/[\]]/,"\\]"),c=RegExp("[\\?&]"+b+"=([^&#]*)").exec(a);if(null===c||c&&"string"!==typeof c[1]&&c[1].length)return"";c=c[1];try{c=decodeURIComponent(c)}catch(f){k.error("Skipping decoding for malformed query param: "+
c)}return c.replace(/\+/g," ")};c.getHashParam=function(a,b){var c=a.match(RegExp(b+"=([^&]*)"));return c?c[1]:null};c.cookie={get:function(a){for(var a=a+"=",b=v.cookie.split(";"),c=0;c<b.length;c++){for(var f=b[c];" "==f.charAt(0);)f=f.substring(1,f.length);if(0===f.indexOf(a))return decodeURIComponent(f.substring(a.length,f.length))}return null},parse:function(a){var b;try{b=c.JSONDecode(c.cookie.get(a))||{}}catch(d){}return b},set_seconds:function(a,b,c,f,g,e,i){var j="",h="",l="";i?j="; domain="+
i:f&&(j=(j=Ka(v.location.hostname))?"; domain=."+j:"");c&&(h=new Date,h.setTime(h.getTime()+1E3*c),h="; expires="+h.toGMTString());e&&(g=!0,l="; SameSite=None");g&&(l+="; secure");v.cookie=a+"="+encodeURIComponent(b)+h+"; path=/"+j+l},set:function(a,b,c,f,g,e,i){var j="",h="",l="";i?j="; domain="+i:f&&(j=(j=Ka(v.location.hostname))?"; domain=."+j:"");c&&(h=new Date,h.setTime(h.getTime()+864E5*c),h="; expires="+h.toGMTString());e&&(g=!0,l="; SameSite=None");g&&(l+="; secure");a=a+"="+encodeURIComponent(b)+
h+"; path=/"+j+l;return v.cookie=a},remove:function(a,b,d){c.cookie.set(a,"",-1,b,!1,!1,d)}};var ha=null,P=function(a,b){if(null!==ha&&!b)return ha;var c=!0;try{var a=a||window.localStorage,f="__mplss_"+ia(8);a.setItem(f,"xyz");"xyz"!==a.getItem(f)&&(c=!1);a.removeItem(f)}catch(g){c=!1}return ha=c};c.localStorage={is_supported:function(a){(a=P(null,a))||k.error("localStorage unsupported; falling back to cookie store");return a},error:function(a){k.error("localStorage error: "+a)},get:function(a){try{return window.localStorage.getItem(a)}catch(b){c.localStorage.error(b)}return null},
parse:function(a){try{return c.JSONDecode(c.localStorage.get(a))||{}}catch(b){}return null},set:function(a,b){try{window.localStorage.setItem(a,b)}catch(d){c.localStorage.error(d)}},remove:function(a){try{window.localStorage.removeItem(a)}catch(b){c.localStorage.error(b)}}};c.register_event=function(){function a(a,f,g){return function(e){if(e=e||b(window.event)){var i=!0,j;c.isFunction(g)&&(j=g(e));e=f.call(a,e);if(!1===j||!1===e)i=!1;return i}}}function b(a){if(a)a.preventDefault=b.preventDefault,
a.stopPropagation=b.stopPropagation;return a}b.preventDefault=function(){this.returnValue=!1};b.stopPropagation=function(){this.cancelBubble=!0};return function(b,c,g,e,i){b?b.addEventListener&&!e?b.addEventListener(c,g,!!i):(c="on"+c,b[c]=a(b,g,b[c])):k.error("No valid element provided to register_event")}}();var Ya=/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/;c.dom_query=function(){function a(a,b){var c;return 0<=(" "+a.className+" ").replace(d," ").indexOf(" "+b+" ")}function b(b){if(!v.getElementsByTagName)return[];
var b=b.split(" "),d,e,i,j,h,l,m,k=[v];for(j=0;j<b.length;j++)if(d=b[j].replace(/^\s+/,"").replace(/\s+$/,""),-1<d.indexOf("#")){e=d.split("#");d=e[0];k=v.getElementById(e[1]);if(!k||d&&k.nodeName.toLowerCase()!=d)return[];k=[k]}else if(-1<d.indexOf(".")){e=d.split(".");d=e[0];var n=e[1];d||(d="*");e=[];for(h=i=0;h<k.length;h++){m="*"==d?k[h].all?k[h].all:k[h].getElementsByTagName("*"):k[h].getElementsByTagName(d);for(l=0;l<m.length;l++)e[i++]=m[l]}k=[];for(h=d=0;h<e.length;h++)e[h].className&&c.isString(e[h].className)&&
a(e[h],n)&&(k[d++]=e[h])}else if(e=d.match(Ya)){d=e[1];var o=e[2],n=e[3],p=e[4];d||(d="*");e=[];for(h=i=0;h<k.length;h++){m="*"==d?k[h].all?k[h].all:k[h].getElementsByTagName("*"):k[h].getElementsByTagName(d);for(l=0;l<m.length;l++)e[i++]=m[l]}k=[];d=0;switch(n){case "=":n=function(a){return a.getAttribute(o)==p};break;case "~":n=function(a){return a.getAttribute(o).match(RegExp("\\b"+p+"\\b"))};break;case "|":n=function(a){return a.getAttribute(o).match(RegExp("^"+p+"-?"))};break;case "^":n=function(a){return 0===
a.getAttribute(o).indexOf(p)};break;case "$":n=function(a){return a.getAttribute(o).lastIndexOf(p)==a.getAttribute(o).length-p.length};break;case "*":n=function(a){return-1<a.getAttribute(o).indexOf(p)};break;default:n=function(a){return a.getAttribute(o)}}k=[];for(h=d=0;h<e.length;h++)n(e[h])&&(k[d++]=e[h])}else{e=[];for(h=i=0;h<k.length;h++){m=k[h].getElementsByTagName(d);for(l=0;l<m.length;l++)e[i++]=m[l]}k=e}return k}var d=/[\t\r\n]/g;return function(a){return c.isElement(a)?[a]:c.isObject(a)&&
!c.isUndefined(a.length)?a:b.call(this,a)}}();c.info={campaignParams:function(){var a="utm_source utm_medium utm_campaign utm_content utm_term".split(" "),b="",d={};c.each(a,function(a){b=c.getQueryParam(v.URL,a);b.length&&(d[a]=b)});return d},searchEngine:function(a){return 0===a.search("https?://(.*)google.([^/?]*)")?"google":0===a.search("https?://(.*)bing.com")?"bing":0===a.search("https?://(.*)yahoo.com")?"yahoo":0===a.search("https?://(.*)duckduckgo.com")?"duckduckgo":null},searchInfo:function(a){var b=
c.info.searchEngine(a),d;d={};if(null!==b)d.$search_engine=b,a=c.getQueryParam(a,"yahoo"!=b?"q":"p"),a.length&&(d.mp_keyword=a);return d},browser:function(a,b,d){b=b||"";return d||c.includes(a," OPR/")?c.includes(a,"Mini")?"Opera Mini":"Opera":/(BlackBerry|PlayBook|BB10)/i.test(a)?"BlackBerry":c.includes(a,"IEMobile")||c.includes(a,"WPDesktop")?"Internet Explorer Mobile":c.includes(a,"SamsungBrowser/")?"Samsung Internet":c.includes(a,"Edge")||c.includes(a,"Edg/")?"Microsoft Edge":c.includes(a,"FBIOS")?
"Facebook Mobile":c.includes(a,"Chrome")?"Chrome":c.includes(a,"CriOS")?"Chrome iOS":c.includes(a,"UCWEB")||c.includes(a,"UCBrowser")?"UC Browser":c.includes(a,"FxiOS")?"Firefox iOS":c.includes(b,"Apple")?c.includes(a,"Mobile")?"Mobile Safari":"Safari":c.includes(a,"Android")?"Android Mobile":c.includes(a,"Konqueror")?"Konqueror":c.includes(a,"Firefox")?"Firefox":c.includes(a,"MSIE")||c.includes(a,"Trident/")?"Internet Explorer":c.includes(a,"Gecko")?"Mozilla":""},browserVersion:function(a,b,d){b=
{"Internet Explorer Mobile":/rv:(\d+(\.\d+)?)/,"Microsoft Edge":/Edge?\/(\d+(\.\d+)?)/,Chrome:/Chrome\/(\d+(\.\d+)?)/,"Chrome iOS":/CriOS\/(\d+(\.\d+)?)/,"UC Browser":/(UCBrowser|UCWEB)\/(\d+(\.\d+)?)/,Safari:/Version\/(\d+(\.\d+)?)/,"Mobile Safari":/Version\/(\d+(\.\d+)?)/,Opera:/(Opera|OPR)\/(\d+(\.\d+)?)/,Firefox:/Firefox\/(\d+(\.\d+)?)/,"Firefox iOS":/FxiOS\/(\d+(\.\d+)?)/,Konqueror:/Konqueror:(\d+(\.\d+)?)/,BlackBerry:/BlackBerry (\d+(\.\d+)?)/,"Android Mobile":/android\s(\d+(\.\d+)?)/,"Samsung Internet":/SamsungBrowser\/(\d+(\.\d+)?)/,
"Internet Explorer":/(rv:|MSIE )(\d+(\.\d+)?)/,Mozilla:/rv:(\d+(\.\d+)?)/}[c.info.browser(a,b,d)];if(void 0===b)return null;a=a.match(b);return!a?null:parseFloat(a[a.length-2])},os:function(){return/Windows/i.test(n)?/Phone/.test(n)||/WPDesktop/.test(n)?"Windows Phone":"Windows":/(iPhone|iPad|iPod)/.test(n)?"iOS":/Android/.test(n)?"Android":/(BlackBerry|PlayBook|BB10)/i.test(n)?"BlackBerry":/Mac/i.test(n)?"Mac OS X":/Linux/.test(n)?"Linux":/CrOS/.test(n)?"Chrome OS":""},device:function(a){return/Windows Phone/i.test(a)||
/WPDesktop/.test(a)?"Windows Phone":/iPad/.test(a)?"iPad":/iPod/.test(a)?"iPod Touch":/iPhone/.test(a)?"iPhone":/(BlackBerry|PlayBook|BB10)/i.test(a)?"BlackBerry":/Android/.test(a)?"Android":""},referringDomain:function(a){a=a.split("/");return 3<=a.length?a[2]:""},properties:function(){return c.extend(c.strip_empty_properties({$os:c.info.os(),$browser:c.info.browser(n,H.vendor,R),$referrer:v.referrer,$referring_domain:c.info.referringDomain(v.referrer),$device:c.info.device(n)}),{$current_url:z.location.href,
$browser_version:c.info.browserVersion(n,H.vendor,R),$screen_height:T.height,$screen_width:T.width,mp_lib:"web",$lib_version:D.LIB_VERSION,$insert_id:ia(),time:c.timestamp()/1E3})},people_properties:function(){return c.extend(c.strip_empty_properties({$os:c.info.os(),$browser:c.info.browser(n,H.vendor,R)}),{$browser_version:c.info.browserVersion(n,H.vendor,R)})},pageviewInfo:function(a){return c.strip_empty_properties({mp_page:a,mp_referrer:v.referrer,mp_browser:c.info.browser(n,H.vendor,R),mp_platform:c.info.os()})}};
var ia=function(a){var b=Math.random().toString(36).substring(2,10)+Math.random().toString(36).substring(2,10);return a?b.substring(0,a):b},Ga=function(a){var b=5381;if(0==a.length)return b;for(var c=0;c<a.length;c++)b=(b<<5)-b+a.charCodeAt(c),b&=b;return b};c.safewrap(function(a,b,c){return(Ga(a+b)>>>0)%100<c});var Za=/[a-z0-9][a-z0-9-]*\.[a-z]+$/i,$a=/[a-z0-9][a-z0-9-]+\.[a-z.]{2,6}$/i,Ka=function(a){var b=$a,c=a.split("."),c=c[c.length-1];if(4<c.length||"com"===c||"org"===c)b=Za;return(a=a.match(b))?
a[0]:""},B=null,U=null;if("undefined"!==typeof JSON)B=JSON.stringify,U=JSON.parse;B=B||c.JSONEncode;U=U||c.JSONDecode;c.toArray=c.toArray;c.isObject=c.isObject;c.JSONEncode=c.JSONEncode;c.JSONDecode=c.JSONDecode;c.isBlockedUA=c.isBlockedUA;c.isEmptyObject=c.isEmptyObject;c.isEmptyString=c.isEmptyString;c.info=c.info;c.info.device=c.info.device;c.info.browser=c.info.browser;c.info.browserVersion=c.info.browserVersion;c.info.properties=c.info.properties;var A=u("parsers"),$=function(a){try{return{body:c.JSONDecode(a)}}catch(b){return A.log("JSON decode failed"),
A.log(b),{transfer_encoding:"base64",body:c.base64Encode(a)}}},sa=function(a){if(!a)return{};A.log("about to decode buffer");A.log(a);A.log(a.byteLength);if(0>=a.byteLength)return{};try{var b=(new TextDecoder("utf-8")).decode(a);try{return{body:c.JSONDecode(b)}}catch(d){return A.error(d),{transfer_encoding:"base64",body:c.base64Encode(b)}}}catch(f){return A.error(f),A.log(a),{transfer_encoding:"base64",body:"can not be decoded"}}},p=u("capture"),Ma="http:"===(document&&document.location.protocol)?
"http://":"https://",t=u("web3capture"),s=u("capture fetch"),za=u("referrer"),wa=u("utm");V="utm_source";W="utm_medium";X="utm_campaign";Y="utm_term";Z="utm_content";I="moesif_stored_user_id";J="moesif_stored_company_id";L="moesif_stored_session_id";K="moesif_anonymous_id";M="moesif_campaign_data";N="moesif_campaign_company";var E=u("campaign"),ab=u("lock"),La=function(a,b){b=b||{};this.storageKey=a;this.storage=b.storage||window.localStorage;this.pollIntervalMS=b.pollIntervalMS||100;this.timeoutMS=
b.timeoutMS||2E3};La.prototype.withLock=function(a,b,c){!c&&"function"!==typeof b&&(c=b,b=null);var f=c||(new Date).getTime()+"|"+Math.random(),g=(new Date).getTime(),e=this.storageKey,i=this.pollIntervalMS,j=this.timeoutMS,h=this.storage,k=e+":X",m=e+":Y",n=e+":Z",o=function(a){(new Date).getTime()-g>j?(ab.error("Timeout waiting for mutex on "+e+"; clearing lock. ["+f+"]"),h.removeItem(n),h.removeItem(m),q()):setTimeout(function(){try{a()}catch(c){b&&b(c)}},i*(Math.random()+0.1))},p=function(a,b){a()?
b():o(function(){p(a,b)})},s=function(){var a=h.getItem(m);if(a&&a!==f)return!1;h.setItem(m,f);if(h.getItem(m)===f)return!0;if(!P(h,!0))throw Error("localStorage support dropped while acquiring lock");return!1},q=function(){h.setItem(k,f);p(s,function(){h.getItem(k)===f?r():o(function(){h.getItem(m)!==f?q():p(function(){return!h.getItem(n)},r)})})},r=function(){h.setItem(n,"1");try{a()}finally{h.removeItem(n),h.getItem(m)===f&&h.removeItem(m),h.getItem(k)===f&&h.removeItem(k)}};try{if(P(h,!0))q();
else throw Error("localStorage support check failed");}catch(t){b&&b(t)}};var o=u("batch"),C=function(a,b){b=b||{};this.storageKey=a;this.storage=b.storage||window.localStorage;this.lock=new La(a,{storage:this.storage});this.storageExpiration=b.storageExpiration||216E5;this.pid=b.pid||null;this.memQueue=[]};C.prototype.enqueue=function(a,b,d){var f={id:ia(),flushAfter:(new Date).getTime()+2*b,payload:a};this.lock.withLock(c.bind(function(){var b;try{var c=this.readFromStorage();c.push(f);if(b=this.saveToStorage(c))o.log("succeeded saving to storage"),
this.memQueue.push(f)}catch(i){o.error("Error enqueueing item",a),b=!1}d&&d(b)},this),function(a){o.error("Error acquiring storage lock",a);d&&d(!1)},this.pid)};C.prototype.fillBatch=function(a){this.memQueue=ja(this.memQueue,{},this.storageExpiration);var b=this.memQueue.slice(0,a);if(b.length<a){var d=this.readFromStorage();o.log("current storedQueue size "+d.length);if(d.length){var f={};c.each(b,function(a){f[a.id]=!0});for(var g=0;g<d.length;g++){var e=d[g],i=(new Date).getTime(),j=i-this.storageExpiration;
if(i>e.flushAfter&&e.flushAfter>=j&&!f[e.id]){if(b.push(e),b.length>=a)break}else o.log("fill batch filtered item because invalid or expired"+B(e))}}}return b};var ja=function(a,b,d){var f=[],g=(new Date).getTime()-d;o.log("expiration time is "+g);c.each(a,function(a){a.id&&!b[a.id]?a.flushAfter&&a.flushAfter>=g&&f.push(a):o.log("filtered out item because invalid or expired"+B(a))});return f};C.prototype.removeItemsByID=function(a,b){var d={};c.each(a,function(a){d[a]=!0});this.memQueue=ja(this.memQueue,
d,this.storageExpiration);var f=c.bind(function(){var b;try{var c=this.readFromStorage(),c=ja(c,d,this.storageExpiration);b=this.saveToStorage(c)}catch(f){o.error("Error removing items",a),b=!1}return b},this);this.lock.withLock(c.bind(function(){var a=f();b&&(o.log("triggering callback of removalItems"),b(a))},this),c.bind(function(a){var c=!1;o.error("Error acquiring storage lock",a);if(!P(this.storage,!0)&&(c=f(),!c)){o.error("still can not remove from storage, thus stop using storage");try{this.storage.removeItem(this.storageKey)}catch(d){o.error("error clearing queue",
d)}}b&&b(c)},this),this.pid)};C.prototype.readFromStorage=function(){var a;try{o.log("trying to get storage with storage key "+this.storageKey),(a=this.storage.getItem(this.storageKey))?(a=U(a),c.isArray(a)||(o.error("Invalid storage entry:",a),a=null)):o.log("storageEntry is empty")}catch(b){o.error("Error retrieving queue",b),a=null}return a||[]};C.prototype.saveToStorage=function(a){try{return this.storage.setItem(this.storageKey,B(a)),!0}catch(b){return o.error("Error saving queue",b),!1}};C.prototype.clear=
function(){this.memQueue=[];try{this.storage.removeItem(this.storageKey)}catch(a){o.error("Failed to clear storage",a)}};var w=u("batch"),x=function(a,b,c){this.queue=new C(a,{storage:c.storage,storageExpiration:c.libConfig.batch_storage_expiration});this.endpoint=b;this.libConfig=c.libConfig;this.sendRequest=c.sendRequestFunc;this.batchSize=this.libConfig.batch_size;this.flushInterval=this.libConfig.batch_flush_interval_ms;this.stopAllBatching=c.stopAllBatching;this.stopped=!1;this.removalFailures=
0};x.prototype.enqueue=function(a,b){this.queue.enqueue(a,this.flushInterval,b)};x.prototype.start=function(){this.stopped=!1;this.removalFailures=0;this.flush()};x.prototype.stop=function(){this.stopped=!0;if(this.timeoutID)clearTimeout(this.timeoutID),this.timeoutID=null};x.prototype.clear=function(){this.queue.clear()};x.prototype.resetBatchSize=function(){this.batchSize=this.libConfig.batch_size};x.prototype.resetFlush=function(){this.scheduleFlush(this.libConfig.batch_flush_interval_ms)};x.prototype.scheduleFlush=
function(a){this.flushInterval=a;if(!this.stopped)this.timeoutID=setTimeout(c.bind(this.flush,this),this.flushInterval)};x.prototype.flush=function(a){try{if(this.requestInProgress)w.log("Flush: Request already in progress");else{var a=a||{},b=this.batchSize,d=this.queue.fillBatch(b);w.log("current batch size is "+d.length);if(1>d.length)this.resetFlush();else{this.requestInProgress=!0;var f=this.libConfig.batch_request_timeout_ms,g=(new Date).getTime(),e=c.map(d,function(a){return a.payload}),i=
c.bind(function(a){this.requestInProgress=!1;try{var e=!1;if(c.isObject(a)&&"timeout"===a.error&&(new Date).getTime()-g>=f)w.error("Network timeout; retrying"),this.flush();else if(c.isObject(a)&&a.xhr_req&&(500<=a.xhr_req.status||0>=a.xhr_req.status)){var h=2*this.flushInterval,i=a.xhr_req.responseHeaders;if(i){var j=i["Retry-After"];j&&(h=1E3*parseInt(j,10)||h)}h=Math.min(6E5,h);w.error("Error; retry in "+h+" ms");this.scheduleFlush(h)}else if(c.isObject(a)&&a.xhr_req&&413===a.xhr_req.status)if(1<
d.length){var k=Math.max(1,Math.floor(b/2));this.batchSize=Math.min(this.batchSize,k,d.length-1);w.error("413 response; reducing batch size to "+this.batchSize);this.resetFlush()}else w.error("Single-event request too large; dropping",d),this.resetBatchSize(),e=!0;else e=!0;e&&this.queue.removeItemsByID(c.map(d,function(a){return a.id}),c.bind(function(a){a?(this.removalFailures=0,this.flush()):(this.removalFailures+=1,w.error("failed to remove items from batched queue "+this.removalFailures+" times."),
5<this.removalFailures?(w.error("stop batching because too m any errors remove from storage"),this.stopAllBatching()):this.resetFlush())},this))}catch(n){w.error("Error handling API response",n),this.resetFlush()}},this),j={method:"POST",verbose:!0,ignore_json_errors:!0,timeout_ms:f};if(a.sendBeacon)j.transport="sendBeacon";w.log("Moesif Request:",this.endpoint,e);this.sendRequest(this.endpoint,e,j,i)}}}catch(h){w.error("Error flushing request queue",h),this.resetFlush()}};ka="api.moesif.net";qa=
"/v1/events";la="/v1/events/batch";pa="/v1/actions";ma="/v1/actions/batch";na="/v1/users";oa="/v1/companies";var Ea=window.XMLHttpRequest&&"withCredentials"in new XMLHttpRequest;!Ea&&-1===n.indexOf("MSIE")&&n.indexOf("Mozilla");var da=function(){},Fa=null;navigator.sendBeacon&&(Fa=function(){return navigator.sendBeacon.apply(navigator,arguments)});var F="http:"===(document&&document.location.protocol)?"http://":"https://";window.moesif=Da();window.moesif["new"]=Da})();
})();