cdn.moengage.com Open in urlscan Pro
3.161.82.96  Public Scan

URL: https://cdn.moengage.com/webpush/moe_webSdk.min.latest.js
Submission: On September 25 via manual from SK — Scanned from IT

Form analysis 0 forms found in the DOM

Text Content

/*! 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 O(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(){O(e,t,n,i-1)}))})).catch(n);n(a)}}var C={_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(){O(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(){O(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){O(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(){O(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(){O(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(){O(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(){O(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(){O(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~([^~]+)~/,N="__lfsc__:",L=N.length,M="arbf",k="blob",x=L+M.length,B=Object.prototype.toString;function U(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 F(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 W={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=N;e instanceof ArrayBuffer?(i=e,a+=M):(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+F(i))}else if("[object Blob]"===n)(n=new FileReader).onload=function(){var n="~~local_forage_type~"+e.type+"~"+F(this.result);t(N+k+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,L)!==N)return JSON.parse(e);var t,n=e.substring(x),i=e.substring(L,x);i===k&&R.test(n)&&(t=(e=n.match(R))[1],n=n.substring(e[0].length));var a=U(n);switch(i){case M:return a;case k: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:U,bufferToString:F};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 K(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 G(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){K(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(G.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=W,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){K(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){K(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 G.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){K(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){K(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){K(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){K(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){K(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=W,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:C,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(W);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:()=>da,initializeLaunchSequence:()=>sa});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",OPTED_STATUS_TRACK_TIME:"OPTED_STATUS_TRACK_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_OPT_IN_SHOWN",h="MOE_OPT_IN_ALLOWED",m="MOE_OPT_IN_DISMISSED",f="MOE_OPT_IN_BLOCKED",v="MOE_OPT_IN_ATTEMPT",S="MOE_LOGOUT",E="EVENT_ACTION_DEVICE_ATTRIBUTE",y="MOE_PUSH_PERMISSION_STATE_ALLOWED",b="MOE_PUSH_PERMISSION_STATE_BLOCKED",_="MOE_PAGE_EXIT",T="MOE_PAGE_SCROLL",I="MOE_PAGE_URL_EVENT",A="USER_ATTRIBUTE_UNIQUE_ID",w="USER_ATTRIBUTE_USER_EMAIL",D="USER_ATTRIBUTE_USER_NAME",O="USER_ATTRIBUTE_USER_FIRST_NAME",C="USER_ATTRIBUTE_USER_LAST_NAME",P="USER_ATTRIBUTE_USER_MOBILE",R="USER_ATTRIBUTE_USER_GENDER",N="USER_ATTRIBUTE_USER_BDAY",L="USER_ID_MODIFIED_FROM",M=["id","first_name","last_name","email","mobile","name","gender","birthday"],k=[A,L,w,P],x="MOE_LIFECYCLE",B={MOE_INIT:"SDK_INITIALIZED",SETTINGS_FETCHED:"SETTINGS_FETCHED",EVENT_TRACKED:"EVENT_TRACKED",DEVICE_UUID:"DEVICE_UUID",MOE_INIT_COMPLETED:"SDK_INITIALIZATION_COMPLETED",CARDS_INIT:"CARDS_INITIALIZED"},U={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"},F={code:1e3,reason:"Web push not supported in current browser environment"},W={code:1001,reason:"Registering the service worker failed"},H={code:1002,reason:"Web push settings not configured"},K={code:1004,reason:"Hard ask was dismissed to many times"},G={code:1005,reason:"Service worker can not be registered on this page due to scope issues"},V="https://media.giphy.com/media/KDRv3QggAjyo/giphy.gif",j={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_6:"sdk-06.moengage.com",DC_100:"sdk-100.moengage.com",eu:"sdk-02.moengage.com",in:"sdk-03.moengage.com"},Y={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"},z="Dashboard --\x3e Settings --\x3e Channel --\x3e Push",q="SESSION",$="v3/sdkconfig/",J="moe_tracking",X="events",Q="batched_events",Z="moe_uuid",ee="MoengagePageEventHistoryManager",te={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_6:"https://sdk-06.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",CAMPAIGN_IMPRESSION_CANCEL_BEFORE_DELAY:"IMP_CNCL_BFR_DEL"},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},ne={CARDS:{name:"CARDS",src:"https://cdn.moengage.com/webpush/moe_webSdk_cards.min.latest.js",windowLocation:"moeCards"}},ie="moe_database",ae={NAME:"offline_data"},re="v2/sdk/report/",oe=15e3,se="number",le={TOPIC:"MOE_AUTOMATED_EVENTS",NAMES:[s,l,c,d,g,u,"MOE_USER_SUBSCRIBED",v,p,h,m,f,y,b,S,te.EVENT_NAMES.OSM.CLICK,te.EVENT_NAMES.OSM.IMPRESSION,te.EVENT_NAMES.OSM.DISMISS,te.EVENT_NAMES.OSM.AUTO_DISMIS]},ce=[v],de="moe_cards",ge={STORE_NAME:"campaigns"},ue={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"},pe="appOpen",he="IOS_PERMISSION_DENIED",me="moe_push_opted",fe="v1/sdk_logging/",ve="v2/device/add",Se="v2/device/token-check",Ee="v2/report/add",ye={TV:"tv",TABLET:"tablet",MOBILE:"mobile",WEB:"web"};var be,_e=n(483);function Te(e,t,n){return null!=e&&t?(e=e[(t=Array.isArray(t)?t:t.split("."))[0]])&&1<t.length?Te(e,t.slice(1),n):void 0===e?n||null:e:null}class Ie{static set(e,t){Ie.baseLogTag,window&&(window.moeInternals?window.moeInternals.ephemeral||(window.moeInternals.ephemeral={}):(window.moeInternals={},window.moeInternals.ephemeral={}),window.moeInternals.ephemeral[e]=t)}static get(e){return Te(window,"moeInternals.ephemeral."+e,null)}}Ie.baseLogTag="EphemeralStorage";class Ae{constructor(){this.items=[]}static enqueue(e,t){e=Ae.getLocalStorageQName(e);let n=new Ae;We.get(e)&&(n=We.get(e)),n.items.push(t),n.items=n.items.slice(Math.max(n.items.length-50,0)),We.set(e,n)}static dequeue(e){e=Ae.getLocalStorageQName(e);const t=We.get(e);let n=null;return t&&0<t.items.length&&(n=t.items[0],t.items.splice(0,1),We.set(e,t)),n}static isEmpty(e){return e=Ae.getLocalStorageQName(e),!(We.get(e)&&0<We.get(e).items.length)}static purge(e){var t=Ae.getLocalStorageQName(e);Ae.isEmpty(e)||We.remove(t)}static getLocalStorageQName(e){return r.Q.PREFIX+"_"+e}}class we{constructor(e){var t=we.baseLogTag+".constructor";e.placeholder||ut.warn(1,t,"Placeholder for cards inbox not passed in cardsConfig: ",e),this.placeholder=Te(e,"placeholder",""),this.enable=Te(e,"enable",!1),this.overLayColor=Te(e,"overLayColor","rgba(0, 0, 0, 0.8)"),this.backgroundColor=Te(e,"backgroundColor","#F6FBFC"),this.navigationBar=new De(Te(e,"navigationBar",{})),this.closeButton=new Pe(Te(e,"closeButton",{})),this.tab=new Re(Te(e,"tab",{})),this.cardDismiss=new Ne(Te(e,"cardDismiss",{})),this.optionButtonColor=Te(e,"optionButtonColor","#C4C4C4"),this.dateTimeColor=Te(e,"dateTimeColor","#8E8E8E"),this.unclickedCardIndicatorColor=Te(e,"unclickedIndicatorColor","blue"),this.pinIcon=Te(e,"pinIcon","https://app-cdn.moengage.com/sdk/pin-icon.svg"),this.refreshIcon=Te(e,"refreshIcon","https://app-cdn.moengage.com/sdk/refresh-icon.svg"),this.webFloating=new ke(Te(e,"webFloating",{})),this.mWebFloating=new ke(Te(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 Ce(Te(e,"card",{})),this.errorContent=new Oe(Te(e,"errorContent",{})),this.noDataContent=new xe(Te(e,"noDataContent",{})),this.openInbox=Te(e,"openInbox",(()=>{})),this.zIndex=Te(e,"zIndex","999999"),this.fontFaces=(null===(e=e.fontFaces)||void 0===e?void 0:e.map((e=>new Le(e))))||[]}}we.baseLogTag="CardsConfigModel";class De{constructor(e){this.backgroundColor=Te(e,"backgroundColor","#00237C"),this.text=Te(e,"text","Notification"),this.color=Te(e,"color","#fff"),this.fontSize=Te(e,"fontSize","16px"),this.fontFamily=Te(e,"fontFamily","inherit")}}class Oe{constructor(e={}){this.img=Te(e,"img","https://app-cdn.moengage.com/sdk/cards-error.svg"),this.text=Te(e,"text",'Error something went wrong <button onclick="window.location.reload();" style="color: #06A6B7; display: contents;" class="btn-icon pointer-cursor" >Refresh</button>')}}class Ce{constructor(e){this.headerFontSize=Te(e,"headerFontSize","16px"),this.descriptionFontSize=Te(e,"descriptionFontSize","14px"),this.ctaFontSize=Te(e,"ctaFontSize","12px"),this.fontFamily=Te(e,"fontFamily","inherit"),this.horizontalRowColor=Te(e,"horizontalRowColor","#D9DFED")}}class Pe{constructor(e){this.mWebIcon=Te(e,"mWebIcon","https://app-cdn.moengage.com/sdk/back-icon.svg"),this.webIcon=Te(e,"webIcon","https://app-cdn.moengage.com/sdk/cross-icon.svg"),this.callBack=Te(e,"callBack",(()=>{}))}}class Re{constructor(e){this.inactiveTabFontColor=Te(e,"inactiveTabFontColor","#7C7C7C"),this.fontSize=Te(e,"fontSize","14px"),this.fontFamily=Te(e,"fontFamily","inherit"),this.backgroundColor=Te(e,"backgroundColor","#F6FBFC"),this.active=new Me(Te(e,"active",{}))}}class Ne{constructor(e){this.color=Te(e,"color","red"),this.enable=Te(e,"enable",!1)}}class Le{constructor(e){this.family=Te(e,"family",""),this.url=Te(e,"url","")}}class Me{constructor(e){this.color=Te(e,"color","#06A6B7"),this.underlineColor=Te(e,"underlineColor","#06A6B7"),this.backgroundColor=Te(e,"backgroundColor","transparent")}}class ke{constructor(e){this.enable=Te(e,"enable",!1),this.icon=Te(e,"icon","https://app-cdn.moengage.com/sdk/bell-icon.svg"),this.postion=Te(e,"postion","0px 10px 40px 0"),this.countBackgroundColor=Te(e,"countBackgroundColor","#FF5A5F"),this.countColor=Te(e,"countColor","#fff"),this.zIndex=Te(e,"zIndex","999998"),this.iconBackgroundColor=Te(e,"iconBackgroundColor","#D9DFED"),this.fontFamily=Te(e,"fontFamily","inherit")}}class xe{constructor(e){this.img=Te(e,"img","https://app-cdn.moengage.com/sdk/cards-no-result.svg"),this.text=Te(e,"text","No notifications to show, check again later.")}}class Be{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=Be.baseLogTag+".constructor";null!=Te(e,"app_id",null)?(this.appId=Te(e,"app_id",null),this.integrationType=be.OLD_SDK):null!=Te(e,"appId",null)?(this.appId=Te(e,"appId",null),this.integrationType=be.NEW_SDK):(ut.error(1,t,"App Id not specified. Please check docs page to complete the integration - ",Y.WEBSDK_DOCS),this.integrationType=null),null!=Te(e,"debug_logs",null)?this.debugLevel=Te(e,"debug_logs",0):null!=Te(e,"debugLevel",null)?this.debugLevel=Te(e,"debugLevel",0):(ut.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=Te(e,"forceSwUpdate",!1),this.cluster=Te(e,"cluster",this.cluster),this.cluster&&null!=j[this.cluster]&&(this.environment=j[this.cluster]),Te(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=Te(e,"swPath",null),null!=e.customSoftAsk?this.customSoftAsk={mainClass:Te(e,"customSoftAsk.mainClass",null),allowClass:Te(e,"customSoftAsk.allowClass",null),dismissClass:Te(e,"customSoftAsk.dismissClass",null)}:this.customSoftAsk={mainClass:Te(e,"main_class",null),allowClass:Te(e,"allow_class",null),dismissClass:Te(e,"block_class",null)},null!=Te(e,"inapp.host",null)&&(this.inapp={host:Te(e,"inapp.host",null)}),null!=Te(e,"swScope",null)&&(this.swScope=Te(e,"swScope",null)),null!=Te(e,"disable_onsite",null)&&(this.disableOnsite=Te(e,"disable_onsite",!1)),null!=Te(e,"enableSPA",null)&&(this.enableSPA=Te(e,"enableSPA",!1)),null!=Te(e,"cards",null)&&(this.cards=new we(Te(e,"cards",{}))),null!=Te(e,"api_proxy_domain",null)&&(this.apiProxyDomain=Te(e,"api_proxy_domain",null),this.baseDomainName="https://"+this.apiProxyDomain+"/",this.environment=this.apiProxyDomain),null!=Te(e,"disable_web_push",null)&&(this.disableWebPush=Te(e,"disable_web_push",!1)),null!=Te(e,"disableCookies",null)&&(this.disableCookies=Te(e,"disableCookies",!1)))}static save(t){Ie.set(e,new Be(t)),We.set(r.INIT_DATA,new Be(t))}static get(){return Ie.get(e)}static setSoftAskConfig(e){var t=Be.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:Te(e,"main_class",Te(e,"mainClass",null)),allowClass:Te(e,"allow_class",Te(e,"allowClass",null)),dismissClass:Te(e,"block_class",Te(e,"dismissClass",null))}},Be.save(e)}}Be.baseLogTag="InitData",(bt=be=be||{}).OLD_SDK="OLD_SDK",bt.NEW_SDK="NEW_SDK";class Ue{static set(e,t){var n;null!==(n=Be.get())&&void 0!==n&&n.disableCookies||(n=Ue.baseTag+".set",null==t?Ue.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),ut.log(3,n,"Setting ",e,":",t),n=Date.now(),n=";expires="+new Date(n+31536e6*o).toUTCString(),document.cookie=e+"="+encodeURIComponent(t)+n+";domain="+Ue.getOrigin()+";path=/;SameSite=None; Secure"))}static get(e){var t;if(null===(t=Be.get())||void 0===t||!t.disableCookies){var n=Ue.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"===Te(a,"MOE_DATA_TYPE",null)?(a=Te(a,"actualValue",null),a=a?String(a):null):"boolean"===Te(a,"MOE_DATA_TYPE",null)&&(a=Te(a,"actualValue",null))}catch(t){}return ut.log(3,n,"Got ",e,":",a),a}}return null}}static remove(e){var t;null!==(t=Be.get())&&void 0!==t&&t.disableCookies||(t=Ue.baseTag+".remove",document.cookie=e+"=;domain="+Ue.getOrigin()+";path=/;expires=Thu, 01 Jan 1970 00:00:01 GMT;",ut.log(3,t,"Removed ",e))}static setRaw(e,t,n){if(null===(i=Be.get())||void 0===i||!i.disableCookies){var i=Ue.baseTag+".setRaw";if(null==t)Ue.remove(e);else{ut.log(3,i,"Setting ",e,":",t);let a="";null!=n&&(a=";expires="+n.toISOString()),document.cookie=e+"="+encodeURIComponent(t)+a+";domain="+Ue.getOrigin()+";path=/;"}}}static getOrigin(){if(null===(e=Be.get())||void 0===e||!e.disableCookies){var e=Ue.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&&(ut.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}}}Ue.baseTag="CookieStorage";const Fe="MOE_DATA";class We{static setPrefix(e){We.prefix=e+"_"}static set(e,t){if(We.baseLogTag,e=We.prefix+e,localStorage){const n=We.getMoeData();n[e]=t,localStorage.setItem(Fe,JSON.stringify(n))}var n=We.KEYS_SHARED_WITH_COOKIE.indexOf(e);if(We.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=>!!k.includes(e.key)))),e===r.SUBSCRIPTION_DETAILS&&(i.domain=t.domain,i.token=t.token,i.endpoint=t.endpoint,i.keys=t.keys),Ue.set(e,i)}}static get(e){return We.baseLogTag,e=We.prefix+e,localStorage?Te(We.getMoeData(),e,null):null}static remove(e){var t=We.baseLogTag+".remove",n=We.prefix+e;if(localStorage&&null!=We.get(e)){const i=We.getMoeData();delete i[n],localStorage.setItem(Fe,JSON.stringify(i)),ut.log(2,t,"Key",e,"removed.")}We.isSharedWithCookie&&0<=We.KEYS_SHARED_WITH_COOKIE.indexOf(e)&&Ue.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&&We.remove(r[t]);for(const e in r.Q)Ae.purge(e)}static getString(e){if(e=We.prefix+e,localStorage)return"string"==typeof(e=We.get(e))||e instanceof String?e:JSON.stringify(e)}static removePrefix(){We.prefix=""}static copyKeysFromCookie(){for(let n=0;n<We.KEYS_SHARED_WITH_COOKIE.length;n++){var e=We.KEYS_SHARED_WITH_COOKIE[n],t=Ue.get(e);if(null!=t){const n="object"!=typeof t||Array.isArray(t)?t:Object.assign({},t);if(e===r.USER_DATA&&(t=We.get(e)&&We.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=>!(k.includes(e.key)&&n.attributes.findIndex((t=>t.key===e.key))<0))),n.attributes=e}We.set(e,n)}}We.removeStaleKeysFromLS()}static removeStaleKeysFromLS(){var e=We.baseLogTag+".removeStaleKeysFromLS";try{Object.keys(We.getMoeData()).forEach((e=>{this.KEYS_SHARED_WITH_COOKIE.includes(e)&&!Ue.get(e)&&We.remove(e)}))}catch(t){ut.error(1,e,t)}}static getMoeData(){var e=We.baseLogTag+".getMoeData",t=localStorage.getItem(Fe);if(null==t)return{};try{return JSON.parse(t)}catch(t){return ut.error(1,e,t),{}}}}function He(e){return 0===Object.keys(e).length&&e.constructor===Object}function Ke(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 Ge(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 Ve(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 je(e,t){return t.isChrome()||t.isOpera()||t.isEdge()||t.isSafari()?e.chrome.vapidPublicKey:t.isFirefox()?e.firefox.vapidPublicKey:""}function Ye(){const e=Be.get().swPath;return!(!e||!e.includes("tools/moengage"))}function ze(e){return e.replace(/[\uff0e]/g,".")}function qe(){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 $e(){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)?ye.TV:t?ye.TABLET:qe()?ye.MOBILE:ye.WEB}function Je(e,t){const n=t&&new RegExp("^("+t.join("|")+")$");return $e()===ye.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:ye.TV.toUpperCase()}:{}}function Xe(e){return new Date(Date.parse(e))}function Qe(){return window[window.moengage_object||"Moengage"]}We.baseLogTag="PersistentStorage",We.prefix="",We.isSharedWithCookie=!1,We.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 Ze=e=>"string"==typeof e,et=e=>"[object Date]"===Object.prototype.toString.call(e);function tt(e){return"object"==typeof e&&!et(e)}function nt(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=>nt(e[n],t[n])))}function it(){const e=new Date;return`${e.getDate()}:${e.getMonth()+1}:${e.getFullYear()}:${e.getHours()}:${e.getMinutes()}:`+e.getSeconds()}const at=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{}},rt=e=>{var t,n,i=We.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()},ot=(e,t)=>{if(!t)return e;"?"!==e[e.length-1]&&(e+="?");for(const n in t)t.hasOwnProperty(n)&&null!=t[n]&&(e+=n+"="+encodeURIComponent(t[n])+"&");return"&"===e[e.length-1]?e.slice(0,-1):e},st=e=>{let t;try{t=JSON.stringify(e)}catch(e){return!1}return new Blob([t]).size/1024>195},lt=e=>e===s||e===b;function ct(e){return`Event "${e}" can't get tracked as its size is more than 195 KB. Max permissible event size is 195 KB.`}class dt{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||Qe().remoteLogs.addRemoteLogs(this.logData(e,{msg:n+[...a].toString(),file_name:t,trace:i}))}}let gt="color: white; background: #41AE55; border-radius: 5px;";class ut{static setLogLevel(e,t){var n=ut.baseLogTag+".setLogLevel";null==Ie.get(a)&&Ie.set(a,[]),null==e?ut.logLevel=0:e in[0,1,2]?0<(ut.logLevel=e)&&t&&ut.releaseAllLogs():ut.warn(0,n,"Value",e,"not supported for setDebugLevel(). Current log level is",ut.logLevel,". Debug level can only be [0, 1, 2]")}static setLogTabStyle(e){ut.tagLogStyle=ut.tagLogStyle.replace("#48beab",e)}static log(e,t,n,...i){e<=ut.logLevel?console.log("%c "+ut.logBrand+" %c %c info %c %c "+t+" ",gt,"","color: white; background: #18a0bf; border-radius: 5px;","",ut.tagLogStyle,n,...i):ut.cacheLog((()=>{ut.log(e,t,n,...i)}))}static remoteLogTracking(e,t,n,i,...a){dt.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||dt.log("error",t,n,...i),e<=ut.logLevel?console.error("%c "+ut.logBrand+" %c %c error %c %c "+t+" ",gt,"","color: white; background: #cc0a0a; border-radius: 5px;","",ut.tagLogStyle,n,...i.slice(0,-1)):ut.cacheLog((()=>{ut.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||dt.log("warning",t,n,...i),e<=ut.logLevel?console.warn("%c "+ut.logBrand+" %c %c warn %c %c "+t+" ",gt,"","color: white; background: #e8ab51; border-radius: 5px;","",ut.tagLogStyle,n,...i.slice(0,-1)):ut.cacheLog((()=>{ut.warn(e,t,n,...i,{isCached:!0})}))}static customLabel(e,t,n,...i){e<=ut.logLevel?console.log("%c "+ut.logBrand+" %c %c "+t+" %c %c "+n+" %c ",gt,"",ut.tagLogStyle,"","color: white; background: #a400ff; border-radius: 5px;","",...i):ut.cacheLog((()=>{ut.customLabel(e,t,n,...i)}))}static image(e,t){e<=ut.logLevel?console.log("%c+","font-size: 1px; padding: 20px 80px; line-height: 45px; background: url("+t+"); background-size: 160px 90px; color: transparent;"):ut.cacheLog((()=>{ut.image(e,t)}))}static releaseAllLogs(){var e=Ie.get(a),t=e.length;const n=e;if(Ie.set(a,[]),0<t){ut.log(0,"Logger.releaseAllLogs","<---- HISTORICAL LOGS BEGIN ----\x3e");for(let e=0;e<t;e++)n[e]();ut.log(0,"Logger.releaseAllLogs","<---- HISTORICAL LOGS END ----\x3e")}}static setLogBrand(e){ut.logBrand=e}static setBrandColor(e){gt="color: white; background: "+e+"; border-radius: 5px;"}static cacheLog(e){let t=Ie.get(a);null==t&&(t=[]),t.push(e),Ie.set(a,t)}}ut.baseLogTag="Logger",ut.logBrand="MoEngage",ut.logLevel=0,ut.tagLogStyle="color: white; background: #48beab; border-radius: 5px;";class pt{static get(e,t){return pt.makeNetworkCall(pt.METHODS.GET,e,t)}static post(e,t){return pt.makeNetworkCall(pt.METHODS.POST,e,t)}static makeNetworkCall(e,t,n={}){return new Promise(((i,a)=>{var r=JSON.stringify(Te(n,"postData",null));t=ot(t,Te(n,"queryParams",null));const o=new XMLHttpRequest;o.open(e,t,!0),pt.addRequestHeaders(o,Te(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}}(Ji=(Ji=pt=pt||{}).METHODS||(Ji.METHODS={})).GET="GET",Ji.POST="POST";const ht=pt;class mt{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){ut.error(1,"Utils.PromiseObject","Promises not supported")}}}var ft=n(877);class vt{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=Ie.get("wasBrowserInactive");return!(!t&&null!==t)&&(this.isWindowActive()&&Ie.set("wasBrowserInactive",!1),(new Date).getTime()>e)}isNonEventInteractive(e){return vt.NON_INTERACTIVE_EVENTS.includes(e.name)||0<e.attributes.filter((e=>"moe_non_interactive"===e.key&&1===e.value)).length}getCurrentSource(){const e=at(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=at(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,We.set(q,t)}removeCurrentSource(){const e=this.getSession();e&&(e.currentSource=void 0,We.set(q,e))}getSavedSource(){var e=Te(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,nt(e,t)}getSessionKey(){return Te(this.getSession(),"sessionKey",null)}getSessionStartTime(){return Te(this.getSession(),"sessionStartTime",null)}getSessionExpiryTime(){return Te(this.getSession(),"sessionExpiryTime",null)}getSessionMaxTime(){return Te(this.getSession(),"sessionMaxTime",null)}getSession(){return We.get(q)}geCustomIdentifiersToTrack(){return Te(this.getSession(),"customIdentifiersToTrack",[])||[]}generateSessionKey(){return(0,ft.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},We.set(q,t)}extendSession(){const e=this.getSession();e&&(e.sessionExpiryTime=(new Date).getTime()+1e3*e.sessionMaxTime,We.set(q,e))}handleBrowserInactivity(e){"hidden"===e&&Ie.set("wasBrowserInactive",!0)}isWindowActive(){return!!Ie.get("isWindowActive")}getNumberOfSessions(){return Te(We.get(q),"numberOfSessions")||0}}vt.NON_INTERACTIVE_EVENTS=[d,p,d,S];class St{constructor(e,t,n){this.os="web",this.osPlatform=e.userAgent,this.isMobile=qe(),this.os=qe()?"mweb":"web",this.name=St.getBrowserName(e.userAgent,t),this.isIncognito=n}static getInstance(){return e=this,i=function*(){if(null!=Ie.get(t))return Ie.get(t);var e=yield St.isIncognito(window),n=new St(navigator,document,e);return Ie.set(t,n),(e=We.get(r.BROWSER_DETAILS))&&St.isBrowserUpdated(e,n)||We.set(t,n),n},new(n=(n=void 0)||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())}));var e,n,i}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?St.BROWSER_NAMES.INTERNET_EXPLORER:-1<e.indexOf("Edg")?St.BROWSER_NAMES.EDGE:-1<e.indexOf("OPR")||-1<e.indexOf("Opera")?St.BROWSER_NAMES.OPERA:-1<e.indexOf("Chrome")||e.match(/\b(?:crmo|crios)\/([\w\.]+)/i)?-1<e.indexOf("MMS")?St.BROWSER_NAMES.OPERA_NEON:St.BROWSER_NAMES.CHROME:-1<e.indexOf("Safari")?St.BROWSER_NAMES.SAFARI:-1<e.indexOf("Firefox")?St.BROWSER_NAMES.FIREFOX:St.BROWSER_NAMES.OTHERS}static isBrowserUpdated(e,t){return nt(e,t)}isWebPushCompatible(){return this.isChrome()||this.isFirefox()||this.isOpera()||this.isSafari()||this.isEdge()}isChrome(){return this.name===St.BROWSER_NAMES.CHROME}isFirefox(){return this.name===St.BROWSER_NAMES.FIREFOX}isOpera(){return this.name===St.BROWSER_NAMES.OPERA||this.name===St.BROWSER_NAMES.OPERA_NEON}isSafari(){return this.name===St.BROWSER_NAMES.SAFARI}isEdge(){return this.name===St.BROWSER_NAMES.EDGE}static isIOS(){return!(!navigator.userAgent.match(/iPad/i)&&!navigator.userAgent.match(/iPhone/i))}}(bt=(bt=St=St||{}).BROWSER_NAMES||(bt.BROWSER_NAMES={})).CHROME="Google Chrome",bt.FIREFOX="Mozilla Firefox",bt.OPERA="Opera",bt.OPERA_NEON="Opera Neon",bt.SAFARI="Apple Safari",bt.INTERNET_EXPLORER="Internet Explorer",bt.EDGE="Edge",bt.OTHERS="Others";const Et=St;class yt{constructor(e,t){this.key=e,this.value=t,this.updated_at=(new Date).getTime()}static equal(e,t){return e.key===t.key&&JSON.stringify(e.value)===JSON.stringify(t.value)}}var bt,_t=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())}))};let Tt=null;class It{constructor(e){this.attributes=[],this.subscribedToOldSdk=!1,null==e?(this.deviceUuid=(0,ft.v4)(),this.attributes=[],this.deviceAdded=!1):(this.deviceUuid=Te(e,"deviceUuid",(0,ft.v4)()),this.attributes=Te(e,"attributes",[]),this.deviceAdded=Te(e,"deviceAdded",!1))}addAttribute(e){const t=It.baseLogTag+".addAttribute";return new Promise((n=>_t(this,void 0,void 0,(function*(){let i=!0;e.key=It.getMorphedKey(e.key);let a=-1;for(let t=this.attributes.length-1;0<=t;t--)e.key===this.attributes[t].key&&(a=t);0<=a?(nt(this.attributes[a].value,e.value)&&(ut.log(2,t,"Duplicate attribute found: ",e),i=yield this.isAttibuteTrackingRequired(this.attributes[a].updated_at)),i&&(this.attributes[a].value=e.value,this.attributes[a].updated_at=(new Date).getTime())):(ut.log(2,t,"Adding attribute:",e),this.attributes.push(e)),this.save().then((()=>{n(i)}))}))))}isAttibuteTrackingRequired(e){return _t(this,void 0,void 0,(function*(){var t=yield nn.getWebSDKSettings();if(null===t.configs.userAttributeCacheTime)return!0;var n=(new Date).getTime()-e;return Math.round(n/1e3)>t.configs.userAttributeCacheTime}))}static getLocalUser(){const e=It.baseLogTag+".getLocalUser";return new Promise((t=>{var n;We.get(r.USER_DATA)?(ut.log(2,e,"Found user in localstorage"),n=We.get(r.USER_DATA),t(new It(n))):t(null)}))}static getCookieUser(){return new Promise((e=>{var t=It.baseLogTag+".getLocalUser";Ue.get(r.USER_DATA)?(ut.log(2,t,"Found user in cookie"),t=Ue.get(r.USER_DATA),e(new It(t))):e(null)}))}static getMigrationUser(){const e=It.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 It({deviceAdded:Te(i,"device_add",!1),deviceUuid:Te(i,"uuid",(0,ft.v4)())}),n=Te(i,"user_attrs",{});for(const t in n)n.hasOwnProperty(t)&&e.attributes.push(new yt(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){ut.error(1,e,"Error getting the migration user. Resolving as a new user."),ut.error(1,e,n),t(null)}else t(null)}))}static getSync(){return It.instance}static get(){const e=It.baseLogTag+".get";return null!=Tt||(Tt=new Promise((t=>{Et.getInstance().then((n=>{nn.getWebSDKSettings().then((n=>{var i=It.getLocalUser(),a=n.isDomainLevelStorage?It.getCookieUser():"resolved",o=It.getMigrationUser();Promise.all([i,a,o]).then((i=>{const a=i[0],o=i[1],s=i[2];s?s.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))}ut.log(1,e,"User resolved from older SDK: ",n),t(n)})):(()=>{var i;if(o&&"resolved"!==o)ut.log(1,e,"User resolved from cookie: ",o),o.save().then((e=>{t(e)}));else{ut.log(1,e,"Local user: ",a);const o=new It(a);n.isPushSubBilling&&null!==(i=We.get(r.SUBSCRIPTION_DETAILS))&&void 0!==i&&i.token&&(o.deviceAdded=!0),o.save().then((e=>{t(e)}))}})()})).catch((t=>{ut.log(1,e,"Error in fetching/creating user",t)}))})).catch((t=>{ut.error(1,e,"Error in getting Web SDK Settings. This might indicate that the App is blocked.")}))}))}))),Tt}static logout(){return new Promise((e=>{Tt=null,e(!(this.instance=null))}))}save(){It.baseLogTag,It.isAmpEnabled()&&(this.deviceUuid=Ue.get("moe_uuid")),We.get("WEB_SETTINGS");var e=We.get(r.WEB_SETTINGS);return null!=e&&e.configs.isWebPersonalisationModuleEnabled&&(this.deviceUuid=this.deviceUuid||window.MoeWebP.deviceUuid),It.instance=this,new Promise((e=>{We.set(r.USER_DATA,this),Ue.setRaw(Z,It.instance.deviceUuid),e(this)}))}static isAmpEnabled(){const e=Ue.get(Z);return e&&e.includes("amp")}getAttribute(e){let t=null;return e=It.getMorphedKey(e),this.attributes.map((n=>{n.key===e&&(t=n.value)})),t}indexOfAttribute(e){let t=-1;return e=It.getMorphedKey(e),this.attributes.map(((n,i)=>{n.key===e&&(t=i)})),t}static getMorphedKey(e){switch(e){case"id":e=A;break;case"email":e=w;break;case"name":e=D;break;case"first_name":e=O;break;case"last_name":e=C;break;case"mobile":e=P;break;case"gender":e=R;break;case"birthday":e=N}return e}}It.baseLogTag="UserModel",It.isResolved=!1,It.instance=null;class At{constructor(){var e=At.baseLogTag+".constructor";const t=void 0;let n=It.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){ut.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,ft.v4)(),segmentSdkData:i?r:void 0}}}At.baseLogTag="ReportPostData";class wt{constructor(e,t,n){wt.baseLogTag,this.type=e,this.getParams=t,this.event=n,this.postData=new At;const i={},a={};for(const e of n.attributes)if(e&&null!=e.key&&(this.status=wt.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=He(a)?void 0:a,window&&window.location&&null!=window.location.href&&(this.postData.url=window.location.href)}}wt.baseLogTag="ReportClass",(bt=(Ji=wt=wt||{}).STATUS||(Ji.STATUS={}))[bt.INVALID=0]="INVALID",bt[bt.VALID=1]="VALID",(Ji=Ji.REPORT_ADD_TYPE||(Ji.REPORT_ADD_TYPE={}))[Ji.USER_ATTRIBUTE=0]="USER_ATTRIBUTE",Ji[Ji.EVENT=1]="EVENT";const Dt=wt;function Ot(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 Ct(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 Pt=class{constructor(e){this.isBeaconDisabled=this.parseSentryBooleanFlag(Te(e,"b_d",!1)),this.isCardsModuleEnabled=this.parseSentryBooleanFlag(Te(e,"c_s",!1)),this.isWebPersonalisationModuleEnabled=this.parseSentryBooleanFlag(Te(e,"c_w_p_e",!1)),this.eventBatchCount=Te(e,"e_b_c",10),this.logLevel=Te(e,"log_level"),this.periodicFlushTime=Te(e,"p_f_t",30),this.isBatchingEnabled=this.parseSentryBooleanFlag(Te(e,"s_e_b_e",!1)),this.sessionInactiveDuration=Te(e,"s_i_d",1800),this.isRemoteLoggingEnabled=this.parseSentryBooleanFlag(Te(e,"s_log",!1)),this.sourceExtraParams=Te(e,"src_ext",[]),this.whitelistedEvents=Te(e,"w_e",[]),this.blacklistedEvents=Te(e,"b_e",[]),this.isAppActive=this.parseSentryBooleanFlag(Te(e,"a_s",!0)),this.remoteLogTracking=this.isRemoteLoggingEnabled&&!!this.logLevel,this.subscriberBasedBillingAttributes=Te(e,"s_b_a",[]),this.isMultiIdEnabled=this.parseSentryBooleanFlag(Te(e,"m_i_e",!1)),this.userAttributeCacheTime=Te(e,"u_a_c_t",43200)}parseSentryBooleanFlag(e="blocked"){return"allowed"===e||!0===e||"true"===e}};class Rt{constructor(){this.settingsVersion="V1",this.isDomainLevelStorage=!1,this.isConfigured=!1,this.isPushSubBilling=!1,this.platformSettings=new xt,this.optInConfig=new Nt,this.configs=new Pt({})}static parseOldSettings(e){const t=Rt.baseLogTag+".parseOldSettings",n=new Rt;if((n.oldWebData=e).webData&&!He(e.webData))if(n.isConfigured=!0,e=e.webData,n.configs=new Pt(e),n.settingsVersion=Te(e,"wp_settings_version","V1"),"V2"===n.settingsVersion)n.isDomainLevelStorage=Te(e,"domain_level_storage",!1),n.isPushSubBilling=Te(e,"sub_billing",!1),n.platformSettings.chrome.domainType=Te(e,"is_enabled",!1)?"https":"na",n.platformSettings.chrome.subscriptionMode=Te(e,"web_push_platform_data.chrome.subscription_mode","vapid"),n.platformSettings.chrome.vapidPublicKey=Te(e,"web_push_platform_data.chrome.vapid_public_key",null),n.platformSettings.firefox.subscriptionMode=Te(e,"web_push_platform_data.firefox.subscription_mode","vapid"),n.platformSettings.firefox.vapidPublicKey=Te(e,"web_push_platform_data.firefox.vapid_public_key",null),n.optInConfig.reappearTime=Te(e,"prompt_again",24),n.optInConfig.type={"1-step":"ONE_CLICK","2-step":"TWO_STEP","self-handled":"SELF_HANDLED"}[Te(e,"opt_in_type","2-step")],n.optInConfig.showOverlay=Te(e,"show_overlay",!1),n.optInConfig.loadTime=Te(e,"load_time",0),n.optInConfig.type!==Nt.TYPE.SELF_HANDLED&&(i=e,a=n.optInConfig.type,r=n.optInConfig.showOverlay,new Promise(((e,t)=>{a===Nt.TYPE.ONE_CLICK&&r?e(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 Et.getInstance();return n=a.isFirefox()?(i=Ot(`\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),Ct(`\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=Ot(`\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),Ct(`\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=Ot(`\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),Ct(`\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}}))}(Te(i,"overlay",null),Te(i,"hide_moe_branding",!1)).then((e=>e))):a===Nt.TYPE.TWO_STEP&&e(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&amp;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&amp;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}}(Te(i,"opt_in_preview",null),Te(i,"hide_moe_branding",!1))),t("Its 1-step without overlay, so not constructing it.")})).then((e=>{n.optInConfig.softAskConfig.desktop.customHTML=e.webUI,n.optInConfig.softAskConfig.mobile.customHTML=e.mobileUI})).catch((e=>{ut.error(2,t,"Failed to construct overlay for hard ask: ",e)})));else{"false"===Te(e,"domain_level_storage",!1)?n.isDomainLevelStorage=!1:n.isDomainLevelStorage=!(!Te(e,"domain_level_storage",!1)&&"true"!==Te(e,"domain_level_storage",!1));let i=Te(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=Te(e,"webPushPlatformData.chrome.domain_type",""),n.platformSettings.chrome.subscriptionMode=Te(e,"webPushPlatformData.chrome.subscriptionMode","normal"),n.platformSettings.chrome.vapidPublicKey=Te(e,"webPushPlatformData.chrome.vapidPublicKey",null),n.platformSettings.firefox.enabled=!0,n.platformSettings.firefox.subscriptionMode=Te(e,"webPushPlatformData.firefox.subscriptionMode","normal"),n.platformSettings.firefox.vapidPublicKey=Te(e,"webPushPlatformData.firefox.vapidPublicKey",null),n.platformSettings.safari.websitePushId=Te(e,"webPushPlatformData.safari.websitePushId",null),null==n.platformSettings.safari.websitePushId?n.platformSettings.safari.enabled=!1:n.platformSettings.safari.enabled=!0,n.optInConfig.reappearTime=parseInt(Te(e,"promptAgain",24)),Te(e,"call_push_moengage",!0)?Te(e,"banner.banner_flag",null)?n.optInConfig.type=Nt.TYPE.TWO_STEP:n.optInConfig.type=Nt.TYPE.ONE_CLICK:(n.optInConfig.type=Nt.TYPE.SELF_HANDLED,n.optInConfig.reappearTime=0),n.optInConfig.showOverlay=Te(e,"show_overlay",!1),n.optInConfig.loadTime=Te(e,"load_time",0),n.optInConfig.softAskConfig.desktop.customHTML=Te(e,"bannerHtml.web",null),n.optInConfig.softAskConfig.mobile.customHTML=Te(e,"bannerHtml.mweb",null),Be.get().disableCookies&&(n.isDomainLevelStorage=!1,ut.warn(2,t,"Cookies Storage Been Disabled"))}else n.isConfigured=!1;var i,a,r;return n}}Rt.baseLogTag="SdkSettings";class Nt{constructor(){this.type=Nt.TYPE.NA,this.reappearTime=24,this.softAskConfig={desktop:new Lt,mobile:new Lt}}}class Lt{constructor(){this.customHTML=null}}(Ji=(Ji=Nt=Nt||{}).TYPE||(Ji.TYPE={})).NA="NA",Ji.ONE_CLICK="ONE_CLICK",Ji.TWO_STEP="TWO_STEP",Ji.SELF_HANDLED="SELF_HANDLED";class Mt{constructor(){this.enabled=!1,this.websitePushId=null}}class kt{constructor(){this.enabled=!1,this.isServiceWorkerRoot=!0,this.serviceWorkerFilename="serviceworker.js",this.subscriptionMode="normal",this.vapidPublicKey=null,this.domainType=""}}(Ji=(Ji=kt=kt||{}).DOMAIN_TYPE||(Ji.DOMAIN_TYPE={})).NA="NA",Ji.HTTPS="https",Ji.MUTLI="multi";class xt{constructor(){this.safari=new Mt,this.chrome=new kt,this.firefox=new kt}}const Bt=Rt;class Ut{static initialize(){return e=this,n=function*(){if(null==Ut.ready){Ut.offlineDataStore=_e.createInstance({driver:[_e.INDEXEDDB],name:ie,storeName:ae.NAME});const t=_e.createInstance({driver:[_e.INDEXEDDB],name:ie,storeName:"moe_data"}),n=_e.createInstance({driver:[_e.INDEXEDDB],name:ie,storeName:"moe_backup"});var e=[Ut.offlineDataStore.ready(),t.ready(),n.ready()];Ut.ready=Promise.all(e)}return yield Ut.ready},new(t=(t=void 0)||Promise)((function(i,a){function r(e){try{s(n.next(e))}catch(e){a(e)}}function o(e){try{s(n.throw(e))}catch(e){a(e)}}function s(e){var n;e.done?i(e.value):((n=e.value)instanceof t?n:new t((function(e){e(n)}))).then(r,o)}s((n=n.apply(e,[])).next())}));var e,t,n}}class Ft{constructor(e){this.EVENT_ACTION=e.event.name,this.EVENT_ATTRS=e.event.attributes&&Wt(e.event.attributes),this.EVENT_G_TIME=(new Date).getTime().toString(),this.EVENT_L_TIME=it(),this.EVENT_ATTRS_CUST=e.postData.c,this.N_I_E=e.postData.nie}}Ft.baseLogTag="ReportAddViewEvent";const Wt=e=>{const t={};return e.forEach((e=>{t[e.key]=e.value})),t};class Ht{static visibilityChange(){"hidden"===document.visibilityState&&(Ht.windowClosed||zt.reactToTriggerEvents())}static removeEventListeners(){document.removeEventListener("visibilitychange",Ht.visibilityChange,!1)}static addListeners(){document.addEventListener("visibilitychange",Ht.visibilityChange,!1)}}Ht.windowClosed=!1;const Kt=Ht;function Gt(e,t){try{var n=$e();return!(null==e||!e.configs.isBatchingEnabled||("web"!==n||t.name!==Et.BROWSER_NAMES.CHROME&&t.name!==Et.BROWSER_NAMES.EDGE&&t.name!==Et.BROWSER_NAMES.OPERA)&&("mobile"!==n||Et.isIOS()||t.name!==Et.BROWSER_NAMES.CHROME&&t.name!==Et.BROWSER_NAMES.OPERA)||!navigator.sendBeacon)}catch(e){ut.error(1,"Utils.batching.isBatchingSupported",e)}}class Vt{static getRemoteLogsBatchRequestOptions(e){return new Promise((t=>{nn.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=nn.baseLogTag+".sendBatchOfLogs";return new Promise(((n,i)=>{Vt.getRemoteLogsBatchRequestOptions(e).then((i=>{var a=(a=Be.get()).baseDomainName+fe+i.query_params.os.toLowerCase()+"/"+a.appId;ht.post(a,{postData:i}).then((()=>{ut.log(1,t,"[sendBatchOfLogs] batch payload: "+JSON.stringify(e)),ut.log(1,t,"Batch Remote Logs sent to MoEngage successfully"),Vt.batchRemoteLogsApiRetries=1,n(!0)})).catch((n=>{ut.log(1,t,"Batch Remote Logs API failed",n),this.handleRemoteLogsFailure(e)}))}))}))}static handleRemoteLogsFailure(e){var t=nn.baseLogTag+".handleRemoteLogsFailure";ut.log(1,t,"Retry Batch Logs Failed API",Vt.batchRemoteLogsApiRetries),Vt.batchRemoteLogsApiRetries<3&&setTimeout((()=>{Vt.batchRemoteLogsApiRetries++,Vt.sendBatchOfLogs(e)}),3e3*Vt.batchRemoteLogsApiRetries)}static sendBeacon(e){Vt.getRemoteLogsBatchRequestOptions(e).then((e=>{var t=(t=Be.get()).baseDomainName+fe+e.query_params.os.toLowerCase()+"/"+t.appId+"?"+(new Date).getTime();ut.log(1,"RemoteLogsApi.sendBeacon","[sendBeacon] Remote Logs batch payload: "+JSON.stringify(e)),navigator.sendBeacon(t,JSON.stringify(e))}))}}Vt.batchRemoteLogsApiRetries=1;var jt=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 Yt{static updateEventStore(){$e()!==ye.TV&&_e.createInstance({driver:[_e.INDEXEDDB,_e.WEBSQL,_e.LOCALSTORAGE],name:"moe_tracking",storeName:Q}).setItem(Q,Yt.reports)}static spliceReports(e=Yt.reports.length){return e=Yt.reports.splice(0,e),Yt.updateEventStore(),e}static spliceRemoteLogs(e=Yt.remoteLogs.length){return Yt.remoteLogs.splice(0,e)}static shouldCreateNewBatch(){return!Yt.lastbatchCreatedAt||(new Date).getTime()-Yt.lastbatchCreatedAt>=oe}static shouldCreateNewBatchForRemoteLogs(){return!Yt.lastRemoteLogsbatchCreatedAt||(new Date).getTime()-Yt.lastRemoteLogsbatchCreatedAt>=oe}static reactToTriggerEvents(){var e=Yt.baseLogTag+".reactToTriggerEvents";0<Yt.reports.length&&Yt.shouldCreateNewBatch()?(ut.log(1,e,`Trigger Events: Created Batch of ${Yt.reports.length} reports`,it()),Yt.createBatch()):ut.log(2,e,it()+": No report's to sync for this event."),0<Yt.remoteLogs.length&&Yt.shouldCreateNewBatchForRemoteLogs()?(ut.log(1,e,`Trigger Events: Created Batch of remote logs ${Yt.remoteLogs.length} reports`,it()),Yt.createRemoteLogsBatch()):ut.log(2,e,it()+": No logs's to sync for remote logs.")}static periodicSync(e){var t=Yt.baseLogTag+".periodicSync";0<Yt.reports.length&&Yt.shouldCreateNewBatch()?(ut.log(1,t,`Periodic sync: Created Batch of ${Yt.reports.length} reports`,it()),Yt.createBatch()):ut.log(2,t,it()+`: No report's to sync at this interval. The next sync will attempt in ${e} seconds`),0<Yt.remoteLogs.length&&Yt.shouldCreateNewBatchForRemoteLogs()?(ut.log(1,t,`Periodic sync: Created Batch of remote logs ${Yt.reports.length} reports`,it()),Yt.createRemoteLogsBatch()):ut.log(2,t,it()+`: No report's to sync at this interval for remote logs. The next sync will attempt in ${e} seconds`)}static clearInterval(){clearInterval(Yt.periodicSyncInterval),Yt.lastbatchCreatedAt=null}static init(e){Et.getInstance().then((t=>jt(this,void 0,void 0,(function*(){(Yt.isOfflineBatchingSupported(t,e)||e.configs.remoteLogTracking)&&(yield Ut.initialize(),Yt.periodicSyncInterval&&Yt.clearInterval(),Yt.periodicSyncInterval=window.setInterval(Yt.periodicSync.bind(this,e.configs.periodicFlushTime),1e3*e.configs.periodicFlushTime),Kt.addListeners())}))))}static sendBatch(e){var t=Yt.baseLogTag+".sendBatch";try{nn.sendBatchOfReports(e).then((()=>{Yt.lastbatchCreatedAt=(new Date).getTime()}))}catch(e){ut.error(1,t,"Error in sending batch",e)}}static sendRemoteLogs(e){var t=Yt.baseLogTag+".sendRemoteLogs";try{Vt.sendBatchOfLogs(e).then((()=>{Yt.lastRemoteLogsbatchCreatedAt=(new Date).getTime()}))}catch(e){ut.error(1,t,"Error in sending batch of remote logs",e)}}static createBatch(e){0<Yt.reports.length&&(e=Yt.spliceReports(e),Yt.sendBatch(e))}static createRemoteLogsBatch(e){0<Yt.remoteLogs.length&&(e=Yt.spliceRemoteLogs(e),Yt.sendRemoteLogs(e))}static addReport(e,t){var n=Yt.baseLogTag+".addReport";return e=new Ft(e),st(e)?(ut.error(1,n,ct(e.EVENT_ACTION)),!1):(Yt.reports.push(e),st(Yt.reports)?(Yt.reports.pop(),ut.log(1,n,`Created Batch of ${Yt.reports.length} reports as payload size would have breached after adding new event to this batch: "${e.EVENT_ACTION}"`,it()),Yt.createBatch(),Yt.reports.push(e),Yt.updateEventStore()):(Yt.updateEventStore(),Yt.reports.length===t&&(ut.log(1,n,`Created Batch of ${t} reports`,it()),Yt.createBatch(t))),!0)}static sendBeacon(){var e=Yt.baseLogTag+".sendBeacon";0<Yt.reports.length&&(ut.log(1,e,`Window Unload: Created batch of ${Yt.reports.length} reports`,it()),nn.sendBeacon(Yt.spliceReports())),0<Yt.remoteLogs.length&&(ut.log(1,e,`Window Unload: Created Remote Logs batch of ${Yt.remoteLogs.length} reports`,it()),Vt.sendBeacon(Yt.spliceRemoteLogs()),Yt.lastRemoteLogsbatchCreatedAt=(new Date).getTime())}static flushReports(){return jt(this,void 0,void 0,(function*(){var e=Yt.baseLogTag+".flushReports";try{Kt.removeEventListeners(),0<Yt.reports.length&&(ut.log(1,e,`Flushed ${Yt.reports.length} reports`,it()),Yt.sendBatch(Yt.spliceReports())),0<Yt.remoteLogs.length&&(ut.log(1,e,`Flushed ${Yt.remoteLogs.length} remote logs`,it()),Yt.sendRemoteLogs(Yt.spliceRemoteLogs()))}catch(t){ut.error(1,e,"Error in flushing reports",t)}}))}static isOfflineBatchingSupported(e,t){return Gt(t=t||We.get(r.WEB_SETTINGS),e)}static addRemoteLogs(e,t=15){var n=Yt.baseLogTag+".addRemoteLogs";Yt.remoteLogs.push(e),Yt.remoteLogs.length===t&&(ut.log(1,n,`Created Batch of ${t} reports`,it()),Yt.createRemoteLogsBatch(t))}}Yt.baseLogTag="BatchManager",Yt.reports=[],Yt.remoteLogs=[],Yt.lastbatchCreatedAt=null,Yt.lastRemoteLogsbatchCreatedAt=null;const zt=Yt;class qt{static getListeners(){return this.listeners}static getTopicListeners(e){return Te(qt.topicListeners,e,[])}static addListener(e){qt.listeners.push(e)}static addTopicListener(e,t){qt.topicListeners[e]=qt.getTopicListeners(e),qt.topicListeners[e].push(t)}static broadcast(e){qt.listeners.map((t=>{t(e)})),Te(qt.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(){qt.listeners=[],qt.topicListeners={}}static resetListeners(){qt.listeners=[]}}qt.listeners=[],qt.topicListeners={};const $t=qt;class Jt{constructor(e,t,n=!0){this.name=e,this.attributes=t,this.timestamp=(new Date).getTime(),n&&this.attributes.push(new yt("URL",location.href))}static createUserAttributeEvent(e){return new Promise(((t,n)=>{const i=[],a=e.key;switch(e.key){case"id":e.key=A;break;case"email":e.key=w;break;case"name":e.key=D;break;case"first_name":e.key=O;break;case"last_name":e.key=C;break;case"mobile":e.key=P;break;case"gender":e.key=R;break;case"birthday":e.key=N}i.push(e),It.get().then((n=>{var r=n.indexOfAttribute("oldUniqueIds");e.key===A&&-1<r&&null!=n.attributes[r].value&&0<n.attributes[r].value.length&&i.push(new yt(L,n.attributes[r].value[n.attributes[r].value.length-1])),e.key!==a&&ut.log(2,"Event.createUserAttributeEvent","Key changed to MoE reserved keyname: ",e.key),t(new Jt("EVENT_ACTION_USER_ATTRIBUTE",i,!1))}))}))}static createEvent(e,t,n){return new Promise(((i,a)=>{It.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 yt("moe_logged_in_status",!!a.getAttribute("id"));const s=new vt;var o=new yt("moe_first_visit",s.getNumberOfSessions()<=1);t.push(r,o),i(new Jt(e,t,n))}catch(r){ut.error(1,"Event.createEvent","Error occurred in create events ",r)}}))))}))}}class Xt{static addEvent(e){Xt.history.push(e),Xt.listeners.forEach((t=>{t(e)}))}static getHistory(){return Xt.history}static addEventListener(e){Xt.listeners.push(e)}static clear(){Xt.history=[]}static clearListeners(){Xt.listeners=[]}}Xt.history=[],Xt.listeners=[];class Qt{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 nn.getWebSDKSettings()}catch(r){return ut.error(1,i,"Error in getting Web SDK Settings. This might indicate that the App is blocked."),void a(!1)}if("string"==typeof e&&e)if(o.configs.blacklistedEvents&&o.configs.blacklistedEvents.includes(e))ut.error(1,i,`This event "${e}" is blacklisted. Please contact Moengage team to whitelist it.`),a({error:5001,message:`Event "${e}" is blacklisted.`});else if(!ce.includes(e)||o.configs.whitelistedEvents&&o.configs.whitelistedEvents.includes(e))try{const s=[];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)&&s.push(new yt(e,t[e]));const i=new vt;yield i.initiateSessionAndSource(o);const l=yield Jt.createEvent(e,s);Xt.addEvent(l),null!=o&&o.configs.isWebPersonalisationModuleEnabled&&null!==(r=window.MoeWebP)&&void 0!==r&&r.handleInSessionEvent(l),nn.collectGetParams().then((t=>{lt(e)&&delete t.push_id;const r=new Dt(Dt.REPORT_ADD_TYPE.EVENT,t,l);var o={session_id:i.getSessionKey(),start_time:i.getSessionStartTime(),background_initiated:0};const s=[];(t=i.getActiveSource())&&(i.setCurrentSource(t),s.push(t)),r.postData.meta.session=o,s.length&&(r.postData.meta.source=s),i.isNonEventInteractive(l)&&(r.postData.nie=1),nn.reportAdd(r,n).then((()=>{i.isNonEventInteractive(l)||i.extendSession(),a(!0)}))}))}else ut.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){ut.error(1,i,"Error occurred in tracking events ",r)}else ut.error(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 ut.error(1,i,"Event name not a string or null or empty string:",e),a({error:5001,message:"Event name can not be null"})}))))}}var Zt,en,tn=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 nn{static deviceAdd(){return new Promise(((e,t)=>{const n=Be.get();return nn.collectGetParams(ve).then((i=>{i={queryParams:i=Object.assign(Object.assign({},i),{url:window.location.href})},ht.post(n.baseDomainName+ve,i).then((()=>{this.trackDeviceAttributes(),It.get().then((t=>{t.deviceAdded=!0,t.save().then((()=>{on.startPeriodicClear(r.Q.REPORT),nn.onDeviceAdd.res(),e(!0)}))}))})).catch((e=>{Ae.enqueue(r.Q.DEVICE,!0),t(!1)}))}))}))}static trackDeviceAttributes(){return new Promise(((e,t)=>tn(this,void 0,void 0,(function*(){let t=$e().toUpperCase();t="WEB"===t?"DESKTOP":t,Qt.track(E,{deviceType:t});let n=We.get(r.PUSH_TOKEN);n||"granted"===(yield window.Moengage.device.getPermissionState())&&(n=!0),Qt.track(E,{[me]:!!n,source:"deviceAdd"}),We.set(r.OPTED_STATUS_TRACK_TIME,Date.now()),e(null)}))))}static reportAdd(e,t){const n=nn.baseLogTag+".reportAdd";return new Promise(((i,a)=>(t=!!t,nn.getWebSDKSettings().then((o=>{o.isPushSubBilling?It.get().then((o=>{o.deviceAdded?nn.reportAddInternal(e,t).then((()=>{this.sendBroadcast(e),i(!0)})).catch((()=>{a(!1)})):(Ae.enqueue(r.Q.REPORT,e),ut.log(1,n,"Report added to queue as device not added yet:",e.event.name),ut.log(2,n,"Event Queued:",e.event.name),e.type===Dt.REPORT_ADD_TYPE.USER_ATTRIBUTE&&(nn.isPushSubAttributeAccepted(e.event.attributes[0].key)?(ut.log(1,n,"Attribute accepted for push sub billing."),nn.deviceAdd()):ut.log(2,n,"Attribute NOT accepted for push sub billing.")),i(!0))})):nn.reportAddInternal(e,t).then((()=>{this.sendBroadcast(e),i(!0)})).catch((()=>{a(!1)}))})).catch((e=>{ut.error(1,n,"Error in getting Web SDK Settings. This might indicate that the App is blocked."),a(!1)})))))}static sendBroadcast(e){le.NAMES.includes(e.event.name)&&$t.broadcastToWindow({topic:le.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=>{nn.collectGetParams(re).then((n=>{var i=nn.getSegmentId()||"";const a=It.getSync(),r=new vt;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,ft.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 tn(this,void 0,void 0,(function*(){const n=nn.baseLogTag+".addReportsToOfflineDB";var i=yield nn.getBatchRequestOptions([]);yield Ut.offlineDataStore.setItem(t||"report_add_"+(new Date).getTime(),e),yield Ut.offlineDataStore.setItem("requestMetaData",i),navigator.serviceWorker&&navigator.serviceWorker.ready.then((e=>{e.sync?e.sync.register("moe_offline_data_sync").then((()=>{ut.log(2,n,"offline sync event registered")})).catch((e=>{ut.error(1,n,"Service worker sync error",e)})):ut.log(2,n,"Service worker sync unavailable")}))}))}static sendReportBeacon(e,t,n){var i=nn.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){ut.error(2,i,"Failed to send Report call with Beacon:",e)}return!1}static sendBatchOfReports(e){const t=nn.baseLogTag+".sendBatchOfReports";return new Promise(((n,i)=>{nn.getBatchRequestOptions(e).then((a=>{var r=Be.get();const o=r.baseDomainName+re+r.appId;nn.getWebSDKSettings().then((i=>window.navigator.onLine?nn.sendReportBeacon(i.configs.isBeaconDisabled,o,a)?(ut.log(1,t,"[sendBatchOfReports] batch payload: "+JSON.stringify(e)),ut.log(1,t,"Batch sent to MoEngage successfully through beacon"),void n(!0)):void ht.post(o,{postData:a}).then((()=>{ut.log(1,t,"[sendBatchOfReports] batch payload: "+JSON.stringify(e)),ut.log(1,t,"Batch sent to MoEngage successfully"),n(!0)})).catch((a=>{ut.error(1,t,"Batch Report add API failed",a),n(this.sendToOfflineTracking(e,a,i))})):this.sendToOfflineTracking(e,"User is offline.",i))).catch((e=>{ut.error(1,t,"Error in getting Web SDK Settings. This might indicate that the App is blocked."),i(e)}))}))}))}static sendToOfflineTracking(e,t,n){const i=nn.baseLogTag+".sendToOfflineTracking";return ut.error(1,i,"Add Report API failed, adding reports to offline db. ",t),new Promise(((a,r)=>{Et.getInstance().then((o=>{zt.isOfflineBatchingSupported(o,n)?(nn.addReportsToOfflineDB(e).then((()=>{ut.log(2,i,"Network offline: Batch added to offline db")})),a(!0)):r(t)})).catch((()=>{r(t)}))}))}static reportAddInternal(e,t){const n=nn.baseLogTag+".reportAddInternal";return new Promise(((i,a)=>{nn.getWebSDKSettings().then((a=>{Et.getInstance().then((o=>{if(t){const t=nn.getUpdatedPushDetails();for(const n in t)!t.hasOwnProperty(n)||lt(e.event.name)&&"push_id"===n||(e.getParams[n]=t[n]);var s=Je();const n={queryParams:Object.assign(Object.assign({},e.getParams),s)};if(e.postData.nie){const t=Object.assign({},e);delete t.postData.meta.source,delete t.postData.meta.session,n.postData=t.postData}else n.postData=e.postData;s=Be.get().baseDomainName,s+=ve,ht.post(s,n).then((()=>{let t=$e().toUpperCase();t="WEB"===t?"DESKTOP":t,Qt.track(E,{deviceType:t}),i(nn.handleReportAddSuccess(e))})).catch((t=>{Gt(a,o)?Ae.enqueue(r.Q.DEVICE,e):nn.handleReportAddFailure(e,t)}))}else Gt(a,o)?(zt.addReport(e,a.configs.eventBatchCount)&&(ut.log(1,n,"Event batched successfully:",e.event),this.addEventsToIDB(e.event)),i(!0)):(s=new Ft(e),st(s)?(ut.error(1,n,ct(s.EVENT_ACTION)),i(!1)):nn.sendBatchOfReports([s]).then((()=>{i(nn.handleReportAddSuccess(e))})).catch((t=>{nn.handleReportAddFailure(e,t)})))}))})).catch((e=>{ut.error(1,n,"Error in getting Web SDK Settings. This might indicate that the App is blocked."),a(!1)}))}))}static handleReportAddSuccess(e){var t=nn.baseLogTag+".handleReportAddSuccess";return e.type===Dt.REPORT_ADD_TYPE.EVENT?(ut.log(1,t,"Event tracked successfully:",e.event),this.addEventsToIDB(e.event)):e.type===Dt.REPORT_ADD_TYPE.USER_ATTRIBUTE&&ut.log(1,t,"User attribute added successfully:",e.event.attributes),nn.addReportApiRetries=1,!0}static handleReportAddFailure(e,t){var n=nn.baseLogTag+".handleReportAddFailure";ut.error(1,n,"Add Report API failed",t),e.type===Dt.REPORT_ADD_TYPE.EVENT?ut.log(1,n,"Queueing unsuccessful event tracking:",e.event):e.type===Dt.REPORT_ADD_TYPE.USER_ATTRIBUTE&&ut.log(1,n,"Queueing unsuccessful user attribute add:",e.event.attributes),nn.addReportApiRetries<3&&setTimeout((()=>{nn.addReportApiRetries++,Ae.enqueue(r.Q.REPORT,e),on.startPeriodicClear(r.Q.REPORT)}),3e3*nn.addReportApiRetries)}static checkIfTokenValid(e){const t=Be.get().baseDomainName+Se,n=Be.get();return new Promise((i=>{e?It.get().then((a=>{a={queryParams:{app_id:n.appId,unique_id:a.deviceUuid,push_id:e}},ht.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=Be.get();var i,a;null!=n&&null!=n.appId||(n=new Be(We.get(r.INIT_DATA))),nn.sdkSettings?nn.isAppBlocked(nn.sdkSettings)?t(!1):e(nn.sdkSettings):(i=(new Date).getTime(),null==(a=We.get(r.SETUP_TIME))||0<n.debugLevel||864e5<i-a?nn.getAndPersistWebSettings(n).then((t=>{e(t)})).catch((e=>{t(!1)})):We.get(r.WEB_SETTINGS)?(nn.sdkSettings=We.get(r.WEB_SETTINGS),nn.isAppBlocked(nn.sdkSettings)?t(!1):e(nn.sdkSettings)):nn.getAndPersistWebSettings(n).then((t=>{e(t)})).catch((e=>{t(!1)})))}))}static getAndPersistWebSettings(e){const t=nn.baseLogTag+".getAndPersistWebSettings";return new Promise(((n,i)=>tn(this,void 0,void 0,(function*(){try{var a={queryParams:{app_id:(e=null==e.appId?new Be(We.get(r.INIT_DATA)):e).appId}};ut.log(1,t,"Fetching latest web sdk settings for",e.appId);var o=yield ht.get(e.baseDomainName+"v2/websdksettings",a);ut.log(1,t,"Fetching config settings for",e.appId);let h=o.responseText;"string"==typeof h&&(h=JSON.parse(h));var s=qe()?"mweb":"web",l=e.baseDomainName+$+s+"/"+e.appId;try{var c,d=We.get(r.USER_DATA),g={postData:{query_params:{unique_id:d&&d.deviceUuid}}},u=yield ht.post(l,g);ut.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){ut.error(1,t,"Config API failed")}var p=(new Date).getTime();if(h=Bt.parseOldSettings(h),We.set(r.WEB_SETTINGS,h),We.set(r.SETUP_TIME,p),nn.isAppBlocked(h))return void i(!1);nn.sdkSettings=h,n(h)}catch(a){ut.error(1,t,"Settings APi Failed: ",a),nn.webSdkApiRetries<3?setTimeout((()=>{nn.webSdkApiRetries++,n(nn.getAndPersistWebSettings(e))}),3e3*nn.webSdkApiRetries):i(!1)}}))))}static collectGetParams(e){return new Promise(((t,n)=>{It.get().then((n=>{let i=Be.get();null!=i&&null!=i.appId||(i=new Be(We.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());Et.getInstance().then((a=>{var s,l=Je(e,[Ee,ve,re]);const c=Object.assign({os:a.os,os_platform:a.osPlatform,is_incognito:a.isIncognito,app_id:i.appId,os_ver:a.name,sdk_ver:"2.45.2",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()},l);l=n.getAttribute("cart_token"),Ye()&&l&&null!==(s=this.sdkSettings)&&void 0!==s&&s.configs.isMultiIdEnabled&&e!==ve&&(c.cart_token=l),null!=(l=We.get(r.PUSH_TOKEN))&&"NA"!==l&&""!==l&&"null"!==l&&(c.push_id=l),a.isWebPushCompatible()&&(Ve(this.sdkSettings.platformSettings,a)?(c.subscription_type="vapid",c.vapid_public=je(this.sdkSettings.platformSettings,a)):c.subscription_type="normal"),null!=i.environment&&(c.environment=i.environment),a.name===Et.BROWSER_NAMES.SAFARI&&(c.websitePushId=this.sdkSettings.platformSettings.safari.websitePushId);var d=We.get(r.SUBSCRIPTION_DETAILS);if(null!=d&&null!=d.keys){for(const e in d.keys)c["keys_"+e]=encodeURI(d.keys[e]);null!=d.endpoint&&(c.endpoint=encodeURI(d.endpoint)),c.expirationTime=d.expirationTime}t(c)}))}))}))}static getUpdatedPushDetails(){const e={};var t=We.get(r.SUBSCRIPTION_DETAILS);if(null!=t){var n=We.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){var t;return!!(e===w||e===P||null!==(t=this.sdkSettings)&&void 0!==t&&t.configs.subscriberBasedBillingAttributes.includes(e))}static sendBeacon(e){if(!window.navigator.onLine)return this.sendToOfflineTracking(e,"User is offline.");nn.getBatchRequestOptions(e).then((e=>{var t=(t=Be.get()).baseDomainName+re+t.appId+"?"+(new Date).getTime();ut.log(1,"MoeApi.sendBeacon","[sendBeacon] batch payload: "+JSON.stringify(e)),navigator.sendBeacon(t,JSON.stringify(e))}))}static addEventsToIDB(e){if($e()!==ye.TV){const t=_e.createInstance({driver:[_e.INDEXEDDB,_e.WEBSQL,_e.LOCALSTORAGE],name:J,storeName:X});null!=t&&t.setItem(e.name,e)}}}nn.baseLogTag="MoeApi",nn.onDeviceAdd=new mt,nn.webSdkApiRetries=1,nn.offlineEvents=[],nn.addReportApiRetries=1;const an=n(967),rn=r.Q;class on{static clear(e){var t=on.baseLogTag+".clear";const n=[];for(;!Ae.isEmpty(e);)switch(e){case rn.REPORT:const i=Ae.dequeue(rn.REPORT);n.push((e=>{nn.reportAdd(i).then((()=>{e()}))}));break;case rn.DEVICE:Ae.dequeue(rn.DEVICE)&&n.push((e=>{nn.deviceAdd().then((()=>{e()}))}));break;default:ut.error(1,t,"Do not know how to handle queue with name:",e)}setTimeout((()=>{on.processing[e]=!0,an(n,5,((t,n)=>{on.processing[e]=!1}))}),0)}static startPeriodicClear(e){const t=on.baseLogTag+".startPeriodicCleanQ";on.clearInterval(e);var n=()=>{Ae.isEmpty(e)?(ut.log(1,t,"If you see multiple event tracks with same, they were captured over multiple visits or page refreshes."),Te(on.processing,e,!1)||on.clearInterval(e)):(on.clear(e),ut.log(1,t,"Starting periodic queue clear for",e))};n(),on.intervals[e]=setInterval(n,6e3)}static clearInterval(e){null!=on.intervals[e]&&(clearInterval(on.intervals[e]),on.intervals[e]=null)}}on.baseLogTag="QManager",on.intervals={},on.processing={},(Ji=Zt=Zt||{}).PROMPT="prompt",Ji.GRANTED="granted",Ji.DENIED="denied",Ji.DISMISSED="dismissed";class sn{static addCallback(e,t){null!=e&&null!=t&&(null==sn.callbacks[e]&&(sn.callbacks[e]=[]),sn.callbacks[e].push(t))}static getCallbacks(e){return sn.callbacks[e]||[]}static runCallbacks(e){sn.getCallbacks(e).forEach((e=>{e()}))}}sn.callbacks={};class ln{constructor(e){this.swRegisterPromise=null,this.swActiveRetries=1;const t=ln.baseLogTag+".constructor";this.sdkSettings=e,this.registerServiceWorker().then((e=>{this.sendDataToServiceWorker()})).catch((e=>{ut.error(1,t,"Error registering serviceworker:",e)}))}showHardAsk(){const e=ln.baseLogTag+".showHardAsk";return new Promise(((t,n)=>{ln.isWebPushSupported().then((i=>{i?this.getCurrentPermissionState().then((i=>{this.registerServiceWorker().then((a=>{i!==Zt.DENIED?(ut.remoteLogTracking(1,"info",e,"Attempting to open hard ask"),Qt.track(v),$t.broadcastToWindow({topic:x,name:U.HARD_ASK_ATTEMPTED}),this.showOverlay(),this.askPermission().then((n=>{this.hideOverlay(),ut.remoteLogTracking(2,"info",e,"Permission state after hard ask:",n),n===Zt.GRANTED?this.getPushTokenDetails().then((e=>{this.sendDataToServiceWorker(e.token),t({state:n,subscriptionDetails:e})})):(this.sendDataToServiceWorker(),t({state:n,subscriptionDetails:null}))})).catch((t=>{ut.error(1,e,t),n(W)}))):(ut.remoteLogTracking(1,"info",e,"Hard ask not shown as permission state is",i),t({state:i,subscriptionDetails:null}))})).catch((t=>{ut.error(1,e,"Error registering serviceworker:",t),n(t)}))})).catch((t=>{ut.error(1,e,"Registering service worker failed:",t),n(W)})):(ut.warn(1,e,"Web push not supported in current browser environment"),n(F))}))}))}sendDataToServiceWorker(e){return new Promise((t=>{nn.collectGetParams().then((t=>{var n;e&&(t.push_id=e||We.get(r.PUSH_TOKEN)||void 0),t.isBatchingEnabled=We.get(r.WEB_SETTINGS).configs.isBatchingEnabled,Ye()||null!==(n=Be.get())&&void 0!==n&&n.swScope?_e.createInstance({driver:[_e.INDEXEDDB],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 Et.getInstance().then((e=>navigator.permissions&&!e.isSafari()?navigator.permissions.query({name:"notifications"}).then((e=>ln.parsePermissionState(e.state))).catch((e=>{})):new Promise((t=>{let n=null===Notification||void 0===Notification?void 0:Notification.permission;e.isSafari()&&"default"===n&&(n="prompt",We.get(he)&&(n="denied")),t(ln.parsePermissionState(n))}))))}getPushTokenDetails(){const e=ln.baseLogTag+".getPushTokenDetails";return new Promise(((t,n)=>{this.getCurrentPermissionState().then((n=>{Et.getInstance().then((i=>{n!==Zt.GRANTED?t({token:null,raw:null}):this.registerServiceWorker().then((n=>{let a=null;const r={userVisibleOnly:!0};Ve(this.sdkSettings.platformSettings,i)&&(a=je(this.sdkSettings.platformSettings,i),r.applicationServerKey=Ke(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=>{ut.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=Ge(e.options.applicationServerKey);[a,a+"=",a+"==",Ge(Ke(a))].indexOf(t)<0?e.unsubscribe().then((()=>{o()})):o()}else o();else o()}))})).catch((n=>{ut.error(1,e,"Error in getting push token: ",n),t({token:null,raw:null})}))}))}))}))}removeToken(){return We.remove(r.PUSH_TOKEN),We.remove(r.OPTED_STATUS_TRACK_TIME),We.remove(r.SUBSCRIPTION_DETAILS),Promise.resolve()}askPermission(){return new Promise(((e,t)=>{null!==Notification&&void 0!==Notification&&Notification.requestPermission().then((t=>{We.set(r.OPT_IN_SHOWN_TIME,Date.now()),Qt.track(p),$t.broadcastToWindow({topic:x,name:U.HARD_ASK_SHOWN}),$t.deprecatedSdkCallback("opt_in_shown"),sn.runCallbacks(U.HARD_ASK_SHOWN),e(ln.parsePermissionState(t))})).catch((e=>{t(K)}))}))}registerServiceWorker(){const e=ln.baseLogTag+".registerServiceWorker";return null!=this.swRegisterPromise||(this.swRegisterPromise=new Promise(((t,n)=>{if(ln.registeredServiceWorker)t(ln.registeredServiceWorker);else if("serviceWorker"in navigator){let i="serviceworker.js",a=!1;if(Be.get()&&null!=Be.get().swPath&&(i=Be.get().swPath,a=!0),"/"===i[0]||i.startsWith("http")||(i="/"+i),Ye())ut.log(1,e,"Removing scope in case of shopify."),this.registerScopedSW(i,/moengage/,t,n);else{let r="/";Be.get()&&null!=Be.get().swScope?(r=Be.get().swScope,this.registerScopedSW(i,r,t,n)):(a&&(ut.log(1,e,"Using user defined path to serviceworker:",i),r=i.substr(0,i.lastIndexOf("/")+1),ln.canSwBeRegisteredWithScope(r)||(ut.error(1,e,"Service worker can only be registered from same directory or child directory."),n(G))),navigator.serviceWorker.register(i,{scope:r}).then((i=>{ut.log(2,e,"Serviceworker registered"),navigator.serviceWorker.ready.then((n=>{ut.log(2,e,"Serviceworker ready"),ln.registeredServiceWorker=n,Be.get()&&Be.get().forceSwUpdate&&n.update(),t(n)})).catch((t=>{ut.error(1,e,"Service worker register failed:",t),n(W)}))})).catch((t=>{ut.error(1,e,"Service worker register failed:",t),n(W)}))),ut.log(1,e,"Scope for serviceworker:",r)}}else ut.error(1,e,"Service worker not supported"),n("Service worker not supported")}))),this.swRegisterPromise}registerScopedSW(e,t,n,i){const a=ln.baseLogTag+".registerScopedSW";navigator.serviceWorker.register(e).then((e=>{ut.log(2,a,"Serviceworker registered"),navigator.serviceWorker.getRegistrations().then((e=>{e.forEach((e=>{setTimeout((()=>{e.active&&e.active.scriptURL.match(t)&&(ut.log(2,a,"Serviceworker ready"),ln.registeredServiceWorker=e,Be.get()&&Be.get().forceSwUpdate&&e.update(),n(e))}),100)}))})).catch((e=>{ut.error(1,a,"Service worker register failed:",e),i(W)}))})).catch((e=>{ut.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=>{Et.getInstance().then((t=>{!t.isIncognito&&"serviceWorker"in navigator&&"PushManager"in window&&"Notification"in window&&t.isWebPushCompatible()?e(!0):e(!1)}))}))}static parsePermissionState(e){return"prompt"===e?Zt.PROMPT:"granted"===e?Zt.GRANTED:"denied"===e?Zt.DENIED:"default"===e?Zt.DISMISSED:null}showNotification(e){const t=ln.baseLogTag+".showNotification";this.registerServiceWorker().then((n=>{e?e.title?e.body?(null==e.requireInteraction&&(e.requireInteraction=!0),n.showNotification(e.title,e)):ut.error(1,t,"Notification body can not be blank"):ut.error(1,t,"Notification title can not be blank"):ut.error(1,t,"Notification object can not be blank")})).catch((e=>{ut.error(1,t,"Error registering serviceworker:",e)}))}showOverlay(){if(this.sdkSettings.optInConfig.showOverlay&&this.sdkSettings.optInConfig.type===Nt.TYPE.ONE_CLICK){const e=document.createElement("div");e.id="moe-push-div",e.style.display="none",e.className="moe-push-class",Et.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)===Et.BROWSER_NAMES.CHROME||t===Et.BROWSER_NAMES.OPERA_NEON?i=document.getElementsByClassName("moe_chrome"):t===Et.BROWSER_NAMES.FIREFOX?i=document.getElementsByClassName("moe_firefox"):t!==Et.BROWSER_NAMES.OPERA&&t!==Et.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))}}ln.baseLogTag="HTTPS-NotificationManager";const cn="Web push settings not configured on MoEngage dashboard: "+z;class dn{constructor(e,t){this.currentManager=null;var n=dn.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 ln(e):ut.error(1,n,"Web Push does not work in http mode"):(Ye()&&new ln(e),ut.warn(1,n,"Web push settings not configured. Please configure at ",z))):this.browser.name===Et.BROWSER_NAMES.SAFARI&&e.platformSettings.safari&&"safari"in window&&"pushNotification"in window.safari&&(this.currentManager=null,ut.warn(1,n,"Web push is only supported on Safari 16 and above."))}showHardAsk(){const e=dn.baseLogTag+".showHardAsk";return new Promise(((t,n)=>{this.getCurrentPermissionState().then((i=>{null!=this.currentManager?i===Zt.PROMPT?this.currentManager.showHardAsk().then((n=>{n.state===Zt.DISMISSED?(Qt.track(m),$t.broadcastToWindow({topic:x,name:U.HARD_ASK_DISMISSED}),$t.deprecatedSdkCallback("opt_in_dismissed"),sn.runCallbacks(U.HARD_ASK_DISMISSED),ut.log(1,e,"Hard ask was dismissed")):n.state===Zt.GRANTED?(Qt.track(h),$t.broadcastToWindow({topic:x,name:U.HARD_ASK_ALLOWED,data:n.subscriptionDetails}),$t.deprecatedSdkCallback("opt_in_allowed"),sn.runCallbacks(U.HARD_ASK_ALLOWED),ut.log(1,e,"Push permission was granted"),ut.customLabel(1,e,"token",n.subscriptionDetails.token)):n.state===Zt.DENIED&&(Qt.track(f),Qt.track("Web Push Opt-in Denied"),$t.broadcastToWindow({topic:x,name:U.HARD_ASK_DENIED}),$t.deprecatedSdkCallback("opt_in_blocked"),sn.runCallbacks(U.HARD_ASK_DENIED),ut.log(1,e,"Notification permission was denied")),t(n)})).catch((n=>{ut.error(1,e,"Error showing hard ask:",n),t({state:i,subscriptionDetails:null})})):(ut.log(1,e,"Not showing Hard Ask as current permission state is",i),this.getPushTokenDetails().then((n=>{ut.customLabel(1,e,"token",n.token),t({state:i,subscriptionDetails:n})})).catch((n=>{ut.warn(1,e,"Could not get push token details"),t({state:i,subscriptionDetails:null})}))):(ut.log(1,e,"MoEngage web push settings not configured. Please configure at",z),n(H))})).catch((e=>{n(e)}))}))}getCurrentPermissionState(){return null!=this.currentManager?this.currentManager.getCurrentPermissionState():Promise.reject(cn)}getPushTokenDetails(){return null!=this.currentManager?this.currentManager.getPushTokenDetails():Promise.reject(cn)}removeToken(){return null!=this.currentManager?this.currentManager.removeToken():Promise.reject(cn)}showNotification(e){var t=dn.baseLogTag+".showNotification";if(null!=this.currentManager)return this.currentManager.showNotification(e);ut.warn(1,t,cn)}}dn.baseLogTag="NotificationManager";class gn{constructor(e){this.mainDivs=[],this.config=e}showSoftAsk(){const e=gn.baseLogTag+".showSoftAsk";return new Promise(((t,n)=>{let i=this.config.optInConfig.loadTime;Et.getInstance().then((n=>{(this.config.optInConfig.type===Nt.TYPE.SELF_HANDLED||n.isSafari()&&this.config.optInConfig.type===Nt.TYPE.ONE_CLICK)&&(i=0),i&&ut.log(1,e,"Delay of",i," second(s) requested before opt-in flow"),setTimeout((()=>{!n.isWebPushCompatible()||this.config.optInConfig.type!==Nt.TYPE.TWO_STEP&&this.config.optInConfig.type!==Nt.TYPE.SELF_HANDLED?(We.set(r.SOFT_ASK_STATUS,en.NOT_SHOWN),t({showHardAsk:!0,softAskState:en.NOT_SHOWN})):this.showOptIn((()=>{ut.log(1,e,"Soft ask was shown"),We.set(r.OPT_IN_SHOWN_TIME,Date.now()),We.set(r.SOFT_ASK_STATUS,en.SHOWN),$t.broadcastToWindow({topic:x,name:U.SOFT_ASK_SHOWN}),$t.deprecatedSdkCallback("soft_ask_shown"),sn.runCallbacks(U.SOFT_ASK_SHOWN)}),(()=>{Qt.track(u),this.hideOptIn(),ut.log(1,e,"Soft ask was allowed"),We.set(r.SOFT_ASK_STATUS,en.ALLOWED),t({showHardAsk:!0,softAskState:en.ALLOWED}),$t.broadcastToWindow({topic:x,name:U.SOFT_ASK_ALLOWED}),$t.deprecatedSdkCallback("soft_ask_allowed"),sn.runCallbacks(U.SOFT_ASK_ALLOWED)}),(()=>{this.hideOptIn(),Qt.track(g),ut.log(1,e,"Soft ask was dismissed"),We.set(r.SOFT_ASK_STATUS,en.DISMISSED),t({showHardAsk:!1,softAskState:en.DISMISSED}),$t.broadcastToWindow({topic:x,name:U.SOFT_ASK_DISMISSED}),$t.deprecatedSdkCallback("soft_ask_closed"),sn.runCallbacks(U.SOFT_ASK_DISMISSED)}),(e=>{e=!!e,this.hideOptIn(),t({showHardAsk:e,softAskState:en.NOT_SHOWN})}))}),1e3*i)}))}))}showOptIn(e,t,n,i){const a=gn.baseLogTag+".showOptIn";if(this.config.optInConfig.type===Nt.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"),Et.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?(ut.error(1,a,"Error showing soft ask. Allow button id is missing"),i()):(e(),Qt.track(d),l.onclick=()=>{t()},c?c.onclick=()=>{n()}:window.moeRemoveBanner=()=>{n()})}else ut.error(1,a,"Error displaying soft ask"),i()}))}else if(this.config.optInConfig.type===Nt.TYPE.SELF_HANDLED){var r=Be.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)ut.error(1,a,"Could not find main class for the soft ask. Class name given:",r.customSoftAsk.mainClass),Et.getInstance().then((e=>{e.isWebPushCompatible()&&(ut.warn(1,a,"Proceeding to hard ask directly"),i(!0))}));else{e(),s.length<1&&(ut.warn(1,a,"Could not find any element for allow button. Class name given:",r.customSoftAsk.allowClass),ut.warn(1,a,"Docs for self-handled opt in available here - ",Y.SELF_HANDLED_DOCS)),l.length<1&&ut.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 Et.getInstance().then((e=>{e.isWebPushCompatible()?(ut.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)):(ut.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"}))}}gn.baseLogTag="SoftAskManager",(Ji=en=en||{}).SHOWN="shown",Ji.NOT_SHOWN="not shown",Ji.ALLOWED="allowed",Ji.DISMISSED="dismissed";class un{constructor(e){this.deviceToLogout=Te(e,"deviceToLogout",null)}static get(){return new un(We.get(r.GRACEFUL_DATA))}save(){We.set(r.GRACEFUL_DATA,this)}}class pn{onWindowVisibilityChange(e){pn.baseLogTag,Ie.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=>{Ie.set("isWindowActive","visible"===t),e(t)};window.addEventListener("visibilitychange",t,!1)}static beforeUnload(){pn.isBatchingEnabled&&(Kt.windowClosed=!0,zt.sendBeacon()),window.Moengage.onsite&&window.Moengage.onsite.sendDelayCampaignStats&&window.Moengage.onsite.sendDelayCampaignStats()}static removeBeforeUnloadListeners(){window.removeEventListener("beforeunload",pn.beforeUnload,!1)}static addBeforeUnloadListeners(e){e.configs.isBatchingEnabled&&(pn.isBatchingEnabled=!0),window.addEventListener("beforeunload",pn.beforeUnload,!1)}}pn.baseLogTag="WindowEventManager",pn.isBatchingEnabled=!1;var hn=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 mn="MoEngage.user";class fn{static addAttribute(e,t){const n=mn+".addUserAttribute";return new Promise(((i,a)=>{let r=!1;if("string"!=typeof e||null==e)ut.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)ut.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)ut.error(1,n,"Attribute value null"),i({error:5003,message:"Attribute value was empty"});else if("string"==typeof t&&""===t)ut.error(1,n,"Attribute value needs to be non-empty string or non-empty object"),i({error:5004,message:"Attribute value needs to be non-empty string or non-empty object"});else if(tt(t)&&M.includes(e))ut.error(1,n,`Value of '${e}' attribute cannot be an object`),i({error:5002,message:"Attribute value cannot be an object"});else if("object"==typeof t&&Array.isArray(t)&&!t.length)ut.error(1,n,"Attribute value needs to be non-empty string or non-empty object"),i({error:5006,message:"Attribute value needs to be non-empty string or non-empty object"});else if(tt(t)&&!Object.keys(t).length)ut.error(1,n,"Attribute value cannot be empty object"),i({error:5005,message:"Attribute value cannot be empty object"});else{const a=new yt(e,t),o=()=>{It.get().then((e=>{e.addAttribute(a).then((e=>{e?("id"===a.key&&ut.log(1,n,"Logging in the user with id: ",a.value),Jt.createUserAttributeEvent(a).then((e=>{ut.log(2,n,"Event to be converted to report:",e),Xt.addEvent(e),nn.collectGetParams().then((t=>{t=new Dt(Dt.REPORT_ADD_TYPE.USER_ATTRIBUTE,t,e),nn.reportAdd(t).then((()=>{r&&$i.onsite.refresh&&$i.onsite.refresh(),i(!0)}))}))}))):(ut.error(1,n,"Attribute already present/queued. Not adding again."),i({error:5005,message:"Attribute already present/queued. Not adding again."}))}))}))};"id"===e?(r=!0,It.get().then((e=>{var a=e.indexOfAttribute("id");-1<a?(r=!1,t===e.attributes[a].value?(ut.log(1,n,"User already logged in with id:",t),i(!0)):(ut.log(1,n,"Logging out previous user with id:",e.attributes[a].value),rt(!0),fn.logout(!0,t).then((()=>{o()})))):(function(){const e=mn+".refreshCards";nn.getWebSDKSettings().then((t=>{null!=t&&t.configs.isCardsModuleEnabled&&$i.cards&&(ut.log(1,e,"Fetching new Cards after login"),$i.cards.refreshCards())})).catch((t=>{ut.error(2,e,"Error Refreshing Cards:",t)}))}(),rt(!0),o())}))):o()}}))}static login(e){return fn.addAttribute("id",e)}static logout(e,t){const n=mn+".logout",i=e?{type:"forced",new_uid:t}:null;return function(){const e=un.get();null!=It.getSync()&&(e.deviceToLogout=It.getSync().deviceUuid,e.save())}(),new Promise((e=>{Qt.track(S,i).then((()=>hn(this,void 0,void 0,(function*(){ut.log(1,n,"Logging out now!"),yield zt.flushReports(),pn.removeBeforeUnloadListeners(),nn.getWebSDKSettings().then((t=>hn(this,void 0,void 0,(function*(){var n;t.isDomainLevelStorage&&Ue.remove(r.USER_DATA),Xt.clear(),yield Zi(),yield function(){return Vi(this,void 0,void 0,(function*(){const e="Moengage.disableCards",t=Be.get();try{nn.getWebSDKSettings().then((e=>Vi(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 Sn.loadModule(ne.CARDS);yield e.logout(),zi=new mt}})))).catch((t=>{ut.error(1,e,"Error in getting Web SDK Settings. This might indicate that the App is blocked.")}))}catch(t){ut.error(1,e,"Error logging out from cards module:",t)}}))}(),rt(),We.logout(),yield It.logout(),We.remove(r.GRACEFUL_DATA),nn.onDeviceAdd=new mt,yield sa(),t.configs.remoteLogTracking&&(n=Be.get(),yield nn.getAndPersistWebSettings(n)),e(!0)})))).catch((t=>{ut.error(1,n,"Error in getting Web SDK Settings. This might indicate that the App is blocked."),e(!1)}))}))))}))}static updateUniqueId(e){const t=mn+".updateUniqueId";return new Promise((n=>{It.get().then((i=>{var a=i.indexOfAttribute(A),r=i.indexOfAttribute("oldUniqueIds");if(!(-1<a))return ut.log(2,t,"Logging in as no id found"),fn.login(e);var o=i.attributes[a].value;e!==o?(ut.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 yt("oldUniqueIds",[o]))),i.save().then((()=>{fn.login(e).then((()=>{n(!0)}))}))):(ut.warn(1,t,"New id and old id are the same. Not updating the id."),n(!0))}))}))}static getAttributes(){const e=It.getSync().attributes,t={};return e.map((e=>{t[e.key]=e.value})),t}}class vn{constructor(e,t){this.notificationManager=null,this.softAskManager=null,vn.baseLogTag,this.sdkSettings=e,this.browser=t,this.softAskManager=new gn(this.sdkSettings),this.notificationManager=new dn(this.sdkSettings,t)}callWebPush(){const e=vn.baseLogTag+".callWebPush";this.isWebPushEnabled()&&this.notificationManager.getCurrentPermissionState().then((t=>{return n=this,a=function*(){var n=(n=t)=>{It.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((()=>{Qt.track(E,{[me]:!1}),Qt.track(b),n===Zt.DENIED?ut.log(1,e,"Not asking for permission as current state is denied."):(We.remove(r.OPT_IN_SHOWN_TIME),this.startPushSubscription())}))}))}))};const i=yield Et.getInstance();var a=We.get(r.PUSH_TOKEN),o=t===Zt.DENIED&&!this.sdkSettings.isDomainLevelStorage;null==a&&t!==Zt.DENIED?this.startPushSubscription():null!=a&&(o||i.isSafari()&&t===Zt.PROMPT)?(ut.log(1,e,"User has removed the permission"),ut.image(1,V),i.isSafari()&&t===Zt.PROMPT&&(We.set(he,!0),t=Zt.DENIED),n(t)):o?ut.warn(1,e,"Not proceeding with push subscription as current state is denied"):null!=a&&t===Zt.GRANTED?this.browser.name===Et.BROWSER_NAMES.CHROME?Ve(this.sdkSettings.platformSettings,this.browser)?this.startPushSubscription():ut.warn(1,e,"Subscription mode is not VAPID type. Cannot subscribe to web push."):(this.startPushSubscription(),this.notificationManager.getPushTokenDetails().then((t=>{ut.customLabel(1,e,"token",t.token)}))):this.sdkSettings.isDomainLevelStorage?"granted"===Ue.get(r.HARD_ASK_STATUS)?(a=null===(a=Ue.get(r.SUBSCRIPTION_DETAILS))||void 0===a?void 0:a.domain)&&a===window.location.origin?(ut.log(1,e,"It seems that the user has unsubscribed manually. Starting push subscription.."),n(t)):ut.log(1,e,"Not showing opt-in as user subscribed to sub-domain"):this.startPushSubscription():n()},new(i=(i=void 0)||Promise)((function(e,t){function r(e){try{s(a.next(e))}catch(e){t(e)}}function o(e){try{s(a.throw(e))}catch(e){t(e)}}function s(t){var n;t.done?e(t.value):((n=t.value)instanceof i?n:new i((function(e){e(n)}))).then(r,o)}s((a=a.apply(n,[])).next())}));var n,i,a})).catch((t=>{ut.error(1,e,"Error in getting current state:",t)}))}startPushSubscription(){const e=vn.baseLogTag+".startPushSubscription",t=()=>{We.set(r.HARD_ASK_STATUS,Zt.PROMPT);const t=We.get(r.PUSH_TOKEN);this.notificationManager.showHardAsk().then((n=>{We.set(r.HARD_ASK_STATUS,n.state),n.state===Zt.GRANTED?null!=n.subscriptionDetails.token?(We.set(r.PUSH_TOKEN,n.subscriptionDetails.token),n.subscriptionDetails.domain=window.location.origin,We.set(r.SUBSCRIPTION_DETAILS,n.subscriptionDetails),n.subscriptionDetails.token&&t!==n.subscriptionDetails.token&&nn.deviceAdd().then((()=>{ut.image(1,"https://media.giphy.com/media/90F8aUepslB84/giphy.gif"),It.getSync().subscribedToOldSdk?ut.remoteLogTracking(1,"info",e,"User subscribed from older sdk, hence not sending subscription event"):(null!=t?fn.addAttribute("Web Migrated User","true"):fn.addAttribute("Web Subscription URL",location.href),Qt.track(y,{MOE_WEB_PUSH_TOKEN:n.subscriptionDetails.token,migrated_user:!!window.location.search.includes("moe_migration=true")||void 0}))})),this.sdkSettings.isDomainLevelStorage&&(Ue.set(r.SUBSCRIPTION_DETAILS,{domain:n.subscriptionDetails.domain,token:n.subscriptionDetails.token,endpoint:n.subscriptionDetails.endpoint,keys:n.subscriptionDetails.keys}),Ue.set(r.PUSH_TOKEN,n.subscriptionDetails.token))):(ut.error(1,e,"Push token was received as null."),ut.error(1,e,"Please contact MoEngage support if this troubleshooting does not solve the issue.")):n.state===Zt.DENIED&&ut.image(1,V)})).catch((t=>{ut.warn(1,e,t)}))},n=()=>{this.softAskManager?this.softAskManager.showSoftAsk().then((e=>{e.showHardAsk&&t()})):ut.log(1,e,"SoftAskManager not set.")};this.notificationManager.getCurrentPermissionState().then((i=>{if(i===Zt.GRANTED)this.sdkSettings.optInConfig.type!==Nt.TYPE.ONE_CLICK&&ut.remoteLogTracking(1,"info",e,"Skipping soft ask as browser permission is set to allow all notifications"),t();else{var a=parseInt(We.get(r.OPT_IN_SHOWN_TIME));if(We.get(r.SOFT_ASK_STATUS),We.get(r.HARD_ASK_STATUS),i=(Date.now()-a)/36e5,!a||i>this.sdkSettings.optInConfig.reappearTime)if(this.browser.name===Et.BROWSER_NAMES.SAFARI&&this.sdkSettings.optInConfig.type===Nt.TYPE.ONE_CLICK){ut.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)"),ut.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."),ut.log(1,e,"You can clear localstorage to get opt-in again.")}}}))}isWebPushEnabled(){return!this.browser.isIncognito&&0<=vn.SUPPORTED_BROWSERS.indexOf(this.browser.name)&&navigator.serviceWorker&&"PushManager"in window&&"Notification"in window}getPermissionState(){return this.notificationManager.getCurrentPermissionState()}showNotification(e){this.notificationManager&&this.notificationManager.showNotification(e)}trackPushOptedDeviceAttribute(){return new Promise((e=>{var t=We.get(r.OPTED_STATUS_TRACK_TIME);t&&864e5<Date.now()-t&&(t=We.get(r.PUSH_TOKEN),Qt.track(E,{[me]:!!t}),We.set(r.OPTED_STATUS_TRACK_TIME,Date.now())),e(null)}))}}vn.baseLogTag="WebPushManager",vn.SUPPORTED_BROWSERS=[Et.BROWSER_NAMES.CHROME,Et.BROWSER_NAMES.FIREFOX,Et.BROWSER_NAMES.OPERA,Et.BROWSER_NAMES.SAFARI,Et.BROWSER_NAMES.EDGE];class Sn{static loadModule(e){var t=Sn.baseLogTag+".loadModule";return null!=Sn.loadPromises[e.name]||(ut.log(1,t,"Starting to fetch module: ",e.name),Sn.loadPromises[e.name]=new Promise(((t,n)=>{Sn.addScript(e.src,(()=>{var n=new(0,window[ne[e.name].windowLocation])(n=Be.get());t(n)}))}))),Sn.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)}}Sn.baseLogTag="ModuleManager",Sn.loadPromises={};var En=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 yn{static initialize(){return En(this,void 0,void 0,(function*(){var e;return null==yn.ready&&(yn.serviceMetaStore=_e.createInstance({driver:[_e.INDEXEDDB,_e.WEBSQL,_e.LOCALSTORAGE],name:te.DATABASE_NAME,storeName:te.STORES.SERVICE_META.NAME}),yn.campaingsMetaStore=_e.createInstance({driver:[_e.INDEXEDDB,_e.WEBSQL,_e.LOCALSTORAGE],name:te.DATABASE_NAME,storeName:te.STORES.CAMPAIGNS_META.NAME}),yn.pendingSecondaryEvents=_e.createInstance({driver:[_e.INDEXEDDB,_e.WEBSQL,_e.LOCALSTORAGE],name:te.DATABASE_NAME,storeName:te.STORES.PENDING_SECONDARY_EVENTS.NAME}),yn.pendingTimerCampaigns=_e.createInstance({driver:[_e.INDEXEDDB,_e.WEBSQL,_e.LOCALSTORAGE],name:te.DATABASE_NAME,storeName:te.STORES.PENDING_TIMER_CAMPAIGNS.NAME}),yn.triggeringPrimaryEvents=_e.createInstance({driver:[_e.INDEXEDDB,_e.WEBSQL,_e.LOCALSTORAGE],name:te.DATABASE_NAME,storeName:te.STORES.TRIGGERING_PRIMARY_EVENTS.NAME}),yn.campaingsTagsStore=_e.createInstance({driver:[_e.INDEXEDDB,_e.WEBSQL,_e.LOCALSTORAGE],name:te.DATABASE_NAME,storeName:te.STORES.CAMPAIGNS_TAGS.NAME}),yn.campaingsStatsStore=_e.createInstance({driver:[_e.INDEXEDDB,_e.WEBSQL,_e.LOCALSTORAGE],name:te.DATABASE_NAME,storeName:te.STORES.CAMPAIGNS_STATS.NAME}),yn.testCampaignStore=_e.createInstance({driver:[_e.INDEXEDDB,_e.WEBSQL,_e.LOCALSTORAGE],name:te.DATABASE_NAME,storeName:te.STORES.CAMPAIGNS_STATS.NAME}),yn.exitIntentCampaignStore=_e.createInstance({driver:[_e.INDEXEDDB,_e.WEBSQL,_e.LOCALSTORAGE],name:te.DATABASE_NAME,storeName:te.STORES.EXIT_INTENT_CAMPAIGN_STORE.NAME}),e=[yn.serviceMetaStore.ready(),yn.campaingsMetaStore.ready(),yn.pendingSecondaryEvents.ready(),yn.pendingTimerCampaigns.ready(),yn.triggeringPrimaryEvents.ready(),yn.campaingsTagsStore.ready(),yn.campaingsStatsStore.ready(),yn.testCampaignStore.ready(),yn.exitIntentCampaignStore.ready()],yn.ready=Promise.all(e)),yn.ready}))}static clear(){return En(this,void 0,void 0,(function*(){var e=yn.baseLogTag+".clear";try{yield yn.initialize(),yield Promise.all([yn.serviceMetaStore.clear(),yn.campaingsMetaStore.clear(),yn.campaingsTagsStore.clear(),yn.campaingsStatsStore.clear(),yn.testCampaignStore.clear(),yn.exitIntentCampaignStore.clear(),yn.pendingSecondaryEvents.clear(),yn.pendingTimerCampaigns.clear(),yn.triggeringPrimaryEvents.clear()]);var t=[yn.serviceMetaStore.ready(),yn.campaingsMetaStore.ready(),yn.campaingsTagsStore.ready(),yn.campaingsStatsStore.ready(),yn.testCampaignStore.ready(),yn.exitIntentCampaignStore.ready(),yn.pendingSecondaryEvents.clear(),yn.pendingTimerCampaigns.clear(),yn.triggeringPrimaryEvents.clear()];yn.ready=Promise.all(t)}catch(t){ut.error(1,e,"Error clearing onsite stores:",t)}return yn.ready}))}}yn.baseLogTag="MOE_ONSITE_STORES";var bn,_n,Tn,In,An,wn=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 Dn=(e,t,n)=>null==e.campaignId?()=>{}:()=>(yn.campaingsStatsStore.getItem(e.campaignId).then((t=>{t=null!=t?Object.assign(Object.assign({},t),{clicks:Te(t,"clicks",0)+1}):{clicks:1},yn.campaingsStatsStore.setItem(e.campaignId,t)})),null==n&&(n={}),Rn().track_event(te.EVENT_NAMES[t].CLICK,Object.assign(Object.assign({campaign_id:e.campaignId,campaign_name:e.campaignName,type:te.EVENT_NAMES[t].TYPE},n),e.campaignContext))),On=(e,t,n=!1)=>null==e.campaignId?()=>{}:()=>{if(yn.initialize().then((()=>{yn.campaingsStatsStore.getItem(e.campaignId).then((t=>{t=null!=t?Object.assign(Object.assign({},t),{impressions:Te(t,"impressions",0)+1,lastImpression:new Date}):{impressions:1,lastImpression:new Date},yn.campaingsStatsStore.setItem(e.campaignId,t)}))})),!n)return Rn().track_event(te.EVENT_NAMES[t].IMPRESSION,Object.assign({campaign_id:e.campaignId,campaign_name:e.campaignName,type:te.EVENT_NAMES[t].TYPE,templateType:e.templateType},e.campaignContext))},Cn=(e,t,n)=>{n=n?te.EVENT_NAMES[t].AUTO_DISMIS:te.EVENT_NAMES[t].DISMISS,Rn().track_event(n,Object.assign({campaign_id:e.campaignId,campaign_name:e.campaignName,type:te.EVENT_NAMES[t].TYPE},e.campaignContext))},Pn=(e,t)=>{Rn().track_event(te.EVENT_NAMES[t].DELIVERED,Object.assign({campaign_id:e.campaignId,campaign_name:e.campaignName,type:te.EVENT_NAMES[t].TYPE},e.campaignContext))},Rn=()=>{var e=window.moengage_object||"Moengage";return window[e]};class Nn{static isValid(e,t){return!Nn.isCampaignExpired(e)&&Nn.isCampaignActive(e)&&Nn.isUserInCampaignSegment(e)&&Nn.isCampaignWithinFC(e,t)}static isCampaignExpired(e){return(new Date).getTime()>new Date(e.expiryTime).getTime()}static isValidMessagingCampaign(e,t,n,i,a){return Nn.canCampaignBeRenderedOverExisting(e,a.length)&&Nn.hasCampaignClearedSelfDelay(e,t)&&Nn.hasCampaignClearedGlobalDelay(e,n,i)}static isCampaignActive(e){var t=Nn.baseLogTag+".isValid";return e.status===Tn.ACTIVE||(ut.warn(1,t,`Campaign ${e.campaignId} : Status is `+e.status),!1)}static isUserInCampaignSegment(e){var t=Nn.baseLogTag+".isValid";return!!e.userInSegment||(ut.warn(1,t,`Campaign ${e.campaignId} : User is not in segment`),!1)}static isCampaignWithinFC(e,t){var n=Nn.baseLogTag+".isValid";if([An.SELF_HANDLED].indexOf(e.templateType)<0){var i=Te(e,"delivery.fc_meta.count",0);if(0<i){var a=Te(t,"impressions",0);if(null!=t)return!(i<=a&&(ut.warn(1,n,`Campaign ${e.campaignId} : FC reached. ${t.impressions} times shown`),1))}}return!0}static hasCampaignClearedGlobalDelay(e,t,n){var i=Nn.baseLogTag+".isValid",a=Te(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 ut.remoteLogTracking(1,"info",i,`Can't render ${e.campaignId} as last global campaign was rendered ${r} seconds ago.`),!1}}}catch(e){return ut.error(1,i,"Error checking global delay:",e),!1}return!0}static hasCampaignClearedSelfDelay(e,t){var n=Nn.baseLogTag+".hasCampaignClearedSelfDelay",i=Te(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<=Te(e,"delivery.fc_meta.delay",0))return ut.warn(1,n,`Can't render ${e.campaignId} as it was rendered ${r} seconds ago.`),!1}}catch(t){return ut.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=Nn.baseLogTag+".canCampaignBeRenderedOverExisting";return!(0<t&&!e.display.config.showOverOtherCampaigns&&(ut.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}}Nn.baseLogTag="CampaignUtils";const Ln=e=>wn(void 0,void 0,void 0,(function*(){var t=e.map((e=>yn.campaingsStatsStore.getItem(e.campaignId)));let n;try{n=yield Promise.all(t);const i=e.filter(((e,t)=>Nn.isValid(e,n[t])));return i.sort(Nn.comparator)}catch(t){return ut.error(1,"filterAndSortCampaigns","Error filtering and sorting campaigns: ",t),[]}}));class Mn{}Mn.REMOVE_TRAIL_CHARS=/[^\w\s]+$/gi;const kn=(e,t)=>{const n=Te(e,"triggerData.primary_condition.included_filters",null);return(null==n?void 0:n.filter_operator)===In.OR&&-1<(null==n?void 0:n.filters.findIndex((e=>e.action_name===t)))},xn=e=>wn(void 0,void 0,void 0,(function*(){var t=yield yn.exitIntentCampaignStore.getItem(e.campaignId);if(t)return t.error?t:(e.onsitePayload=t,ut.log(1,"getPrefetchedCampaign","Prefetched exit intent campaign found: "+e.campaignId),e)})),Bn=e=>wn(void 0,void 0,void 0,(function*(){try{return yield yn.campaingsMetaStore.getItem(e)}catch(e){return ut.error(2,"getCampaignById","Error getting campaign from store: ",e),null}})),Un=()=>new Promise((e=>{setTimeout((()=>wn(void 0,void 0,void 0,(function*(){const t=[];yield yn.campaingsMetaStore.iterate((e=>{t.push(e)})),e(t)}))),0)})),Fn=e=>null===(e=Te(e,"triggerData.secondary_condition.included_filters.filters"))||void 0===e?void 0:e.length,Wn=e=>"moe-onsite-campaign-"+e;class Hn{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===bn.STRING&&typeof n===bn.STRING&&(n=this.removeSpecialChars(n),i=this.removeSpecialChars(i)),t.key===this.filter.name&&(this.dataType!==bn.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(Mn.REMOVE_TRAIL_CHARS,"")}}(Ji=bn=bn||{}).BOOL="bool",Ji.STRING="string",Ji.DATE="datetime",Ji.NUMBER="double",Ji.LONG="long",Ji.ARRAY_BOOL="array_bool",Ji.ARRAY_NUMBER="array_double",Ji.ARRAY_STRING="array_string",Ji.ARRAY_DATETIME="array_datetime",Ji.OBJECT="object",(Ji=_n=_n||{}).ALLOF="all_of",Ji.ANYOFF="any_of";const Kn=["is","exists","contains","startsWith","endsWith","in","containsInTheFollowing","startsWithInTheFollowing","endsWithInTheFollowing"];class Gn extends Hn{constructor(e,t){super(bn.STRING,Kn,e,t)}evaluate(){Gn.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&&Ze(n.value))switch(this.filter.operator){case"is":e=this.checkEq();break;case"exists":e=this.checkExists();break;case"contains":case"containsInTheFollowing":e=this.checkContains(n);break;case"startsWith":case"startsWithInTheFollowing":e=this.checkStartsWith(n);break;case"endsWith":case"endsWithInTheFollowing":e=this.checkEndsWith(n);break;case"in":e=this.checkIn(n)}return this.filter.negate?!e:e}checkContains(e){var t=t=>this.filter.case_sensitive?0<=e.value.indexOf(t):0<=e.value.toLowerCase().indexOf(t.toLowerCase());return Array.isArray(this.filter.value)?this.checkInTheFollowing(t).includes(!0):t(this.filter.value)}checkStartsWith(e){var t=t=>{var n=(e,t)=>e.substr(0,t.length)===t;return this.filter.case_sensitive?n(e.value,t):n(e.value.toLowerCase(),t.toLowerCase())};return Array.isArray(this.filter.value)?this.checkInTheFollowing(t).includes(!0):t(this.filter.value)}checkEndsWith(e){var t=t=>{var n=(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 n(e.value,t);const i=this.removeSpecialChars(e.value),a=this.removeSpecialChars(t);return n(i.toLowerCase(),a.toLowerCase())};return Array.isArray(this.filter.value)?this.checkInTheFollowing(t).includes(!0):t(this.filter.value)}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}checkInTheFollowing(e){return this.filter.value.map((t=>e(t)))}}Gn.baseLogTag="StringDataType";const Vn=["is","exists"];class jn extends Hn{constructor(e,t){super(bn.BOOL,Vn,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}}jn.baseLogTag="BooleanDataType";const Yn=["is","exists","greaterThan","lessThan","between","in"];class zn extends Hn{constructor(e,t){super(bn.NUMBER,Yn,e,t)}evaluate(){zn.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)}}zn.baseLogTag="NumberDataType";const qn=["exists","on","between","before","after","inTheLast","inTheNext","today"];class $n extends Hn{constructor(e,t){!et(t.value)&&Ze(t.value)&&(t.value=new Date(t.value.split("Z").join(""))),!et(t.value2)&&Ze(t.value2)&&null!=t.value2&&(t.value2=new Date(t.value2.split("Z").join(""))),!et(t.value1)&&Ze(t.value1)&&null!=t.value1&&(t.value1=new Date(t.value1.split("Z").join(""))),super(bn.DATE,qn,e,t)}evaluate(){$n.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===se?((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===se?(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)}}$n.baseLogTag="DateTimeDataType";const Jn=["is","exists","contains","startsWith","endsWith","in","lessThan","greaterThan","between","inTheLast","inTheNext","after","before","on","today"];class Xn extends Hn{constructor(e,t){super(t.data_type,Jn,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===_n.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 yt(e,t),new Jt(this.event.name,[t])}getDataType(e){let t;switch(this.filter.data_type){case bn.ARRAY_BOOL:t=new jn(e,this.filter);break;case bn.ARRAY_DATETIME:t=new $n(e,this.filter);break;case bn.ARRAY_NUMBER:t=new zn(e,this.filter);break;case bn.ARRAY_STRING:t=new Gn(e,this.filter)}return t}}class Qn{constructor(e,t){this.event=e,this.filter=t}evaluate(){let e;var t=this.event.attributes.filter((e=>e.key===this.filter.name));const n=0<t.length?t[0]:null;if(!n)return!1;var i=this.filter.filters.map((e=>{if("exists"===e.operator){var t=(null==e?void 0:e.name)in(null==n?void 0:n.value);return e.negate?!t:t}return(null==e?void 0:e.name)in(null==n?void 0:n.value)&&(t=new yt(e.name,n.value[e.name]),t=new Jt(e.name,[t]),Zn.doesEventMatchFilters(t,e))})),a=this.filter.filter_operator;e=(null==i?void 0:i[0])||!1;for(let t=1;t<i.length;t++)if(a===In.AND){if(e=e&&i[t],!1===e)break}else if(a===In.OR&&(e=e||i[t],!0===e))break;return e}}class Zn{static doesEventMatchFilters(e,t){Zn.baseLogTag;let n=!1,i=null;switch(t.data_type){case bn.BOOL:i=new jn(e,t),i.validate()&&(n=i.evaluate());break;case bn.STRING:i=new Gn(e,t),i.validate()&&(n=i.evaluate());break;case bn.NUMBER:case bn.LONG:i=new zn(e,t),i.validate()&&(n=i.evaluate());break;case bn.DATE:i=new $n(e,t),i.validate()&&(n=i.evaluate());break;case bn.OBJECT:i=new Qn(e,t),n=i.evaluate();break;case bn.ARRAY_STRING:case bn.ARRAY_DATETIME:case bn.ARRAY_BOOL:case bn.ARRAY_NUMBER:i=new Xn(e,t),i.validate()&&(n=i.evaluate())}return n}static doesValueMatchFilter(e,t){return e=new yt(t.name,e),e=new Jt("Sample event",[e]),Zn.doesEventMatchFilters(e,t)}}Zn.baseLogTag="TriggerEvaluator";class ei{constructor(e){var t=ei.baseLogTag+".constructor";this.campaignId=Te(e,"campaign_id",null),this.campaignName=Te(e,"campaign_name",null),this.templateType=Te(e,"template_type",null),this.campaignContext=Te(e,"campaign_context",null);var n=Te(e,"status",null);const i=[Tn.ACTIVE,Tn.EXPIRED,Tn.PAUSED];i.indexOf(n)<0?this.status=Tn.ACTIVE:this.status=i[i.indexOf(n)],this.tag=Te(e,"tag",null),this.triggerData=null,ti.validate(Te(e,"trigger"))?this.triggerData=new ti(Te(e,"trigger")):ut.log(2,t,"Rejecting trigger data for :",e),this.expiryTime=Xe(Te(e,"expiry_time")+"Z"),this.updatedTime=Xe(Te(e,"updated_time")+"Z"),this.delivery=new si(Te(e,"delivery")),this.userInSegment=Te(e,"user_in_segment",!0),n=Te(e,"display",this.display=null),t=Te(e,"display_filter",null),this.templateType!==An.SELF_HANDLED&&(null!=t?this.display=new di({rules:{uri_filters:t}},this.templateType):null!=n&&(this.display=new di(n,this.templateType))),this.stats={},this.onsitePayload=null,this.editorVersion=Te(e,"editor_version",null)}static isValidMetaJSON(e){ei.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=Te(t,`triggerData.${n}_condition.included_filters`,null);return null==i?void 0:i.filters.filter((t=>t.action_name===e||t.action_name===_&&"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)||In.AND}static isTriggered(e,t,n,i){let a=!0;if(0<(null==t?void 0:t.length)){let o;o=i||ei.getFilterOperator(n);var r=t.map((t=>Zn.doesEventMatchFilters(e,t)));a=r[0]||!1;for(let e=1;e<r.length;e++)if(o===In.AND){if(a=a&&r[e],!1===a)break}else if(o===In.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=ei.getFilters(i);if(ei.areFiltersAbsent(i)||ei.isTriggered(e,a,i))return!0}return!1}static getURLFilterResult(e){var t=new Jt(I,[]);const n=ei.getTriggerEvent(t.name,e,"url");if(n){var i=n.find((e=>e.action_name===I));return e=ei.getFilters(i),ei.isTriggered(t,e,i)}return!0}}ei.baseLogTag="OnsiteCampaignMeta";class ti{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,ii.validate(e.primary_condition)?this.primary_condition=new ii(e.primary_condition):this.primary_condition=null,ii.validate(e.secondary_condition)?this.secondary_condition=new ii(e.secondary_condition):this.secondary_condition=null,ii.validate(e.url_condition)?this.url_condition=new ii(e.url_condition):this.url_condition=null,this.description=e.description,null!=e.trigger_delay?this.trigger_delay=new ni(e.trigger_delay):this.trigger_delay=null}static validate(e){let t=!1;return["primary_condition"].forEach((n=>{null!=Te(e,n,null)&&(t=!0)})),t}}class ni{constructor(e){if(this.delay=Te(e,"delay",0),this.unit=Te(e,"unit","seconds"),this.delay_type=Te(e,"delay_type",""),this.attribute=Te(e,"attribute",""),Te(e,"delay",null)&&Te(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 ii{constructor(e){this.included_filters=new ai(Te(e,"included_filters",null)),this.excluded_filters=new ai(Te(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 ai{constructor(e){this.filter_operator=Te(e,"filter_operator",In.AND),this.filters=null===(e=Te(e,"filters",[]))||void 0===e?void 0:e.map((e=>new ri(e)))}}class ri{constructor(e){const t=Te(e,"action_name",null);"string"==typeof t&&(t.includes(".")?this.action_name=ze(t):this.action_name=t);var n=Te(e,"executed",null);"boolean"==typeof n&&(this.executed=n),this.filter_type=Te(e,"filter_type",null),n=Te(e,"attributes",null),oi.validateJson(n)&&(this.attributes=new oi(n)),"nested_filters"===this.filter_type&&(this.filters=new ai(e))}}class oi{constructor(e){this.filters=[],this.filterOperator=Te(e,"filter_operator",In.AND),this.filters=Te(e,"filters",[]),this.filters.length&&this.filters.forEach((e=>{var t;null!==(t=null==e?void 0:e.name)&&void 0!==t&&t.includes(".")&&(e.name=ze(e.name))}))}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}}(Ji=Tn=Tn||{}).ACTIVE="ACTIVE",Ji.PAUSED="PAUSED",Ji.EXPIRED="EXPIRED",(Ji=In=In||{}).AND="and",Ji.OR="or";class si{constructor(e){this.priority=Te(e,"priority",0),this.dismiss_interval=Te(e,"dismiss_interval",0),this.fc_meta=new li(Te(e,"fc_meta",null))}}class li{constructor(e){this.count=0,this.delay=0,this.ignore_global_delay=!1,null!=e&&(this.count=Te(e,"count",0),this.delay=Te(e,"delay",0),this.ignore_global_delay=Te(e,"ignore_global_delay",!1))}}class ci{constructor(e){this.aggregations=[],this.filters=[],this.aggregations=Te(e,"aggregations",[]),this.filter_operator=Te(e,"filter_operator",In.AND),this.filters=Te(e,"filters",[])}}class di{constructor(e,t){this.config={blocking:Te(e,"config.blocking",di.getDefaultValue("blocking",t)),pushPage:Te(e,"config.push_page",di.getDefaultValue("push_page",t)),sticky:Te(e,"config.sticky",di.getDefaultValue("sticky",t)),scrollable:Te(e,"config.scrollable",di.getDefaultValue("scrollable",t)),showOverOtherCampaigns:Te(e,"config.show_over_campaigns",di.getDefaultValue("show_over_campaigns",t))},this.rules={uriFilters:new ci(Te(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]}}(Ji=An=An||{}).SELF_HANDLED="SELF_HANDLED",Ji.POP_UP="POP_UP",Ji.BANNER="BANNER";class gi{constructor(e,t){this.channel=e,this.target=t}sendMessage(e,t){return new Promise(((n,i)=>{var a={id:(0,ft.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){gi.pendingPromises[e.id]={resolve:t,reject:n},window.addEventListener("message",(e=>{e.data&&Te(e.data,"channel",null)===this.channel&&null!=gi.pendingPromises[e.data.id]&&(gi.pendingPromises[e.data.id].resolve(e.data),delete gi.pendingPromises[e.data.id])}))}}gi.pendingPromises={};class ui{constructor(e){this.draftId=Te(e,"draft_id",null),this.draftType=Te(e,"draft_type",null),this.templateType=Te(e,"template_type",null),this.action=Te(e,"action",null);var t=Te(e,"campaign_meta",{});this.locale=Te(e,"locale",null),this.variation=Te(e,"variation",null),this.displaySettings=new di({config:t.config},this.templateType)}static isValidRawJson(e){var{draft_id:t,draft_tag:n,draft_type:e}=e;return e===te.DRAFT_CAMPAIGN_TPYES.WEB_PERSONALIZATON?null!=t&&null!=n:null!=t}}class pi{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=te.WEB_HELPER_IFRAME_URL,document.body.appendChild(t),t.addEventListener("load",(()=>{this.helper=new gi(te.IFRAME_CHANNEL,t),e(t)}))}))),this.iFramePromise}getDraftCampaignInfo(){return e=this,n=function*(){var e="IframeHelper.getDraftCampaignInfo";try{ut.log(1,e,"Loading helper frame"),yield this.getIframe(),ut.log(1,e,"Helper frame loaded");var t=yield this.helper.sendMessage(te.IFRAME_TOPICS.COOKIE_STORAGE,{TYPE:"GET",KEY:te.COOKIE_STORAGE.TEST_DRAFT_ID});ut.log(1,e,"Data from iframe: ",t);var n=t.message;ut.log(1,e,"Raw test campaign",n);let i=null;return null!=n&&(ui.isValidRawJson(n)?i=new ui(n):ut.error(1,e,"Data is not a valid test campaign")),i}catch(e){return null}},new(t=(t=void 0)||Promise)((function(i,a){function r(e){try{s(n.next(e))}catch(e){a(e)}}function o(e){try{s(n.throw(e))}catch(e){a(e)}}function s(e){var n;e.done?i(e.value):((n=e.value)instanceof t?n:new t((function(e){e(n)}))).then(r,o)}s((n=n.apply(e,[])).next())}));var e,t,n}}class hi{constructor(e){this.templateType=Te(e,"template_type",null),this.payloadType=Te(e,"payload_type",null),this.payload=Te(e,"payload",null),this.position=Te(e,"position",null),this.campaignContext=Te(e,"campaign_context",null),this.editorVersion=Te(e,"editor_version",null),this.htmlJsonPayload=JSON.parse(Te(e,"html_json_payload",null)),this.updatedTime=Xe(Te(e,"updated_time")+"Z")}}var mi=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 fi{constructor(e){this.appId=e.appId,this.store=_e.createInstance({driver:[_e.INDEXEDDB,_e.WEBSQL,_e.LOCALSTORAGE],name:te.DATABASE_NAME,storeName:te.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 vt;var n=at(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 mi(this,void 0,void 0,(function*(){var e=fi.baseLogTag+".getCampaignsMeta";try{var t=yield this.getRequestOptions();const e=yield this.store.getItem(te.STORES.SERVICE_META.KEYS.LAST_META_CALL_TIME);var n=yield ht.post(this.host+te.API.META,Object.assign(Object.assign({},t),{postData: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(te.STORES.SERVICE_META.KEYS.LAST_META_CALL_TIME,new Date),this.store.setItem(te.STORES.SERVICE_META.KEYS.UNIQUE_ID,t.queryParams.unique_id);const i=JSON.parse(n.responseText),a=[];return i.campaigns.forEach((e=>{ei.isValidMetaJSON(e)&&a.push(new ei(e))})),{campaignsMeta:a,globalDelayBetweenInapps:Te(i,"min_delay_btw_inapps",0)}}catch(t){throw ut.error(1,e,"Error getting meta for inapp: ",t),new Error("Could not get meta payload")}}))}getCampaignPayload(e,t){return mi(this,void 0,void 0,(function*(){var n=fi.baseLogTag+".getCampaignPayload";let i;try{const n={contexts:["string"],campaign_context:e.campaignContext,user_session_attributes:this.getUserSessionAttributes()};if(t){const a={};for(let e=0;e<t.attributes.length;e++)a[t.attributes[e].key]=t.attributes[e].value;n.event={name:t.name,attributes:a,time:(new Date).toISOString()},i=yield ht.post(this.host+te.API.CAMPAIGN_PAYLOAD+e.campaignId,yield this.getRequestOptions(n))}else i=yield ht.post(this.host+te.API.CAMPAIGN_PAYLOAD+e.campaignId,yield this.getRequestOptions(n));return i=JSON.parse(i.responseText),i.code===te.GCG_ERROR_CODE&&(i={payload:i}),new hi(i)}catch(i){if(ut.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 mi(this,void 0,void 0,(function*(){var n=fi.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 ht.post(this.host+te.API.CAMPAIGNS_PAYLOAD,this.getRequestOptions(a))}else i=yield ht.post(this.host+te.API.CAMPAIGNS_PAYLOAD,this.getRequestOptions());const n=[];return JSON.parse(i.responseText).forEach((e=>{n.push(new hi(e))})),n}catch(i){throw ut.error(1,n,"Error geting payload",i),new Error("Could not get payload for "+e)}}))}getDraftCampaign(e){return mi(this,void 0,void 0,(function*(){var t=fi.baseLogTag+".getDraftCampaign";try{const t=yield this.getRequestOptions();t.queryParams=Object.assign({},t.queryParams,{locale:e.locale,variation:e.variation});var n=yield ht.post(this.host+te.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 hi(i)}catch(n){return ut.error(1,t,"Error geting test campaign payload",n),null}}))}getRequestOptions(e={}){const t=Qe();return nn.getWebSDKSettings().then((n=>{var i=We.get(r.USER_DATA);let a;const{deviceUuid:o,attributes:s}=i;if(s.map((e=>{e.key===A&&(a=null===(e=null==e?void 0:e.value)||void 0===e?void 0:e.toString())})),!o)throw new Error("device_unique_id not found in localStorage.");var l=qe()?"mweb":"web";return i=Je(),{headers:{"Content-Type":"application/json","MOE-APPKEY":this.appId},queryParams:Object.assign({sdk_ver:t.getSdkVersion(),unique_id:o,os:l},i),postData:Object.assign(Object.assign({},e),{uid:a})}})).catch((e=>{throw new Error("Error in getting Web SDK Settings. This might indicate that the App is blocked.")}))}sendDeliveryFunnelStats(e,t){return mi(this,void 0,void 0,(function*(){const n=fi.baseLogTag+".sendDeliveryFunnelStats";try{var i=yield this.getRequestOptions(null);return ht.post(this.host+te.API.STATS,Object.assign(Object.assign({},i),{headers:Object.assign(Object.assign({},i.headers),{"MOE-INAPP-BATCH-ID":t}),postData:Object.assign(Object.assign({},i.postData),{deliveryStats:e})})).then((()=>{ut.log(1,n,"Delivery Funnel stats sent to Moengage: ",e)})).catch((e=>{ut.warn(1,n,"Error sending campaign stats: ",e)}))}catch(i){ut.warn(1,n,"Error sending campaign stats: ",i)}}))}sendBeacon(e,t){this.getRequestOptions().then((t=>{var n=this.host+te.API.STATS;t.queryParams.app_id=t.headers["MOE-APPKEY"],delete t.queryParams.uid,n=ot(n,t.queryParams),ut.log(1,"OnsiteApi.sendBeacon","[sendBeacon] payload: "+JSON.stringify(e)),t=new Blob([JSON.stringify(e)],{type:"text/plain;charset=UTF-8"}),navigator.sendBeacon(n,t)}))}}fi.baseLogTag="OnsiteApi";class vi{constructor(){this.isExitIntentShown=!1,this.isPopStateEventBound=!1}onScroll(e){const t=vi.baseLogTag+".onScroll";null==e&&(e=()=>{});var n=vi.throttle((()=>{ut.remoteLogTracking(1,"info",t,"Scrolled percent:",vi.getScrollPercent()),e(vi.getScrollPercent())}),te.SCROLL_CAMPAIGN_THROTTLING_TIME);return e(vi.getScrollPercent()),window.addEventListener("scroll",n),n}onMobileTabChange(e){const t=vi.baseLogTag+".onMobileTabChange";document.addEventListener("visibilitychange",(()=>{this.isExitIntentShown||"hidden"!==document.visibilityState||(ut.log(1,t,"TRIGGERED: MOBILE EXIT INTENT"),e(),this.isExitIntentShown=!0)}))}onMobileBackHit(e){const t=vi.baseLogTag+".onMobileBackHit";setTimeout((()=>{this.isPopStateEventBound=!0,window.addEventListener("popstate",(n=>{!this.isExitIntentShown&&n.state&&"exit_intent"===n.state.moeIntent&&(ut.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=vi.baseLogTag+".onMobileScrollAndExit",n=document.documentElement.offsetHeight;let i,a=vi.getScrollY();0<n&&(this.scrollExitIntentInterval=window.setInterval((()=>{let r=a-vi.getScrollY();r<0&&(r=0,a=vi.getScrollY()),i=vi.getScrollPercent()>te.EXIT_INTENT.CONFIG.SCROLL_DOWN_THRESHOLD,i&&r/n>te.EXIT_INTENT.CONFIG.SCROLL_UP_THRESHOLD/100&&(clearInterval(this.scrollExitIntentInterval),this.scrollExitIntentInterval=null,this.isExitIntentShown||(ut.log(1,t,"TRIGGERED: MOBILE EXIT INTENT"),e(),this.isExitIntentShown=!0))}),te.EXIT_INTENT.CONFIG.SCROLL_INTERVAL))}mobileExitIntent(e){this.onMobileScrollAndExit(e),this.onMobileBackHit(e),this.onMobileTabChange(e)}onExit(e){const t=vi.baseLogTag+".onExit";qe()?this.mobileExitIntent(e):(this.exitIntentListener=n=>{return i=this,r=function*(){var i=window.innerWidth,a=window.innerHeight;(n.clientY<0||n.clientX<0||n.clientY>=a||n.clientX>=i)&&(ut.log(1,t,"TRIGGERED: EXIT INTENT"),e())},new(a=(a=void 0)||Promise)((function(e,t){function n(e){try{s(r.next(e))}catch(e){t(e)}}function o(e){try{s(r.throw(e))}catch(e){t(e)}}function s(t){var i;t.done?e(t.value):((i=t.value)instanceof a?i:new a((function(e){e(i)}))).then(n,o)}s((r=r.apply(i,[])).next())}));var i,a,r},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*vi.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)}}}vi.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 Ei{static getPendingSecondaryEventCampaign(e){return Si(this,void 0,void 0,(function*(){return yield yn.pendingSecondaryEvents.getItem(e)}))}static setPendingSecondaryEventCampaign(e,t){return Si(this,void 0,void 0,(function*(){yield yn.pendingSecondaryEvents.setItem(e,t)}))}static removePendingSecondaryEventCampaign(e){return Si(this,void 0,void 0,(function*(){yield yn.pendingSecondaryEvents.removeItem(e)}))}static getPendingSecondaryEventKeys(){return Si(this,void 0,void 0,(function*(){return yield yn.pendingSecondaryEvents.keys()}))}static getPendingTimerCampaign(e){return Si(this,void 0,void 0,(function*(){return yield yn.pendingTimerCampaigns.getItem(e)}))}static setPendingTimerCampaign(e,t){return Si(this,void 0,void 0,(function*(){yield yn.pendingTimerCampaigns.setItem(e,t)}))}static removePendingTimerCampaign(e){return Si(this,void 0,void 0,(function*(){yield yn.pendingTimerCampaigns.removeItem(e)}))}static getPendingTimerKeys(){return Si(this,void 0,void 0,(function*(){return yield yn.pendingTimerCampaigns.keys()}))}static getTriggeringPrimaryEvent(e){return Si(this,void 0,void 0,(function*(){return yield yn.triggeringPrimaryEvents.getItem(e)}))}static setTriggeringPrimaryEvent(e,t){return Si(this,void 0,void 0,(function*(){yield yn.triggeringPrimaryEvents.setItem(e,t)}))}static removeTriggeringPrimaryEvent(e){return Si(this,void 0,void 0,(function*(){yield yn.triggeringPrimaryEvents.removeItem(e)}))}static getTriggeringPrimaryEventKeys(){return Si(this,void 0,void 0,(function*(){return yield yn.triggeringPrimaryEvents.keys()}))}static removeCampaignFromStores(e){return Si(this,void 0,void 0,(function*(){yield Ei.removePendingSecondaryEventCampaign(e),yield Ei.removePendingTimerCampaign(e)}))}}var yi=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 bi{static setListener(e){this.listener=e}static destroy(){this.listener=null,this.deliveryStats=null}static setDeliveryStats(e){this.deliveryStats=e}static createNewTimers(){return yi(this,void 0,void 0,(function*(){var e=this.baseLogTag+".createNewTimers",t=yield Ei.getPendingTimerKeys();for(let a=0;a<t.length;a++){var n=t[a],i=(i=yield Ei.getPendingTimerCampaign(n)).timer-(Date.now()-i.startTime);ut.log(1,e,`Creating new setTimeout with time: ${i} ms for the campaign: `+n),yield this.createPendingTimerCampaign(n,i)}}))}static deletePendingTimer(e){return yi(this,void 0,void 0,(function*(){var t=this.baseLogTag+".deletePendingTimer",n=yield Ei.getPendingTimerCampaign(e);null!=n&&n.timerId&&(ut.log(1,t,`There was an existing setTimeout associated to the campaign: ${e}. Clearing it`),clearTimeout(n.timerId))}))}static deleteAllPendingTimers(){return yi(this,void 0,void 0,(function*(){var e=this.baseLogTag+".deleteAllPendingTimers";ut.log(1,e,"Clearing all setTimeout's associated to different campaign(s)");var t=yield Ei.getPendingTimerKeys();for(let e=0;e<t.length;e++){var n=t[e];n=yield Ei.getPendingTimerCampaign(n),clearTimeout(n.timerId)}}))}static createPendingTimerCampaign(e,t){return yi(this,void 0,void 0,(function*(){yield this.deletePendingTimer(e);var n=setTimeout((()=>yi(this,void 0,void 0,(function*(){yield this.checkAndInvokeListener(e),yield Ei.removeCampaignFromStores(e)}))),t);n={startTime:Date.now(),timerId:n,timer:t},yield Ei.setPendingTimerCampaign(e,n)}))}static checkAndInvokeListener(e){return yi(this,void 0,void 0,(function*(){var t=this.baseLogTag+".checkAndInvokeListener",n=yield Bn(e);null!=n&&n.campaignId&&((yield this.isSatisfyingEventsArray(e))?ei.getURLFilterResult(n)&&(ut.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))):(ut.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,te.DELIVERY_FUNNEL.ATTEMPTED.CAMPAIGN_ATTEMPTED),this.deliveryStats.setStats(n,te.DELIVERY_FUNNEL.EVALUATION.CAMPAIGN_EVALUATION_PATH_TIME_EXPIRED),this.deliveryStats.sendDeliveryStats([n])))}))}static checkIfPendingAction(e,t){return t===In.AND&&!e.events.some((e=>1===e.filters.length&&!e.filters[0].executed))}static isSatisfyingEventsArray(e){return yi(this,void 0,void 0,(function*(){var t=yield Ei.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===In.AND&&a===In.OR&&r&&!o)return!1}return!0}return!1}))}static logDeliveryFunnelForExpiredTimerCampaigns(){return yi(this,void 0,void 0,(function*(){var e=this.baseLogTag+".logDeliveryFunnelForExpiredTimerCampaigns",t=yield Ei.getPendingTimerKeys(),n=Date.now();const i=[];for(let o=0;o<t.length;o++){var a=t[o],r=yield Ei.getPendingTimerCampaign(a);n-r.startTime>=r.timer&&(yield this.isSatisfyingEventsArray(a))&&null!=(r=yield Bn(a))&&r.campaignId&&(ut.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,te.DELIVERY_FUNNEL.ATTEMPTED.CAMPAIGN_ATTEMPTED),this.deliveryStats.setStats(t,te.DELIVERY_FUNNEL.EVALUATION.CAMPAIGN_EVALUATION_USER_NOT_ON_APP)}this.deliveryStats.sendDeliveryStats(e)}static deleteTimerAndRemoveFromStores(e){return yi(this,void 0,void 0,(function*(){yield this.deletePendingTimer(e),yield Ei.removeCampaignFromStores(e)}))}}bi.baseLogTag="CampaignTimerManager",bi.listener=null,bi.deliveryStats=null,bi.closeProximityTimerCampaigns=[],bi.closeProximityCampaignsTimeout=null;var _i=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 Ti{static setDeliveryStats(e){this.deliveryStats=e}static destroy(){this.deliveryStats=null}static createPendingSecondaryEvents(e,t){return _i(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];Fn(r)&&(({campaignEntry:i,isCampaignTimerSet:a}=this.constructCampaignEntry(r)),yield Ei.setTriggeringPrimaryEvent(r.campaignId,t),yield Ei.setPendingSecondaryEventCampaign(r.campaignId,i),a&&(ut.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 bi.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===In.AND?In.OR:In.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 _i(this,void 0,void 0,(function*(){var e=this.baseLogTag+".pruneRemovedCampaigns";const t=(yield Un()).map((e=>e.campaignId));var n=yield Ei.getPendingSecondaryEventKeys();for(let a=0;a<n.length;a++){var i=n[a];t.includes(i)||(ut.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 bi.deleteTimerAndRemoveFromStores(i))}}))}static updateCampaignTimeInSecondaryEventsStore(){return _i(this,void 0,void 0,(function*(){var e=this.baseLogTag+".updateCampaignTimeInSecondaryEventsStore",t=yield Ei.getPendingSecondaryEventKeys();const n=[];for(let r=0;r<t.length;r++){var i=t[r];const o=yield Ei.getPendingSecondaryEventCampaign(i);var a=Date.now();o.time_left-=a-o.updated_time,o.updated_time=a,o.time_left<=0?(null!=(a=yield Bn(i))&&a.campaignId&&(ut.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 bi.deleteTimerAndRemoveFromStores(i)):yield Ei.setPendingSecondaryEventCampaign(i,o)}this.sendPathTimeExpiredStat(n)}))}static updatePendingSecondaryEventsHistory(e,t){return _i(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 Ei.getPendingSecondaryEventCampaign(s);if(h)if(h.time_left-=o-h.updated_time,h.updated_time=o,h.time_left<=0){var l=yield Bn(s);null!=l&&l.campaignId&&(ut.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&&ei.isTriggered(e,g.filters,null,g.filterOperator)||!e.attributes||!e.attributes.length)&&(u?d===In.OR?(r.toBeRemoved=!0,c!==In.OR&&(c!==In.AND||h.events.length&&!h.events.every((e=>e.toBeRemoved)))||(ut.log(1,n,`Campaign: ${s}, triggered by event: ${e.name}, is eligible for further processing`),i.push(s))):d===In.AND&&(o.toBeRemoved=!0,r.filters.every((e=>e.toBeRemoved))&&(r.toBeRemoved=!0,(c===In.OR||c===In.AND&&h.events.every((e=>e.toBeRemoved)))&&(ut.log(1,n,`Campaign: ${s}, triggered by event: ${e.name}, is eligible for further processing`),i.push(s)))):d===In.OR?(o.toBeRemoved=!0,r.filters.every((e=>e.toBeRemoved))&&(c===In.AND||c===In.OR&&1===h.events.length?(ut.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===In.AND&&(r.toBeRemoved=!0,1===h.events.length&&h.events[0].toBeRemoved&&c===In.OR&&(ut.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,te.DELIVERY_FUNNEL.ATTEMPTED.CAMPAIGN_ATTEMPTED),this.deliveryStats.setStats(t,te.DELIVERY_FUNNEL.EVALUATION.CAMPAIGN_EVALUATION_PATH_TIME_EXPIRED)}this.deliveryStats.sendDeliveryStats(e)}static updatePendingSecondaryEvents(e,t){return _i(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 Ei.setPendingSecondaryEventCampaign(e,t)}))}static clearCampaignsData(e){return _i(this,void 0,void 0,(function*(){for(let t=0;t<e.length;t++)yield bi.deleteTimerAndRemoveFromStores(e[t])}))}static removeStaleTriggeringPrimaryEventCampaigns(){return _i(this,void 0,void 0,(function*(){const e=this.baseLogTag+".removeStaleTriggeringPrimaryEventCampaigns",t=yield Ei.getTriggeringPrimaryEventKeys(),n=yield Ei.getPendingSecondaryEventKeys();t.forEach((t=>_i(this,void 0,void 0,(function*(){n.includes(t)||(ut.warn(1,e,`Campaign: ${t} does not exist in pendingSecondaryEvents store but exists in triggeringPrimaryEvents store. Removing it from triggeringPrimaryEvents store`),yield Ei.removeTriggeringPrimaryEvent(t))}))))}))}}Ti.baseLogTag="SecondaryEventsManager",Ti.deliveryStats=null;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){this.primaryEventsHash={},this.secondaryEventsHash={},this.messagingCampaigns=[],this.scrollCampaigns=[],this.scrollCampaignTriggered=!1,this.exitIntentCampaigns=[],this.exitCampaignTriggered=!1,this.listener=null,this.historyManager=window[ee],this.onEvent=e=>Ii(this,void 0,void 0,(function*(){var t=Ai.baseLogTag+".onEvent";try{null!=this.primaryEventsHash[e.name]&&(yield this.handlePrimaryEvent(e)),null!=this.secondaryEventsHash[e.name]&&(yield this.handleSecondaryEvent(e))}catch(e){ut.error(1,t,"Error occurred during check event trigger campaigns: ",e)}})),this.onScroll=e=>Ii(this,void 0,void 0,(function*(){const t=Ai.baseLogTag+".onScroll";try{if(this.scrollCampaigns&&0<this.scrollCampaigns.length&&!this.scrollCampaignTriggered){var n=yield this.getCampaignsFromHash(T);const i=yield Ln(n);null!=i&&i.map((n=>Ii(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 yt(a.name,a.value),i=yield Jt.createEvent(T,[i]),ei.getFilterResult(i,n)&&e>a.value&&!this.scrollCampaignTriggered&&(this.scrollCampaignTriggered=!0,window.removeEventListener("scroll",this.scrollListenerCallback),ut.log(1,t,"Triggered Scroll campaign"),this.trigger([n],i)))}))))}}catch(n){ut.error(1,t,"Error occurred in triggering scroll campaigns ",n)}})),this.onExit=e=>Ii(this,void 0,void 0,(function*(){var t=Ai.baseLogTag+".onExit";try{if(0<this.exitIntentCampaigns.length&&!this.exitCampaignTriggered){const i=yield Jt.createEvent("MOE_EXIT",[]);var n=(yield this.getCampaignsFromHash(_)).filter((e=>ei.getFilterResult(i,e)));n.length?(ut.log(1,t,"Triggered Exit Intent campaign: ",n),this.trigger(n,i)):("onBackClick"===e&&window.history.back(),ut.log(1,t,"No Exit Intent campaign is eligible."))}}catch(n){ut.error(1,t,"Error occurred in triggering exit intent campaigns ",n)}})),this.messagingCampaigns=e,this.windowEventManager=new vi}onTrigger(e){this.listener=e}handlePrimaryEvent(e){return Ii(this,void 0,void 0,(function*(){var t=Ai.baseLogTag+".handlePrimaryEvent",n=this.primaryEventsHash[e.name];const i=[],a=[];for(let e=0;e<n.length;e++){var r=n[e];r=yield Bn(r),Fn(r)?i.push(r):Te(r,"triggerData.primary_condition.included_filters.filter_operator")===In.OR&&a.push(r)}var o=i.filter((t=>ei.didPrimaryEventFilterTrigger(e,t)));o.length&&(yield Ti.createPendingSecondaryEvents(o,e)),o=a.filter((t=>ei.getFilterResult(e,t))),o.length&&(ut.log(1,t,`Campaigns triggered for event ${e.name}: `+o.length),this.trigger(o,e))}))}handleSecondaryEvent(e){return Ii(this,void 0,void 0,(function*(){var t=Ai.baseLogTag+".handleSecondaryEvent",n=yield Ti.updatePendingSecondaryEventsHistory(e,this.secondaryEventsHash[e.name]);let i=[];for(let e=0;e<n.length;e++)i.push(yield Bn(n[e]));i=i.filter((e=>ei.getURLFilterResult(e))),i.length&&(ut.log(1,t,`Campaigns triggered by secondary event "${e.name}": `+i.length),this.trigger(i))}))}getCampaignsFromHash(e){return Ii(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 Bn(n[e]));return t}))}addEntryInEventsHash(e,t,n){null==e[t]&&(e[t]=[]),e[t].push(n)}createPrimaryEventsHash(e){Te(e,"triggerData.primary_condition.included_filters.filters",[]).forEach((t=>{this.addEntryInEventsHash(this.primaryEventsHash,t.action_name,e.campaignId)}))}createSecondaryEventsHash(e){const t=Te(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 Ii(this,void 0,void 0,(function*(){Ai.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=>kn(e,T))),0<this.scrollCampaigns.length&&(this.scrollListenerCallback=this.windowEventManager.onScroll(this.onScroll)),this.exitCampaignTriggered=!1,this.exitIntentCampaigns=this.messagingCampaigns.filter((e=>kn(e,_))),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}}Ai.baseLogTag="OnsiteTriggerManager";class wi{constructor(e,t){this.waitForDelay=null,this.delayTimer=null,this.iframe=null,this.onFrameLoad=new mt,this.active=!1,this.dismissInterval=null,this.isJSONPayloadApproach=!1,this.osmDivRendering=null,this.osmDivSelector=null,this.campaignRendered=!1,this.isActive=()=>this.active,this.campaignMeta=e,this.data=t,this.active=!1,this.campaignRendered=!1;const n=Te(e,"triggerData.trigger_delay.delayInSeconds",0)||0;this.waitForDelay=new Promise((e=>{this.delayTimer=setTimeout((()=>{this.campaignRendered=!0,e()}),1e3*n)}))}setIsActive(e){this.active=e}}const Di={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"}},Oi=e=>{try{return!Ci()&&window.Moengage.onsite.displayManager.campaignRenderMap[e].campaignMeta}catch(t){ut.error(1,"OsmFunctions.getCampaignMeta","Campaign meta not found: "+e)}},Ci=()=>!!window.Moengage.onsite.displayManager.testCampaign&&(ut.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 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())}))};function Ri(e,t,n,i,a){return Pi(this,void 0,void 0,(function*(){const r=Wn(t),o=/moe-campaign-id/g;yield Pi(this,void 0,void 0,(function*(){try{let d=e.root;const{styles:g,scripts:u}=e,p=document.createElement("div");p.id=r,n.parentNode.insertBefore(p,n);const h=document.querySelector("#"+r),m=new DOMParser;d=d.replace(o,t);var s=m.parseFromString(d,"text/html");yield function(e){return Pi(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){ut.error(2,"InsertCustomHtmlJs.removeEmptyHrefTags","Error while removing Empty href attributes",e)}}))}(s),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){ut.error(2,"InsertCustomHtmlJs.addCampaignId","Error while adding Campaign Id",e)}}(s);const f=g.map((e=>m.parseFromString(e,"text/html").head.childNodes[0]));var l=u.map((e=>(e=e.replace(o,t),m.parseFromString(e,"text/html").head.childNodes[0]))),c=f.map((e=>new Promise(((t,n)=>{!function(e){const{node:t,onLoad:n,onError:i}=e;t instanceof HTMLMetaElement||"dns-prefetch"===t.getAttribute("rel")?n():(t.onload=()=>n(),t.onerror=()=>i()),document.querySelector("#"+r).appendChild(t)}({node:e,onLoad:t,onError:n})}))));yield Promise.all(c).catch((e=>{ut.warn(1,"InsertCustomHtmlJs","Error loading Styles",(null==e?void 0:e.message)||"")}));const v=s.body.childNodes[0];h.appendChild(v),[...v.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 Pi(this,void 0,void 0,(function*(){for(const n of e)yield function(e){return new Promise(((n,i)=>{const a=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),a.setAttribute(o,i)}a.src?(a.onload=n,a.onerror=i):(a.innerHTML=e.innerHTML,n()),document.querySelector("#"+r).appendChild(a)}))}(n)}))}(l).then((()=>{window.Brz.emit("init.dom",window.jQuery(v)),ut.log(1,"InsertCustomHtmlJs","Custom HTML/JS DOM Level OSM Insertion: "+r),a&&a(i,"OSM")()})).catch((e=>{ut.warn(1,"InsertCustomHtmlJs","Error loading script",(null==e?void 0:e.message)||"")}))}catch(e){ut.error(2,"InsertCustomHtmlJs","Failed to Insert OSM into DOM: "+r)}}))}))}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())}))};class Li{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=>{var n;t.campaignMeta.campaignId===e&&(t.iframe?null!==(n=t.iframe)&&void 0!==n&&n.remove():null!==(t=t.osmDivSelector)&&void 0!==t&&t.remove())}))}),0),this.campaignRenderMap[e].setIsActive(!1),this.campaignRenderOrder=this.campaignRenderOrder.filter((t=>t!==e)),clearInterval(this.campaignRenderMap[e].dismissInterval),this.campaignRenderMap[e].delayTimer=null,this.renderAllActiveCampaigns()}else this.dismissTestInapp(e)},this.clickTracker=Dn,this.dismissEvent=Cn,this.startInitialization(),this.initialInlineBodyStyle=document.body.getAttribute("style")}startInitialization(){return Ni(this,void 0,void 0,(function*(){var e=Li.baseLogTag+".startInitialization";try{null==this.initializationPromiseObject&&(this.initializationPromiseObject=new mt),this.initializationPromiseObject.res()}catch(t){ut.error(1,e,"Error initializing display managaer:",t)}}))}getOSMPusher(e){const t=document.createElement("div");if(t.id=te.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(te.PUSH_BANNER))&&void 0!==e&&e.remove()}queueDraftCampaign(e,t){return Ni(this,void 0,void 0,(function*(){var n=Li.baseLogTag+".queueDraftCampaign";try{yield this.initializationPromiseObject.p,e.position=t.position,this.testCampaign=e;var i=!("1"!==t.editorVersion||!t.htmlJsonPayload);const a=!i&&Li.createDefaultIframe(this.testCampaign.draftId,t.payload);let r;ut.warn(1,n,"Going to render test campaign "+e.draftId),r="FRAMESET"===document.body.nodeName?this.getOSMPusher(0):document.body.firstChild,i?(yield Ri(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){ut.error(1,n,"Error queueing draft campaign",e)}}))}renderTestCampaign(e,t,n){return Ni(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===An.POP_UP&&(t.style.margin="0px auto"),-1<t.srcdoc.indexOf(te.POSITIONED_TEMPLATE)&&(i=-1<t.srcdoc.indexOf(te.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(Wn(e.draftId));t.style.zIndex="2147483647",this.testCampaignPositionStyling(e,t)}e.templateType===An.BANNER&&this.bannerTestCampaignStyling(e,t,n)}))}queueLiveCampaign(e,t){var n;return Ni(this,void 0,void 0,(function*(){var i,a=Li.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()&&null===this.campaignRenderMap[e.campaignId].delayTimer)if(this.campaignRenderOrder.push(e.campaignId),this.campaignRenderMap[e.campaignId]=new wi(e,t),this.campaignRenderMap[e.campaignId].isJSONPayloadApproach=!("1"!==t.editorVersion||!t.htmlJsonPayload),this.campaignRenderMap[e.campaignId].isJSONPayloadApproach?this.campaignRenderMap[e.campaignId].osmDivRendering=n=>Ni(this,void 0,void 0,(function*(){yield Ri(t.htmlJsonPayload,e.campaignId,n,e,On)})):(i=Li.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(ut.warn(1,a,"Going to render "+e.campaignId),(null===(n=t.payload)||void 0===n?void 0:n.code)===te.GCG_ERROR_CODE)return ut.warn(1,a,`Can not render ${e.campaignId} as it falls under Control Group.`),void On(e,"OSM",!0)();this.campaignRenderMap[e.campaignId].setIsActive(!0),null!=this.renderListener&&this.renderListener(e),this.renderAllActiveCampaigns()}else ut.warn(1,a,"Can not render "+e.campaignId);else ut.warn(1,a,`Can not render ${e.campaignId}, as campaign is already Active.`)}catch(i){ut.error(1,a,"Error queuing campaign "+e.campaignId,i)}}))}renderAllActiveCampaigns(){return Ni(this,void 0,void 0,(function*(){var e,t=Li.baseLogTag+".renderAllActiveCampaigns";const n=this.getActiveCampaigns();if(this.restoreBodyStyle(),0<n.length){for(let i=0;i<n.length;i++)if(n[i].isJSONPayloadApproach||"visible"!==n[i].iframe.style.visibility){if(null==document.getElementById(Wn(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(Wn(n[i].campaignMeta.campaignId))):(e.parentNode.insertBefore(n[i].iframe,e),n[i].iframe.onload=()=>{Mi.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?(ut.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",ut.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===An.POP_UP&&(n[i].iframe.style.margin="0px auto"),n[i].data.payload&&-1<n[i].data.payload.indexOf(te.POSITIONED_TEMPLATE)&&(e=-1<n[i].data.payload.indexOf(te.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),On(n[i].campaignMeta,"OSM")()),null!=n[i].dismissInterval||0<(e=1e3*Te(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(),Cn(n[i].campaignMeta,"OSM",!0))}),e))}else n[i].iframe.style.zIndex=(2147483647-(n.length-i-1)).toString();this.bannerLiveCampaignsStyling(n)}}))}restoreBodyStyle(){this.removeOSMPusher(),this.pushCardsTemplate(0);let e=0;Object.keys(this.campaignRenderMap).forEach((t=>{this.campaignRenderMap[t].campaignMeta.templateType===An.POP_UP&&this.campaignRenderMap[t].isActive()&&e++})),1<=e||(this.initialInlineBodyStyle?document.body.setAttribute("style",this.initialInlineBodyStyle):document.body.removeAttribute("style"))}canCampaignBeRendered(e){return Ni(this,void 0,void 0,(function*(){var t=Li.baseLogTag+".queueLiveCampaign";try{var n=yield yn.campaingsStatsStore.getItem(e.campaignId),i=yield yn.serviceMetaStore.getItem(te.STORES.SERVICE_META.KEYS.GLOBAL_DELAY),a=yield yn.serviceMetaStore.getItem(te.STORES.SERVICE_META.KEYS.LAST_INAPP_SHOWN_TIME);return Nn.isValid(e,n)&&Nn.isValidMessagingCampaign(e,n,i,a,this.getActiveCampaigns())&&ei.getURLFilterResult(e)}catch(n){ut.error(1,t,`Error checking if campaign ${e.campaignId} can be rendered:`,n)}return!1}))}static createDefaultIframe(e,t){Li.baseLogTag,e=Wn(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,Di[t]),qe()&&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=Li.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)),ut.log(2,i,"JS-bridge script inserted successfully",t)}catch(e){ut.warn(2,i,"Failed to insert OSM JS Bridge: ",t)}}handleClassBasedTrackingForTestCampaign(e,t,n){const i=Li.baseLogTag+".handleClassBasedTrackingForTestCampaign";var a=e=>Array.prototype.slice.call(e),r=a(e.contentDocument.getElementsByClassName(te.CSS_SELECTORS.DISMISS_INAPP)),o=a(e.contentDocument.getElementsByClassName(te.CSS_SELECTORS.CLICK_INAPP));if(a=a(e.contentDocument.getElementsByTagName("a")),0===r.length&&ut.warn(1,i,"No dismiss class items present in this template"),0===o.length&&ut.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(te.CSS_SELECTORS.CLICK_INAPP)&&ut.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(te.CSS_SELECTORS.DISMISS_INAPP)&&this.dismissTestInapp(n.draftId)}));else{for(const e of o)e.addEventListener("click",(e=>{ut.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=Li.baseLogTag+".handleClassBasedTracking",n=e=>Array.prototype.slice.call(e);const i=e.iframe;var a=n(i.contentDocument.getElementsByClassName(te.CSS_SELECTORS.DISMISS_INAPP)),r=n(i.contentDocument.getElementsByClassName(te.CSS_SELECTORS.CLICK_INAPP));if(n=n(i.contentDocument.getElementsByTagName("a")),0===a.length&&ut.warn(1,t,"No dismiss class items present in this template"),0===r.length&&ut.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(te.CSS_SELECTORS.CLICK_INAPP)&&(n=t.target.dataset.id,Dn(e.campaignMeta,"OSM",{widget_id:n})()),t.target&&t.target.classList.contains(te.CSS_SELECTORS.DISMISS_INAPP)&&(this.dismissInapp(e.campaignMeta.campaignId),t.target.classList.contains(te.CSS_SELECTORS.CLICK_INAPP)||Cn(e.campaignMeta,"OSM"))}));else{for(const t of r)t.addEventListener("click",(t=>{t=t.target.dataset.id,Dn(e.campaignMeta,"OSM",{widget_id:t})()}));for(const t of a)t.addEventListener("click",(()=>{this.dismissInapp(e.campaignMeta.campaignId),t.classList.contains(te.CSS_SELECTORS.CLICK_INAPP)||Cn(e.campaignMeta,"OSM")}))}for(const e of n)"_blank"!==e.getAttribute("target")&&e.setAttribute("target","_parent")}changeAnchorTagReDirectionMethod(e){var t,n=Li.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"))}ut.log(1,n,"Anchor Tag Href Rendering Changed to onClick for Campaign Frame: "+e.id)}catch(t){ut.error(1,n,"Failed to Change Anchor Tag Href Rendering for Campaign Frame: "+e.id)}}liveCampaignPositionStyling(e,t){var n=Li.baseLogTag+".liveCampaignPositionStyling";try{e.templateType===An.BANNER?e.display.config.sticky?t.style.position="fixed":t.style.position="absolute":e.templateType===An.POP_UP&&(t.style.position="fixed","DIV"===t.tagName?t.style.inset="0":t.style.backgroundColor="rgba(99, 99, 99, 0.21)"),ut.log(1,n,"Added Position Styles for CampaignId: "+e.campaignId)}catch(t){ut.error(1,n,"Failed adding Styles for CampaignId: "+e.campaignId)}}testCampaignPositionStyling(e,t){var n=Li.baseLogTag+".testCampaignPositionStyling";try{e.templateType===An.BANNER?e.displaySettings.config.sticky?t.style.position="fixed":t.style.position="absolute":e.templateType===An.POP_UP&&(t.style.position="fixed","DIV"===t.tagName?t.style.inset="0":t.style.backgroundColor="rgba(99, 99, 99, 0.21)"),ut.log(1,n,"Added Position Styles for CampaignId: "+e.draftId)}catch(t){ut.error(1,n,"Failed adding Styles for CampaignId: "+e.draftId)}}bannerTestCampaignStyling(e,t,n){var i,a=Li.baseLogTag+".bannerTestCampaignStyling";try{let n,r,o=!0;t?(n=parseInt(getComputedStyle(t.contentDocument.body).height),o=-1<t.srcdoc.indexOf(te.POSITIONED_TEMPLATE)):(i=document.querySelector("#"+Wn(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),ut.log(1,a,"Added Banner Styles for Test CampaignId: "+e.draftId)}catch(n){ut.error(1,a,"Failed Added Banner Styles for Test CampaignId: "+e.draftId)}}bannerLiveCampaignsStyling(e){var t=Li.baseLogTag+".bannerLiveCampaignsStyling";let n=0,i=0;for(let r=e.filter((e=>e.campaignMeta.templateType===An.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(te.POSITIONED_TEMPLATE)),n+=a,e[r].campaignMeta.display.config.pushPage&&(o&&"TOP"===e[r].data.position||!o)&&(i+=a),ut.log(1,t,"Added Banner Styles for Live CampaignId: "+e[r].campaignMeta.campaignId)}}catch(a){ut.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)}}Li.baseLogTag="MessagingDisplayManager";class Mi{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 ki=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 xi{constructor(e,t,n){this.baseLogTag="DeliveryFunnelManager",this.displayManager=t,this.OnsiteApiClient=new fi(e),this.deliveryStats=n}attemptCampaigns(e){e.forEach((e=>{this.deliveryStats.setStats(e,te.DELIVERY_FUNNEL.ATTEMPTED.CAMPAIGN_ATTEMPTED)}))}getImpressionStats(e){return ki(this,void 0,void 0,(function*(){var t=this.baseLogTag+".getImpressionStats";try{return yield yn.campaingsStatsStore.getItem(e.campaignId)}catch(n){ut.error(1,t,"Error getting impression stats for "+e.campaignId,n)}}))}getLastGlobalInappShown(){return ki(this,void 0,void 0,(function*(){return yield yn.serviceMetaStore.getItem(te.STORES.SERVICE_META.KEYS.LAST_INAPP_SHOWN_TIME)}))}getGlobalDelay(){return ki(this,void 0,void 0,(function*(){return yield yn.serviceMetaStore.getItem(te.STORES.SERVICE_META.KEYS.GLOBAL_DELAY)}))}filterValidCampaigns(e){return ki(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!==An.SELF_HANDLED){if(!Nn.isCampaignWithinFC(e,t[n]))return this.deliveryStats.setStats(e,te.DELIVERY_FUNNEL.PRIORITIZED.CAMPAIGN_PRIORITY_MAX_TIMES_SHOWN),!1;if(!Nn.hasCampaignClearedSelfDelay(e,t[n]))return this.deliveryStats.setStats(e,te.DELIVERY_FUNNEL.PRIORITIZED.CAMPAIGN_PRIORITY_MIN_DELAY),!1;if(!Nn.hasCampaignClearedGlobalDelay(e,a,i))return this.deliveryStats.setStats(e,te.DELIVERY_FUNNEL.PRIORITIZED.CAMPAIGN_PRIORITY_GLOBAL_DELAY),!1}return!Nn.isCampaignExpired(e)||(this.deliveryStats.setStats(e,te.DELIVERY_FUNNEL.PRIORITIZED.CAMPAIGN_PRIORITY_EXPIRED),!1)}))}catch(n){ut.error(1,t,"Error filtering and sorting campaigns",n)}}))}prioritizeMessagingCampaigns(e){return ki(this,void 0,void 0,(function*(){const t=yield this.filterValidCampaigns(e);if(0<t.length){const[e,...n]=t.sort(Nn.comparator);return n&&0<n.length&&n.map((t=>{t.campaignId!==e.campaignId&&this.deliveryStats.setStats(t,te.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(Nn.comparator);for(let e=0;e<i.length;e++)0===e?n.push(i[e]):this.deliveryStats.setStats(i[e],te.DELIVERY_FUNNEL.PRIORITIZED.CAMPAIGN_PRIORITY_HIGH_PRIORITY_CAMPAIGN_AVAILABLE)}})),n}prioritizePersonalizationCampaigns(e){return ki(this,void 0,void 0,(function*(){var t=yield this.filterValidCampaigns(e);return 0<t.length?this.getCampaignTagMap(t):[]}))}getOnsitePayload(e,t){return ki(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){var a=i.reason;return void this.setDeliveryFailureStats(e,a)}return void this.deliveryStats.setStats(e,te.DELIVERY_FUNNEL.DELIVERED.CAMPAIGN_DELIVERED_API_FAILURE)}catch(i){return ut.error(1,n,"Error getting onsite payload",i),void this.deliveryStats.setStats(e,te.DELIVERY_FUNNEL.DELIVERED.CAMPAIGN_DELIVERED_API_FAILURE)}}))}setDeliveryFailureStats(e,t){if(t){if(t.includes("PAUSED"))return void this.deliveryStats.setStats(e,te.DELIVERY_FUNNEL.DELIVERED.CAMPAIGN_DELIVERED_PAUSED);if(t.includes("EXPIRED"))return void this.deliveryStats.setStats(e,te.DELIVERY_FUNNEL.DELIVERED.CAMPAIGN_DELIVERED_EXPIRED);if(t.includes("personalize"))return void this.deliveryStats.setStats(e,te.DELIVERY_FUNNEL.DELIVERED.CAMPAIGN_DELIVERED_PERSONALIZATION_FAILURE)}this.deliveryStats.setStats(e,te.DELIVERY_FUNNEL.DELIVERED.CAMPAIGN_DELIVERED_API_FAILURE)}getEventForPersonalisation(e){return ki(this,void 0,void 0,(function*(){var t=yield Ei.getTriggeringPrimaryEvent(e.campaignId);return t?new Jt(t.name,t.attributes):null}))}deliverMessagingCampaign(e,t){return ki(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,Nn.doCampaignPayloadHasMandatoryParams(e.onsitePayload)?e:(ut.warn(1,n,"Can not render "+e.campaignId),void this.deliveryStats.setStats(e,te.DELIVERY_FUNNEL.DELIVERED.CAMPAIGN_DELIVERED_MANDATORY_PARAMS_MISSING))}catch(i){ut.error(1,n,"Error delivering messaging campaign",i)}}}))}deliverPersonalizationCampaigns(e,t,n){return ki(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){ut.error(1,i,"Error delivering personalization campaigns",a)}}}))}messagingCampaignImpression(e,t){return ki(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 Nn.hasCampaignClearedGlobalDelay(e,a,i)?Nn.canCampaignBeRenderedOverExisting(e,r.length)?ei.getURLFilterResult(e)?null==this.displayManager.campaignRenderMap[e.campaignId]||"MOE_EXIT"!==t&&t!==T?e:(ut.warn(1,n,`Can not render ${e.campaignId} `+(this.displayManager.campaignRenderMap[e.campaignId].isActive()?", as campaign is already Active.":"")),void this.deliveryStats.setStats(e,te.DELIVERY_FUNNEL.IMPRESSION.CAMPAIGN_IMPRESSION_MAX_TIMES_SHOWN)):(ut.warn(1,n,"Can not render "+e.campaignId),void this.deliveryStats.setStats(e,te.DELIVERY_FUNNEL.IMPRESSION.CAMPAIGN_IMPRESSION_CONTEXT_CHANGED)):void this.deliveryStats.setStats(e,te.DELIVERY_FUNNEL.IMPRESSION.CAMPAIGN_IMPRESSION_ANOTHER_CAMPAIGN_VISIBLE):(ut.warn(1,n,"Can not render "+e.campaignId),void this.deliveryStats.setStats(e,te.DELIVERY_FUNNEL.IMPRESSION.CAMPAIGN_IMPRESSION_GLOBAL_DELAY))}catch(i){return void ut.error(1,n,"Error delivering messaging campaign",i)}}))}mostEligibleMessagingCampaign(e,t){return ki(this,void 0,void 0,(function*(){if(0<e.length){this.attemptCampaigns(e);var n,i=yield this.prioritizeMessagingCampaigns(e);let a;return kn(i,_)?(n=yield xn(i)).error?this.setDeliveryFailureStats(i,n.reason):a=n:a=yield this.deliverMessagingCampaign(i,t),i=yield this.messagingCampaignImpression(a,null==t?void 0:t.name),this.deliveryStats.sendDeliveryStats(e),i}}))}mostEligiblePersonalizationCampaigns(e,t,n){return ki(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 ki(this,void 0,void 0,(function*(){var n=this.baseLogTag+".mostEligibleSelfHandledPersonalizationCampaigns";this.attemptCampaigns(e);const i=yield this.filterValidCampaigns(e);ut.log(1,n,"Eligible campaigns with tag ",t,"are",i);const a=i.sort(Nn.comparator)[0];return a&&(ut.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}))}delayDeliveryCampaignStats(e){this.deliveryStats.setStats(e,te.DELIVERY_FUNNEL.IMPRESSION.CAMPAIGN_IMPRESSION_CANCEL_BEFORE_DELAY),this.deliveryStats.sendDeliveryStats([e],!0)}}class Bi{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=Bi.baseLogTag+".handler";ut.log(1,s,(null==r?void 0:r.name)&&`Triggered for ${r.name}: `||"Campaign(s) triggered: ",a);var l=a.filter((e=>e.templateType===An.SELF_HANDLED)),c=a.filter((e=>e.templateType!==An.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)?ut.log(1,s,"Stopped triggering the campaign because handle_page_change was called: ",a):c&&i(c))}))}}Bi.baseLogTag="EventTriggerHandler";class Ui{constructor(e){this.baseLogTag="DeliveryStats",this.OnsiteApiClient=new fi(e),this.batchId=(0,ft.v4)()}sendDeliveryStats(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*(){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.sendBeacon(n,this.batchId)}catch(n){ut.error(1,t,"Error in sending delivery funnel stats",n)}}))}setStats(e,t){var n=(new Date).toISOString();e&&(e.stats[t]=e.stats[t]||[],e.stats[t].includes(n)||e.stats[t].push(n))}}var Fi=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 Wi=new mt;class Hi{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,ut.setLogLevel(e.debugLevel),this.OnsiteApiClient=new fi(this.initData),this.iframeHelper=new pi}setLogLevel(e){ut.setLogLevel(e,!1)}isTestCampaignAvailable(){return Fi(this,void 0,void 0,(function*(){const e=Hi.baseLogTag+".isTestCampaignAvailable";if(window.opener){let t;window.addEventListener("message",(n=>Fi(this,void 0,void 0,(function*(){var i,a;n.data&&"inapp_test"===n.data.action&&(i=n.data,(yield ui.isValidRawJson(i))?(t=!0,a=new ui(i),ut.log(1,e,"Valid test campaign data found checking TestCampaign",i),yield this.checkForTestCampaign(a)):ut.error(1,e,"Data is not a valid test campaign",i),Wi.res())}))),!1),window.opener.postMessage("moe_test_osm","*"),setTimeout((()=>Fi(this,void 0,void 0,(function*(){t||(yield this.checkForTestCampaign()),Wi.res()}))),100)}else Wi.res()}))}initialize(){const e=Hi.baseLogTag+".initialize";return ut.log(1,e,"Initialising onsite module"),null==this.initializationPomise&&(this.initializationPomise=new Promise((t=>Fi(this,void 0,void 0,(function*(){try{yield yn.initialize(),yield this.isTestCampaignAvailable(),Wi.p.then((()=>Fi(this,void 0,void 0,(function*(){yield this.syncCampaigns();const n=yield Un();var i=this.isExitIntentCampaignFound(n);if(i.length&&(yield this.prefetchExitIntentCampaigns(i)),i=n.filter((e=>null!=e.triggerData)),this.displayManager=new Li,this.displayManager.onRender((t=>{ut.log(1,e,"Campaign rendered: "+t.campaignId),yn.serviceMetaStore.setItem(te.STORES.SERVICE_META.KEYS.LAST_INAPP_SHOWN_TIME,new Date)})),null!=this.testDraftInfo&&this.testDraftInfo.draftType===te.DRAFT_CAMPAIGN_TPYES.ONSITE_MESSAGING){ut.log(1,e,"Test campaigns present, will be showing only the test campaign."),ut.log(1,e,"No live campaign will be shown till draft campaign showing");try{ut.log(1,e,"Trying to render draft campaign with id "+this.testDraftInfo.draftId);var a=yield this.OnsiteApiClient.getDraftCampaign(this.testDraftInfo);ut.log(1,e,"Test campaign payload: ",a),a&&this.displayManager.queueDraftCampaign(this.testDraftInfo,a)}catch(n){ut.error(1,e,`Error fetching data for test campaign ${this.testDraftInfo.draftId}: `,n)}}else this.deliveryStats=new Ui(this.initData),this.triggerManager=new Ai(i),this.funnelManager=new xi(this.initData,this.displayManager,this.deliveryStats),this.eventTriggerHandler=new Bi,i=this.eventTriggerHandler.handler.bind(null,this.funnelManager,this.onsiteSelfHandledTriggerListeners,this.handlePersonalizationCampagins.bind(this),this.handleMessagingCampaigns.bind(this)),this.triggerManager.onTrigger(i),bi.setListener(i),Ti.setDeliveryStats(this.deliveryStats),bi.setDeliveryStats(this.deliveryStats),yield bi.logDeliveryFunnelForExpiredTimerCampaigns(),yield Ti.updateCampaignTimeInSecondaryEventsStore(),yield bi.createNewTimers(),this.triggerManager.startWatching();t(!0)}))))}catch(t){ut.error(1,e,t)}}))))),this.initializationPomise}handleMessagingCampaigns(e){return Fi(this,void 0,void 0,(function*(){var t=Hi.baseLogTag+".handleMessagingCampaigns";e.onsitePayload&&(ut.log(1,t,"Campaign triggered: "+e.campaignId),ut.log(1,t,"Payload for campaign:",e.onsitePayload),this.displayManager.queueLiveCampaign(e,e.onsitePayload))}))}handlePersonalizationCampagins(e){return Fi(this,void 0,void 0,(function*(){const t=Hi.baseLogTag+".handlePersonalizationCampagins";0<e.length&&e.forEach((e=>{null!=e.tag&&(ut.log(1,t,"Personlization Campaign triggered: "+e.campaignId),this.onsiteSelfHandledTriggerListeners[e.tag].forEach((t=>{this.handleSelfHandledCallback(e,e.onsitePayload,t)})))}))}))}logout(){var e;return Fi(this,void 0,void 0,(function*(){var t=Hi.baseLogTag+".logout";if(ut.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(),Ti.destroy(),bi.destroy(),this.displayManager=null,this.funnelManager=null,this.eventTriggerHandler=null,yield bi.deleteAllPendingTimers(),yield yn.clear(),ut.log(1,t,"Starting module logout complete")}))}checkForTestCampaign(e){return Fi(this,void 0,void 0,(function*(){var t=Hi.baseLogTag+".checkForTestCampaign";try{var n=e||(yield this.iframeHelper.getDraftCampaignInfo());null==n?(ut.log(1,t,"No draft campaign found"),this.testDraftInfo=null):(ut.log(1,t,"Found draft campaign: ",n),this.testDraftInfo=n,null==this.testDraftInfo.draftId&&(this.testDraftInfo.draftType=te.DRAFT_CAMPAIGN_TPYES.WEB_PERSONALIZATON))}catch(n){ut.error(1,t,"Error getting test campaign",n)}}))}getData(e,t){return Fi(this,void 0,void 0,(function*(){const n=Hi.baseLogTag+".getData";null==t&&(ut.warn(1,n,"Moengage.onsite.getData called without a providing a callback."),t=()=>{});try{if(yield this.initializationPomise,null!=this.testDraftInfo){var i;ut.log(1,n,"Fetching test campaign: ",this.testDraftInfo),this.testDraftInfo.draftType===te.DRAFT_CAMPAIGN_TPYES.WEB_PERSONALIZATON&&(i=yield this.OnsiteApiClient.getDraftCampaign(this.testDraftInfo),t(null,{payload:i.payload,click:()=>{ut.log(1,n,"This is a test campaign")},imp:()=>{ut.log(1,n,"This is a test campaign")}}))}else{const i=yield yn.campaingsTagsStore.getItem(e);if(i){const o=yield Promise.all(i.map((e=>Bn(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):(ut.error(1,n,"Error fetching campaign payload"),t({message:"There was an error fetching data for this tag"},null))}else ut.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){ut.error(1,n,"Error getting campaign",i)}}))}registerCallback(e,t){return Fi(this,void 0,void 0,(function*(){var n=Hi.baseLogTag+".registerCallback";try{yield this.initializationPomise,null==this.onsiteSelfHandledTriggerListeners[e]?this.onsiteSelfHandledTriggerListeners[e]=[t]:this.onsiteSelfHandledTriggerListeners[e].push(t)}catch(t){ut.error(1,n,"Error setting callback for tag",e),ut.error(1,n,"Error stack:",t)}}))}handleSelfHandledCallback(e,t,n){return Fi(this,void 0,void 0,(function*(){var i=Hi.baseLogTag+".handleSelfHandledCallback";if(e.campaignContext=t.campaignContext,"JSON"===t.payloadType)try{t.payload=JSON.parse(t.payload);var a=Te(e,"triggerData.trigger_delay.delayInSeconds",0)||0;setTimeout((()=>{Pn(e,"WP"),n(null,{payload:t.payload,click:t=>{Dn(e,"WP",t)()},imp:On(e,"WP")})}),1e3*a)}catch(r){a=`Payload for campaign_id ${e.campaignId} is not a valid JSON`,ut.error(1,i,a),ut.error(1,i,"Payload provided:",t.payload),n({message:a},null)}else Pn(e,"WP"),n(null,{payload:t.payload,click:t=>{Dn(e,"WP",t)()},imp:On(e,"WP")})}))}syncCampaigns(){return Fi(this,void 0,void 0,(function*(){var e=Hi.baseLogTag+".syncCampaigns";try{(yield this.shouldClearMetaStorage())&&(yield yn.campaingsMetaStore.clear(),yield this.rebuildTagStore()),(yield this.shouldSaveRemoteCampaigns())&&(yield this.saveRemoteCampaigns())}catch(t){ut.error(1,e,"Error getting remote campaigns: ",t)}}))}shouldClearMetaStorage(){return Fi(this,void 0,void 0,(function*(){return(yield yn.serviceMetaStore.getItem(te.STORES.SERVICE_META.KEYS.LAST_FETCH_SDK_VERSION))!==Qe().getSdkVersion()}))}shouldSaveRemoteCampaigns(){var e;return Fi(this,void 0,void 0,(function*(){var t=Hi.baseLogTag+".shouldSaveRemoteCampaigns",n=yield yn.serviceMetaStore.getItem(te.STORES.SERVICE_META.KEYS.LAST_FETCH_SDK_VERSION),i=yield yn.serviceMetaStore.getItem(te.STORES.SERVICE_META.KEYS.LAST_META_CALL_TIME),a=(i=new Date(i),(new Date).getTime());return null==i||a-i>te.META_REFRESH_TIME||(ut.remoteLogTracking(1,"info",t,"Last fetch was less than 15 mins ago at ",i),n!==Qe().getSdkVersion()?(ut.remoteLogTracking(1,"info",t,"Version change detected. Will proceed to fetch latest campaigns"),!0):!(!(n=yield yn.serviceMetaStore.getItem(te.STORES.SERVICE_META.KEYS.UNIQUE_ID))||n===(null===(e=We.get(r.USER_DATA))||void 0===e?void 0:e.deviceUuid)||(ut.remoteLogTracking(1,"info",t,"Unique device id change detected. Will proceed to fetch latest campaigns"),0)))}))}saveRemoteCampaigns(){return Fi(this,void 0,void 0,(function*(){var e=Hi.baseLogTag+".saveRemoteCampaigns";yield yn.campaingsMetaStore.clear(),yield yn.exitIntentCampaignStore.clear();var t=yield this.OnsiteApiClient.getCampaignsMeta();null!=t&&(yield this.addCampaignsToDB(t.campaignsMeta),ut.log(1,e,"Inapp campaigns meta saved!")),yield Ti.pruneRemovedCampaigns(),yield Ti.removeStaleTriggeringPrimaryEventCampaigns(),yield yn.serviceMetaStore.setItem(te.STORES.SERVICE_META.KEYS.GLOBAL_DELAY,t.globalDelayBetweenInapps),yield yn.serviceMetaStore.setItem(te.STORES.SERVICE_META.KEYS.LAST_FETCH_SDK_VERSION,Qe().getSdkVersion())}))}addCampaignsToDB(e){return Fi(this,void 0,void 0,(function*(){var t=Hi.baseLogTag+".addCampaignsToDB";ut.log(1,t,`Adding/Updating ${e.length} campaigns in DB`,e.map((e=>e.campaignId)));try{yield Promise.all(e.map((e=>yn.campaingsMetaStore.setItem(e.campaignId,e)))),yield this.rebuildTagStore()}catch(e){ut.error(1,t,"Error saving remote campaigns:",e)}}))}rebuildTagStore(){return Fi(this,void 0,void 0,(function*(){var e=Hi.baseLogTag+".rebuildTagStore";try{yield yn.campaingsTagsStore.clear();var t=yield Un();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 yn.campaingsTagsStore.clear();for(const t in e)e.hasOwnProperty(t)&&n.push(yn.campaingsTagsStore.setItem(t,e[t]));yield Promise.all(n)}catch(t){ut.error(1,e,"Error updating tags store:",t)}}))}isExitIntentCampaignFound(e){return e.filter((e=>e.templateType!==An.SELF_HANDLED&&kn(e,_)))}prefetchExitIntentCampaigns(e){return Fi(this,void 0,void 0,(function*(){var t=Hi.baseLogTag+".prefetchExitIntentCampaigns";const n=yield Jt.createEvent("MOE_EXIT",[]),i=(yield Ln(e)).filter((e=>ei.getFilterResult(n,e)));if(!i||!i.length)return ut.log(1,t,"Exit intent campaign not eligible to prefetch"),!1;{const e=yield xn(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 yn.exitIntentCampaignStore.setItem(a,e),ut.log(1,t,"Exit intent campaign prefetched: "+a)):e.error&&e.reason&&(yield yn.exitIntentCampaignStore.setItem(a,e))}}}))}refresh(){return Fi(this,void 0,void 0,(function*(){$i.onsite.appId&&(yield Zi(),Qi())}))}sendDelayCampaignStats(){return Fi(this,void 0,void 0,(function*(){var e=Hi.baseLogTag+".sendDelayCampaignStats",t=Object.keys(this.displayManager.campaignRenderMap).filter((e=>!this.displayManager.campaignRenderMap[e].campaignRendered));0<t.length&&(ut.log(1,e,"Campaigns found:",t),this.funnelManager.delayDeliveryCampaignStats(this.displayManager.campaignRenderMap[t[0]].campaignMeta))}))}}function Ki(){var e,t;const n="pageChangeHandler";window.Moengage.pageChangeHandlerCallingTime=(new Date).getTime(),(()=>{var e;const t=window.Moengage;if(t.onsite){if(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,i=Object.keys(n.campaignRenderMap);t.onsite.sendDelayCampaignStats&&t.onsite.sendDelayCampaignStats(),i.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((()=>{qe()?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.resetListeners(),t.onsite.initializationPomise=null,t.onsite.initialize&&t.onsite.initialize()}})(),window.MoeFocusHandler&&window.MoeFocusHandler(),window.Moengage.shouldClearPrevEvents=(new Date).getTime(),Xt.clear(),Xt.clearListeners(),$i.track_page_view();var i=$i.onsite.triggerManager;0<(null===(e=null==i?void 0:i.exitIntentCampaigns)||void 0===e?void 0:e.length)&&qe()&&null!==(t=null==i?void 0:i.windowEventManager)&&void 0!==t&&t.onMobileScrollAndExit(i.onExit),nn.getWebSDKSettings().then((e=>{e.isDomainLevelStorage&&We.copyKeysFromCookie(),null!=e&&e.configs.isCardsModuleEnabled&&$i.cards&&($i.cards.checkCacheAndSaveRemote(pe),$i.cards.displayManager.closeIframe(),$i.cards.displayManager.addCardsInboxListener()),null!=e&&e.configs.isWebPersonalisationModuleEnabled&&(null!==(e=window.MoeWebP)&&void 0!==e&&e.getLiveExperiences(),ut.log(1,n,"webP sync function called"))})).catch((e=>{ut.error(1,n,"Error in getting Web SDK Settings. This might indicate that the App is blocked.")}))}Hi.baseLogTag="MoeOnsite",window[te.OSM_MODULE]=Hi,window.MoeOsm=(ut.log(1,"OsmFunctions","Osm Functions for tracking user behaviour"),{trackEvent:(e,t,n,i)=>(e=Oi(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=Oi(e))?window.Moengage.onsite.displayManager.clickTracker(e,"OSM",{widget_id:t})():Promise.resolve(),trackDismiss:(e,t=!1)=>(e=Oi(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 Gi{constructor(){this.getDeviceUniqueId=e=>{window.addEventListener(x,(t=>{t.detail.name===B.DEVICE_UUID&&(t=t.detail.data,e(t))}))}}onUpdateDeviceId(e){this.getDeviceUniqueId(e)}trackClick(e,t){return Gi.track("MOE_WEBP_MESSAGE_CLICKED",e,t)}trackImpression(e){return Gi.track("MOE_WEBP_MESSAGE_SHOWN",e)}static track(e,t,n){var i=Gi.baseLogTag+".track";if("string"==typeof t)try{t=JSON.parse(t)}catch(e){return void ut.error(2,i,"Error parsing JSON string:",e)}var a=t&&t.cid.split("_")[0];if(!a)return Promise.reject();try{return Qe()?(ut.log(1,i,e+": Event Tracked"),Qe().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){ut.error(2,i,"Failed Tracking expression",e)}}}Gi.baseLogTag="Web Personalisation Tracking";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())}))};const ji="MoEngage";let Yi=new mt,zi=new mt;const qi={getData:(e,t)=>{nn.getWebSDKSettings().then((n=>{Yi.p.then((n=>{n.getData(e,t)}))})).catch((e=>{}))},registerCallback:(e,t)=>{nn.getWebSDKSettings().then((n=>{Yi.p.then((n=>{n.registerCallback(e,t)}))})).catch((e=>{}))}};class $i{static callWebPush(e){const t=ji+".callWebPush";nn.getWebSDKSettings().then((n=>{var i,a,r,o,s,l,c;n.isConfigured?n.optInConfig.type===Nt.TYPE.SELF_HANDLED?(ut.log(1,t,"Starting web push functions"),null!=e&&(Be.setSoftAskConfig(e),i=Te(e,"soft_ask_display_callback",null),a=Te(e,"soft_ask_allow_callback",null),r=Te(e,"soft_ask_block_callback",null),o=Te(e,"hard_ask_allow_callback",null),s=Te(e,"hard_ask_dismiss_callback",null),l=Te(e,"hard_ask_block_callback",null),c=U,sn.addCallback(c.SOFT_ASK_SHOWN,i),sn.addCallback(c.SOFT_ASK_ALLOWED,a),sn.addCallback(c.SOFT_ASK_DISMISSED,r),sn.addCallback(c.HARD_ASK_ALLOWED,o),sn.addCallback(c.HARD_ASK_DISMISSED,s),sn.addCallback(c.HARD_ASK_DENIED,l)),Et.getInstance().then((e=>{new vn(n,e).callWebPush()}))):ut.warn(1,t,"This feature can only be used when you have chosed self-handled approach in the dashboard. You can check dashboard here:",z):ut.log(1,t,"Web push settings not configured on dashboard yet. To start web push subscriptions, please configure the settings on dashboard.")})).catch((e=>{ut.error(1,t,"Error in getting Web SDK Settings. This might indicate that the App is blocked.")}))}static showNotification(e){nn.getWebSDKSettings().then((t=>{Et.getInstance().then((n=>{new vn(t,n).showNotification(e)}))})).catch((e=>{}))}static getSdkVersion(){return"2.45.2"}static setDebugLevel(e){return Vi(this,void 0,void 0,(function*(){const t=ji+".setDebugLevel";try{"number"==typeof e&&(!Be.get().disableOnsite&&$i.onsite.setLogLevel&&$i.onsite.setLogLevel(e),nn.getWebSDKSettings().then((t=>{null!=t&&t.configs.isCardsModuleEnabled&&$i.cards&&$i.cards.setLogLevel(e),null!=t&&t.configs.isWebPersonalisationModuleEnabled&&window.MoeWebP&&window.MoeWebP.setLogLevel&&window.MoeWebP.setLogLevel(e),ut.setLogLevel(e,!0)})).catch((n=>{ut.setLogLevel(e,!0),ut.error(1,t,"Error in getting Web SDK Settings. This might indicate that the App is blocked.")})))}catch(e){ut.error(0,t,"Error changing log level:",e)}}))}static vitals(){var e=It.getSync();return{deviceUuid:e.deviceUuid,userDetails:e,pushToken:We.get(r.PUSH_TOKEN),softAskStatus:We.get(r.SOFT_ASK_STATUS),hardAskStatus:We.get(r.HARD_ASK_STATUS)}}static help(){var e=ji+".help";ut.log(0,e,"Moengage Dashboard - ",Y.MOE_DASHBOARD);for(const t in Y)Y.hasOwnProperty(t)&&ut.log(0,e,t,"-",Y[t])}static track_event(e,t){return Qt.track(e,t)}static add_unique_user_id(e){return Vi(this,void 0,void 0,(function*(){return yield fn.login(e)}))}static update_unique_user_id(e){return fn.updateUniqueId(e)}static add_user_attribute(e,t){return fn.addAttribute(e,t)}static add_first_name(e){return fn.addAttribute("first_name",e)}static add_last_name(e){return fn.addAttribute("last_name",e)}static add_email(e){return fn.addAttribute("email",e)}static add_mobile(e){return fn.addAttribute("mobile",e)}static add_user_name(e){return fn.addAttribute("name",e)}static add_gender(e){return fn.addAttribute("gender",e)}static add_birthday(e){return fn.addAttribute("birthday",e)}static destroy_session(){return $i.user.logout()}static call_web_push(e){$i.callWebPush(e)}static getBranch(){return"master"}static track_page_view(){return Qt.track(l,{timestamp:Number(Date.now())}),Qt.track(c,{timestamp:Number(Date.now())})}static handle_page_change(){Ki()}}$i.user=fn,$i.event=Qt,$i.device=class{static getUuid(){return We.get(r.USER_DATA).deviceUuid}static getPushToken(){return We.get(r.PUSH_TOKEN)}static getPermissionState(e){return new Promise(((t,n)=>{nn.getWebSDKSettings().then((i=>{Et.getInstance().then((a=>{new vn(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)}))}))}},$i.onsite=qi,$i.reports=zt.reports,$i.remoteLogs=zt,$i.web_p=new Gi;var Ji=()=>{};const Xi={track_event:Ji,add_user_attribute:Ji,add_first_name:Ji,add_last_name:Ji,add_email:Ji,add_mobile:Ji,add_user_name:Ji,add_gender:Ji,add_birthday:Ji,destroy_session:Ji,add_unique_user_id:Ji,moe_events:Ji,location_type_attribute:Ji,call_web_push:Ji,setDebugLevel:Ji};function Qi(){var e;null!==(e=null===(e=$i.onsite)||void 0===e?void 0:e.initData)&&void 0!==e&&e.appId||(e=Be.get(),$i.onsite=new Hi(e),Yi.res($i.onsite),null!==(e=$i.onsite)&&void 0!==e&&e.initialize())}function Zi(){var e;return Vi(this,void 0,void 0,(function*(){null!==(e=null===(e=$i.onsite)||void 0===e?void 0:e.initData)&&void 0!==e&&e.appId&&(ut.log(1,"Moengage.disableOnsiteApi","logging out from inapp module"),yield $i.onsite.logout(),Yi=new mt,$i.onsite=qi)}))}var ea=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 ta{static initialize(){return ea(this,void 0,void 0,(function*(){var e;return null==ta.ready&&(ta.campaignStore=_e.createInstance({driver:[_e.INDEXEDDB,_e.WEBSQL,_e.LOCALSTORAGE],name:de,storeName:ge.STORE_NAME}),ta.metaStore=_e.createInstance({driver:[_e.INDEXEDDB,_e.WEBSQL,_e.LOCALSTORAGE],name:de,storeName:ue.STORE_NAME}),e=[ta.campaignStore.ready(),ta.metaStore.ready()],ta.ready=Promise.all(e)),ta.ready}))}static clear(){return ea(this,void 0,void 0,(function*(){var e=ta.baseLogTag+".clear";try{yield ta.initialize(),yield Promise.all([ta.campaignStore.clear(),ta.metaStore.clear()]);var t=[ta.campaignStore.ready(),ta.metaStore.ready()];ta.ready=Promise.all(t)}catch(t){ut.error(1,e,"Error clearing cards stores:",t)}return ta.ready}))}}let na;function ia(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=Qe();return n&&0<n.initialised?(ut.error(1,t,"MoEngage Web SDK initialised multiple times. Please integrate the Web SDK only once!"),n):(ut.log(1,t,"Init data: ",e),"undefined"==typeof Promise?(ut.error(1,t,"Promises not supported"),Xi):e.app_id||e.appId?((n=oa())&&(e=Object.assign({},e,n)),Be.save(e),ra().then((()=>{$t.broadcastToWindow({topic:x,name:B.MOE_INIT,data:Be.get()}),$e()===ye.WEB&&aa(),ut.setLogLevel(Be.get().debugLevel),ut.log(1,t,"Script loaded!"),ut.customLabel(1,t,"SDK Version","2.45.2"),0<Be.get().debugLevel&&(ut.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."),ut.warn(1,t,"Please initialize with debugLevel as",0,"when using on your production environment.")),sa().then((()=>{$t.broadcastToWindow({topic:x,name:B.MOE_INIT_COMPLETED})}))})),e=window.moengage_object||"Moengage",window[e]=$i,$i):(ut.error(1,t,"App Id not specified. Please check docs page to complete the integration - ",Y.WEBSDK_DOCS),Xi))}ut.error(1,t,"Bot detected, Can't initialise the MoEngage Web SDK")}ta.baseLogTag="MOE_CARDS_STORES";const aa=()=>{_e.createInstance({driver:[_e.INDEXEDDB,_e.WEBSQL,_e.LOCALSTORAGE],name:J,storeName:X}).clear()},ra=()=>new Promise((e=>{"complete"!==window.document.readyState?window.addEventListener("load",(()=>{e(!0)})):e(!0)}));window&&(window.moe=ia,window.moeBannerText="banner",window[ee]=Xt);const oa=()=>{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)&&(ut.log(1,".isSegmentDataFound","Data found for segment initialisation",i),i)}catch(e){return!1}},sa=()=>{const e="Initialization";return new Promise((t=>nn.getWebSDKSettings().then((n=>(dt.setRemoteLogging(n),n.isDomainLevelStorage&&(We.isSharedWithCookie=!0,We.copyKeysFromCookie()),pn.addBeforeUnloadListeners(n),(n.configs.isBatchingEnabled||n.configs.remoteLogTracking)&&(zt.init(n),ut.log(1,e,"Enabled Batching for "+(n.configs.isBatchingEnabled?"Event Tracking":"")+(n.configs.remoteLogTracking?", Remote Logs Tracking":""))),It.get().then((i=>{if(un.get().deviceToLogout===i.deviceUuid)return ut.remoteLogTracking(1,"info",e,"User was not able to logout last time. Completing the logout now and starting new session."),$i.user.logout();i.deviceAdded&&nn.onDeviceAdd.res(),n.isPushSubBilling&&ut.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 vt;(new pn).onWindowVisibilityChange(a.handleBrowserInactivity),ut.customLabel(1,e,"Device UUID",i.deviceUuid),ut.customLabel(1,e,"Device Added",i.deviceAdded),$t.broadcastToWindow({topic:x,name:B.SETTINGS_FETCHED,data:n}),$t.broadcastToWindow({topic:x,name:B.DEVICE_UUID,data:i.deviceUuid}),n.isPushSubBilling||i.deviceAdded||nn.deviceAdd(),$i.track_page_view(),on.clear(r.Q.DEVICE),on.clear(r.Q.REPORT),Be.get().enableSPA&&!na&&ca(),Et.getInstance().then((t=>{var i,a;const o=!Be.get().disableWebPush&&new vn(n,t);var s,l=!(null!==(i=null===(l=window.MoeWebP)||void 0===l?void 0:l.isEditorModeEnabled)&&void 0!==i&&i.call(l));o&&o.isWebPushEnabled()&&l?(0<=[Nt.TYPE.ONE_CLICK,Nt.TYPE.TWO_STEP].indexOf(n.optInConfig.type)?o.callWebPush():(ut.log(1,e,"Self handled setting. Will show opt-in on manual invocation, if required."),o.getPermissionState().then((t=>{var n=We.get(r.PUSH_TOKEN);(t===Zt.GRANTED||null!=n&&t===Zt.DENIED)&&(t===Zt.GRANTED&&ut.log(1,e,"Notification permission already granted. Proceeding to subscribe the user"),o.callWebPush())})).catch((t=>{ut.warn(1,e,"Cannot get permission state: ",t)}))),o.trackPushOptedDeviceAttribute()):vn.SUPPORTED_BROWSERS.indexOf(t.name)<0?ut.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"):ut.warn(1,e,"Web push feature not enabled for current environment"),!Be.get().disableOnsite&&l?nn.onDeviceAdd.p.then((()=>{Qi()})):ut.warn(1,e,"Onsite is disabled in this page since `disableOnsite: true` is passed during initialization."),null!=n&&n.configs.isCardsModuleEnabled&&null!==(a=Be.get().cards)&&void 0!==a&&a.enable&&l?(s=n,Sn.loadModule(ne.CARDS).then((e=>{zi.res(e),e.initialize(s),$i.cards=e})).catch((e=>{zi.rej(e)}))):ta.clear(),la()})),t(!0)}))))).catch((n=>{ut.error(1,e,"Error in getting Web SDK Settings. This might indicate that the App is blocked."),t(!1)}))))},la=()=>{const e="Moengage.clearWindowQ";ra().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++){ut.remoteLogTracking(1,"info",e,"Method called before SDK downloaded:",[i[t].f],i[t].a);var n=i[t].f;"onsite.getData"===n?$i.onsite.getData(...i[t].a):"onsite.registerCallback"===n?$i.onsite.registerCallback(...i[t].a):null!=$i[i[t].f]&&$i[i[t].f].apply(null,i[t].a)}i=[]}}catch(t){ut.error(1,e,t)}}))},ca=()=>{const e="startSpaUrlHandler";let t=document.location.href;(()=>{na=!0,ut.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,ut.log(1,e,"URL Change detected",t),Ki())}))}));i.observe(n,{childList:!0,subtree:!0})})()},da={clearWindowQ:la,startSpaUrlHandler:ca,isSegmentDataFound:oa,clearEventsFromIDB:aa,moeInit:ia,windowLoaded:ra}})()})();