-
Notifications
You must be signed in to change notification settings - Fork 14
/
webSDK.min.js
2 lines (2 loc) · 249 KB
/
webSDK.min.js
1
2
/*! For license information please see sdk.js.LICENSE.txt */
(()=>{var e={483:(e,t,n)=>{e.exports=function e(t,n,i){function a(o,s){if(!n[o]){if(!t[o]){if(r)return r(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}l=n[o]={exports:{}},t[o][0].call(l.exports,(function(e){return a(t[o][1][e]||e)}),l,l.exports,e,t,n,i)}return n[o].exports}for(var r=void 0,o=0;o<i.length;o++)a(i[o]);return a}({1:[function(e,t,i){(function(e){"use strict";var n,i,a,r,o=e.MutationObserver||e.WebKitMutationObserver,s=o?(n=0,o=new o(c),i=e.document.createTextNode(""),o.observe(i,{characterData:!0}),function(){i.data=n=++n%2}):e.setImmediate||void 0===e.MessageChannel?"document"in e&&"onreadystatechange"in e.document.createElement("script")?function(){var t=e.document.createElement("script");t.onreadystatechange=function(){c(),t.onreadystatechange=null,t.parentNode.removeChild(t),t=null},e.document.documentElement.appendChild(t)}:function(){setTimeout(c,0)}:((a=new e.MessageChannel).port1.onmessage=c,function(){a.port2.postMessage(0)}),l=[];function c(){var e,t;r=!0;for(var n=l.length;n;){for(t=l,l=[],e=-1;++e<n;)t[e]();n=l.length}r=!1}t.exports=function(e){1!==l.push(e)||r||s()}}).call(this,void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],2:[function(e,t,n){"use strict";var i=e(1);function a(){}var r={},o=["REJECTED"],s=["FULFILLED"],l=["PENDING"];function c(e){if("function"!=typeof e)throw new TypeError("resolver must be a function");this.state=l,this.queue=[],this.outcome=void 0,e!==a&&p(this,e)}function d(e,t,n){this.promise=e,"function"==typeof t&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),"function"==typeof n&&(this.onRejected=n,this.callRejected=this.otherCallRejected)}function g(e,t,n){i((function(){var i;try{i=t(n)}catch(i){return r.reject(e,i)}i===e?r.reject(e,new TypeError("Cannot resolve promise with itself")):r.resolve(e,i)}))}function u(e){var t=e&&e.then;if(e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof t)return function(){t.apply(e,arguments)}}function p(e,t){var n=!1;function i(t){n||(n=!0,r.reject(e,t))}function a(t){n||(n=!0,r.resolve(e,t))}var o=h((function(){t(a,i)}));"error"===o.status&&i(o.value)}function h(e,t){var n={};try{n.value=e(t),n.status="success"}catch(e){n.status="error",n.value=e}return n}(t.exports=c).prototype.catch=function(e){return this.then(null,e)},c.prototype.then=function(e,t){if("function"!=typeof e&&this.state===s||"function"!=typeof t&&this.state===o)return this;var n=new this.constructor(a);return this.state!==l?g(n,this.state===s?e:t,this.outcome):this.queue.push(new d(n,e,t)),n},d.prototype.callFulfilled=function(e){r.resolve(this.promise,e)},d.prototype.otherCallFulfilled=function(e){g(this.promise,this.onFulfilled,e)},d.prototype.callRejected=function(e){r.reject(this.promise,e)},d.prototype.otherCallRejected=function(e){g(this.promise,this.onRejected,e)},r.resolve=function(e,t){var n=h(u,t);if("error"===n.status)return r.reject(e,n.value);if(n=n.value)p(e,n);else{e.state=s,e.outcome=t;for(var i=-1,a=e.queue.length;++i<a;)e.queue[i].callFulfilled(t)}return e},r.reject=function(e,t){e.state=o,e.outcome=t;for(var n=-1,i=e.queue.length;++n<i;)e.queue[n].callRejected(t);return e},c.resolve=function(e){return e instanceof this?e:r.resolve(new this(a),e)},c.reject=function(e){var t=new this(a);return r.reject(t,e)},c.all=function(e){var t=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var n=e.length,i=!1;if(!n)return this.resolve([]);for(var o=new Array(n),s=0,l=-1,c=new this(a);++l<n;)!function(e,a){t.resolve(e).then((function(e){o[a]=e,++s!==n||i||(i=!0,r.resolve(c,o))}),(function(e){i||(i=!0,r.reject(c,e))}))}(e[l],l);return c},c.race=function(e){var t=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var n=e.length,i=!1;if(!n)return this.resolve([]);for(var o=-1,s=new this(a);++o<n;)!function(e){t.resolve(e).then((function(e){i||(i=!0,r.resolve(s,e))}),(function(e){i||(i=!0,r.reject(s,e))}))}(e[o]);return s}},{1:1}],3:[function(e,t,i){(function(t){"use strict";"function"!=typeof t.Promise&&(t.Promise=e(2))}).call(this,void 0!==n.g?n.g:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{2:2}],4:[function(e,t,n){"use strict";var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},a=function(){try{if("undefined"!=typeof indexedDB)return indexedDB;if("undefined"!=typeof webkitIndexedDB)return webkitIndexedDB;if("undefined"!=typeof mozIndexedDB)return mozIndexedDB;if("undefined"!=typeof OIndexedDB)return OIndexedDB;if("undefined"!=typeof msIndexedDB)return msIndexedDB}catch(e){return}}();function r(e,t){e=e||[],t=t||{};try{return new Blob(e,t)}catch(a){if("TypeError"!==a.name)throw a;for(var n=new("undefined"!=typeof BlobBuilder?BlobBuilder:"undefined"!=typeof MSBlobBuilder?MSBlobBuilder:"undefined"!=typeof MozBlobBuilder?MozBlobBuilder:WebKitBlobBuilder),i=0;i<e.length;i+=1)n.append(e[i]);return n.getBlob(t.type)}}"undefined"==typeof Promise&&e(3);var o=Promise;function s(e,t){t&&e.then((function(e){t(null,e)}),(function(e){t(e)}))}function l(e,t,n){"function"==typeof t&&e.then(t),"function"==typeof n&&e.catch(n)}function c(e){return"string"!=typeof e&&(console.warn(e+" used as a key, but it is not a string."),e=String(e)),e}function d(){if(arguments.length&&"function"==typeof arguments[arguments.length-1])return arguments[arguments.length-1]}var g="local-forage-detect-blob-support",u=void 0,p={},h=Object.prototype.toString,m="readonly",f="readwrite";function v(e){return"boolean"==typeof u?o.resolve(u):(t=e,new o((function(e){var n=t.transaction(g,f),i=r([""]);n.objectStore(g).put(i,"key"),n.onabort=function(t){t.preventDefault(),t.stopPropagation(),e(!1)},n.oncomplete=function(){var t=navigator.userAgent.match(/Chrome\/(\d+)/),n=navigator.userAgent.match(/Edge\//);e(n||!t||43<=parseInt(t[1],10))}})).catch((function(){return!1})).then((function(e){return u=e})));var t}function S(e){e=p[e.name];var t={};t.promise=new o((function(e,n){t.resolve=e,t.reject=n})),e.deferredOperations.push(t),e.dbReady?e.dbReady=e.dbReady.then((function(){return t.promise})):e.dbReady=t.promise}function E(e){return(e=p[e.name].deferredOperations.pop())&&(e.resolve(),e.promise)}function y(e,t){if(e=p[e.name].deferredOperations.pop())return e.reject(t),e.promise}function b(e,t){return new o((function(n,i){if(p[e.name]=p[e.name]||{forages:[],db:null,dbReady:null,deferredOperations:[]},e.db){if(!t)return n(e.db);S(e),e.db.close()}var r=[e.name];t&&r.push(e.version);var o=a.open.apply(a,r);t&&(o.onupgradeneeded=function(t){var n=o.result;try{n.createObjectStore(e.storeName),t.oldVersion<=1&&n.createObjectStore(g)}catch(n){if("ConstraintError"!==n.name)throw n;console.warn('The database "'+e.name+'" has been upgraded from version '+t.oldVersion+" to version "+t.newVersion+', but the storage "'+e.storeName+'" already exists.')}}),o.onerror=function(e){e.preventDefault(),i(o.error)},o.onsuccess=function(){n(o.result),E(e)}}))}function _(e){return b(e,!1)}function T(e){return b(e,!0)}function I(e,t){if(!e.db)return 1;var n=!e.db.objectStoreNames.contains(e.storeName),i=e.version<e.db.version,a=e.version>e.db.version;return i&&(e.version!==t&&console.warn('The database "'+e.name+"\" can't be downgraded from version "+e.db.version+" to version "+e.version+"."),e.version=e.db.version),(a||n)&&(!n||(n=e.db.version+1)>e.version&&(e.version=n),1)}function A(e){return r([function(e){for(var t=e.length,n=new ArrayBuffer(t),i=new Uint8Array(n),a=0;a<t;a++)i[a]=e.charCodeAt(a);return n}(atob(e.data))],{type:e.type})}function w(e){return e&&e.__local_forage_encoded_blob}function D(e){var t=this,n=t._initReady().then((function(){var e=p[t._dbInfo.name];if(e&&e.dbReady)return e.dbReady}));return l(n,e,e),n}function C(e,t,n,i){void 0===i&&(i=1);try{var a=e.db.transaction(e.storeName,t);n(null,a)}catch(a){if(0<i&&(!e.db||"InvalidStateError"===a.name||"NotFoundError"===a.name))return o.resolve().then((function(){if(!e.db||"NotFoundError"===a.name&&!e.db.objectStoreNames.contains(e.storeName)&&e.version<=e.db.version)return e.db&&(e.version=e.db.version+1),T(e)})).then((function(){return function(e){S(e);for(var t=p[e.name],n=t.forages,i=0;i<n.length;i++){var a=n[i];a._dbInfo.db&&(a._dbInfo.db.close(),a._dbInfo.db=null)}return e.db=null,_(e).then((function(t){return e.db=t,I(e)?T(e):t})).then((function(i){e.db=t.db=i;for(var a=0;a<n.length;a++)n[a]._dbInfo.db=i})).catch((function(t){throw y(e,t),t}))}(e).then((function(){C(e,t,n,i-1)}))})).catch(n);n(a)}}var O={_driver:"asyncStorage",_initStorage:function(e){var t=this,n={db:null};if(e)for(var i in e)n[i]=e[i];var a=p[n.name];a||(a={forages:[],db:null,dbReady:null,deferredOperations:[]},p[n.name]=a),a.forages.push(t),t._initReady||(t._initReady=t.ready,t.ready=D);var r=[];function s(){return o.resolve()}for(var l=0;l<a.forages.length;l++){var c=a.forages[l];c!==t&&r.push(c._initReady().catch(s))}var d=a.forages.slice(0);return o.all(r).then((function(){return n.db=a.db,_(n)})).then((function(e){return n.db=e,I(n,t._defaultConfig.version)?T(n):e})).then((function(e){n.db=a.db=e,t._dbInfo=n;for(var i=0;i<d.length;i++){var r=d[i];r!==t&&(r._dbInfo.db=n.db,r._dbInfo.version=n.version)}}))},_support:function(){try{if(!a)return!1;var e="undefined"!=typeof openDatabase&&/(Safari|iPhone|iPad|iPod)/.test(navigator.userAgent)&&!/Chrome/.test(navigator.userAgent)&&!/BlackBerry/.test(navigator.platform),t="function"==typeof fetch&&-1!==fetch.toString().indexOf("[native code");return(!e||t)&&"undefined"!=typeof indexedDB&&"undefined"!=typeof IDBKeyRange}catch(e){return!1}}(),iterate:function(e,t){var n=this,i=new o((function(t,i){n.ready().then((function(){C(n._dbInfo,m,(function(a,r){if(a)return i(a);try{var o=r.objectStore(n._dbInfo.storeName).openCursor(),s=1;o.onsuccess=function(){var n,i=o.result;i?(w(n=i.value)&&(n=A(n)),void 0!==(n=e(n,i.key,s++))?t(n):i.continue()):t()},o.onerror=function(){i(o.error)}}catch(a){i(a)}}))})).catch(i)}));return s(i,t),i},getItem:function(e,t){var n=this;e=c(e);var i=new o((function(t,i){n.ready().then((function(){C(n._dbInfo,m,(function(a,r){if(a)return i(a);try{var o=r.objectStore(n._dbInfo.storeName).get(e);o.onsuccess=function(){var e=o.result;w(e=void 0===e?null:e)&&(e=A(e)),t(e)},o.onerror=function(){i(o.error)}}catch(a){i(a)}}))})).catch(i)}));return s(i,t),i},setItem:function(e,t,n){var i=this;e=c(e);var a=new o((function(n,a){var r;i.ready().then((function(){return r=i._dbInfo,"[object Blob]"===h.call(t)?v(r.db).then((function(e){return e?t:(n=t,new o((function(e,t){var i=new FileReader;i.onerror=t,i.onloadend=function(t){t=btoa(t.target.result||""),e({__local_forage_encoded_blob:!0,data:t,type:n.type})},i.readAsBinaryString(n)})));var n})):t})).then((function(t){C(i._dbInfo,f,(function(r,o){if(r)return a(r);try{var s=o.objectStore(i._dbInfo.storeName);null===t&&(t=void 0);var l=s.put(t,e);o.oncomplete=function(){n(t=void 0===t?null:t)},o.onabort=o.onerror=function(){var e=l.error||l.transaction.error;a(e)}}catch(r){a(r)}}))})).catch(a)}));return s(a,n),a},removeItem:function(e,t){var n=this;e=c(e);var i=new o((function(t,i){n.ready().then((function(){C(n._dbInfo,f,(function(a,r){if(a)return i(a);try{var o=r.objectStore(n._dbInfo.storeName).delete(e);r.oncomplete=function(){t()},r.onerror=function(){i(o.error)},r.onabort=function(){var e=o.error||o.transaction.error;i(e)}}catch(a){i(a)}}))})).catch(i)}));return s(i,t),i},clear:function(e){var t=this,n=new o((function(e,n){t.ready().then((function(){C(t._dbInfo,f,(function(i,a){if(i)return n(i);try{var r=a.objectStore(t._dbInfo.storeName).clear();a.oncomplete=function(){e()},a.onabort=a.onerror=function(){var e=r.error||r.transaction.error;n(e)}}catch(i){n(i)}}))})).catch(n)}));return s(n,e),n},length:function(e){var t=this,n=new o((function(e,n){t.ready().then((function(){C(t._dbInfo,m,(function(i,a){if(i)return n(i);try{var r=a.objectStore(t._dbInfo.storeName).count();r.onsuccess=function(){e(r.result)},r.onerror=function(){n(r.error)}}catch(i){n(i)}}))})).catch(n)}));return s(n,e),n},key:function(e,t){var n=this,i=new o((function(t,i){e<0?t(null):n.ready().then((function(){C(n._dbInfo,m,(function(a,r){if(a)return i(a);try{var o=r.objectStore(n._dbInfo.storeName),s=!1,l=o.openCursor();l.onsuccess=function(){var n=l.result;n?0===e||s?t(n.key):(s=!0,n.advance(e)):t(null)},l.onerror=function(){i(l.error)}}catch(a){i(a)}}))})).catch(i)}));return s(i,t),i},keys:function(e){var t=this,n=new o((function(e,n){t.ready().then((function(){C(t._dbInfo,m,(function(i,a){if(i)return n(i);try{var r=a.objectStore(t._dbInfo.storeName).openCursor(),o=[];r.onsuccess=function(){var t=r.result;t?(o.push(t.key),t.continue()):e(o)},r.onerror=function(){n(r.error)}}catch(i){n(i)}}))})).catch(n)}));return s(n,e),n},dropInstance:function(e,t){t=d.apply(this,arguments);var n,i=this.config();return(e="function"!=typeof e&&e||{}).name||(e.name=e.name||i.name,e.storeName=e.storeName||i.storeName),s(n=e.name?(n=e.name===i.name&&this._dbInfo.db?o.resolve(this._dbInfo.db):_(e).then((function(t){var n=p[e.name],i=n.forages;n.db=t;for(var a=0;a<i.length;a++)i[a]._dbInfo.db=t;return t})),e.storeName?n.then((function(t){if(t.objectStoreNames.contains(e.storeName)){var n=t.version+1;S(e);var i=p[e.name],r=i.forages;t.close();for(var s=0;s<r.length;s++){var l=r[s];l._dbInfo.db=null,l._dbInfo.version=n}return new o((function(t,i){var r=a.open(e.name,n);r.onerror=function(e){r.result.close(),i(e)},r.onupgradeneeded=function(){r.result.deleteObjectStore(e.storeName)},r.onsuccess=function(){var e=r.result;e.close(),t(e)}})).then((function(e){i.db=e;for(var t=0;t<r.length;t++){var n=r[t];n._dbInfo.db=e,E(n._dbInfo)}})).catch((function(t){throw(y(e,t)||o.resolve()).catch((function(){})),t}))}})):n.then((function(t){S(e);var n=p[e.name],i=n.forages;t.close();for(var r=0;r<i.length;r++)i[r]._dbInfo.db=null;return new o((function(t,n){var i=a.deleteDatabase(e.name);i.onerror=i.onblocked=function(e){var t=i.result;t&&t.close(),n(e)},i.onsuccess=function(){var e=i.result;e&&e.close(),t(e)}})).then((function(e){n.db=e;for(var t=0;t<i.length;t++)E(i[t]._dbInfo)})).catch((function(t){throw(y(e,t)||o.resolve()).catch((function(){})),t}))}))):o.reject("Invalid arguments"),t),n}},P="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",R=/^~~local_forage_type~([^~]+)~/,L="__lfsc__:",N=L.length,k="arbf",M="blob",x=N+k.length,B=Object.prototype.toString;function W(e){var t,n,i,a,r=.75*e.length,o=e.length,s=0;"="===e[e.length-1]&&(r--,"="===e[e.length-2]&&r--),r=new ArrayBuffer(r);for(var l=new Uint8Array(r),c=0;c<o;c+=4)t=P.indexOf(e[c]),n=P.indexOf(e[c+1]),i=P.indexOf(e[c+2]),a=P.indexOf(e[c+3]),l[s++]=t<<2|n>>4,l[s++]=(15&n)<<4|i>>2,l[s++]=(3&i)<<6|63&a;return r}function U(e){for(var t=new Uint8Array(e),n="",i=0;i<t.length;i+=3)n+=P[t[i]>>2],n+=P[(3&t[i])<<4|t[i+1]>>4],n+=P[(15&t[i+1])<<2|t[i+2]>>6],n+=P[63&t[i+2]];return t.length%3==2?n=n.substring(0,n.length-1)+"=":t.length%3==1&&(n=n.substring(0,n.length-2)+"=="),n}var F={serialize:function(e,t){var n="";if(e&&(n=B.call(e)),e&&("[object ArrayBuffer]"===n||e.buffer&&"[object ArrayBuffer]"===B.call(e.buffer))){var i,a=L;e instanceof ArrayBuffer?(i=e,a+=k):(i=e.buffer,"[object Int8Array]"===n?a+="si08":"[object Uint8Array]"===n?a+="ui08":"[object Uint8ClampedArray]"===n?a+="uic8":"[object Int16Array]"===n?a+="si16":"[object Uint16Array]"===n?a+="ur16":"[object Int32Array]"===n?a+="si32":"[object Uint32Array]"===n?a+="ui32":"[object Float32Array]"===n?a+="fl32":"[object Float64Array]"===n?a+="fl64":t(new Error("Failed to get type for BinaryArray"))),t(a+U(i))}else if("[object Blob]"===n)(n=new FileReader).onload=function(){var n="~~local_forage_type~"+e.type+"~"+U(this.result);t(L+M+n)},n.readAsArrayBuffer(e);else try{t(JSON.stringify(e))}catch(n){console.error("Couldn't convert value into a JSON string: ",e),t(null,n)}},deserialize:function(e){if(e.substring(0,N)!==L)return JSON.parse(e);var t,n=e.substring(x),i=e.substring(N,x);i===M&&R.test(n)&&(t=(e=n.match(R))[1],n=n.substring(e[0].length));var a=W(n);switch(i){case k:return a;case M:return r([a],{type:t});case"si08":return new Int8Array(a);case"ui08":return new Uint8Array(a);case"uic8":return new Uint8ClampedArray(a);case"si16":return new Int16Array(a);case"ur16":return new Uint16Array(a);case"si32":return new Int32Array(a);case"ui32":return new Uint32Array(a);case"fl32":return new Float32Array(a);case"fl64":return new Float64Array(a);default:throw new Error("Unkown type: "+i)}},stringToBuffer:W,bufferToString:U};function H(e,t,n,i){e.executeSql("CREATE TABLE IF NOT EXISTS "+t.storeName+" (id INTEGER PRIMARY KEY, key unique, value)",[],n,i)}function G(e,t,n,i,a,r){e.executeSql(n,i,a,(function(e,o){o.code===o.SYNTAX_ERR?e.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name = ?",[t.storeName],(function(e,s){s.rows.length?r(e,o):H(e,t,(function(){e.executeSql(n,i,a,r)}),r)}),r):r(e,o)}),r)}function K(e,t,n,i){var a=this;e=c(e);var r=new o((function(r,o){a.ready().then((function(){var s=t=void 0===t?null:t,l=a._dbInfo;l.serializer.serialize(t,(function(t,c){c?o(c):l.db.transaction((function(n){G(n,l,"INSERT OR REPLACE INTO "+l.storeName+" (key, value) VALUES (?, ?)",[e,t],(function(){r(s)}),(function(e,t){o(t)}))}),(function(t){t.code===t.QUOTA_ERR&&(0<i?r(K.apply(a,[e,s,n,i-1])):o(t))}))}))})).catch(o)}));return s(r,n),r}var V={_driver:"webSQLStorage",_initStorage:function(e){var t=this,n={db:null};if(e)for(var i in e)n[i]="string"!=typeof e[i]?e[i].toString():e[i];var a=new o((function(e,i){try{n.db=openDatabase(n.name,String(n.version),n.description,n.size)}catch(e){return i(e)}n.db.transaction((function(a){H(a,n,(function(){t._dbInfo=n,e()}),(function(e,t){i(t)}))}),i)}));return n.serializer=F,a},_support:"function"==typeof openDatabase,iterate:function(e,t){var n=this,i=new o((function(t,i){n.ready().then((function(){var a=n._dbInfo;a.db.transaction((function(n){G(n,a,"SELECT * FROM "+a.storeName,[],(function(n,i){for(var r=i.rows,o=r.length,s=0;s<o;s++){var l=r.item(s),c=(c=l.value)&&a.serializer.deserialize(c);if(void 0!==(c=e(c,l.key,s+1)))return void t(c)}t()}),(function(e,t){i(t)}))}))})).catch(i)}));return s(i,t),i},getItem:function(e,t){var n=this;e=c(e);var i=new o((function(t,i){n.ready().then((function(){var a=n._dbInfo;a.db.transaction((function(n){G(n,a,"SELECT * FROM "+a.storeName+" WHERE key = ? LIMIT 1",[e],(function(e,n){n=(n=n.rows.length?n.rows.item(0).value:null)&&a.serializer.deserialize(n),t(n)}),(function(e,t){i(t)}))}))})).catch(i)}));return s(i,t),i},setItem:function(e,t,n){return K.apply(this,[e,t,n,1])},removeItem:function(e,t){var n=this;e=c(e);var i=new o((function(t,i){n.ready().then((function(){var a=n._dbInfo;a.db.transaction((function(n){G(n,a,"DELETE FROM "+a.storeName+" WHERE key = ?",[e],(function(){t()}),(function(e,t){i(t)}))}))})).catch(i)}));return s(i,t),i},clear:function(e){var t=this,n=new o((function(e,n){t.ready().then((function(){var i=t._dbInfo;i.db.transaction((function(t){G(t,i,"DELETE FROM "+i.storeName,[],(function(){e()}),(function(e,t){n(t)}))}))})).catch(n)}));return s(n,e),n},length:function(e){var t=this,n=new o((function(e,n){t.ready().then((function(){var i=t._dbInfo;i.db.transaction((function(t){G(t,i,"SELECT COUNT(key) as c FROM "+i.storeName,[],(function(t,n){n=n.rows.item(0).c,e(n)}),(function(e,t){n(t)}))}))})).catch(n)}));return s(n,e),n},key:function(e,t){var n=this,i=new o((function(t,i){n.ready().then((function(){var a=n._dbInfo;a.db.transaction((function(n){G(n,a,"SELECT key FROM "+a.storeName+" WHERE id = ? LIMIT 1",[e+1],(function(e,n){n=n.rows.length?n.rows.item(0).key:null,t(n)}),(function(e,t){i(t)}))}))})).catch(i)}));return s(i,t),i},keys:function(e){var t=this,n=new o((function(e,n){t.ready().then((function(){var i=t._dbInfo;i.db.transaction((function(t){G(t,i,"SELECT key FROM "+i.storeName,[],(function(t,n){for(var i=[],a=0;a<n.rows.length;a++)i.push(n.rows.item(a).key);e(i)}),(function(e,t){n(t)}))}))})).catch(n)}));return s(n,e),n},dropInstance:function(e,t){t=d.apply(this,arguments);var n=this.config();(e="function"!=typeof e&&e||{}).name||(e.name=e.name||n.name,e.storeName=e.storeName||n.storeName);var i=this,a=e.name?new o((function(t){var a,r=e.name===n.name?i._dbInfo.db:openDatabase(e.name,"","",0);e.storeName?t({db:r,storeNames:[e.storeName]}):t((a=r,new o((function(e,t){a.transaction((function(n){n.executeSql("SELECT name FROM sqlite_master WHERE type='table' AND name <> '__WebKitDatabaseInfoTable__'",[],(function(t,n){for(var i=[],r=0;r<n.rows.length;r++)i.push(n.rows.item(r).name);e({db:a,storeNames:i})}),(function(e,n){t(n)}))}),(function(e){t(e)}))}))))})).then((function(e){return new o((function(t,n){e.db.transaction((function(i){for(var a=[],r=0,s=e.storeNames.length;r<s;r++)a.push(function(e){return new o((function(t,n){i.executeSql("DROP TABLE IF EXISTS "+e,[],(function(){t()}),(function(e,t){n(t)}))}))}(e.storeNames[r]));o.all(a).then((function(){t()})).catch((function(e){n(e)}))}),(function(e){n(e)}))}))})):o.reject("Invalid arguments");return s(a,t),a}};function j(e,t){var n=e.name+"/";return e.storeName!==t.storeName&&(n+=e.storeName+"/"),n}function Y(e,t){for(var n,i,a=e.length,r=0;r<a;){if((n=e[r])===(i=t)||"number"==typeof n&&"number"==typeof i&&isNaN(n)&&isNaN(i))return 1;r++}}e={_driver:"localStorageWrapper",_initStorage:function(e){var t={};if(e)for(var n in e)t[n]=e[n];return t.keyPrefix=j(e,this._defaultConfig),!function(){var e="_localforage_support_test";try{return localStorage.setItem(e,!0),void localStorage.removeItem(e)}catch(e){return 1}}()||0<localStorage.length?((this._dbInfo=t).serializer=F,o.resolve()):o.reject()},_support:function(){try{return"undefined"!=typeof localStorage&&"setItem"in localStorage&&!!localStorage.setItem}catch(e){return!1}}(),iterate:function(e,t){var n=this,i=n.ready().then((function(){for(var t=n._dbInfo,i=t.keyPrefix,a=i.length,r=localStorage.length,o=1,s=0;s<r;s++){var l=localStorage.key(s);if(0===l.indexOf(i)){var c=(c=localStorage.getItem(l))&&t.serializer.deserialize(c);if(void 0!==(c=e(c,l.substring(a),o++)))return c}}}));return s(i,t),i},getItem:function(e,t){var n=this;e=c(e);var i=n.ready().then((function(){var t=n._dbInfo,i=localStorage.getItem(t.keyPrefix+e);return i&&t.serializer.deserialize(i)}));return s(i,t),i},setItem:function(e,t,n){var i=this;e=c(e);var a=i.ready().then((function(){var n=t=void 0===t?null:t;return new o((function(a,r){var o=i._dbInfo;o.serializer.serialize(t,(function(t,i){if(i)r(i);else try{localStorage.setItem(o.keyPrefix+e,t),a(n)}catch(t){"QuotaExceededError"!==t.name&&"NS_ERROR_DOM_QUOTA_REACHED"!==t.name||r(t),r(t)}}))}))}));return s(a,n),a},removeItem:function(e,t){var n=this;e=c(e);var i=n.ready().then((function(){var t=n._dbInfo;localStorage.removeItem(t.keyPrefix+e)}));return s(i,t),i},clear:function(e){var t=this,n=t.ready().then((function(){for(var e=t._dbInfo.keyPrefix,n=localStorage.length-1;0<=n;n--){var i=localStorage.key(n);0===i.indexOf(e)&&localStorage.removeItem(i)}}));return s(n,e),n},length:function(e){var t=this.keys().then((function(e){return e.length}));return s(t,e),t},key:function(e,t){var n=this,i=n.ready().then((function(){var t,i=n._dbInfo;try{t=localStorage.key(e)}catch(i){t=null}return t&&t.substring(i.keyPrefix.length)}));return s(i,t),i},keys:function(e){var t=this,n=t.ready().then((function(){for(var e=t._dbInfo,n=localStorage.length,i=[],a=0;a<n;a++){var r=localStorage.key(a);0===r.indexOf(e.keyPrefix)&&i.push(r.substring(e.keyPrefix.length))}return i}));return s(n,e),n},dropInstance:function(e,t){t=d.apply(this,arguments),(e="function"!=typeof e&&e||{}).name||(i=this.config(),e.name=e.name||i.name,e.storeName=e.storeName||i.storeName);var n=this,i=e.name?new o((function(t){e.storeName?t(j(e,n._defaultConfig)):t(e.name+"/")})).then((function(e){for(var t=localStorage.length-1;0<=t;t--){var n=localStorage.key(t);0===n.indexOf(e)&&localStorage.removeItem(n)}})):o.reject("Invalid arguments");return s(i,t),i}};var z=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},q={},$={},J={INDEXEDDB:O,WEBSQL:V,LOCALSTORAGE:e},X=(e=[J.INDEXEDDB._driver,J.WEBSQL._driver,J.LOCALSTORAGE._driver],["dropInstance"]),Q=["clear","getItem","iterate","key","keys","length","removeItem","setItem"].concat(X),Z={description:"",driver:e.slice(),name:"localforage",size:4980736,storeName:"keyvaluepairs",version:1};function ee(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];if(n)for(var i in n)n.hasOwnProperty(i)&&(z(n[i])?e[i]=n[i].slice():e[i]=n[i])}return e}function te(e){for(var t in function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,te),J){var n,i;J.hasOwnProperty(t)&&(i=(n=J[t])._driver,this[t]=i,q[i]||this.defineDriver(n))}this._defaultConfig=ee({},Z),this._config=ee({},this._defaultConfig,e),this._driverSet=null,this._initDriver=null,this._ready=!1,this._dbInfo=null,this._wrapLibraryMethodsWithReady(),this.setDriver(this._config.driver).catch((function(){}))}e=new(te.prototype.config=function(e){if("object"!==(void 0===e?"undefined":i(e)))return"string"==typeof e?this._config[e]:this._config;if(this._ready)return new Error("Can't call config() after localforage has been used.");for(var t in e){if("storeName"===t&&(e[t]=e[t].replace(/\W/g,"_")),"version"===t&&"number"!=typeof e[t])return new Error("Database version must be a number.");this._config[t]=e[t]}return!("driver"in e&&e.driver)||this.setDriver(this._config.driver)},te.prototype.defineDriver=function(e,t,n){var i=new o((function(t,n){try{var i=e._driver,a=new Error("Custom driver not compliant; see https://mozilla.github.io/localForage/#definedriver");if(!e._driver)return void n(a);for(var r=Q.concat("_initStorage"),l=0,c=r.length;l<c;l++){var d=r[l];if((!Y(X,d)||e[d])&&"function"!=typeof e[d])return void n(a)}!function(){for(var t=0,n=X.length;t<n;t++){var i=X[t];e[i]||(e[i]=function(e){return function(){var t=new Error("Method "+e+" is not implemented by the current driver");return s(t=o.reject(t),arguments[arguments.length-1]),t}}(i))}}();var g=function(n){q[i]&&console.info("Redefining LocalForage driver: "+i),q[i]=e,$[i]=n,t()};"_support"in e?e._support&&"function"==typeof e._support?e._support().then(g,n):g(!!e._support):g(!0)}catch(a){n(a)}}));return l(i,t,n),i},te.prototype.driver=function(){return this._driver||null},te.prototype.getDriver=function(e,t,n){return l(e=q[e]?o.resolve(q[e]):o.reject(new Error("Driver not found.")),t,n),e},te.prototype.getSerializer=function(e){var t=o.resolve(F);return l(t,e),t},te.prototype.ready=function(e){var t=this,n=t._driverSet.then((function(){return null===t._ready&&(t._ready=t._initDriver()),t._ready}));return l(n,e,e),n},te.prototype.setDriver=function(e,t,n){var i=this;z(e)||(e=[e]);var a=this._getSupportedDrivers(e);function r(){i._config.driver=i.driver()}function s(e){return i._extend(e),r(),i._ready=i._initStorage(i._config),i._ready}return e=null!==this._driverSet?this._driverSet.catch((function(){return o.resolve()})):o.resolve(),this._driverSet=e.then((function(){var e=a[0];return i._dbInfo=null,i._ready=null,i.getDriver(e).then((function(e){i._driver=e._driver,r(),i._wrapLibraryMethodsWithReady(),i._initDriver=function(e){return function(){var t=0;return function n(){for(;t<e.length;){var a=e[t];return t++,i._dbInfo=null,i._ready=null,i.getDriver(a).then(s).catch(n)}r();var l=new Error("No available storage method found.");return i._driverSet=o.reject(l),i._driverSet}()}}(a)}))})).catch((function(){r();var e=new Error("No available storage method found.");return i._driverSet=o.reject(e),i._driverSet})),l(this._driverSet,t,n),this._driverSet},te.prototype.supports=function(e){return!!$[e]},te.prototype._extend=function(e){ee(this,e)},te.prototype._getSupportedDrivers=function(e){for(var t=[],n=0,i=e.length;n<i;n++){var a=e[n];this.supports(a)&&t.push(a)}return t},te.prototype._wrapLibraryMethodsWithReady=function(){for(var e=0,t=Q.length;e<t;e++)!function(e,t){e[t]=function(){var n=arguments;return e.ready().then((function(){return e[t].apply(e,n)}))}}(this,Q[e])},te.prototype.createInstance=function(e){return new te(e)},te),t.exports=e},{3:3}]},{},[4])(4)},375:(e,t,n)=>{let i;e.exports="function"==typeof queueMicrotask?queueMicrotask.bind("undefined"!=typeof window?window:n.g):e=>(i=i||Promise.resolve()).then(e).catch((e=>setTimeout((()=>{throw e}),0)))},967:(e,t,n)=>{e.exports=function(e,t,n){if("number"!=typeof t)throw new Error("second argument must be a Number");let a,r,o,s,l,c,d=!0;function g(e){function t(){n&&n(e,a),n=null}d?i(t):t()}function u(t,n,i){if(a[t]=i,n&&(l=!0),0==--o||n)g(n);else if(!l&&c<r){let t;s?(t=s[c],c+=1,e[t]((function(e,n){u(t,e,n)}))):(t=c,c+=1,e[t]((function(e,n){u(t,e,n)})))}}o=r=Array.isArray(e)?(a=[],e.length):(s=Object.keys(e),a={},s.length),c=t,o?s?s.some((function(n,i){return e[n]((function(e,t){u(n,e,t)})),i===t-1})):e.some((function(e,n){return e((function(e,t){u(n,e,t)})),n===t-1})):g(null),d=!1};const i=n(375)},877:(e,t,n)=>{var i=n(570),a=n(171);(n=a).v1=i,n.v4=a,e.exports=n},327:e=>{for(var t=[],n=0;n<256;++n)t[n]=(n+256).toString(16).substr(1);e.exports=function(e,n){var i=n||0;return[(n=t)[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],"-",n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],n[e[i++]],n[e[+i]]].join("")}},217:e=>{var t,n,i="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)||"undefined"!=typeof msCrypto&&"function"==typeof window.msCrypto.getRandomValues&&msCrypto.getRandomValues.bind(msCrypto);i?(t=new Uint8Array(16),e.exports=function(){return i(t),t}):(n=new Array(16),e.exports=function(){for(var e,t=0;t<16;t++)0==(3&t)&&(e=4294967296*Math.random()),n[t]=e>>>((3&t)<<3)&255;return n})},570:(e,t,n)=>{var i,a,r=n(217),o=n(327),s=0,l=0;e.exports=function(e,t,n){var c=t&&n||0,d=t||[],g=(e=e||{}).node||i,u=void 0!==e.clockseq?e.clockseq:a;null!=g&&null!=u||(h=r(),null==g&&(g=i=[1|h[0],h[1],h[2],h[3],h[4],h[5]]),null==u&&(u=a=16383&(h[6]<<8|h[7])));var p=void 0!==e.msecs?e.msecs:(new Date).getTime(),h=(n=void 0!==e.nsecs?e.nsecs:l+1,p-s+(n-l)/1e4);if(h<0&&void 0===e.clockseq&&(u=u+1&16383),1e4<=(n=(h<0||s<p)&&void 0===e.nsecs?0:n))throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");s=p,a=u,n=(1e4*(268435455&(p+=122192928e5))+(l=n))%4294967296,d[c++]=n>>>24&255,d[c++]=n>>>16&255,d[c++]=n>>>8&255,d[c++]=255&n,p=p/4294967296*1e4&268435455,d[c++]=p>>>8&255,d[c++]=255&p,d[c++]=p>>>24&15|16,d[c++]=p>>>16&255,d[c++]=u>>>8|128,d[c++]=255&u;for(var m=0;m<6;++m)d[c+m]=g[m];return t||o(d)}},171:(e,t,n)=>{var i=n(217),a=n(327);e.exports=function(e,t,n){var r=t&&n||0;"string"==typeof e&&(t="binary"===e?new Array(16):null,e=null);var o=(e=e||{}).random||(e.rng||i)();if(o[6]=15&o[6]|64,o[8]=63&o[8]|128,t)for(var s=0;s<16;++s)t[r+s]=o[s];return t||a(o)}}},t={};function n(i){var a=t[i];return void 0!==a||(a=t[i]={exports:{}},e[i](a,a.exports,n)),a.exports}n.d=(e,t)=>{for(var i in t)n.o(t,i)&&!n.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var i={};(()=>{"use strict";n.r(i),n.d(i,{exportForTesting:()=>ea,initializeLaunchSequence:()=>Xi});const e="initData",t="browserDetails",a="unifiedLogs",r={USER_DATA:"USER_DATA",PUSH_TOKEN:"PUSH_TOKEN",SUBSCRIPTION_DETAILS:"SUBSCRIPTION_DETAILS",SETUP_TIME:"SETUP_TIME",OPT_IN_SHOWN_TIME:"OPT_IN_SHOWN_TIME",SOFT_ASK_STATUS:"SOFT_ASK_STATUS",HARD_ASK_STATUS:"HARD_ASK_STATUS",WEB_SETTINGS:"WEB_SETTINGS",GRACEFUL_DATA:"GRACEFUL_DATA",Q:{PREFIX:"Q",REPORT:"REPORT",DEVICE:"DEVICE"},INIT_DATA:"INIT_DATA",OLD_SDK:{USER_DATA:"moengage_data",SUBSCRIPTION_DETAILS:"MOE_PUSH_ENDPOINT",PUSH_TOKEN:"MOE_PUSH_TOKEN"},BROWSER_DETAILS:"browserDetails",SESSION:"SESSION"},o=2,s="MOE_WEB_UNSUBSCRIBED",l="EVENT_ACTION_WEB_SESSION_START",c="MOE_PAGE_VIEWED",d="MOE_WEB_OPTIN_BANNER_LOAD",g="MOE_WEB_OPTIN_CLOSED",u="MOE_WEB_OPTIN_ACCEPTED",p="MOE_USER_SUBSCRIBED",h="MOE_OPT_IN_SHOWN",m="MOE_OPT_IN_ALLOWED",f="MOE_OPT_IN_DISMISSED",v="MOE_OPT_IN_BLOCKED",S="MOE_OPT_IN_ATTEMPT",E="MOE_LOGOUT",y="EVENT_ACTION_DEVICE_ATTRIBUTE",b="MOE_PAGE_EXIT",_="MOE_PAGE_SCROLL",T="MOE_PAGE_URL_EVENT",I="USER_ATTRIBUTE_UNIQUE_ID",A="USER_ATTRIBUTE_USER_EMAIL",w="USER_ATTRIBUTE_USER_NAME",D="USER_ATTRIBUTE_USER_FIRST_NAME",C="USER_ATTRIBUTE_USER_LAST_NAME",O="USER_ATTRIBUTE_USER_MOBILE",P="USER_ATTRIBUTE_USER_GENDER",R="USER_ATTRIBUTE_USER_BDAY",L="USER_ID_MODIFIED_FROM",N=[I,L,A,O],k="MOE_LIFECYCLE",M={MOE_INIT:"SDK_INITIALIZED",SETTINGS_FETCHED:"SETTINGS_FETCHED",EVENT_TRACKED:"EVENT_TRACKED",DEVICE_UUID:"DEVICE_UUID",MOE_INIT_COMPLETED:"SDK_INITIALIZATION_COMPLETED"},x={HARD_ASK_SHOWN:"HARD_ASK_SHOWN",HARD_ASK_DISMISSED:"HARD_ASK_DISMISSED",HARD_ASK_ATTEMPTED:"HARD_ASK_ATTEMPTED",HARD_ASK_ALLOWED:"HARD_ASK_ALLOWED",HARD_ASK_DENIED:"HARD_ASK_DENIED",SOFT_ASK_SHOWN:"SOFT_ASK_SHOWN",SOFT_ASK_DISMISSED:"SOFT_ASK_DISMISSED",SOFT_ASK_ALLOWED:"SOFT_ASK_ALLOWED"},B={code:1e3,reason:"Web push not supported in current browser environment"},W={code:1001,reason:"Registering the service worker failed"},U={code:1002,reason:"Web push settings not configured"},F={code:1004,reason:"Hard ask was dismissed to many times"},H={code:1005,reason:"Service worker can not be registered on this page due to scope issues"},G="https://media.giphy.com/media/KDRv3QggAjyo/giphy.gif",K={DC_1:"sdk-01.moengage.com",DC_2:"sdk-02.moengage.com",DC_3:"sdk-03.moengage.com",DC_4:"sdk-04.moengage.com",DC_5:"sdk-05.moengage.com",DC_100:"sdk-100.moengage.com",eu:"sdk-02.moengage.com",in:"sdk-03.moengage.com"},V={MOE_DASHBOARD:"https://app.moengage.com",MIGRATION_DOCS:"https://docs.moengage.com/docs/web-sdk-integration",WEBSDK_DOCS:"https://docs.moengage.com/docs/web-sdk-integration",SELF_HANDLED_DOCS:"https://docs.moengage.com/docs/self-handled-opt-ins"},j="Dashboard --\x3e Settings --\x3e Channel --\x3e Push",Y="SESSION",z="v3/sdkconfig/",q="moe_tracking",$="events",J="batched_events",X="moe_uuid",Q="MoengagePageEventHistoryManager",Z={HOST_1:"https://sdk-01.moengage.com/",HOST_2:"https://sdk-02.moengage.com/",HOST_3:"https://sdk-03.moengage.com/",HOST_4:"https://sdk-04.moengage.com/",HOST_5:"https://sdk-05.moengage.com/",HOST_100:"https://sdk-100.moengage.com/",API:{META:"v3/campaigns/inapp/live",CAMPAIGN_PAYLOAD:"v3/campaigns/inapp/live/",DRAFT_CAMPAIGN_PAYLOAD:"v3/campaigns/inapp/test/",STATS:"v3/campaigns/inapp/live/stats",CAMPAIGNS_PAYLOAD:"v3/campaigns/inapp/live/campaigns"},DRAFT_CAMPAIGN_TPYES:{WEB_PERSONALIZATON:"web_personalization",ONSITE_MESSAGING:"onsite_messaging"},META_REFRESH_TIME:9e5,DATABASE_NAME:"moe_onsite",OSM_MODULE:"moeOnsite",DELIVERY_FUNNEL:{ATTEMPTED:{CAMPAIGN_ATTEMPTED:"ATM"},PRIORITIZED:{CAMPAIGN_PRIORITY_HIGH_PRIORITY_CAMPAIGN_AVAILABLE:"PRT_HIGH_PRT_CMP_AVL",CAMPAIGN_PRIORITY_MAX_TIMES_SHOWN:"PRT_MAX_TIM_SWN",CAMPAIGN_PRIORITY_MIN_DELAY:"PRT_MIN_DEL",CAMPAIGN_PRIORITY_GLOBAL_DELAY:"PRT_GBL_DEL",CAMPAIGN_PRIORITY_EXPIRED:"PRT_EXP"},DELIVERED:{CAMPAIGN_DELIVERED_API_FAILURE:"DLV_API_FLR",CAMPAIGN_DELIVERED_PERSONALIZATION_FAILURE:"DLV_PERSN_FLR",CAMPAIGN_DELIVERED_PAUSED:"DLV_PAU",CAMPAIGN_DELIVERED_EXPIRED:"DLV_EXP",CAMPAIGN_DELIVERED_MANDATORY_PARAMS_MISSING:"DLV_MAND_PARM_MIS"},IMPRESSION:{CAMPAIGN_IMPRESSION_CONTEXT_CHANGED:"IMP_CTX_CHG",CAMPAIGN_IMPRESSION_GLOBAL_DELAY:"IMP_GBL_DEL",CAMPAIGN_IMPRESSION_MAX_TIMES_SHOWN:"IMP_MAX_TIM_SHW",CAMPAIGN_IMPRESSION_ANOTHER_CAMPAIGN_VISIBLE:"IMP_ANTR_CMP_VISB"},EVALUATION:{CAMPAIGN_EVALUATION_PATH_TIME_EXPIRED:"EVL_PATH_TIME_EXP",CAMPAIGN_EVALUATION_USER_NOT_ON_APP:"EVL_USER_NOT_ON_APP"}},STORES:{CAMPAIGNS_META:{NAME:"campaigns_meta"},CAMPAIGNS_TAGS:{NAME:"campaigns_tags"},CAMPAIGNS_STATS:{NAME:"campaigns_stats"},TEST_CAMPAIGN_STORE:{NAME:"test_campaign"},EXIT_INTENT_CAMPAIGN_STORE:{NAME:"exit_intent"},SERVICE_META:{NAME:"service_meta",KEYS:{LAST_META_CALL_TIME:"last_meta_call_time",GLOBAL_DELAY:"global_delay_between_inapps",LAST_INAPP_SHOWN_TIME:"last_inapp_shown",LAST_FETCH_SDK_VERSION:"last_fetch_sdk_version",UNIQUE_ID:"unique_id"}},PENDING_SECONDARY_EVENTS:{NAME:"pending_secondary_events"},PENDING_TIMER_CAMPAIGNS:{NAME:"pending_timer_campaigns"},TRIGGERING_PRIMARY_EVENTS:{NAME:"triggering_primary_events"}},EVENT_NAMES:{OSM:{CLICK:"MOE_ONSITE_MESSAGE_CLICKED",IMPRESSION:"MOE_ONSITE_MESSAGE_SHOWN",DISMISS:"MOE_ONSITE_MESSAGE_DISMISSED",AUTO_DISMIS:"MOE_ONSITE_MESSAGE_AUTO_DISMISS",TYPE:"onsite"},WP:{CLICK:"MOE_WEBP_MESSAGE_CLICKED",IMPRESSION:"MOE_WEBP_MESSAGE_SHOWN",DISMISS:"MOE_WEBP_MESSAGE_DISMISSED",DELIVERED:"MOE_WEBP_MESSAGE_DELIVERED",TYPE:"webp"}},WEB_HELPER_IFRAME_URL:"https://cdn.moengage.com/webpush/beta/webpushhelper.html",IFRAME_CHANNEL:"inapp_helper",IFRAME_TOPICS:{COOKIE_STORAGE:"COOKIE_STORAGE"},COOKIE_STORAGE:{TEST_DRAFT_TYPE:"moe_inapp_draft_type",TEST_DRAFT_ID:"moe_inapp_draft_id",TEST_DRAFT_TAG:"moe_inapp_draft_tag",TEST_CAMPAIGN_META:"test_campaign_meta",TEST_TEMPLATE_TYPE:"test_template_type",TEST_VARIATION:"moe_inapp_draft_variation",TEST_LOCALE:"moe_inapp_draft_locale"},CSS_SELECTORS:{CLICK_INAPP:"moe-inapp-click",DISMISS_INAPP:"moe-inapp-close"},EXIT_INTENT:{CONFIG:{SCROLL_DOWN_THRESHOLD:50,SCROLL_UP_THRESHOLD:5,SCROLL_INTERVAL:1e3}},POSITIONED_TEMPLATE:'data-editor-type="MOE_EDITOR"',SIDE_BANNER:'data-template-type="SIDE_BANNER"',PUSH_BANNER:"moe-osm-pusher",GCG_ERROR_CODE:"E001",SCROLL_CAMPAIGN_THROTTLING_TIME:1500},ee={CARDS:{name:"CARDS",src:"https://cdn.moengage.com/webpush/moe_webSdk_cards.min.latest.js",windowLocation:"moeCards"}},te={NAME:"offline_data"},ne="v2/sdk/report/",ie=15e3,ae="number",re={TOPIC:"MOE_AUTOMATED_EVENTS",NAMES:[s,l,c,d,g,u,p,S,h,m,f,v,E,Z.EVENT_NAMES.OSM.CLICK,Z.EVENT_NAMES.OSM.IMPRESSION,Z.EVENT_NAMES.OSM.DISMISS,Z.EVENT_NAMES.OSM.AUTO_DISMIS]},oe=[S],se="moe_cards",le={STORE_NAME:"campaigns"},ce={STORE_NAME:"meta",LAST_FETCH_SDK_VERSION:"last_fetch_sdk_version",LAST_META_CALL_TIME:"last_meta_call_time",UNIQUE_ID:"unique_id",LAST_SYNC_CARDS:"last_sync_cards",SYNC_INTERVALS:"sync_intervals",SHOW_ALL_TAB:"show_all_tab"},de="appOpen",ge="IOS_PERMISSION_DENIED",ue="v1/sdk_logging/",pe="v2/device/add",he="v2/device/token-check",me="v2/report/add",fe={TV:"tv",TABLET:"tablet",MOBILE:"mobile",WEB:"web"};var ve,Se=n(483);function Ee(e,t,n){return null!=e&&t?(e=e[(t=Array.isArray(t)?t:t.split("."))[0]])&&1<t.length?Ee(e,t.slice(1),n):void 0===e?n||null:e:null}class ye{static set(e,t){ye.baseLogTag,window&&(window.moeInternals?window.moeInternals.ephemeral||(window.moeInternals.ephemeral={}):(window.moeInternals={},window.moeInternals.ephemeral={}),window.moeInternals.ephemeral[e]=t)}static get(e){return Ee(window,"moeInternals.ephemeral."+e,null)}}ye.baseLogTag="EphemeralStorage";class be{constructor(){this.items=[]}static enqueue(e,t){e=be.getLocalStorageQName(e);let n=new be;xe.get(e)&&(n=xe.get(e)),n.items.push(t),n.items=n.items.slice(Math.max(n.items.length-50,0)),xe.set(e,n)}static dequeue(e){e=be.getLocalStorageQName(e);const t=xe.get(e);let n=null;return t&&0<t.items.length&&(n=t.items[0],t.items.splice(0,1),xe.set(e,t)),n}static isEmpty(e){return e=be.getLocalStorageQName(e),!(xe.get(e)&&0<xe.get(e).items.length)}static purge(e){var t=be.getLocalStorageQName(e);be.isEmpty(e)||xe.remove(t)}static getLocalStorageQName(e){return r.Q.PREFIX+"_"+e}}class _e{constructor(e){var t=_e.baseLogTag+".constructor";e.placeholder||at.warn(1,t,"Placeholder for cards inbox not passed in cardsConfig: ",e),this.placeholder=Ee(e,"placeholder",""),this.enable=Ee(e,"enable",!1),this.overLayColor=Ee(e,"overLayColor","rgba(0, 0, 0, 0.8)"),this.backgroundColor=Ee(e,"backgroundColor","#F6FBFC"),this.navigationBar=new Te(Ee(e,"navigationBar",{})),this.closeButton=new we(Ee(e,"closeButton",{})),this.tab=new De(Ee(e,"tab",{})),this.cardDismiss=new Ce(Ee(e,"cardDismiss",{})),this.optionButtonColor=Ee(e,"optionButtonColor","#C4C4C4"),this.dateTimeColor=Ee(e,"dateTimeColor","#8E8E8E"),this.unclickedCardIndicatorColor=Ee(e,"unclickedIndicatorColor","blue"),this.pinIcon=Ee(e,"pinIcon","https://app-cdn.moengage.com/sdk/pin-icon.svg"),this.refreshIcon=Ee(e,"refreshIcon","https://app-cdn.moengage.com/sdk/refresh-icon.svg"),this.webFloating=new Re(Ee(e,"webFloating",{})),this.mWebFloating=new Re(Ee(e,"mWebFloating",{countBackgroundColor:"#FF5A5F",enable:!1,icon:"https://app-cdn.moengage.com/sdk/bell-icon.svg",countColor:"#fff",postion:"0px 10px 40px 0",iconBackgroundColor:"#D9DFED"})),this.card=new Ae(Ee(e,"card",{})),this.errorContent=new Ie(Ee(e,"errorContent",{})),this.noDataContent=new Le(Ee(e,"noDataContent",{})),this.openInbox=Ee(e,"openInbox",(()=>{})),this.zIndex=Ee(e,"zIndex","999999"),this.fontFaces=(null===(e=e.fontFaces)||void 0===e?void 0:e.map((e=>new Oe(e))))||[]}}_e.baseLogTag="CardsConfigModel";class Te{constructor(e){this.backgroundColor=Ee(e,"backgroundColor","#00237C"),this.text=Ee(e,"text","Notification"),this.color=Ee(e,"color","#fff"),this.fontSize=Ee(e,"fontSize","16px"),this.fontFamily=Ee(e,"fontFamily","inherit")}}class Ie{constructor(e={}){this.img=Ee(e,"img","https://app-cdn.moengage.com/sdk/cards-error.svg"),this.text=Ee(e,"text",'Error something went wrong <button onclick="window.location.reload();" style="color: #06A6B7; display: contents;" class="btn-icon pointer-cursor" >Refresh</button>')}}class Ae{constructor(e){this.headerFontSize=Ee(e,"headerFontSize","16px"),this.descriptionFontSize=Ee(e,"descriptionFontSize","14px"),this.ctaFontSize=Ee(e,"ctaFontSize","12px"),this.fontFamily=Ee(e,"fontFamily","inherit"),this.horizontalRowColor=Ee(e,"horizontalRowColor","#D9DFED")}}class we{constructor(e){this.mWebIcon=Ee(e,"mWebIcon","https://app-cdn.moengage.com/sdk/back-icon.svg"),this.webIcon=Ee(e,"webIcon","https://app-cdn.moengage.com/sdk/cross-icon.svg"),this.callBack=Ee(e,"callBack",(()=>{}))}}class De{constructor(e){this.inactiveTabFontColor=Ee(e,"inactiveTabFontColor","#7C7C7C"),this.fontSize=Ee(e,"fontSize","14px"),this.fontFamily=Ee(e,"fontFamily","inherit"),this.backgroundColor=Ee(e,"backgroundColor","#F6FBFC"),this.active=new Pe(Ee(e,"active",{}))}}class Ce{constructor(e){this.color=Ee(e,"color","red"),this.enable=Ee(e,"enable",!1)}}class Oe{constructor(e){this.family=Ee(e,"family",""),this.url=Ee(e,"url","")}}class Pe{constructor(e){this.color=Ee(e,"color","#06A6B7"),this.underlineColor=Ee(e,"underlineColor","#06A6B7"),this.backgroundColor=Ee(e,"backgroundColor","transparent")}}class Re{constructor(e){this.enable=Ee(e,"enable",!1),this.icon=Ee(e,"icon","https://app-cdn.moengage.com/sdk/bell-icon.svg"),this.postion=Ee(e,"postion","0px 10px 40px 0"),this.countBackgroundColor=Ee(e,"countBackgroundColor","#FF5A5F"),this.countColor=Ee(e,"countColor","#fff"),this.zIndex=Ee(e,"zIndex","999998"),this.iconBackgroundColor=Ee(e,"iconBackgroundColor","#D9DFED"),this.fontFamily=Ee(e,"fontFamily","inherit")}}class Le{constructor(e){this.img=Ee(e,"img","https://app-cdn.moengage.com/sdk/cards-no-result.svg"),this.text=Ee(e,"text","No notifications to show, check again later.")}}class Ne{constructor(e){this.debugLevel=0,this.cluster=null,this.environment=null,this.baseDomainName="https://sdk-01.moengage.com/",this.inapp=null,this.customSoftAsk=null;var t=Ne.baseLogTag+".constructor";null!=Ee(e,"app_id",null)?(this.appId=Ee(e,"app_id",null),this.integrationType=ve.OLD_SDK):null!=Ee(e,"appId",null)?(this.appId=Ee(e,"appId",null),this.integrationType=ve.NEW_SDK):(at.error(1,t,"App Id not specified. Please check docs page to complete the integration - ",V.WEBSDK_DOCS),this.integrationType=null),null!=Ee(e,"debug_logs",null)?this.debugLevel=Ee(e,"debug_logs",0):null!=Ee(e,"debugLevel",null)?this.debugLevel=Ee(e,"debugLevel",0):(at.log(2,t,"No log level config found. Using default value of",0),this.debugLevel=0),this.appId&&(this.baseDomainName="https://sdk-01.moengage.com/",this.forceSwUpdate=Ee(e,"forceSwUpdate",!1),this.cluster=Ee(e,"cluster",this.cluster),this.cluster&&null!=K[this.cluster]&&(this.environment=K[this.cluster]),Ee(e,"environment",null)&&(this.environment=e.environment),this.environment&&(this.baseDomainName="https://"+this.environment+"/"),0<this.debugLevel&&this.appId.indexOf("_DEBUG")<0?this.appId=this.appId+"_DEBUG":0===this.debugLevel&&0<=this.appId.indexOf("_DEBUG")&&(this.appId=this.appId.substr(0,this.appId.indexOf("_DEBUG"))),this.swPath=Ee(e,"swPath",null),null!=e.customSoftAsk?this.customSoftAsk={mainClass:Ee(e,"customSoftAsk.mainClass",null),allowClass:Ee(e,"customSoftAsk.allowClass",null),dismissClass:Ee(e,"customSoftAsk.dismissClass",null)}:this.customSoftAsk={mainClass:Ee(e,"main_class",null),allowClass:Ee(e,"allow_class",null),dismissClass:Ee(e,"block_class",null)},null!=Ee(e,"inapp.host",null)&&(this.inapp={host:Ee(e,"inapp.host",null)}),null!=Ee(e,"swScope",null)&&(this.swScope=Ee(e,"swScope",null)),null!=Ee(e,"disable_onsite",null)&&(this.disableOnsite=Ee(e,"disable_onsite",!1)),null!=Ee(e,"enableSPA",null)&&(this.enableSPA=Ee(e,"enableSPA",!1)),null!=Ee(e,"cards",null)&&(this.cards=new _e(Ee(e,"cards",{}))),null!=Ee(e,"api_proxy_domain",null)&&(this.apiProxyDomain=Ee(e,"api_proxy_domain",null),this.baseDomainName="https://"+this.apiProxyDomain+"/",this.environment=this.apiProxyDomain),null!=Ee(e,"disable_web_push",null)&&(this.disableWebPush=Ee(e,"disable_web_push",!1)),null!=Ee(e,"disableCookies",null)&&(this.disableCookies=Ee(e,"disableCookies",!1)))}static save(t){ye.set(e,new Ne(t)),xe.set(r.INIT_DATA,new Ne(t))}static get(){return ye.get(e)}static setSoftAskConfig(e){var t=Ne.get();e={appId:t.appId,debugLevel:t.debugLevel,cluster:t.cluster,environment:t.environment,swPath:t.swPath,enableSPA:t.enableSPA,cards:t.cards,apiProxyDomain:t.apiProxyDomain,disableCookies:t.disableCookies,customSoftAsk:{mainClass:Ee(e,"main_class",Ee(e,"mainClass",null)),allowClass:Ee(e,"allow_class",Ee(e,"allowClass",null)),dismissClass:Ee(e,"block_class",Ee(e,"dismissClass",null))}},Ne.save(e)}}Ne.baseLogTag="InitData",(lt=ve=ve||{}).OLD_SDK="OLD_SDK",lt.NEW_SDK="NEW_SDK";class ke{static set(e,t){var n;null!==(n=Ne.get())&&void 0!==n&&n.disableCookies||(n=ke.baseTag+".set",null==t?ke.remove(e):(t="boolean"==typeof t?JSON.stringify({actualValue:t,MOE_DATA_TYPE:"boolean"}):"string"==typeof t?JSON.stringify({actualValue:t,MOE_DATA_TYPE:"string"}):JSON.stringify(t),at.log(3,n,"Setting ",e,":",t),n=Date.now(),n=";expires="+new Date(n+31536e6*o).toUTCString(),document.cookie=e+"="+encodeURIComponent(t)+n+";domain="+ke.getOrigin()+";path=/;SameSite=None; Secure"))}static get(e){var t;if(null===(t=Ne.get())||void 0===t||!t.disableCookies){var n=ke.baseTag+".get",i=e+"=",a=decodeURIComponent(document.cookie).split(";");for(let r=a.length-1;0<=r;r--){let o=a[r];for(;" "===o.charAt(0);)o=o.substring(1);if(0===o.indexOf(i)){let a=o.substring(i.length,o.length);try{a=JSON.parse(a),"string"===Ee(a,"MOE_DATA_TYPE",null)?(a=Ee(a,"actualValue",null),a=a?String(a):null):"boolean"===Ee(a,"MOE_DATA_TYPE",null)&&(a=Ee(a,"actualValue",null))}catch(t){}return at.log(3,n,"Got ",e,":",a),a}}return null}}static remove(e){var t;null!==(t=Ne.get())&&void 0!==t&&t.disableCookies||(t=ke.baseTag+".remove",document.cookie=e+"=;domain="+ke.getOrigin()+";path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT;",at.log(3,t,"Removed ",e))}static setRaw(e,t,n){if(null===(i=Ne.get())||void 0===i||!i.disableCookies){var i=ke.baseTag+".setRaw";if(null==t)ke.remove(e);else{at.log(3,i,"Setting ",e,":",t);let a="";null!=n&&(a=";expires="+n.toISOString()),document.cookie=e+"="+encodeURIComponent(t)+a+";domain="+ke.getOrigin()+";path=/;"}}}static getOrigin(){if(null===(e=Ne.get())||void 0===e||!e.disableCookies){var e=ke.baseTag+".getOrigin";let t=window.location.origin;return t=t.indexOf(".")!==t.lastIndexOf(".")?t.substring(t.indexOf(".")):"."+t.substring(t.lastIndexOf("/")+1),"localhost"===window.location.hostname&&(at.warn(1,e,"Cross domain user persitence will not work with localhost. \n\nWe will save the key-value pairs in the localhost cookie store for reference. You'll be able to test this functionality in a hosted staging/test environment."),t=""),t}}}ke.baseTag="CookieStorage";const Me="MOE_DATA";class xe{static setPrefix(e){xe.prefix=e+"_"}static set(e,t){if(xe.baseLogTag,e=xe.prefix+e,localStorage){const n=xe.getMoeData();n[e]=t,localStorage.setItem(Me,JSON.stringify(n))}var n=xe.KEYS_SHARED_WITH_COOKIE.indexOf(e);if(xe.isSharedWithCookie&&0<=n){const i="object"!=typeof t||Array.isArray(t)?t:Object.assign({},t);0===n&&Array.isArray(i.attributes)&&(i.attributes=i.attributes.filter((e=>!!N.includes(e.key)))),e===r.SUBSCRIPTION_DETAILS&&(i.domain=t.domain,i.token=t.token,i.endpoint=t.endpoint,i.keys=t.keys),ke.set(e,i)}}static get(e){return xe.baseLogTag,e=xe.prefix+e,localStorage?Ee(xe.getMoeData(),e,null):null}static remove(e){var t=xe.baseLogTag+".remove",n=xe.prefix+e;if(localStorage&&null!=xe.get(e)){const i=xe.getMoeData();delete i[n],localStorage.setItem(Me,JSON.stringify(i)),at.log(2,t,"Key",e,"removed.")}xe.isSharedWithCookie&&0<=xe.KEYS_SHARED_WITH_COOKIE.indexOf(e)&&ke.remove(e)}static logout(){const e=["INIT_DATA","Q","WEB_SETTINGS","SUBSCRIPTION_DETAILS","PUSH_TOKEN","GRACEFUL_DATA"];for(const t in r)e.indexOf(t)<0&&xe.remove(r[t]);for(const e in r.Q)be.purge(e)}static getString(e){if(e=xe.prefix+e,localStorage)return"string"==typeof(e=xe.get(e))||e instanceof String?e:JSON.stringify(e)}static removePrefix(){xe.prefix=""}static copyKeysFromCookie(){for(let n=0;n<xe.KEYS_SHARED_WITH_COOKIE.length;n++){var e=xe.KEYS_SHARED_WITH_COOKIE[n],t=ke.get(e);if(null!=t){const n="object"!=typeof t||Array.isArray(t)?t:Object.assign({},t);if(e===r.USER_DATA&&(t=xe.get(e)&&xe.get(e).attributes,Array.isArray(n.attributes)&&Array.isArray(t)&&0<t.length)){let e=[...t];n.attributes.forEach((t=>{var n=e.findIndex((e=>e.key===t.key));0<=n?e[n]=t:e.push(t)})),e=e.filter((e=>!(N.includes(e.key)&&n.attributes.findIndex((t=>t.key===e.key))<0))),n.attributes=e}xe.set(e,n)}}xe.removeStaleKeysFromLS()}static removeStaleKeysFromLS(){var e=xe.baseLogTag+".removeStaleKeysFromLS";try{Object.keys(xe.getMoeData()).forEach((e=>{this.KEYS_SHARED_WITH_COOKIE.includes(e)&&!ke.get(e)&&xe.remove(e)}))}catch(t){at.error(1,e,t)}}static getMoeData(){var e=xe.baseLogTag+".getMoeData",t=localStorage.getItem(Me);if(null==t)return{};try{return JSON.parse(t)}catch(t){return at.error(1,e,t),{}}}}function Be(e){return 0===Object.keys(e).length&&e.constructor===Object}function We(e){e=(e+"=".repeat((4-e.length%4)%4)).replace(/\-/g,"+").replace(/_/g,"/");const t=atob(e),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}function Ue(e){let t="";var n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i=new Uint8Array(e),a=i.byteLength,r=a-(e=a%3);let o,s,l,c,d;for(let e=0;e<r;e+=3)d=i[e]<<16|i[e+1]<<8|i[e+2],o=(16515072&d)>>18,s=(258048&d)>>12,l=(4032&d)>>6,c=63&d,t+=n[o]+n[s]+n[l]+n[c];return 1==e?(d=i[r],o=(252&d)>>2,s=(3&d)<<4,t+=n[o]+n[s]+"=="):2==e&&(d=i[r]<<8|i[1+r],o=(64512&d)>>10,s=(1008&d)>>4,l=(15&d)<<2,t+=n[o]+n[s]+n[l]+"="),t}function Fe(e,t){return t.isChrome()||t.isOpera()||t.isEdge()||t.isSafari()?"vapid"===e.chrome.subscriptionMode&&e.chrome.vapidPublicKey:t.isFirefox()&&"vapid"===e.firefox.subscriptionMode&&e.firefox.vapidPublicKey}function He(e,t){return t.isChrome()||t.isOpera()||t.isEdge()||t.isSafari()?e.chrome.vapidPublicKey:t.isFirefox()?e.firefox.vapidPublicKey:""}function Ge(){const e=Ne.get().swPath;return!(!e||!e.includes("tools/moengage"))}function Ke(){const e=navigator.userAgent;return!(!/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|ipad|iris|kindle|Android|Silk|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i.test(e)&&!/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(e.substr(0,4)))}function Ve(){var e=navigator.userAgent.toLowerCase(),t=/(ipad|tablet|(android(?!.*mobile))|(windows(?!.*phone)(.*touch))|kindle|playbook|silk|(puffin(?!.*(IP|AP|WP))))/.test(e);return/nexus player|neo-x5|adt-2|tsbnettv|roku|tizen|smart-tv.+(samsung)|hbbtv.+maple;(\d+)|(nux; netcast.+smarttv|lg (netcast\.tv-201\d|android tv))|(apple) ?tv|crkey|droid.+aft(\w)( bui|\))|\(dtv[\);].+(aquos)|(aquos-tv[\w ]+)\)|(bravia[\w ]+)( bui|\))|(mitv-\w{5}) bui|Hbbtv.*(technisat) (.*);|\b(roku)[\dx]*[\)\/]((?:dvp-)?[\d\.]*)|hbbtv\/\d+\.\d+\.\d+ +\([\w\+ ]*; *([\w\d][^;]*);([^;]*)|\b(android tv|smart[- ]?tv|opera tv|tv; rv:)\b/i.test(e)?fe.TV:t?fe.TABLET:Ke()?fe.MOBILE:fe.WEB}function je(e,t){const n=t&&new RegExp("^("+t.join("|")+")$");return Ve()===fe.TV&&(null!=n&&n.test(e)||!t)?{moe_os_type:function(){var e=navigator.userAgent.toLowerCase();return/tizen/i.test(e)?"Tizen":/web0s/i.test(e)?"WebOS":/xbox/i.test(e)?"Xbox":/vizio/i.test(e)?"viziotv":"SmartTV"}(),os:fe.TV.toUpperCase()}:{}}function Ye(e){return new Date(Date.parse(e))}function ze(){return window[window.moengage_object||"Moengage"]}xe.baseLogTag="PersistentStorage",xe.prefix="",xe.isSharedWithCookie=!1,xe.KEYS_SHARED_WITH_COOKIE=[r.USER_DATA,r.SUBSCRIPTION_DETAILS,r.SOFT_ASK_STATUS,r.PUSH_TOKEN,r.OPT_IN_SHOWN_TIME,r.HARD_ASK_STATUS,r.SESSION];const qe=e=>"string"==typeof e,$e=e=>"[object Date]"===Object.prototype.toString.call(e);function Je(e,t){if(null==e||null==t)return e===t;if(e instanceof Function)return e===t;if(e instanceof RegExp)return e===t;if(e===t||e.valueOf()===t.valueOf())return!0;if(Array.isArray(e)&&e.length!==t.length)return!1;if(e instanceof Date)return!1;if(!(e instanceof Object))return!1;if(!(t instanceof Object))return!1;const n=Object.keys(e);return Object.keys(t).every((e=>-1!==n.indexOf(e)))&&n.every((n=>Je(e[n],t[n])))}function Xe(){const e=new Date;return`${e.getDate()}:${e.getMonth()+1}:${e.getFullYear()}:${e.getHours()}:${e.getMinutes()}:`+e.getSeconds()}const Qe=e=>{if(e){const t=e.replace("?","").split("&"),n={};return t.forEach((e=>{e=(t=e.split("="))[0];var t=decodeURIComponent(t[1]||"");n[e]?"[object Array]"===Object.prototype.toString.call(n[e])?n[e].push(t):n[e]=[n[e],t]:n[e]=t})),JSON.parse(JSON.stringify(n))}return{}},Ze=()=>window.location.search.includes("moe_migration=true"),et=e=>{var t,n,i=xe.get(r.WEB_SETTINGS);null!=i&&i.configs.isWebPersonalisationModuleEnabled&&null!==(t=window.MoeWebP)&&void 0!==t&&t.clearLastFetchedTime(),e&&null!==(n=window.MoeWebP)&&void 0!==n&&n.getLiveExperiences()},tt=(e,t)=>{e+="?";for(const n in t)t.hasOwnProperty(n)&&null!=t[n]&&(e+=n+"="+encodeURIComponent(t[n])+"&");return e};class nt{static logData(e,t){return{log_type:e,sent_time:(new Date).toISOString(),lake_fields:t}}static setRemoteLogging(e){return this.isTrackingEnabled||(this.logLevel=null==e?void 0:e.configs.logLevel,this.isTrackingEnabled=e.configs.remoteLogTracking,this.isTrackingEnabled)}static log(e,t,n,i,...a){!this.isTrackingEnabled||e!==this.logLevel&&"verbose"!==this.logLevel||ze().remoteLogs.addRemoteLogs(this.logData(e,{msg:n+[...a].toString(),file_name:t,trace:i}))}}let it="color: white; background: #41AE55; border-radius: 5px;";class at{static setLogLevel(e,t){var n=at.baseLogTag+".setLogLevel";null==ye.get(a)&&ye.set(a,[]),null==e?at.logLevel=0:e in[0,1,2]?0<(at.logLevel=e)&&t&&at.releaseAllLogs():at.warn(0,n,"Value",e,"not supported for setDebugLevel(). Current log level is",at.logLevel,". Debug level can only be [0, 1, 2]")}static setLogTabStyle(e){at.tagLogStyle=at.tagLogStyle.replace("#48beab",e)}static log(e,t,n,...i){e<=at.logLevel?console.log("%c "+at.logBrand+" %c %c info %c %c "+t+" ",it,"","color: white; background: #18a0bf; border-radius: 5px;","",at.tagLogStyle,n,...i):at.cacheLog((()=>{at.log(e,t,n,...i)}))}static remoteLogTracking(e,t,n,i,...a){nt.log(t,n,i,...a),this.log(e,n,i,...a)}static error(e,t,n,...i){var a;null!==(a=i[i.length-1])&&void 0!==a&&a.isCached||nt.log("error",t,n,...i),e<=at.logLevel?console.error("%c "+at.logBrand+" %c %c error %c %c "+t+" ",it,"","color: white; background: #cc0a0a; border-radius: 5px;","",at.tagLogStyle,n,...i.slice(0,-1)):at.cacheLog((()=>{at.error(e,t,n,...i,{isCached:!0})}))}static warn(e,t,n,...i){var a;null!==(a=i[i.length-1])&&void 0!==a&&a.isCached||nt.log("warning",t,n,...i),e<=at.logLevel?console.warn("%c "+at.logBrand+" %c %c warn %c %c "+t+" ",it,"","color: white; background: #e8ab51; border-radius: 5px;","",at.tagLogStyle,n,...i.slice(0,-1)):at.cacheLog((()=>{at.warn(e,t,n,...i,{isCached:!0})}))}static customLabel(e,t,n,...i){e<=at.logLevel?console.log("%c "+at.logBrand+" %c %c "+t+" %c %c "+n+" %c ",it,"",at.tagLogStyle,"","color: white; background: #a400ff; border-radius: 5px;","",...i):at.cacheLog((()=>{at.customLabel(e,t,n,...i)}))}static image(e,t){e<=at.logLevel?console.log("%c+","font-size: 1px; padding: 20px 80px; line-height: 45px; background: url("+t+"); background-size: 160px 90px; color: transparent;"):at.cacheLog((()=>{at.image(e,t)}))}static releaseAllLogs(){var e=ye.get(a),t=e.length;const n=e;if(ye.set(a,[]),0<t){at.log(0,"Logger.releaseAllLogs","<---- HISTORICAL LOGS BEGIN ----\x3e");for(let e=0;e<t;e++)n[e]();at.log(0,"Logger.releaseAllLogs","<---- HISTORICAL LOGS END ----\x3e")}}static setLogBrand(e){at.logBrand=e}static setBrandColor(e){it="color: white; background: "+e+"; border-radius: 5px;"}static cacheLog(e){let t=ye.get(a);null==t&&(t=[]),t.push(e),ye.set(a,t)}}at.baseLogTag="Logger",at.logBrand="MoEngage",at.logLevel=0,at.tagLogStyle="color: white; background: #48beab; border-radius: 5px;";class rt{static get(e,t){return rt.makeNetworkCall(rt.METHODS.GET,e,t)}static post(e,t){return rt.makeNetworkCall(rt.METHODS.POST,e,t)}static makeNetworkCall(e,t,n={}){return new Promise(((i,a)=>{var r=JSON.stringify(Ee(n,"postData",null));t=tt(t,Ee(n,"queryParams",null));const o=new XMLHttpRequest;o.open(e,t,!0),rt.addRequestHeaders(o,Ee(n,"headers",{})),o.onreadystatechange=()=>{4===o.readyState&&200===o.status||4===o.readyState&&410===o.status?i({status:o.status,responseText:o.responseText}):4===o.readyState&&200!==o.status&&a({code:o.status,reason:o.responseText})},o.send(r)}))}static addRequestHeaders(e,t){for(const n in t)t.hasOwnProperty(n)&&e.setRequestHeader(n,t[n]);return e}}(Ui=(Ui=rt=rt||{}).METHODS||(Ui.METHODS={})).GET="GET",Ui.POST="POST";const ot=rt;class st{constructor(){this.p=null,this.res=null,this.rej=null;try{this.p=new Promise(((e,t)=>{this.res=e,this.rej=t}))}catch(e){at.error(1,"Utils.PromiseObject","Promises not supported")}}}var lt,ct=n(877);class dt{initiateSessionAndSource(e){return new Promise(((t,n)=>{this.isSessionRunning()&&this.isCurrentSourceSameAsPreviousSource()||this.startNewSession(e),t(!0)}))}isSessionRunning(){return this.getSessionKey()&&!this.isSessionExpired()}isSessionExpired(){var e=this.getSessionExpiryTime(),t=ye.get("wasBrowserInactive");return!(!t&&null!==t)&&(this.isWindowActive()&&ye.set("wasBrowserInactive",!1),(new Date).getTime()>e)}isNonEventInteractive(e){return dt.NON_INTERACTIVE_EVENTS.includes(e.name)||0<e.attributes.filter((e=>"moe_non_interactive"===e.key&&1===e.value)).length}getCurrentSource(){const e=Qe(window.location.search);let t="";const n={};if(Object.keys(e).includes("utm_source")){t="utm_",this.geCustomIdentifiersToTrack().forEach((t=>{e[t]&&(n[t]=e[t])}));const i={source_url:window.location.href};return e[t+"source"]&&(i.source=e[t+"source"]),e[t+"medium"]&&(i.medium=e[t+"medium"]),e[t+"term"]&&(i.term=e[t+"term"]),e[t+"campaign"]&&(i.campaign_name=e[t+"campaign"]),e[t+"content"]&&(i.content=e[t+"content"]),e.utm_id&&(i.campaign_id=e.utm_id),Object.keys(n).length&&(i.extra=n),i}}getActiveSource(){return this.getSavedSource()||this.getCurrentSource()}isSourceOrganic(){const e=Qe(window.location.search),t=Object.keys(e);let n=!1;return this.geCustomIdentifiersToTrack().forEach((t=>{e[t]&&(n=!0)})),!t.includes("utm_source")&&!t.includes("source")&&!n}setCurrentSource(e){const t=this.getSession();t.currentSource=e,xe.set(Y,t)}removeCurrentSource(){const e=this.getSession();e&&(e.currentSource=void 0,xe.set(Y,e))}getSavedSource(){var e=Ee(this.getSession(),"currentSource",void 0);if(e)return e}isCurrentSourceSameAsPreviousSource(){if(this.isSourceOrganic())return!0;const e=Object.assign({},this.getCurrentSource());delete e.source_url;const t=Object.assign({},this.getSavedSource());return delete t.source_url,Je(e,t)}getSessionKey(){return Ee(this.getSession(),"sessionKey",null)}getSessionStartTime(){return Ee(this.getSession(),"sessionStartTime",null)}getSessionExpiryTime(){return Ee(this.getSession(),"sessionExpiryTime",null)}getSessionMaxTime(){return Ee(this.getSession(),"sessionMaxTime",null)}getSession(){return xe.get(Y)}geCustomIdentifiersToTrack(){return Ee(this.getSession(),"customIdentifiersToTrack",[])||[]}generateSessionKey(){return(0,ct.v4)()}startNewSession(e){this.removeCurrentSource();var t=this.getNumberOfSessions();t={sessionKey:this.generateSessionKey(),sessionStartTime:(new Date).toISOString(),sessionMaxTime:e.configs.sessionInactiveDuration,customIdentifiersToTrack:e.configs.sourceExtraParams,sessionExpiryTime:(new Date).getTime()+1e3*e.configs.sessionInactiveDuration,numberOfSessions:++t},xe.set(Y,t)}extendSession(){const e=this.getSession();e&&(e.sessionExpiryTime=(new Date).getTime()+1e3*e.sessionMaxTime,xe.set(Y,e))}handleBrowserInactivity(e){"hidden"===e&&ye.set("wasBrowserInactive",!0)}isWindowActive(){return!!ye.get("isWindowActive")}getNumberOfSessions(){return Ee(xe.get(Y),"numberOfSessions")||0}}dt.NON_INTERACTIVE_EVENTS=[d,h,d,E];class gt{constructor(e,t,n){this.os="web",this.osPlatform=e.userAgent,this.isMobile=Ke(),this.os=Ke()?"mweb":"web",this.name=gt.getBrowserName(e.userAgent,t),this.isIncognito=n}static getInstance(){return function(e,t,n,i){return new(n=n||Promise)((function(t,a){function r(e){try{s(i.next(e))}catch(e){a(e)}}function o(e){try{s(i.throw(e))}catch(e){a(e)}}function s(e){var i;e.done?t(e.value):((i=e.value)instanceof n?i:new n((function(e){e(i)}))).then(r,o)}s((i=i.apply(e,[])).next())}))}(this,0,void 0,(function*(){if(null!=ye.get(t))return ye.get(t);var e=yield gt.isIncognito(window),n=new gt(navigator,document,e);return ye.set(t,n),(e=xe.get(r.BROWSER_DETAILS))&>.isBrowserUpdated(e,n)||xe.set(t,n),n}))}static isIncognito(e){const t=e.RequestFileSystem||e.webkitRequestFileSystem;return new Promise((n=>{t?t(e.TEMPORARY,100,(()=>{n(!1)}),(()=>{n(!0)})):n(!1)}))}static getBrowserName(e,t){return-1!==e.indexOf("MSIE")||1==t.documentMode?gt.BROWSER_NAMES.INTERNET_EXPLORER:-1<e.indexOf("Edg")?gt.BROWSER_NAMES.EDGE:-1<e.indexOf("OPR")||-1<e.indexOf("Opera")?gt.BROWSER_NAMES.OPERA:-1<e.indexOf("Chrome")||e.match(/\b(?:crmo|crios)\/([\w\.]+)/i)?-1<e.indexOf("MMS")?gt.BROWSER_NAMES.OPERA_NEON:gt.BROWSER_NAMES.CHROME:-1<e.indexOf("Safari")?gt.BROWSER_NAMES.SAFARI:-1<e.indexOf("Firefox")?gt.BROWSER_NAMES.FIREFOX:gt.BROWSER_NAMES.OTHERS}static isBrowserUpdated(e,t){return Je(e,t)}isWebPushCompatible(){return this.isChrome()||this.isFirefox()||this.isOpera()||this.isSafari()||this.isEdge()}isChrome(){return this.name===gt.BROWSER_NAMES.CHROME}isFirefox(){return this.name===gt.BROWSER_NAMES.FIREFOX}isOpera(){return this.name===gt.BROWSER_NAMES.OPERA||this.name===gt.BROWSER_NAMES.OPERA_NEON}isSafari(){return this.name===gt.BROWSER_NAMES.SAFARI}isEdge(){return this.name===gt.BROWSER_NAMES.EDGE}static isIOS(){return!(!navigator.userAgent.match(/iPad/i)&&!navigator.userAgent.match(/iPhone/i))}}(lt=(lt=gt=gt||{}).BROWSER_NAMES||(lt.BROWSER_NAMES={})).CHROME="Google Chrome",lt.FIREFOX="Mozilla Firefox",lt.OPERA="Opera",lt.OPERA_NEON="Opera Neon",lt.SAFARI="Apple Safari",lt.INTERNET_EXPLORER="Internet Explorer",lt.EDGE="Edge",lt.OTHERS="Others";const ut=gt;class pt{constructor(e,t){this.key=e,this.value=t}static equal(e,t){return e.key===t.key&&JSON.stringify(e.value)===JSON.stringify(t.value)}}let ht=null;class mt{constructor(e){this.attributes=[],this.subscribedToOldSdk=!1,null==e?(this.deviceUuid=(0,ct.v4)(),this.attributes=[],this.deviceAdded=!1):(this.deviceUuid=Ee(e,"deviceUuid",(0,ct.v4)()),this.attributes=Ee(e,"attributes",[]),this.deviceAdded=Ee(e,"deviceAdded",!1))}addAttribute(e){const t=mt.baseLogTag+".addAttribute";return new Promise((n=>{e.key=mt.getMorphedKey(e.key);let i=-1;for(let t=this.attributes.length-1;0<=t;t--)e.key===this.attributes[t].key&&(i=t);at.log(2,t,"Adding attribute:",e),0<=i?(this.attributes[i].value,e.value,this.attributes[i].value=e.value):this.attributes.push(e),this.save().then((()=>{n(!0)}))}))}static getLocalUser(){const e=mt.baseLogTag+".getLocalUser";return new Promise((t=>{var n;xe.get(r.USER_DATA)?(at.log(2,e,"Found user in localstorage"),n=xe.get(r.USER_DATA),t(new mt(n))):t(null)}))}static getCookieUser(){return new Promise((e=>{var t=mt.baseLogTag+".getLocalUser";ke.get(r.USER_DATA)?(at.log(2,t,"Found user in cookie"),t=ke.get(r.USER_DATA),e(new mt(t))):e(null)}))}static getMigrationUser(){const e=mt.baseLogTag+".getLocalUser";return new Promise((t=>{var n=localStorage.getItem(r.OLD_SDK.USER_DATA);if(n)try{var i=JSON.parse(n);if(i.is_new_sdk_migrated)t(null);else{const e=new mt({deviceAdded:Ee(i,"device_add",!1),deviceUuid:Ee(i,"uuid",(0,ct.v4)())}),n=Ee(i,"user_attrs",{});for(const t in n)n.hasOwnProperty(t)&&e.attributes.push(new pt(t,n[t]));var a=localStorage.getItem(r.OLD_SDK.PUSH_TOKEN);null!=a&&"NA"!==a&&"null"!==a&&(e.subscribedToOldSdk=!0),t(e)}}catch(n){at.error(1,e,"Error getting the migration user. Resolving as a new user."),at.error(1,e,n),t(null)}else t(null)}))}static getSync(){return mt.instance}static get(){const e=mt.baseLogTag+".get";return null!=ht||(ht=new Promise((t=>{ut.getInstance().then((n=>{zt.getWebSDKSettings().then((n=>{var i=mt.getLocalUser(),a=n.isDomainLevelStorage?mt.getCookieUser():"resolved";n=mt.getMigrationUser(),Promise.all([i,a,n]).then((n=>{const i=n[0],a=n[1],o=n[2];o?o.save().then((n=>{var i=localStorage.getItem(r.OLD_SDK.USER_DATA);if(i){const e=JSON.parse(i);e.is_new_sdk_migrated=!0,localStorage.setItem(r.OLD_SDK.USER_DATA,JSON.stringify(e))}at.log(1,e,"User resolved from older SDK: ",n),t(n)})):a&&"resolved"!==a?(at.log(1,e,"User resolved from cookie: ",a),a.save().then((e=>{t(e)}))):(at.log(1,e,"Local user: ",i),new mt(i).save().then((e=>{t(e)})))})).catch((t=>{at.log(1,e,"Error in fetching/creating user",t)}))})).catch((t=>{at.error(1,e,"Error in getting Web SDK Settings. This might indicate that the App is blocked.")}))}))}))),ht}static logout(){return new Promise((e=>{ht=null,e(!(this.instance=null))}))}save(){mt.baseLogTag,mt.isAmpEnabled()&&(this.deviceUuid=ke.get("moe_uuid")),xe.get("WEB_SETTINGS");var e=xe.get(r.WEB_SETTINGS);return null!=e&&e.configs.isWebPersonalisationModuleEnabled&&(this.deviceUuid=this.deviceUuid||window.MoeWebP.deviceUuid),mt.instance=this,new Promise((e=>{xe.set(r.USER_DATA,this),ke.setRaw(X,mt.instance.deviceUuid),e(this)}))}static isAmpEnabled(){const e=ke.get(X);return e&&e.includes("amp")}getAttribute(e){let t=null;return e=mt.getMorphedKey(e),this.attributes.map((n=>{n.key===e&&(t=n.value)})),t}indexOfAttribute(e){let t=-1;return e=mt.getMorphedKey(e),this.attributes.map(((n,i)=>{n.key===e&&(t=i)})),t}static getMorphedKey(e){switch(e){case"id":e=I;break;case"email":e=A;break;case"name":e=w;break;case"first_name":e=D;break;case"last_name":e=C;break;case"mobile":e=O;break;case"gender":e=P;break;case"birthday":e=R}return e}}mt.baseLogTag="UserModel",mt.isResolved=!1,mt.instance=null;class ft{constructor(){var e=ft.baseLogTag+".constructor";const t=void 0;let n=mt.getSync().getAttribute("id");n=n?n.toString():void 0;const i=window.analytics;let a,r;if(i){r=i._VERSIONS;try{a=i.user().anonymousId()}catch(t){at.error(1,e,"Error getting anonymous id from segment api",t)}}this.c=void 0,this.h="",this.identifiers=void 0,(n||a)&&(this.identifiers={moe_user_id:n,segment_id:a}),this.meta={bid:(0,ct.v4)(),segmentSdkData:i?r:void 0}}}ft.baseLogTag="ReportPostData";class vt{constructor(e,t,n){vt.baseLogTag,this.type=e,this.getParams=t,this.event=n,this.postData=new ft;const i={},a={};for(const e of n.attributes)if(e&&null!=e.key&&(this.status=vt.STATUS.VALID,null!=e.value))if("function"==typeof e.value.getMonth){const t={};t[e.key]=Math.round(e.value.getTime()-6e4*e.value.getTimezoneOffset()),null==a.timestamp&&(a.timestamp=[]),a.timestamp.push(t)}else i[e.key]=e.value;this.postData.e=n.name,this.postData.a=i,this.postData.c=Be(a)?void 0:a,window&&window.location&&null!=window.location.href&&(this.postData.url=window.location.href)}}vt.baseLogTag="ReportClass",(lt=(Ui=vt=vt||{}).STATUS||(Ui.STATUS={}))[lt.INVALID=0]="INVALID",lt[lt.VALID=1]="VALID",(Ui=Ui.REPORT_ADD_TYPE||(Ui.REPORT_ADD_TYPE={}))[Ui.USER_ATTRIBUTE=0]="USER_ATTRIBUTE",Ui[Ui.EVENT=1]="EVENT";const St=vt;function Et(e,t){return`\n <div id='chrome_desktop_backend' style='z-index: 999999999;position: fixed;height: 100%;top: 0px;left: 0px;width: 100%;background: rgba(0, 0, 0, 0.89);'>\n ${e}\n ${!t&&'\n <a href="#" target="_blank"\n style="text-decoration: none !important;cursor: pointer !important;color:#A5A0A0 !important;font-size: 11px !important;bottom: 0px;left: 10px;position: absolute;"\n onclick="window.open(\'https://moengage.com/web-push/?utm_source=moengage_branding&utm_medium=webpush\',\'_blank\');event.cancelBubble = true; if (event.stopPropagation) event.stopPropagation();return false;">\n Powered by <img src="https://app-cdn.moengage.com/images/brand/logo_full_white.png"\n style="max-width: 100% !important; height: 35px !important;vertical-align: middle !important; padding-right: 3px !important;"></a>\n '}\n </div>\n `}function yt(e,t){return`\n <div id='chrome_mobile_backend' style='z-index: 999999999;position: fixed;height: 100%;top: 0px;left: 0px;width: 100%;background: rgba(0, 0, 0, 0.798039);'>\n ${e}\n ${!t&&'\n <a href="#" target="_blank"\n style="text-decoration: none !important;cursor: pointer !important;color:#A5A0A0 !important;font-size: 11px !important;left: 0px;bottom: 23%;position: absolute;"\n onclick="window.open(\'https://moengage.com/web-push/?utm_source=moengage_branding&utm_medium=webpush\',\'_blank\');event.cancelBubble = true; if (event.stopPropagation) event.stopPropagation();return false;">\n Powered by <img src="https://app-cdn.moengage.com/images/brand/logo_full_white.png"\n style="max-width: 100% !important; height: 35px !important;vertical-align: middle !important; padding-right: 3px !important;"></a>\n '}\n </div>\n `}const bt=class{constructor(e){this.isBeaconDisabled=this.parseSentryBooleanFlag(Ee(e,"b_d",!1)),this.isCardsModuleEnabled=this.parseSentryBooleanFlag(Ee(e,"c_s",!1)),this.isWebPersonalisationModuleEnabled=this.parseSentryBooleanFlag(Ee(e,"c_w_p_e",!1)),this.eventBatchCount=Ee(e,"e_b_c",10),this.logLevel=Ee(e,"log_level"),this.shouldSendUID=this.parseSentryBooleanFlag(Ee(e,"o_u_e",!1)),this.periodicFlushTime=Ee(e,"p_f_t",30),this.isBatchingEnabled=this.parseSentryBooleanFlag(Ee(e,"s_e_b_e",!1)),this.sessionInactiveDuration=Ee(e,"s_i_d",1800),this.isRemoteLoggingEnabled=this.parseSentryBooleanFlag(Ee(e,"s_log",!1)),this.sourceExtraParams=Ee(e,"src_ext",[]),this.whitelistedEvents=Ee(e,"w_e",[]),this.blacklistedEvents=Ee(e,"b_e",[]),this.isAppActive=this.parseSentryBooleanFlag(Ee(e,"a_s",!0)),this.remoteLogTracking=this.isRemoteLoggingEnabled&&!!this.logLevel}parseSentryBooleanFlag(e="blocked"){return"allowed"===e||!0===e||"true"===e}};class _t{constructor(){this.settingsVersion="V1",this.isDomainLevelStorage=!1,this.isConfigured=!1,this.isPushSubBilling=!1,this.platformSettings=new Dt,this.optInConfig=new Tt,this.configs=new bt({})}static parseOldSettings(e){const t=_t.baseLogTag+".parseOldSettings",n=new _t;if((n.oldWebData=e).webData&&!Be(e.webData))if(n.isConfigured=!0,e=e.webData,n.configs=new bt(e),n.settingsVersion=Ee(e,"wp_settings_version","V1"),"V2"===n.settingsVersion)n.isDomainLevelStorage=Ee(e,"domain_level_storage",!1),n.isPushSubBilling=Ee(e,"sub_billing",!1),n.platformSettings.chrome.domainType=Ee(e,"is_enabled",!1)?"https":"na",n.platformSettings.chrome.subscriptionMode=Ee(e,"web_push_platform_data.chrome.subscription_mode","vapid"),n.platformSettings.chrome.vapidPublicKey=Ee(e,"web_push_platform_data.chrome.vapid_public_key",null),n.platformSettings.firefox.subscriptionMode=Ee(e,"web_push_platform_data.firefox.subscription_mode","vapid"),n.platformSettings.firefox.vapidPublicKey=Ee(e,"web_push_platform_data.firefox.vapid_public_key",null),n.optInConfig.reappearTime=Ee(e,"prompt_again",24),n.optInConfig.type={"1-step":"ONE_CLICK","2-step":"TWO_STEP","self-handled":"SELF_HANDLED"}[Ee(e,"opt_in_type","2-step")],n.optInConfig.showOverlay=Ee(e,"show_overlay",!1),n.optInConfig.loadTime=Ee(e,"load_time",0),n.optInConfig.type!==Tt.TYPE.SELF_HANDLED&&function(e,t,n){return t===Tt.TYPE.ONE_CLICK&&n?function(e,t){return function(e,t,n,i){return new(n=n||Promise)((function(t,a){function r(e){try{s(i.next(e))}catch(e){a(e)}}function o(e){try{s(i.throw(e))}catch(e){a(e)}}function s(e){var i;e.done?t(e.value):((i=e.value)instanceof n?i:new n((function(e){e(i)}))).then(r,o)}s((i=i.apply(e,[])).next())}))}(this,0,void 0,(function*(){let n="",i="";const a=yield ut.getInstance();return n=a.isFirefox()?(i=Et(`\n <div class="moe_firefox" style="display:none;">\n <div style='position:relative;top: 200px;left: 400px;height: 100px;width: 180px;color: white;font-size: larger;'>\n ${e.firefox.desktop.text}\n </div>\n <div\n style="position:relative;top: 45px;left: 300px;width: 80px;height: 80px;color: white;background-size: contain;transform: rotate(180deg);background-image: url('https://cdn.moengage.com/images/pointdown.png');background-repeat: no-repeat;">\n </div>\n </div>\n `,t),yt(`\n <div class='moe_firefox' style="display:none;height:100%;">\n <div style='position:relative;top: 15%;left: 23%;height: 100px;width: 150px;color: white;font-size: larger;'>\n ${e.firefox.mobile.text}\n </div>\n <div\n style="position:relative;top: 5%;left: 240px;width: 80px;height: 80px;color: white;background-size: contain;background-image: url('https://cdn.moengage.com/images/pointdown.png');background-repeat: no-repeat;">\n </div>\n </div>\n `,t)):a.isOpera()?(i=Et(`\n <div class="moe_opera" style="display:none;">\n <div style='position:relative;top: 240px;left: 40%;height: 100px;width: 180px;color: white;font-size: larger;'>\n ${e.opera.desktop.text}\n </div>\n <div\n style="position:relative;top: 45px;left: 55%;width: 80px;height: 80px;color: white;background-size: contain;transform: rotate(180deg) scaleX(-1);background-image: url('https://cdn.moengage.com/images/pointdown.png');background-repeat: no-repeat;">\n </div>\n </div>\n `,t),yt(`\n <div class='moe_opera' style="display:none;height:100%;">\n <div style='position:relative;top: 15%;left: 23%;height: 100px;width: 150px;color: white;font-size: larger;'>\n ${e.opera.mobile.text}\n </div>\n <div\n style="position:relative;top: 5%;left: 240px;width: 80px;height: 80px;color: white;background-size: contain;background-image: url('https://cdn.moengage.com/images/pointdown.png');background-repeat: no-repeat;">\n </div>\n </div>\n `,t)):(i=Et(`\n <div class="moe_chrome" style="display:none;">\n <div style='position:relative;top: 200px;left: 400px;height: 100px;width: 180px;color: white;font-size: larger;'>\n ${e.chrome.desktop.text}\n </div>\n <div\n style="position:relative;top: 30px;left: 300px;width: 80px;height: 80px;color: white;background-size: contain;transform: rotate(180deg);background-image: url('https://cdn.moengage.com/images/pointdown.png');background-repeat: no-repeat;">\n </div>\n </div>\n `,t),yt(`\n <div class='moe_chrome' style="display:none;height:100%;">\n <div style='position:relative;top: 15%;left: 23%;height: 100px;width: 150px;color: white;font-size: larger;'>\n ${e.chrome.mobile.text}\n </div>\n <div\n style="position:relative;top: 5%;left: 240px;width: 80px;height: 80px;color: white;background-size: contain;background-image: url('https://cdn.moengage.com/images/pointdown.png');background-repeat: no-repeat;">\n </div>\n </div>\n `,t)),{mobileUI:n,webUI:i}}))}(Ee(e,"overlay",null),Ee(e,"hide_moe_branding",!1)).then((e=>e)):t===Tt.TYPE.TWO_STEP?new Promise((t=>{t(function(e,t){var{web:n,mobile:e}=e,n=`\n <div id="desktopBannerWrapped" data-rapid_height="50"\n style="width: 422px; top: 1px; left: calc(50% - 211px); margin: 0px; padding: 0px; box-shadow: rgb(136, 136, 136) 0px 0px 4px; font-size: 11px; font-weight: 400; position: fixed; z-index: 2147483647; background: ${n.banner.background_color};">\n <div style="margin: 0;padding: 0 20px 10px;word-spacing: normal!important;letter-spacing: normal!important;font-family: Open Sans,sans-serif!important;">\n <div\n style="float: left;position: relative;display: inline-block;margin: 15px 15px 0 0!important;padding: 0!important;word-spacing: normal!important;letter-spacing: normal!important;font-family: Open Sans,sans-serif!important;">\n <img style="word-spacing: normal!important;letter-spacing: normal!important;font-family: Open Sans,sans-serif!important;height: 65px!important;width: 65px!important;" src="${n.banner.icon}">\n </div>\n <div style="word-spacing: normal!important;letter-spacing: normal!important;font-family: Open Sans,sans-serif!important;position: relative!important;padding: 10px 0 0!important;color: #000!important;text-align: left!important;margin: 0!important;line-height: 1.4em!important;display: inline-block!important;width: calc(100% - 80px)!important;">\n <span style="margin-bottom: 5px; text-align: left; font-size: 14px; font-weight: 700; overflow: hidden; height: 2.8em; line-height: 1.4em; display: block; font-family: Open Sans, sans-serif !important; word-spacing: normal !important; letter-spacing: normal !important; color: ${n.banner.title.text_color+" !important"};">\n ${n.banner.title.text}\n </span>\n <p style="overflow: hidden; height: 2.8em; word-spacing: normal !important; letter-spacing: normal !important; font-family: Open Sans, sans-serif !important; font-size: 12px !important; line-height: 1.4em !important; margin: 10px 0px !important; padding: 0px !important; text-align: left !important; color: ${n.banner.body.text_color+" !important"};">\n ${n.banner.body.text}\n </p>\n </div>\n <div\n style="display: flex;justify-content: space-between;word-spacing: normal!important;letter-spacing: normal!important;font-family: Open Sans,sans-serif!important;">${t?"":`<div style="margin-top: 0.5em;">\n <a href="https://moengage.com/?utm_source=Journey&utm_medium=soft_ask" target="_blank" style="word-spacing: normal !important; letter-spacing: normal !important; font-family: Open Sans, sans-serif !important; text-decoration: none !important; font-size: 10px !important; line-height: 1.2em !important; font-weight: 400 !important; color: ${n.logo.logo_color+" !important"};">\n Powered by <span style="text-decoration: none;word-spacing: normal!important;letter-spacing: normal!important;font-family: Open Sans,sans-serif!important;"><img id="moeBannerLogoweb" src="https://app-cdn.moengage.com/images/brand/logo-blue.png" style="width: 6.5em;"></span>\n </a>\n </div>`}\n <div style="word-spacing: normal!important;letter-spacing: normal!important;font-family: Open Sans,sans-serif!important;margin: 0!important;padding: 0!important;margin-left: auto !important;">\n <button id="moe-dontallow_button" style="overflow: hidden; word-spacing: normal !important; letter-spacing: normal !important; width: 100px !important; height: 26px !important; font-size: 14px !important; cursor: pointer !important; line-height: 1.1em !important; border-radius: 4px !important; border: 1px solid rgba(0, 0, 0, 0.1) !important; display: inline-block !important; font-weight: 400 !important; margin: 0px 20px 0px 0px !important; padding: 5px !important; text-transform: none !important; box-sizing: border-box !important; text-shadow: none !important; box-shadow: none !important; white-space: nowrap !important; color: ${n.dismiss_button.text_color}; background: ${n.dismiss_button.background_color};">\n ${n.dismiss_button.text}\n </button>\n <button\n style="overflow: hidden; word-spacing: normal !important; letter-spacing: normal !important; width: 90px !important; height: 26px !important; font-size: 14px !important; cursor: pointer !important; line-height: 1.1em !important; border-radius: 4px !important; border: 1px solid rgba(0, 0, 0, 0.1) !important; display: inline-block !important; font-weight: 400 !important; margin: 0px !important; padding: 5px !important; text-transform: none !important; box-sizing: border-box !important; text-shadow: none !important; box-shadow: none !important; white-space: nowrap !important; color: ${n.allow_button.text_color}; background: ${n.allow_button.background_color};" id="optInText">\n ${n.allow_button.text}\n </button>\n </div>\n </div>\n </div>\n </div>\n `;return{mobileUI:`\n <div id="mobileBannerWrapped" class="moe-mobile-box" style="position: fixed; top: 0px; left: 0px; width: 100%; box-shadow: rgb(51, 51, 51) 0px 5px 10px -5px; z-index: 2147483647; font-family: Helvetica Neue, Helvetica, Arial, Roboto, sans-serif, sans-serif; background: ${e.nudge.background_color};">\n <div class="moe-logo-text" style="box-sizing: border-box;padding: 10px !important;float: left !important;width: 100% !important">\n <img alt="" height="40px" width="40px" style="box-sizing: border-box;width: 40px !important;height: 40px !important;float: left !important" src="${e.nudge.icon}">\n <span style="box-sizing: border-box; width: calc(100% - 40px); overflow: hidden; height: 2.4em; float: left !important; word-break: break-word !important; font-weight: 400 !important; line-height: 1.2em !important; font-size: 17px !important; text-align: left !important; padding: 0px 0px 0px 10px !important; font-family: Helvetica Neue, Helvetica, Arial, Roboto, sans-serif, sans-serif !important; color:${e.nudge.title.text_color+" !important"}">\n ${e.nudge.title.text}\n </span>\n </div>\n <div class="moe-buttons-panel" style="box-sizing: border-box;text-align: right;padding: 0 10px !important;float: left;width: 100% !important;margin-top: 5px;margin-bottom: 3px">\n <div style="width: 100%;box-sizing: border-box">\n <button id="moe-dontallow_button" class="moe-mobile-button-outline" style="box-sizing: border-box; font-size: 14px !important; display: inline-block !important; text-transform: none !important; height: 34px !important; font-weight: 400 !important; line-height: 1.2em !important; font-family: Helvetica Neue, Helvetica, Arial, Roboto, sans-serif, sans-serif !important; padding: 0px 5px !important; width: 120px !important; border-radius: 2px !important; border: 1px solid rgba(0, 0, 0, 0.1) !important; margin: 0px 5px 0px 0px !important; color: ${e.dismiss_button.text_color}; background: ${e.dismiss_button.background_color};">\n <div style="height: 1.2em; line-height: 1.2em; overflow: hidden; color: ${e.dismiss_button.text_color}; background: ${e.dismiss_button.background_color};">\n ${e.dismiss_button.text}\n </div>\n </button>\n <button class="moe-mobile-button-fill" style="box-sizing: border-box; font-size: 14px !important; display: inline-block !important; text-transform: none !important; height: 34px !important; font-weight: 400 !important; line-height: 1.2em !important; font-family: Helvetica Neue, Helvetica, Arial, Roboto, sans-serif, sans-serif !important; padding: 0px 5px !important; width: 120px !important; border-radius: 2px !important; border: 1px solid rgba(0, 0, 0, 0.1) !important; margin: 0px !important; color: ${e.allow_button.text_color}; background: ${e.allow_button.background_color};" id="optInText">\n <div style="height: 1.2em; line-height: 1.2em; overflow: hidden; color: ${e.allow_button.text_color}; background: ${e.allow_button.background_color};">\n ${e.allow_button.text}\n </div>\n </button>\n </div>\n </div>${t?"":`<div style="float: left;margin-top: -2.25em;">\n <a href="https://moengage.com/?utm_source=Journey&utm_medium=soft_ask" target="_blank" style="word-spacing: normal !important; letter-spacing: normal !important; font-family: Open Sans, sans-serif !important; text-decoration: none !important; font-size: 10px !important; line-height: 1.2em !important; font-weight: 400 !important; color: ${e.logo.logo_color+" !important"};">\n Powered by <span style="text-decoration: none;word-spacing: normal!important;letter-spacing: normal!important;font-family: Open Sans,sans-serif!important;">\n <img id="moeBannerLogomobile" src="https://app-cdn.moengage.com/images/brand/logo-blue.png" style="width: 6.5em;">\n </span>\n </a>\n </div>`}\n </div>\n `,webUI:n}}(Ee(e,"opt_in_preview",null),Ee(e,"hide_moe_branding",!1)))})):void 0}(e,n.optInConfig.type,n.optInConfig.showOverlay).then((e=>{n.optInConfig.softAskConfig.desktop.customHTML=e.webUI,n.optInConfig.softAskConfig.mobile.customHTML=e.mobileUI})).catch((e=>{at.error(2,t,"Failed to construct overlay for hard ask",e)}));else{"false"===Ee(e,"domain_level_storage",!1)?n.isDomainLevelStorage=!1:n.isDomainLevelStorage=!(!Ee(e,"domain_level_storage",!1)&&"true"!==Ee(e,"domain_level_storage",!1));let i=Ee(e,"PushSubBilling",!1);"false"===i?i=!1:"true"===i&&(i=!0),(e=>"boolean"==typeof e)(i)||(i=!1),n.isPushSubBilling=i,n.platformSettings.chrome.domainType=Ee(e,"webPushPlatformData.chrome.domain_type",""),n.platformSettings.chrome.subscriptionMode=Ee(e,"webPushPlatformData.chrome.subscriptionMode","normal"),n.platformSettings.chrome.vapidPublicKey=Ee(e,"webPushPlatformData.chrome.vapidPublicKey",null),n.platformSettings.firefox.enabled=!0,n.platformSettings.firefox.subscriptionMode=Ee(e,"webPushPlatformData.firefox.subscriptionMode","normal"),n.platformSettings.firefox.vapidPublicKey=Ee(e,"webPushPlatformData.firefox.vapidPublicKey",null),n.platformSettings.safari.websitePushId=Ee(e,"webPushPlatformData.safari.websitePushId",null),null==n.platformSettings.safari.websitePushId?n.platformSettings.safari.enabled=!1:n.platformSettings.safari.enabled=!0,n.optInConfig.reappearTime=parseInt(Ee(e,"promptAgain",24)),Ee(e,"call_push_moengage",!0)?Ee(e,"banner.banner_flag",null)?n.optInConfig.type=Tt.TYPE.TWO_STEP:n.optInConfig.type=Tt.TYPE.ONE_CLICK:(n.optInConfig.type=Tt.TYPE.SELF_HANDLED,n.optInConfig.reappearTime=0),n.optInConfig.showOverlay=Ee(e,"show_overlay",!1),n.optInConfig.loadTime=Ee(e,"load_time",0),n.optInConfig.softAskConfig.desktop.customHTML=Ee(e,"bannerHtml.web",null),n.optInConfig.softAskConfig.mobile.customHTML=Ee(e,"bannerHtml.mweb",null),Ne.get().disableCookies&&(n.isDomainLevelStorage=!1,at.warn(2,t,"Cookies Storage Been Disabled"))}else n.isConfigured=!1;return n}}_t.baseLogTag="SdkSettings";class Tt{constructor(){this.type=Tt.TYPE.NA,this.reappearTime=24,this.softAskConfig={desktop:new It,mobile:new It}}}class It{constructor(){this.customHTML=null}}(Ui=(Ui=Tt=Tt||{}).TYPE||(Ui.TYPE={})).NA="NA",Ui.ONE_CLICK="ONE_CLICK",Ui.TWO_STEP="TWO_STEP",Ui.SELF_HANDLED="SELF_HANDLED";class At{constructor(){this.enabled=!1,this.websitePushId=null}}class wt{constructor(){this.enabled=!1,this.isServiceWorkerRoot=!0,this.serviceWorkerFilename="serviceworker.js",this.subscriptionMode="normal",this.vapidPublicKey=null,this.domainType=""}}(Ui=(Ui=wt=wt||{}).DOMAIN_TYPE||(Ui.DOMAIN_TYPE={})).NA="NA",Ui.HTTPS="https",Ui.MUTLI="multi";class Dt{constructor(){this.safari=new At,this.chrome=new wt,this.firefox=new wt}}const Ct=_t;var Ot=function(e,t,n,i){return new(n=n||Promise)((function(a,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function s(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?a(e.value):((t=e.value)instanceof n?t:new n((function(e){e(t)}))).then(o,s)}l((i=i.apply(e,t||[])).next())}))};class Pt{static initStore(){return Ot(this,void 0,void 0,(function*(){return null==Pt.ready&&(Pt.offlineDataStore=Se.createInstance({driver:[Se.INDEXEDDB,Se.WEBSQL,Se.LOCALSTORAGE],name:"moe_database",storeName:te.NAME}),Pt.ready=Promise.resolve(Pt.offlineDataStore.ready())),yield Pt.ready}))}static initialize(){return Ot(this,void 0,void 0,(function*(){yield Pt.initStore()}))}}class Rt{constructor(e){this.EVENT_ACTION=e.event.name,this.EVENT_ATTRS=Lt(e.event.attributes),this.EVENT_G_TIME=(new Date).getTime().toString(),this.EVENT_L_TIME=Xe(),this.EVENT_ATTRS_CUST=e.postData.c,this.N_I_E=e.postData.nie}}Rt.baseLogTag="ReportAddViewEvent";const Lt=e=>{const t={};return e.forEach((e=>{t[e.key]=e.value})),t};class Nt{static visibilityChange(){"hidden"===document.visibilityState&&(Nt.windowClosed||Wt.reactToTriggerEvents())}static beforeUnload(){Nt.windowClosed=!0,Wt.sendBeacon()}static removeEventListeners(){document.removeEventListener("visibilitychange",Nt.visibilityChange,!1),window.removeEventListener("beforeunload",Nt.beforeUnload,!1)}static addListeners(){document.addEventListener("visibilitychange",Nt.visibilityChange,!1),window.addEventListener("beforeunload",Nt.beforeUnload,!1)}}Nt.windowClosed=!1;const kt=Nt;function Mt(e,t){try{var n=Ve();return!(null==e||!e.configs.isBatchingEnabled||("web"!==n||t.name!==ut.BROWSER_NAMES.CHROME&&t.name!==ut.BROWSER_NAMES.EDGE&&t.name!==ut.BROWSER_NAMES.OPERA)&&("mobile"!==n||ut.isIOS()||t.name!==ut.BROWSER_NAMES.CHROME&&t.name!==ut.BROWSER_NAMES.OPERA)||!navigator.sendBeacon)}catch(e){at.error(1,"Utils.batching.isBatchingSupported",e)}}class xt{static getRemoteLogsBatchRequestOptions(e){return new Promise((t=>{zt.collectGetParams().then((n=>{n={query_params:Object.assign(Object.assign({},n),{unique_id:n.unique_id,os:"web"===n.os?"Web":"mWeb"}),logs:[...e]},t(n)}))}))}static sendBatchOfLogs(e){const t=zt.baseLogTag+".sendBatchOfLogs";return new Promise(((n,i)=>{xt.getRemoteLogsBatchRequestOptions(e).then((i=>{var a=(a=Ne.get()).baseDomainName+ue+i.query_params.os.toLowerCase()+"/"+a.appId;ot.post(a,{postData:i}).then((()=>{at.log(1,t,"[sendBatchOfLogs] batch payload: "+JSON.stringify(e)),at.log(1,t,"Batch Remote Logs sent to MoEngage successfully"),xt.batchRemoteLogsApiRetries=1,n(!0)})).catch((n=>{at.log(1,t,"Batch Remote Logs API failed",n),this.handleRemoteLogsFailure(e)}))}))}))}static handleRemoteLogsFailure(e){var t=zt.baseLogTag+".handleRemoteLogsFailure";at.log(1,t,"Retry Batch Logs Failed API",xt.batchRemoteLogsApiRetries),xt.batchRemoteLogsApiRetries<3&&setTimeout((()=>{xt.batchRemoteLogsApiRetries++,xt.sendBatchOfLogs(e)}),3e3*xt.batchRemoteLogsApiRetries)}static sendBeacon(e){xt.getRemoteLogsBatchRequestOptions(e).then((e=>{var t=(t=Ne.get()).baseDomainName+ue+e.query_params.os.toLowerCase()+"/"+t.appId+"?"+(new Date).getTime();at.log(1,"RemoteLogsApi.sendBeacon","[sendBeacon] Remote Logs batch payload: "+JSON.stringify(e)),navigator.sendBeacon(t,JSON.stringify(e))}))}}xt.batchRemoteLogsApiRetries=1;class Bt{static updateEventStore(){Ve()!==fe.TV&&Se.createInstance({driver:[Se.INDEXEDDB,Se.WEBSQL,Se.LOCALSTORAGE],name:"moe_tracking",storeName:J}).setItem(J,Bt.reports)}static spliceReports(e=Bt.reports.length){return e=Bt.reports.splice(0,e),Bt.updateEventStore(),e}static spliceRemoteLogs(e=Bt.remoteLogs.length){return Bt.remoteLogs.splice(0,e)}static shouldCreateNewBatch(){return!Bt.lastbatchCreatedAt||(new Date).getTime()-Bt.lastbatchCreatedAt>=ie}static shouldCreateNewBatchForRemoteLogs(){return!Bt.lastRemoteLogsbatchCreatedAt||(new Date).getTime()-Bt.lastRemoteLogsbatchCreatedAt>=ie}static reactToTriggerEvents(){var e=Bt.baseLogTag+".reactToTriggerEvents";0<Bt.reports.length&&Bt.shouldCreateNewBatch()?(at.log(1,e,`Trigger Events: Created Batch of ${Bt.reports.length} reports`,Xe()),Bt.createBatch()):at.log(2,e,Xe()+": No report's to sync for this event."),0<Bt.remoteLogs.length&&Bt.shouldCreateNewBatchForRemoteLogs()?(at.log(1,e,`Trigger Events: Created Batch of remote logs ${Bt.remoteLogs.length} reports`,Xe()),Bt.createRemoteLogsBatch()):at.log(2,e,Xe()+": No logs's to sync for remote logs.")}static periodicSync(e){var t=Bt.baseLogTag+".periodicSync";0<Bt.reports.length&&Bt.shouldCreateNewBatch()?(at.log(1,t,`Periodic sync: Created Batch of ${Bt.reports.length} reports`,Xe()),Bt.createBatch()):at.log(2,t,Xe()+`: No report's to sync at this interval. The next sync will attempt in ${e} seconds`),0<Bt.remoteLogs.length&&Bt.shouldCreateNewBatchForRemoteLogs()?(at.log(1,t,`Periodic sync: Created Batch of remote logs ${Bt.reports.length} reports`,Xe()),Bt.createRemoteLogsBatch()):at.log(2,t,Xe()+`: No report's to sync at this interval for remote logs. The next sync will attempt in ${e} seconds`)}static clearInterval(){clearInterval(Bt.periodicSyncInterval),Bt.lastbatchCreatedAt=null}static init(e){ut.getInstance().then((t=>{(Bt.isOfflineBatchingSupported(t,e)||e.configs.remoteLogTracking)&&(Bt.periodicSyncInterval&&Bt.clearInterval(),Bt.periodicSyncInterval=window.setInterval(Bt.periodicSync.bind(this,e.configs.periodicFlushTime),1e3*e.configs.periodicFlushTime),kt.addListeners())}))}static sendBatch(e){var t=Bt.baseLogTag+".sendBatch";try{zt.sendBatchOfReports(e).then((()=>{Bt.lastbatchCreatedAt=(new Date).getTime()}))}catch(e){at.error(1,t,"Error in sending batch",e)}}static sendRemoteLogs(e){var t=Bt.baseLogTag+".sendRemoteLogs";try{xt.sendBatchOfLogs(e).then((()=>{Bt.lastRemoteLogsbatchCreatedAt=(new Date).getTime()}))}catch(e){at.error(1,t,"Error in sending batch of remote logs",e)}}static createBatch(e){0<Bt.reports.length&&(e=Bt.spliceReports(e),Bt.sendBatch(e))}static createRemoteLogsBatch(e){0<Bt.remoteLogs.length&&(e=Bt.spliceRemoteLogs(e),Bt.sendRemoteLogs(e))}static addReport(e,t){var n=Bt.baseLogTag+".addReport";e=new Rt(e),Bt.reports.push(e),Bt.updateEventStore(),Bt.reports.length===t&&(at.log(1,n,`Created Batch of ${t} reports`,Xe()),Bt.createBatch(t))}static sendBeacon(){var e=Bt.baseLogTag+".sendBeacon";0<Bt.reports.length&&(at.log(1,e,`Window Unload: Created batch of ${Bt.reports.length} reports`,Xe()),zt.sendBeacon(Bt.spliceReports())),0<Bt.remoteLogs.length&&(at.log(1,e,`Window Unload: Created Remote Logs batch of ${Bt.remoteLogs.length} reports`,Xe()),xt.sendBeacon(Bt.spliceRemoteLogs()),Bt.lastRemoteLogsbatchCreatedAt=(new Date).getTime())}static flushReports(){return function(e,t,n,i){return new(n=n||Promise)((function(t,a){function r(e){try{s(i.next(e))}catch(e){a(e)}}function o(e){try{s(i.throw(e))}catch(e){a(e)}}function s(e){var i;e.done?t(e.value):((i=e.value)instanceof n?i:new n((function(e){e(i)}))).then(r,o)}s((i=i.apply(e,[])).next())}))}(this,0,void 0,(function*(){var e=Bt.baseLogTag+".flushReports";try{kt.removeEventListeners(),0<Bt.reports.length&&(at.log(1,e,`Flushed ${Bt.reports.length} reports`,Xe()),Bt.sendBatch(Bt.spliceReports())),0<Bt.remoteLogs.length&&(at.log(1,e,`Flushed ${Bt.remoteLogs.length} remote logs`,Xe()),Bt.sendRemoteLogs(Bt.spliceRemoteLogs()))}catch(t){at.error(1,e,"Error in flushing reports",t)}}))}static isOfflineBatchingSupported(e,t){return Mt(t=t||xe.get(r.WEB_SETTINGS),e)}static addRemoteLogs(e,t=15){var n=Bt.baseLogTag+".addRemoteLogs";Bt.remoteLogs.push(e),Bt.remoteLogs.length===t&&(at.log(1,n,`Created Batch of ${t} reports`,Xe()),Bt.createRemoteLogsBatch(t))}}Bt.baseLogTag="BatchManager",Bt.reports=[],Bt.remoteLogs=[],Bt.lastbatchCreatedAt=null,Bt.lastRemoteLogsbatchCreatedAt=null;const Wt=Bt;class Ut{static getListeners(){return this.listeners}static getTopicListeners(e){return Ee(Ut.topicListeners,e,[])}static addListener(e){Ut.listeners.push(e)}static addTopicListener(e,t){Ut.topicListeners[e]=Ut.getTopicListeners(e),Ut.topicListeners[e].push(t)}static broadcast(e){Ut.listeners.map((t=>{t(e)})),Ee(Ut.topicListeners,e.topic,[]).map((t=>{t(e)}))}static broadcastToWindow(e){window&&window.dispatchEvent(new CustomEvent(e.topic,{detail:{name:e.name,data:e.data||null}}))}static deprecatedSdkCallback(e){window.dispatchEvent(new CustomEvent("MOE_OPT_IN",{detail:e}))}static resetAllListeners(){Ut.listeners=[],Ut.topicListeners={}}}Ut.listeners=[],Ut.topicListeners={};const Ft=Ut;class Ht{constructor(e,t,n=!0){this.name=e,this.attributes=t,this.timestamp=(new Date).getTime(),n&&this.attributes.push(new pt("URL",location.href))}static createUserAttributeEvent(e){return new Promise(((t,n)=>{const i=[],a=e.key;switch(e.key){case"id":e.key=I;break;case"email":e.key=A;break;case"name":e.key=w;break;case"first_name":e.key=D;break;case"last_name":e.key=C;break;case"mobile":e.key=O;break;case"gender":e.key=P;break;case"birthday":e.key=R}i.push(e),mt.get().then((n=>{var r=n.indexOfAttribute("oldUniqueIds");e.key===I&&-1<r&&null!=n.attributes[r].value&&0<n.attributes[r].value.length&&i.push(new pt(L,n.attributes[r].value[n.attributes[r].value.length-1])),e.key!==a&&at.log(2,"Event.createUserAttributeEvent","Key changed to MoE reserved keyname: ",e.key),t(new Ht("EVENT_ACTION_USER_ATTRIBUTE",i,!1))}))}))}static createEvent(e,t,n){return new Promise(((i,a)=>{mt.get().then((a=>function(e,t,n,i){return new(n=n||Promise)((function(t,a){function r(e){try{s(i.next(e))}catch(e){a(e)}}function o(e){try{s(i.throw(e))}catch(e){a(e)}}function s(e){var i;e.done?t(e.value):((i=e.value)instanceof n?i:new n((function(e){e(i)}))).then(r,o)}s((i=i.apply(e,[])).next())}))}(this,0,void 0,(function*(){try{var r=new pt("moe_logged_in_status",!!a.getAttribute("id"));const s=new dt;var o=new pt("moe_first_visit",s.getNumberOfSessions()<=1);t.push(r,o),i(new Ht(e,t,n))}catch(r){at.error(1,"Event.createEvent","Error occurred in create events ",r)}}))))}))}}class Gt{static addEvent(e){Gt.history.push(e),Gt.listeners.forEach((t=>{t(e)}))}static getHistory(){return Gt.history}static addEventListener(e){Gt.listeners.push(e)}static clear(){Gt.history=[]}static clearListeners(){Gt.listeners=[]}}Gt.history=[],Gt.listeners=[];class Kt{static track(e,t,n){const i="MoEngage.event.trackEvent";return new Promise(((a,r)=>function(e,t,n,i){return new(n=n||Promise)((function(t,a){function r(e){try{s(i.next(e))}catch(e){a(e)}}function o(e){try{s(i.throw(e))}catch(e){a(e)}}function s(e){var i;e.done?t(e.value):((i=e.value)instanceof n?i:new n((function(e){e(i)}))).then(r,o)}s((i=i.apply(e,[])).next())}))}(this,0,void 0,(function*(){var r;let o;n=!!n;try{o=yield zt.getWebSDKSettings()}catch(r){return void at.error(1,i,"Error in getting Web SDK Settings. This might indicate that the App is blocked.")}if("string"==typeof e&&e)if(o.configs.blacklistedEvents&&o.configs.blacklistedEvents.includes(e))at.log(1,i,`This event "${e}" is blacklisted. Please contact Moengage team to whitelist it.`),a({error:5001,message:`Event "${e}" is blacklisted.`});else if(!oe.includes(e)||o.configs.whitelistedEvents&&o.configs.whitelistedEvents.includes(e))try{const l=[];if(null==t||null!==t&&t===Object(t)&&"[object Object]"===Object.prototype.toString.call(t)){for(const e in t=null==t?{}:t)t.hasOwnProperty(e)&&l.push(new pt(e,t[e]));const i=new dt;yield i.initiateSessionAndSource(o);const c=yield Ht.createEvent(e,l);Gt.addEvent(c),null!=o&&o.configs.isWebPersonalisationModuleEnabled&&null!==(r=window.MoeWebP)&&void 0!==r&&r.handleInSessionEvent(c),zt.collectGetParams().then((t=>{e===s&&delete t.push_id;const r=new St(St.REPORT_ADD_TYPE.EVENT,t,c);var o={session_id:i.getSessionKey(),start_time:i.getSessionStartTime(),background_initiated:0};const l=[];(t=i.getActiveSource())&&(i.setCurrentSource(t),l.push(t)),r.postData.meta.session=o,l.length&&(r.postData.meta.source=l),i.isNonEventInteractive(c)&&(r.postData.nie=1),zt.reportAdd(r,n).then((()=>{i.isNonEventInteractive(c)||i.extendSession(),a(!0)}))}))}else at.error(1,i,"Event attributes were not passed a key-value pair object for event: ",e),a({error:5002,message:"Event value needs to be a key-value pair object"})}catch(r){at.error(1,i,"Error occurred in tracking events ",r)}else at.log(1,i,`This event "${e}" has not been whitelisted. Please contact Moengage team to whitelist it.`),a({error:5001,message:`Event "${e}" is not whitelisted.`});else at.log(1,i,"Event name not a string or null or empty string:",e),a({error:5001,message:"Event name can not be null"})}))))}}var Vt,jt,Yt=function(e,t,n,i){return new(n=n||Promise)((function(a,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function s(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?a(e.value):((t=e.value)instanceof n?t:new n((function(e){e(t)}))).then(o,s)}l((i=i.apply(e,t||[])).next())}))};class zt{static deviceAdd(){return new Promise(((e,t)=>{const n=Ne.get();return zt.collectGetParams(pe).then((i=>{i={queryParams:i=Object.assign(Object.assign({},i),{url:window.location.href})},ot.post(n.baseDomainName+pe,i).then((()=>{let t=Ve().toUpperCase();t="WEB"===t?"DESKTOP":t,Kt.track(y,{deviceType:t}),mt.get().then((t=>{t.deviceAdded=!0,t.save().then((()=>{Jt.startPeriodicClear(r.Q.REPORT),zt.onDeviceAdd.res(),e(!0)}))}))})).catch((e=>{be.enqueue(r.Q.DEVICE,!0),t(!1)}))}))}))}static reportAdd(e,t){const n=zt.baseLogTag+".reportAdd";return new Promise(((i,a)=>(t=!!t,zt.getWebSDKSettings().then((o=>{o.isPushSubBilling?mt.get().then((o=>{o.deviceAdded?zt.reportAddInternal(e,t).then((()=>{this.sendBroadcast(e),i(!0)})).catch((()=>{a(!1)})):(be.enqueue(r.Q.REPORT,e),at.log(1,n,"Report added to queue as device not added yet:",e.event.name),at.log(2,n,"Event Queued:",e.event.name),e.type===St.REPORT_ADD_TYPE.USER_ATTRIBUTE&&(zt.isPushSubAttributeAccepted(e.event.attributes[0].key)?(at.log(1,n,"Attribute accepted for push sub billing."),zt.deviceAdd()):at.log(2,n,"Attribute NOT accepted for push sub billing.")),i(!0))})):zt.reportAddInternal(e,t).then((()=>{this.sendBroadcast(e),i(!0)})).catch((()=>{a(!1)}))})).catch((e=>{at.error(1,n,"Error in getting Web SDK Settings. This might indicate that the App is blocked."),a(!1)})))))}static sendBroadcast(e){re.NAMES.includes(e.event.name)&&Ft.broadcastToWindow({topic:re.TOPIC,name:e.event.name,data:e.event.attributes})}static getSegmentId(){const e=window.analytics;if(e&&e.user)return e.user().anonymousId()}static getBatchRequestOptions(e){return new Promise((t=>{zt.collectGetParams(ne).then((n=>{var i=zt.getSegmentId()||"";const a=mt.getSync(),r=new dt;var o={session_id:r.getSessionKey(),start_time:r.getSessionStartTime(),background_initiated:0};const s=[];var l=r.getActiveSource();l&&(r.setCurrentSource(l),s.push(l)),o={query_params:n,identifiers:{moe_user_id:a.getAttribute("id")||void 0,segment_id:i||void 0},meta:{bid:(0,ct.v4)(),request_time:(new Date).toISOString(),session:o,source:s.length?s:void 0},viewsCount:e.length,viewsInfo:[...e]},t(o)}))}))}static addReportsToOfflineDB(e,t){return Yt(this,void 0,void 0,(function*(){const n=zt.baseLogTag+".addReportsToOfflineDB";var i=yield zt.getBatchRequestOptions([]);yield Pt.offlineDataStore.setItem(t||"report_add_"+(new Date).getTime(),e),yield Pt.offlineDataStore.setItem("requestMetaData",i),navigator.serviceWorker&&navigator.serviceWorker.ready.then((e=>{e.sync?e.sync.register("moe_offline_data_sync").then((()=>{at.log(2,n,"offline sync event registered")})).catch((e=>{at.error(1,n,"Service worker sync error",e)})):at.log(2,n,"Service worker sync unavailable")}))}))}static sendReportBeacon(e,t,n){var i=zt.baseLogTag+".sendReportBeacon";try{if(!e&&navigator.sendBeacon&&navigator.sendBeacon(t,new Blob([JSON.stringify(n)],{type:"text/plain;charset=UTF-8"})))return!0}catch(e){at.error(2,i,"Failed to send Report call with Beacon:",e)}return!1}static sendBatchOfReports(e){const t=zt.baseLogTag+".sendBatchOfReports";return new Promise(((n,i)=>{zt.getBatchRequestOptions(e).then((a=>{var r=Ne.get();const o=r.baseDomainName+ne+r.appId;zt.getWebSDKSettings().then((r=>zt.sendReportBeacon(r.configs.isBeaconDisabled,o,a)?(at.log(1,t,"[sendBatchOfReports] batch payload: "+JSON.stringify(e)),at.log(1,t,"Batch sent to MoEngage successfully through beacon"),void n(!0)):void ot.post(o,{postData:a}).then((()=>{at.log(1,t,"[sendBatchOfReports] batch payload: "+JSON.stringify(e)),at.log(1,t,"Batch sent to MoEngage successfully"),n(!0)})).catch((a=>{at.error(1,t,"Batch Report add API failed",a),ut.getInstance().then((o=>{Wt.isOfflineBatchingSupported(o,r)?(zt.addReportsToOfflineDB(e).then((()=>{at.log(2,t,"Network offline: Batch added to offline db")})),n(!0)):i(a)})).catch((()=>{i(a)}))})))).catch((e=>{at.error(1,t,"Error in getting Web SDK Settings. This might indicate that the App is blocked."),i(e)}))}))}))}static reportAddInternal(e,t){const n=zt.baseLogTag+".reportAddInternal";return new Promise(((i,a)=>{zt.getWebSDKSettings().then((a=>{ut.getInstance().then((o=>{var l;if(null!==(l=a.configs)&&void 0!==l&&l.isBatchingEnabled&&!t)Mt(a,o)?(Wt.addReport(e,a.configs.eventBatchCount),at.log(1,n,"Event batched successfully:",e.event),this.addEventsToIDB(e.event),i(!0)):(c=new Rt(e),zt.sendBatchOfReports([c]).then((()=>{i(zt.handleReportAddSuccess(e))})).catch((t=>{zt.handleReportAddFailure(e,t)})));else{const l=zt.getUpdatedPushDetails();for(const t in l)!l.hasOwnProperty(t)||e.event.name===s&&"push_id"===t||(e.getParams[t]=l[t]);var c=je();const d={queryParams:Object.assign(Object.assign({},e.getParams),c)};if(e.postData.nie){const t=Object.assign({},e);delete t.postData.meta.source,delete t.postData.meta.session,d.postData=t.postData}else d.postData=e.postData;let g=Ne.get().baseDomainName;if(g+=t?pe:me,!g.includes(pe)&&zt.sendReportBeacon(null===(c=a.configs)||void 0===c?void 0:c.isBeaconDisabled,tt(g,Ee(d,"queryParams",null)),d.postData))return at.log(1,n,"Event tracked through beacon:",e.event),void i(zt.handleReportAddSuccess(e));ot.post(g,d).then((()=>{if(g.includes(pe)){let e=Ve().toUpperCase();e="WEB"===e?"DESKTOP":e,Kt.track(y,{deviceType:e})}i(zt.handleReportAddSuccess(e))})).catch((i=>{var s;Mt(a,o)?(at.error(1,n,"Add Report API failed, adding reports to offline db",i),t?be.enqueue(r.Q.DEVICE,e):(s=new Rt(e),zt.offlineEvents.push(s),zt.addReportsToOfflineDB(zt.offlineEvents,"report_add").then((()=>{at.log(2,n,"Network offline: Batch added to offline db")})))):zt.handleReportAddFailure(e,i)}))}}))})).catch((e=>{at.error(1,n,"Error in getting Web SDK Settings. This might indicate that the App is blocked."),a(!1)}))}))}static handleReportAddSuccess(e){var t=zt.baseLogTag+".handleReportAddSuccess";return e.type===St.REPORT_ADD_TYPE.EVENT?(at.log(1,t,"Event tracked successfully:",e.event),this.addEventsToIDB(e.event)):e.type===St.REPORT_ADD_TYPE.USER_ATTRIBUTE&&at.log(1,t,"User attribute added successfully:",e.event.attributes),zt.addReportApiRetries=1,!0}static handleReportAddFailure(e,t){var n=zt.baseLogTag+".handleReportAddFailure";at.error(1,n,"Add Report API failed",t),e.type===St.REPORT_ADD_TYPE.EVENT?at.log(1,n,"Queueing unsuccessful event tracking:",e.event):e.type===St.REPORT_ADD_TYPE.USER_ATTRIBUTE&&at.log(1,n,"Queueing unsuccessful user attribute add:",e.event.attributes),zt.addReportApiRetries<3&&setTimeout((()=>{zt.addReportApiRetries++,be.enqueue(r.Q.REPORT,e),Jt.startPeriodicClear(r.Q.REPORT)}),3e3*zt.addReportApiRetries)}static checkIfTokenValid(e){const t=Ne.get().baseDomainName+he,n=Ne.get();return new Promise((i=>{e?mt.get().then((a=>{a={queryParams:{app_id:n.appId,unique_id:a.deviceUuid,push_id:e}},ot.post(t,a).then((e=>{200===e.status?i(!0):i(!1)})).catch((e=>{i(!1)}))})):i(!1)}))}static isAppBlocked(e){return!(!e||!1!==e.configs.isAppActive)}static getWebSDKSettings(){return new Promise(((e,t)=>{let n=Ne.get();var i,a;null!=n&&null!=n.appId||(n=new Ne(xe.get(r.INIT_DATA))),zt.sdkSettings?zt.isAppBlocked(zt.sdkSettings)?t(!1):e(zt.sdkSettings):(i=(new Date).getTime(),null==(a=xe.get(r.SETUP_TIME))||0<n.debugLevel||864e5<i-a?zt.getAndPersistWebSettings(n).then((t=>{e(t)})).catch((e=>{t(!1)})):xe.get(r.WEB_SETTINGS)?(zt.sdkSettings=xe.get(r.WEB_SETTINGS),zt.isAppBlocked(zt.sdkSettings)?t(!1):e(zt.sdkSettings)):zt.getAndPersistWebSettings(n).then((t=>{e(t)})).catch((e=>{t(!1)})))}))}static getAndPersistWebSettings(e){const t=zt.baseLogTag+".getAndPersistWebSettings";return new Promise(((n,i)=>Yt(this,void 0,void 0,(function*(){try{var a={queryParams:{app_id:(e=null==e.appId?new Ne(xe.get(r.INIT_DATA)):e).appId}};at.log(1,t,"Fetching latest web sdk settings for",e.appId);var o=yield ot.get(e.baseDomainName+"v2/websdksettings",a);at.log(1,t,"Fetching config settings for",e.appId);let h=o.responseText;"string"==typeof h&&(h=JSON.parse(h));var s=Ke()?"mweb":"web",l=e.baseDomainName+z+s+"/"+e.appId;try{var c,d=xe.get(r.USER_DATA),g={postData:{query_params:{unique_id:d&&d.deviceUuid}}},u=yield ot.post(l,g);at.log(1,t,"Fetched latest web and config settings"),200===u.status&&(c=u.responseText,c=JSON.parse(c),h.webData=Object.assign(Object.assign({},h.webData),c))}catch(e){at.error(1,t,"Config API failed")}var p=(new Date).getTime();if(h=Ct.parseOldSettings(h),xe.set(r.WEB_SETTINGS,h),xe.set(r.SETUP_TIME,p),zt.isAppBlocked(h))return void i(!1);zt.sdkSettings=h,n(h)}catch(a){at.error(1,t,"Settings APi Failed: ",a),zt.webSdkApiRetries<3?setTimeout((()=>{zt.webSdkApiRetries++,n(zt.getAndPersistWebSettings(e))}),3e3*zt.webSdkApiRetries):i(!1)}}))))}static collectGetParams(e){return new Promise(((t,n)=>{mt.get().then((n=>{let i=Ne.get();null!=i&&null!=i.appId||(i=new Ne(xe.get(r.INIT_DATA)));const a=new Date,o=Date.UTC(a.getUTCFullYear(),a.getUTCMonth(),a.getUTCDate(),a.getUTCHours(),a.getUTCMinutes(),a.getUTCSeconds(),a.getUTCMilliseconds());ut.getInstance().then((a=>{var s=je(e,[me,pe,ne]);const l=Object.assign({os:a.os,os_platform:a.osPlatform,is_incognito:a.isIncognito,app_id:i.appId,os_ver:a.name,sdk_ver:"2.30.19",model:a.name,app_ver:"1.0",device_ts:Number(o),device_tz_offset:(-6e4*(new Date).getTimezoneOffset()).toString(),unique_id:n.deviceUuid,device_tz:(new Date).getTimezoneOffset().toString()},s);null!=(s=xe.get(r.PUSH_TOKEN))&&"NA"!==s&&""!==s&&"null"!==s&&(l.push_id=s),a.isWebPushCompatible()&&(Fe(this.sdkSettings.platformSettings,a)?(l.subscription_type="vapid",l.vapid_public=He(this.sdkSettings.platformSettings,a)):l.subscription_type="normal"),null!=i.environment&&(l.environment=i.environment),a.name===ut.BROWSER_NAMES.SAFARI&&(l.websitePushId=this.sdkSettings.platformSettings.safari.websitePushId);var c=xe.get(r.SUBSCRIPTION_DETAILS);if(null!=c&&null!=c.keys){for(const e in c.keys)l["keys_"+e]=encodeURI(c.keys[e]);null!=c.endpoint&&(l.endpoint=encodeURI(c.endpoint)),l.expirationTime=c.expirationTime}t(l)}))}))}))}static getUpdatedPushDetails(){const e={};var t=xe.get(r.SUBSCRIPTION_DETAILS);if(null!=t){var n=xe.get(r.PUSH_TOKEN);if(null!=n&&"NA"!==n&&""!==n&&"null"!==n&&(e.push_id=n),t.keys){for(const n in t.keys)e["keys_"+n]=encodeURI(t.keys[n]);null!=t.endpoint&&(e.endpoint=encodeURI(t.endpoint)),e.expirationTime=t.expirationTime}}return e}static isPushSubAttributeAccepted(e){return e===A||e===O}static sendBeacon(e){zt.getBatchRequestOptions(e).then((e=>{var t=(t=Ne.get()).baseDomainName+ne+t.appId+"?"+(new Date).getTime();at.log(1,"MoeApi.sendBeacon","[sendBeacon] batch payload: "+JSON.stringify(e)),navigator.sendBeacon(t,JSON.stringify(e))}))}static addEventsToIDB(e){if(Ve()!==fe.TV){const t=Se.createInstance({driver:[Se.INDEXEDDB,Se.WEBSQL,Se.LOCALSTORAGE],name:q,storeName:$});null!=t&&t.setItem(e.name,e)}}}zt.baseLogTag="MoeApi",zt.onDeviceAdd=new st,zt.webSdkApiRetries=1,zt.offlineEvents=[],zt.addReportApiRetries=1;const qt=n(967),$t=r.Q;class Jt{static clear(e){var t=Jt.baseLogTag+".clear";const n=[];for(;!be.isEmpty(e);)switch(e){case $t.REPORT:const i=be.dequeue($t.REPORT);n.push((e=>{zt.reportAdd(i).then((()=>{e()}))}));break;case $t.DEVICE:be.dequeue($t.DEVICE)&&n.push((e=>{zt.deviceAdd().then((()=>{e()}))}));break;default:at.error(1,t,"Do not know how to handle queue with name:",e)}setTimeout((()=>{Jt.processing[e]=!0,qt(n,5,((t,n)=>{Jt.processing[e]=!1}))}),0)}static startPeriodicClear(e){const t=Jt.baseLogTag+".startPeriodicCleanQ";Jt.clearInterval(e);var n=()=>{be.isEmpty(e)?(at.log(1,t,"If you see multiple event tracks with same, they were captured over multiple visits or page refreshes."),Ee(Jt.processing,e,!1)||Jt.clearInterval(e)):(Jt.clear(e),at.log(1,t,"Starting periodic queue clear for",e))};n(),Jt.intervals[e]=setInterval(n,6e3)}static clearInterval(e){null!=Jt.intervals[e]&&(clearInterval(Jt.intervals[e]),Jt.intervals[e]=null)}}Jt.baseLogTag="QManager",Jt.intervals={},Jt.processing={},(Ui=Vt=Vt||{}).PROMPT="prompt",Ui.GRANTED="granted",Ui.DENIED="denied",Ui.DISMISSED="dismissed";class Xt{static addCallback(e,t){null!=e&&null!=t&&(null==Xt.callbacks[e]&&(Xt.callbacks[e]=[]),Xt.callbacks[e].push(t))}static getCallbacks(e){return Xt.callbacks[e]||[]}static runCallbacks(e){Xt.getCallbacks(e).forEach((e=>{e()}))}}Xt.callbacks={};class Qt{constructor(e){this.swRegisterPromise=null,this.swActiveRetries=1;const t=Qt.baseLogTag+".constructor";this.sdkSettings=e,this.registerServiceWorker().then((e=>{this.sendDataToServiceWorker()})).catch((e=>{at.error(1,t,"Error registering serviceworker:",e)}))}showHardAsk(){const e=Qt.baseLogTag+".showHardAsk";return new Promise(((t,n)=>{Qt.isWebPushSupported().then((i=>{i?this.getCurrentPermissionState().then((i=>{this.registerServiceWorker().then((a=>{i!==Vt.DENIED?(at.remoteLogTracking(1,"info",e,"Attempting to open hard ask"),Kt.track(S),Ft.broadcastToWindow({topic:k,name:x.HARD_ASK_ATTEMPTED}),this.showOverlay(),this.askPermission().then((n=>{this.hideOverlay(),at.remoteLogTracking(2,"info",e,"Permission state after hard ask:",n),n===Vt.GRANTED?this.getPushTokenDetails().then((e=>{this.sendDataToServiceWorker(e.token),t({state:n,subscriptionDetails:e})})):(this.sendDataToServiceWorker(),t({state:n,subscriptionDetails:null}))})).catch((t=>{at.error(1,e,t),n(W)}))):(at.remoteLogTracking(1,"info",e,"Hard ask not shown as permission state is",i),t({state:i,subscriptionDetails:null}))})).catch((t=>{at.error(1,e,"Error registering serviceworker:",t),n(t)}))})).catch((t=>{at.error(1,e,"Registering service worker failed:",t),n(W)})):(at.warn(1,e,"Web push not supported in current browser environment"),n(B))}))}))}sendDataToServiceWorker(e){return new Promise((t=>{zt.collectGetParams().then((t=>{var n;e&&(t.push_id=e||xe.get(r.PUSH_TOKEN)||void 0),t.isBatchingEnabled=xe.get(r.WEB_SETTINGS).configs.isBatchingEnabled,Ge()||null!==(n=Ne.get())&&void 0!==n&&n.swScope?Se.createInstance({driver:[Se.INDEXEDDB,Se.WEBSQL,Se.LOCALSTORAGE],name:"moe_database",storeName:"moe_data"}).setItem("reportParams",{data:t}):navigator.serviceWorker.ready.then((()=>{this.sendDataToServiceWorkerOnControllerReady(t)}))}))}))}sendDataToServiceWorkerOnControllerReady(e){navigator.serviceWorker.controller?navigator.serviceWorker.controller.postMessage({data:e}):this.swActiveRetries<3&&setTimeout((()=>{this.swActiveRetries++,this.sendDataToServiceWorkerOnControllerReady(e)}),500)}getCurrentPermissionState(){return ut.getInstance().then((e=>navigator.permissions&&!e.isSafari()?navigator.permissions.query({name:"notifications"}).then((e=>Qt.parsePermissionState(e.state))).catch((e=>{})):new Promise((t=>{let n=Notification.permission;e.isSafari()&&"default"===n&&(n="prompt",xe.get(ge)&&(n="denied")),t(Qt.parsePermissionState(n))}))))}getPushTokenDetails(){const e=Qt.baseLogTag+".getPushTokenDetails";return new Promise(((t,n)=>{this.getCurrentPermissionState().then((n=>{ut.getInstance().then((i=>{n!==Vt.GRANTED?t({token:null,raw:null}):this.registerServiceWorker().then((n=>{let a=null;const r={userVisibleOnly:!0};Fe(this.sdkSettings.platformSettings,i)&&(a=He(this.sdkSettings.platformSettings,i),r.applicationServerKey=We(a));const o=()=>{n.pushManager.subscribe(r).then((e=>{(e=>{const n=e.toJSON();var a=e.endpoint.substring(0,n.endpoint.lastIndexOf("/")+1);e=n.expirationTime;let r=n.endpoint.split("/")[n.endpoint.split("/").length-1];i.isEdge()&&(r=r.replace("?token=",""));const o={};if(n.keys)for(const e in n.keys)n.keys.hasOwnProperty(e)&&(o[e]=n.keys[e]);t({token:r,endpoint:a,keys:o,expirationTime:e,raw:n})})(e)})).catch((n=>{at.error(1,e,"Error in subscribtion: ",n),t({token:null,raw:null})}))};n.pushManager.getSubscription().then((e=>{if(e)if("vapid"===this.sdkSettings.platformSettings.chrome.subscriptionMode&&e.options&&e.options.applicationServerKey){var t=Ue(e.options.applicationServerKey);[a,a+"=",a+"==",Ue(We(a))].indexOf(t)<0?e.unsubscribe().then((()=>{o()})):o()}else o();else o()}))})).catch((n=>{at.error(1,e,"Error in getting push token: ",n),t({token:null,raw:null})}))}))}))}))}removeToken(){return xe.remove(r.PUSH_TOKEN),xe.remove(r.SUBSCRIPTION_DETAILS),Promise.resolve()}askPermission(){return new Promise(((e,t)=>{Notification.requestPermission().then((t=>{xe.set(r.OPT_IN_SHOWN_TIME,Date.now()),Kt.track(h),Ft.broadcastToWindow({topic:k,name:x.HARD_ASK_SHOWN}),Ft.deprecatedSdkCallback("opt_in_shown"),Xt.runCallbacks(x.HARD_ASK_SHOWN),e(Qt.parsePermissionState(t))})).catch((e=>{t(F)}))}))}registerServiceWorker(){const e=Qt.baseLogTag+".registerServiceWorker";return null!=this.swRegisterPromise||(this.swRegisterPromise=new Promise(((t,n)=>{if(Qt.registeredServiceWorker)t(Qt.registeredServiceWorker);else if("serviceWorker"in navigator){let i="serviceworker.js",a=!1;if(Ne.get()&&null!=Ne.get().swPath&&(i=Ne.get().swPath,a=!0),"/"===i[0]||i.startsWith("http")||(i="/"+i),Ge())at.log(1,e,"Removing scope in case of shopify."),this.registerScopedSW(i,/moengage/,t,n);else{let r="/";Ne.get()&&null!=Ne.get().swScope?(r=Ne.get().swScope,this.registerScopedSW(i,r,t,n)):(a&&(at.log(1,e,"Using user defined path to serviceworker:",i),r=i.substr(0,i.lastIndexOf("/")+1),Qt.canSwBeRegisteredWithScope(r)||(at.error(1,e,"Service worker can only be registered from same directory or child directory."),n(H))),navigator.serviceWorker.register(i,{scope:r}).then((i=>{at.log(2,e,"Serviceworker registered"),navigator.serviceWorker.ready.then((n=>{at.log(2,e,"Serviceworker ready"),Qt.registeredServiceWorker=n,Ne.get()&&Ne.get().forceSwUpdate&&n.update(),t(n)})).catch((t=>{at.error(1,e,"Service worker register failed:",t),n(W)}))})).catch((t=>{at.error(1,e,"Service worker register failed:",t),n(W)}))),at.log(1,e,"Scope for serviceworker:",r)}}else at.error(1,e,"Service worker not supported"),n("Service worker not supported")}))),this.swRegisterPromise}registerScopedSW(e,t,n,i){const a=Qt.baseLogTag+".registerScopedSW";navigator.serviceWorker.register(e).then((e=>{at.log(2,a,"Serviceworker registered"),navigator.serviceWorker.getRegistrations().then((e=>{e.forEach((e=>{setTimeout((()=>{e.active&&e.active.scriptURL.match(t)&&(at.log(2,a,"Serviceworker ready"),Qt.registeredServiceWorker=e,Ne.get()&&Ne.get().forceSwUpdate&&e.update(),n(e))}),100)}))})).catch((e=>{at.error(1,a,"Service worker register failed:",e),i(W)}))})).catch((e=>{at.error(1,a,"Service worker register failed:",e),i(W)}))}static canSwBeRegisteredWithScope(e){var t=window.location.pathname;return e=e,!((t=t).indexOf(e)<0)&&0<=t.substring(t.indexOf(e)).length}static isWebPushSupported(){return new Promise((e=>{ut.getInstance().then((t=>{!t.isIncognito&&"serviceWorker"in navigator&&"PushManager"in window&&t.isWebPushCompatible()?e(!0):e(!1)}))}))}static parsePermissionState(e){return"prompt"===e?Vt.PROMPT:"granted"===e?Vt.GRANTED:"denied"===e?Vt.DENIED:"default"===e?Vt.DISMISSED:null}showNotification(e){const t=Qt.baseLogTag+".showNotification";this.registerServiceWorker().then((n=>{e?e.title?e.body?(null==e.requireInteraction&&(e.requireInteraction=!0),n.showNotification(e.title,e)):at.error(1,t,"Notification body can not be blank"):at.error(1,t,"Notification title can not be blank"):at.error(1,t,"Notification object can not be blank")})).catch((e=>{at.error(1,t,"Error registering serviceworker:",e)}))}showOverlay(){if(this.sdkSettings.optInConfig.showOverlay&&this.sdkSettings.optInConfig.type===Tt.TYPE.ONE_CLICK){const e=document.createElement("div");e.id="moe-push-div",e.style.display="none",e.className="moe-push-class",ut.getInstance().then((t=>{t.isMobile?e.innerHTML=this.sdkSettings.optInConfig.softAskConfig.mobile.customHTML:e.innerHTML=this.sdkSettings.optInConfig.softAskConfig.desktop.customHTML;const n=document.body.firstChild;let i;if(n.parentNode.insertBefore(e,n),(t=t.name)===ut.BROWSER_NAMES.CHROME||t===ut.BROWSER_NAMES.OPERA_NEON?i=document.getElementsByClassName("moe_chrome"):t===ut.BROWSER_NAMES.FIREFOX?i=document.getElementsByClassName("moe_firefox"):t!==ut.BROWSER_NAMES.OPERA&&t!==ut.BROWSER_NAMES.SAFARI||(i=document.getElementsByClassName("moe_opera")),0===i.length)document.getElementById("moe-push-div").style.display="none";else for(let e=i.length-1;0<=e;e--)i[e].style.display="block";this.overlayTimer=window.setTimeout((()=>{""===e.style.opacity&&(e.style.display="block")}),1500),e.onclick=()=>{this.hideOverlay()}}))}}hideOverlay(){clearTimeout(this.overlayTimer);const e=document.getElementById("moe-push-div");null!=e&&(e.style.visibility="none",e.style.opacity="0",e.parentNode.removeChild(e))}}Qt.baseLogTag="HTTPS-NotificationManager";const Zt="Web push settings not configured on MoEngage dashboard: "+j;class en{constructor(e,t){this.currentManager=null;var n=en.baseLogTag+".constructor";this.config=e,this.browser=t,this.browser.isWebPushCompatible()?e.platformSettings.chrome&&("https"===e.platformSettings.chrome.domainType?"https"===function(){if(window)return"localhost"===window.location.hostname?"https":"http:"===window.location.protocol?"http":"https:"===window.location.protocol?"https":void 0}()?this.currentManager=new Qt(e):at.error(1,n,"Web Push does not work in http mode"):(Ge()&&new Qt(e),at.warn(1,n,"Web push settings not configured. Please configure at ",j))):this.browser.name===ut.BROWSER_NAMES.SAFARI&&e.platformSettings.safari&&"safari"in window&&"pushNotification"in window.safari&&(this.currentManager=null,at.warn(1,n,"Web push is only supported on Safari 16 and above."))}showHardAsk(){const e=en.baseLogTag+".showHardAsk";return new Promise(((t,n)=>{this.getCurrentPermissionState().then((i=>{null!=this.currentManager?i===Vt.PROMPT?this.currentManager.showHardAsk().then((n=>{n.state===Vt.DISMISSED?(Kt.track(f),Ft.broadcastToWindow({topic:k,name:x.HARD_ASK_DISMISSED}),Ft.deprecatedSdkCallback("opt_in_dismissed"),Xt.runCallbacks(x.HARD_ASK_DISMISSED),at.log(1,e,"Hard ask was dismissed")):n.state===Vt.GRANTED?(Kt.track(m),Ft.broadcastToWindow({topic:k,name:x.HARD_ASK_ALLOWED,data:n.subscriptionDetails}),Ft.deprecatedSdkCallback("opt_in_allowed"),Xt.runCallbacks(x.HARD_ASK_ALLOWED),at.log(1,e,"Push permission was granted"),at.customLabel(1,e,"token",n.subscriptionDetails.token)):n.state===Vt.DENIED&&(Kt.track(v),Kt.track("Web Push Opt-in Denied"),Ft.broadcastToWindow({topic:k,name:x.HARD_ASK_DENIED}),Ft.deprecatedSdkCallback("opt_in_blocked"),Xt.runCallbacks(x.HARD_ASK_DENIED),at.log(1,e,"Notification permission was denied")),t(n)})).catch((n=>{at.error(1,e,"Error showing hard ask:",n),t({state:i,subscriptionDetails:null})})):(at.log(1,e,"Not showing Hard Ask as current permission state is",i),this.getPushTokenDetails().then((n=>{at.customLabel(1,e,"token",n.token),t({state:i,subscriptionDetails:n})})).catch((n=>{at.warn(1,e,"Could not get push token details"),t({state:i,subscriptionDetails:null})}))):(at.log(1,e,"MoEngage web push settings not configured. Please configure at",j),n(U))})).catch((e=>{n(e)}))}))}getCurrentPermissionState(){return null!=this.currentManager?this.currentManager.getCurrentPermissionState():Promise.reject(Zt)}getPushTokenDetails(){return null!=this.currentManager?this.currentManager.getPushTokenDetails():Promise.reject(Zt)}removeToken(){return null!=this.currentManager?this.currentManager.removeToken():Promise.reject(Zt)}showNotification(e){var t=en.baseLogTag+".showNotification";if(null!=this.currentManager)return this.currentManager.showNotification(e);at.warn(1,t,Zt)}}en.baseLogTag="NotificationManager";class tn{constructor(e){this.mainDivs=[],this.config=e}showSoftAsk(){const e=tn.baseLogTag+".showSoftAsk";return new Promise(((t,n)=>{let i=this.config.optInConfig.loadTime;ut.getInstance().then((n=>{(this.config.optInConfig.type===Tt.TYPE.SELF_HANDLED||n.isSafari()&&this.config.optInConfig.type===Tt.TYPE.ONE_CLICK)&&(i=0),i&&at.log(1,e,"Delay of",i," second(s) requested before opt-in flow"),setTimeout((()=>{!n.isWebPushCompatible()||this.config.optInConfig.type!==Tt.TYPE.TWO_STEP&&this.config.optInConfig.type!==Tt.TYPE.SELF_HANDLED?(xe.set(r.SOFT_ASK_STATUS,jt.NOT_SHOWN),t({showHardAsk:!0,softAskState:jt.NOT_SHOWN})):this.showOptIn((()=>{at.log(1,e,"Soft ask was shown"),xe.set(r.OPT_IN_SHOWN_TIME,Date.now()),xe.set(r.SOFT_ASK_STATUS,jt.SHOWN),Ft.broadcastToWindow({topic:k,name:x.SOFT_ASK_SHOWN}),Ft.deprecatedSdkCallback("soft_ask_shown"),Xt.runCallbacks(x.SOFT_ASK_SHOWN)}),(()=>{Kt.track(u),this.hideOptIn(),at.log(1,e,"Soft ask was allowed"),xe.set(r.SOFT_ASK_STATUS,jt.ALLOWED),t({showHardAsk:!0,softAskState:jt.ALLOWED}),Ft.broadcastToWindow({topic:k,name:x.SOFT_ASK_ALLOWED}),Ft.deprecatedSdkCallback("soft_ask_allowed"),Xt.runCallbacks(x.SOFT_ASK_ALLOWED)}),(()=>{this.hideOptIn(),Kt.track(g),at.log(1,e,"Soft ask was dismissed"),xe.set(r.SOFT_ASK_STATUS,jt.DISMISSED),t({showHardAsk:!1,softAskState:jt.DISMISSED}),Ft.broadcastToWindow({topic:k,name:x.SOFT_ASK_DISMISSED}),Ft.deprecatedSdkCallback("soft_ask_closed"),Xt.runCallbacks(x.SOFT_ASK_DISMISSED)}),(e=>{e=!!e,this.hideOptIn(),t({showHardAsk:e,softAskState:jt.NOT_SHOWN})}))}),1e3*i)}))}))}showOptIn(e,t,n,i){const a=tn.baseLogTag+".showOptIn";if(this.config.optInConfig.type===Tt.TYPE.TWO_STEP){let r=document.getElementById("moe-push-div");null==r&&(r=document.createElement("div"),r.id="moe-push-div",r.className="moe-push-class"),ut.getInstance().then((o=>{let s=null;if(s=(o.isMobile?this.config.optInConfig.softAskConfig.mobile:this.config.optInConfig.softAskConfig.desktop).customHTML,null!=s){r.innerHTML=s;const o=document.body.firstChild;o.parentNode.insertBefore(r,o),this.moeDiv=r;const l=document.getElementById("optInText")||document.getElementById("optInTextConventional"),c=document.getElementById("moe-dontallow_button");null==l?(at.error(1,a,"Error showing soft ask. Allow button id is missing"),i()):(e(),Kt.track(d),l.onclick=()=>{t()},c?c.onclick=()=>{n()}:window.moeRemoveBanner=()=>{n()})}else at.error(1,a,"Error displaying soft ask"),i()}))}else if(this.config.optInConfig.type===Tt.TYPE.SELF_HANDLED){var r=Ne.get();if(r.customSoftAsk){var o=document.getElementsByClassName(r.customSoftAsk.mainClass),s=document.getElementsByClassName(r.customSoftAsk.allowClass),l=document.getElementsByClassName(r.customSoftAsk.dismissClass);if(o.length<1)at.error(1,a,"Could not find main class for the soft ask. Class name given:",r.customSoftAsk.mainClass),ut.getInstance().then((e=>{e.isWebPushCompatible()&&(at.warn(1,a,"Proceeding to hard ask directly"),i(!0))}));else{e(),s.length<1&&(at.warn(1,a,"Could not find any element for allow button. Class name given:",r.customSoftAsk.allowClass),at.warn(1,a,"Docs for self-handled opt in available here - ",V.SELF_HANDLED_DOCS)),l.length<1&&at.warn(1,a,"Could not find any element for dismiss button. Class name given:",r.customSoftAsk.dismissClass);for(let e=o.length-1;0<=e;e--){const t=o[e];this.mainDivs.push(t),t.style.display="block"}for(let e=s.length-1;0<=e;e--)s[e].onclick=()=>{t()};for(let e=l.length-1;0<=e;e--)l[e].onclick=()=>{n()}}}else ut.getInstance().then((e=>{e.isWebPushCompatible()?(at.warn(1,a,"No soft ask configured. Proceeding to hard ask directly. \n\nYou can ignore this message if you do not want any soft ask."),i(!0)):(at.error(1,a,"Soft ask needs to be present in case of http implementation. Can not show hard ask otherwise."),i())}))}}hideOptIn(){null!=this.moeDiv&&(this.moeDiv.style.display="none"),0<this.mainDivs.length&&this.mainDivs.map((e=>{e.style.display="none"}))}}tn.baseLogTag="SoftAskManager",(Ui=jt=jt||{}).SHOWN="shown",Ui.NOT_SHOWN="not shown",Ui.ALLOWED="allowed",Ui.DISMISSED="dismissed";class nn{constructor(e){this.deviceToLogout=Ee(e,"deviceToLogout",null)}static get(){return new nn(xe.get(r.GRACEFUL_DATA))}save(){xe.set(r.GRACEFUL_DATA,this)}}var an=function(e,t,n,i){return new(n=n||Promise)((function(a,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function s(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?a(e.value):((t=e.value)instanceof n?t:new n((function(e){e(t)}))).then(o,s)}l((i=i.apply(e,t||[])).next())}))};const rn="MoEngage.user";class on{static addAttribute(e,t){const n=rn+".addUserAttribute";return new Promise(((i,a)=>{let r=!1;if("string"!=typeof e||null==e)at.error(1,n,"Attribute name needs to be a string"),i({error:5e3,message:"Attribute name needs to be a string. Type provided was "+typeof e});else if(""===e)at.error(1,n,"Attribute name can not be an empty string"),i({error:5001,message:"Attribute name can not be an empty string"});else if(null==t)at.error(1,n,"Attribute value null"),i({error:5003,message:"Attribute value was empty"});else if("string"==typeof t&&""===t)i({error:5004,message:"Attribute value needs to be non-empty string, non-empty array or date object"});else if("object"!=typeof t||Array.isArray(t)||"function"==typeof t.getMonth)if("object"==typeof t&&Array.isArray(t)&&0===t.length)at.error(1,n,"Value cannot be empty, non-string, non-array or non-date object"),i({error:5006,message:"Attribute value needs to be non-empty string, non-empty array or date object"});else if("object"==typeof t&&Array.isArray(t)&&void 0!==t.find((e=>"object"==typeof e&&"function"!=typeof e.getMonth)))at.error(1,n,"Elements of the attribute value-array cannot be non-Date objects"),i({error:5007,message:"Attribute value-array cannot have non-Date objects as its elements"});else{const a=new pt(e,t),o=()=>{mt.get().then((e=>{e.addAttribute(a).then((e=>{e?("id"===a.key&&at.log(1,n,"Logging in the user with id: ",a.value),Ht.createUserAttributeEvent(a).then((e=>{at.log(2,n,"Event to be converted to report:",e),Gt.addEvent(e),zt.collectGetParams().then((t=>{t=new St(St.REPORT_ADD_TYPE.USER_ATTRIBUTE,t,e),zt.reportAdd(t).then((()=>{r&&Wi.onsite.refresh&&Wi.onsite.refresh(),i(!0)}))}))}))):(at.log(1,n,"Attribute already present/queued. Not adding again."),i({error:5005,message:"Attribute already present/queued. Not adding again."}))}))}))};"id"===e?(r=!0,mt.get().then((e=>{var a=e.indexOfAttribute("id");-1<a?(r=!1,t===e.attributes[a].value?(at.log(1,n,"User already logged in with id:",t),i(!0)):(at.log(1,n,"Logging out previous user with id:",e.attributes[a].value),et(!0),on.logout(!0,t).then((()=>{o()})))):(et(!0),o())}))):o()}else at.error(1,n,"Value cannot be empty, non-string, non-array or non-date object"),i({error:5005,message:"Attribute value needs to be non-empty string, non-empty array or date object"})}))}static login(e){return on.addAttribute("id",e)}static logout(e,t){const n=rn+".logout",i=e?{type:"forced",new_uid:t}:null;return function(){const e=nn.get();null!=mt.getSync()&&(e.deviceToLogout=mt.getSync().deviceUuid,e.save())}(),new Promise((e=>{Kt.track(E,i).then((()=>an(this,void 0,void 0,(function*(){at.log(1,n,"Logging out now!"),yield Wt.flushReports(),zt.getWebSDKSettings().then((t=>an(this,void 0,void 0,(function*(){var n;t.isDomainLevelStorage&&ke.remove(r.USER_DATA),Gt.clear(),yield Gi(),yield function(){return Ni(this,void 0,void 0,(function*(){const e="Moengage.disableCards",t=Ne.get();try{zt.getWebSDKSettings().then((e=>Ni(this,void 0,void 0,(function*(){var n;if(null!=e&&e.configs.isCardsModuleEnabled&&null!==(n=t.cards)&&void 0!==n&&n.enable){const e=yield ln.loadModule(ee.CARDS);yield e.logout(),xi=new st}})))).catch((t=>{at.error(1,e,"Error in getting Web SDK Settings. This might indicate that the App is blocked.")}))}catch(t){at.error(1,e,"Error logging out from cards module:",t)}}))}(),et(),xe.logout(),yield mt.logout(),xe.remove(r.GRACEFUL_DATA),zt.onDeviceAdd=new st,yield Xi(),t.configs.remoteLogTracking&&(n=Ne.get(),yield zt.getAndPersistWebSettings(n)),e(!0)})))).catch((t=>{at.error(1,n,"Error in getting Web SDK Settings. This might indicate that the App is blocked."),e(!1)}))}))))}))}static updateUniqueId(e){const t=rn+".updateUniqueId";return new Promise((n=>{mt.get().then((i=>{var a=i.indexOfAttribute(I),r=i.indexOfAttribute("oldUniqueIds");if(!(-1<a))return at.log(2,t,"Logging in as no id found"),on.login(e);var o=i.attributes[a].value;e!==o?(at.log(2,t,"Different ids found"),-1<r?(i.attributes[r].value.push(o),i.attributes.splice(a,1)):(i.attributes.splice(a,1),i.addAttribute(new pt("oldUniqueIds",[o]))),i.save().then((()=>{on.login(e).then((()=>{n(!0)}))}))):(at.warn(1,t,"New id and old id are the same. Not updating the id."),n(!0))}))}))}static getAttributes(){const e=mt.getSync().attributes,t={};return e.map((e=>{t[e.key]=e.value})),t}}class sn{constructor(e,t){this.notificationManager=null,this.softAskManager=null,sn.baseLogTag,this.sdkSettings=e,this.browser=t,this.softAskManager=new tn(this.sdkSettings),this.notificationManager=new en(this.sdkSettings,t)}callWebPush(){const e=sn.baseLogTag+".callWebPush";this.isWebPushEnabled()&&this.notificationManager.getCurrentPermissionState().then((t=>function(e,t,n,i){return new(n=n||Promise)((function(t,a){function r(e){try{s(i.next(e))}catch(e){a(e)}}function o(e){try{s(i.throw(e))}catch(e){a(e)}}function s(e){var i;e.done?t(e.value):((i=e.value)instanceof n?i:new n((function(e){e(i)}))).then(r,o)}s((i=i.apply(e,[])).next())}))}(this,0,void 0,(function*(){const n=(n=t)=>{mt.get().then((t=>{let i=!1;var a=t.getAttribute("email"),o=t.getAttribute("mobile");null===a&&null===o||(i=!0),t.deviceAdded=i,t.save().then((()=>{this.notificationManager.removeToken().then((()=>{n===Vt.DENIED?at.log(1,e,"Not asking for permission as current state is denied."):(xe.remove(r.OPT_IN_SHOWN_TIME),this.startPushSubscription())}))}))}))},i=yield ut.getInstance();var a=xe.get(r.PUSH_TOKEN),o=t===Vt.DENIED&&!this.sdkSettings.isDomainLevelStorage;null==a&&t!==Vt.DENIED?this.startPushSubscription():null!=a&&(o||i.isSafari()&&t===Vt.PROMPT)?(at.log(1,e,"User has removed the permission"),at.image(1,G),i.isSafari()&&t===Vt.PROMPT&&(xe.set(ge,!0),t=Vt.DENIED),Kt.track(s,{Source:"Website"}).then((()=>{n(t)}))):o?at.warn(1,e,"Not proceeding with push subscription as current state is denied"):null!=a&&t===Vt.GRANTED?this.browser.name===ut.BROWSER_NAMES.CHROME?Fe(this.sdkSettings.platformSettings,this.browser)?this.startPushSubscription():at.warn(1,e,"Subscription mode is not VAPID type. Cannot subscribe to web push."):(this.startPushSubscription(),this.notificationManager.getPushTokenDetails().then((t=>{at.customLabel(1,e,"token",t.token)}))):this.sdkSettings.isDomainLevelStorage?"granted"===ke.get(r.HARD_ASK_STATUS)?(a=null===(a=ke.get(r.SUBSCRIPTION_DETAILS))||void 0===a?void 0:a.domain)&&a===window.location.origin?(at.log(1,e,"It seems that the user has unsubscribed manually. Starting push subscription.."),Kt.track(s,{Source:"Website"}).then((()=>{n(t)}))):at.log(1,e,"Not showing opt-in as user subscribed to sub-domain"):this.startPushSubscription():n()})))).catch((t=>{at.error(1,e,"Error in getting current state:",t)}))}startPushSubscription(){const e=sn.baseLogTag+".startPushSubscription",t=()=>{xe.set(r.HARD_ASK_STATUS,Vt.PROMPT);const t=xe.get(r.PUSH_TOKEN);this.notificationManager.showHardAsk().then((n=>{xe.set(r.HARD_ASK_STATUS,n.state),n.state===Vt.GRANTED?null!=n.subscriptionDetails.token?(xe.set(r.PUSH_TOKEN,n.subscriptionDetails.token),n.subscriptionDetails.domain=window.location.origin,xe.set(r.SUBSCRIPTION_DETAILS,n.subscriptionDetails),n.subscriptionDetails.token&&t!==n.subscriptionDetails.token&&zt.deviceAdd().then((()=>{at.image(1,"https://media.giphy.com/media/90F8aUepslB84/giphy.gif"),mt.getSync().subscribedToOldSdk?at.remoteLogTracking(1,"info",e,"User subscribed from older sdk, hence not sending subscription event"):(null!=t?on.addAttribute("Web Migrated User","true"):(on.addAttribute("Web Push Preference","granted"),on.addAttribute("Web Subscription URL",location.href)),Ze(),Kt.track(p,{MOE_WEB_PUSH_TOKEN:n.subscriptionDetails.token,migrated_user:!!Ze()||void 0}))})),this.sdkSettings.isDomainLevelStorage&&(ke.set(r.SUBSCRIPTION_DETAILS,{domain:n.subscriptionDetails.domain,token:n.subscriptionDetails.token,endpoint:n.subscriptionDetails.endpoint,keys:n.subscriptionDetails.keys}),ke.set(r.PUSH_TOKEN,n.subscriptionDetails.token))):(at.error(1,e,"Push token was received as null."),at.error(1,e,"Please contact MoEngage support if this troubleshooting does not solve the issue.")):n.state===Vt.DENIED&&at.image(1,G)})).catch((t=>{at.warn(1,e,t)}))},n=()=>{this.softAskManager?this.softAskManager.showSoftAsk().then((e=>{e.showHardAsk&&t()})):at.log(1,e,"SoftAskManager not set.")};this.notificationManager.getCurrentPermissionState().then((i=>{if(i===Vt.GRANTED)this.sdkSettings.optInConfig.type!==Tt.TYPE.ONE_CLICK&&at.remoteLogTracking(1,"info",e,"Skipping soft ask as browser permission is set to allow all notifications"),t();else{var a=parseInt(xe.get(r.OPT_IN_SHOWN_TIME));if(xe.get(r.SOFT_ASK_STATUS),xe.get(r.HARD_ASK_STATUS),i=(Date.now()-a)/36e5,!a||i>this.sdkSettings.optInConfig.reappearTime)if(this.browser.name===ut.BROWSER_NAMES.SAFARI&&this.sdkSettings.optInConfig.type===Tt.TYPE.ONE_CLICK){at.log(1,e,"1 step optin configured. In Safari 16+ and macOS 13+, the web push optin will be shown after a user click. Any delay will be ignored.");const t=()=>{window.removeEventListener("click",t),n()};window.addEventListener("click",t)}else n();else{let t,n;n=i<1?(t=Math.floor(60*i),"minute(s)"):(t=Math.floor(100*i)/100,"hour(s)"),at.remoteLogTracking(1,"info",e,"Not showing opt in as last it was shown",t,n,"back on",new Date(a),". Reappear time is set to",this.sdkSettings.optInConfig.reappearTime,"hours."),at.log(1,e,"You can clear localstorage to get opt-in again.")}}}))}isWebPushEnabled(){return!this.browser.isIncognito&&0<=sn.SUPPORTED_BROWSERS.indexOf(this.browser.name)&&navigator.serviceWorker&&"PushManager"in window}getPermissionState(){return this.notificationManager.getCurrentPermissionState()}showNotification(e){this.notificationManager&&this.notificationManager.showNotification(e)}}sn.baseLogTag="WebPushManager",sn.SUPPORTED_BROWSERS=[ut.BROWSER_NAMES.CHROME,ut.BROWSER_NAMES.FIREFOX,ut.BROWSER_NAMES.OPERA,ut.BROWSER_NAMES.SAFARI,ut.BROWSER_NAMES.EDGE];class ln{static loadModule(e){var t=ln.baseLogTag+".loadModule";return null!=ln.loadPromises[e.name]||(at.log(1,t,"Starting to fetch module: ",e.name),ln.loadPromises[e.name]=new Promise(((t,n)=>{ln.addScript(e.src,(()=>{var n=new(0,window[ee[e.name].windowLocation])(n=Ne.get());t(n)}))}))),ln.loadPromises[e.name]}static addScript(e,t){const n=document.createElement("script");n.setAttribute("src",e),n.onload=t,n.async=!0,document.body.appendChild(n)}}ln.baseLogTag="ModuleManager",ln.loadPromises={};var cn=function(e,t,n,i){return new(n=n||Promise)((function(a,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function s(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?a(e.value):((t=e.value)instanceof n?t:new n((function(e){e(t)}))).then(o,s)}l((i=i.apply(e,t||[])).next())}))};class dn{static initialize(){return cn(this,void 0,void 0,(function*(){var e;return null==dn.ready&&(dn.serviceMetaStore=Se.createInstance({driver:[Se.INDEXEDDB,Se.WEBSQL,Se.LOCALSTORAGE],name:Z.DATABASE_NAME,storeName:Z.STORES.SERVICE_META.NAME}),dn.campaingsMetaStore=Se.createInstance({driver:[Se.INDEXEDDB,Se.WEBSQL,Se.LOCALSTORAGE],name:Z.DATABASE_NAME,storeName:Z.STORES.CAMPAIGNS_META.NAME}),dn.pendingSecondaryEvents=Se.createInstance({driver:[Se.INDEXEDDB,Se.WEBSQL,Se.LOCALSTORAGE],name:Z.DATABASE_NAME,storeName:Z.STORES.PENDING_SECONDARY_EVENTS.NAME}),dn.pendingTimerCampaigns=Se.createInstance({driver:[Se.INDEXEDDB,Se.WEBSQL,Se.LOCALSTORAGE],name:Z.DATABASE_NAME,storeName:Z.STORES.PENDING_TIMER_CAMPAIGNS.NAME}),dn.triggeringPrimaryEvents=Se.createInstance({driver:[Se.INDEXEDDB,Se.WEBSQL,Se.LOCALSTORAGE],name:Z.DATABASE_NAME,storeName:Z.STORES.TRIGGERING_PRIMARY_EVENTS.NAME}),dn.campaingsTagsStore=Se.createInstance({driver:[Se.INDEXEDDB,Se.WEBSQL,Se.LOCALSTORAGE],name:Z.DATABASE_NAME,storeName:Z.STORES.CAMPAIGNS_TAGS.NAME}),dn.campaingsStatsStore=Se.createInstance({driver:[Se.INDEXEDDB,Se.WEBSQL,Se.LOCALSTORAGE],name:Z.DATABASE_NAME,storeName:Z.STORES.CAMPAIGNS_STATS.NAME}),dn.testCampaignStore=Se.createInstance({driver:[Se.INDEXEDDB,Se.WEBSQL,Se.LOCALSTORAGE],name:Z.DATABASE_NAME,storeName:Z.STORES.CAMPAIGNS_STATS.NAME}),dn.exitIntentCampaignStore=Se.createInstance({driver:[Se.INDEXEDDB,Se.WEBSQL,Se.LOCALSTORAGE],name:Z.DATABASE_NAME,storeName:Z.STORES.EXIT_INTENT_CAMPAIGN_STORE.NAME}),e=[dn.serviceMetaStore.ready(),dn.campaingsMetaStore.ready(),dn.pendingSecondaryEvents.ready(),dn.pendingTimerCampaigns.ready(),dn.triggeringPrimaryEvents.ready(),dn.campaingsTagsStore.ready(),dn.campaingsStatsStore.ready(),dn.testCampaignStore.ready(),dn.exitIntentCampaignStore.ready()],dn.ready=Promise.all(e)),dn.ready}))}static clear(){return cn(this,void 0,void 0,(function*(){var e=dn.baseLogTag+".clear";try{yield dn.initialize(),yield Promise.all([dn.serviceMetaStore.clear(),dn.campaingsMetaStore.clear(),dn.campaingsTagsStore.clear(),dn.campaingsStatsStore.clear(),dn.testCampaignStore.clear(),dn.exitIntentCampaignStore.clear(),dn.pendingSecondaryEvents.clear(),dn.pendingTimerCampaigns.clear(),dn.triggeringPrimaryEvents.clear()]);var t=[dn.serviceMetaStore.ready(),dn.campaingsMetaStore.ready(),dn.campaingsTagsStore.ready(),dn.campaingsStatsStore.ready(),dn.testCampaignStore.ready(),dn.exitIntentCampaignStore.ready(),dn.pendingSecondaryEvents.clear(),dn.pendingTimerCampaigns.clear(),dn.triggeringPrimaryEvents.clear()];dn.ready=Promise.all(t)}catch(t){at.error(1,e,"Error clearing onsite stores:",t)}return dn.ready}))}}dn.baseLogTag="MOE_ONSITE_STORES";var gn,un,pn,hn,mn,fn=function(e,t,n,i){return new(n=n||Promise)((function(a,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function s(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?a(e.value):((t=e.value)instanceof n?t:new n((function(e){e(t)}))).then(o,s)}l((i=i.apply(e,t||[])).next())}))};const vn=(e,t,n)=>null==e.campaignId?()=>{}:()=>(dn.campaingsStatsStore.getItem(e.campaignId).then((t=>{t=null!=t?Object.assign(Object.assign({},t),{clicks:Ee(t,"clicks",0)+1}):{clicks:1},dn.campaingsStatsStore.setItem(e.campaignId,t)})),null==n&&(n={}),bn().track_event(Z.EVENT_NAMES[t].CLICK,Object.assign(Object.assign({campaign_id:e.campaignId,campaign_name:e.campaignName,type:Z.EVENT_NAMES[t].TYPE},n),e.campaignContext))),Sn=(e,t,n=!1)=>null==e.campaignId?()=>{}:()=>{if(dn.initialize().then((()=>{dn.campaingsStatsStore.getItem(e.campaignId).then((t=>{t=null!=t?Object.assign(Object.assign({},t),{impressions:Ee(t,"impressions",0)+1,lastImpression:new Date}):{impressions:1,lastImpression:new Date},dn.campaingsStatsStore.setItem(e.campaignId,t)}))})),!n)return bn().track_event(Z.EVENT_NAMES[t].IMPRESSION,Object.assign({campaign_id:e.campaignId,campaign_name:e.campaignName,type:Z.EVENT_NAMES[t].TYPE,templateType:e.templateType},e.campaignContext))},En=(e,t,n)=>{n=n?Z.EVENT_NAMES[t].AUTO_DISMIS:Z.EVENT_NAMES[t].DISMISS,bn().track_event(n,Object.assign({campaign_id:e.campaignId,campaign_name:e.campaignName,type:Z.EVENT_NAMES[t].TYPE},e.campaignContext))},yn=(e,t)=>{bn().track_event(Z.EVENT_NAMES[t].DELIVERED,Object.assign({campaign_id:e.campaignId,campaign_name:e.campaignName,type:Z.EVENT_NAMES[t].TYPE},e.campaignContext))},bn=()=>{var e=window.moengage_object||"Moengage";return window[e]};class _n{static isValid(e,t){return!_n.isCampaignExpired(e)&&_n.isCampaignActive(e)&&_n.isUserInCampaignSegment(e)&&_n.isCampaignWithinFC(e,t)}static isCampaignExpired(e){return(new Date).getTime()>new Date(e.expiryTime).getTime()}static isValidMessagingCampaign(e,t,n,i,a){return _n.canCampaignBeRenderedOverExisting(e,a.length)&&_n.hasCampaignClearedSelfDelay(e,t)&&_n.hasCampaignClearedGlobalDelay(e,n,i)}static isCampaignActive(e){var t=_n.baseLogTag+".isValid";return e.status===pn.ACTIVE||(at.warn(1,t,`Campaign ${e.campaignId} : Status is `+e.status),!1)}static isUserInCampaignSegment(e){var t=_n.baseLogTag+".isValid";return!!e.userInSegment||(at.warn(1,t,`Campaign ${e.campaignId} : User is not in segment`),!1)}static isCampaignWithinFC(e,t){var n=_n.baseLogTag+".isValid";if([mn.SELF_HANDLED].indexOf(e.templateType)<0){var i=Ee(e,"delivery.fc_meta.count",0);if(0<i){var a=Ee(t,"impressions",0);if(null!=t)return!(i<=a&&(at.warn(1,n,`Campaign ${e.campaignId} : FC reached. ${t.impressions} times shown`),1))}}return!0}static hasCampaignClearedGlobalDelay(e,t,n){var i=_n.baseLogTag+".isValid",a=Ee(e,"delivery.fc_meta.ignore_global_delay",!1);try{if(!a){const a=new Date;if(n){var r=(a.getTime()-new Date(n).getTime())/1e3;if(t&&r<=t)return at.remoteLogTracking(1,"info",i,`Can't render ${e.campaignId} as last global campaign was rendered ${r} seconds ago.`),!1}}}catch(e){return at.error(1,i,"Error checking global delay:",e),!1}return!0}static hasCampaignClearedSelfDelay(e,t){var n=_n.baseLogTag+".hasCampaignClearedSelfDelay",i=Ee(e,"delivery.fc_meta.delay",0);try{if(0<i&&null!=t&&t.lastImpression){var a=t.lastImpression,r=((new Date).getTime()-new Date(a).getTime())/1e3;if(r<=Ee(e,"delivery.fc_meta.delay",0))return at.warn(1,n,`Can't render ${e.campaignId} as it was rendered ${r} seconds ago.`),!1}}catch(t){return at.error(1,n,"Can't check self delay for "+e.campaignId,t),!1}return!0}static doCampaignPayloadHasMandatoryParams(e){var{payload:t,payloadType:n,htmlJsonPayload:e}=e;return!(!t&&!e||!n)}static canCampaignBeRenderedOverExisting(e,t){var n=_n.baseLogTag+".canCampaignBeRenderedOverExisting";return!(0<t&&!e.display.config.showOverOtherCampaigns&&(at.warn(1,n,`Can not show ${e.campaignId} over other existing campaigns`),1))}static comparator(e,t){return t.delivery.priority>e.delivery.priority||!(t.delivery.priority<e.delivery.priority)&&t.updatedTime>e.updatedTime?1:-1}}_n.baseLogTag="CampaignUtils";const Tn=e=>fn(void 0,void 0,void 0,(function*(){var t=e.map((e=>dn.campaingsStatsStore.getItem(e.campaignId)));let n;try{n=yield Promise.all(t);const i=e.filter(((e,t)=>_n.isValid(e,n[t])));return i.sort(_n.comparator)}catch(t){return at.error(1,"filterAndSortCampaigns","Error filtering and sorting campaigns: ",t),[]}}));class In{}In.REMOVE_TRAIL_CHARS=/[^\w\s]+$/gi;const An=(e,t)=>{const n=Ee(e,"triggerData.primary_condition.included_filters",null);return(null==n?void 0:n.filter_operator)===hn.OR&&-1<(null==n?void 0:n.filters.findIndex((e=>e.action_name===t)))},wn=e=>fn(void 0,void 0,void 0,(function*(){var t=yield dn.exitIntentCampaignStore.getItem(e.campaignId);return e.onsitePayload=t,at.log(1,"getPrefetchedCampaign","Prefetched exit intent campaign found: "+e.campaignId),e})),Dn=e=>fn(void 0,void 0,void 0,(function*(){try{return yield dn.campaingsMetaStore.getItem(e)}catch(e){return at.error(2,"getCampaignById","Error getting campaign from store: ",e),null}})),Cn=()=>new Promise((e=>{setTimeout((()=>fn(void 0,void 0,void 0,(function*(){const t=[];yield dn.campaingsMetaStore.iterate((e=>{t.push(e)})),e(t)}))),0)})),On=e=>null===(e=Ee(e,"triggerData.secondary_condition.included_filters.filters"))||void 0===e?void 0:e.length,Pn=e=>"moe-onsite-campaign-"+e;class Rn{constructor(e,t,n,i){this.dataType=e,this.availableOperations=t,this.event=n,this.filter=i}validate(){return!(this.availableOperations.indexOf(this.filter.operator)<0)}checkEq(){let e=!1;return this.event.attributes.forEach((t=>{let n=t.value,i=this.filter.value;this.dataType===gn.STRING&&typeof n===gn.STRING&&(n=this.removeSpecialChars(n),i=this.removeSpecialChars(i)),t.key===this.filter.name&&(this.dataType!==gn.STRING||this.filter.case_sensitive?n===i&&(e=!0):n.toLowerCase()===i.toLowerCase()&&(e=!0))})),e}checkExists(){let e=!1;return this.event.attributes.forEach((t=>{t.key===this.filter.name&&(e=!0)})),e}removeSpecialChars(e){return e.replace(In.REMOVE_TRAIL_CHARS,"")}}(Ui=gn=gn||{}).BOOL="bool",Ui.STRING="string",Ui.DATE="datetime",Ui.NUMBER="double",Ui.LONG="long",Ui.ARRAY_BOOL="array_bool",Ui.ARRAY_NUMBER="array_double",Ui.ARRAY_STRING="array_string",Ui.ARRAY_DATETIME="array_datetime",(Ui=un=un||{}).ALLOF="all_of",Ui.ANYOFF="any_of";const Ln=["is","exists","contains","startsWith","endsWith","in"];class Nn extends Rn{constructor(e,t){super(gn.STRING,Ln,e,t)}evaluate(){Nn.baseLogTag;let e=!1;var t=this.event.attributes.filter((e=>e.key===this.filter.name)),n=0<t.length?t[0]:null;if(null!=n&&qe(n.value))switch(this.filter.operator){case"is":e=this.checkEq();break;case"exists":e=this.checkExists();break;case"contains":e=this.checkContains(n);break;case"startsWith":e=this.checkStartsWith(n);break;case"endsWith":e=this.checkEndsWith(n);break;case"in":e=this.checkIn(n)}return this.filter.negate?!e:e}checkContains(e){return this.filter.case_sensitive?0<=e.value.indexOf(this.filter.value):0<=e.value.toLowerCase().indexOf(this.filter.value.toLowerCase())}checkStartsWith(e){var t=(e,t)=>e.substr(0,t.length)===t;return this.filter.case_sensitive?t(e.value,this.filter.value):t(e.value.toLowerCase(),this.filter.value.toLowerCase())}checkEndsWith(e){var t=(e,t,n)=>((void 0===n||n>e.length)&&(n=e.length),e.substring(n-t.length,n)===t);if(this.filter.case_sensitive)return t(e.value,this.filter.value);const n=this.removeSpecialChars(e.value),i=this.removeSpecialChars(this.filter.value);return t(n.toLowerCase(),i.toLowerCase())}checkIn(e){let t=!1;if(Array.isArray(this.filter.value))for(let n=this.filter.value.length-1;0<=n;n--)if(this.filter.case_sensitive){if(this.filter.value[n]===e.value){t=!0;break}}else if(this.filter.value[n].toLowerCase()===e.value.toLowerCase()){t=!0;break}return t}}Nn.baseLogTag="StringDataType";const kn=["is","exists"];class Mn extends Rn{constructor(e,t){super(gn.BOOL,kn,e,t)}evaluate(){let e=!1;switch(this.filter.operator){case"is":e=this.checkEq();break;case"exists":e=this.checkExists()}return this.filter.negate?!e:e}}Mn.baseLogTag="BooleanDataType";const xn=["is","exists","greaterThan","lessThan","between","in"];class Bn extends Rn{constructor(e,t){super(gn.NUMBER,xn,e,t)}evaluate(){Bn.baseLogTag;let e=!1;var t=this.event.attributes.filter((e=>e.key===this.filter.name)),n=0<t.length?t[0]:null;if(null!=n&&"number"==typeof n.value)switch(this.filter.operator){case"is":e=this.checkEq();break;case"exists":e=this.checkExists();break;case"greaterThan":e=this.checkGreaterThan(n);break;case"lessThan":e=this.checkLessThan(n);break;case"between":e=this.checkBetween(n);break;case"in":e=this.checkIn(n)}return this.filter.negate?!e:e}checkGreaterThan(e){return e.value>this.filter.value}checkLessThan(e){return e.value<this.filter.value}checkBetween(e){return this.filter.value2?this.filter.value&&this.filter.value2&&this.filter.value<=e.value&&e.value<this.filter.value2:this.filter.value&&this.filter.value1&&this.filter.value<=e.value&&e.value<this.filter.value1}checkIn(e){return Array.isArray(this.filter.value)&&0<=this.filter.value.indexOf(e.value)}}Bn.baseLogTag="NumberDataType";const Wn=["exists","on","between","before","after","inTheLast","inTheNext","today"];class Un extends Rn{constructor(e,t){!$e(t.value)&&qe(t.value)&&(t.value=new Date(t.value.split("Z").join(""))),!$e(t.value2)&&qe(t.value2)&&null!=t.value2&&(t.value2=new Date(t.value2.split("Z").join(""))),!$e(t.value1)&&qe(t.value1)&&null!=t.value1&&(t.value1=new Date(t.value1.split("Z").join(""))),super(gn.DATE,Wn,e,t)}evaluate(){Un.baseLogTag;let e=!1;var t=this.event.attributes.filter((e=>e.key===this.filter.name));const n=0<t.length?t[0]:null;if(null!=n)switch(n.value.setHours(0,0,0,0),this.filter.operator){case"is":e=this.checkEq();break;case"exists":e=this.checkExists();break;case"on":e=this.checkOn(n);break;case"between":e=this.checkBetween(n);break;case"before":e=this.checkBefore(n);break;case"after":e=this.checkAfter(n);break;case"inTheLast":e=this.checkLastX(n);break;case"inTheNext":e=this.checkNextX(n);break;case"today":e=this.checkToday(n)}return this.filter.negate?!e:e}checkOn(e){return e.value.setHours(0,0,0,0)===this.filter.value.setHours(0,0,0,0)}checkBetween(e){return this.filter.value2?this.filter.value.getTime()<=e.value.getTime()&&e.value.getTime()<this.filter.value2.getTime():this.filter.value.getTime()<=e.value.getTime()&&e.value.getTime()<this.filter.value1.getTime()}checkBefore(e){const{value:t}=this.filter;return typeof t===ae?((new Date).setHours(0,0,0,0)-e.value.setHours(0,0,0,0))/864e5>t:e.value.setHours(0,0,0,0)<t.setHours(0,0,0,0)}checkAfter(e){const{value:t}=this.filter;return typeof t===ae?(e.value.setHours(0,0,0,0)-(new Date).setHours(0,0,0,0))/864e5>t:e.value.setHours(0,0,0,0)>t.setHours(0,0,0,0)}checkLastX(e){var t=(new Date).setHours(0,0,0,0);return 0<t-(e=e.value.setHours(0,0,0,0))&&(t-e)/864e5<=this.filter.value}checkNextX(e){var t=(new Date).setHours(0,0,0,0);return 0<(e=e.value.setHours(0,0,0,0))-t&&(e-t)/864e5<=this.filter.value}checkToday(e){return e.value.setHours(0,0,0,0)===(new Date).setHours(0,0,0,0)}}Un.baseLogTag="DateTimeDataType";const Fn=["is","exists","contains","startsWith","endsWith","in","lessThan","greaterThan","between","inTheLast","inTheNext","after","before","on","today"];class Hn extends Rn{constructor(e,t){super(t.data_type,Fn,e,t)}evaluate(){let e=!1;var t=this.event.attributes.filter((e=>e.key===this.filter.name));return null!=(t=0<t.length?t[0]:null)&&(e=>Array.isArray(e))(t.value)&&(e=this.filter.array_filter_type&&this.filter.array_filter_type===un.ANYOFF?this.checkAnyOf(t):this.checkAllOf(t)),e}checkAllOf(e){return e.value.every((t=>this.getFilterResult(t,e)))}checkAnyOf(e){return e.value.some((t=>this.getFilterResult(t,e)))}getFilterResult(e,t){let n=!1;e=this.createCustomEvent(t.key,e);const i=this.getDataType(e);return i.validate()&&(n=i.evaluate()),n}createCustomEvent(e,t){return t=new pt(e,t),new Ht(this.event.name,[t])}getDataType(e){let t;switch(this.filter.data_type){case gn.ARRAY_BOOL:t=new Mn(e,this.filter);break;case gn.ARRAY_DATETIME:t=new Un(e,this.filter);break;case gn.ARRAY_NUMBER:t=new Bn(e,this.filter);break;case gn.ARRAY_STRING:t=new Nn(e,this.filter)}return t}}class Gn{static doesEventMatchFilters(e,t){Gn.baseLogTag;let n=!1,i=null;switch(t.data_type){case gn.BOOL:i=new Mn(e,t),i.validate()&&(n=i.evaluate());break;case gn.STRING:i=new Nn(e,t),i.validate()&&(n=i.evaluate());break;case gn.NUMBER:case gn.LONG:i=new Bn(e,t),i.validate()&&(n=i.evaluate());break;case gn.DATE:i=new Un(e,t),i.validate()&&(n=i.evaluate());break;case gn.ARRAY_STRING:case gn.ARRAY_DATETIME:case gn.ARRAY_BOOL:case gn.ARRAY_NUMBER:i=new Hn(e,t),i.validate()&&(n=i.evaluate())}return n}static doesValueMatchFilter(e,t){return e=new pt(t.name,e),e=new Ht("sample event",[e]),Gn.doesEventMatchFilters(e,t)}}Gn.baseLogTag="TriggerEvaluator";class Kn{constructor(e){var t=Kn.baseLogTag+".constructor";this.campaignId=Ee(e,"campaign_id",null),this.campaignName=Ee(e,"campaign_name",null),this.templateType=Ee(e,"template_type",null),this.campaignContext=Ee(e,"campaign_context",null);var n=Ee(e,"status",null);const i=[pn.ACTIVE,pn.EXPIRED,pn.PAUSED];i.indexOf(n)<0?this.status=pn.ACTIVE:this.status=i[i.indexOf(n)],this.tag=Ee(e,"tag",null),this.triggerData=null,Vn.validate(Ee(e,"trigger"))?this.triggerData=new Vn(Ee(e,"trigger")):at.log(2,t,"Rejecting trigger data for :",e),this.expiryTime=Ye(Ee(e,"expiry_time")+"Z"),this.updatedTime=Ye(Ee(e,"updated_time")+"Z"),this.delivery=new Jn(Ee(e,"delivery")),this.userInSegment=Ee(e,"user_in_segment",!0),n=Ee(e,"display",this.display=null),t=Ee(e,"display_filter",null),this.templateType!==mn.SELF_HANDLED&&(null!=t?this.display=new Zn({rules:{uri_filters:t}},this.templateType):null!=n&&(this.display=new Zn(n,this.templateType))),this.stats={},this.onsitePayload=null,this.editorVersion=Ee(e,"editor_version",null)}static isValidMetaJSON(e){Kn.baseLogTag;let t=!0;var n=["campaign_id","campaign_name","template_type","status","expiry_time","updated_time","delivery","user_in_segment"];for(let i=0;i<n.length;i++)if(null==e[n[i]]){t=!1;break}return t}static getTriggerEvent(e,t,n){const i=Ee(t,`triggerData.${n}_condition.included_filters`,null);return null==i?void 0:i.filters.filter((t=>t.action_name===e||t.action_name===b&&"MOE_EXIT"===e))}static areFiltersAbsent(e){return!(null==e||!e.action_name||null!==(e=null==e?void 0:e.attributes)&&void 0!==e&&e.filters)}static getFilters(e){return(null==e?void 0:e.action_name)&&(null===(e=null==e?void 0:e.attributes)||void 0===e?void 0:e.filters)||null}static getFilterOperator(e){return(null==e?void 0:e.action_name)&&(null===(e=null==e?void 0:e.attributes)||void 0===e?void 0:e.filterOperator)||hn.AND}static isTriggered(e,t,n,i){let a=!0;if(0<(null==t?void 0:t.length)){let o;o=i||Kn.getFilterOperator(n);var r=t.map((t=>Gn.doesEventMatchFilters(e,t)));a=r[0]||!1;for(let e=1;e<r.length;e++)if(o===hn.AND){if(a=a&&r[e],!1===a)break}else if(o===hn.OR&&(a=a||r[e],!0===a))break}return a}static getFilterResult(e,t){return this.didPrimaryEventFilterTrigger(e,t)&&this.getURLFilterResult(t)}static didPrimaryEventFilterTrigger(e,t){var n=this.getTriggerEvent(e.name,t,"primary");for(let t=0;t<n.length;t++){var i=n[t],a=Kn.getFilters(i);if(Kn.areFiltersAbsent(i)||Kn.isTriggered(e,a,i))return!0}return!1}static getURLFilterResult(e){var t=new Ht(T,[]);const n=Kn.getTriggerEvent(t.name,e,"url");if(n){var i=n.find((e=>e.action_name===T));return e=Kn.getFilters(i),Kn.isTriggered(t,e,i)}return!0}}Kn.baseLogTag="OnsiteCampaignMeta";class Vn{constructor(e){this.cs_id=e.cs_id,this._id=e._id,this.references=e.references,this.trigger_wait_time=e.trigger_wait_time||null,Yn.validate(e.primary_condition)?this.primary_condition=new Yn(e.primary_condition):this.primary_condition=null,Yn.validate(e.secondary_condition)?this.secondary_condition=new Yn(e.secondary_condition):this.secondary_condition=null,Yn.validate(e.url_condition)?this.url_condition=new Yn(e.url_condition):this.url_condition=null,this.description=e.description,null!=e.trigger_delay?this.trigger_delay=new jn(e.trigger_delay):this.trigger_delay=null}static validate(e){let t=!1;return["primary_condition"].forEach((n=>{null!=Ee(e,n,null)&&(t=!0)})),t}}class jn{constructor(e){if(this.delay=Ee(e,"delay",0),this.unit=Ee(e,"unit","seconds"),this.delay_type=Ee(e,"delay_type",""),this.attribute=Ee(e,"attribute",""),Ee(e,"delay",null)&&Ee(e,"unit",null)){let e=this.delay;"minutes"!==this.unit&&"hours"!==this.unit&&"days"!==this.unit||(e*=60),"hours"!==this.unit&&"days"!==this.unit||(e*=60),"days"===this.unit&&(e*=24),this.delayInSeconds=e}else this.delayInSeconds=0}}class Yn{constructor(e){this.included_filters=new zn(Ee(e,"included_filters",null)),this.excluded_filters=new zn(Ee(e,"excluded_filters",null))}static validate(e){return!!(e&&(e=e.included_filters)&&Array.isArray(e.filters)&&e.filters.length&&null!=e.filter_operator)}}class zn{constructor(e){this.filter_operator=Ee(e,"filter_operator",hn.AND),this.filters=null===(e=Ee(e,"filters",[]))||void 0===e?void 0:e.map((e=>new qn(e)))}}class qn{constructor(e){var t=Ee(e,"action_name",null);"string"==typeof t&&(this.action_name=t),"boolean"==typeof(t=Ee(e,"executed",null))&&(this.executed=t),this.filter_type=Ee(e,"filter_type",null),t=Ee(e,"attributes",null),$n.validateJson(t)&&(this.attributes=new $n(t)),"nested_filters"===this.filter_type&&(this.filters=new zn(e))}}class $n{constructor(e){this.filters=[],this.filterOperator=Ee(e,"filter_operator",hn.AND),this.filters=Ee(e,"filters",[])}static validateJson(e){if(null==e)return!1;var t=["filters"];for(let n=0;n<t.length;n++)if(null==e[t[n]])return!1;return!0}}(Ui=pn=pn||{}).ACTIVE="ACTIVE",Ui.PAUSED="PAUSED",Ui.EXPIRED="EXPIRED",(Ui=hn=hn||{}).AND="and",Ui.OR="or";class Jn{constructor(e){this.priority=Ee(e,"priority",0),this.dismiss_interval=Ee(e,"dismiss_interval",0),this.fc_meta=new Xn(Ee(e,"fc_meta",null))}}class Xn{constructor(e){this.count=0,this.delay=0,this.ignore_global_delay=!1,null!=e&&(this.count=Ee(e,"count",0),this.delay=Ee(e,"delay",0),this.ignore_global_delay=Ee(e,"ignore_global_delay",!1))}}class Qn{constructor(e){this.aggregations=[],this.filters=[],this.aggregations=Ee(e,"aggregations",[]),this.filter_operator=Ee(e,"filter_operator",hn.AND),this.filters=Ee(e,"filters",[])}}class Zn{constructor(e,t){this.config={blocking:Ee(e,"config.blocking",Zn.getDefaultValue("blocking",t)),pushPage:Ee(e,"config.push_page",Zn.getDefaultValue("push_page",t)),sticky:Ee(e,"config.sticky",Zn.getDefaultValue("sticky",t)),scrollable:Ee(e,"config.scrollable",Zn.getDefaultValue("scrollable",t)),showOverOtherCampaigns:Ee(e,"config.show_over_campaigns",Zn.getDefaultValue("show_over_campaigns",t))},this.rules={uriFilters:new Qn(Ee(e,"rules.uri_filters",{}))}}static getDefaultValue(e,t){return{blocking:{POP_UP:!0,BANNER:!1},push_page:{POP_UP:!1,BANNER:!0},sticky:{POP_UP:!1,BANNER:!0},scrollable:{POP_UP:!1,BANNER:!0},show_over_campaigns:{POP_UP:!1,BANNER:!1}}[e][t]}}(Ui=mn=mn||{}).SELF_HANDLED="SELF_HANDLED",Ui.POP_UP="POP_UP",Ui.BANNER="BANNER";class ei{constructor(e,t){this.channel=e,this.target=t}sendMessage(e,t){return new Promise(((n,i)=>{var a={id:(0,ct.v4)(),channel:this.channel,topic:e,message:t};this.addToListener(a,n,i),this.target instanceof HTMLIFrameElement?this.target.contentWindow.postMessage(a,this.target.src):this.target.postMessage(a,"*")}))}static listenToChannel(e,t,n){window.addEventListener("message",(i=>{i.data&&i.data.channel&&i.data.topic&&i.data.channel===e&&i.data.topic===t&&n(i.data,(n=>{n={id:i.data.id,channel:e,topic:t,message:n},i.source.postMessage(n,i.origin)}))}))}addToListener(e,t,n){ei.pendingPromises[e.id]={resolve:t,reject:n},window.addEventListener("message",(e=>{e.data&&Ee(e.data,"channel",null)===this.channel&&null!=ei.pendingPromises[e.data.id]&&(ei.pendingPromises[e.data.id].resolve(e.data),delete ei.pendingPromises[e.data.id])}))}}ei.pendingPromises={};class ti{constructor(e){this.draftId=Ee(e,"draft_id",null),this.draftType=Ee(e,"draft_type",null),this.templateType=Ee(e,"template_type",null),this.action=Ee(e,"action",null);var t=Ee(e,"campaign_meta",{});this.locale=Ee(e,"locale",null),this.variation=Ee(e,"variation",null),this.displaySettings=new Zn({config:t.config},this.templateType)}static isValidRawJson(e){var{draft_id:t,draft_tag:n,draft_type:e}=e;return e===Z.DRAFT_CAMPAIGN_TPYES.WEB_PERSONALIZATON?null!=t&&null!=n:null!=t}}class ni{getIframe(){return null==this.iFramePromise&&(this.iFramePromise=new Promise((e=>{const t=document.createElement("iframe");t.id="moengage-web-helper-frame",t.style.display="none",t.src=Z.WEB_HELPER_IFRAME_URL,document.body.appendChild(t),t.addEventListener("load",(()=>{this.helper=new ei(Z.IFRAME_CHANNEL,t),e(t)}))}))),this.iFramePromise}getDraftCampaignInfo(){return function(e,t,n,i){return new(n=n||Promise)((function(t,a){function r(e){try{s(i.next(e))}catch(e){a(e)}}function o(e){try{s(i.throw(e))}catch(e){a(e)}}function s(e){var i;e.done?t(e.value):((i=e.value)instanceof n?i:new n((function(e){e(i)}))).then(r,o)}s((i=i.apply(e,[])).next())}))}(this,0,void 0,(function*(){var e="IframeHelper.getDraftCampaignInfo";try{at.log(1,e,"Loading helper frame"),yield this.getIframe(),at.log(1,e,"Helper frame loaded");var t=yield this.helper.sendMessage(Z.IFRAME_TOPICS.COOKIE_STORAGE,{TYPE:"GET",KEY:Z.COOKIE_STORAGE.TEST_DRAFT_ID});at.log(1,e,"Data from iframe: ",t);var n=t.message;at.log(1,e,"Raw test campaign",n);let i=null;return null!=n&&(ti.isValidRawJson(n)?i=new ti(n):at.error(1,e,"Data is not a valid test campaign")),i}catch(e){return null}}))}}class ii{constructor(e){this.templateType=Ee(e,"template_type",null),this.payloadType=Ee(e,"payload_type",null),this.payload=Ee(e,"payload",null),this.position=Ee(e,"position",null),this.campaignContext=Ee(e,"campaign_context",null),this.editorVersion=Ee(e,"editor_version",null),this.htmlJsonPayload=JSON.parse(Ee(e,"html_json_payload",null)),this.updatedTime=Ye(Ee(e,"updated_time")+"Z")}}var ai=function(e,t,n,i){return new(n=n||Promise)((function(a,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function s(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?a(e.value):((t=e.value)instanceof n?t:new n((function(e){e(t)}))).then(o,s)}l((i=i.apply(e,t||[])).next())}))};class ri{constructor(e){this.appId=e.appId,this.store=Se.createInstance({driver:[Se.INDEXEDDB,Se.WEBSQL,Se.LOCALSTORAGE],name:Z.DATABASE_NAME,storeName:Z.STORES.SERVICE_META.NAME}),this.host=e.baseDomainName}getUserSessionAttributes(){var e=function(){const e=new Date;return{day:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][e.getDay()],hours:String(e.getHours()).padStart(2,"0")}}();const t=new dt;var n=Qe(window.location.search);return Object.assign(Object.assign({},n),{USER_TYPE:1<t.getNumberOfSessions()?"Returning":"New",DAY_OF_THE_WEEK:e.day,TIME_OF_THE_DAY:e.hours})}getCampaignsMeta(){return ai(this,void 0,void 0,(function*(){var e=ri.baseLogTag+".getCampaignsMeta";try{var t=yield this.getRequestOptions();const e=yield this.store.getItem(Z.STORES.SERVICE_META.KEYS.LAST_META_CALL_TIME);var n=yield ot.post(this.host+Z.API.META,Object.assign(Object.assign({},t),{postData:{campaign_ids:[],user_session_attributes:this.getUserSessionAttributes()},last_fetch_time:e&&"object"==typeof e?e.toISOString():e}));this.store.setItem(Z.STORES.SERVICE_META.KEYS.LAST_META_CALL_TIME,new Date),this.store.setItem(Z.STORES.SERVICE_META.KEYS.UNIQUE_ID,t.queryParams.unique_id);const i=JSON.parse(n.responseText),a=[];return i.campaigns.forEach((e=>{Kn.isValidMetaJSON(e)&&a.push(new Kn(e))})),{campaignsMeta:a,globalDelayBetweenInapps:Ee(i,"min_delay_btw_inapps",0)}}catch(t){throw at.error(1,e,"Error getting meta for inapp: ",t),new Error("Could not get meta payload")}}))}getCampaignPayload(e,t){return ai(this,void 0,void 0,(function*(){var n=ri.baseLogTag+".getCampaignPayload";let i;try{if(t){const n={};for(let e=0;e<t.attributes.length;e++)n[t.attributes[e].key]=t.attributes[e].value;var a={event:{name:t.name,attributes:n,time:(new Date).toISOString()},contexts:["string"],campaign_context:e.campaignContext,user_session_attributes:this.getUserSessionAttributes()};i=yield ot.post(this.host+Z.API.CAMPAIGN_PAYLOAD+e.campaignId,yield this.getRequestOptions(a))}else i=yield ot.post(this.host+Z.API.CAMPAIGN_PAYLOAD+e.campaignId,yield this.getRequestOptions());return i=JSON.parse(i.responseText),i.code===Z.GCG_ERROR_CODE&&(i={payload:i}),new ii(i)}catch(i){if(at.error(1,n,"Error geting payload",i),i.code&&(409===i.code||400===i.code)&&i.reason)return{error:!0,reason:JSON.parse(i.reason).description||""};throw new Error("Could not get payload for "+e.campaignId)}}))}getCampaignsPayload(e,t){return ai(this,void 0,void 0,(function*(){var n=ri.baseLogTag+".getCampaignsPayload";let i;try{if(t){const n={};for(let e=0;e<t.attributes.length;e++)n[t.attributes[e].key]=t.attributes[e].value;var a={event:{name:t.name,attributes:n,time:(new Date).toISOString()},contexts:["string"],campaign_ids:e};i=yield ot.post(this.host+Z.API.CAMPAIGNS_PAYLOAD,this.getRequestOptions(a))}else i=yield ot.post(this.host+Z.API.CAMPAIGNS_PAYLOAD,this.getRequestOptions());const n=[];return JSON.parse(i.responseText).forEach((e=>{n.push(new ii(e))})),n}catch(i){throw at.error(1,n,"Error geting payload",i),new Error("Could not get payload for "+e)}}))}getDraftCampaign(e){return ai(this,void 0,void 0,(function*(){var t=ri.baseLogTag+".getDraftCampaign";try{const t=yield this.getRequestOptions();t.queryParams=Object.assign({},t.queryParams,{locale:e.locale,variation:e.variation});var n=yield ot.get(this.host+Z.API.DRAFT_CAMPAIGN_PAYLOAD+e.draftId,t);const i=JSON.parse(n.responseText);return"JSON"===i.payload_type&&(i.payload=JSON.parse(i.payload)),new ii(i)}catch(n){return at.error(1,t,"Error geting test campaign payload",n),null}}))}getRequestOptions(e){const t=ze();return zt.getWebSDKSettings().then((n=>{var i=xe.get(r.USER_DATA);let a;const{deviceUuid:o,attributes:s}=i;if(s.map((e=>{e.key===I&&(a=e.value)})),!o)throw new Error("device_unique_id not found in localStorage.");var l=Ke()?"mweb":"web";return i=je(),{headers:{"Content-Type":"application/json","MOE-APPKEY":this.appId},queryParams:Object.assign({sdk_ver:t.getSdkVersion(),unique_id:o,uid:n.configs.shouldSendUID?a:void 0,os:l},i),postData:e||{}}})).catch((e=>{throw new Error("Error in getting Web SDK Settings. This might indicate that the App is blocked.")}))}sendDeliveryFunnelStats(e,t){return ai(this,void 0,void 0,(function*(){const n=ri.baseLogTag+".sendDeliveryFunnelStats";try{var i=yield this.getRequestOptions(null);return ot.post(this.host+Z.API.STATS,Object.assign(Object.assign({},i),{headers:Object.assign(Object.assign({},i.headers),{"MOE-INAPP-BATCH-ID":t}),postData:e})).then((()=>{at.log(1,n,"Delivery Funnel stats sent to Moengage: ",e)})).catch((e=>{at.warn(1,n,"Error sending campaign stats: ",e)}))}catch(i){at.warn(1,n,"Error sending campaign stats: ",i)}}))}}ri.baseLogTag="OnsiteApi";class oi{constructor(){this.isExitIntentShown=!1,this.isPopStateEventBound=!1}onScroll(e){const t=oi.baseLogTag+".onScroll";null==e&&(e=()=>{});var n=oi.throttle((()=>{at.remoteLogTracking(1,"info",t,"Scrolled percent:",oi.getScrollPercent()),e(oi.getScrollPercent())}),Z.SCROLL_CAMPAIGN_THROTTLING_TIME);return e(oi.getScrollPercent()),window.addEventListener("scroll",n),n}onMobileTabChange(e){const t=oi.baseLogTag+".onMobileTabChange";document.addEventListener("visibilitychange",(()=>{this.isExitIntentShown||"hidden"!==document.visibilityState||(at.log(1,t,"TRIGGERED: MOBILE EXIT INTENT"),e(),this.isExitIntentShown=!0)}))}onMobileBackHit(e){const t=oi.baseLogTag+".onMobileBackHit";setTimeout((()=>{this.isPopStateEventBound=!0,window.addEventListener("popstate",(n=>{!this.isExitIntentShown&&n.state&&"exit_intent"===n.state.moeIntent&&(at.log(1,t,"TRIGGERED: MOBILE EXIT INTENT"),e("onBackClick"),this.isExitIntentShown=!0)}))}),1e3),this.setHistoryState()}setHistoryState(){window.history.state&&"no_intent"===window.history.state.moeIntent||(window.history.replaceState(Object.assign(Object.assign({},window.history.state),{moeIntent:"exit_intent"}),""),window.history.pushState(Object.assign(Object.assign({},window.history.state),{moeIntent:"no_intent"}),""))}onMobileScrollAndExit(e){const t=oi.baseLogTag+".onMobileScrollAndExit",n=document.documentElement.offsetHeight;let i,a=oi.getScrollY();0<n&&(this.scrollExitIntentInterval=window.setInterval((()=>{let r=a-oi.getScrollY();r<0&&(r=0,a=oi.getScrollY()),i=oi.getScrollPercent()>Z.EXIT_INTENT.CONFIG.SCROLL_DOWN_THRESHOLD,i&&r/n>Z.EXIT_INTENT.CONFIG.SCROLL_UP_THRESHOLD/100&&(clearInterval(this.scrollExitIntentInterval),this.scrollExitIntentInterval=null,this.isExitIntentShown||(at.log(1,t,"TRIGGERED: MOBILE EXIT INTENT"),e(),this.isExitIntentShown=!0))}),Z.EXIT_INTENT.CONFIG.SCROLL_INTERVAL))}mobileExitIntent(e){this.onMobileScrollAndExit(e),this.onMobileBackHit(e),this.onMobileTabChange(e)}onExit(e){const t=oi.baseLogTag+".onExit";Ke()?this.mobileExitIntent(e):(this.exitIntentListener=n=>function(e,t,n,i){return new(n=n||Promise)((function(t,a){function r(e){try{s(i.next(e))}catch(e){a(e)}}function o(e){try{s(i.throw(e))}catch(e){a(e)}}function s(e){var i;e.done?t(e.value):((i=e.value)instanceof n?i:new n((function(e){e(i)}))).then(r,o)}s((i=i.apply(e,[])).next())}))}(this,0,void 0,(function*(){var i=window.innerWidth,a=window.innerHeight;(n.clientY<0||n.clientX<0||n.clientY>=a||n.clientX>=i)&&(at.log(1,t,"TRIGGERED: EXIT INTENT"),e())})),document.addEventListener("mouseout",this.exitIntentListener,!1))}static getScrollPercent(){const e=window,t=document,n=t.documentElement,i=t.getElementsByTagName("body")[0],a=e.innerHeight||n.clientHeight||i.clientHeight;var r=document.body,o=document.documentElement;return a<(o=Math.max(r.scrollHeight,r.offsetHeight,o.clientHeight,o.scrollHeight,o.offsetHeight))?100*oi.getScrollY()/(o-a):100}static getScrollY(){let e=0;return"number"==typeof window.pageYOffset?e=window.pageYOffset:document.body&&document.body.scrollTop&&(e=document.body.scrollTop),e}static throttle(e,t){let n;return(...i)=>{n=n||window.setTimeout((()=>{n=null,e.apply(null,i)}),t)}}}oi.baseLogTag="WindowEventManager";var si=function(e,t,n,i){return new(n=n||Promise)((function(a,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function s(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?a(e.value):((t=e.value)instanceof n?t:new n((function(e){e(t)}))).then(o,s)}l((i=i.apply(e,t||[])).next())}))};class li{static getPendingSecondaryEventCampaign(e){return si(this,void 0,void 0,(function*(){return yield dn.pendingSecondaryEvents.getItem(e)}))}static setPendingSecondaryEventCampaign(e,t){return si(this,void 0,void 0,(function*(){yield dn.pendingSecondaryEvents.setItem(e,t)}))}static removePendingSecondaryEventCampaign(e){return si(this,void 0,void 0,(function*(){yield dn.pendingSecondaryEvents.removeItem(e)}))}static getPendingSecondaryEventKeys(){return si(this,void 0,void 0,(function*(){return yield dn.pendingSecondaryEvents.keys()}))}static getPendingTimerCampaign(e){return si(this,void 0,void 0,(function*(){return yield dn.pendingTimerCampaigns.getItem(e)}))}static setPendingTimerCampaign(e,t){return si(this,void 0,void 0,(function*(){yield dn.pendingTimerCampaigns.setItem(e,t)}))}static removePendingTimerCampaign(e){return si(this,void 0,void 0,(function*(){yield dn.pendingTimerCampaigns.removeItem(e)}))}static getPendingTimerKeys(){return si(this,void 0,void 0,(function*(){return yield dn.pendingTimerCampaigns.keys()}))}static getTriggeringPrimaryEvent(e){return si(this,void 0,void 0,(function*(){return yield dn.triggeringPrimaryEvents.getItem(e)}))}static setTriggeringPrimaryEvent(e,t){return si(this,void 0,void 0,(function*(){yield dn.triggeringPrimaryEvents.setItem(e,t)}))}static removeTriggeringPrimaryEvent(e){return si(this,void 0,void 0,(function*(){yield dn.triggeringPrimaryEvents.removeItem(e)}))}static getTriggeringPrimaryEventKeys(){return si(this,void 0,void 0,(function*(){return yield dn.triggeringPrimaryEvents.keys()}))}static removeCampaignFromStores(e){return si(this,void 0,void 0,(function*(){yield li.removePendingSecondaryEventCampaign(e),yield li.removePendingTimerCampaign(e)}))}}var ci=function(e,t,n,i){return new(n=n||Promise)((function(a,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function s(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?a(e.value):((t=e.value)instanceof n?t:new n((function(e){e(t)}))).then(o,s)}l((i=i.apply(e,t||[])).next())}))};class di{static setListener(e){this.listener=e}static destroy(){this.listener=null,this.deliveryStats=null}static setDeliveryStats(e){this.deliveryStats=e}static createNewTimers(){return ci(this,void 0,void 0,(function*(){var e=this.baseLogTag+".createNewTimers",t=yield li.getPendingTimerKeys();for(let a=0;a<t.length;a++){var n=t[a],i=(i=yield li.getPendingTimerCampaign(n)).timer-(Date.now()-i.startTime);at.log(1,e,`Creating new setTimeout with time: ${i} ms for the campaign: `+n),yield this.createPendingTimerCampaign(n,i)}}))}static deletePendingTimer(e){return ci(this,void 0,void 0,(function*(){var t=this.baseLogTag+".deletePendingTimer",n=yield li.getPendingTimerCampaign(e);null!=n&&n.timerId&&(at.log(1,t,`There was an existing setTimeout associated to the campaign: ${e}. Clearing it`),clearTimeout(n.timerId))}))}static deleteAllPendingTimers(){return ci(this,void 0,void 0,(function*(){var e=this.baseLogTag+".deleteAllPendingTimers";at.log(1,e,"Clearing all setTimeout's associated to different campaign(s)");var t=yield li.getPendingTimerKeys();for(let e=0;e<t.length;e++){var n=t[e];n=yield li.getPendingTimerCampaign(n),clearTimeout(n.timerId)}}))}static createPendingTimerCampaign(e,t){return ci(this,void 0,void 0,(function*(){yield this.deletePendingTimer(e);var n=setTimeout((()=>ci(this,void 0,void 0,(function*(){yield this.checkAndInvokeListener(e),yield li.removeCampaignFromStores(e)}))),t);n={startTime:Date.now(),timerId:n,timer:t},yield li.setPendingTimerCampaign(e,n)}))}static checkAndInvokeListener(e){return ci(this,void 0,void 0,(function*(){var t=this.baseLogTag+".checkAndInvokeListener",n=yield Dn(e);null!=n&&n.campaignId&&((yield this.isSatisfyingEventsArray(e))?Kn.getURLFilterResult(n)&&(at.log(1,t,`Campaign ${e} satisfies the secondary_condition and the url_condition after timer has elapsed`),this.closeProximityTimerCampaigns.push(n),this.closeProximityCampaignsTimeout||(this.closeProximityCampaignsTimeout=setTimeout((()=>{this.listener(this.closeProximityTimerCampaigns),this.closeProximityTimerCampaigns=[],this.closeProximityCampaignsTimeout=null}),500))):(at.warn(1,t,`Campaign: ${e} does not satisfy secondary_condition after its timer has elapsed. Removing its entry from secondary stores`),this.deliveryStats.setStats(n,Z.DELIVERY_FUNNEL.ATTEMPTED.CAMPAIGN_ATTEMPTED),this.deliveryStats.setStats(n,Z.DELIVERY_FUNNEL.EVALUATION.CAMPAIGN_EVALUATION_PATH_TIME_EXPIRED),this.deliveryStats.sendDeliveryStats([n])))}))}static checkIfPendingAction(e,t){return t===hn.AND&&!e.events.some((e=>1===e.filters.length&&!e.filters[0].executed))}static isSatisfyingEventsArray(e){return ci(this,void 0,void 0,(function*(){var t=yield li.getPendingSecondaryEventCampaign(e);if(null!=t&&t.events){if(!t.events.length)return!0;var n=t.operator;for(let e=0;e<t.events.length;e++){var i=t.events[e],a=i.operator;let r=!1,o=!1;for(let e=0;e<i.filters.length;e++)if(i.filters[e].executed){if(this.checkIfPendingAction(t,a))return!1;r=!0}else o=!0;if(n===hn.AND&&a===hn.OR&&r&&!o)return!1}return!0}return!1}))}static logDeliveryFunnelForExpiredTimerCampaigns(){return ci(this,void 0,void 0,(function*(){var e=this.baseLogTag+".logDeliveryFunnelForExpiredTimerCampaigns",t=yield li.getPendingTimerKeys(),n=Date.now();const i=[];for(let o=0;o<t.length;o++){var a=t[o],r=yield li.getPendingTimerCampaign(a);n-r.startTime>=r.timer&&(yield this.isSatisfyingEventsArray(a))&&null!=(r=yield Dn(a))&&r.campaignId&&(at.warn(1,e,`Campaign: ${a} contained 'has not executed' event(s) and had satisfied secondary_condition, but the website was closed when the timer elapsed`),i.push(r),yield this.deleteTimerAndRemoveFromStores(a))}this.sendUserNotOnAppStat(i)}))}static sendUserNotOnAppStat(e){for(let n=0;n<e.length;n++){var t=e[n];this.deliveryStats.setStats(t,Z.DELIVERY_FUNNEL.ATTEMPTED.CAMPAIGN_ATTEMPTED),this.deliveryStats.setStats(t,Z.DELIVERY_FUNNEL.EVALUATION.CAMPAIGN_EVALUATION_USER_NOT_ON_APP)}this.deliveryStats.sendDeliveryStats(e)}static deleteTimerAndRemoveFromStores(e){return ci(this,void 0,void 0,(function*(){yield this.deletePendingTimer(e),yield li.removeCampaignFromStores(e)}))}}di.baseLogTag="CampaignTimerManager",di.listener=null,di.deliveryStats=null,di.closeProximityTimerCampaigns=[],di.closeProximityCampaignsTimeout=null;var gi=function(e,t,n,i){return new(n=n||Promise)((function(a,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function s(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?a(e.value):((t=e.value)instanceof n?t:new n((function(e){e(t)}))).then(o,s)}l((i=i.apply(e,t||[])).next())}))};class ui{static setDeliveryStats(e){this.deliveryStats=e}static destroy(){this.deliveryStats=null}static createPendingSecondaryEvents(e,t){return gi(this,void 0,void 0,(function*(){var n=this.baseLogTag+".createPendingSecondaryEvents";for(let o=0;o<e.length;o++){var i,a,r=e[o];On(r)&&(({campaignEntry:i,isCampaignTimerSet:a}=this.constructCampaignEntry(r)),yield li.setTriggeringPrimaryEvent(r.campaignId,t),yield li.setPendingSecondaryEventCampaign(r.campaignId,i),a&&(at.log(1,n,`The campaign: ${r.campaignId} has at least one 'has not executed' secondary event. Starting timer for this campaign. Time remaining: ${i.time_left} ms`),yield di.createPendingTimerCampaign(r.campaignId,i.time_left)))}}))}static constructCampaignEntry(e){const t=e.triggerData.secondary_condition.included_filters,n={operator:t.filter_operator,events:[]};let i=!1;return t.filters.forEach((e=>{if("nested_filters"===e.filter_type){const t={operator:e.filters.filter_operator,filters:[]};e.filters.filters.forEach((e=>{t.filters.push(e),!1===e.executed&&(i=!0)})),n.events.push(t)}else{var t={operator:n.operator===hn.AND?hn.OR:hn.AND,filters:[e]};n.events.push(t),!1===e.executed&&(i=!0)}})),n.updated_time=Date.now(),n.time_left=1e3*e.triggerData.trigger_wait_time.wait_period,{campaignEntry:n,isCampaignTimerSet:i}}static pruneRemovedCampaigns(){return gi(this,void 0,void 0,(function*(){var e=this.baseLogTag+".pruneRemovedCampaigns";const t=(yield Cn()).map((e=>e.campaignId));var n=yield li.getPendingSecondaryEventKeys();for(let a=0;a<n.length;a++){var i=n[a];t.includes(i)||(at.warn(1,e,`The campaign: $${i} is not present in the latest meta call. Removing its entry from secondary stores and removing any pending timer`),yield di.deleteTimerAndRemoveFromStores(i))}}))}static updateCampaignTimeInSecondaryEventsStore(){return gi(this,void 0,void 0,(function*(){var e=this.baseLogTag+".updateCampaignTimeInSecondaryEventsStore",t=yield li.getPendingSecondaryEventKeys();const n=[];for(let r=0;r<t.length;r++){var i=t[r];const o=yield li.getPendingSecondaryEventCampaign(i);var a=Date.now();o.time_left-=a-o.updated_time,o.updated_time=a,o.time_left<=0?(null!=(a=yield Dn(i))&&a.campaignId&&(at.warn(1,e,`Campaign: ${i} does not have time left to render. Removing its entry from secondary stores and clearing any setTimeout associated to it`),n.push(a)),yield di.deleteTimerAndRemoveFromStores(i)):yield li.setPendingSecondaryEventCampaign(i,o)}this.sendPathTimeExpiredStat(n)}))}static updatePendingSecondaryEventsHistory(e,t){return gi(this,void 0,void 0,(function*(){var n=this.baseLogTag+".updatePendingSecondaryEventsHistory";const i=[],a=[],r=[];var o=Date.now();for(let p=0;p<t.length;p++){var s=t[p];const h=yield li.getPendingSecondaryEventCampaign(s);if(h)if(h.time_left-=o-h.updated_time,h.updated_time=o,h.time_left<=0){var l=yield Dn(s);null!=l&&l.campaignId&&(at.warn(1,n,`Campaign ${s} which is associated to the event: ${e.name} does not have time left to render. Removing its entry from secondary stores and clearing any setTimeout associated to it`),r.push(l)),a.push(s)}else{var c=h.operator;for(let t=0;t<h.events.length;t++){const r=h.events[t];var d=r.operator;for(let t=0;t<r.filters.length;t++){const o=r.filters[t];var g=o.attributes,u=o.executed;e.name===o.action_name&&(g&&Kn.isTriggered(e,g.filters,null,g.filterOperator)||!e.attributes||!e.attributes.length)&&(u?d===hn.OR?(r.toBeRemoved=!0,c!==hn.OR&&(c!==hn.AND||h.events.length&&!h.events.every((e=>e.toBeRemoved)))||(at.log(1,n,`Campaign: ${s}, triggered by event: ${e.name}, is eligible for further processing`),i.push(s))):d===hn.AND&&(o.toBeRemoved=!0,r.filters.every((e=>e.toBeRemoved))&&(r.toBeRemoved=!0,(c===hn.OR||c===hn.AND&&h.events.every((e=>e.toBeRemoved)))&&(at.log(1,n,`Campaign: ${s}, triggered by event: ${e.name}, is eligible for further processing`),i.push(s)))):d===hn.OR?(o.toBeRemoved=!0,r.filters.every((e=>e.toBeRemoved))&&(c===hn.AND||c===hn.OR&&1===h.events.length?(at.warn(1,n,`The event: ${e.name} breaks secondary conditons of the campaign: ${s}. Removing the campaign from secondary stores and clearing any setTimeout associated to it`),a.push(s)):r.toBeRemoved=!0)):d===hn.AND&&(r.toBeRemoved=!0,1===h.events.length&&h.events[0].toBeRemoved&&c===hn.OR&&(at.warn(1,n,`The event: ${e.name} breaks secondary conditons of the campaign: ${s}. Removing the campaign from secondary stores and clearing any setTimeout associated to it`),a.push(s))))}}a.includes(s)||i.includes(s)||(yield this.updatePendingSecondaryEvents(s,h))}}return this.sendPathTimeExpiredStat(r),yield this.clearCampaignsData(a),yield this.clearCampaignsData(i),i}))}static sendPathTimeExpiredStat(e){for(let n=0;n<e.length;n++){var t=e[n];this.deliveryStats.setStats(t,Z.DELIVERY_FUNNEL.ATTEMPTED.CAMPAIGN_ATTEMPTED),this.deliveryStats.setStats(t,Z.DELIVERY_FUNNEL.EVALUATION.CAMPAIGN_EVALUATION_PATH_TIME_EXPIRED)}this.deliveryStats.sendDeliveryStats(e)}static updatePendingSecondaryEvents(e,t){return gi(this,void 0,void 0,(function*(){t.events=t.events.filter((e=>!e.toBeRemoved));for(let e=0;e<t.events.length;e++){const n=t.events[e];n.filters=n.filters.filter((e=>!e.toBeRemoved))}yield li.setPendingSecondaryEventCampaign(e,t)}))}static clearCampaignsData(e){return gi(this,void 0,void 0,(function*(){for(let t=0;t<e.length;t++)yield di.deleteTimerAndRemoveFromStores(e[t])}))}static removeStaleTriggeringPrimaryEventCampaigns(){return gi(this,void 0,void 0,(function*(){const e=this.baseLogTag+".removeStaleTriggeringPrimaryEventCampaigns",t=yield li.getTriggeringPrimaryEventKeys(),n=yield li.getPendingSecondaryEventKeys();t.forEach((t=>gi(this,void 0,void 0,(function*(){n.includes(t)||(at.warn(1,e,`Campaign: ${t} does not exist in pendingSecondaryEvents store but exists in triggeringPrimaryEvents store. Removing it from triggeringPrimaryEvents store`),yield li.removeTriggeringPrimaryEvent(t))}))))}))}}ui.baseLogTag="SecondaryEventsManager",ui.deliveryStats=null;var pi=function(e,t,n,i){return new(n=n||Promise)((function(a,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function s(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?a(e.value):((t=e.value)instanceof n?t:new n((function(e){e(t)}))).then(o,s)}l((i=i.apply(e,t||[])).next())}))};class hi{constructor(e){this.primaryEventsHash={},this.secondaryEventsHash={},this.messagingCampaigns=[],this.scrollCampaigns=[],this.scrollCampaignTriggered=!1,this.exitIntentCampaigns=[],this.exitCampaignTriggered=!1,this.listener=null,this.historyManager=window[Q],this.onEvent=e=>pi(this,void 0,void 0,(function*(){var t=hi.baseLogTag+".onEvent";try{null!=this.primaryEventsHash[e.name]&&(yield this.handlePrimaryEvent(e)),null!=this.secondaryEventsHash[e.name]&&(yield this.handleSecondaryEvent(e))}catch(e){at.error(1,t,"Error occurred during check event trigger campaigns: ",e)}})),this.onScroll=e=>pi(this,void 0,void 0,(function*(){const t=hi.baseLogTag+".onScroll";try{if(this.scrollCampaigns&&0<this.scrollCampaigns.length&&!this.scrollCampaignTriggered){var n=yield this.getCampaignsFromHash(_);const i=yield Tn(n);null!=i&&i.map((n=>pi(this,void 0,void 0,(function*(){var i,a=null===(i=null===(a=null===(i=null===(a=null===(i=null==n?void 0:n.triggerData)||void 0===i?void 0:i.primary_condition)||void 0===a?void 0:a.included_filters)||void 0===i?void 0:i.filters[0])||void 0===a?void 0:a.attributes)||void 0===i?void 0:i.filters[0];a&&(i=new pt(a.name,a.value),i=yield Ht.createEvent(_,[i]),Kn.getFilterResult(i,n)&&e>a.value&&!this.scrollCampaignTriggered&&(this.scrollCampaignTriggered=!0,window.removeEventListener("scroll",this.scrollListenerCallback),at.log(1,t,"Triggered Scroll campaign"),this.trigger([n],i)))}))))}}catch(n){at.error(1,t,"Error occurred in triggering scroll campaigns ",n)}})),this.onExit=e=>pi(this,void 0,void 0,(function*(){var t=hi.baseLogTag+".onExit";try{if(0<this.exitIntentCampaigns.length&&!this.exitCampaignTriggered){const i=yield Ht.createEvent("MOE_EXIT",[]);var n=(yield this.getCampaignsFromHash(b)).filter((e=>Kn.getFilterResult(i,e)));n.length?(at.log(1,t,"Triggered Exit Intent campaign: ",n),this.trigger(n,i)):("onBackClick"===e&&window.history.back(),at.log(1,t,"No Exit Intent campaign is eligible."))}}catch(n){at.error(1,t,"Error occurred in triggering exit intent campaigns ",n)}})),this.messagingCampaigns=e,this.windowEventManager=new oi}onTrigger(e){this.listener=e}handlePrimaryEvent(e){return pi(this,void 0,void 0,(function*(){var t=hi.baseLogTag+".handlePrimaryEvent",n=this.primaryEventsHash[e.name];const i=[],a=[];for(let e=0;e<n.length;e++){var r=n[e];r=yield Dn(r),On(r)?i.push(r):Ee(r,"triggerData.primary_condition.included_filters.filter_operator")===hn.OR&&a.push(r)}var o=i.filter((t=>Kn.didPrimaryEventFilterTrigger(e,t)));o.length&&(yield ui.createPendingSecondaryEvents(o,e)),o=a.filter((t=>Kn.getFilterResult(e,t))),o.length&&(at.log(1,t,`Campaigns triggered for event ${e.name}: `+o.length),this.trigger(o,e))}))}handleSecondaryEvent(e){return pi(this,void 0,void 0,(function*(){var t=hi.baseLogTag+".handleSecondaryEvent",n=yield ui.updatePendingSecondaryEventsHistory(e,this.secondaryEventsHash[e.name]);let i=[];for(let e=0;e<n.length;e++)i.push(yield Dn(n[e]));i=i.filter((e=>Kn.getURLFilterResult(e))),i.length&&(at.log(1,t,`Campaigns triggered by secondary event "${e.name}": `+i.length),this.trigger(i))}))}getCampaignsFromHash(e){return pi(this,void 0,void 0,(function*(){const t=[];var n=this.primaryEventsHash[e];if(null!=n&&n.length)for(let e=0;e<n.length;e++)t.push(yield Dn(n[e]));return t}))}addEntryInEventsHash(e,t,n){null==e[t]&&(e[t]=[]),e[t].push(n)}createPrimaryEventsHash(e){Ee(e,"triggerData.primary_condition.included_filters.filters",[]).forEach((t=>{this.addEntryInEventsHash(this.primaryEventsHash,t.action_name,e.campaignId)}))}createSecondaryEventsHash(e){const t=Ee(e,"triggerData.secondary_condition.included_filters.filters",[]);null!=t&&t.forEach((t=>{"nested_filters"===t.filter_type?t.filters.filters.forEach((t=>{this.addEntryInEventsHash(this.secondaryEventsHash,t.action_name,e.campaignId)})):this.addEntryInEventsHash(this.secondaryEventsHash,t.action_name,e.campaignId)}))}startWatching(){return pi(this,void 0,void 0,(function*(){hi.baseLogTag,this.messagingCampaigns.forEach((e=>{this.createPrimaryEventsHash(e),this.createSecondaryEventsHash(e)})),this.historyManager&&(this.historyManager.getHistory().forEach(this.onEvent),this.historyManager.addEventListener(this.onEvent)),this.scrollCampaignTriggered=!1,this.scrollCampaigns=this.messagingCampaigns.filter((e=>An(e,_))),0<this.scrollCampaigns.length&&(this.scrollListenerCallback=this.windowEventManager.onScroll(this.onScroll)),this.exitCampaignTriggered=!1,this.exitIntentCampaigns=this.messagingCampaigns.filter((e=>An(e,b))),0<this.exitIntentCampaigns.length&&this.windowEventManager.onExit(this.onExit)}))}setScrollListenerCallback(e){this.scrollListenerCallback=e}getScrollListenerCallback(){return this.scrollListenerCallback}getWindowEventManager(){return this.windowEventManager}trigger(e,t){null!=this.listener&&this.listener(e,t)}destory(){this.listener=null}}hi.baseLogTag="OnsiteTriggerManager";class mi{constructor(e,t){this.waitForDelay=null,this.iframe=null,this.onFrameLoad=new st,this.active=!1,this.dismissInterval=null,this.isJSONPayloadApproach=!1,this.osmDivRendering=null,this.osmDivSelector=null,this.isActive=()=>this.active,this.campaignMeta=e,this.data=t,this.active=!1;const n=Ee(e,"triggerData.trigger_delay.delayInSeconds",0)||0;this.waitForDelay=new Promise((e=>{this.delayTimer=setTimeout((()=>{e()}),1e3*n)}))}setIsActive(e){this.active=e}}const fi={CENTER:{position:"absolute",top:"50%",left:"50%",bottom:"auto",right:"auto",transform:"translate(-50%, -50%)"},CENTER_LEFT:{position:"absolute",top:"50%",left:"10px",bottom:"auto",right:"auto",transform:"translate(0,-50%)"},CENTER_RIGHT:{position:"absolute",top:"50%",right:"10px",bottom:"auto",left:"auto",transform:"translate(0,-50%)"},TOP_LEFT:{position:"absolute",top:"10px",left:"10px",bottom:"auto",right:"auto"},TOP_CENTER:{position:"absolute",top:"0",left:"50%",bottom:"auto",right:"auto",transform:"translate(-50%, 0)"},TOP_RIGHT:{position:"absolute",top:"10px",right:"10px",bottom:"auto",left:"auto"},BOTTOM_LEFT:{position:"absolute",bottom:"10px",left:"10px",top:"auto",right:"auto"},BOTTOM_CENTER:{position:"absolute",left:"50%",bottom:"10px",top:"auto",right:"auto",transform:"translate(-50%, 0)"},BOTTOM_RIGHT:{position:"absolute",bottom:"10px",right:"10px",top:"auto",left:"auto"},TOP:{position:"absolute",top:"0",left:"50%",bottom:"auto",right:"auto",transform:"translate(-50%, 0)"},BOTTOM:{position:"absolute",bottom:"0",top:"auto",right:"auto",left:"50%",transform:"translate(-50%, 0)"},LEFT:{position:"absolute",left:"0",bottom:"auto",right:"auto",top:"auto"},RIGHT:{position:"absolute",right:"0",bottom:"auto",left:"auto",top:"auto"}},vi=e=>{try{return!Si()&&window.Moengage.onsite.displayManager.campaignRenderMap[e].campaignMeta}catch(t){at.error(1,"OsmFunctions.getCampaignMeta","Campaign meta not found: "+e)}},Si=()=>!!window.Moengage.onsite.displayManager.testCampaign&&(at.log(1,"OsmFunctions.isTestCampaign","Test campaign element. No data will be sent to BE right now. We'll start tracking events once the campaign is live"),!0);var Ei=function(e,t,n,i){return new(n=n||Promise)((function(a,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function s(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?a(e.value):((t=e.value)instanceof n?t:new n((function(e){e(t)}))).then(o,s)}l((i=i.apply(e,t||[])).next())}))};function yi(e,t,n){return Ei(this,void 0,void 0,(function*(){const i=Pn(t),a=/moe-campaign-id/g;yield Ei(this,void 0,void 0,(function*(){try{let l=e.root;const{styles:c,scripts:d}=e,g=document.createElement("div");g.id=i,n.parentNode.insertBefore(g,n);const u=document.querySelector("#"+i),p=new DOMParser;l=l.replace(a,t);var r=p.parseFromString(l,"text/html");yield function(e){return Ei(this,void 0,void 0,(function*(){try{const t=e.getElementsByTagName("a");for(let e=t.length-1;0<=e;e--)""===t[e].getAttribute("href")&&t[e].removeAttribute("href")}catch(e){at.error(2,"InsertCustomHtmlJs.removeEmptyHrefTags","Error while removing Empty href attributes",e)}}))}(r),function(e){try{["trackEvent","trackClick","trackDismiss","dismissMessage","leadGenFormSubmit","fetchRatingValue"].forEach((n=>{!function(e,n){e.querySelectorAll("[onclick]").forEach((e=>{var i=e.getAttribute("onclick").replace(new RegExp(n+"\\((.*?)\\)","g"),((e,i)=>i?n+`('${t}',${i})`:n+`('${t}')`));e.setAttribute("onclick",i)}))}(e,n)}))}catch(e){at.error(2,"InsertCustomHtmlJs.addCampaignId","Error while adding Campaign Id",e)}}(r);const h=c.map((e=>p.parseFromString(e,"text/html").head.childNodes[0]));var o=d.map((e=>(e=e.replace(a,t),p.parseFromString(e,"text/html").head.childNodes[0]))),s=h.map((e=>new Promise(((t,n)=>{!function(e){const{node:t,onLoad:n,onError:a}=e;t instanceof HTMLMetaElement||"dns-prefetch"===t.getAttribute("rel")?n():(t.onload=()=>n(),t.onerror=()=>a()),document.querySelector("#"+i).appendChild(t)}({node:e,onLoad:t,onError:n})}))));yield Promise.all(s).catch((e=>{at.warn(1,"InsertCustomHtmlJs","Error loading Styles",(null==e?void 0:e.message)||"")}));const m=r.body.childNodes[0];u.appendChild(m),[...m.querySelectorAll(".brz-embed-code script")].map((e=>{!function(e){const t=document.createElement("script");t.innerHTML=e.innerHTML;for(let a=0;a<e.attributes.length;a++){var{name:n,value:i}=e.attributes[a];t.setAttribute(n,i)}e.replaceWith(t)}(e)})),function(e){return Ei(this,void 0,void 0,(function*(){for(const n of e)yield function(e){return new Promise(((n,a)=>{const r=document.createElement("script");for(let n=0;n<e.attributes.length;n++){var o=e.attributes[n].name;let i=e.attributes[n].value;"src"===o&&(i.includes("typeform")||i.includes("tv-button"))&&(i=i+"?campaignId="+t),r.setAttribute(o,i)}r.src?(r.onload=n,r.onerror=a):(r.innerHTML=e.innerHTML,n()),document.querySelector("#"+i).appendChild(r)}))}(n)}))}(o).then((()=>{window.Brz.emit("init.dom",window.jQuery(m)),at.log(1,"InsertCustomHtmlJs","Custom HTML/JS DOM Level OSM Insertion: "+i)})).catch((e=>{at.warn(1,"InsertCustomHtmlJs","Error loading script",(null==e?void 0:e.message)||"")}))}catch(e){at.error(2,"InsertCustomHtmlJs","Failed to Insert OSM into DOM: "+i)}}))}))}var bi=function(e,t,n,i){return new(n=n||Promise)((function(a,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function s(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?a(e.value):((t=e.value)instanceof n?t:new n((function(e){e(t)}))).then(o,s)}l((i=i.apply(e,t||[])).next())}))};class _i{constructor(){this.renderListener=null,this.initializationPromiseObject=null,this.campaignRenderOrder=[],this.campaignRenderMap={},this.dismissTestInapp=e=>{this.initialInlineBodyStyle?document.body.setAttribute("style",this.initialInlineBodyStyle):document.body.removeAttribute("style"),this.removeOSMPusher(),this.pushCardsTemplate(0),setTimeout((()=>{var t;return null===(t=document.getElementById("moe-onsite-campaign-"+e))||void 0===t?void 0:t.remove()}),0)},this.dismissInapp=e=>{if(0!==this.getActiveCampaigns().length){const t=this.getActiveCampaigns();setTimeout((()=>{t.forEach((t=>{t.campaignMeta.campaignId===e&&(t.iframe||t.osmDivSelector).remove()}))}),0),this.campaignRenderMap[e].setIsActive(!1),clearInterval(this.campaignRenderMap[e].dismissInterval),this.renderAllActiveCampaigns()}else this.dismissTestInapp(e)},this.clickTracker=vn,this.dismissEvent=En,this.startInitialization(),this.initialInlineBodyStyle=document.body.getAttribute("style")}startInitialization(){return bi(this,void 0,void 0,(function*(){var e=_i.baseLogTag+".startInitialization";try{null==this.initializationPromiseObject&&(this.initializationPromiseObject=new st),this.initializationPromiseObject.res()}catch(t){at.error(1,e,"Error initializing display managaer:",t)}}))}getOSMPusher(e){const t=document.createElement("div");if(t.id=Z.PUSH_BANNER,t.style.setProperty("display","block","important"),t.style.height=e+"px","FRAMESET"===document.body.nodeName){const e=document.head;e.parentNode.insertBefore(t,e)}else{const e=document.body.firstChild;e.parentNode.insertBefore(t,e)}return t}removeOSMPusher(){var e;null!==(e=document.getElementById(Z.PUSH_BANNER))&&void 0!==e&&e.remove()}queueDraftCampaign(e,t){return bi(this,void 0,void 0,(function*(){var n=_i.baseLogTag+".queueDraftCampaign";try{yield this.initializationPromiseObject.p,e.position=t.position,this.testCampaign=e;var i=!("1"!==t.editorVersion||!t.htmlJsonPayload);const a=!i&&_i.createDefaultIframe(this.testCampaign.draftId,t.payload);let r;at.warn(1,n,"Going to render test campaign "+e.draftId),r="FRAMESET"===document.body.nodeName?this.getOSMPusher(0):document.body.firstChild,i?(yield yi(t.htmlJsonPayload,this.testCampaign.draftId,r),this.renderTestCampaign(e,a,t)):(r.parentNode.insertBefore(a,r),a.onload=()=>{a.contentWindow.postMessage({campaignId:e.draftId},"*"),"1"===t.editorVersion?this.handleBridgeInsertion(a.contentDocument,e.draftId):this.handleClassBasedTrackingForTestCampaign(a,t,e),this.renderTestCampaign(e,a)})}catch(e){at.error(1,n,"Error queueing draft campaign",e)}}))}renderTestCampaign(e,t,n){return bi(this,void 0,void 0,(function*(){if(t){var i;t.style.visibility="hidden",t.style.display="block",t.style.zIndex="2147483647",e.displaySettings.config.blocking?(t.style.height=window.innerHeight+"px",t.style.width="100%"):(t.style.height=getComputedStyle(t.contentDocument.body).height,t.style.width=getComputedStyle(t.contentDocument.body).width,e.templateType===mn.POP_UP&&(t.style.margin="0px auto"),-1<t.srcdoc.indexOf(Z.POSITIONED_TEMPLATE)&&(i=-1<t.srcdoc.indexOf(Z.SIDE_BANNER),this.adjustPositionOfCampaign(t.style,e.position,i))),t.style.visibility="visible",this.testCampaignPositionStyling(e,t),e.displaySettings.config.scrollable||(document.body.style.overflow="hidden")}else{const t=document.getElementById(Pn(e.draftId));t.style.zIndex="2147483647",this.testCampaignPositionStyling(e,t)}e.templateType===mn.BANNER&&this.bannerTestCampaignStyling(e,t,n)}))}queueLiveCampaign(e,t){var n;return bi(this,void 0,void 0,(function*(){var i,a=_i.baseLogTag+".queueLiveCampaign";e.campaignContext=t.campaignContext,e.editorVersion=t.editorVersion;try{if(yield this.initializationPromiseObject.p,null!=this.campaignRenderMap[e.campaignId]&&this.campaignRenderMap[e.campaignId].isActive())at.warn(1,a,`Can not render ${e.campaignId}, as campaign is already Active.`);else if(this.campaignRenderOrder.push(e.campaignId),this.campaignRenderMap[e.campaignId]=new mi(e,t),this.campaignRenderMap[e.campaignId].isJSONPayloadApproach=!("1"!==t.editorVersion||!t.htmlJsonPayload),this.campaignRenderMap[e.campaignId].isJSONPayloadApproach?this.campaignRenderMap[e.campaignId].osmDivRendering=n=>bi(this,void 0,void 0,(function*(){yield yi(t.htmlJsonPayload,e.campaignId,n)})):(i=_i.createDefaultIframe(e.campaignId,this.campaignRenderMap[e.campaignId].data.payload),this.campaignRenderMap[e.campaignId].iframe=i),yield this.campaignRenderMap[e.campaignId].waitForDelay,yield this.canCampaignBeRendered(e)){if(at.warn(1,a,"Going to render "+e.campaignId),(null===(n=t.payload)||void 0===n?void 0:n.code)===Z.GCG_ERROR_CODE)return at.warn(1,a,`Can not render ${e.campaignId} as it falls under Control Group.`),void Sn(e,"OSM",!0)();this.campaignRenderMap[e.campaignId].setIsActive(!0),Sn(e,"OSM")(),null!=this.renderListener&&this.renderListener(e),this.renderAllActiveCampaigns()}else at.warn(1,a,"Can not render "+e.campaignId)}catch(i){at.error(1,a,"Error queuing campaign "+e.campaignId,i)}}))}renderAllActiveCampaigns(){return bi(this,void 0,void 0,(function*(){var e,t=_i.baseLogTag+".renderAllActiveCampaigns";const n=this.getActiveCampaigns();if(this.restoreBodyStyle(),0<n.length){for(let i=0;i<n.length;i++){if(null==document.getElementById(Pn(n[i].campaignMeta.campaignId))){let e;e="FRAMESET"===document.body.nodeName?this.getOSMPusher(0):document.body.firstChild,n[i].isJSONPayloadApproach?(yield n[i].osmDivRendering(e),n[i].onFrameLoad.res(),n[i].osmDivSelector=document.getElementById(Pn(n[i].campaignMeta.campaignId))):(e.parentNode.insertBefore(n[i].iframe,e),n[i].iframe.onload=()=>{Ti.setScrollState(n),n[i].iframe.contentWindow.postMessage({campaignId:n[i].campaignMeta.campaignId},"*"),"1"===n[i].campaignMeta.editorVersion?(this.handleBridgeInsertion(n[i].iframe.contentDocument,n[i].campaignMeta.campaignId,n[i].campaignMeta),this.changeAnchorTagReDirectionMethod(n[i].iframe)):this.handleClassBasedTracking(n[i]),n[i].onFrameLoad.res()})}yield n[i].onFrameLoad.p,n[i].isJSONPayloadApproach?(at.log(1,t,"zindex for "+n[i].campaignMeta.campaignId,2147483647..toString()),n[i].osmDivSelector.style.zIndex=(2147483647-(n.length-i-1)).toString(),this.liveCampaignPositionStyling(n[i].campaignMeta,n[i].osmDivSelector)):(n[i].iframe.style.visibility="hidden",n[i].iframe.style.display="block",at.log(1,t,"zindex for "+n[i].campaignMeta.campaignId,2147483647..toString()),n[i].iframe.style.zIndex=(2147483647-(n.length-i-1)).toString(),n[i].iframe.style.margin="0",n[i].campaignMeta.display.config.blocking?(n[i].iframe.style.height=window.innerHeight+"px",n[i].iframe.style.width="100%"):(n[i].iframe.style.height=getComputedStyle(n[i].iframe.contentDocument.body).height,n[i].iframe.style.padding.includes("10px")?n[i].iframe.style.width=parseInt(getComputedStyle(n[i].iframe.contentDocument.body).width)+20+"px":n[i].iframe.style.width=getComputedStyle(n[i].iframe.contentDocument.body).width,n[i].campaignMeta.templateType===mn.POP_UP&&(n[i].iframe.style.margin="0px auto"),n[i].data.payload&&-1<n[i].data.payload.indexOf(Z.POSITIONED_TEMPLATE)&&(e=-1<n[i].data.payload.indexOf(Z.SIDE_BANNER),this.adjustPositionOfCampaign(n[i].iframe.style,n[i].data.position,e))),n[i].iframe.style.visibility="visible",this.liveCampaignPositionStyling(n[i].campaignMeta,n[i].iframe)),null!=n[i].dismissInterval||0<(e=1e3*Ee(n[i].campaignMeta,"delivery.dismiss_interval",0))&&(n[i].dismissInterval=setTimeout((()=>{const e=this.campaignRenderMap[n[i].campaignMeta.campaignId];e&&e.isActive()&&(this.dismissInapp(n[i].campaignMeta.campaignId),window.MoeFocusHandler&&window.MoeFocusHandler(),En(n[i].campaignMeta,"OSM",!0))}),e))}this.bannerLiveCampaignsStyling(n)}}))}restoreBodyStyle(){this.removeOSMPusher(),this.pushCardsTemplate(0);let e=0;Object.keys(this.campaignRenderMap).forEach((t=>{this.campaignRenderMap[t].campaignMeta.templateType===mn.POP_UP&&this.campaignRenderMap[t].isActive()&&e++})),1<=e||(this.initialInlineBodyStyle?document.body.setAttribute("style",this.initialInlineBodyStyle):document.body.removeAttribute("style"))}canCampaignBeRendered(e){return bi(this,void 0,void 0,(function*(){var t=_i.baseLogTag+".queueLiveCampaign";try{var n=yield dn.campaingsStatsStore.getItem(e.campaignId),i=yield dn.serviceMetaStore.getItem(Z.STORES.SERVICE_META.KEYS.GLOBAL_DELAY),a=yield dn.serviceMetaStore.getItem(Z.STORES.SERVICE_META.KEYS.LAST_INAPP_SHOWN_TIME);return _n.isValid(e,n)&&_n.isValidMessagingCampaign(e,n,i,a,this.getActiveCampaigns())&&Kn.getURLFilterResult(e)}catch(n){at.error(1,t,`Error checking if campaign ${e.campaignId} can be rendered:`,n)}return!1}))}static createDefaultIframe(e,t){_i.baseLogTag,e=Pn(e);const n=document.createElement("iframe");return n.setAttribute("id",e),n.style.left="0px",n.style.top="0px",n.style.bottom="0px",n.style.right="0px",n.style.border="0px none",n.style.height="100%",n.style.width=window.innerWidth.toString()+"px",n.style.padding="0",n.style.overflow="hidden",n.style.overflowY="hidden",n.style.zIndex="999999",n.style.display="none",n.style.position="fixed",n.setAttribute("srcdoc",t),n}onRender(e){this.renderListener=e}getActiveCampaigns(){return this.campaignRenderOrder.map((e=>this.campaignRenderMap[e])).filter((e=>e.isActive()))}destroy(){this.getActiveCampaigns().forEach((e=>{e.setIsActive(!1)})),this.renderAllActiveCampaigns(),this.campaignRenderOrder=[],this.campaignRenderMap={}}adjustPositionOfCampaign(e,t,n){t&&(Object.assign(e,fi[t]),Ke()&&n&&this.addMarginInMweb(e,t))}addMarginInMweb(e,t){const n={paddingLeft:"10px",paddingRight:"10px",marginTop:"0",marginBottom:"0"};"TOP"===t&&(n.marginTop="10px"),"BOTTOM"===t&&(n.marginBottom="10px"),Object.assign(e,n)}handleBridgeInsertion(e,t,n){var i=_i.baseLogTag+".handleBridgeInsertion";try{e.head.append(((e,t)=>{const n=document.createElement("script");return n.type="text/javascript",n.text=(t=t,`\n const moeSDK = window.parent.Moengage;\n let moeOsmCampaignMeta = ${JSON.stringify(e)};\n const moengage = {\n trackEvent: function (eventName, eventAttr, isNonInteractive) {\n if(moeOsmCampaignMeta) {\n return moeSDK.track_event(eventName, eventAttr);\n }\n return Promise.resolve();\n },\n trackClick: function (id) {\n if(moeOsmCampaignMeta) {\n return moeSDK.onsite.displayManager.clickTracker(OsmCampaignMeta, 'OSM', {\n widget_id: id,\n })();\n }\n return Promise.resolve();\n },\n trackDismiss: function (isAuto = false) {\n if(moeOsmCampaignMeta) {\n return moeSDK.onsite.displayManager.dismissEvent(OsmCampaignMeta, 'OSM', isAuto);\n }\n return Promise.resolve();\n },\n setAlias: function (data) {\n return moeSDK.update_unique_user_id(data);\n },\n setUniqueId: function (data) {\n return moeSDK.add_unique_user_id(data);\n },\n destroySession: function () {\n return moeSDK.destroy_session();\n },\n setUserName: function (data) {\n return moeSDK.add_user_name(data);\n },\n setFirstName: function (data) {\n return moeSDK.add_first_name(data);\n },\n setLastName: function (data) {\n return moeSDK.add_last_name(data);\n },\n setEmailId: function (data) {\n return moeSDK.add_email(data);\n },\n setMobileNumber: function (data) {\n return moeSDK.add_mobile(data);\n },\n setGender: function (data) {\n return moeSDK.add_gender(data);\n },\n setBirthDate: function (data) {\n //iso date format only\n return moeSDK.add_birthday(data);\n },\n setUserAttribute: function (name, value) {\n return moeSDK.add_user_attribute(name, value);\n },\n dismissMessage: function () {\n setTimeout(() => {\n moeSDK.onsite.displayManager.dismissInapp('${t}');\n }, 100)\n },\n showPushOptIn: function (config) {\n return moeSDK.call_web_push(config);\n },\n copyText: function (selector) {\n return new Promise((res, rej) => {\n if(!selector) rej();\n var text = document.querySelector(selector);\n if(text.textContent) {\n navigator.clipboard.writeText(text.textContent);\n res(null);\n }\n else {\n text.select();\n text.setSelectionRange(0, 99999);\n navigator.clipboard.writeText(text.value);\n res(null);\n }\n })\n }\n }\n const MoeOsm = moengage;\n `),n.setAttribute("data-moe-script","1"),n})(n,t)),at.log(2,i,"JS-bridge script inserted successfully",t)}catch(e){at.warn(2,i,"Failed to insert OSM JS Bridge: ",t)}}handleClassBasedTrackingForTestCampaign(e,t,n){const i=_i.baseLogTag+".handleClassBasedTrackingForTestCampaign";var a=e=>Array.prototype.slice.call(e),r=a(e.contentDocument.getElementsByClassName(Z.CSS_SELECTORS.DISMISS_INAPP)),o=a(e.contentDocument.getElementsByClassName(Z.CSS_SELECTORS.CLICK_INAPP));if(a=a(e.contentDocument.getElementsByTagName("a")),0===r.length&&at.warn(1,i,"No dismiss class items present in this template"),0===o.length&&at.warn(1,i,"No click class items present in this template"),-1<t.payload.indexOf("TEXT_INPUT")||-1<t.payload.indexOf('dynamic-listeners="true"'))e.contentDocument.body.addEventListener("click",(e=>{e.target&&e.target.classList.contains(Z.CSS_SELECTORS.CLICK_INAPP)&&at.log(1,i,"Clicked on test campaign element. No data will be sent to BE right now. We'll start sending the click events once the campaign is live"),e.target&&e.target.classList.contains(Z.CSS_SELECTORS.DISMISS_INAPP)&&this.dismissTestInapp(n.draftId)}));else{for(const e of o)e.addEventListener("click",(e=>{at.log(1,i,"Clicked on test campaign element. No data will be sent to BE right now. We'll start sending the click events once the campaign is live")}));for(const e of r)e.addEventListener("click",(()=>{this.dismissTestInapp(n.draftId)}))}for(const e of a)"_blank"!==e.getAttribute("target")&&e.setAttribute("target","_parent")}handleClassBasedTracking(e){var t=_i.baseLogTag+".handleClassBasedTracking",n=e=>Array.prototype.slice.call(e);const i=e.iframe;var a=n(i.contentDocument.getElementsByClassName(Z.CSS_SELECTORS.DISMISS_INAPP)),r=n(i.contentDocument.getElementsByClassName(Z.CSS_SELECTORS.CLICK_INAPP));if(n=n(i.contentDocument.getElementsByTagName("a")),0===a.length&&at.warn(1,t,"No dismiss class items present in this template"),0===r.length&&at.warn(1,t,"No click class items present in this template"),e.data.payload&&(-1<e.data.payload.indexOf("TEXT_INPUT")||-1<e.data.payload.indexOf('dynamic-listeners="true"')))i.contentDocument.body.addEventListener("click",(t=>{var n;t.target&&t.target.classList.contains(Z.CSS_SELECTORS.CLICK_INAPP)&&(n=t.target.dataset.id,vn(e.campaignMeta,"OSM",{widget_id:n})()),t.target&&t.target.classList.contains(Z.CSS_SELECTORS.DISMISS_INAPP)&&(this.dismissInapp(e.campaignMeta.campaignId),t.target.classList.contains(Z.CSS_SELECTORS.CLICK_INAPP)||En(e.campaignMeta,"OSM"))}));else{for(const t of r)t.addEventListener("click",(t=>{t=t.target.dataset.id,vn(e.campaignMeta,"OSM",{widget_id:t})()}));for(const t of a)t.addEventListener("click",(()=>{this.dismissInapp(e.campaignMeta.campaignId),t.classList.contains(Z.CSS_SELECTORS.CLICK_INAPP)||En(e.campaignMeta,"OSM")}))}for(const e of n)"_blank"!==e.getAttribute("target")&&e.setAttribute("target","_parent")}changeAnchorTagReDirectionMethod(e){var t,n=_i.baseLogTag+".changeAnchorTagReDirectionMethod";try{for(const n of(t=e.contentDocument.getElementsByTagName("a"),Array.prototype.slice.call(t))){var i=n.getAttribute("target"),a=n.getAttribute("href");a&&"_parent"===i&&(n.setAttribute("onclick",`setTimeout(()=>{window.open('${a}','_parent')})`),n.removeAttribute("href"))}at.log(1,n,"Anchor Tag Href Rendering Changed to onClick for Campaign Frame: "+e.id)}catch(t){at.error(1,n,"Failed to Change Anchor Tag Href Rendering for Campaign Frame: "+e.id)}}liveCampaignPositionStyling(e,t){var n=_i.baseLogTag+".liveCampaignPositionStyling";try{e.templateType===mn.BANNER?e.display.config.sticky?t.style.position="fixed":t.style.position="absolute":e.templateType===mn.POP_UP&&(t.style.position="fixed","DIV"===t.tagName?t.style.inset="0":t.style.backgroundColor="rgba(99, 99, 99, 0.21)"),at.log(1,n,"Added Position Styles for CampaignId: "+e.campaignId)}catch(t){at.error(1,n,"Failed adding Styles for CampaignId: "+e.campaignId)}}testCampaignPositionStyling(e,t){var n=_i.baseLogTag+".testCampaignPositionStyling";try{e.templateType===mn.BANNER?e.displaySettings.config.sticky?t.style.position="fixed":t.style.position="absolute":e.templateType===mn.POP_UP&&(t.style.position="fixed","DIV"===t.tagName?t.style.inset="0":t.style.backgroundColor="rgba(99, 99, 99, 0.21)"),at.log(1,n,"Added Position Styles for CampaignId: "+e.draftId)}catch(t){at.error(1,n,"Failed adding Styles for CampaignId: "+e.draftId)}}bannerTestCampaignStyling(e,t,n){var i,a=_i.baseLogTag+".bannerTestCampaignStyling";try{let n,r,o=!0;t?(n=parseInt(getComputedStyle(t.contentDocument.body).height),o=-1<t.srcdoc.indexOf(Z.POSITIONED_TEMPLATE)):(i=document.querySelector("#"+Pn(e.draftId)+" .brz-container"),n=parseInt(getComputedStyle(i).height)),r=e.displaySettings.config.pushPage&&(o&&"TOP"===e.position||!o)?this.getOSMPusher(n):this.getOSMPusher(0),this.pushCardsTemplate(n,r),at.log(1,a,"Added Banner Styles for Test CampaignId: "+e.draftId)}catch(n){at.error(1,a,"Failed Added Banner Styles for Test CampaignId: "+e.draftId)}}bannerLiveCampaignsStyling(e){var t=_i.baseLogTag+".bannerLiveCampaignsStyling";let n=0,i=0;for(let r=e.filter((e=>e.campaignMeta.templateType===mn.BANNER)).length-1;0<=r;r--)try{if(e[r].isJSONPayloadApproach||e[r].iframe.contentDocument){let a,o=!0;e[r].isJSONPayloadApproach?a=parseInt(getComputedStyle(e[r].osmDivSelector.querySelector(".brz-container")).height):(a=parseInt(getComputedStyle(e[r].iframe.contentDocument.body).height),o=e[r].data.payload&&-1<e[r].data.payload.indexOf(Z.POSITIONED_TEMPLATE)),n+=a,e[r].campaignMeta.display.config.pushPage&&(o&&"TOP"===e[r].data.position||!o)&&(i+=a),at.log(1,t,"Added Banner Styles for Live CampaignId: "+e[r].campaignMeta.campaignId)}}catch(a){at.error(1,t,"Failed Adding Banner Styles for Live CampaignId: "+e[r].campaignMeta.campaignId)}var a=this.getOSMPusher(i);this.pushCardsTemplate(i,a)}pushCardsTemplate(e,t){var n;null!==(n=null===(n=null===(n=window)||void 0===n?void 0:n.Moengage)||void 0===n?void 0:n.cards)&&void 0!==n&&n.updatePushBannerHeight(e,t)}}_i.baseLogTag="MessagingDisplayManager";class Ti{static setScrollState(e){let t=!0;for(let n=0;n<e.length;n++)t=t&&e[n].campaignMeta.display.config.scrollable;t||(document.body.style.overflow="hidden")}}var Ii=function(e,t,n,i){return new(n=n||Promise)((function(a,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function s(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?a(e.value):((t=e.value)instanceof n?t:new n((function(e){e(t)}))).then(o,s)}l((i=i.apply(e,t||[])).next())}))};class Ai{constructor(e,t,n){this.baseLogTag="DeliveryFunnelManager",this.displayManager=t,this.OnsiteApiClient=new ri(e),this.deliveryStats=n}attemptCampaigns(e){e.forEach((e=>{this.deliveryStats.setStats(e,Z.DELIVERY_FUNNEL.ATTEMPTED.CAMPAIGN_ATTEMPTED)}))}getImpressionStats(e){return Ii(this,void 0,void 0,(function*(){var t=this.baseLogTag+".getImpressionStats";try{return yield dn.campaingsStatsStore.getItem(e.campaignId)}catch(n){at.error(1,t,"Error getting impression stats for "+e.campaignId,n)}}))}getLastGlobalInappShown(){return Ii(this,void 0,void 0,(function*(){return yield dn.serviceMetaStore.getItem(Z.STORES.SERVICE_META.KEYS.LAST_INAPP_SHOWN_TIME)}))}getGlobalDelay(){return Ii(this,void 0,void 0,(function*(){return yield dn.serviceMetaStore.getItem(Z.STORES.SERVICE_META.KEYS.GLOBAL_DELAY)}))}filterValidCampaigns(e){return Ii(this,void 0,void 0,(function*(){var t=this.baseLogTag+".filterValidCampaigns",n=e.map((e=>this.getImpressionStats(e)));const i=yield this.getLastGlobalInappShown(),a=yield this.getGlobalDelay();try{const t=yield Promise.all(n);return e.filter(((e,n)=>{if(e.templateType!==mn.SELF_HANDLED){if(!_n.isCampaignWithinFC(e,t[n]))return this.deliveryStats.setStats(e,Z.DELIVERY_FUNNEL.PRIORITIZED.CAMPAIGN_PRIORITY_MAX_TIMES_SHOWN),!1;if(!_n.hasCampaignClearedSelfDelay(e,t[n]))return this.deliveryStats.setStats(e,Z.DELIVERY_FUNNEL.PRIORITIZED.CAMPAIGN_PRIORITY_MIN_DELAY),!1;if(!_n.hasCampaignClearedGlobalDelay(e,a,i))return this.deliveryStats.setStats(e,Z.DELIVERY_FUNNEL.PRIORITIZED.CAMPAIGN_PRIORITY_GLOBAL_DELAY),!1}return!_n.isCampaignExpired(e)||(this.deliveryStats.setStats(e,Z.DELIVERY_FUNNEL.PRIORITIZED.CAMPAIGN_PRIORITY_EXPIRED),!1)}))}catch(n){at.error(1,t,"Error filtering and sorting campaigns",n)}}))}prioritizeMessagingCampaigns(e){return Ii(this,void 0,void 0,(function*(){const t=yield this.filterValidCampaigns(e);if(0<t.length){const[e,...n]=t.sort(_n.comparator);return n&&0<n.length&&n.map((t=>{t.campaignId!==e.campaignId&&this.deliveryStats.setStats(t,Z.DELIVERY_FUNNEL.PRIORITIZED.CAMPAIGN_PRIORITY_HIGH_PRIORITY_CAMPAIGN_AVAILABLE)})),e}}))}getCampaignTagMap(e){const t={},n=[],i=[];return e.forEach((e=>{null!=e.tag&&(i.indexOf(e.tag)<0&&i.push(e.tag),null==t[e.tag]&&(t[e.tag]=[]),t[e.tag].push(e))})),i.forEach((e=>{if(null!=t[e]){var i=t[e].sort(_n.comparator);for(let e=0;e<i.length;e++)0===e?n.push(i[e]):this.deliveryStats.setStats(i[e],Z.DELIVERY_FUNNEL.PRIORITIZED.CAMPAIGN_PRIORITY_HIGH_PRIORITY_CAMPAIGN_AVAILABLE)}})),n}prioritizePersonalizationCampaigns(e){return Ii(this,void 0,void 0,(function*(){var t=yield this.filterValidCampaigns(e);return 0<t.length?this.getCampaignTagMap(t):[]}))}getOnsitePayload(e,t){return Ii(this,void 0,void 0,(function*(){var n=this.baseLogTag+".getOnsitePayload";try{var i=yield this.OnsiteApiClient.getCampaignPayload(e,t);if(i&&!i.error)return i;if(i&&i.error){const t=i.reason;return t&&t.includes("PAUSED")?void this.deliveryStats.setStats(e,Z.DELIVERY_FUNNEL.DELIVERED.CAMPAIGN_DELIVERED_PAUSED):t&&t.includes("EXPIRED")?void this.deliveryStats.setStats(e,Z.DELIVERY_FUNNEL.DELIVERED.CAMPAIGN_DELIVERED_EXPIRED):t&&t.includes("personalize")?void this.deliveryStats.setStats(e,Z.DELIVERY_FUNNEL.DELIVERED.CAMPAIGN_DELIVERED_PERSONALIZATION_FAILURE):void this.deliveryStats.setStats(e,Z.DELIVERY_FUNNEL.DELIVERED.CAMPAIGN_DELIVERED_API_FAILURE)}return void this.deliveryStats.setStats(e,Z.DELIVERY_FUNNEL.DELIVERED.CAMPAIGN_DELIVERED_API_FAILURE)}catch(i){return at.error(1,n,"Error getting onsite payload",i),void this.deliveryStats.setStats(e,Z.DELIVERY_FUNNEL.DELIVERED.CAMPAIGN_DELIVERED_API_FAILURE)}}))}getEventForPersonalisation(e){return Ii(this,void 0,void 0,(function*(){var t=yield li.getTriggeringPrimaryEvent(e.campaignId);return t?new Ht(t.name,t.attributes):null}))}deliverMessagingCampaign(e,t){return Ii(this,void 0,void 0,(function*(){var n=this.baseLogTag+".deliverMessagingCampaign";if(e){var i=(yield this.getEventForPersonalisation(e))||t;try{var a=yield this.getOnsitePayload(e,i);if(a)return e.onsitePayload=a,_n.doCampaignPayloadHasMandatoryParams(e.onsitePayload)?e:(at.warn(1,n,"Can not render "+e.campaignId),void this.deliveryStats.setStats(e,Z.DELIVERY_FUNNEL.DELIVERED.CAMPAIGN_DELIVERED_MANDATORY_PARAMS_MISSING))}catch(i){at.error(1,n,"Error delivering messaging campaign",i)}}}))}deliverPersonalizationCampaigns(e,t,n){return Ii(this,void 0,void 0,(function*(){var i=this.baseLogTag+".deliverPersonalizationCampaigns";if(0<e.length){var a=e.map((e=>this.getOnsitePayload(e,n)));try{const n=yield Promise.all(a);return e.filter(((e,i)=>{if(n[i]&&n[i].payload&&(e.onsitePayload=n[i],null!=e.tag&&null!=t[e.tag])){if("JSON"!==e.onsitePayload.payloadType)return!0;if((e=>{try{JSON.parse(e)}catch(e){return!1}return!0})(e.onsitePayload.payload))return!0}return!1}))}catch(a){at.error(1,i,"Error delivering personalization campaigns",a)}}}))}messagingCampaignImpression(e,t){return Ii(this,void 0,void 0,(function*(){var n=this.baseLogTag+".messagingCampaignImpression";if(e)try{var i=yield this.getLastGlobalInappShown(),a=yield this.getGlobalDelay(),r=this.displayManager.getActiveCampaigns();return _n.hasCampaignClearedGlobalDelay(e,a,i)?_n.canCampaignBeRenderedOverExisting(e,r.length)?Kn.getURLFilterResult(e)?null==this.displayManager.campaignRenderMap[e.campaignId]||"MOE_EXIT"!==t&&t!==_?e:(at.warn(1,n,`Can not render ${e.campaignId} `+(this.displayManager.campaignRenderMap[e.campaignId].isActive()?", as campaign is already Active.":"")),void this.deliveryStats.setStats(e,Z.DELIVERY_FUNNEL.IMPRESSION.CAMPAIGN_IMPRESSION_MAX_TIMES_SHOWN)):(at.warn(1,n,"Can not render "+e.campaignId),void this.deliveryStats.setStats(e,Z.DELIVERY_FUNNEL.IMPRESSION.CAMPAIGN_IMPRESSION_CONTEXT_CHANGED)):void this.deliveryStats.setStats(e,Z.DELIVERY_FUNNEL.IMPRESSION.CAMPAIGN_IMPRESSION_ANOTHER_CAMPAIGN_VISIBLE):(at.warn(1,n,"Can not render "+e.campaignId),void this.deliveryStats.setStats(e,Z.DELIVERY_FUNNEL.IMPRESSION.CAMPAIGN_IMPRESSION_GLOBAL_DELAY))}catch(i){return void at.error(1,n,"Error delivering messaging campaign",i)}}))}mostEligibleMessagingCampaign(e,t){return Ii(this,void 0,void 0,(function*(){if(0<e.length){this.attemptCampaigns(e);var n=yield this.prioritizeMessagingCampaigns(e);let i;return i=An(n,b)?yield wn(n):yield this.deliverMessagingCampaign(n,t),n=yield this.messagingCampaignImpression(i,null==t?void 0:t.name),this.deliveryStats.sendDeliveryStats(e),n}}))}mostEligiblePersonalizationCampaigns(e,t,n){return Ii(this,void 0,void 0,(function*(){if(0<e.length){this.attemptCampaigns(e);var i=yield this.prioritizePersonalizationCampaigns(e);return i=yield this.deliverPersonalizationCampaigns(i,t,n),this.deliveryStats.sendDeliveryStats(e),i||[]}return[]}))}mostEligibleSelfHandledPersonalizationCampaigns(e,t){return Ii(this,void 0,void 0,(function*(){var n=this.baseLogTag+".mostEligibleSelfHandledPersonalizationCampaigns";this.attemptCampaigns(e);const i=yield this.filterValidCampaigns(e);at.log(1,n,"Eligible campaigns with tag ",t,"are",i);const a=i.sort(_n.comparator)[0];return a&&(at.log(1,n,"Campaign with highest priority for tag",t,"is",a.campaignId),(n=yield this.getOnsitePayload(a))&&n.payload&&(a.onsitePayload=n)),this.deliveryStats.sendDeliveryStats(e),a}))}}class wi{handler(e,t,n,i,a,r){var o;return function(e,t,n,i){return new(n=n||Promise)((function(t,a){function r(e){try{s(i.next(e))}catch(e){a(e)}}function o(e){try{s(i.throw(e))}catch(e){a(e)}}function s(e){var i;e.done?t(e.value):((i=e.value)instanceof n?i:new n((function(e){e(i)}))).then(r,o)}s((i=i.apply(e,[])).next())}))}(this,0,void 0,(function*(){var s=wi.baseLogTag+".handler";at.log(1,s,(null==r?void 0:r.name)&&`Triggered for ${r.name}: `||"Campaign(s) triggered: ",a);var l=a.filter((e=>e.templateType===mn.SELF_HANDLED)),c=a.filter((e=>e.templateType!==mn.SELF_HANDLED));0<l.length&&0<(l=yield e.mostEligiblePersonalizationCampaigns(l,t,r)).length&&n(l),0<c.length&&(c=yield e.mostEligibleMessagingCampaign(c,r),null!=r&&r.timestamp&&r.timestamp<(null===(o=window.Moengage)||void 0===o?void 0:o.pageChangeHandlerCallingTime)?at.log(1,s,"Stopped triggering the campaign because handle_page_change was called: ",a):c&&i(c))}))}}wi.baseLogTag="EventTriggerHandler";class Di{constructor(e){this.baseLogTag="DeliveryStats",this.OnsiteApiClient=new ri(e),this.batchId=(0,ct.v4)()}sendDeliveryStats(e){return function(e,t,n,i){return new(n=n||Promise)((function(t,a){function r(e){try{s(i.next(e))}catch(e){a(e)}}function o(e){try{s(i.throw(e))}catch(e){a(e)}}function s(e){var i;e.done?t(e.value):((i=e.value)instanceof n?i:new n((function(e){e(i)}))).then(r,o)}s((i=i.apply(e,[])).next())}))}(this,0,void 0,(function*(){var t=this.baseLogTag+".sendDeliveryStats";if(0<e.length)try{const t={};e.forEach((e=>{t[e.campaignContext.cid]||(t[e.campaignContext.cid]=e.stats,e.stats={})}));var n={stats:t};this.OnsiteApiClient.sendDeliveryFunnelStats(n,this.batchId)}catch(n){at.error(1,t,"Error in sending delivery funnel stats",n)}}))}setStats(e,t){var n=(new Date).toISOString();e.stats[t]=e.stats[t]||[],e.stats[t].includes(n)||e.stats[t].push(n)}}var Ci=function(e,t,n,i){return new(n=n||Promise)((function(a,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function s(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?a(e.value):((t=e.value)instanceof n?t:new n((function(e){e(t)}))).then(o,s)}l((i=i.apply(e,t||[])).next())}))};const Oi=new st;class Pi{constructor(e){this.initializationPomise=null,this.testDraftInfo=null,this.triggerManager=null,this.displayManager=null,this.onsiteSelfHandledTriggerListeners={},this.funnelManager=null,this.eventTriggerHandler=null,this.deliveryStats=null,this.initData=e,at.setLogLevel(e.debugLevel),this.OnsiteApiClient=new ri(this.initData),this.iframeHelper=new ni}setLogLevel(e){at.setLogLevel(e,!1)}isTestCampaignAvailable(){return Ci(this,void 0,void 0,(function*(){const e=Pi.baseLogTag+".isTestCampaignAvailable";if(window.opener){let t;window.addEventListener("message",(n=>Ci(this,void 0,void 0,(function*(){var i,a;n.data&&"inapp_test"===n.data.action&&(i=n.data,(yield ti.isValidRawJson(i))?(t=!0,a=new ti(i),at.log(1,e,"Valid test campaign data found checking TestCampaign",i),yield this.checkForTestCampaign(a)):at.error(1,e,"Data is not a valid test campaign",i),Oi.res())}))),!1),window.opener.postMessage("moe_test_osm","*"),window.opener=null,setTimeout((()=>Ci(this,void 0,void 0,(function*(){t||(yield this.checkForTestCampaign()),Oi.res()}))),100)}else Oi.res()}))}initialize(){const e=Pi.baseLogTag+".initialize";return at.log(1,e,"Initialising onsite module"),null==this.initializationPomise&&(this.initializationPomise=new Promise((t=>Ci(this,void 0,void 0,(function*(){try{yield dn.initialize(),yield this.isTestCampaignAvailable(),Oi.p.then((()=>Ci(this,void 0,void 0,(function*(){yield this.syncCampaigns();const n=yield Cn();var i=this.isExitIntentCampaignFound(n);if(i.length&&(yield this.prefetchExitIntentCampaigns(i)),i=n.filter((e=>null!=e.triggerData)),this.displayManager=new _i,this.displayManager.onRender((t=>{at.log(1,e,"Campaign rendered: "+t.campaignId),dn.serviceMetaStore.setItem(Z.STORES.SERVICE_META.KEYS.LAST_INAPP_SHOWN_TIME,new Date)})),null!=this.testDraftInfo&&this.testDraftInfo.draftType===Z.DRAFT_CAMPAIGN_TPYES.ONSITE_MESSAGING){at.log(1,e,"Test campaigns present, will be showing only the test campaign."),at.log(1,e,"No live campaign will be shown till draft campaign showing");try{at.log(1,e,"Trying to render draft campaign with id "+this.testDraftInfo.draftId);var a=yield this.OnsiteApiClient.getDraftCampaign(this.testDraftInfo);at.log(1,e,"Test campaign payload: ",a),a&&this.displayManager.queueDraftCampaign(this.testDraftInfo,a)}catch(n){at.error(1,e,`Error fetching data for test campaign ${this.testDraftInfo.draftId}: `,n)}}else this.deliveryStats=new Di(this.initData),this.triggerManager=new hi(i),this.funnelManager=new Ai(this.initData,this.displayManager,this.deliveryStats),this.eventTriggerHandler=new wi,i=this.eventTriggerHandler.handler.bind(null,this.funnelManager,this.onsiteSelfHandledTriggerListeners,this.handlePersonalizationCampagins.bind(this),this.handleMessagingCampaigns.bind(this)),this.triggerManager.onTrigger(i),di.setListener(i),ui.setDeliveryStats(this.deliveryStats),di.setDeliveryStats(this.deliveryStats),yield di.logDeliveryFunnelForExpiredTimerCampaigns(),yield ui.updateCampaignTimeInSecondaryEventsStore(),yield di.createNewTimers(),this.triggerManager.startWatching();t(!0)}))))}catch(t){at.error(1,e,t)}}))))),this.initializationPomise}handleMessagingCampaigns(e){return Ci(this,void 0,void 0,(function*(){var t=Pi.baseLogTag+".handleMessagingCampaigns";e.onsitePayload&&(at.log(1,t,"Campaign triggered: "+e.campaignId),at.log(1,t,"Payload for campaign:",e.onsitePayload),this.displayManager.queueLiveCampaign(e,e.onsitePayload))}))}handlePersonalizationCampagins(e){return Ci(this,void 0,void 0,(function*(){const t=Pi.baseLogTag+".handlePersonalizationCampagins";0<e.length&&e.forEach((e=>{null!=e.tag&&(at.log(1,t,"Personlization Campaign triggered: "+e.campaignId),this.onsiteSelfHandledTriggerListeners[e.tag].forEach((t=>{this.handleSelfHandledCallback(e,e.onsitePayload,t)})))}))}))}logout(){var e;return Ci(this,void 0,void 0,(function*(){var t=Pi.baseLogTag+".logout";if(at.log(1,t,"Starting module logout"),this.initializationPomise=null,this.displayManager){const t=Object.keys(this.displayManager.campaignRenderMap);null!==(e=this.displayManager.testCampaign)&&void 0!==e&&e.draftId&&t.push(null===(e=this.displayManager.testCampaign)||void 0===e?void 0:e.draftId),t.forEach((e=>{const t=document.getElementById("moe-onsite-campaign-"+e);t&&t.remove()})),this.displayManager.destroy()}this.triggerManager&&this.triggerManager.destory(),ui.destroy(),di.destroy(),this.displayManager=null,this.funnelManager=null,this.eventTriggerHandler=null,yield di.deleteAllPendingTimers(),yield dn.clear(),at.log(1,t,"Starting module logout complete")}))}checkForTestCampaign(e){return Ci(this,void 0,void 0,(function*(){var t=Pi.baseLogTag+".checkForTestCampaign";try{var n=e||(yield this.iframeHelper.getDraftCampaignInfo());null==n?(at.log(1,t,"No draft campaign found"),this.testDraftInfo=null):(at.log(1,t,"Found draft campaign: ",n),this.testDraftInfo=n,null==this.testDraftInfo.draftId&&(this.testDraftInfo.draftType=Z.DRAFT_CAMPAIGN_TPYES.WEB_PERSONALIZATON))}catch(n){at.error(1,t,"Error getting test campaign",n)}}))}getData(e,t){return Ci(this,void 0,void 0,(function*(){const n=Pi.baseLogTag+".getData";null==t&&(at.warn(1,n,"Moengage.onsite.getData called without a providing a callback."),t=()=>{});try{if(yield this.initializationPomise,null!=this.testDraftInfo){var i;at.log(1,n,"Fetching test campaign: ",this.testDraftInfo),this.testDraftInfo.draftType===Z.DRAFT_CAMPAIGN_TPYES.WEB_PERSONALIZATON&&(i=yield this.OnsiteApiClient.getDraftCampaign(this.testDraftInfo),t(null,{payload:i.payload,click:()=>{at.log(1,n,"This is a test campaign")},imp:()=>{at.log(1,n,"This is a test campaign")}}))}else{const i=yield dn.campaingsTagsStore.getItem(e);if(i){const o=yield Promise.all(i.map((e=>Dn(e))));var a=o.filter((e=>null==e.triggerData)),r=yield this.funnelManager.mostEligibleSelfHandledPersonalizationCampaigns(a,e);r&&r.onsitePayload?this.handleSelfHandledCallback(r,r.onsitePayload,t):(at.error(1,n,"Error fetching campaign payload"),t({message:"There was an error fetching data for this tag"},null))}else at.warn(1,n,"Could not find any eligible campaign for tag",e),t({message:"Could not find any eligible campaign for tag "+e},null)}}catch(i){at.error(1,n,"Error getting campaign",i)}}))}registerCallback(e,t){return Ci(this,void 0,void 0,(function*(){var n=Pi.baseLogTag+".registerCallback";try{yield this.initializationPomise,null==this.onsiteSelfHandledTriggerListeners[e]?this.onsiteSelfHandledTriggerListeners[e]=[t]:this.onsiteSelfHandledTriggerListeners[e].push(t)}catch(t){at.error(1,n,"Error setting callback for tag",e),at.error(1,n,"Error stack:",t)}}))}handleSelfHandledCallback(e,t,n){return Ci(this,void 0,void 0,(function*(){var i=Pi.baseLogTag+".handleSelfHandledCallback";if(e.campaignContext=t.campaignContext,"JSON"===t.payloadType)try{t.payload=JSON.parse(t.payload);var a=Ee(e,"triggerData.trigger_delay.delayInSeconds",0)||0;setTimeout((()=>{yn(e,"WP"),n(null,{payload:t.payload,click:t=>{vn(e,"WP",t)()},imp:Sn(e,"WP")})}),1e3*a)}catch(r){a=`Payload for campaign_id ${e.campaignId} is not a valid JSON`,at.error(1,i,a),at.error(1,i,"Payload provided:",t.payload),n({message:a},null)}else yn(e,"WP"),n(null,{payload:t.payload,click:t=>{vn(e,"WP",t)()},imp:Sn(e,"WP")})}))}syncCampaigns(){return Ci(this,void 0,void 0,(function*(){var e=Pi.baseLogTag+".syncCampaigns";try{(yield this.shouldClearMetaStorage())&&(yield dn.campaingsMetaStore.clear(),yield this.rebuildTagStore()),(yield this.shouldSaveRemoteCampaigns())&&(yield this.saveRemoteCampaigns())}catch(t){at.error(1,e,"Error getting remote campaigns: ",t)}}))}shouldClearMetaStorage(){return Ci(this,void 0,void 0,(function*(){return(yield dn.serviceMetaStore.getItem(Z.STORES.SERVICE_META.KEYS.LAST_FETCH_SDK_VERSION))!==ze().getSdkVersion()}))}shouldSaveRemoteCampaigns(){var e;return Ci(this,void 0,void 0,(function*(){var t=Pi.baseLogTag+".shouldSaveRemoteCampaigns",n=yield dn.serviceMetaStore.getItem(Z.STORES.SERVICE_META.KEYS.LAST_FETCH_SDK_VERSION),i=yield dn.serviceMetaStore.getItem(Z.STORES.SERVICE_META.KEYS.LAST_META_CALL_TIME),a=(i=new Date(i),(new Date).getTime());return null==i||a-i>Z.META_REFRESH_TIME||(at.remoteLogTracking(1,"info",t,"Last fetch was less than 15 mins ago at ",i),n!==ze().getSdkVersion()?(at.remoteLogTracking(1,"info",t,"Version change detected. Will proceed to fetch latest campaigns"),!0):!(!(n=yield dn.serviceMetaStore.getItem(Z.STORES.SERVICE_META.KEYS.UNIQUE_ID))||n===(null===(e=xe.get(r.USER_DATA))||void 0===e?void 0:e.deviceUuid)||(at.remoteLogTracking(1,"info",t,"Unique device id change detected. Will proceed to fetch latest campaigns"),0)))}))}saveRemoteCampaigns(){return Ci(this,void 0,void 0,(function*(){var e=Pi.baseLogTag+".saveRemoteCampaigns";yield dn.campaingsMetaStore.clear(),yield dn.exitIntentCampaignStore.clear();var t=yield this.OnsiteApiClient.getCampaignsMeta();null!=t&&(yield this.addCampaignsToDB(t.campaignsMeta),at.log(1,e,"Inapp campaigns meta saved!")),yield ui.pruneRemovedCampaigns(),yield ui.removeStaleTriggeringPrimaryEventCampaigns(),yield dn.serviceMetaStore.setItem(Z.STORES.SERVICE_META.KEYS.GLOBAL_DELAY,t.globalDelayBetweenInapps),yield dn.serviceMetaStore.setItem(Z.STORES.SERVICE_META.KEYS.LAST_FETCH_SDK_VERSION,ze().getSdkVersion())}))}addCampaignsToDB(e){return Ci(this,void 0,void 0,(function*(){var t=Pi.baseLogTag+".addCampaignsToDB";at.log(1,t,`Adding/Updating ${e.length} campaigns in DB`,e.map((e=>e.campaignId)));try{yield Promise.all(e.map((e=>dn.campaingsMetaStore.setItem(e.campaignId,e)))),yield this.rebuildTagStore()}catch(e){at.error(1,t,"Error saving remote campaigns:",e)}}))}rebuildTagStore(){return Ci(this,void 0,void 0,(function*(){var e=Pi.baseLogTag+".rebuildTagStore";try{yield dn.campaingsTagsStore.clear();var t=yield Cn();const e={};for(const n of t)null!=n.tag&&(null==e[n.tag]&&(e[n.tag]=[]),e[n.tag].push(n.campaignId));const n=[];yield dn.campaingsTagsStore.clear();for(const t in e)e.hasOwnProperty(t)&&n.push(dn.campaingsTagsStore.setItem(t,e[t]));yield Promise.all(n)}catch(t){at.error(1,e,"Error updating tags store:",t)}}))}isExitIntentCampaignFound(e){return e.filter((e=>e.templateType!==mn.SELF_HANDLED&&An(e,b)))}prefetchExitIntentCampaigns(e){return Ci(this,void 0,void 0,(function*(){var t=Pi.baseLogTag+".prefetchExitIntentCampaigns";const n=yield Ht.createEvent("MOE_EXIT",[]),i=(yield Tn(e)).filter((e=>Kn.getFilterResult(n,e)));if(!i||!i.length)return at.log(1,t,"Exit intent campaign not eligible to prefetch"),!1;{const e=yield wn(i[0]);if(!e||!e.onsitePayload||e.onsitePayload.updatedTime.getTime()!==i[0].updatedTime.getTime()){var a=i[0].campaignId;const e=yield this.OnsiteApiClient.getCampaignPayload(i[0]);(e.payload||e.htmlJsonPayload)&&(e.updatedTime=i[0].updatedTime,yield dn.exitIntentCampaignStore.setItem(a,e),at.log(1,t,"Exit intent campaign prefetched: "+a))}}}))}refresh(){return Ci(this,void 0,void 0,(function*(){Wi.onsite.appId&&(yield Gi(),Hi())}))}}function Ri(){var e,t;const n="pageChangeHandler";window.Moengage.pageChangeHandlerCallingTime=(new Date).getTime(),(()=>{var e;const t=window.Moengage;if(t.onsite&&t.onsite.displayManager){t.onsite.triggerManager&&null!==(e=null===(e=t.onsite.triggerManager.primaryEventsHash)||void 0===e?void 0:e.MOE_PAGE_SCROLL)&&void 0!==e&&e.length&&window.removeEventListener("scroll",t.onsite.triggerManager.getScrollListenerCallback());const n=t.onsite.displayManager;Object.keys(n.campaignRenderMap).forEach((e=>{document.getElementById("moe-onsite-campaign-"+e)&&document.getElementById("moe-onsite-campaign-"+e).remove(),n.campaignRenderMap[e].isActive()&&n.dismissInapp(e),clearTimeout(n.campaignRenderMap[e].delayTimer),delete n.campaignRenderMap[e],n.campaignRenderOrder=n.campaignRenderOrder.filter((t=>t!==e))})),setTimeout((()=>{Ke()?t.onsite.triggerManager.windowEventManager.isPopStateEventBound&&(t.onsite.triggerManager.windowEventManager.setHistoryState(),t.onsite.triggerManager.windowEventManager.isExitIntentShown=!1,t.onsite.triggerManager.windowEventManager.scrollExitIntentInterval=null):document.removeEventListener("mouseout",t.onsite.triggerManager.windowEventManager.exitIntentListener)}),0)}t.onsite.initializationPomise=null,t.onsite.initialize()})(),window.MoeFocusHandler&&window.MoeFocusHandler(),window.Moengage.shouldClearPrevEvents=(new Date).getTime(),Gt.clear(),Gt.clearListeners(),Wi.track_page_view();var i=Wi.onsite.triggerManager;0<(null===(e=null==i?void 0:i.exitIntentCampaigns)||void 0===e?void 0:e.length)&&Ke()&&null!==(t=null==i?void 0:i.windowEventManager)&&void 0!==t&&t.onMobileScrollAndExit(i.onExit),zt.getWebSDKSettings().then((e=>{e.isDomainLevelStorage&&xe.copyKeysFromCookie(),null!=e&&e.configs.isCardsModuleEnabled&&Wi.cards&&(Wi.cards.checkCacheAndSaveRemote(de),Wi.cards.displayManager.closeIframe()),null!=e&&e.configs.isWebPersonalisationModuleEnabled&&(null!==(e=window.MoeWebP)&&void 0!==e&&e.getLiveExperiences(),at.log(1,n,"webP sync function called"))})).catch((e=>{at.error(1,n,"Error in getting Web SDK Settings. This might indicate that the App is blocked.")}))}Pi.baseLogTag="MoeOnsite",window[Z.OSM_MODULE]=Pi,window.MoeOsm=(at.log(1,"OsmFunctions","Osm Functions for tracking user behaviour"),{trackEvent:(e,t,n,i)=>(e=vi(e),{}.constructor===n.constructor&&e?(n=Object.assign(Object.assign({campaign_id:e.campaignId,campaign_name:e.campaignName},e.campaignContext),n),window.Moengage.track_event(t,n)):Promise.resolve()),trackClick:(e,t)=>(e=vi(e))?window.Moengage.onsite.displayManager.clickTracker(e,"OSM",{widget_id:t})():Promise.resolve(),trackDismiss:(e,t=!1)=>(e=vi(e))?window.Moengage.onsite.displayManager.dismissEvent(e,"OSM",t):Promise.resolve(),setAlias:e=>window.Moengage.update_unique_user_id(e),setUniqueId:e=>window.Moengage.add_unique_user_id(e),destroySession:()=>window.Moengage.destroy_session(),setUserName:e=>window.Moengage.add_user_name(e),setFirstName:e=>window.Moengage.add_first_name(e),setLastName:e=>window.Moengage.add_last_name(e),setEmailId:e=>window.Moengage.add_email(e),setMobileNumber:e=>window.Moengage.add_mobile(e),setGender:e=>window.Moengage.add_gender(e),setBirthDate:e=>window.Moengage.add_birthday(e),setUserAttribute:(e,t)=>window.Moengage.add_user_attribute(e,t),dismissMessage(e){setTimeout((()=>{window.Moengage.onsite.displayManager.dismissInapp(""+e)}),100)},showPushOptIn:e=>window.Moengage.call_web_push(e),copyText:e=>new Promise(((t,n)=>{e||n();const i=document.querySelector(e);i.textContent?navigator.clipboard.writeText(i.textContent):(i.select(),i.setSelectionRange(0,99999),navigator.clipboard.writeText(i.value)),t(null)}))});class Li{constructor(){this.getDeviceUniqueId=e=>{window.addEventListener(k,(t=>{t.detail.name===M.DEVICE_UUID&&(t=t.detail.data,e(t))}))}}onUpdateDeviceId(e){this.getDeviceUniqueId(e)}trackClick(e,t){return Li.track("MOE_WEBP_MESSAGE_CLICKED",e,t)}trackImpression(e){return Li.track("MOE_WEBP_MESSAGE_SHOWN",e)}static track(e,t,n){var i=Li.baseLogTag+".track";if("string"==typeof t)try{t=JSON.parse(t)}catch(e){return void at.error(2,i,"Error parsing JSON string:",e)}var a=t&&t.cid.split("_")[0];if(!a)return Promise.reject();try{return ze()?(at.log(1,i,e+": Event Tracked"),ze().track_event(e,Object.assign({campaign_id:a},t))):(window.moengage_q=window.moengage_q||[]).push({f:"track_event",a:[e,Object.assign(Object.assign({campaign_id:a},t),n)]}),Promise.resolve()}catch(e){at.error(2,i,"Failed Tracking expression",e)}}}Li.baseLogTag="Web Personalisation Tracking";var Ni=function(e,t,n,i){return new(n=n||Promise)((function(a,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function s(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?a(e.value):((t=e.value)instanceof n?t:new n((function(e){e(t)}))).then(o,s)}l((i=i.apply(e,t||[])).next())}))};const ki="MoEngage";let Mi=new st,xi=new st;const Bi={getData:(e,t)=>{zt.getWebSDKSettings().then((n=>{Mi.p.then((n=>{n.getData(e,t)}))})).catch((e=>{}))},registerCallback:(e,t)=>{zt.getWebSDKSettings().then((n=>{Mi.p.then((n=>{n.registerCallback(e,t)}))})).catch((e=>{}))}};class Wi{static callWebPush(e){const t=ki+".callWebPush";zt.getWebSDKSettings().then((n=>{var i,a,r,o,s,l,c;n.isConfigured?n.optInConfig.type===Tt.TYPE.SELF_HANDLED?(at.log(1,t,"Starting web push functions"),null!=e&&(Ne.setSoftAskConfig(e),i=Ee(e,"soft_ask_display_callback",null),a=Ee(e,"soft_ask_allow_callback",null),r=Ee(e,"soft_ask_block_callback",null),o=Ee(e,"hard_ask_allow_callback",null),s=Ee(e,"hard_ask_dismiss_callback",null),l=Ee(e,"hard_ask_block_callback",null),c=x,Xt.addCallback(c.SOFT_ASK_SHOWN,i),Xt.addCallback(c.SOFT_ASK_ALLOWED,a),Xt.addCallback(c.SOFT_ASK_DISMISSED,r),Xt.addCallback(c.HARD_ASK_ALLOWED,o),Xt.addCallback(c.HARD_ASK_DISMISSED,s),Xt.addCallback(c.HARD_ASK_DENIED,l)),ut.getInstance().then((e=>{new sn(n,e).callWebPush()}))):at.warn(1,t,"This feature can only be used when you have chosed self-handled approach in the dashboard. You can check dashboard here:",j):at.log(1,t,"Web push settings not configured on dashboard yet. To start web push subscriptions, please configure the settings on dashboard.")})).catch((e=>{at.error(1,t,"Error in getting Web SDK Settings. This might indicate that the App is blocked.")}))}static showNotification(e){zt.getWebSDKSettings().then((t=>{ut.getInstance().then((n=>{new sn(t,n).showNotification(e)}))})).catch((e=>{}))}static getSdkVersion(){return"2.30.19"}static setDebugLevel(e){return Ni(this,void 0,void 0,(function*(){const t=ki+".setDebugLevel";try{"number"==typeof e&&(!Ne.get().disableOnsite&&Wi.onsite.setLogLevel&&Wi.onsite.setLogLevel(e),zt.getWebSDKSettings().then((t=>{null!=t&&t.configs.isCardsModuleEnabled&&Wi.cards&&Wi.cards.setLogLevel(e),null!=t&&t.configs.isWebPersonalisationModuleEnabled&&window.MoeWebP&&window.MoeWebP.setLogLevel&&window.MoeWebP.setLogLevel(e),at.setLogLevel(e,!0)})).catch((n=>{at.setLogLevel(e,!0),at.error(1,t,"Error in getting Web SDK Settings. This might indicate that the App is blocked.")})))}catch(e){at.error(0,t,"Error changing log level:",e)}}))}static vitals(){var e=mt.getSync();return{deviceUuid:e.deviceUuid,userDetails:e,pushToken:xe.get(r.PUSH_TOKEN),softAskStatus:xe.get(r.SOFT_ASK_STATUS),hardAskStatus:xe.get(r.HARD_ASK_STATUS)}}static help(){var e=ki+".help";at.log(0,e,"Moengage Dashboard - ",V.MOE_DASHBOARD);for(const t in V)V.hasOwnProperty(t)&&at.log(0,e,t,"-",V[t])}static track_event(e,t){return Kt.track(e,t)}static add_unique_user_id(e){return Ni(this,void 0,void 0,(function*(){var t=yield on.login(e);return Ne.get(),zt.getWebSDKSettings().then((e=>{null!=e&&e.configs.isCardsModuleEnabled&&Wi.cards&&(at.log(1,"Moengage.add_unique_user_id","Fetching new Cards after login"),Wi.cards.refreshCards())})).catch((e=>{})),t}))}static update_unique_user_id(e){return on.updateUniqueId(e)}static add_user_attribute(e,t){return on.addAttribute(e,t)}static add_first_name(e){return on.addAttribute("first_name",e)}static add_last_name(e){return on.addAttribute("last_name",e)}static add_email(e){return on.addAttribute("email",e)}static add_mobile(e){return on.addAttribute("mobile",e)}static add_user_name(e){return on.addAttribute("name",e)}static add_gender(e){return on.addAttribute("gender",e)}static add_birthday(e){return on.addAttribute("birthday",e)}static destroy_session(){return Wi.user.logout()}static call_web_push(e){Wi.callWebPush(e)}static getBranch(){return"master"}static track_page_view(){return Kt.track(l,{timestamp:Number(Date.now())}),Kt.track(c,{timestamp:Number(Date.now())})}static handle_page_change(){Ri()}}Wi.user=on,Wi.event=Kt,Wi.device=class{static getUuid(){return xe.get(r.USER_DATA).deviceUuid}static getPushToken(){return xe.get(r.PUSH_TOKEN)}static getPermissionState(e){return new Promise(((t,n)=>{zt.getWebSDKSettings().then((i=>{ut.getInstance().then((a=>{new sn(i,a).getPermissionState().then((n=>{t(n),e&&e(null,n)})).catch((t=>{n(t),e&&e(t,null)}))}))})).catch((t=>{n(t),e&&e(t,null)}))}))}},Wi.onsite=Bi,Wi.reports=Wt.reports,Wi.remoteLogs=Wt,Wi.web_p=new Li;var Ui=()=>{};const Fi={track_event:Ui,add_user_attribute:Ui,add_first_name:Ui,add_last_name:Ui,add_email:Ui,add_mobile:Ui,add_user_name:Ui,add_gender:Ui,add_birthday:Ui,destroy_session:Ui,add_unique_user_id:Ui,moe_events:Ui,location_type_attribute:Ui,call_web_push:Ui,setDebugLevel:Ui};function Hi(){var e;null!==(e=null===(e=Wi.onsite)||void 0===e?void 0:e.initData)&&void 0!==e&&e.appId||(e=Ne.get(),Wi.onsite=new Pi(e),Mi.res(Wi.onsite),Wi.onsite.initialize())}function Gi(){var e;return Ni(this,void 0,void 0,(function*(){null!==(e=null===(e=Wi.onsite)||void 0===e?void 0:e.initData)&&void 0!==e&&e.appId&&(at.log(1,"Moengage.disableOnsiteApi","logging out from inapp module"),yield Wi.onsite.logout(),Mi=new st,Wi.onsite=Bi)}))}class Ki{onWindowVisibilityChange(e){ye.set("isWindowActive",!0),document.addEventListener("focus",(()=>{t(!0)}),!1),document.addEventListener("blur",(()=>{t(!1)}),!1),window.addEventListener("focus",(()=>{t(!0)}),!1),window.addEventListener("blur",(()=>{"IFRAME"!==document.activeElement.tagName&&t(!1)}),!1);const t=e=>"boolean"==typeof e?n(e?"visible":"hidden"):document.hidden?n("hidden"):n("visible"),n=t=>{ye.set("isWindowActive","visible"===t),e(t)};window.addEventListener("visibilitychange",t,!1)}}Ki.baseLogTag="WindowEventManager";var Vi=function(e,t,n,i){return new(n=n||Promise)((function(a,r){function o(e){try{l(i.next(e))}catch(e){r(e)}}function s(e){try{l(i.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?a(e.value):((t=e.value)instanceof n?t:new n((function(e){e(t)}))).then(o,s)}l((i=i.apply(e,t||[])).next())}))};class ji{static initialize(){return Vi(this,void 0,void 0,(function*(){var e;return null==ji.ready&&(ji.campaignStore=Se.createInstance({driver:[Se.INDEXEDDB,Se.WEBSQL,Se.LOCALSTORAGE],name:se,storeName:le.STORE_NAME}),ji.metaStore=Se.createInstance({driver:[Se.INDEXEDDB,Se.WEBSQL,Se.LOCALSTORAGE],name:se,storeName:ce.STORE_NAME}),e=[ji.campaignStore.ready(),ji.metaStore.ready()],ji.ready=Promise.all(e)),ji.ready}))}static clear(){return Vi(this,void 0,void 0,(function*(){var e=ji.baseLogTag+".clear";try{yield ji.initialize(),yield Promise.all([ji.campaignStore.clear(),ji.metaStore.clear()]);var t=[ji.campaignStore.ready(),ji.metaStore.ready()];ji.ready=Promise.all(t)}catch(t){at.error(1,e,"Error clearing cards stores:",t)}return ji.ready}))}}let Yi;function zi(e){const t="Pre-Initialization";if(!(e=>{const t=["bot","spider","crawler","crawling","Applebot","PetalBot","pingbot","proximic","AdsBot-Google","Googlebot","Cincraw","SnapchatBot","Snapchat-Proxy/1.0","SnapchatAds","Snapchat-Ads/1.0","YandexRenderResourcesBot","bingbot","slurp","MicrosoftPreview","Baiduspider","HeadlessChrome",...Array.isArray(e)?e:[]];return new RegExp(t.join("|"),"i").test(navigator.userAgent)})(null==e?void 0:e.bots_list)){var n=ze();return n&&0<n.initialised?(at.error(1,t,"MoEngage Web SDK initialised multiple times. Please integrate the Web SDK only once!"),n):(at.log(1,t,"Init data: ",e),"undefined"==typeof Promise?(at.error(1,t,"Promises not supported"),Fi):e.app_id||e.appId?((n=Ji())&&(e=Object.assign({},e,n)),Ne.save(e),$i().then((()=>{Ft.broadcastToWindow({topic:k,name:M.MOE_INIT,data:Ne.get()}),Ve()===fe.WEB&&qi(),at.setLogLevel(Ne.get().debugLevel),at.log(1,t,"Script loaded!"),at.customLabel(1,t,"SDK Version","2.30.19"),0<Ne.get().debugLevel&&(at.warn(1,t,"You are currently using MoEngage in debug environment. You'll find all the data captured in this environment in the TEST mode on the dashoard."),at.warn(1,t,"Please initialize with debugLevel as",0,"when using on your production environment.")),Xi().then((()=>{Ft.broadcastToWindow({topic:k,name:M.MOE_INIT_COMPLETED})}))})),e=window.moengage_object||"Moengage",window[e]=Wi,Wi):(at.error(1,t,"App Id not specified. Please check docs page to complete the integration - ",V.WEBSDK_DOCS),Fi))}at.error(1,t,"Bot detected, Can't initialise the MoEngage Web SDK")}ji.baseLogTag="MOE_CARDS_STORES";const qi=()=>{Se.createInstance({driver:[Se.INDEXEDDB,Se.WEBSQL,Se.LOCALSTORAGE],name:q,storeName:$}).clear()},$i=()=>new Promise((e=>{"complete"!==window.document.readyState?window.addEventListener("load",(()=>{e(!0)})):e(!0)}));window&&(window.moe=zi,window.moeBannerText="banner",window[Q]=Gt);const Ji=()=>{try{var e=localStorage.getItem("moe_segment_cluster"),t=localStorage.getItem("moe_segment_sw_path"),n=localStorage.getItem("moe_segment_sw_scope");const i={};return e&&(i.cluster=e),t&&(i.swPath=t),n&&(i.swScope=n),!!(e||t||n)&&(at.log(1,".isSegmentDataFound","Data found for segment initialisation",i),i)}catch(e){return!1}},Xi=()=>{const e="Initialization";return new Promise((t=>zt.getWebSDKSettings().then((n=>(nt.setRemoteLogging(n),n.isDomainLevelStorage&&(xe.isSharedWithCookie=!0,xe.copyKeysFromCookie()),(n.configs.isBatchingEnabled||n.configs.remoteLogTracking)&&(Wt.init(n),at.log(1,e,"Enabled Batching for "+(n.configs.isBatchingEnabled?"Event Tracking":"")+(n.configs.remoteLogTracking?", Remote Logs Tracking":""))),mt.get().then((i=>{if(nn.get().deviceToLogout===i.deviceUuid)return at.remoteLogTracking(1,"info",e,"User was not able to logout last time. Completing the logout now and starting new session."),Wi.user.logout();i.deviceAdded&&zt.onDeviceAdd.res(),n.isPushSubBilling&&at.warn(1,e,"You are under push subscriber based billing plan. We are only tracking users with an email, phone number or have subscribed to web push. All user attributes and events will be stored in a queue till we receive either of the properties.");var a=new dt;(new Ki).onWindowVisibilityChange(a.handleBrowserInactivity),at.customLabel(1,e,"Device UUID",i.deviceUuid),at.customLabel(1,e,"Device Added",i.deviceAdded),Ft.broadcastToWindow({topic:k,name:M.SETTINGS_FETCHED,data:n}),Ft.broadcastToWindow({topic:k,name:M.DEVICE_UUID,data:i.deviceUuid}),n.isPushSubBilling||i.deviceAdded||zt.deviceAdd(),Wi.track_page_view(),Jt.clear(r.Q.DEVICE),Jt.clear(r.Q.REPORT),Ne.get().enableSPA&&!Yi&&Zi(),ut.getInstance().then((t=>{var i;const a=!Ne.get().disableWebPush&&new sn(n,t);var o,s=!(null!==(s=window.MoeWebP)&&void 0!==s&&s.isEditorModeEnabled());a&&a.isWebPushEnabled()&&s?0<=[Tt.TYPE.ONE_CLICK,Tt.TYPE.TWO_STEP].indexOf(n.optInConfig.type)?a.callWebPush():(at.log(1,e,"Self handled setting. Will show opt-in on manual invocation, if required."),a.getPermissionState().then((t=>{var n=xe.get(r.PUSH_TOKEN);(t===Vt.GRANTED||null!=n&&t===Vt.DENIED)&&(t===Vt.GRANTED&&at.log(1,e,"Notification permission already granted. Proceeding to subscribe the user"),a.callWebPush())})).catch((t=>{at.warn(1,e,"Cannot get permission state: ",t)}))):sn.SUPPORTED_BROWSERS.indexOf(t.name)<0?at.warn(1,e,"Web push not supported on this browser. Supported browsers are:\n\t\t1. Google Chrome\n\t\t2. Mozilla Firefox\n\t\t3. Opera\n\t\t4. Edge\n\t\t5. Safari 16 and above + macOS 13 and above"):at.warn(1,e,"Web push feature not enabled for current environment"),!Ne.get().disableOnsite&&s?zt.onDeviceAdd.p.then((()=>{Hi()})):at.warn(1,e,"Onsite is disabled in this page since `disableOnsite: true` is passed during initialization."),null!=n&&n.configs.isCardsModuleEnabled&&null!==(i=Ne.get().cards)&&void 0!==i&&i.enable&&s?(o=n,ln.loadModule(ee.CARDS).then((e=>{xi.res(e),e.initialize(o),Wi.cards=e})).catch((e=>{xi.rej(e)}))):ji.clear(),Qi()})),t(!0)}))))).catch((n=>{at.error(1,e,"Error in getting Web SDK Settings. This might indicate that the App is blocked."),t(!1)}))))},Qi=()=>{const e="Moengage.clearWindowQ";$i().then((()=>{try{var t=window.moengage_object||"Moengage";if(window[t]&&window.moengage_q){let i=window.moengage_q;if(window.moengage_q=[],i&&0<i.length&&window[t])for(let t=0;t<i.length;t++){at.remoteLogTracking(1,"info",e,"Method called before SDK downloaded:",[i[t].f],i[t].a);var n=i[t].f;"onsite.getData"===n?Wi.onsite.getData(...i[t].a):"onsite.registerCallback"===n?Wi.onsite.registerCallback(...i[t].a):null!=Wi[i[t].f]&&Wi[i[t].f].apply(null,i[t].a)}i=[]}}catch(t){at.error(1,e,t)}}))},Zi=()=>{const e="startSpaUrlHandler";let t=document.location.href;(()=>{Yi=!0,at.log(1,e,"Start listening to URL changes");const n=document.querySelector("body"),i=new MutationObserver((n=>{n.forEach((n=>{t===document.location.href||document.location.href.includes("moe-card=1")||(t=document.location.href,at.log(1,e,"URL Change detected",t),Ri())}))}));i.observe(n,{childList:!0,subtree:!0})})()},ea={clearWindowQ:Qi,startSpaUrlHandler:Zi,isSegmentDataFound:Ji,clearEventsFromIDB:qi,moeInit:zi,windowLoaded:$i}})()})();