diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c178c48..667c49cc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,8 +1,8 @@ # Change Log All notable changes to this project will be documented in this file. -## [1.7.4] - 3 May, 2024 -- Cross-site scripting (XSS) bugfix. +## [1.7.4] - 17 May, 2024 +- Fixes a issue in path for installation of Service worker for shopify. ## [1.7.3] - 3 Apr, 2024 - Fixes a issue in release pipeline of Service worker. diff --git a/clevertap.js b/clevertap.js index 55e7efad..9ea36e7a 100644 --- a/clevertap.js +++ b/clevertap.js @@ -4,317 +4,6 @@ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.clevertap = factory()); }(this, (function () { 'use strict'; - function _typeof(obj) { - "@babel/helpers - typeof"; - - if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { - _typeof = function (obj) { - return typeof obj; - }; - } else { - _typeof = function (obj) { - return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; - }; - } - - return _typeof(obj); - } - - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } - } - - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - if (staticProps) _defineProperties(Constructor, staticProps); - return Constructor; - } - - function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; - } - - function ownKeys(object, enumerableOnly) { - var keys = Object.keys(object); - - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); - keys.push.apply(keys, symbols); - } - - return keys; - } - - function _objectSpread2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = arguments[i] != null ? arguments[i] : {}; - - if (i % 2) { - ownKeys(Object(source), true).forEach(function (key) { - _defineProperty(target, key, source[key]); - }); - } else if (Object.getOwnPropertyDescriptors) { - Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); - } else { - ownKeys(Object(source)).forEach(function (key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - } - - return target; - } - - function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function"); - } - - subClass.prototype = Object.create(superClass && superClass.prototype, { - constructor: { - value: subClass, - writable: true, - configurable: true - } - }); - if (superClass) _setPrototypeOf(subClass, superClass); - } - - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return _getPrototypeOf(o); - } - - function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { - o.__proto__ = p; - return o; - }; - - return _setPrototypeOf(o, p); - } - - function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - - try { - Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); - return true; - } catch (e) { - return false; - } - } - - function _construct(Parent, args, Class) { - if (_isNativeReflectConstruct()) { - _construct = Reflect.construct; - } else { - _construct = function _construct(Parent, args, Class) { - var a = [null]; - a.push.apply(a, args); - var Constructor = Function.bind.apply(Parent, a); - var instance = new Constructor(); - if (Class) _setPrototypeOf(instance, Class.prototype); - return instance; - }; - } - - return _construct.apply(null, arguments); - } - - function _isNativeFunction(fn) { - return Function.toString.call(fn).indexOf("[native code]") !== -1; - } - - function _wrapNativeSuper(Class) { - var _cache = typeof Map === "function" ? new Map() : undefined; - - _wrapNativeSuper = function _wrapNativeSuper(Class) { - if (Class === null || !_isNativeFunction(Class)) return Class; - - if (typeof Class !== "function") { - throw new TypeError("Super expression must either be null or a function"); - } - - if (typeof _cache !== "undefined") { - if (_cache.has(Class)) return _cache.get(Class); - - _cache.set(Class, Wrapper); - } - - function Wrapper() { - return _construct(Class, arguments, _getPrototypeOf(this).constructor); - } - - Wrapper.prototype = Object.create(Class.prototype, { - constructor: { - value: Wrapper, - enumerable: false, - writable: true, - configurable: true - } - }); - return _setPrototypeOf(Wrapper, Class); - }; - - return _wrapNativeSuper(Class); - } - - function _assertThisInitialized(self) { - if (self === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return self; - } - - function _possibleConstructorReturn(self, call) { - if (call && (typeof call === "object" || typeof call === "function")) { - return call; - } - - return _assertThisInitialized(self); - } - - function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); - - return function _createSuperInternal() { - var Super = _getPrototypeOf(Derived), - result; - - if (hasNativeReflectConstruct) { - var NewTarget = _getPrototypeOf(this).constructor; - - result = Reflect.construct(Super, arguments, NewTarget); - } else { - result = Super.apply(this, arguments); - } - - return _possibleConstructorReturn(this, result); - }; - } - - function _toConsumableArray(arr) { - return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); - } - - function _arrayWithoutHoles(arr) { - if (Array.isArray(arr)) return _arrayLikeToArray(arr); - } - - function _iterableToArray(iter) { - if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); - } - - function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); - } - - function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - - return arr2; - } - - function _nonIterableSpread() { - throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - function _createForOfIteratorHelper(o, allowArrayLike) { - var it; - - if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { - if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { - if (it) o = it; - var i = 0; - - var F = function () {}; - - return { - s: F, - n: function () { - if (i >= o.length) return { - done: true - }; - return { - done: false, - value: o[i++] - }; - }, - e: function (e) { - throw e; - }, - f: F - }; - } - - throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); - } - - var normalCompletion = true, - didErr = false, - err; - return { - s: function () { - it = o[Symbol.iterator](); - }, - n: function () { - var step = it.next(); - normalCompletion = step.done; - return step; - }, - e: function (e) { - didErr = true; - err = e; - }, - f: function () { - try { - if (!normalCompletion && it.return != null) it.return(); - } finally { - if (didErr) throw err; - } - } - }; - } - var id = 0; function _classPrivateFieldLooseKey(name) { @@ -329,9 +18,9 @@ return receiver; } - var TARGET_DOMAIN = 'clevertap-prod.com'; - var TARGET_PROTOCOL = 'https:'; - var DEFAULT_REGION = 'eu1'; + const TARGET_DOMAIN = 'clevertap-prod.com'; + const TARGET_PROTOCOL = 'https:'; + const DEFAULT_REGION = 'eu1'; var _accountId = _classPrivateFieldLooseKey("accountId"); @@ -343,17 +32,14 @@ var _token = _classPrivateFieldLooseKey("token"); - var Account = /*#__PURE__*/function () { - function Account() { - var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}, - id = _ref.id; - - var region = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; - var targetDomain = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : TARGET_DOMAIN; - var token = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ''; - - _classCallCheck(this, Account); - + class Account { + constructor() { + let { + id + } = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + let region = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; + let targetDomain = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : TARGET_DOMAIN; + let token = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : ''; Object.defineProperty(this, _accountId, { writable: true, value: void 0 @@ -389,171 +75,151 @@ } } - _createClass(Account, [{ - key: "id", - get: function get() { - return _classPrivateFieldLooseBase(this, _accountId)[_accountId]; - }, - set: function set(accountId) { - _classPrivateFieldLooseBase(this, _accountId)[_accountId] = accountId; - } - }, { - key: "region", - get: function get() { - return _classPrivateFieldLooseBase(this, _region)[_region]; - }, - set: function set(region) { - _classPrivateFieldLooseBase(this, _region)[_region] = region; - } - }, { - key: "dcSDKVersion", - get: function get() { - return _classPrivateFieldLooseBase(this, _dcSdkversion)[_dcSdkversion]; - }, - set: function set(dcSDKVersion) { - _classPrivateFieldLooseBase(this, _dcSdkversion)[_dcSdkversion] = dcSDKVersion; - } - }, { - key: "targetDomain", - get: function get() { - return _classPrivateFieldLooseBase(this, _targetDomain)[_targetDomain]; - }, - set: function set(targetDomain) { - _classPrivateFieldLooseBase(this, _targetDomain)[_targetDomain] = targetDomain; - } - }, { - key: "token", - get: function get() { - return _classPrivateFieldLooseBase(this, _token)[_token]; - }, - set: function set(token) { - _classPrivateFieldLooseBase(this, _token)[_token] = token; - } - }, { - key: "finalTargetDomain", - get: function get() { - if (this.region) { - return "".concat(this.region, ".").concat(this.targetDomain); - } else { - if (this.targetDomain === TARGET_DOMAIN) { - return "".concat(DEFAULT_REGION, ".").concat(this.targetDomain); - } + get id() { + return _classPrivateFieldLooseBase(this, _accountId)[_accountId]; + } + + set id(accountId) { + _classPrivateFieldLooseBase(this, _accountId)[_accountId] = accountId; + } + + get region() { + return _classPrivateFieldLooseBase(this, _region)[_region]; + } + + set region(region) { + _classPrivateFieldLooseBase(this, _region)[_region] = region; + } + + get dcSDKVersion() { + return _classPrivateFieldLooseBase(this, _dcSdkversion)[_dcSdkversion]; + } + + set dcSDKVersion(dcSDKVersion) { + _classPrivateFieldLooseBase(this, _dcSdkversion)[_dcSdkversion] = dcSDKVersion; + } + + get targetDomain() { + return _classPrivateFieldLooseBase(this, _targetDomain)[_targetDomain]; + } + + set targetDomain(targetDomain) { + _classPrivateFieldLooseBase(this, _targetDomain)[_targetDomain] = targetDomain; + } + + get token() { + return _classPrivateFieldLooseBase(this, _token)[_token]; + } + + set token(token) { + _classPrivateFieldLooseBase(this, _token)[_token] = token; + } + + get finalTargetDomain() { + if (this.region) { + return "".concat(this.region, ".").concat(this.targetDomain); + } else { + if (this.targetDomain === TARGET_DOMAIN) { + return "".concat(DEFAULT_REGION, ".").concat(this.targetDomain); + } + + return this.targetDomain; + } + } + + get dataPostPEURL() { + return "".concat(TARGET_PROTOCOL, "//").concat(this.finalTargetDomain, "/defineVars"); + } - return this.targetDomain; - } - } - }, { - key: "dataPostPEURL", - get: function get() { - return "".concat(TARGET_PROTOCOL, "//").concat(this.finalTargetDomain, "/defineVars"); - } - }, { - key: "dataPostURL", - get: function get() { - return "".concat(TARGET_PROTOCOL, "//").concat(this.finalTargetDomain, "/a?t=96"); - } - }, { - key: "recorderURL", - get: function get() { - return "".concat(TARGET_PROTOCOL, "//").concat(this.finalTargetDomain, "/r?r=1"); - } - }, { - key: "emailURL", - get: function get() { - return "".concat(TARGET_PROTOCOL, "//").concat(this.finalTargetDomain, "/e?r=1"); - } - }]); - - return Account; - }(); - - var unsupportedKeyCharRegex = new RegExp('^\\s+|\\\.|\:|\\\$|\'|\"|\\\\|\\s+$', 'g'); - var unsupportedValueCharRegex = new RegExp("^\\s+|\'|\"|\\\\|\\s+$", 'g'); - var singleQuoteRegex = new RegExp('\'', 'g'); - var CLEAR = 'clear'; - var CHARGED_ID = 'Charged ID'; - var CHARGEDID_COOKIE_NAME = 'WZRK_CHARGED_ID'; - var GCOOKIE_NAME = 'WZRK_G'; - var KCOOKIE_NAME = 'WZRK_K'; - var CAMP_COOKIE_NAME = 'WZRK_CAMP'; - var CAMP_COOKIE_G = 'WZRK_CAMP_G'; // cookie for storing campaign details against guid - - var SCOOKIE_PREFIX = 'WZRK_S'; - var SCOOKIE_EXP_TIME_IN_SECS = 60 * 20; // 20 mins - - var EV_COOKIE = 'WZRK_EV'; - var META_COOKIE = 'WZRK_META'; - var PR_COOKIE = 'WZRK_PR'; - var ARP_COOKIE = 'WZRK_ARP'; - var LCOOKIE_NAME = 'WZRK_L'; - var GLOBAL = 'global'; // used for email unsubscribe also - var DISPLAY = 'display'; - var WEBPUSH_LS_KEY = 'WZRK_WPR'; - var OPTOUT_KEY = 'optOut'; - var CT_OPTOUT_KEY = 'ct_optout'; - var OPTOUT_COOKIE_ENDSWITH = ':OO'; - var USEIP_KEY = 'useIP'; - var LRU_CACHE = 'WZRK_X'; - var LRU_CACHE_SIZE = 100; - var IS_OUL = 'isOUL'; - var EVT_PUSH = 'push'; - var EVT_PING = 'ping'; - var COOKIE_EXPIRY = 86400 * 365; // 1 Year in seconds - - var MAX_TRIES = 200; // API tries - - var FIRST_PING_FREQ_IN_MILLIS = 2 * 60 * 1000; // 2 mins - - var CONTINUOUS_PING_FREQ_IN_MILLIS = 5 * 60 * 1000; // 5 mins - - var GROUP_SUBSCRIPTION_REQUEST_ID = '2'; - var categoryLongKey = 'cUsY'; - var WZRK_PREFIX = 'wzrk_'; - var WZRK_ID = 'wzrk_id'; - var NOTIFICATION_VIEWED = 'Notification Viewed'; - var NOTIFICATION_CLICKED = 'Notification Clicked'; - var FIRE_PUSH_UNREGISTERED = 'WZRK_FPU'; - var PUSH_SUBSCRIPTION_DATA = 'WZRK_PSD'; // PUSH SUBSCRIPTION DATA FOR REGISTER/UNREGISTER TOKEN - - var COMMAND_INCREMENT = '$incr'; - var COMMAND_DECREMENT = '$decr'; - var COMMAND_SET = '$set'; - var COMMAND_ADD = '$add'; - var COMMAND_REMOVE = '$remove'; - var COMMAND_DELETE = '$delete'; - var WEBINBOX_CONFIG = 'WZRK_INBOX_CONFIG'; - var WEBINBOX = 'WZRK_INBOX'; - var MAX_INBOX_MSG = 15; - var VARIABLES = 'WZRK_PE'; - var PUSH_DELAY_MS = 1000; - var MAX_DELAY_FREQUENCY = 1000 * 60 * 10; - var WZRK_FETCH = 'wzrk_fetch'; - var WIZ_IFRAME = 'wiz-iframe'; - var WIZ_IFRAME_INTENT = 'wiz-iframe-intent'; - var ADJUST_IFRAME_HEIGHT = 'adjustIFrameHeight'; - var UPDATE_HEIGHT = 'update height'; - var GET_NOTIFICATION = 'getnotif'; - var EVENT = 'Event'; - var PROFILE = 'Profile'; - var OUL = 'OUL'; - var CLOSE_BOX_POPUP = 'closeBoxPopUp'; - var CLOSE_BANNER_POPUP = 'closeBannerPopUp'; - var GET_NOTIFICATION_DATA = 'getnotifData'; - var CLOSE_INTERSTITIAL_POPUP = 'closeInterstitialPopUp'; - var SYSTEM_EVENTS = ['Stayed', 'UTM Visited', 'App Launched', 'Notification Sent', NOTIFICATION_VIEWED, NOTIFICATION_CLICKED]; - - var isString = function isString(input) { + get dataPostURL() { + return "".concat(TARGET_PROTOCOL, "//").concat(this.finalTargetDomain, "/a?t=96"); + } + + get recorderURL() { + return "".concat(TARGET_PROTOCOL, "//").concat(this.finalTargetDomain, "/r?r=1"); + } + + get emailURL() { + return "".concat(TARGET_PROTOCOL, "//").concat(this.finalTargetDomain, "/e?r=1"); + } + + } + + const unsupportedKeyCharRegex = new RegExp('^\\s+|\\\.|\:|\\\$|\'|\"|\\\\|\\s+$', 'g'); + const unsupportedValueCharRegex = new RegExp("^\\s+|\'|\"|\\\\|\\s+$", 'g'); + const singleQuoteRegex = new RegExp('\'', 'g'); + const CLEAR = 'clear'; + const CHARGED_ID = 'Charged ID'; + const CHARGEDID_COOKIE_NAME = 'WZRK_CHARGED_ID'; + const GCOOKIE_NAME = 'WZRK_G'; + const KCOOKIE_NAME = 'WZRK_K'; + const CAMP_COOKIE_NAME = 'WZRK_CAMP'; + const CAMP_COOKIE_G = 'WZRK_CAMP_G'; // cookie for storing campaign details against guid + + const SCOOKIE_PREFIX = 'WZRK_S'; + const SCOOKIE_EXP_TIME_IN_SECS = 60 * 20; // 20 mins + + const EV_COOKIE = 'WZRK_EV'; + const META_COOKIE = 'WZRK_META'; + const PR_COOKIE = 'WZRK_PR'; + const ARP_COOKIE = 'WZRK_ARP'; + const LCOOKIE_NAME = 'WZRK_L'; + const GLOBAL = 'global'; // used for email unsubscribe also + const DISPLAY = 'display'; + const WEBPUSH_LS_KEY = 'WZRK_WPR'; + const OPTOUT_KEY = 'optOut'; + const CT_OPTOUT_KEY = 'ct_optout'; + const OPTOUT_COOKIE_ENDSWITH = ':OO'; + const USEIP_KEY = 'useIP'; + const LRU_CACHE = 'WZRK_X'; + const LRU_CACHE_SIZE = 100; + const IS_OUL = 'isOUL'; + const EVT_PUSH = 'push'; + const EVT_PING = 'ping'; + const COOKIE_EXPIRY = 86400 * 365; // 1 Year in seconds + + const MAX_TRIES = 200; // API tries + + const FIRST_PING_FREQ_IN_MILLIS = 2 * 60 * 1000; // 2 mins + + const CONTINUOUS_PING_FREQ_IN_MILLIS = 5 * 60 * 1000; // 5 mins + + const GROUP_SUBSCRIPTION_REQUEST_ID = '2'; + const categoryLongKey = 'cUsY'; + const WZRK_PREFIX = 'wzrk_'; + const WZRK_ID = 'wzrk_id'; + const NOTIFICATION_VIEWED = 'Notification Viewed'; + const NOTIFICATION_CLICKED = 'Notification Clicked'; + const FIRE_PUSH_UNREGISTERED = 'WZRK_FPU'; + const PUSH_SUBSCRIPTION_DATA = 'WZRK_PSD'; // PUSH SUBSCRIPTION DATA FOR REGISTER/UNREGISTER TOKEN + + const COMMAND_INCREMENT = '$incr'; + const COMMAND_DECREMENT = '$decr'; + const COMMAND_SET = '$set'; + const COMMAND_ADD = '$add'; + const COMMAND_REMOVE = '$remove'; + const COMMAND_DELETE = '$delete'; + const WEBINBOX_CONFIG = 'WZRK_INBOX_CONFIG'; + const WEBINBOX = 'WZRK_INBOX'; + const MAX_INBOX_MSG = 15; + const VARIABLES = 'WZRK_PE'; + const PUSH_DELAY_MS = 1000; + const MAX_DELAY_FREQUENCY = 1000 * 60 * 10; + const WZRK_FETCH = 'wzrk_fetch'; + const SYSTEM_EVENTS = ['Stayed', 'UTM Visited', 'App Launched', 'Notification Sent', NOTIFICATION_VIEWED, NOTIFICATION_CLICKED]; + + const isString = input => { return typeof input === 'string' || input instanceof String; }; - var isObject = function isObject(input) { + const isObject = input => { // TODO: refine return Object.prototype.toString.call(input) === '[object Object]'; }; - var isDateObject = function isDateObject(input) { - return _typeof(input) === 'object' && input instanceof Date; + const isDateObject = input => { + return typeof input === 'object' && input instanceof Date; }; - var isObjectEmpty = function isObjectEmpty(obj) { - for (var prop in obj) { + const isObjectEmpty = obj => { + for (const prop in obj) { if (obj.hasOwnProperty(prop)) { return false; } @@ -561,26 +227,26 @@ return true; }; - var isConvertibleToNumber = function isConvertibleToNumber(n) { + const isConvertibleToNumber = n => { return !isNaN(parseFloat(n)) && isFinite(n); }; - var isNumber = function isNumber(n) { + const isNumber = n => { return /^-?[\d.]+(?:e-?\d+)?$/.test(n) && typeof n === 'number'; }; - var isValueValid = function isValueValid(value) { + const isValueValid = value => { if (value === null || value === undefined || value === 'undefined') { return false; } return true; }; - var removeUnsupportedChars = function removeUnsupportedChars(o, logger) { + const removeUnsupportedChars = (o, logger) => { // keys can't be greater than 1024 chars, values can't be greater than 1024 chars - if (_typeof(o) === 'object') { - for (var key in o) { + if (typeof o === 'object') { + for (const key in o) { if (o.hasOwnProperty(key)) { - var sanitizedVal = removeUnsupportedChars(o[key], logger); - var sanitizedKey = void 0; + const sanitizedVal = removeUnsupportedChars(o[key], logger); + let sanitizedKey; sanitizedKey = sanitize(key, unsupportedKeyCharRegex); if (sanitizedKey.length > 1024) { @@ -593,7 +259,7 @@ } } } else { - var val; + let val; if (isString(o)) { val = sanitize(o, unsupportedValueCharRegex); @@ -611,324 +277,301 @@ return o; }; - var sanitize = function sanitize(input, regex) { + const sanitize = (input, regex) => { return input.replace(regex, ''); }; - var getToday = function getToday() { - var today = new Date(); + const getToday = () => { + const today = new Date(); return today.getFullYear() + '' + today.getMonth() + '' + today.getDay(); }; - var getNow = function getNow() { + const getNow = () => { return Math.floor(new Date().getTime() / 1000); }; - var convertToWZRKDate = function convertToWZRKDate(dateObj) { + const convertToWZRKDate = dateObj => { return '$D_' + Math.round(dateObj.getTime() / 1000); }; - var setDate = function setDate(dt) { + const setDate = dt => { // expecting yyyymmdd format either as a number or a string if (isDateValid(dt)) { return '$D_' + dt; } }; - var isDateValid = function isDateValid(date) { - var matches = /^(\d{4})(\d{2})(\d{2})$/.exec(date); + const isDateValid = date => { + const matches = /^(\d{4})(\d{2})(\d{2})$/.exec(date); if (matches == null) return false; - var d = matches[3]; - var m = matches[2] - 1; - var y = matches[1]; - var composedDate = new Date(y, m, d); // eslint-disable-next-line eqeqeq + const d = matches[3]; + const m = matches[2] - 1; + const y = matches[1]; + const composedDate = new Date(y, m, d); // eslint-disable-next-line eqeqeq return composedDate.getDate() == d && composedDate.getMonth() == m && composedDate.getFullYear() == y; }; - var StorageManager = /*#__PURE__*/function () { - function StorageManager() { - _classCallCheck(this, StorageManager); - } + class StorageManager { + static save(key, value) { + if (!key || !value) { + return false; + } - _createClass(StorageManager, null, [{ - key: "save", - value: function save(key, value) { - if (!key || !value) { - return false; - } + if (this._isLocalStorageSupported()) { + localStorage.setItem(key, typeof value === 'string' ? value : JSON.stringify(value)); + return true; + } + } - if (this._isLocalStorageSupported()) { - localStorage.setItem(key, typeof value === 'string' ? value : JSON.stringify(value)); - return true; - } + static read(key) { + if (!key) { + return false; } - }, { - key: "read", - value: function read(key) { - if (!key) { - return false; - } - var data = null; + let data = null; - if (this._isLocalStorageSupported()) { - data = localStorage.getItem(key); - } + if (this._isLocalStorageSupported()) { + data = localStorage.getItem(key); + } - if (data != null) { - try { - data = JSON.parse(data); - } catch (e) {} - } + if (data != null) { + try { + data = JSON.parse(data); + } catch (e) {} + } - return data; + return data; + } + + static remove(key) { + if (!key) { + return false; } - }, { - key: "remove", - value: function remove(key) { - if (!key) { - return false; - } - if (this._isLocalStorageSupported()) { - localStorage.removeItem(key); - return true; - } + if (this._isLocalStorageSupported()) { + localStorage.removeItem(key); + return true; } - }, { - key: "removeCookie", - value: function removeCookie(name, domain) { - var cookieStr = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; + } - if (domain) { - cookieStr = cookieStr + ' domain=' + domain + '; path=/'; - } + static removeCookie(name, domain) { + let cookieStr = name + '=; expires=Thu, 01 Jan 1970 00:00:01 GMT;'; - document.cookie = cookieStr; + if (domain) { + cookieStr = cookieStr + ' domain=' + domain + '; path=/'; } - }, { - key: "createCookie", - value: function createCookie(name, value, seconds, domain) { - var expires = ''; - var domainStr = ''; - if (seconds) { - var date = new Date(); - date.setTime(date.getTime() + seconds * 1000); - expires = '; expires=' + date.toGMTString(); - } + document.cookie = cookieStr; + } - if (domain) { - domainStr = '; domain=' + domain; - } + static createCookie(name, value, seconds, domain) { + let expires = ''; + let domainStr = ''; + + if (seconds) { + const date = new Date(); + date.setTime(date.getTime() + seconds * 1000); + expires = '; expires=' + date.toGMTString(); + } - value = encodeURIComponent(value); - document.cookie = name + '=' + value + expires + domainStr + '; path=/'; + if (domain) { + domainStr = '; domain=' + domain; } - }, { - key: "readCookie", - value: function readCookie(name) { - var nameEQ = name + '='; - var ca = document.cookie.split(';'); - for (var idx = 0; idx < ca.length; idx++) { - var c = ca[idx]; + value = encodeURIComponent(value); + document.cookie = name + '=' + value + expires + domainStr + '; path=/'; + } - while (c.charAt(0) === ' ') { - c = c.substring(1, c.length); - } // eslint-disable-next-line eqeqeq + static readCookie(name) { + const nameEQ = name + '='; + const ca = document.cookie.split(';'); + for (let idx = 0; idx < ca.length; idx++) { + let c = ca[idx]; - if (c.indexOf(nameEQ) == 0) { - return decodeURIComponent(c.substring(nameEQ.length, c.length)); - } - } + while (c.charAt(0) === ' ') { + c = c.substring(1, c.length); + } // eslint-disable-next-line eqeqeq - return null; + + if (c.indexOf(nameEQ) == 0) { + return decodeURIComponent(c.substring(nameEQ.length, c.length)); + } } - }, { - key: "_isLocalStorageSupported", - value: function _isLocalStorageSupported() { - return 'localStorage' in window && window.localStorage !== null && typeof window.localStorage.setItem === 'function'; + + return null; + } + + static _isLocalStorageSupported() { + return 'localStorage' in window && window.localStorage !== null && typeof window.localStorage.setItem === 'function'; + } + + static saveToLSorCookie(property, value) { + if (value == null) { + return; } - }, { - key: "saveToLSorCookie", - value: function saveToLSorCookie(property, value) { - if (value == null) { - return; - } - try { - if (this._isLocalStorageSupported()) { - this.save(property, encodeURIComponent(JSON.stringify(value))); + try { + if (this._isLocalStorageSupported()) { + this.save(property, encodeURIComponent(JSON.stringify(value))); + } else { + if (property === GCOOKIE_NAME) { + this.createCookie(property, encodeURIComponent(value), 0, window.location.hostname); } else { - if (property === GCOOKIE_NAME) { - this.createCookie(property, encodeURIComponent(value), 0, window.location.hostname); - } else { - this.createCookie(property, encodeURIComponent(JSON.stringify(value)), 0, window.location.hostname); - } + this.createCookie(property, encodeURIComponent(JSON.stringify(value)), 0, window.location.hostname); } + } - $ct.globalCache[property] = value; - } catch (e) {} + $ct.globalCache[property] = value; + } catch (e) {} + } + + static readFromLSorCookie(property) { + let data; + + if ($ct.globalCache.hasOwnProperty(property)) { + return $ct.globalCache[property]; } - }, { - key: "readFromLSorCookie", - value: function readFromLSorCookie(property) { - var data; - if ($ct.globalCache.hasOwnProperty(property)) { - return $ct.globalCache[property]; - } + if (this._isLocalStorageSupported()) { + data = this.read(property); + } else { + data = this.readCookie(property); + } - if (this._isLocalStorageSupported()) { - data = this.read(property); - } else { - data = this.readCookie(property); - } + if (data !== null && data !== undefined && !(typeof data.trim === 'function' && data.trim() === '')) { + let value; - if (data !== null && data !== undefined && !(typeof data.trim === 'function' && data.trim() === '')) { - var value; + try { + value = JSON.parse(decodeURIComponent(data)); + } catch (err) { + value = decodeURIComponent(data); + } - try { - value = JSON.parse(decodeURIComponent(data)); - } catch (err) { - value = decodeURIComponent(data); - } + $ct.globalCache[property] = value; + return value; + } + } - $ct.globalCache[property] = value; - return value; - } - } - }, { - key: "createBroadCookie", - value: function createBroadCookie(name, value, seconds, domain) { - // sets cookie on the base domain. e.g. if domain is baz.foo.bar.com, set cookie on ".bar.com" - // To update an existing "broad domain" cookie, we need to know what domain it was actually set on. - // since a retrieved cookie never tells which domain it was set on, we need to set another test cookie - // to find out which "broadest" domain the cookie was set on. Then delete the test cookie, and use that domain - // for updating the actual cookie. - if (domain) { - var broadDomain = $ct.broadDomain; - - if (broadDomain == null) { - // if we don't know the broadDomain yet, then find out - var domainParts = domain.split('.'); - var testBroadDomain = ''; - - for (var idx = domainParts.length - 1; idx >= 0; idx--) { - if (idx === 0) { - testBroadDomain = domainParts[idx] + testBroadDomain; - } else { - testBroadDomain = '.' + domainParts[idx] + testBroadDomain; - } // only needed if the cookie already exists and needs to be updated. See note above. + static createBroadCookie(name, value, seconds, domain) { + // sets cookie on the base domain. e.g. if domain is baz.foo.bar.com, set cookie on ".bar.com" + // To update an existing "broad domain" cookie, we need to know what domain it was actually set on. + // since a retrieved cookie never tells which domain it was set on, we need to set another test cookie + // to find out which "broadest" domain the cookie was set on. Then delete the test cookie, and use that domain + // for updating the actual cookie. + if (domain) { + let broadDomain = $ct.broadDomain; + + if (broadDomain == null) { + // if we don't know the broadDomain yet, then find out + const domainParts = domain.split('.'); + let testBroadDomain = ''; + + for (let idx = domainParts.length - 1; idx >= 0; idx--) { + if (idx === 0) { + testBroadDomain = domainParts[idx] + testBroadDomain; + } else { + testBroadDomain = '.' + domainParts[idx] + testBroadDomain; + } // only needed if the cookie already exists and needs to be updated. See note above. - if (this.readCookie(name)) { - // no guarantee that browser will delete cookie, hence create short lived cookies - var testCookieName = 'test_' + name + idx; - this.createCookie(testCookieName, value, 10, testBroadDomain); // self-destruct after 10 seconds + if (this.readCookie(name)) { + // no guarantee that browser will delete cookie, hence create short lived cookies + var testCookieName = 'test_' + name + idx; + this.createCookie(testCookieName, value, 10, testBroadDomain); // self-destruct after 10 seconds - if (!this.readCookie(testCookieName)) { - // if test cookie not set, then the actual cookie wouldn't have been set on this domain either. - continue; - } else { - // else if cookie set, then delete the test and the original cookie - this.removeCookie(testCookieName, testBroadDomain); - } + if (!this.readCookie(testCookieName)) { + // if test cookie not set, then the actual cookie wouldn't have been set on this domain either. + continue; + } else { + // else if cookie set, then delete the test and the original cookie + this.removeCookie(testCookieName, testBroadDomain); } + } - this.createCookie(name, value, seconds, testBroadDomain); - var tempCookie = this.readCookie(name); // eslint-disable-next-line eqeqeq + this.createCookie(name, value, seconds, testBroadDomain); + const tempCookie = this.readCookie(name); // eslint-disable-next-line eqeqeq - if (tempCookie == value) { - broadDomain = testBroadDomain; - $ct.broadDomain = broadDomain; - break; - } + if (tempCookie == value) { + broadDomain = testBroadDomain; + $ct.broadDomain = broadDomain; + break; } - } else { - this.createCookie(name, value, seconds, broadDomain); } } else { - this.createCookie(name, value, seconds, domain); + this.createCookie(name, value, seconds, broadDomain); } + } else { + this.createCookie(name, value, seconds, domain); } - }, { - key: "getMetaProp", - value: function getMetaProp(property) { - var metaObj = this.readFromLSorCookie(META_COOKIE); + } - if (metaObj != null) { - return metaObj[property]; - } + static getMetaProp(property) { + const metaObj = this.readFromLSorCookie(META_COOKIE); + + if (metaObj != null) { + return metaObj[property]; } - }, { - key: "setMetaProp", - value: function setMetaProp(property, value) { - if (this._isLocalStorageSupported()) { - var wzrkMetaObj = this.readFromLSorCookie(META_COOKIE); + } - if (wzrkMetaObj == null) { - wzrkMetaObj = {}; - } + static setMetaProp(property, value) { + if (this._isLocalStorageSupported()) { + let wzrkMetaObj = this.readFromLSorCookie(META_COOKIE); - if (value === undefined) { - delete wzrkMetaObj[property]; - } else { - wzrkMetaObj[property] = value; - } + if (wzrkMetaObj == null) { + wzrkMetaObj = {}; + } - this.saveToLSorCookie(META_COOKIE, wzrkMetaObj); + if (value === undefined) { + delete wzrkMetaObj[property]; + } else { + wzrkMetaObj[property] = value; } + + this.saveToLSorCookie(META_COOKIE, wzrkMetaObj); } - }, { - key: "getAndClearMetaProp", - value: function getAndClearMetaProp(property) { - var value = this.getMetaProp(property); - this.setMetaProp(property, undefined); - return value; - } - }, { - key: "setInstantDeleteFlagInK", - value: function setInstantDeleteFlagInK() { - var k = this.readFromLSorCookie(KCOOKIE_NAME); + } - if (k == null) { - k = {}; - } + static getAndClearMetaProp(property) { + const value = this.getMetaProp(property); + this.setMetaProp(property, undefined); + return value; + } + + static setInstantDeleteFlagInK() { + let k = this.readFromLSorCookie(KCOOKIE_NAME); - k.flag = true; - this.saveToLSorCookie(KCOOKIE_NAME, k); + if (k == null) { + k = {}; } - }, { - key: "backupEvent", - value: function backupEvent(data, reqNo, logger) { - var backupArr = this.readFromLSorCookie(LCOOKIE_NAME); - if (typeof backupArr === 'undefined') { - backupArr = {}; - } + k.flag = true; + this.saveToLSorCookie(KCOOKIE_NAME, k); + } - backupArr[reqNo] = { - q: data - }; - this.saveToLSorCookie(LCOOKIE_NAME, backupArr); - logger.debug("stored in ".concat(LCOOKIE_NAME, " reqNo : ").concat(reqNo, " -> ").concat(data)); + static backupEvent(data, reqNo, logger) { + let backupArr = this.readFromLSorCookie(LCOOKIE_NAME); + + if (typeof backupArr === 'undefined') { + backupArr = {}; } - }, { - key: "removeBackup", - value: function removeBackup(respNo, logger) { - var backupMap = this.readFromLSorCookie(LCOOKIE_NAME); - if (typeof backupMap !== 'undefined' && backupMap !== null && typeof backupMap[respNo] !== 'undefined') { - logger.debug("del event: ".concat(respNo, " data-> ").concat(backupMap[respNo].q)); - delete backupMap[respNo]; - this.saveToLSorCookie(LCOOKIE_NAME, backupMap); - } + backupArr[reqNo] = { + q: data + }; + this.saveToLSorCookie(LCOOKIE_NAME, backupArr); + logger.debug("stored in ".concat(LCOOKIE_NAME, " reqNo : ").concat(reqNo, " -> ").concat(data)); + } + + static removeBackup(respNo, logger) { + const backupMap = this.readFromLSorCookie(LCOOKIE_NAME); + + if (typeof backupMap !== 'undefined' && backupMap !== null && typeof backupMap[respNo] !== 'undefined') { + logger.debug("del event: ".concat(respNo, " data-> ").concat(backupMap[respNo].q)); + delete backupMap[respNo]; + this.saveToLSorCookie(LCOOKIE_NAME, backupMap); } - }]); + } - return StorageManager; - }(); - var $ct = { + } + const $ct = { globalCache: { gcookie: null, REQ_N: 0, @@ -968,10 +611,8 @@ var _deleteFromObject = _classPrivateFieldLooseKey("deleteFromObject"); - var LRUCache = /*#__PURE__*/function () { - function LRUCache(max) { - _classCallCheck(this, LRUCache); - + class LRUCache { + constructor(max) { Object.defineProperty(this, _deleteFromObject, { value: _deleteFromObject2 }); @@ -980,14 +621,14 @@ value: void 0 }); this.max = max; - var lruCache = StorageManager.readFromLSorCookie(LRU_CACHE); + let lruCache = StorageManager.readFromLSorCookie(LRU_CACHE); if (lruCache) { - var tempLruCache = {}; + const tempLruCache = {}; _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder] = []; lruCache = lruCache.cache; - for (var entry in lruCache) { + for (const entry in lruCache) { if (lruCache.hasOwnProperty(entry)) { tempLruCache[lruCache[entry][0]] = lruCache[entry][1]; @@ -1002,112 +643,103 @@ } } - _createClass(LRUCache, [{ - key: "get", - value: function get(key) { - var item = this.cache[key]; + get(key) { + const item = this.cache[key]; - if (item) { - this.cache = _classPrivateFieldLooseBase(this, _deleteFromObject)[_deleteFromObject](key, this.cache); - this.cache[key] = item; - - _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder].push(key); - } + if (item) { + this.cache = _classPrivateFieldLooseBase(this, _deleteFromObject)[_deleteFromObject](key, this.cache); + this.cache[key] = item; - this.saveCacheToLS(this.cache); - return item; + _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder].push(key); } - }, { - key: "set", - value: function set(key, value) { - var item = this.cache[key]; - var allKeys = _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder]; + this.saveCacheToLS(this.cache); + return item; + } - if (item != null) { - this.cache = _classPrivateFieldLooseBase(this, _deleteFromObject)[_deleteFromObject](key, this.cache); - } else if (allKeys.length === this.max) { - this.cache = _classPrivateFieldLooseBase(this, _deleteFromObject)[_deleteFromObject](allKeys[0], this.cache); - } + set(key, value) { + const item = this.cache[key]; - this.cache[key] = value; + const allKeys = _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder]; - if (_classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder][_classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder] - 1] !== key) { - _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder].push(key); - } + if (item != null) { + this.cache = _classPrivateFieldLooseBase(this, _deleteFromObject)[_deleteFromObject](key, this.cache); + } else if (allKeys.length === this.max) { + this.cache = _classPrivateFieldLooseBase(this, _deleteFromObject)[_deleteFromObject](allKeys[0], this.cache); + } + + this.cache[key] = value; - this.saveCacheToLS(this.cache); + if (_classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder][_classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder] - 1] !== key) { + _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder].push(key); } - }, { - key: "saveCacheToLS", - value: function saveCacheToLS(cache) { - var objToArray = []; - var allKeys = _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder]; + this.saveCacheToLS(this.cache); + } - for (var index in allKeys) { - if (allKeys.hasOwnProperty(index)) { - var temp = []; - temp.push(allKeys[index]); - temp.push(cache[allKeys[index]]); - objToArray.push(temp); - } + saveCacheToLS(cache) { + const objToArray = []; + + const allKeys = _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder]; + + for (const index in allKeys) { + if (allKeys.hasOwnProperty(index)) { + const temp = []; + temp.push(allKeys[index]); + temp.push(cache[allKeys[index]]); + objToArray.push(temp); } + } - StorageManager.saveToLSorCookie(LRU_CACHE, { - cache: objToArray - }); + StorageManager.saveToLSorCookie(LRU_CACHE, { + cache: objToArray + }); + } + + getKey(value) { + if (value === null) { + return null; } - }, { - key: "getKey", - value: function getKey(value) { - if (value === null) { - return null; - } - var allKeys = _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder]; + const allKeys = _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder]; - for (var index in allKeys) { - if (allKeys.hasOwnProperty(index)) { - if (this.cache[allKeys[index]] === value) { - return allKeys[index]; - } + for (const index in allKeys) { + if (allKeys.hasOwnProperty(index)) { + if (this.cache[allKeys[index]] === value) { + return allKeys[index]; } } - - return null; } - }, { - key: "getSecondLastKey", - value: function getSecondLastKey() { - var keysArr = _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder]; - if (keysArr != null && keysArr.length > 1) { - return keysArr[keysArr.length - 2]; - } + return null; + } - return -1; + getSecondLastKey() { + const keysArr = _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder]; + + if (keysArr != null && keysArr.length > 1) { + return keysArr[keysArr.length - 2]; } - }, { - key: "getLastKey", - value: function getLastKey() { - var keysLength = _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder].length; - if (keysLength) { - return _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder][keysLength - 1]; - } + return -1; + } + + getLastKey() { + const keysLength = _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder].length; + + if (keysLength) { + return _classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder][keysLength - 1]; } - }]); + } - return LRUCache; - }(); + } var _deleteFromObject2 = function _deleteFromObject2(key, obj) { - var allKeys = JSON.parse(JSON.stringify(_classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder])); - var newCache = {}; - var indexToDelete; + const allKeys = JSON.parse(JSON.stringify(_classPrivateFieldLooseBase(this, _keyOrder)[_keyOrder])); + const newCache = {}; + let indexToDelete; - for (var index in allKeys) { + for (const index in allKeys) { if (allKeys.hasOwnProperty(index)) { if (allKeys[index] !== key) { newCache[allKeys[index]] = obj[allKeys[index]]; @@ -1130,15 +762,14 @@ var _session = _classPrivateFieldLooseKey("session"); - var CleverTapAPI = /*#__PURE__*/function () { - function CleverTapAPI(_ref) { - var logger = _ref.logger, - request = _ref.request, - device = _ref.device, - session = _ref.session; - - _classCallCheck(this, CleverTapAPI); - + class CleverTapAPI { + constructor(_ref) { + let { + logger, + request, + device, + session + } = _ref; Object.defineProperty(this, _logger, { writable: true, value: void 0 @@ -1171,137 +802,132 @@ */ - _createClass(CleverTapAPI, [{ - key: "s", - value: function s(global, session, resume, respNumber, optOutResponse) { - var oulReq = false; - var newGuid = false; // for a scenario when OUL request is true from client side - // but resume is returned as false from server end - // we maintan a OulReqN var in the window object - // and compare with respNumber to determine the response of an OUL request + s(global, session, resume, respNumber, optOutResponse) { + let oulReq = false; + let newGuid = false; // for a scenario when OUL request is true from client side + // but resume is returned as false from server end + // we maintan a OulReqN var in the window object + // and compare with respNumber to determine the response of an OUL request - if (window.isOULInProgress) { - if (resume || respNumber !== 'undefined' && respNumber === window.oulReqN) { - window.isOULInProgress = false; - oulReq = true; - } - } // call back function used to store global and session ids for the user + if (window.isOULInProgress) { + if (resume || respNumber !== 'undefined' && respNumber === window.oulReqN) { + window.isOULInProgress = false; + oulReq = true; + } + } // call back function used to store global and session ids for the user - if (typeof respNumber === 'undefined') { - respNumber = 0; - } + if (typeof respNumber === 'undefined') { + respNumber = 0; + } - StorageManager.removeBackup(respNumber, _classPrivateFieldLooseBase(this, _logger)[_logger]); + StorageManager.removeBackup(respNumber, _classPrivateFieldLooseBase(this, _logger)[_logger]); - if (respNumber > $ct.globalCache.REQ_N) { - // request for some other user so ignore - return; - } + if (respNumber > $ct.globalCache.REQ_N) { + // request for some other user so ignore + return; + } - if (!isValueValid(_classPrivateFieldLooseBase(this, _device)[_device].gcookie)) { - if (global) { - newGuid = true; - } + if (!isValueValid(_classPrivateFieldLooseBase(this, _device)[_device].gcookie)) { + if (global) { + newGuid = true; } + } - if (!isValueValid(_classPrivateFieldLooseBase(this, _device)[_device].gcookie) || resume || typeof optOutResponse === 'boolean') { - var sessionObj = _classPrivateFieldLooseBase(this, _session)[_session].getSessionCookieObject(); - /* If the received session is less than the session in the cookie, - then don't update guid as it will be response for old request - */ + if (!isValueValid(_classPrivateFieldLooseBase(this, _device)[_device].gcookie) || resume || typeof optOutResponse === 'boolean') { + const sessionObj = _classPrivateFieldLooseBase(this, _session)[_session].getSessionCookieObject(); + /* If the received session is less than the session in the cookie, + then don't update guid as it will be response for old request + */ - if (window.isOULInProgress || sessionObj.s && session < sessionObj.s) { - return; - } + if (window.isOULInProgress || sessionObj.s && session < sessionObj.s) { + return; + } - _classPrivateFieldLooseBase(this, _logger)[_logger].debug("Cookie was ".concat(_classPrivateFieldLooseBase(this, _device)[_device].gcookie, " set to ").concat(global)); + _classPrivateFieldLooseBase(this, _logger)[_logger].debug("Cookie was ".concat(_classPrivateFieldLooseBase(this, _device)[_device].gcookie, " set to ").concat(global)); - _classPrivateFieldLooseBase(this, _device)[_device].gcookie = global; + _classPrivateFieldLooseBase(this, _device)[_device].gcookie = global; - if (!isValueValid(_classPrivateFieldLooseBase(this, _device)[_device].gcookie)) { - // clear useIP meta prop - StorageManager.getAndClearMetaProp(USEIP_KEY); - } + if (!isValueValid(_classPrivateFieldLooseBase(this, _device)[_device].gcookie)) { + // clear useIP meta prop + StorageManager.getAndClearMetaProp(USEIP_KEY); + } - if (global && StorageManager._isLocalStorageSupported()) { - if ($ct.LRU_CACHE == null) { - $ct.LRU_CACHE = new LRUCache(LRU_CACHE_SIZE); - } + if (global && StorageManager._isLocalStorageSupported()) { + if ($ct.LRU_CACHE == null) { + $ct.LRU_CACHE = new LRUCache(LRU_CACHE_SIZE); + } - var kIdFromLS = StorageManager.readFromLSorCookie(KCOOKIE_NAME); - var guidFromLRUCache; + const kIdFromLS = StorageManager.readFromLSorCookie(KCOOKIE_NAME); + let guidFromLRUCache; - if (kIdFromLS != null && kIdFromLS.id) { - guidFromLRUCache = $ct.LRU_CACHE.cache[kIdFromLS.id]; + if (kIdFromLS != null && kIdFromLS.id) { + guidFromLRUCache = $ct.LRU_CACHE.cache[kIdFromLS.id]; - if (resume) { - if (!guidFromLRUCache) { - StorageManager.saveToLSorCookie(FIRE_PUSH_UNREGISTERED, true); // replace login identity in OUL request - // with the gcookie returned in exchange + if (resume) { + if (!guidFromLRUCache) { + StorageManager.saveToLSorCookie(FIRE_PUSH_UNREGISTERED, true); // replace login identity in OUL request + // with the gcookie returned in exchange - $ct.LRU_CACHE.set(kIdFromLS.id, global); - } + $ct.LRU_CACHE.set(kIdFromLS.id, global); } } + } - StorageManager.saveToLSorCookie(GCOOKIE_NAME, global); // lastk provides the guid + StorageManager.saveToLSorCookie(GCOOKIE_NAME, global); // lastk provides the guid - var lastK = $ct.LRU_CACHE.getSecondLastKey(); + const lastK = $ct.LRU_CACHE.getSecondLastKey(); - if (StorageManager.readFromLSorCookie(FIRE_PUSH_UNREGISTERED) && lastK !== -1) { - var lastGUID = $ct.LRU_CACHE.cache[lastK]; // fire the request directly via fireRequest to unregister the token - // then other requests with the updated guid should follow + if (StorageManager.readFromLSorCookie(FIRE_PUSH_UNREGISTERED) && lastK !== -1) { + const lastGUID = $ct.LRU_CACHE.cache[lastK]; // fire the request directly via fireRequest to unregister the token + // then other requests with the updated guid should follow - _classPrivateFieldLooseBase(this, _request)[_request].unregisterTokenForGuid(lastGUID); - } + _classPrivateFieldLooseBase(this, _request)[_request].unregisterTokenForGuid(lastGUID); } - - StorageManager.createBroadCookie(GCOOKIE_NAME, global, COOKIE_EXPIRY, window.location.hostname); - StorageManager.saveToLSorCookie(GCOOKIE_NAME, global); } - if (StorageManager._isLocalStorageSupported()) { - _classPrivateFieldLooseBase(this, _session)[_session].manageSession(session); - } // session cookie + StorageManager.createBroadCookie(GCOOKIE_NAME, global, COOKIE_EXPIRY, window.location.hostname); + StorageManager.saveToLSorCookie(GCOOKIE_NAME, global); + } + if (StorageManager._isLocalStorageSupported()) { + _classPrivateFieldLooseBase(this, _session)[_session].manageSession(session); + } // session cookie - var obj = _classPrivateFieldLooseBase(this, _session)[_session].getSessionCookieObject(); // for the race-condition where two responses come back with different session ids. don't write the older session id. + const obj = _classPrivateFieldLooseBase(this, _session)[_session].getSessionCookieObject(); // for the race-condition where two responses come back with different session ids. don't write the older session id. - if (typeof obj.s === 'undefined' || obj.s <= session) { - obj.s = session; - obj.t = getNow(); // time of last response from server - _classPrivateFieldLooseBase(this, _session)[_session].setSessionCookieObject(obj); - } // set blockRequest to false only if the device has a valid gcookie + if (typeof obj.s === 'undefined' || obj.s <= session) { + obj.s = session; + obj.t = getNow(); // time of last response from server + _classPrivateFieldLooseBase(this, _session)[_session].setSessionCookieObject(obj); + } // set blockRequest to false only if the device has a valid gcookie - if (isValueValid(_classPrivateFieldLooseBase(this, _device)[_device].gcookie)) { - $ct.blockRequest = false; - } // only process the backup events after an OUL request or a new guid is recieved + if (isValueValid(_classPrivateFieldLooseBase(this, _device)[_device].gcookie)) { + $ct.blockRequest = false; + } // only process the backup events after an OUL request or a new guid is recieved - if ((oulReq || newGuid) && !_classPrivateFieldLooseBase(this, _request)[_request].processingBackup) { - _classPrivateFieldLooseBase(this, _request)[_request].processBackupEvents(); - } - $ct.globalCache.RESP_N = respNumber; + if ((oulReq || newGuid) && !_classPrivateFieldLooseBase(this, _request)[_request].processingBackup) { + _classPrivateFieldLooseBase(this, _request)[_request].processBackupEvents(); } - }]); - - return CleverTapAPI; - }(); - var _logger$1 = _classPrivateFieldLooseKey("logger"); + $ct.globalCache.RESP_N = respNumber; + } - var DeviceManager = /*#__PURE__*/function () { - function DeviceManager(_ref) { - var logger = _ref.logger; + } - _classCallCheck(this, DeviceManager); + var _logger$1 = _classPrivateFieldLooseKey("logger"); + class DeviceManager { + constructor(_ref) { + let { + logger + } = _ref; Object.defineProperty(this, _logger$1, { writable: true, value: void 0 @@ -1311,79 +937,75 @@ this.gcookie = this.getGuid(); } - _createClass(DeviceManager, [{ - key: "getGuid", - value: function getGuid() { - var guid = null; + getGuid() { + let guid = null; - if (isValueValid(this.gcookie)) { - return this.gcookie; - } + if (isValueValid(this.gcookie)) { + return this.gcookie; + } - if (StorageManager._isLocalStorageSupported()) { - var value = StorageManager.read(GCOOKIE_NAME); + if (StorageManager._isLocalStorageSupported()) { + const value = StorageManager.read(GCOOKIE_NAME); - if (isValueValid(value)) { - try { - guid = JSON.parse(decodeURIComponent(value)); - } catch (e) { - _classPrivateFieldLooseBase(this, _logger$1)[_logger$1].debug('Cannot parse Gcookie from localstorage - must be encoded ' + value); // assumming guids are of size 32. supporting both formats. - // guid can have encodedURIComponent or be without it. - // 1.56e4078ed15749928c042479ec2b4d47 - breaks on JSON.parse(decodeURIComponent()) - // 2.%2256e4078ed15749928c042479ec2b4d47%22 + if (isValueValid(value)) { + try { + guid = JSON.parse(decodeURIComponent(value)); + } catch (e) { + _classPrivateFieldLooseBase(this, _logger$1)[_logger$1].debug('Cannot parse Gcookie from localstorage - must be encoded ' + value); // assumming guids are of size 32. supporting both formats. + // guid can have encodedURIComponent or be without it. + // 1.56e4078ed15749928c042479ec2b4d47 - breaks on JSON.parse(decodeURIComponent()) + // 2.%2256e4078ed15749928c042479ec2b4d47%22 - if (value.length === 32) { - guid = value; - StorageManager.saveToLSorCookie(GCOOKIE_NAME, value); - } else { - _classPrivateFieldLooseBase(this, _logger$1)[_logger$1].error('Illegal guid ' + value); - } - } // Persist to cookie storage if not present there. + if (value.length === 32) { + guid = value; + StorageManager.saveToLSorCookie(GCOOKIE_NAME, value); + } else { + _classPrivateFieldLooseBase(this, _logger$1)[_logger$1].error('Illegal guid ' + value); + } + } // Persist to cookie storage if not present there. - if (isValueValid(guid)) { - StorageManager.createBroadCookie(GCOOKIE_NAME, guid, COOKIE_EXPIRY, window.location.hostname); - } + if (isValueValid(guid)) { + StorageManager.createBroadCookie(GCOOKIE_NAME, guid, COOKIE_EXPIRY, window.location.hostname); } } + } - if (!isValueValid(guid)) { - guid = StorageManager.readCookie(GCOOKIE_NAME); - - if (isValueValid(guid) && (guid.indexOf('%') === 0 || guid.indexOf('\'') === 0 || guid.indexOf('"') === 0)) { - guid = null; - } + if (!isValueValid(guid)) { + guid = StorageManager.readCookie(GCOOKIE_NAME); - if (isValueValid(guid)) { - StorageManager.saveToLSorCookie(GCOOKIE_NAME, guid); - } + if (isValueValid(guid) && (guid.indexOf('%') === 0 || guid.indexOf('\'') === 0 || guid.indexOf('"') === 0)) { + guid = null; } - return guid; + if (isValueValid(guid)) { + StorageManager.saveToLSorCookie(GCOOKIE_NAME, guid); + } } - }]); - return DeviceManager; - }(); + return guid; + } + + } - var DATA_NOT_SENT_TEXT = 'This property has been ignored.'; - var CLEVERTAP_ERROR_PREFIX = 'CleverTap error:'; // Formerly wzrk_error_txt + const DATA_NOT_SENT_TEXT = 'This property has been ignored.'; + const CLEVERTAP_ERROR_PREFIX = 'CleverTap error:'; // Formerly wzrk_error_txt - var EMBED_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " Incorrect embed script."); - var EVENT_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " Event structure not valid. ").concat(DATA_NOT_SENT_TEXT); - var GENDER_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " Gender value should be either M or F. ").concat(DATA_NOT_SENT_TEXT); - var EMPLOYED_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " Employed value should be either Y or N. ").concat(DATA_NOT_SENT_TEXT); - var MARRIED_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " Married value should be either Y or N. ").concat(DATA_NOT_SENT_TEXT); - var EDUCATION_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " Education value should be either School, College or Graduate. ").concat(DATA_NOT_SENT_TEXT); - var AGE_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " Age value should be a number. ").concat(DATA_NOT_SENT_TEXT); - var DOB_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " DOB value should be a Date Object"); - var ENUM_FORMAT_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " setEnum(value). value should be a string or a number"); - var PHONE_FORMAT_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " Phone number should be formatted as +[country code][number]"); + const EMBED_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " Incorrect embed script."); + const EVENT_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " Event structure not valid. ").concat(DATA_NOT_SENT_TEXT); + const GENDER_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " Gender value should be either M or F. ").concat(DATA_NOT_SENT_TEXT); + const EMPLOYED_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " Employed value should be either Y or N. ").concat(DATA_NOT_SENT_TEXT); + const MARRIED_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " Married value should be either Y or N. ").concat(DATA_NOT_SENT_TEXT); + const EDUCATION_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " Education value should be either School, College or Graduate. ").concat(DATA_NOT_SENT_TEXT); + const AGE_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " Age value should be a number. ").concat(DATA_NOT_SENT_TEXT); + const DOB_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " DOB value should be a Date Object"); + const ENUM_FORMAT_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " setEnum(value). value should be a string or a number"); + const PHONE_FORMAT_ERROR = "".concat(CLEVERTAP_ERROR_PREFIX, " Phone number should be formatted as +[country code][number]"); - var _globalChargedId; + let _globalChargedId; - var isEventStructureFlat = function isEventStructureFlat(eventObj) { + const isEventStructureFlat = eventObj => { // Events cannot have nested structure or Arrays if (isObject(eventObj)) { for (var key in eventObj) { @@ -1401,7 +1023,7 @@ return false; }; - var isChargedEventStructureValid = function isChargedEventStructureValid(chargedObj, logger) { + const isChargedEventStructureValid = (chargedObj, logger) => { if (isObject(chargedObj)) { for (var key in chargedObj) { if (chargedObj.hasOwnProperty(key)) { @@ -1434,7 +1056,7 @@ if (isString(chargedObj[CHARGED_ID]) || isNumber(chargedObj[CHARGED_ID])) { // save charged Id - var chargedId = chargedObj[CHARGED_ID] + ''; // casting chargedId to string + const chargedId = chargedObj[CHARGED_ID] + ''; // casting chargedId to string if (typeof _globalChargedId === 'undefined') { _globalChargedId = StorageManager.readFromLSorCookie(CHARGEDID_COOKIE_NAME); @@ -1467,96 +1089,82 @@ var _processEventArray = _classPrivateFieldLooseKey("processEventArray"); - var EventHandler = /*#__PURE__*/function (_Array) { - _inherits(EventHandler, _Array); - - var _super = _createSuper(EventHandler); - - function EventHandler(_ref, values) { - var _this; - - var logger = _ref.logger, - request = _ref.request, - isPersonalisationActive = _ref.isPersonalisationActive; - - _classCallCheck(this, EventHandler); - - _this = _super.call(this); - Object.defineProperty(_assertThisInitialized(_this), _processEventArray, { + class EventHandler extends Array { + constructor(_ref, values) { + let { + logger, + request, + isPersonalisationActive + } = _ref; + super(); + Object.defineProperty(this, _processEventArray, { value: _processEventArray2 }); - Object.defineProperty(_assertThisInitialized(_this), _logger$2, { + Object.defineProperty(this, _logger$2, { writable: true, value: void 0 }); - Object.defineProperty(_assertThisInitialized(_this), _oldValues, { + Object.defineProperty(this, _oldValues, { writable: true, value: void 0 }); - Object.defineProperty(_assertThisInitialized(_this), _request$1, { + Object.defineProperty(this, _request$1, { writable: true, value: void 0 }); - Object.defineProperty(_assertThisInitialized(_this), _isPersonalisationActive, { + Object.defineProperty(this, _isPersonalisationActive, { writable: true, value: void 0 }); - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _logger$2)[_logger$2] = logger; - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _oldValues)[_oldValues] = values; - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _request$1)[_request$1] = request; - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _isPersonalisationActive)[_isPersonalisationActive] = isPersonalisationActive; - return _this; + _classPrivateFieldLooseBase(this, _logger$2)[_logger$2] = logger; + _classPrivateFieldLooseBase(this, _oldValues)[_oldValues] = values; + _classPrivateFieldLooseBase(this, _request$1)[_request$1] = request; + _classPrivateFieldLooseBase(this, _isPersonalisationActive)[_isPersonalisationActive] = isPersonalisationActive; } - _createClass(EventHandler, [{ - key: "push", - value: function push() { - for (var _len = arguments.length, eventsArr = new Array(_len), _key = 0; _key < _len; _key++) { - eventsArr[_key] = arguments[_key]; - } + push() { + for (var _len = arguments.length, eventsArr = new Array(_len), _key = 0; _key < _len; _key++) { + eventsArr[_key] = arguments[_key]; + } + + _classPrivateFieldLooseBase(this, _processEventArray)[_processEventArray](eventsArr); - _classPrivateFieldLooseBase(this, _processEventArray)[_processEventArray](eventsArr); + return 0; + } - return 0; + _processOldValues() { + if (_classPrivateFieldLooseBase(this, _oldValues)[_oldValues]) { + _classPrivateFieldLooseBase(this, _processEventArray)[_processEventArray](_classPrivateFieldLooseBase(this, _oldValues)[_oldValues]); } - }, { - key: "_processOldValues", - value: function _processOldValues() { - if (_classPrivateFieldLooseBase(this, _oldValues)[_oldValues]) { - _classPrivateFieldLooseBase(this, _processEventArray)[_processEventArray](_classPrivateFieldLooseBase(this, _oldValues)[_oldValues]); - } - _classPrivateFieldLooseBase(this, _oldValues)[_oldValues] = null; + _classPrivateFieldLooseBase(this, _oldValues)[_oldValues] = null; + } + + getDetails(evtName) { + if (!_classPrivateFieldLooseBase(this, _isPersonalisationActive)[_isPersonalisationActive]()) { + return; } - }, { - key: "getDetails", - value: function getDetails(evtName) { - if (!_classPrivateFieldLooseBase(this, _isPersonalisationActive)[_isPersonalisationActive]()) { - return; - } - if (typeof $ct.globalEventsMap === 'undefined') { - $ct.globalEventsMap = StorageManager.readFromLSorCookie(EV_COOKIE); - } + if (typeof $ct.globalEventsMap === 'undefined') { + $ct.globalEventsMap = StorageManager.readFromLSorCookie(EV_COOKIE); + } - if (typeof $ct.globalEventsMap === 'undefined') { - return; - } + if (typeof $ct.globalEventsMap === 'undefined') { + return; + } - var evtObj = $ct.globalEventsMap[evtName]; - var respObj = {}; + const evtObj = $ct.globalEventsMap[evtName]; + const respObj = {}; - if (typeof evtObj !== 'undefined') { - respObj.firstTime = new Date(evtObj[1] * 1000); - respObj.lastTime = new Date(evtObj[2] * 1000); - respObj.count = evtObj[0]; - return respObj; - } + if (typeof evtObj !== 'undefined') { + respObj.firstTime = new Date(evtObj[1] * 1000); + respObj.lastTime = new Date(evtObj[2] * 1000); + respObj.count = evtObj[0]; + return respObj; } - }]); + } - return EventHandler; - }( /*#__PURE__*/_wrapNativeSuper(Array)); + } var _processEventArray2 = function _processEventArray2(eventsArr) { if (Array.isArray(eventsArr)) { @@ -1581,12 +1189,12 @@ continue; } - var data = {}; + const data = {}; data.type = 'event'; data.evtName = sanitize(eventName, unsupportedKeyCharRegex); if (eventsArr.length !== 0) { - var eventObj = eventsArr.shift(); + const eventObj = eventsArr.shift(); if (!isObject(eventObj)) { // put it back if it is not an object @@ -1616,19 +1224,19 @@ } }; - var getURLParams = function getURLParams(url) { - var urlParams = {}; - var idx = url.indexOf('?'); + const getURLParams = url => { + const urlParams = {}; + const idx = url.indexOf('?'); if (idx > 1) { - var uri = url.substring(idx + 1); - var match; - var pl = /\+/g; // Regex for replacing addition symbol with a space + const uri = url.substring(idx + 1); + let match; + const pl = /\+/g; // Regex for replacing addition symbol with a space - var search = /([^&=]+)=?([^&]*)/g; + const search = /([^&=]+)=?([^&]*)/g; - var decode = function decode(s) { - var replacement = s.replace(pl, ' '); + const decode = function (s) { + let replacement = s.replace(pl, ' '); try { replacement = decodeURIComponent(replacement); @@ -1648,39 +1256,39 @@ return urlParams; }; - var getDomain = function getDomain(url) { + const getDomain = url => { if (url === '') return ''; var a = document.createElement('a'); a.href = url; return a.hostname; }; - var addToURL = function addToURL(url, k, v) { + const addToURL = (url, k, v) => { return url + '&' + k + '=' + encodeURIComponent(v); }; - var getHostName = function getHostName() { + const getHostName = () => { return window.location.hostname; }; /* eslint-disable */ - var urlBase64ToUint8Array = function urlBase64ToUint8Array(base64String) { - var padding = '='.repeat((4 - base64String.length % 4) % 4); - var base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/'); - var rawData = window.atob(base64); - var processedData = []; + const urlBase64ToUint8Array = base64String => { + let padding = '='.repeat((4 - base64String.length % 4) % 4); + let base64 = (base64String + padding).replace(/\-/g, '+').replace(/_/g, '/'); + let rawData = window.atob(base64); + let processedData = []; - for (var i = 0; i < rawData.length; i++) { + for (let i = 0; i < rawData.length; i++) { processedData.push(rawData.charCodeAt(i)); } return new Uint8Array(processedData); }; - var compressData = function compressData(dataObject, logger) { + const compressData = (dataObject, logger) => { logger && typeof logger.debug === 'function' && logger.debug('dobj:' + dataObject); return compressToBase64(dataObject); }; - var compress = function compress(uncompressed) { + const compress = uncompressed => { if (uncompressed == null) return ''; - var i, + let i, value, context_dictionary = {}, context_dictionaryToCreate = {}, @@ -1940,9 +1548,9 @@ return context_data_string; }; - var getKeyStr = function getKeyStr() { - var key = ''; - var i = 0; + const getKeyStr = () => { + let key = ''; + let i = 0; for (i = 0; i <= 25; i++) { key = key + String.fromCharCode(i + 65); @@ -1959,8 +1567,8 @@ return key + '+/='; }; - var _keyStr = getKeyStr(); - var compressToBase64 = function compressToBase64(input) { + const _keyStr = getKeyStr(); + const compressToBase64 = input => { if (input == null) return ''; var output = ''; var chr1, chr2, chr3, enc1, enc2, enc3, enc4; @@ -2007,66 +1615,58 @@ var _addARPToRequest = _classPrivateFieldLooseKey("addARPToRequest"); - var RequestDispatcher = /*#__PURE__*/function () { - function RequestDispatcher() { - _classCallCheck(this, RequestDispatcher); - + class RequestDispatcher { + constructor() { this.networkRetryCount = 0; this.minDelayFrequency = 0; } - _createClass(RequestDispatcher, [{ - key: "getDelayFrequency", - value: function getDelayFrequency() { - this.logger.debug('Network retry #' + this.networkRetryCount); // Retry with delay as 1s for first 10 retries + /** + * + * @param {string} url + * @param {*} skipARP + * @param {boolean} sendOULFlag + */ + static fireRequest(url, skipARP, sendOULFlag, evtName) { + _classPrivateFieldLooseBase(this, _fireRequest)[_fireRequest](url, 1, skipARP, sendOULFlag, evtName); + } - if (this.networkRetryCount < 10) { - this.logger.debug(this.account.id, 'Failure count is ' + this.networkRetryCount + '. Setting delay frequency to 1s'); - this.minDelayFrequency = PUSH_DELAY_MS; // Reset minimum delay to 1s + getDelayFrequency() { + this.logger.debug('Network retry #' + this.networkRetryCount); // Retry with delay as 1s for first 10 retries - return this.minDelayFrequency; - } + if (this.networkRetryCount < 10) { + this.logger.debug(this.account.id, 'Failure count is ' + this.networkRetryCount + '. Setting delay frequency to 1s'); + this.minDelayFrequency = PUSH_DELAY_MS; // Reset minimum delay to 1s - if (this.account.region == null) { - // Retry with delay as 1s if region is null in case of eu1 - this.logger.debug(this.account.id, 'Setting delay frequency to 1s'); - return PUSH_DELAY_MS; - } else { - // Retry with delay as minimum delay frequency and add random number of seconds to scatter traffic - var randomDelay = (Math.floor(Math.random() * 10) + 1) * 1000; - this.minDelayFrequency += randomDelay; + return this.minDelayFrequency; + } - if (this.minDelayFrequency < MAX_DELAY_FREQUENCY) { - this.logger.debug(this.account.id, 'Setting delay frequency to ' + this.minDelayFrequency); - return this.minDelayFrequency; - } else { - this.minDelayFrequency = PUSH_DELAY_MS; - } + if (this.account.region == null) { + // Retry with delay as 1s if region is null in case of eu1 + this.logger.debug(this.account.id, 'Setting delay frequency to 1s'); + return PUSH_DELAY_MS; + } else { + // Retry with delay as minimum delay frequency and add random number of seconds to scatter traffic + const randomDelay = (Math.floor(Math.random() * 10) + 1) * 1000; + this.minDelayFrequency += randomDelay; + if (this.minDelayFrequency < MAX_DELAY_FREQUENCY) { this.logger.debug(this.account.id, 'Setting delay frequency to ' + this.minDelayFrequency); return this.minDelayFrequency; + } else { + this.minDelayFrequency = PUSH_DELAY_MS; } - } - }], [{ - key: "fireRequest", - /** - * - * @param {string} url - * @param {*} skipARP - * @param {boolean} sendOULFlag - */ - value: function fireRequest(url, skipARP, sendOULFlag, evtName) { - _classPrivateFieldLooseBase(this, _fireRequest)[_fireRequest](url, 1, skipARP, sendOULFlag, evtName); + this.logger.debug(this.account.id, 'Setting delay frequency to ' + this.minDelayFrequency); + return this.minDelayFrequency; } - }]); + } - return RequestDispatcher; - }(); + } var _addARPToRequest2 = function _addARPToRequest2(url, skipResARP) { if (skipResARP === true) { - var _arp = {}; + const _arp = {}; _arp.skipResARP = true; return addToURL(url, 'arp', compressData(JSON.stringify(_arp), this.logger)); } @@ -2098,9 +1698,7 @@ }; var _fireRequest2 = function _fireRequest2(url, tries, skipARP, sendOULFlag, evtName) { - var _this = this, - _window$clevertap, - _window$wizrocket; + var _window$clevertap, _window$wizrocket; if (_classPrivateFieldLooseBase(this, _dropRequestDueToOptOut)[_dropRequestDueToOptOut]()) { this.logger.debug('req dropped due to optout cookie: ' + this.device.gcookie); @@ -2123,19 +1721,19 @@ if (evtName && evtName === WZRK_FETCH) { // New retry mechanism if (!isValueValid(this.device.gcookie) && $ct.globalCache.RESP_N < $ct.globalCache.REQ_N - 1) { - setTimeout(function () { - _this.logger.debug("retrying fire request for url: ".concat(url, ", tries: ").concat(_this.networkRetryCount)); + setTimeout(() => { + this.logger.debug("retrying fire request for url: ".concat(url, ", tries: ").concat(this.networkRetryCount)); - _classPrivateFieldLooseBase(_this, _fireRequest)[_fireRequest](url, undefined, skipARP, sendOULFlag); + _classPrivateFieldLooseBase(this, _fireRequest)[_fireRequest](url, undefined, skipARP, sendOULFlag); }, this.getDelayFrequency()); } } else { if (!isValueValid(this.device.gcookie) && $ct.globalCache.RESP_N < $ct.globalCache.REQ_N - 1 && tries < MAX_TRIES) { // if ongoing First Request is in progress, initiate retry - setTimeout(function () { - _this.logger.debug("retrying fire request for url: ".concat(url, ", tries: ").concat(tries)); + setTimeout(() => { + this.logger.debug("retrying fire request for url: ".concat(url, ", tries: ").concat(tries)); - _classPrivateFieldLooseBase(_this, _fireRequest)[_fireRequest](url, tries + 1, skipARP, sendOULFlag); + _classPrivateFieldLooseBase(this, _fireRequest)[_fireRequest](url, tries + 1, skipARP, sendOULFlag); }, 50); return; } @@ -2162,7 +1760,7 @@ if (((_window$clevertap = window.clevertap) === null || _window$clevertap === void 0 ? void 0 : _window$clevertap.hasOwnProperty('plugin')) || ((_window$wizrocket = window.wizrocket) === null || _window$wizrocket === void 0 ? void 0 : _window$wizrocket.hasOwnProperty('plugin'))) { // used to add plugin name in request parameter - var plugin = window.clevertap.plugin || window.wizrocket.plugin; + const plugin = window.clevertap.plugin || window.wizrocket.plugin; url = addToURL(url, 'ct_pl', plugin); } @@ -2177,7 +1775,7 @@ ctCbScripts[0].parentNode.removeChild(ctCbScripts[0]); } - var s = document.createElement('script'); + const s = document.createElement('script'); s.setAttribute('type', 'text/javascript'); s.setAttribute('src', url); s.setAttribute('class', 'ct-jp-cb'); @@ -2203,11 +1801,12 @@ value: _addARPToRequest2 }); - var getCampaignObject = function getCampaignObject() { - var finalcampObj = {}; + // CleverTap specific utilities + const getCampaignObject = () => { + let finalcampObj = {}; if (StorageManager._isLocalStorageSupported()) { - var campObj = StorageManager.read(CAMP_COOKIE_NAME); + let campObj = StorageManager.read(CAMP_COOKIE_NAME); if (campObj != null) { campObj = JSON.parse(decodeURIComponent(campObj).replace(singleQuoteRegex, '\"')); @@ -2224,45 +1823,46 @@ return finalcampObj; }; - var saveCampaignObject = function saveCampaignObject(campaignObj) { + const saveCampaignObject = campaignObj => { if (StorageManager._isLocalStorageSupported()) { - var newObj = _objectSpread2(_objectSpread2({}, getCampaignObject()), campaignObj); - - var campObj = JSON.stringify(newObj); + const newObj = { ...getCampaignObject(), + ...campaignObj + }; + const campObj = JSON.stringify(newObj); StorageManager.save(CAMP_COOKIE_NAME, encodeURIComponent(campObj)); // Update the CAMP_COOKIE_G to be in sync with CAMP_COOKIE_NAME setCampaignObjectForGuid(); } }; // set Campaign Object against the guid, with daily count and total count details - var setCampaignObjectForGuid = function setCampaignObjectForGuid() { + const setCampaignObjectForGuid = () => { if (StorageManager._isLocalStorageSupported()) { - var guid = StorageManager.read(GCOOKIE_NAME); + let guid = StorageManager.read(GCOOKIE_NAME); if (isValueValid(guid)) { try { guid = JSON.parse(decodeURIComponent(StorageManager.read(GCOOKIE_NAME))); - var guidCampObj = StorageManager.read(CAMP_COOKIE_G) ? JSON.parse(decodeURIComponent(StorageManager.read(CAMP_COOKIE_G))) : {}; + const guidCampObj = StorageManager.read(CAMP_COOKIE_G) ? JSON.parse(decodeURIComponent(StorageManager.read(CAMP_COOKIE_G))) : {}; if (guid && StorageManager._isLocalStorageSupported()) { var finalCampObj = {}; var campObj = getCampaignObject(); - Object.keys(campObj).forEach(function (key) { - var campKeyObj = guid in guidCampObj && Object.keys(guidCampObj[guid]).length && guidCampObj[guid][key] ? guidCampObj[guid][key] : {}; - var globalObj = campObj[key].global; - var today = getToday(); - var dailyObj = campObj[key][today]; + Object.keys(campObj).forEach(key => { + const campKeyObj = guid in guidCampObj && Object.keys(guidCampObj[guid]).length && guidCampObj[guid][key] ? guidCampObj[guid][key] : {}; + const globalObj = campObj[key].global; + const today = getToday(); + const dailyObj = campObj[key][today]; if (typeof globalObj !== 'undefined') { - var campaignIdArray = Object.keys(globalObj); + const campaignIdArray = Object.keys(globalObj); - for (var index in campaignIdArray) { - var resultObj = []; + for (const index in campaignIdArray) { + let resultObj = []; if (campaignIdArray.hasOwnProperty(index)) { - var dailyC = 0; - var totalC = 0; - var campaignId = campaignIdArray[index]; + let dailyC = 0; + let totalC = 0; + const campaignId = campaignIdArray[index]; if (campaignId === 'tc') { continue; @@ -2282,7 +1882,9 @@ } } - finalCampObj = _objectSpread2(_objectSpread2({}, finalCampObj), {}, _defineProperty({}, key, campKeyObj)); + finalCampObj = { ...finalCampObj, + [key]: campKeyObj + }; }); guidCampObj[guid] = finalCampObj; StorageManager.save(CAMP_COOKIE_G, encodeURIComponent(JSON.stringify(guidCampObj))); @@ -2293,22 +1895,22 @@ } } }; - var getCampaignObjForLc = function getCampaignObjForLc() { + const getCampaignObjForLc = () => { // before preparing data to send to LC , check if the entry for the guid is already there in CAMP_COOKIE_G - var guid = JSON.parse(decodeURIComponent(StorageManager.read(GCOOKIE_NAME))); - var campObj = {}; + const guid = JSON.parse(decodeURIComponent(StorageManager.read(GCOOKIE_NAME))); + let campObj = {}; if (StorageManager._isLocalStorageSupported()) { - var resultObj = {}; + let resultObj = {}; campObj = getCampaignObject(); - var storageValue = StorageManager.read(CAMP_COOKIE_G); - var decodedValue = storageValue ? decodeURIComponent(storageValue) : null; - var parsedValue = decodedValue ? JSON.parse(decodedValue) : null; - var resultObjWP = !!guid && storageValue !== undefined && storageValue !== null && parsedValue && parsedValue[guid] && parsedValue[guid].wp ? Object.values(parsedValue[guid].wp) : []; - var resultObjWI = !!guid && storageValue !== undefined && storageValue !== null && parsedValue && parsedValue[guid] && parsedValue[guid].wi ? Object.values(parsedValue[guid].wi) : []; - var today = getToday(); - var todayCwp = 0; - var todayCwi = 0; + const storageValue = StorageManager.read(CAMP_COOKIE_G); + const decodedValue = storageValue ? decodeURIComponent(storageValue) : null; + const parsedValue = decodedValue ? JSON.parse(decodedValue) : null; + const resultObjWP = !!guid && storageValue !== undefined && storageValue !== null && parsedValue && parsedValue[guid] && parsedValue[guid].wp ? Object.values(parsedValue[guid].wp) : []; + const resultObjWI = !!guid && storageValue !== undefined && storageValue !== null && parsedValue && parsedValue[guid] && parsedValue[guid].wi ? Object.values(parsedValue[guid].wi) : []; + const today = getToday(); + let todayCwp = 0; + let todayCwi = 0; if (campObj.wp && campObj.wp[today] && campObj.wp[today].tc !== 'undefined') { todayCwp = campObj.wp[today].tc; @@ -2327,15 +1929,17 @@ return resultObj; } }; - var isProfileValid = function isProfileValid(profileObj, _ref) { - var logger = _ref.logger; - var valid = false; + const isProfileValid = (profileObj, _ref) => { + let { + logger + } = _ref; + let valid = false; if (isObject(profileObj)) { - for (var profileKey in profileObj) { + for (const profileKey in profileObj) { if (profileObj.hasOwnProperty(profileKey)) { valid = true; - var profileVal = profileObj[profileKey]; + let profileVal = profileObj[profileKey]; if (profileVal == null) { delete profileObj[profileKey]; @@ -2411,8 +2015,8 @@ return valid; }; - var processFBUserObj = function processFBUserObj(user) { - var profileData = {}; + const processFBUserObj = user => { + const profileData = {}; profileData.Name = user.name; if (user.id != null) { @@ -2428,16 +2032,16 @@ profileData.Gender = 'O'; } - var getHighestEducation = function getHighestEducation(eduArr) { + const getHighestEducation = function (eduArr) { if (eduArr != null) { - var college = ''; - var highschool = ''; + let college = ''; + let highschool = ''; - for (var i = 0; i < eduArr.length; i++) { - var _edu = eduArr[i]; + for (let i = 0; i < eduArr.length; i++) { + const edu = eduArr[i]; - if (_edu.type != null) { - var type = _edu.type; + if (edu.type != null) { + const type = edu.type; if (type === 'Graduate School') { return 'Graduate'; @@ -2465,13 +2069,13 @@ } } - var edu = getHighestEducation(user.education); + const edu = getHighestEducation(user.education); if (edu != null) { profileData.Education = edu; } - var work = user.work != null ? user.work.length : 0; + const work = user.work != null ? user.work.length : 0; if (work > 0) { profileData.Employed = 'Y'; @@ -2484,16 +2088,18 @@ } if (user.birthday != null) { - var mmddyy = user.birthday.split('/'); // comes in as "08/15/1947" + const mmddyy = user.birthday.split('/'); // comes in as "08/15/1947" profileData.DOB = setDate(mmddyy[2] + mmddyy[0] + mmddyy[1]); } return profileData; }; - var processGPlusUserObj = function processGPlusUserObj(user, _ref2) { - var logger = _ref2.logger; - var profileData = {}; + const processGPlusUserObj = (user, _ref2) => { + let { + logger + } = _ref2; + const profileData = {}; if (user.displayName != null) { profileData.Name = user.displayName; @@ -2520,8 +2126,8 @@ } if (user.emails != null) { - for (var emailIdx = 0; emailIdx < user.emails.length; emailIdx++) { - var emailObj = user.emails[emailIdx]; + for (let emailIdx = 0; emailIdx < user.emails.length; emailIdx++) { + const emailObj = user.emails[emailIdx]; if (emailObj.type === 'account') { profileData.Email = emailObj.value; @@ -2532,8 +2138,8 @@ if (user.organizations != null) { profileData.Employed = 'N'; - for (var i = 0; i < user.organizations.length; i++) { - var orgObj = user.organizations[i]; + for (let i = 0; i < user.organizations.length; i++) { + const orgObj = user.organizations[i]; if (orgObj.type === 'work') { profileData.Employed = 'Y'; @@ -2542,7 +2148,7 @@ } if (user.birthday != null) { - var yyyymmdd = user.birthday.split('-'); // comes in as "1976-07-27" + const yyyymmdd = user.birthday.split('-'); // comes in as "1976-07-27" profileData.DOB = setDate(yyyymmdd[0] + yyyymmdd[1] + yyyymmdd[2]); } @@ -2558,7 +2164,7 @@ logger.debug('gplus usr profile ' + JSON.stringify(profileData)); return profileData; }; - var addToLocalProfileMap = function addToLocalProfileMap(profileObj, override) { + const addToLocalProfileMap = (profileObj, override) => { if (StorageManager._isLocalStorageSupported()) { if ($ct.globalProfileMap == null) { $ct.globalProfileMap = StorageManager.readFromLSorCookie(PR_COOKIE); @@ -2570,9 +2176,9 @@ if (profileObj._custom != null) { - var keys = profileObj._custom; + const keys = profileObj._custom; - for (var key in keys) { + for (const key in keys) { if (keys.hasOwnProperty(key)) { profileObj[key] = keys[key]; } @@ -2581,7 +2187,7 @@ delete profileObj._custom; } - for (var prop in profileObj) { + for (const prop in profileObj) { if (profileObj.hasOwnProperty(prop)) { if ($ct.globalProfileMap.hasOwnProperty(prop) && !override) { continue; @@ -2598,11 +2204,11 @@ StorageManager.saveToLSorCookie(PR_COOKIE, $ct.globalProfileMap); } }; - var closeIframe = function closeIframe(campaignId, divIdIgnored, currentSessionId) { + const closeIframe = (campaignId, divIdIgnored, currentSessionId) => { if (campaignId != null && campaignId !== '-1') { if (StorageManager._isLocalStorageSupported()) { - var campaignObj = getCampaignObject(); - var sessionCampaignObj = campaignObj.wp[currentSessionId]; + const campaignObj = getCampaignObject(); + let sessionCampaignObj = campaignObj.wp[currentSessionId]; if (sessionCampaignObj == null) { sessionCampaignObj = {}; @@ -2615,7 +2221,7 @@ } if ($ct.campaignDivMap != null) { - var divId = $ct.campaignDivMap[campaignId]; + const divId = $ct.campaignDivMap[campaignId]; if (divId != null) { document.getElementById(divId).style.display = 'none'; @@ -2628,24 +2234,24 @@ } } }; - var arp = function arp(jsonMap) { + const arp = jsonMap => { // For unregister calls dont set arp in LS if (jsonMap.skipResARP != null && jsonMap.skipResARP) { console.debug('Update ARP Request rejected', jsonMap); return null; } - var isOULARP = jsonMap[IS_OUL] === true; + const isOULARP = jsonMap[IS_OUL] === true; if (StorageManager._isLocalStorageSupported()) { // Update arp only if it is null or an oul request try { - var arpFromStorage = StorageManager.readFromLSorCookie(ARP_COOKIE); + let arpFromStorage = StorageManager.readFromLSorCookie(ARP_COOKIE); if (arpFromStorage == null || isOULARP) { arpFromStorage = {}; - for (var key in jsonMap) { + for (const key in jsonMap) { if (jsonMap.hasOwnProperty(key)) { if (jsonMap[key] === -1) { delete arpFromStorage[key]; @@ -2662,22 +2268,22 @@ } } }; - var setEnum = function setEnum(enumVal, logger) { + const setEnum = (enumVal, logger) => { if (isString(enumVal) || isNumber(enumVal)) { return '$E_' + enumVal; } logger.error(ENUM_FORMAT_ERROR); }; - var handleEmailSubscription = function handleEmailSubscription(subscription, reEncoded, fetchGroups, account, logger) { - var urlParamsAsIs = getURLParams(location.href); // can't use url_params as it is in lowercase above + const handleEmailSubscription = (subscription, reEncoded, fetchGroups, account, logger) => { + const urlParamsAsIs = getURLParams(location.href); // can't use url_params as it is in lowercase above - var encodedEmailId = urlParamsAsIs.e; - var encodedProfileProps = urlParamsAsIs.p; - var pageType = urlParamsAsIs.page_type; + const encodedEmailId = urlParamsAsIs.e; + const encodedProfileProps = urlParamsAsIs.p; + const pageType = urlParamsAsIs.page_type; if (typeof encodedEmailId !== 'undefined') { - var data = {}; + const data = {}; data.id = account.id; // accountId data.unsubGroups = $ct.unsubGroups; // unsubscribe groups @@ -2686,7 +2292,7 @@ data[categoryLongKey] = $ct.updatedCategoryLong; } - var url = account.emailURL; + let url = account.emailURL; if (fetchGroups) { url = addToURL(url, 'fetchGroups', fetchGroups); @@ -2728,338 +2334,321 @@ var _processProfileArray = _classPrivateFieldLooseKey("processProfileArray"); - var ProfileHandler = /*#__PURE__*/function (_Array) { - _inherits(ProfileHandler, _Array); - - var _super = _createSuper(ProfileHandler); - - function ProfileHandler(_ref, values) { - var _this; - - var logger = _ref.logger, - request = _ref.request, - account = _ref.account, - isPersonalisationActive = _ref.isPersonalisationActive; - - _classCallCheck(this, ProfileHandler); - - _this = _super.call(this); - Object.defineProperty(_assertThisInitialized(_this), _processProfileArray, { + class ProfileHandler extends Array { + constructor(_ref, values) { + let { + logger, + request, + account, + isPersonalisationActive + } = _ref; + super(); + Object.defineProperty(this, _processProfileArray, { value: _processProfileArray2 }); - Object.defineProperty(_assertThisInitialized(_this), _logger$3, { + Object.defineProperty(this, _logger$3, { writable: true, value: void 0 }); - Object.defineProperty(_assertThisInitialized(_this), _request$2, { + Object.defineProperty(this, _request$2, { writable: true, value: void 0 }); - Object.defineProperty(_assertThisInitialized(_this), _account, { + Object.defineProperty(this, _account, { writable: true, value: void 0 }); - Object.defineProperty(_assertThisInitialized(_this), _oldValues$1, { + Object.defineProperty(this, _oldValues$1, { writable: true, value: void 0 }); - Object.defineProperty(_assertThisInitialized(_this), _isPersonalisationActive$1, { + Object.defineProperty(this, _isPersonalisationActive$1, { writable: true, value: void 0 }); - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _logger$3)[_logger$3] = logger; - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _request$2)[_request$2] = request; - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _account)[_account] = account; - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _oldValues$1)[_oldValues$1] = values; - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _isPersonalisationActive$1)[_isPersonalisationActive$1] = isPersonalisationActive; - return _this; + _classPrivateFieldLooseBase(this, _logger$3)[_logger$3] = logger; + _classPrivateFieldLooseBase(this, _request$2)[_request$2] = request; + _classPrivateFieldLooseBase(this, _account)[_account] = account; + _classPrivateFieldLooseBase(this, _oldValues$1)[_oldValues$1] = values; + _classPrivateFieldLooseBase(this, _isPersonalisationActive$1)[_isPersonalisationActive$1] = isPersonalisationActive; } - _createClass(ProfileHandler, [{ - key: "push", - value: function push() { - for (var _len = arguments.length, profilesArr = new Array(_len), _key = 0; _key < _len; _key++) { - profilesArr[_key] = arguments[_key]; - } + push() { + for (var _len = arguments.length, profilesArr = new Array(_len), _key = 0; _key < _len; _key++) { + profilesArr[_key] = arguments[_key]; + } - _classPrivateFieldLooseBase(this, _processProfileArray)[_processProfileArray](profilesArr); + _classPrivateFieldLooseBase(this, _processProfileArray)[_processProfileArray](profilesArr); + + return 0; + } - return 0; + _processOldValues() { + if (_classPrivateFieldLooseBase(this, _oldValues$1)[_oldValues$1]) { + _classPrivateFieldLooseBase(this, _processProfileArray)[_processProfileArray](_classPrivateFieldLooseBase(this, _oldValues$1)[_oldValues$1]); } - }, { - key: "_processOldValues", - value: function _processOldValues() { - if (_classPrivateFieldLooseBase(this, _oldValues$1)[_oldValues$1]) { - _classPrivateFieldLooseBase(this, _processProfileArray)[_processProfileArray](_classPrivateFieldLooseBase(this, _oldValues$1)[_oldValues$1]); - } - _classPrivateFieldLooseBase(this, _oldValues$1)[_oldValues$1] = null; + _classPrivateFieldLooseBase(this, _oldValues$1)[_oldValues$1] = null; + } + + getAttribute(propName) { + if (!_classPrivateFieldLooseBase(this, _isPersonalisationActive$1)[_isPersonalisationActive$1]()) { + return; } - }, { - key: "getAttribute", - value: function getAttribute(propName) { - if (!_classPrivateFieldLooseBase(this, _isPersonalisationActive$1)[_isPersonalisationActive$1]()) { - return; - } - if ($ct.globalProfileMap == null) { - $ct.globalProfileMap = StorageManager.readFromLSorCookie(PR_COOKIE); - } + if ($ct.globalProfileMap == null) { + $ct.globalProfileMap = StorageManager.readFromLSorCookie(PR_COOKIE); + } - if ($ct.globalProfileMap != null) { - return $ct.globalProfileMap[propName]; - } + if ($ct.globalProfileMap != null) { + return $ct.globalProfileMap[propName]; } - }, { - key: "_handleIncrementDecrementValue", + } - /** - * - * @param {any} key - * @param {number} value - * @param {string} command - * increases or decreases value of the number type properties in profile object - */ - value: function _handleIncrementDecrementValue(key, value, command) { - var _$ct$globalProfileMap; + /** + * + * @param {any} key + * @param {number} value + * @param {string} command + * increases or decreases value of the number type properties in profile object + */ + _handleIncrementDecrementValue(key, value, command) { + var _$ct$globalProfileMap; + + // Check if the value is greater than 0 + if ($ct.globalProfileMap == null) { + $ct.globalProfileMap = StorageManager.readFromLSorCookie(PR_COOKIE); + } + + if ($ct.globalProfileMap == null && !((_$ct$globalProfileMap = $ct.globalProfileMap) === null || _$ct$globalProfileMap === void 0 ? void 0 : _$ct$globalProfileMap.hasOwnProperty(key))) { + // Check if the profile map already has the propery defined + console.error('Kindly create profile with required proprty to increment/decrement.'); + } else if (!value || typeof value !== 'number' || value <= 0) { + console.error('Value should be a number greater than 0'); + } else { + // Update the profile property in local storage + if (command === COMMAND_INCREMENT) { + $ct.globalProfileMap[key] = $ct.globalProfileMap[key] + value; + } else { + $ct.globalProfileMap[key] = $ct.globalProfileMap[key] - value; + } + + StorageManager.saveToLSorCookie(PR_COOKIE, $ct.globalProfileMap); // Send the updated value to LC + + let data = {}; + const profileObj = {}; + data.type = 'profile'; + profileObj[key] = { + [command]: value + }; - // Check if the value is greater than 0 - if ($ct.globalProfileMap == null) { - $ct.globalProfileMap = StorageManager.readFromLSorCookie(PR_COOKIE); + if (profileObj.tz == null) { + // try to auto capture user timezone if not present + profileObj.tz = new Date().toString().match(/([A-Z]+[\+-][0-9]+)/)[1]; } - if ($ct.globalProfileMap == null && !((_$ct$globalProfileMap = $ct.globalProfileMap) === null || _$ct$globalProfileMap === void 0 ? void 0 : _$ct$globalProfileMap.hasOwnProperty(key))) { - // Check if the profile map already has the propery defined - console.error('Kindly create profile with required proprty to increment/decrement.'); - } else if (!value || typeof value !== 'number' || value <= 0) { - console.error('Value should be a number greater than 0'); - } else { - // Update the profile property in local storage - if (command === COMMAND_INCREMENT) { - $ct.globalProfileMap[key] = $ct.globalProfileMap[key] + value; - } else { - $ct.globalProfileMap[key] = $ct.globalProfileMap[key] - value; - } - - StorageManager.saveToLSorCookie(PR_COOKIE, $ct.globalProfileMap); // Send the updated value to LC + data.profile = profileObj; + data = _classPrivateFieldLooseBase(this, _request$2)[_request$2].addSystemDataToObject(data, true); - var data = {}; - var profileObj = {}; - data.type = 'profile'; - profileObj[key] = _defineProperty({}, command, value); + _classPrivateFieldLooseBase(this, _request$2)[_request$2].addFlags(data); - if (profileObj.tz == null) { - // try to auto capture user timezone if not present - profileObj.tz = new Date().toString().match(/([A-Z]+[\+-][0-9]+)/)[1]; - } + const compressedData = compressData(JSON.stringify(data), _classPrivateFieldLooseBase(this, _logger$3)[_logger$3]); - data.profile = profileObj; - data = _classPrivateFieldLooseBase(this, _request$2)[_request$2].addSystemDataToObject(data, true); + let pageLoadUrl = _classPrivateFieldLooseBase(this, _account)[_account].dataPostURL; - _classPrivateFieldLooseBase(this, _request$2)[_request$2].addFlags(data); + pageLoadUrl = addToURL(pageLoadUrl, 'type', EVT_PUSH); + pageLoadUrl = addToURL(pageLoadUrl, 'd', compressedData); - var compressedData = compressData(JSON.stringify(data), _classPrivateFieldLooseBase(this, _logger$3)[_logger$3]); + _classPrivateFieldLooseBase(this, _request$2)[_request$2].saveAndFireRequest(pageLoadUrl, $ct.blockRequest); + } + } + /** + * + * @param {any} key + * @param {array} arrayVal + * @param {string} command + * overwrites/sets new value(s) against a key/property in profile object + */ - var pageLoadUrl = _classPrivateFieldLooseBase(this, _account)[_account].dataPostURL; - pageLoadUrl = addToURL(pageLoadUrl, 'type', EVT_PUSH); - pageLoadUrl = addToURL(pageLoadUrl, 'd', compressedData); + _handleMultiValueSet(key, arrayVal, command) { + const array = []; - _classPrivateFieldLooseBase(this, _request$2)[_request$2].saveAndFireRequest(pageLoadUrl, $ct.blockRequest); + for (let i = 0; i < arrayVal.length; i++) { + if (typeof arrayVal[i] === 'number' && !array.includes(arrayVal[i])) { + array.push(arrayVal[i]); + } else if (typeof arrayVal[i] === 'string' && !array.includes(arrayVal[i].toLowerCase())) { + array.push(arrayVal[i].toLowerCase()); + } else { + console.error('array supports only string or number type values'); } } - /** - * - * @param {any} key - * @param {array} arrayVal - * @param {string} command - * overwrites/sets new value(s) against a key/property in profile object - */ - - }, { - key: "_handleMultiValueSet", - value: function _handleMultiValueSet(key, arrayVal, command) { - var array = []; - for (var i = 0; i < arrayVal.length; i++) { - if (typeof arrayVal[i] === 'number' && !array.includes(arrayVal[i])) { - array.push(arrayVal[i]); - } else if (typeof arrayVal[i] === 'string' && !array.includes(arrayVal[i].toLowerCase())) { - array.push(arrayVal[i].toLowerCase()); - } else { - console.error('array supports only string or number type values'); - } - } + if ($ct.globalProfileMap == null) { + var _StorageManager$readF; - if ($ct.globalProfileMap == null) { - var _StorageManager$readF; + $ct.globalProfileMap = (_StorageManager$readF = StorageManager.readFromLSorCookie(PR_COOKIE)) !== null && _StorageManager$readF !== void 0 ? _StorageManager$readF : {}; + } - $ct.globalProfileMap = (_StorageManager$readF = StorageManager.readFromLSorCookie(PR_COOKIE)) !== null && _StorageManager$readF !== void 0 ? _StorageManager$readF : {}; - } + $ct.globalProfileMap[key] = array; + StorageManager.saveToLSorCookie(PR_COOKIE, $ct.globalProfileMap); + this.sendMultiValueData(key, arrayVal, command); + } + /** + * + * @param {any} propKey - the property name to be added in the profile object + * @param {string, number, array} propVal - the property value to be added against the @propkey key + * @param {string} command + * Adds array or single value against a key/property in profile object + */ - $ct.globalProfileMap[key] = array; - StorageManager.saveToLSorCookie(PR_COOKIE, $ct.globalProfileMap); - this.sendMultiValueData(key, arrayVal, command); - } - /** - * - * @param {any} propKey - the property name to be added in the profile object - * @param {string, number, array} propVal - the property value to be added against the @propkey key - * @param {string} command - * Adds array or single value against a key/property in profile object - */ - }, { - key: "_handleMultiValueAdd", - value: function _handleMultiValueAdd(propKey, propVal, command) { - // Initialize array - var array = []; // Check if globalProfileMap is null, initialize if needed + _handleMultiValueAdd(propKey, propVal, command) { + // Initialize array + var array = []; // Check if globalProfileMap is null, initialize if needed - if ($ct.globalProfileMap == null) { - $ct.globalProfileMap = StorageManager.readFromLSorCookie(PR_COOKIE) || {}; - } // Check if the value to be set is either string or number + if ($ct.globalProfileMap == null) { + $ct.globalProfileMap = StorageManager.readFromLSorCookie(PR_COOKIE) || {}; + } // Check if the value to be set is either string or number - if (typeof propVal === 'string' || typeof propVal === 'number') { - if ($ct.globalProfileMap.hasOwnProperty(propKey)) { - array = $ct.globalProfileMap[propKey]; - array.push(typeof propVal === 'number' ? propVal : propVal.toLowerCase()); + if (typeof propVal === 'string' || typeof propVal === 'number') { + if ($ct.globalProfileMap.hasOwnProperty(propKey)) { + array = $ct.globalProfileMap[propKey]; + array.push(typeof propVal === 'number' ? propVal : propVal.toLowerCase()); + } else { + $ct.globalProfileMap[propKey] = propVal; + } + } else { + // Check if propVal is an array + if ($ct.globalProfileMap.hasOwnProperty(propKey)) { + array = Array.isArray($ct.globalProfileMap[propKey]) ? $ct.globalProfileMap[propKey] : [$ct.globalProfileMap[propKey]]; + } // Check for case-sensitive inputs and filter the same ones + + + for (var i = 0; i < propVal.length; i++) { + if (typeof propVal[i] === 'number' && !array.includes(propVal[i])) { + array.push(propVal[i]); + } else if (typeof propVal[i] === 'string' && !array.includes(propVal[i].toLowerCase())) { + array.push(propVal[i].toLowerCase()); + } else if (typeof propVal[i] === 'number' && array.includes(propVal[i]) || typeof propVal[i] === 'string' && array.includes(propVal[i].toLowerCase())) { + console.error('Values already included'); } else { - $ct.globalProfileMap[propKey] = propVal; + console.error('Array supports only string or number type values'); } - } else { - // Check if propVal is an array - if ($ct.globalProfileMap.hasOwnProperty(propKey)) { - array = Array.isArray($ct.globalProfileMap[propKey]) ? $ct.globalProfileMap[propKey] : [$ct.globalProfileMap[propKey]]; - } // Check for case-sensitive inputs and filter the same ones - - - for (var i = 0; i < propVal.length; i++) { - if (typeof propVal[i] === 'number' && !array.includes(propVal[i])) { - array.push(propVal[i]); - } else if (typeof propVal[i] === 'string' && !array.includes(propVal[i].toLowerCase())) { - array.push(propVal[i].toLowerCase()); - } else if (typeof propVal[i] === 'number' && array.includes(propVal[i]) || typeof propVal[i] === 'string' && array.includes(propVal[i].toLowerCase())) { - console.error('Values already included'); - } else { - console.error('Array supports only string or number type values'); - } - } // Update globalProfileMap with the array + } // Update globalProfileMap with the array - $ct.globalProfileMap[propKey] = array; - } // Save to local storage or cookie + $ct.globalProfileMap[propKey] = array; + } // Save to local storage or cookie - StorageManager.saveToLSorCookie(PR_COOKIE, $ct.globalProfileMap); // Call the sendMultiValueData function + StorageManager.saveToLSorCookie(PR_COOKIE, $ct.globalProfileMap); // Call the sendMultiValueData function - this.sendMultiValueData(propKey, propVal, command); - } - /** - * - * @param {any} propKey - * @param {string, number, array} propVal - * @param {string} command - * removes value(s) against a key/property in profile object - */ + this.sendMultiValueData(propKey, propVal, command); + } + /** + * + * @param {any} propKey + * @param {string, number, array} propVal + * @param {string} command + * removes value(s) against a key/property in profile object + */ - }, { - key: "_handleMultiValueRemove", - value: function _handleMultiValueRemove(propKey, propVal, command) { - var _$ct$globalProfileMap2; - if ($ct.globalProfileMap == null) { - $ct.globalProfileMap = StorageManager.readFromLSorCookie(PR_COOKIE); - } + _handleMultiValueRemove(propKey, propVal, command) { + var _$ct$globalProfileMap2; - if (!($ct === null || $ct === void 0 ? void 0 : (_$ct$globalProfileMap2 = $ct.globalProfileMap) === null || _$ct$globalProfileMap2 === void 0 ? void 0 : _$ct$globalProfileMap2.hasOwnProperty(propKey))) { - console.error("The property ".concat(propKey, " does not exist.")); - } else { - if (typeof propVal === 'string' || typeof propVal === 'number') { - var index = $ct.globalProfileMap[propKey].indexOf(propVal); + if ($ct.globalProfileMap == null) { + $ct.globalProfileMap = StorageManager.readFromLSorCookie(PR_COOKIE); + } - if (index !== -1) { - $ct.globalProfileMap[propKey].splice(index, 1); - } - } else { - for (var k = 0; k < propVal.length; k++) { - var idx = $ct.globalProfileMap[propKey].indexOf(propVal[k]); + if (!($ct === null || $ct === void 0 ? void 0 : (_$ct$globalProfileMap2 = $ct.globalProfileMap) === null || _$ct$globalProfileMap2 === void 0 ? void 0 : _$ct$globalProfileMap2.hasOwnProperty(propKey))) { + console.error("The property ".concat(propKey, " does not exist.")); + } else { + if (typeof propVal === 'string' || typeof propVal === 'number') { + var index = $ct.globalProfileMap[propKey].indexOf(propVal); - if (idx !== -1) { - $ct.globalProfileMap[propKey].splice(idx, 1); - } + if (index !== -1) { + $ct.globalProfileMap[propKey].splice(index, 1); + } + } else { + for (var k = 0; k < propVal.length; k++) { + var idx = $ct.globalProfileMap[propKey].indexOf(propVal[k]); + + if (idx !== -1) { + $ct.globalProfileMap[propKey].splice(idx, 1); } } } - - StorageManager.saveToLSorCookie(PR_COOKIE, $ct.globalProfileMap); - this.sendMultiValueData(propKey, propVal, command); } - /** - * - * @param {any} propKey - * @param {string} command - * deletes a key value pair from the profile object - */ - }, { - key: "_handleMultiValueDelete", - value: function _handleMultiValueDelete(propKey, command) { - var _$ct$globalProfileMap3; + StorageManager.saveToLSorCookie(PR_COOKIE, $ct.globalProfileMap); + this.sendMultiValueData(propKey, propVal, command); + } + /** + * + * @param {any} propKey + * @param {string} command + * deletes a key value pair from the profile object + */ - if ($ct.globalProfileMap == null) { - $ct.globalProfileMap = StorageManager.readFromLSorCookie(PR_COOKIE); - } - if (!($ct === null || $ct === void 0 ? void 0 : (_$ct$globalProfileMap3 = $ct.globalProfileMap) === null || _$ct$globalProfileMap3 === void 0 ? void 0 : _$ct$globalProfileMap3.hasOwnProperty(propKey))) { - console.error("The property ".concat(propKey, " does not exist.")); - } else { - delete $ct.globalProfileMap[propKey]; - } + _handleMultiValueDelete(propKey, command) { + var _$ct$globalProfileMap3; - StorageManager.saveToLSorCookie(PR_COOKIE, $ct.globalProfileMap); - this.sendMultiValueData(propKey, null, command); + if ($ct.globalProfileMap == null) { + $ct.globalProfileMap = StorageManager.readFromLSorCookie(PR_COOKIE); } - }, { - key: "sendMultiValueData", - value: function sendMultiValueData(propKey, propVal, command) { - // Send the updated value to LC - var data = {}; - var profileObj = {}; - data.type = 'profile'; // this removes the property at backend - profileObj[propKey] = _defineProperty({}, command, command === COMMAND_DELETE ? true : propVal); + if (!($ct === null || $ct === void 0 ? void 0 : (_$ct$globalProfileMap3 = $ct.globalProfileMap) === null || _$ct$globalProfileMap3 === void 0 ? void 0 : _$ct$globalProfileMap3.hasOwnProperty(propKey))) { + console.error("The property ".concat(propKey, " does not exist.")); + } else { + delete $ct.globalProfileMap[propKey]; + } - if (profileObj.tz == null) { - profileObj.tz = new Date().toString().match(/([A-Z]+[\+-][0-9]+)/)[1]; - } + StorageManager.saveToLSorCookie(PR_COOKIE, $ct.globalProfileMap); + this.sendMultiValueData(propKey, null, command); + } - data.profile = profileObj; - data = _classPrivateFieldLooseBase(this, _request$2)[_request$2].addSystemDataToObject(data, true); + sendMultiValueData(propKey, propVal, command) { + // Send the updated value to LC + let data = {}; + const profileObj = {}; + data.type = 'profile'; // this removes the property at backend - _classPrivateFieldLooseBase(this, _request$2)[_request$2].addFlags(data); + profileObj[propKey] = { + [command]: command === COMMAND_DELETE ? true : propVal + }; - var compressedData = compressData(JSON.stringify(data), _classPrivateFieldLooseBase(this, _logger$3)[_logger$3]); + if (profileObj.tz == null) { + profileObj.tz = new Date().toString().match(/([A-Z]+[\+-][0-9]+)/)[1]; + } - var pageLoadUrl = _classPrivateFieldLooseBase(this, _account)[_account].dataPostURL; + data.profile = profileObj; + data = _classPrivateFieldLooseBase(this, _request$2)[_request$2].addSystemDataToObject(data, true); - pageLoadUrl = addToURL(pageLoadUrl, 'type', EVT_PUSH); - pageLoadUrl = addToURL(pageLoadUrl, 'd', compressedData); + _classPrivateFieldLooseBase(this, _request$2)[_request$2].addFlags(data); - _classPrivateFieldLooseBase(this, _request$2)[_request$2].saveAndFireRequest(pageLoadUrl, $ct.blockRequest); - } - }]); + const compressedData = compressData(JSON.stringify(data), _classPrivateFieldLooseBase(this, _logger$3)[_logger$3]); + + let pageLoadUrl = _classPrivateFieldLooseBase(this, _account)[_account].dataPostURL; + + pageLoadUrl = addToURL(pageLoadUrl, 'type', EVT_PUSH); + pageLoadUrl = addToURL(pageLoadUrl, 'd', compressedData); - return ProfileHandler; - }( /*#__PURE__*/_wrapNativeSuper(Array)); + _classPrivateFieldLooseBase(this, _request$2)[_request$2].saveAndFireRequest(pageLoadUrl, $ct.blockRequest); + } + + } var _processProfileArray2 = function _processProfileArray2(profileArr) { if (Array.isArray(profileArr) && profileArr.length > 0) { - for (var index in profileArr) { + for (const index in profileArr) { if (profileArr.hasOwnProperty(index)) { - var outerObj = profileArr[index]; - var data = {}; - var profileObj = void 0; + const outerObj = profileArr[index]; + let data = {}; + let profileObj; if (outerObj.Site != null) { // organic data from the site @@ -3072,13 +2661,13 @@ } } else if (outerObj.Facebook != null) { // fb connect data - var FbProfileObj = outerObj.Facebook; // make sure that the object contains any data at all + const FbProfileObj = outerObj.Facebook; // make sure that the object contains any data at all if (!isObjectEmpty(FbProfileObj) && !FbProfileObj.error) { profileObj = processFBUserObj(FbProfileObj); } } else if (outerObj['Google Plus'] != null) { - var GPlusProfileObj = outerObj['Google Plus']; + const GPlusProfileObj = outerObj['Google Plus']; if (!isObjectEmpty(GPlusProfileObj) && !GPlusProfileObj.error) { profileObj = processGPlusUserObj(GPlusProfileObj, { @@ -3102,9 +2691,9 @@ _classPrivateFieldLooseBase(this, _request$2)[_request$2].addFlags(data); - var compressedData = compressData(JSON.stringify(data), _classPrivateFieldLooseBase(this, _logger$3)[_logger$3]); + const compressedData = compressData(JSON.stringify(data), _classPrivateFieldLooseBase(this, _logger$3)[_logger$3]); - var pageLoadUrl = _classPrivateFieldLooseBase(this, _account)[_account].dataPostURL; + let pageLoadUrl = _classPrivateFieldLooseBase(this, _account)[_account].dataPostURL; pageLoadUrl = addToURL(pageLoadUrl, 'type', EVT_PUSH); pageLoadUrl = addToURL(pageLoadUrl, 'd', compressedData); @@ -3136,113 +2725,97 @@ var _processLoginArray = _classPrivateFieldLooseKey("processLoginArray"); - var UserLoginHandler = /*#__PURE__*/function (_Array) { - _inherits(UserLoginHandler, _Array); - - var _super = _createSuper(UserLoginHandler); - - function UserLoginHandler(_ref, values) { - var _this; - - var request = _ref.request, - account = _ref.account, - session = _ref.session, - logger = _ref.logger, - device = _ref.device; - - _classCallCheck(this, UserLoginHandler); - - _this = _super.call(this); - Object.defineProperty(_assertThisInitialized(_this), _processLoginArray, { + class UserLoginHandler extends Array { + constructor(_ref, values) { + let { + request, + account, + session, + logger, + device + } = _ref; + super(); + Object.defineProperty(this, _processLoginArray, { value: _processLoginArray2 }); - Object.defineProperty(_assertThisInitialized(_this), _deleteUser, { + Object.defineProperty(this, _deleteUser, { value: _deleteUser2 }); - Object.defineProperty(_assertThisInitialized(_this), _handleCookieFromCache, { + Object.defineProperty(this, _handleCookieFromCache, { value: _handleCookieFromCache2 }); - Object.defineProperty(_assertThisInitialized(_this), _processOUL, { + Object.defineProperty(this, _processOUL, { value: _processOUL2 }); - Object.defineProperty(_assertThisInitialized(_this), _request$3, { + Object.defineProperty(this, _request$3, { writable: true, value: void 0 }); - Object.defineProperty(_assertThisInitialized(_this), _logger$4, { + Object.defineProperty(this, _logger$4, { writable: true, value: void 0 }); - Object.defineProperty(_assertThisInitialized(_this), _account$1, { + Object.defineProperty(this, _account$1, { writable: true, value: void 0 }); - Object.defineProperty(_assertThisInitialized(_this), _session$1, { + Object.defineProperty(this, _session$1, { writable: true, value: void 0 }); - Object.defineProperty(_assertThisInitialized(_this), _oldValues$2, { + Object.defineProperty(this, _oldValues$2, { writable: true, value: void 0 }); - Object.defineProperty(_assertThisInitialized(_this), _device$1, { + Object.defineProperty(this, _device$1, { writable: true, value: void 0 }); - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _request$3)[_request$3] = request; - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _account$1)[_account$1] = account; - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _session$1)[_session$1] = session; - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _logger$4)[_logger$4] = logger; - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _oldValues$2)[_oldValues$2] = values; - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _device$1)[_device$1] = device; - return _this; + _classPrivateFieldLooseBase(this, _request$3)[_request$3] = request; + _classPrivateFieldLooseBase(this, _account$1)[_account$1] = account; + _classPrivateFieldLooseBase(this, _session$1)[_session$1] = session; + _classPrivateFieldLooseBase(this, _logger$4)[_logger$4] = logger; + _classPrivateFieldLooseBase(this, _oldValues$2)[_oldValues$2] = values; + _classPrivateFieldLooseBase(this, _device$1)[_device$1] = device; } // On User Login - _createClass(UserLoginHandler, [{ - key: "clear", - value: function clear() { - _classPrivateFieldLooseBase(this, _logger$4)[_logger$4].debug('clear called. Reset flag has been set.'); + clear() { + _classPrivateFieldLooseBase(this, _logger$4)[_logger$4].debug('clear called. Reset flag has been set.'); - _classPrivateFieldLooseBase(this, _deleteUser)[_deleteUser](); + _classPrivateFieldLooseBase(this, _deleteUser)[_deleteUser](); - StorageManager.setMetaProp(CLEAR, true); + StorageManager.setMetaProp(CLEAR, true); + } + + push() { + for (var _len = arguments.length, profilesArr = new Array(_len), _key = 0; _key < _len; _key++) { + profilesArr[_key] = arguments[_key]; } - }, { - key: "push", - value: function push() { - for (var _len = arguments.length, profilesArr = new Array(_len), _key = 0; _key < _len; _key++) { - profilesArr[_key] = arguments[_key]; - } - _classPrivateFieldLooseBase(this, _processLoginArray)[_processLoginArray](profilesArr); + _classPrivateFieldLooseBase(this, _processLoginArray)[_processLoginArray](profilesArr); - return 0; - } - }, { - key: "_processOldValues", - value: function _processOldValues() { - if (_classPrivateFieldLooseBase(this, _oldValues$2)[_oldValues$2]) { - _classPrivateFieldLooseBase(this, _processLoginArray)[_processLoginArray](_classPrivateFieldLooseBase(this, _oldValues$2)[_oldValues$2]); - } + return 0; + } - _classPrivateFieldLooseBase(this, _oldValues$2)[_oldValues$2] = null; + _processOldValues() { + if (_classPrivateFieldLooseBase(this, _oldValues$2)[_oldValues$2]) { + _classPrivateFieldLooseBase(this, _processLoginArray)[_processLoginArray](_classPrivateFieldLooseBase(this, _oldValues$2)[_oldValues$2]); } - }]); - return UserLoginHandler; - }( /*#__PURE__*/_wrapNativeSuper(Array)); + _classPrivateFieldLooseBase(this, _oldValues$2)[_oldValues$2] = null; + } - var _processOUL2 = function _processOUL2(profileArr) { - var _this2 = this; + } - var sendOULFlag = true; + var _processOUL2 = function _processOUL2(profileArr) { + let sendOULFlag = true; StorageManager.saveToLSorCookie(FIRE_PUSH_UNREGISTERED, sendOULFlag); - var addToK = function addToK(ids) { - var k = StorageManager.readFromLSorCookie(KCOOKIE_NAME); - var g = StorageManager.readFromLSorCookie(GCOOKIE_NAME); - var kId; + const addToK = ids => { + let k = StorageManager.readFromLSorCookie(KCOOKIE_NAME); + const g = StorageManager.readFromLSorCookie(GCOOKIE_NAME); + let kId; if (k == null) { k = {}; @@ -3250,8 +2823,8 @@ } else { /* check if already exists */ kId = k.id; - var anonymousUser = false; - var foundInCache = false; + let anonymousUser = false; + let foundInCache = false; if (kId == null) { kId = ids[0]; @@ -3271,9 +2844,9 @@ } else { // check if the id is present in the cache // set foundInCache to true - for (var idx in ids) { + for (const idx in ids) { if (ids.hasOwnProperty(idx)) { - var id = ids[idx]; + const id = ids[idx]; if ($ct.LRU_CACHE.cache[id]) { kId = id; @@ -3288,30 +2861,30 @@ if (kId !== $ct.LRU_CACHE.getLastKey()) { // New User found // remove the entire cache - _classPrivateFieldLooseBase(_this2, _handleCookieFromCache)[_handleCookieFromCache](); + _classPrivateFieldLooseBase(this, _handleCookieFromCache)[_handleCookieFromCache](); } else { sendOULFlag = false; StorageManager.saveToLSorCookie(FIRE_PUSH_UNREGISTERED, sendOULFlag); } - var gFromCache = $ct.LRU_CACHE.get(kId); + const gFromCache = $ct.LRU_CACHE.get(kId); $ct.LRU_CACHE.set(kId, gFromCache); StorageManager.saveToLSorCookie(GCOOKIE_NAME, gFromCache); - _classPrivateFieldLooseBase(_this2, _device$1)[_device$1].gcookie = gFromCache; - var lastK = $ct.LRU_CACHE.getSecondLastKey(); + _classPrivateFieldLooseBase(this, _device$1)[_device$1].gcookie = gFromCache; + const lastK = $ct.LRU_CACHE.getSecondLastKey(); if (StorageManager.readFromLSorCookie(FIRE_PUSH_UNREGISTERED) && lastK !== -1) { // CACHED OLD USER FOUND. TRANSFER PUSH TOKEN TO THIS USER - var lastGUID = $ct.LRU_CACHE.cache[lastK]; + const lastGUID = $ct.LRU_CACHE.cache[lastK]; - _classPrivateFieldLooseBase(_this2, _request$3)[_request$3].unregisterTokenForGuid(lastGUID); + _classPrivateFieldLooseBase(this, _request$3)[_request$3].unregisterTokenForGuid(lastGUID); } } else { if (!anonymousUser) { - _this2.clear(); + this.clear(); } else { if (g != null) { - _classPrivateFieldLooseBase(_this2, _device$1)[_device$1].gcookie = g; + _classPrivateFieldLooseBase(this, _device$1)[_device$1].gcookie = g; StorageManager.saveToLSorCookie(GCOOKIE_NAME, g); sendOULFlag = false; } @@ -3327,11 +2900,11 @@ }; if (Array.isArray(profileArr) && profileArr.length > 0) { - for (var index in profileArr) { + for (const index in profileArr) { if (profileArr.hasOwnProperty(index)) { - var outerObj = profileArr[index]; - var data = {}; - var profileObj = void 0; + const outerObj = profileArr[index]; + let data = {}; + let profileObj; if (outerObj.Site != null) { // organic data from the site @@ -3344,13 +2917,13 @@ } } else if (outerObj.Facebook != null) { // fb connect data - var FbProfileObj = outerObj.Facebook; // make sure that the object contains any data at all + const FbProfileObj = outerObj.Facebook; // make sure that the object contains any data at all if (!isObjectEmpty(FbProfileObj) && !FbProfileObj.error) { profileObj = processFBUserObj(FbProfileObj); } } else if (outerObj['Google Plus'] != null) { - var GPlusProfileObj = outerObj['Google Plus']; + const GPlusProfileObj = outerObj['Google Plus']; if (isObjectEmpty(GPlusProfileObj) && !GPlusProfileObj.error) { profileObj = processGPlusUserObj(GPlusProfileObj, { @@ -3369,7 +2942,7 @@ } data.profile = profileObj; - var ids = []; + const ids = []; if (StorageManager._isLocalStorageSupported()) { if (profileObj.Identity) { @@ -3405,9 +2978,9 @@ data[IS_OUL] = true; } - var compressedData = compressData(JSON.stringify(data), _classPrivateFieldLooseBase(this, _logger$4)[_logger$4]); + const compressedData = compressData(JSON.stringify(data), _classPrivateFieldLooseBase(this, _logger$4)[_logger$4]); - var pageLoadUrl = _classPrivateFieldLooseBase(this, _account$1)[_account$1].dataPostURL; + let pageLoadUrl = _classPrivateFieldLooseBase(this, _account$1)[_account$1].dataPostURL; pageLoadUrl = addToURL(pageLoadUrl, 'type', EVT_PUSH); pageLoadUrl = addToURL(pageLoadUrl, 'd', compressedData); // Whenever sendOULFlag is true then dont send arp and gcookie (guid in memory in the request) @@ -3475,8 +3048,8 @@ var _processLoginArray2 = function _processLoginArray2(loginArr) { if (Array.isArray(loginArr) && loginArr.length > 0) { - var profileObj = loginArr.pop(); - var processProfile = profileObj != null && isObject(profileObj) && (profileObj.Site != null && Object.keys(profileObj.Site).length > 0 || profileObj.Facebook != null && Object.keys(profileObj.Facebook).length > 0 || profileObj['Google Plus'] != null && Object.keys(profileObj['Google Plus']).length > 0); + const profileObj = loginArr.pop(); + const processProfile = profileObj != null && isObject(profileObj) && (profileObj.Site != null && Object.keys(profileObj.Site).length > 0 || profileObj.Facebook != null && Object.keys(profileObj.Facebook).length > 0 || profileObj['Google Plus'] != null && Object.keys(profileObj['Google Plus']).length > 0); if (processProfile) { StorageManager.setInstantDeleteFlagInK(); @@ -3492,1362 +3065,1185 @@ } }; - var CTWebPersonalisationBanner = /*#__PURE__*/function (_HTMLElement) { - _inherits(CTWebPersonalisationBanner, _HTMLElement); - - var _super = _createSuper(CTWebPersonalisationBanner); - - function CTWebPersonalisationBanner() { - var _this; - - _classCallCheck(this, CTWebPersonalisationBanner); - - _this = _super.call(this); - _this._details = null; - _this.shadow = null; - _this.shadow = _this.attachShadow({ + class CTWebPersonalisationBanner extends HTMLElement { + constructor() { + super(); + this._details = null; + this.shadow = null; + this.shadow = this.attachShadow({ mode: 'open' }); - return _this; } - _createClass(CTWebPersonalisationBanner, [{ - key: "renderBanner", - value: function renderBanner() { - var _this2 = this; + get details() { + return this._details || ''; + } + + set details(val) { + if (this._details === null) { + this._details = val; + this.renderBanner(); + } + } - this.shadow.innerHTML = this.getBannerContent(); + renderBanner() { + this.shadow.innerHTML = this.getBannerContent(); - if (this.trackClick !== false) { - this.addEventListener('click', function () { - var onClickUrl = _this2.details.onClick; + if (this.trackClick !== false) { + this.addEventListener('click', () => { + const onClickUrl = this.details.onClick; - if (onClickUrl) { - _this2.details.window ? window.open(onClickUrl, '_blank') : window.parent.location.href = onClickUrl; - } + if (onClickUrl) { + this.details.window ? window.open(onClickUrl, '_blank') : window.parent.location.href = onClickUrl; + } - window.clevertap.renderNotificationClicked({ - msgId: _this2.msgId, - pivotId: _this2.pivotId - }); + window.clevertap.renderNotificationClicked({ + msgId: this.msgId, + pivotId: this.pivotId }); - } - - window.clevertap.renderNotificationViewed({ - msgId: this.msgId, - pivotId: this.pivotId }); } - }, { - key: "getBannerContent", - value: function getBannerContent() { - return "\n \n
\n "); - } - }, { - key: "details", - get: function get() { - return this._details || ''; - }, - set: function set(val) { - if (this._details === null) { - this._details = val; - this.renderBanner(); - } - } - }]); - - return CTWebPersonalisationBanner; - }( /*#__PURE__*/_wrapNativeSuper(HTMLElement)); - var CTWebPersonalisationCarousel = /*#__PURE__*/function (_HTMLElement) { - _inherits(CTWebPersonalisationCarousel, _HTMLElement); - - var _super = _createSuper(CTWebPersonalisationCarousel); + window.clevertap.renderNotificationViewed({ + msgId: this.msgId, + pivotId: this.pivotId + }); + } - function CTWebPersonalisationCarousel() { - var _this; + getBannerContent() { + return "\n \n \n "); + } - _classCallCheck(this, CTWebPersonalisationCarousel); + } - _this = _super.call(this); - _this._target = null; - _this._carousel = null; - _this.shadow = null; - _this.slides = 0; - _this.previouslySelectedItem = -1; - _this.selectedItem = 1; - _this.autoSlide = null; - _this.stopAutoSlideTimeout = null; - _this.shadow = _this.attachShadow({ + class CTWebPersonalisationCarousel extends HTMLElement { + constructor() { + super(); + this._target = null; + this._carousel = null; + this.shadow = null; + this.slides = 0; + this.previouslySelectedItem = -1; + this.selectedItem = 1; + this.autoSlide = null; + this.stopAutoSlideTimeout = null; + this.shadow = this.attachShadow({ mode: 'open' }); if (customElements.get('ct-web-personalisation-banner') === undefined) { customElements.define('ct-web-personalisation-banner', CTWebPersonalisationBanner); } + } - return _this; + get target() { + return this._target || ''; } - _createClass(CTWebPersonalisationCarousel, [{ - key: "renderCarousel", - value: function renderCarousel() { - this.slides = this.details.length; - this.shadow.innerHTML = this.getStyles(); - var carousel = this.getCarouselContent(); + set target(val) { + if (this._target === null) { + this._target = val; + this.renderCarousel(); + } + } - if (this.display.showNavBtns) { - carousel.insertAdjacentHTML('beforeend', this.display.navBtnsHtml); - } + get details() { + return this.target.display.details; + } - if (this.display.showNavArrows) { - carousel.insertAdjacentHTML('beforeend', this.display.leftNavArrowHtml); - carousel.insertAdjacentHTML('beforeend', this.display.rightNavArrowHtml); - } + get display() { + return this.target.display; + } - this._carousel = carousel; - this.shadow.appendChild(carousel); - this.setupClick(); - this.updateSelectedItem(); // TODO: enable conditionally + renderCarousel() { + this.slides = this.details.length; + this.shadow.innerHTML = this.getStyles(); + const carousel = this.getCarouselContent(); - this.startAutoSlide(); - this.setupOnHover(); - window.clevertap.renderNotificationViewed({ - msgId: this.target.wzrk_id, - pivotId: this.target.wzrk_pivot - }); + if (this.display.showNavBtns) { + carousel.insertAdjacentHTML('beforeend', this.display.navBtnsHtml); } - }, { - key: "setupClick", - value: function setupClick() { - var _this2 = this; - - this._carousel.addEventListener('click', function (event) { - var eventID = event.target.id; - if (eventID.startsWith('carousel__button')) { - var selected = +eventID.split('-')[1]; + if (this.display.showNavArrows) { + carousel.insertAdjacentHTML('beforeend', this.display.leftNavArrowHtml); + carousel.insertAdjacentHTML('beforeend', this.display.rightNavArrowHtml); + } - if (selected !== _this2.selectedItem) { - _this2.previouslySelectedItem = _this2.selectedItem; - _this2.selectedItem = selected; + this._carousel = carousel; + this.shadow.appendChild(carousel); + this.setupClick(); + this.updateSelectedItem(); // TODO: enable conditionally - _this2.updateSelectedItem(); + this.startAutoSlide(); + this.setupOnHover(); + window.clevertap.renderNotificationViewed({ + msgId: this.target.wzrk_id, + pivotId: this.target.wzrk_pivot + }); + } - _this2.startAutoSlide(); - } - } else if (eventID.startsWith('carousel__arrow')) { - eventID.endsWith('right') ? _this2.goToNext() : _this2.goToPrev(); - - _this2.startAutoSlide(); - } else if (eventID.indexOf('-') > -1) { - var item = +eventID.split('-')[1]; - var index = item - 1; - - if (window.parent.clevertap) { - // console.log('Raise notification clicked event for ', item) - window.clevertap.renderNotificationClicked({ - msgId: _this2.target.wzrk_id, - pivotId: _this2.target.wzrk_pivot, - wzrk_slideNo: item - }); - } + setupClick() { + this._carousel.addEventListener('click', event => { + const eventID = event.target.id; - var url = _this2.details[index].onClick; + if (eventID.startsWith('carousel__button')) { + const selected = +eventID.split('-')[1]; - if (url !== '') { - _this2.details[index].window ? window.open(url, '_blank') : window.location.href = url; - } + if (selected !== this.selectedItem) { + this.previouslySelectedItem = this.selectedItem; + this.selectedItem = selected; + this.updateSelectedItem(); + this.startAutoSlide(); } - }); - } - }, { - key: "setupOnHover", - value: function setupOnHover() { - var _this3 = this; - - this._carousel.addEventListener('mouseenter', function (event) { - _this3.stopAutoSlideTimeout = setTimeout(function () { - _this3.autoSlide = clearInterval(_this3.autoSlide); - }, 500); - }); + } else if (eventID.startsWith('carousel__arrow')) { + eventID.endsWith('right') ? this.goToNext() : this.goToPrev(); + this.startAutoSlide(); + } else if (eventID.indexOf('-') > -1) { + const item = +eventID.split('-')[1]; + const index = item - 1; - this._carousel.addEventListener('mouseleave', function (event) { - clearTimeout(_this3.stopAutoSlideTimeout); - - if (_this3.autoSlide === undefined) { - _this3.startAutoSlide(); + if (window.parent.clevertap) { + // console.log('Raise notification clicked event for ', item) + window.clevertap.renderNotificationClicked({ + msgId: this.target.wzrk_id, + pivotId: this.target.wzrk_pivot, + wzrk_slideNo: item + }); } - }); - } - }, { - key: "getCarouselContent", - value: function getCarouselContent() { - var carousel = document.createElement('div'); - carousel.setAttribute('class', 'carousel'); - this.details.forEach(function (detail, i) { - var banner = document.createElement('ct-web-personalisation-banner'); - banner.classList.add('carousel__item'); - banner.trackClick = false; - banner.setAttribute('id', "carousel__item-".concat(i + 1)); - banner.details = detail; - carousel.appendChild(banner); - }); - return carousel; - } - }, { - key: "getStyles", - value: function getStyles() { - var _this$target, _this$target$display; - return "\n \n "); - } - }, { - key: "updateSelectedItem", - value: function updateSelectedItem() { - if (this.previouslySelectedItem !== -1) { - var prevItem = this.shadow.getElementById("carousel__item-".concat(this.previouslySelectedItem)); - var prevButton = this.shadow.getElementById("carousel__button-".concat(this.previouslySelectedItem)); - prevItem.classList.remove('carousel__item--selected'); + const url = this.details[index].onClick; - if (prevButton) { - prevButton.classList.remove('carousel__button--selected'); + if (url !== '') { + this.details[index].window ? window.open(url, '_blank') : window.location.href = url; } } + }); + } - var item = this.shadow.getElementById("carousel__item-".concat(this.selectedItem)); - var button = this.shadow.getElementById("carousel__button-".concat(this.selectedItem)); - item.classList.add('carousel__item--selected'); + setupOnHover() { + this._carousel.addEventListener('mouseenter', event => { + this.stopAutoSlideTimeout = setTimeout(() => { + this.autoSlide = clearInterval(this.autoSlide); + }, 500); + }); + + this._carousel.addEventListener('mouseleave', event => { + clearTimeout(this.stopAutoSlideTimeout); - if (button) { - button.classList.add('carousel__button--selected'); + if (this.autoSlide === undefined) { + this.startAutoSlide(); } - } - }, { - key: "startAutoSlide", - value: function startAutoSlide() { - var _this4 = this; + }); + } - clearInterval(this.autoSlide); - this.autoSlide = setInterval(function () { - _this4.goToNext(); - }, this.display.sliderTime ? this.display.sliderTime * 1000 : 3000); - } - }, { - key: "goToNext", - value: function goToNext() { - this.goTo(this.selectedItem, (this.selectedItem + 1) % this.slides); - } - }, { - key: "goToPrev", - value: function goToPrev() { - this.goTo(this.selectedItem, this.selectedItem - 1); - } - }, { - key: "goTo", - value: function goTo(prev, cur) { - this.previouslySelectedItem = prev; - this.selectedItem = cur; + getCarouselContent() { + const carousel = document.createElement('div'); + carousel.setAttribute('class', 'carousel'); + this.details.forEach((detail, i) => { + const banner = document.createElement('ct-web-personalisation-banner'); + banner.classList.add('carousel__item'); + banner.trackClick = false; + banner.setAttribute('id', "carousel__item-".concat(i + 1)); + banner.details = detail; + carousel.appendChild(banner); + }); + return carousel; + } - if (cur === 0) { - this.selectedItem = this.slides; - } + getStyles() { + var _this$target, _this$target$display; - this.updateSelectedItem(); - } - }, { - key: "target", - get: function get() { - return this._target || ''; - }, - set: function set(val) { - if (this._target === null) { - this._target = val; - this.renderCarousel(); + return "\n \n "); + } + + updateSelectedItem() { + if (this.previouslySelectedItem !== -1) { + const prevItem = this.shadow.getElementById("carousel__item-".concat(this.previouslySelectedItem)); + const prevButton = this.shadow.getElementById("carousel__button-".concat(this.previouslySelectedItem)); + prevItem.classList.remove('carousel__item--selected'); + + if (prevButton) { + prevButton.classList.remove('carousel__button--selected'); } } - }, { - key: "details", - get: function get() { - return this.target.display.details; - } - }, { - key: "display", - get: function get() { - return this.target.display; + + const item = this.shadow.getElementById("carousel__item-".concat(this.selectedItem)); + const button = this.shadow.getElementById("carousel__button-".concat(this.selectedItem)); + item.classList.add('carousel__item--selected'); + + if (button) { + button.classList.add('carousel__button--selected'); } - }]); + } + + startAutoSlide() { + clearInterval(this.autoSlide); + this.autoSlide = setInterval(() => { + this.goToNext(); + }, this.display.sliderTime ? this.display.sliderTime * 1000 : 3000); + } + + goToNext() { + this.goTo(this.selectedItem, (this.selectedItem + 1) % this.slides); + } - return CTWebPersonalisationCarousel; - }( /*#__PURE__*/_wrapNativeSuper(HTMLElement)); + goToPrev() { + this.goTo(this.selectedItem, this.selectedItem - 1); + } - var CTWebPopupImageOnly = /*#__PURE__*/function (_HTMLElement) { - _inherits(CTWebPopupImageOnly, _HTMLElement); + goTo(prev, cur) { + this.previouslySelectedItem = prev; + this.selectedItem = cur; - var _super = _createSuper(CTWebPopupImageOnly); + if (cur === 0) { + this.selectedItem = this.slides; + } - function CTWebPopupImageOnly() { - var _this; + this.updateSelectedItem(); + } - _classCallCheck(this, CTWebPopupImageOnly); + } - _this = _super.call(this); - _this._target = null; - _this._session = null; - _this.shadow = null; - _this.popup = null; - _this.container = null; - _this.resizeObserver = null; - _this.shadow = _this.attachShadow({ + class CTWebPopupImageOnly extends HTMLElement { + constructor() { + super(); + this._target = null; + this._session = null; + this.shadow = null; + this.popup = null; + this.container = null; + this.resizeObserver = null; + this.shadow = this.attachShadow({ mode: 'open' }); - return _this; } - _createClass(CTWebPopupImageOnly, [{ - key: "renderImageOnlyPopup", - value: function renderImageOnlyPopup() { - var _this2 = this; + get target() { + return this._target || ''; + } + + set target(val) { + if (this._target === null) { + this._target = val; + this.renderImageOnlyPopup(); + } + } - var campaignId = this.target.wzrk_id.split('_')[0]; - var currentSessionId = this.session.sessionId; - this.shadow.innerHTML = this.getImageOnlyPopupContent(); - this.popup = this.shadowRoot.getElementById('imageOnlyPopup'); - this.container = this.shadowRoot.getElementById('container'); - this.closeIcon = this.shadowRoot.getElementById('close'); - this.popup.addEventListener('load', this.updateImageAndContainerWidth()); - this.resizeObserver = new ResizeObserver(function () { - return _this2.handleResize(_this2.popup, _this2.container); - }); - this.resizeObserver.observe(this.popup); - this.closeIcon.addEventListener('click', function () { - _this2.resizeObserver.unobserve(_this2.popup); + get session() { + return this._session || ''; + } - document.getElementById('wzrkImageOnlyDiv').style.display = 'none'; + set session(val) { + this._session = val; + } - _this2.remove(); + get msgId() { + return this.target.wzrk_id; + } - if (campaignId != null && campaignId !== '-1') { - if (StorageManager._isLocalStorageSupported()) { - var campaignObj = getCampaignObject(); - var sessionCampaignObj = campaignObj.wp[currentSessionId]; + get pivotId() { + return this.target.wzrk_pivot; + } - if (sessionCampaignObj == null) { - sessionCampaignObj = {}; - campaignObj[currentSessionId] = sessionCampaignObj; - } + get onClickUrl() { + return this.target.display.onClickUrl; + } - sessionCampaignObj[campaignId] = 'dnd'; - saveCampaignObject(campaignObj); + renderImageOnlyPopup() { + const campaignId = this.target.wzrk_id.split('_')[0]; + const currentSessionId = this.session.sessionId; + this.shadow.innerHTML = this.getImageOnlyPopupContent(); + this.popup = this.shadowRoot.getElementById('imageOnlyPopup'); + this.container = this.shadowRoot.getElementById('container'); + this.closeIcon = this.shadowRoot.getElementById('close'); + this.popup.addEventListener('load', this.updateImageAndContainerWidth()); + this.resizeObserver = new ResizeObserver(() => this.handleResize(this.popup, this.container)); + this.resizeObserver.observe(this.popup); + this.closeIcon.addEventListener('click', () => { + this.resizeObserver.unobserve(this.popup); + document.getElementById('wzrkImageOnlyDiv').style.display = 'none'; + this.remove(); + + if (campaignId != null && campaignId !== '-1') { + if (StorageManager._isLocalStorageSupported()) { + const campaignObj = getCampaignObject(); + let sessionCampaignObj = campaignObj.wp[currentSessionId]; + + if (sessionCampaignObj == null) { + sessionCampaignObj = {}; + campaignObj[currentSessionId] = sessionCampaignObj; } + + sessionCampaignObj[campaignId] = 'dnd'; + saveCampaignObject(campaignObj); } - }); - window.clevertap.renderNotificationViewed({ - msgId: this.msgId, - pivotId: this.pivotId - }); + } + }); + window.clevertap.renderNotificationViewed({ + msgId: this.msgId, + pivotId: this.pivotId + }); - if (this.onClickUrl) { - this.popup.addEventListener('click', function () { - _this2.target.display.window ? window.open(_this2.onClickUrl, '_blank') : window.parent.location.href = _this2.onClickUrl; - window.clevertap.renderNotificationClicked({ - msgId: _this2.msgId, - pivotId: _this2.pivotId - }); + if (this.onClickUrl) { + this.popup.addEventListener('click', () => { + this.target.display.window ? window.open(this.onClickUrl, '_blank') : window.parent.location.href = this.onClickUrl; + window.clevertap.renderNotificationClicked({ + msgId: this.msgId, + pivotId: this.pivotId }); - } - } - }, { - key: "handleResize", - value: function handleResize(popup, container) { - var width = this.getRenderedImageWidth(popup); - container.style.setProperty('width', "".concat(width, "px")); - } - }, { - key: "getImageOnlyPopupContent", - value: function getImageOnlyPopupContent() { - return "\n ".concat(this.target.msgContent.css, "\n ").concat(this.target.msgContent.html, "\n "); + }); } - }, { - key: "updateImageAndContainerWidth", - value: function updateImageAndContainerWidth() { - var _this3 = this; - - return function () { - var width = _this3.getRenderedImageWidth(_this3.popup); - - _this3.popup.style.setProperty('width', "".concat(width, "px")); + } - _this3.container.style.setProperty('width', "".concat(width, "px")); + handleResize(popup, container) { + const width = this.getRenderedImageWidth(popup); + container.style.setProperty('width', "".concat(width, "px")); + } - _this3.container.style.setProperty('height', 'auto'); + getImageOnlyPopupContent() { + return "\n ".concat(this.target.msgContent.css, "\n ").concat(this.target.msgContent.html, "\n "); + } - _this3.container.style.setProperty('position', 'fixed'); + updateImageAndContainerWidth() { + return () => { + const width = this.getRenderedImageWidth(this.popup); + this.popup.style.setProperty('width', "".concat(width, "px")); + this.container.style.setProperty('width', "".concat(width, "px")); + this.container.style.setProperty('height', 'auto'); + this.container.style.setProperty('position', 'fixed'); + this.popup.style.setProperty('visibility', 'visible'); + this.closeIcon.style.setProperty('visibility', 'visible'); + document.getElementById('wzrkImageOnlyDiv').style.visibility = 'visible'; + }; + } - _this3.popup.style.setProperty('visibility', 'visible'); + getRenderedImageWidth(img) { + const ratio = img.naturalWidth / img.naturalHeight; + return img.height * ratio; + } - _this3.closeIcon.style.setProperty('visibility', 'visible'); + } - document.getElementById('wzrkImageOnlyDiv').style.visibility = 'visible'; - }; - } - }, { - key: "getRenderedImageWidth", - value: function getRenderedImageWidth(img) { - var ratio = img.naturalWidth / img.naturalHeight; - return img.height * ratio; - } - }, { - key: "target", - get: function get() { - return this._target || ''; - }, - set: function set(val) { - if (this._target === null) { - this._target = val; - this.renderImageOnlyPopup(); - } - } - }, { - key: "session", - get: function get() { - return this._session || ''; - }, - set: function set(val) { - this._session = val; - } - }, { - key: "msgId", - get: function get() { - return this.target.wzrk_id; - } - }, { - key: "pivotId", - get: function get() { - return this.target.wzrk_pivot; - } - }, { - key: "onClickUrl", - get: function get() { - return this.target.display.onClickUrl; - } - }]); - - return CTWebPopupImageOnly; - }( /*#__PURE__*/_wrapNativeSuper(HTMLElement)); - - var Message = /*#__PURE__*/function (_HTMLElement) { - _inherits(Message, _HTMLElement); - - var _super = _createSuper(Message); - - function Message(config, message) { - var _this; - - _classCallCheck(this, Message); - - _this = _super.call(this); - _this.wrapper = null; - _this.snackBar = null; - _this.shadow = _this.attachShadow({ + class Message extends HTMLElement { + constructor(config, message) { + super(); + this.wrapper = null; + this.snackBar = null; + this.shadow = this.attachShadow({ mode: 'open' }); - _this.config = config; - _this.message = message; + this.config = config; + this.message = message; + this.renderMessage(message); + } + + get pivotId() { + return this.message.wzrk_pivot; + } + + get campaignId() { + return this.message.wzrk_id; + } + + createEl(type, id, part) { + const _el = document.createElement(type); - _this.renderMessage(message); + _el.setAttribute('id', id); - return _this; + _el.setAttribute('part', part || id); + + return _el; } - _createClass(Message, [{ - key: "createEl", - value: function createEl(type, id, part) { - var _el = document.createElement(type); + renderMessage(msg) { + this.wrapper = this.createEl('div', 'messageWrapper'); - _el.setAttribute('id', id); + switch (msg.templateType) { + case 'text-only': + case 'text-with-icon': + case 'text-with-icon-and-image': + { + const message = this.prepareBasicMessage(msg.msg[0]); + this.wrapper.appendChild(message); + } + } - _el.setAttribute('part', part || id); + const timeStamp = this.createEl('div', 'timeStamp'); + timeStamp.innerHTML = "".concat(determineTimeStampText(msg.id.split('_')[1]), ""); - return _el; + if (!msg.viewed) { + const unreadMarker = this.createEl('span', 'unreadMarker'); + timeStamp.appendChild(unreadMarker); } - }, { - key: "renderMessage", - value: function renderMessage(msg) { - this.wrapper = this.createEl('div', 'messageWrapper'); - switch (msg.templateType) { - case 'text-only': - case 'text-with-icon': - case 'text-with-icon-and-image': - { - var message = this.prepareBasicMessage(msg.msg[0]); - this.wrapper.appendChild(message); - } - } + this.wrapper.appendChild(timeStamp); + this.shadow.appendChild(this.wrapper); + } - var timeStamp = this.createEl('div', 'timeStamp'); - timeStamp.innerHTML = "".concat(determineTimeStampText(msg.id.split('_')[1]), ""); + prepareBasicMessage(msg) { + const message = this.createEl('div', 'message'); - if (!msg.viewed) { - var unreadMarker = this.createEl('span', 'unreadMarker'); - timeStamp.appendChild(unreadMarker); - } + if (msg.imageUrl) { + const imageContainer = this.addImage(msg.imageUrl, 'mainImg'); + message.appendChild(imageContainer); + } + + const iconTitleDescWrapper = this.createEl('div', 'iconTitleDescWrapper'); + + if (msg.iconUrl) { + const iconContainer = this.addImage(msg.iconUrl, 'iconImg'); + iconTitleDescWrapper.appendChild(iconContainer); + } + + const titleDescWrapper = this.createEl('div', 'titleDescWrapper'); - this.wrapper.appendChild(timeStamp); - this.shadow.appendChild(this.wrapper); + if (msg.title) { + const title = this.createEl('div', 'title'); + title.innerText = msg.title; + titleDescWrapper.appendChild(title); } - }, { - key: "prepareBasicMessage", - value: function prepareBasicMessage(msg) { - var message = this.createEl('div', 'message'); - if (msg.imageUrl) { - var imageContainer = this.addImage(msg.imageUrl, 'mainImg'); - message.appendChild(imageContainer); - } + if (msg.description) { + const description = this.createEl('div', 'description'); + description.innerText = msg.description; + titleDescWrapper.appendChild(description); + } - var iconTitleDescWrapper = this.createEl('div', 'iconTitleDescWrapper'); + if (msg.title || msg.description) { + iconTitleDescWrapper.appendChild(titleDescWrapper); + } - if (msg.iconUrl) { - var iconContainer = this.addImage(msg.iconUrl, 'iconImg'); - iconTitleDescWrapper.appendChild(iconContainer); - } + if (msg.iconUrl || msg.title || msg.description) { + message.appendChild(iconTitleDescWrapper); + } - var titleDescWrapper = this.createEl('div', 'titleDescWrapper'); + if (msg.buttons && msg.buttons.length) { + const buttonsContainer = this.addButtons(msg.buttons); + message.appendChild(buttonsContainer); + } - if (msg.title) { - var title = this.createEl('div', 'title'); - title.innerText = msg.title; - titleDescWrapper.appendChild(title); - } + return message; + } - if (msg.description) { - var description = this.createEl('div', 'description'); - description.innerText = msg.description; - titleDescWrapper.appendChild(description); - } + addButtons() { + let buttons = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + const buttonsContainer = this.createEl('div', 'buttonsContainer'); + let hasCopyAction = false; + buttons.forEach((b, i) => { + const button = this.createEl('button', "button-".concat(i), 'button'); + button.innerText = b.text; - if (msg.title || msg.description) { - iconTitleDescWrapper.appendChild(titleDescWrapper); + if (i > 0) { + button.style.cssText += 'margin-left: 2px;'; } - if (msg.iconUrl || msg.title || msg.description) { - message.appendChild(iconTitleDescWrapper); + if (b.action === 'copy') { + hasCopyAction = true; } - if (msg.buttons && msg.buttons.length) { - var buttonsContainer = this.addButtons(msg.buttons); - message.appendChild(buttonsContainer); - } + buttonsContainer.appendChild(button); + }); - return message; + if (hasCopyAction) { + this.addSnackbar(buttonsContainer); } - }, { - key: "addButtons", - value: function addButtons() { - var _this2 = this; - - var buttons = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - var buttonsContainer = this.createEl('div', 'buttonsContainer'); - var hasCopyAction = false; - buttons.forEach(function (b, i) { - var button = _this2.createEl('button', "button-".concat(i), 'button'); - button.innerText = b.text; + return buttonsContainer; + } - if (i > 0) { - button.style.cssText += 'margin-left: 2px;'; - } + addSnackbar(buttonsContainer) { + this.snackBar = this.createEl('div', "snackbar-".concat(this.campaignId), 'snackbar'); + this.snackBar.innerHTML = greenTickSvg; + const clipboardMsg = this.createEl('span', "snackbar-msg-".concat(this.campaignId), 'snackbar-msg'); + clipboardMsg.innerText = 'Copied to clipboard'; + this.snackBar.appendChild(clipboardMsg); + buttonsContainer.appendChild(this.snackBar); + } - if (b.action === 'copy') { - hasCopyAction = true; - } + addImage(url, type) { + const imageContainer = this.createEl('div', "".concat(type, "Container")); + const image = this.createEl('img', type); + image.setAttribute('src', url); // images will be fetched as and when the element comes into the viewport - buttonsContainer.appendChild(button); - }); + image.setAttribute('loading', 'lazy'); + imageContainer.appendChild(image); + return imageContainer; + } - if (hasCopyAction) { - this.addSnackbar(buttonsContainer); - } - - return buttonsContainer; - } - }, { - key: "addSnackbar", - value: function addSnackbar(buttonsContainer) { - this.snackBar = this.createEl('div', "snackbar-".concat(this.campaignId), 'snackbar'); - this.snackBar.innerHTML = greenTickSvg; - var clipboardMsg = this.createEl('span', "snackbar-msg-".concat(this.campaignId), 'snackbar-msg'); - clipboardMsg.innerText = 'Copied to clipboard'; - this.snackBar.appendChild(clipboardMsg); - buttonsContainer.appendChild(this.snackBar); - } - }, { - key: "addImage", - value: function addImage(url, type) { - var imageContainer = this.createEl('div', "".concat(type, "Container")); - var image = this.createEl('img', type); - image.setAttribute('src', url); // images will be fetched as and when the element comes into the viewport - - image.setAttribute('loading', 'lazy'); - imageContainer.appendChild(image); - return imageContainer; - } - }, { - key: "raiseClickedEvent", - value: function raiseClickedEvent(path, isPreview) { - switch (this.message.templateType) { - case 'text-only': - case 'text-with-icon': - case 'text-with-icon-and-image': - { - this.raiseClickedForBasicTemplates(path, isPreview); - } - } + raiseClickedEvent(path, isPreview) { + switch (this.message.templateType) { + case 'text-only': + case 'text-with-icon': + case 'text-with-icon-and-image': + { + this.raiseClickedForBasicTemplates(path, isPreview); + } } - }, { - key: "raiseClickedForBasicTemplates", - value: function raiseClickedForBasicTemplates(path, isPreview) { - var _this3 = this; - - var msg = this.message.msg[0]; - var payload = { - msgId: this.campaignId, - pivotId: this.pivotId - }; + } - if (path.tagName === 'BUTTON') { - var id = path.id.split('-')[1]; - var button = msg.buttons[id]; - payload.kv = { - wzrk_c2a: button.text - }; + raiseClickedForBasicTemplates(path, isPreview) { + const msg = this.message.msg[0]; + const payload = { + msgId: this.campaignId, + pivotId: this.pivotId + }; - if (button.action === 'url') { - button.openUrlInNewTab ? window.open(button.url, '_blank') : window.location = button.url; - } else if (button.action === 'copy') { - window.focus(); - navigator.clipboard.writeText(button.clipboardText); - this.snackBar.style.setProperty('display', 'flex', 'important'); - setTimeout(function () { - _this3.snackBar.style.setProperty('display', 'none', 'important'); - }, 2000); - } - } else if (path.tagName === 'CT-INBOX-MESSAGE' && msg.onClickUrl) { - msg.openUrlInNewTab ? window.open(msg.onClickUrl, '_blank') : window.location = msg.onClickUrl; - } + if (path.tagName === 'BUTTON') { + const id = path.id.split('-')[1]; + const button = msg.buttons[id]; + payload.kv = { + wzrk_c2a: button.text + }; - if (isPreview) { - console.log('Notifiction clicked event will be raised at run time with payload ::', payload); - } else { - window.clevertap.renderNotificationClicked(payload); + if (button.action === 'url') { + button.openUrlInNewTab ? window.open(button.url, '_blank') : window.location = button.url; + } else if (button.action === 'copy') { + window.focus(); + navigator.clipboard.writeText(button.clipboardText); + this.snackBar.style.setProperty('display', 'flex', 'important'); + setTimeout(() => { + this.snackBar.style.setProperty('display', 'none', 'important'); + }, 2000); } + } else if (path.tagName === 'CT-INBOX-MESSAGE' && msg.onClickUrl) { + msg.openUrlInNewTab ? window.open(msg.onClickUrl, '_blank') : window.location = msg.onClickUrl; } - }, { - key: "pivotId", - get: function get() { - return this.message.wzrk_pivot; - } - }, { - key: "campaignId", - get: function get() { - return this.message.wzrk_id; + + if (isPreview) { + console.log('Notifiction clicked event will be raised at run time with payload ::', payload); + } else { + window.clevertap.renderNotificationClicked(payload); } - }]); + } - return Message; - }( /*#__PURE__*/_wrapNativeSuper(HTMLElement)); + } - var messageStyles = function messageStyles(_ref) { - var backgroundColor = _ref.backgroundColor, - borderColor = _ref.borderColor, - titleColor = _ref.titleColor, - descriptionColor = _ref.descriptionColor, - buttonColor = _ref.buttonColor, - buttonTextColor = _ref.buttonTextColor, - unreadMarkerColor = _ref.unreadMarkerColor; + const messageStyles = (_ref) => { + let { + backgroundColor, + borderColor, + titleColor, + descriptionColor, + buttonColor, + buttonTextColor, + unreadMarkerColor + } = _ref; return "\n \n "); }; - var inboxContainerStyles = function inboxContainerStyles(_ref2) { - var panelBackgroundColor = _ref2.panelBackgroundColor, - panelBorderColor = _ref2.panelBorderColor, - headerBackgroundColor = _ref2.headerBackgroundColor, - headerTitleColor = _ref2.headerTitleColor, - closeIconColor = _ref2.closeIconColor, - categoriesTabColor = _ref2.categoriesTabColor, - categoriesTitleColor = _ref2.categoriesTitleColor, - categoriesBorderColor = _ref2.categoriesBorderColor, - selectedCategoryTabColor = _ref2.selectedCategoryTabColor, - selectedCategoryTitleColor = _ref2.selectedCategoryTitleColor, - selectedCategoryBorderColor = _ref2.selectedCategoryBorderColor, - headerCategoryHeight = _ref2.headerCategoryHeight; + const inboxContainerStyles = (_ref2) => { + let { + panelBackgroundColor, + panelBorderColor, + headerBackgroundColor, + headerTitleColor, + closeIconColor, + categoriesTabColor, + categoriesTitleColor, + categoriesBorderColor, + selectedCategoryTabColor, + selectedCategoryTitleColor, + selectedCategoryBorderColor, + headerCategoryHeight + } = _ref2; return "\n \n "); }; - var Inbox = /*#__PURE__*/function (_HTMLElement) { - _inherits(Inbox, _HTMLElement); - - var _super = _createSuper(Inbox); - - function Inbox(logger) { - var _this; - - _classCallCheck(this, Inbox); - - _this = _super.call(this); - _this.isInboxOpen = false; - _this.isInboxFromFlutter = false; - _this.selectedCategory = null; - _this.unviewedMessages = {}; - _this.unviewedCounter = 0; - _this.isPreview = false; - _this.inboxConfigForPreview = {}; - _this.inboxSelector = null; - _this.inbox = null; - _this.emptyInboxMsg = null; - _this.inboxCard = null; - _this.unviewedBadge = null; - _this.observer = null; - _this.selectedCategoryRef = null; - - _this.addClickListenerOnDocument = function () { - return function (e) { - if (e.composedPath().includes(_this.inbox)) { + class Inbox extends HTMLElement { + constructor(logger) { + super(); + this.isInboxOpen = false; + this.isInboxFromFlutter = false; + this.selectedCategory = null; + this.unviewedMessages = {}; + this.unviewedCounter = 0; + this.isPreview = false; + this.inboxConfigForPreview = {}; + this.inboxSelector = null; + this.inbox = null; + this.emptyInboxMsg = null; + this.inboxCard = null; + this.unviewedBadge = null; + this.observer = null; + this.selectedCategoryRef = null; + + this.addClickListenerOnDocument = (() => { + return e => { + if (e.composedPath().includes(this.inbox)) { // path is not supported on FF. So we fallback to e.composedPath - var path = e.path || e.composedPath && e.composedPath(); + const path = e.path || e.composedPath && e.composedPath(); if (path.length) { - var id = path[0].id; + const id = path[0].id; if (id === 'closeInbox') { - _this.toggleInbox(); + this.toggleInbox(); } else if (id.startsWith('category-')) { - _this.prevCategoryRef = _this.selectedCategoryRef; - _this.selectedCategoryRef = path[0]; - - _this.updateActiveCategory(path[0].innerText); + this.prevCategoryRef = this.selectedCategoryRef; + this.selectedCategoryRef = path[0]; + this.updateActiveCategory(path[0].innerText); } else { - var _path = path.filter(function (p) { + const _path = path.filter(p => { var _p$id; return ((_p$id = p.id) === null || _p$id === void 0 ? void 0 : _p$id.startsWith('button-')) || p.tagName === 'CT-INBOX-MESSAGE'; }); if (_path.length) { - var messageEl = _path[_path.length - 1]; - messageEl.raiseClickedEvent(_path[0], _this.isPreview); + const messageEl = _path[_path.length - 1]; + messageEl.raiseClickedEvent(_path[0], this.isPreview); } } } - } else if (_this.inboxSelector.contains(e.target) || _this.isInboxOpen) { - if (_this.isInboxFromFlutter) { - _this.isInboxFromFlutter = false; + } else if (this.inboxSelector.contains(e.target) || this.isInboxOpen) { + if (this.isInboxFromFlutter) { + this.isInboxFromFlutter = false; } else { - _this.toggleInbox(e); + this.toggleInbox(e); } } }; - }(); + })(); - _this.setBadgeStyle = function (msgCount) { - if (_this.unviewedBadge !== null) { - _this.unviewedBadge.innerText = msgCount > 9 ? '9+' : msgCount; - _this.unviewedBadge.style.display = msgCount > 0 ? 'flex' : 'none'; + this.setBadgeStyle = msgCount => { + if (this.unviewedBadge !== null) { + this.unviewedBadge.innerText = msgCount > 9 ? '9+' : msgCount; + this.unviewedBadge.style.display = msgCount > 0 ? 'flex' : 'none'; } }; - _this.logger = logger; - _this.shadow = _this.attachShadow({ + this.logger = logger; + this.shadow = this.attachShadow({ mode: 'open' }); - return _this; } - _createClass(Inbox, [{ - key: "connectedCallback", - value: function connectedCallback() { - this.init(); - } - }, { - key: "init", - value: function init() { - this.config = this.isPreview ? this.inboxConfigForPreview : StorageManager.readFromLSorCookie(WEBINBOX_CONFIG) || {}; - - if (Object.keys(this.config).length === 0) { - return; - } - - this.inboxSelector = document.getElementById(this.config.inboxSelector); + get incomingMessages() { + return []; + } - if (this.inboxSelector === null) { - return; - } + set incomingMessages(msgs) { + if (msgs === void 0) { + msgs = []; + } - if (this.config.styles.notificationsBadge) { - this.addUnviewedBadge(); - } else if (this.unviewedBadge) { - this.unviewedBadge.remove(); - } + if (msgs.length > 0 && this.inbox) { + this.updateInboxMessages(msgs); + } + } - this.createinbox(); - /** - * We need to remove the listener as there could be a scenario where init would be called when - * we get updated web inbox settings from LC after the inbox has been initialised. - * It can so happen that the inbox-selector would have changed. - */ + get incomingMessagesForPreview() { + return []; + } - document.removeEventListener('click', this.addClickListenerOnDocument); - document.addEventListener('click', this.addClickListenerOnDocument); - this.config.categories.length && this.updateActiveCategory(this.selectedCategoryRef.innerText); - this.shadow.innerHTML = this.getInboxStyles(); - this.shadow.appendChild(this.inbox); + set incomingMessagesForPreview(msgs) { + if (msgs === void 0) { + msgs = []; } - }, { - key: "addMsgsToInboxFromLS", - value: function addMsgsToInboxFromLS() { - var _this2 = this; - var messages = this.deleteExpiredAndGetUnexpiredMsgs(false); - var msgIds = messages ? Object.keys(messages) : []; - - if (msgIds.length === 0) { - return; - } + const previewMsgs = {}; - msgIds.forEach(function (m) { - if (!messages[m].viewed) { - _this2.unviewedMessages[m] = messages[m]; - _this2.unviewedCounter++; - } + if (msgs.length > 0 && this.inbox) { + this.isPreview = true; + this.unviewedCounter = 0; + msgs.forEach(m => { + const key = "".concat(m.wzrk_id.split('_')[0], "_").concat(Date.now()); + m.id = key; + previewMsgs[key] = m; + this.unviewedMessages[key] = m; + this.unviewedCounter++; }); - this.buildUIForMessages(messages); + this.buildUIForMessages(previewMsgs); this.updateUnviewedBadgeCounter(); } - /** - * @param {*} deleteMsgsFromUI - If this param is true, then we'll have to check the UI and delete expired messages from the DOM - * It'll be false when you are building the inbox layout for the very first time. - * - * This method reads the inbox messages from LS, - * based on the deleteMsgsFromUI flag deletes the expired messages from UI and decrements the unviewed counter if the message was not viewed, - * sorts the messages based on the date, - * saves the unexpired messages to LS - * and returns the sorted unexpired messages - * - * Scenarios when we encounter expired messages - - * 1. building ui for the 1st time, no need to decrement the unviewed counter as the correct count will be set at the time of rendering - * 2. UI is already built (deleteMsgsFromUI = true) and you open the inbox - * a. You'll find the expired msg in inbox - * b. You'll not find the expired msg in inbox. - * This happens when we receive new messages from LC, increment unviewed counter, save it in LS. (We build the UI only when the user opens inbox.) - * In both the above scenarios, we'll still have to decrement the unviewed counter if the message was not viewed. - */ - - }, { - key: "deleteExpiredAndGetUnexpiredMsgs", - value: function deleteExpiredAndGetUnexpiredMsgs() { - var deleteMsgsFromUI = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; - var messages = getInboxMessages(); - var now = Math.floor(Date.now() / 1000); - - for (var msg in messages) { - if (messages[msg].wzrk_ttl && messages[msg].wzrk_ttl > 0 && messages[msg].wzrk_ttl < now) { - if (deleteMsgsFromUI) { - var el = this.shadowRoot.getElementById(messages[msg].id); - el && el.remove(); - - if (!messages[msg].viewed) { - this.unviewedCounter--; - this.updateUnviewedBadgeCounter(); - } - } + } - delete messages[msg]; - } - } + connectedCallback() { + this.init(); + } - if (messages && messages.length > 0) { - messages = Object.values(messages).sort(function (a, b) { - return b.date - a.date; - }).reduce(function (acc, m) { - acc[m.id] = m; - return acc; - }, {}); - } + init() { + this.config = this.isPreview ? this.inboxConfigForPreview : StorageManager.readFromLSorCookie(WEBINBOX_CONFIG) || {}; - saveInboxMessages(messages); - return messages; - } - }, { - key: "updateInboxMessages", - value: function updateInboxMessages() { - var _this3 = this; - - var msgs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - var inboxMsgs = this.deleteExpiredAndGetUnexpiredMsgs(); - var date = Date.now(); - var incomingMsgs = {}; - msgs.forEach(function (m, i) { - var key = "".concat(m.wzrk_id.split('_')[0], "_").concat(Date.now()); - m.id = key; // We are doing this to preserve the order of the messages - - m.date = date - i; - m.viewed = 0; - inboxMsgs[key] = m; - incomingMsgs[key] = m; - _this3.unviewedMessages[key] = m; - _this3.unviewedCounter++; - }); - saveInboxMessages(inboxMsgs); - this.buildUIForMessages(incomingMsgs); - this.updateUnviewedBadgeCounter(); + if (Object.keys(this.config).length === 0) { + return; } - }, { - key: "createEl", - value: function createEl(type, id, part) { - var _el = document.createElement(type); - _el.setAttribute('id', id); + this.inboxSelector = document.getElementById(this.config.inboxSelector); - _el.setAttribute('part', part || id); + if (this.inboxSelector === null) { + return; + } - return _el; + if (this.config.styles.notificationsBadge) { + this.addUnviewedBadge(); + } else if (this.unviewedBadge) { + this.unviewedBadge.remove(); } - }, { - key: "addUnviewedBadge", - value: function addUnviewedBadge() { - var _this4 = this; - if (!this.unviewedBadge) { - this.unviewedBadge = this.createEl('div', 'unviewedBadge'); // As this unviewedBadge element will be directly added to the DOM, we are defining inline styles + this.createinbox(); + /** + * We need to remove the listener as there could be a scenario where init would be called when + * we get updated web inbox settings from LC after the inbox has been initialised. + * It can so happen that the inbox-selector would have changed. + */ - this.unviewedBadge.style.cssText = "display: none; position: absolute; height: 16px; width: 26px; border-radius: 8px; background-color: ".concat(this.config.styles.notificationsBadge.backgroundColor, "; font-size: 12px; color: ").concat(this.config.styles.notificationsBadge.textColor, "; font-weight: bold; align-items: center; justify-content: center;"); - document.body.appendChild(this.unviewedBadge); - } + document.removeEventListener('click', this.addClickListenerOnDocument); + document.addEventListener('click', this.addClickListenerOnDocument); + this.config.categories.length && this.updateActiveCategory(this.selectedCategoryRef.innerText); + this.shadow.innerHTML = this.getInboxStyles(); + this.shadow.appendChild(this.inbox); + } - this.updateUnviewedBadgePosition(); // called when user switches b/w portrait and landscape mode. + addMsgsToInboxFromLS() { + const messages = this.deleteExpiredAndGetUnexpiredMsgs(false); + const msgIds = messages ? Object.keys(messages) : []; - window.addEventListener('resize', function () { - _this4.updateUnviewedBadgePosition(); - }); + if (msgIds.length === 0) { + return; } - }, { - key: "updateUnviewedBadgePosition", - value: function updateUnviewedBadgePosition() { - var _this$inboxSelector$g = this.inboxSelector.getBoundingClientRect(), - top = _this$inboxSelector$g.top, - right = _this$inboxSelector$g.right; - - this.unviewedBadge.style.top = "".concat(top - 8, "px"); - this.unviewedBadge.style.left = "".concat(right - 8, "px"); - } - }, { - key: "createinbox", - value: function createinbox() { - var _this5 = this; - - this.inbox = this.createEl('div', 'inbox'); - var header = this.createEl('div', 'header'); - var headerTitle = this.createEl('div', 'headerTitle'); - headerTitle.innerText = this.config.title; - var closeIcon = this.createEl('div', 'closeInbox'); - closeIcon.innerHTML = '×'; - header.appendChild(headerTitle); - header.appendChild(closeIcon); - this.inbox.appendChild(header); - if (this.config.categories.length) { - var categories = this.createCategories(); - this.inbox.appendChild(categories); + msgIds.forEach(m => { + if (!messages[m].viewed) { + this.unviewedMessages[m] = messages[m]; + this.unviewedCounter++; } + }); + this.buildUIForMessages(messages); + this.updateUnviewedBadgeCounter(); + } + /** + * @param {*} deleteMsgsFromUI - If this param is true, then we'll have to check the UI and delete expired messages from the DOM + * It'll be false when you are building the inbox layout for the very first time. + * + * This method reads the inbox messages from LS, + * based on the deleteMsgsFromUI flag deletes the expired messages from UI and decrements the unviewed counter if the message was not viewed, + * sorts the messages based on the date, + * saves the unexpired messages to LS + * and returns the sorted unexpired messages + * + * Scenarios when we encounter expired messages - + * 1. building ui for the 1st time, no need to decrement the unviewed counter as the correct count will be set at the time of rendering + * 2. UI is already built (deleteMsgsFromUI = true) and you open the inbox + * a. You'll find the expired msg in inbox + * b. You'll not find the expired msg in inbox. + * This happens when we receive new messages from LC, increment unviewed counter, save it in LS. (We build the UI only when the user opens inbox.) + * In both the above scenarios, we'll still have to decrement the unviewed counter if the message was not viewed. + */ - this.inboxCard = this.createEl('div', 'inboxCard'); - this.inbox.appendChild(this.inboxCard); - this.emptyInboxMsg = this.createEl('div', 'emptyInboxMsg'); - this.emptyInboxMsg.innerText = 'All messages will be displayed here.'; - this.inboxCard.appendChild(this.emptyInboxMsg); // Intersection observer for notification viewed - - var options = { - root: this.inboxCard, - rootMargin: '0px', - threshold: 0.5 - }; - this.observer = new IntersectionObserver(function (entries, observer) { - _this5.handleMessageViewed(entries); - }, options); - this.addMsgsToInboxFromLS(); - } - }, { - key: "createCategories", - value: function createCategories() { - var _this6 = this; - - var categoriesContainer = this.createEl('div', 'categoriesContainer'); - var leftArrow = this.createEl('div', 'leftArrow'); - leftArrow.innerHTML = arrowSvg; - leftArrow.children[0].style = 'transform: rotate(180deg)'; - leftArrow.addEventListener('click', function () { - _this6.shadowRoot.getElementById('categoriesWrapper').scrollBy(-70, 0); - }); - categoriesContainer.appendChild(leftArrow); - var categoriesWrapper = this.createEl('div', 'categoriesWrapper'); - - var _categories = ['All'].concat(_toConsumableArray(this.config.categories)); - - _categories.forEach(function (c, i) { - var category = _this6.createEl('div', "category-".concat(i), 'category'); - - category.innerText = c; - - if (i === 0) { - _this6.selectedCategoryRef = category; - } - - categoriesWrapper.appendChild(category); - }); - categoriesContainer.appendChild(categoriesWrapper); - var rightArrow = this.createEl('div', 'rightArrow'); - rightArrow.innerHTML = arrowSvg; - rightArrow.addEventListener('click', function () { - _this6.shadowRoot.getElementById('categoriesWrapper').scrollBy(70, 0); - }); - categoriesContainer.appendChild(rightArrow); - var options = { - root: categoriesContainer, - threshold: 0.9 - }; - var firstCategory = categoriesWrapper.children[0]; - var lastCategory = categoriesWrapper.children[this.config.categories.length]; - var firstCategoryObserver = new IntersectionObserver(function (e) { - _this6.categoryObserverCb(leftArrow, e[0].intersectionRatio >= 0.9); - }, options); - firstCategoryObserver.observe(firstCategory); - var lastCategoryObserver = new IntersectionObserver(function (e) { - _this6.categoryObserverCb(rightArrow, e[0].intersectionRatio >= 0.9); - }, options); - lastCategoryObserver.observe(lastCategory); - return categoriesContainer; - } - }, { - key: "categoryObserverCb", - value: function categoryObserverCb(el, hide) { - if (!el) { - return; - } + deleteExpiredAndGetUnexpiredMsgs() { + let deleteMsgsFromUI = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : true; + let messages = getInboxMessages(); + const now = Math.floor(Date.now() / 1000); - el.style.display = hide ? 'none' : 'flex'; - } - }, { - key: "updateActiveCategory", - value: function updateActiveCategory(activeCategory) { - var _this7 = this; + for (const msg in messages) { + if (messages[msg].wzrk_ttl && messages[msg].wzrk_ttl > 0 && messages[msg].wzrk_ttl < now) { + if (deleteMsgsFromUI) { + const el = this.shadowRoot.getElementById(messages[msg].id); + el && el.remove(); - this.selectedCategory = activeCategory; - this.inboxCard.scrollTop = 0; - var counter = 0; - this.prevCategoryRef && this.prevCategoryRef.setAttribute('selected', 'false'); - this.selectedCategoryRef.setAttribute('selected', 'true'); - this.inboxCard.childNodes.forEach(function (c) { - if (c.getAttribute('id') !== 'emptyInboxMsg') { - c.style.display = _this7.selectedCategory === 'All' || c.getAttribute('category') === _this7.selectedCategory ? 'block' : 'none'; - - if (c.style.display === 'block') { - counter++; + if (!messages[msg].viewed) { + this.unviewedCounter--; + this.updateUnviewedBadgeCounter(); } } - }); - if (counter === 0) { - this.emptyInboxMsg.innerText = "".concat(activeCategory, " messages will be displayed here."); - this.emptyInboxMsg.style.display = 'block'; - } else { - this.emptyInboxMsg.style.display = 'none'; + delete messages[msg]; } } - }, { - key: "buildUIForMessages", - value: function buildUIForMessages() { - var _this$config$maxMsgsI; - var messages = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - !this.isPreview && this.updateTSForRenderedMsgs(); - this.inboxCard.scrollTop = 0; - var maxMsgsInInbox = (_this$config$maxMsgsI = this.config.maxMsgsInInbox) !== null && _this$config$maxMsgsI !== void 0 ? _this$config$maxMsgsI : MAX_INBOX_MSG; - var firstChild = this.inboxCard.firstChild; - var sortedMsgs = Object.values(messages).sort(function (a, b) { - return b.date - a.date; - }).map(function (m) { - return m.id; - }); + if (messages && messages.length > 0) { + messages = Object.values(messages).sort((a, b) => b.date - a.date).reduce((acc, m) => { + acc[m.id] = m; + return acc; + }, {}); + } - var _iterator = _createForOfIteratorHelper(sortedMsgs), - _step; + saveInboxMessages(messages); + return messages; + } - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var m = _step.value; - var item = new Message(this.config, messages[m]); - item.setAttribute('id', messages[m].id); - item.setAttribute('pivot', messages[m].wzrk_pivot); - item.setAttribute('part', 'ct-inbox-message'); - - if (this.config.categories.length > 0) { - item.setAttribute('category', messages[m].tags[0] || ''); - item.style.display = this.selectedCategory === 'All' || messages[m].category === this.selectedCategory ? 'block' : 'none'; - } else { - item.style.display = 'block'; - } + updateInboxMessages() { + let msgs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; + const inboxMsgs = this.deleteExpiredAndGetUnexpiredMsgs(); + const date = Date.now(); + const incomingMsgs = {}; + msgs.forEach((m, i) => { + const key = "".concat(m.wzrk_id.split('_')[0], "_").concat(Date.now()); + m.id = key; // We are doing this to preserve the order of the messages + + m.date = date - i; + m.viewed = 0; + inboxMsgs[key] = m; + incomingMsgs[key] = m; + this.unviewedMessages[key] = m; + this.unviewedCounter++; + }); + saveInboxMessages(inboxMsgs); + this.buildUIForMessages(incomingMsgs); + this.updateUnviewedBadgeCounter(); + } - this.inboxCard.insertBefore(item, firstChild); - this.observer.observe(item); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); - } + createEl(type, id, part) { + const _el = document.createElement(type); - var msgTotalCount = this.inboxCard.querySelectorAll('ct-inbox-message').length; + _el.setAttribute('id', id); - while (msgTotalCount > maxMsgsInInbox) { - var ctInboxMsgs = this.inboxCard.querySelectorAll('ct-inbox-message'); + _el.setAttribute('part', part || id); - if (ctInboxMsgs.length > 0) { - ctInboxMsgs[ctInboxMsgs.length - 1].remove(); - } + return _el; + } - msgTotalCount--; - } + addUnviewedBadge() { + if (!this.unviewedBadge) { + this.unviewedBadge = this.createEl('div', 'unviewedBadge'); // As this unviewedBadge element will be directly added to the DOM, we are defining inline styles - var hasMessages = this.inboxCard.querySelectorAll('ct-inbox-message[style*="display: block"]').length; - this.emptyInboxMsg.style.display = hasMessages ? 'none' : 'block'; + this.unviewedBadge.style.cssText = "display: none; position: absolute; height: 16px; width: 26px; border-radius: 8px; background-color: ".concat(this.config.styles.notificationsBadge.backgroundColor, "; font-size: 12px; color: ").concat(this.config.styles.notificationsBadge.textColor, "; font-weight: bold; align-items: center; justify-content: center;"); + document.body.appendChild(this.unviewedBadge); } - /** - * Adds a click listener on the document. For every click we check - * 1. if the click has happenned within the inbox - * - on close button, we close the inbox - * - on any of the category, we set that as the activeCategory - * - on any of the message, we mark raise notification clicked event. To identify the clicks on a button, we have p.id.startsWith('button-') - * 2. if the user has clicked on the inboxSelector, we toggle inbox - * 3. if the click is anywhere else on the UI and the inbox is open, we simply close it - */ - }, { - key: "handleMessageViewed", + this.updateUnviewedBadgePosition(); // called when user switches b/w portrait and landscape mode. - /** - * This function will be called every time when a message comes into the inbox viewport and it's visibility increases to 50% or drops below 50% - * If a msg is 50% visible in the UI, we need to mark the message as viewed in LS and raise notification viewed event - */ - value: function handleMessageViewed(entries) { - var _this8 = this; + window.addEventListener('resize', () => { + this.updateUnviewedBadgePosition(); + }); + } - var raiseViewedEvent = !this.isPreview; + updateUnviewedBadgePosition() { + const { + top, + right + } = this.inboxSelector.getBoundingClientRect(); + this.unviewedBadge.style.top = "".concat(top - 8, "px"); + this.unviewedBadge.style.left = "".concat(right - 8, "px"); + } - if (this.isInboxOpen) { - entries.forEach(function (e) { - if (e.isIntersecting && _this8.unviewedMessages.hasOwnProperty(e.target.id) && e.target.message.viewed === 0) { - e.target.message.viewed = 1; + createinbox() { + this.inbox = this.createEl('div', 'inbox'); + const header = this.createEl('div', 'header'); + const headerTitle = this.createEl('div', 'headerTitle'); + headerTitle.innerText = this.config.title; + const closeIcon = this.createEl('div', 'closeInbox'); + closeIcon.innerHTML = '×'; + header.appendChild(headerTitle); + header.appendChild(closeIcon); + this.inbox.appendChild(header); + + if (this.config.categories.length) { + const categories = this.createCategories(); + this.inbox.appendChild(categories); + } + + this.inboxCard = this.createEl('div', 'inboxCard'); + this.inbox.appendChild(this.inboxCard); + this.emptyInboxMsg = this.createEl('div', 'emptyInboxMsg'); + this.emptyInboxMsg.innerText = 'All messages will be displayed here.'; + this.inboxCard.appendChild(this.emptyInboxMsg); // Intersection observer for notification viewed + + const options = { + root: this.inboxCard, + rootMargin: '0px', + threshold: 0.5 + }; + this.observer = new IntersectionObserver((entries, observer) => { + this.handleMessageViewed(entries); + }, options); + this.addMsgsToInboxFromLS(); + } - if (raiseViewedEvent) { - window.clevertap.renderNotificationViewed({ - msgId: e.target.campaignId, - pivotId: e.target.pivotId - }); + createCategories() { + const categoriesContainer = this.createEl('div', 'categoriesContainer'); + const leftArrow = this.createEl('div', 'leftArrow'); + leftArrow.innerHTML = arrowSvg; + leftArrow.children[0].style = 'transform: rotate(180deg)'; + leftArrow.addEventListener('click', () => { + this.shadowRoot.getElementById('categoriesWrapper').scrollBy(-70, 0); + }); + categoriesContainer.appendChild(leftArrow); + const categoriesWrapper = this.createEl('div', 'categoriesWrapper'); + const _categories = ['All', ...this.config.categories]; - _this8.updateMessageInLS(e.target.id, _objectSpread2(_objectSpread2({}, e.target.message), {}, { - viewed: 1 - })); + _categories.forEach((c, i) => { + const category = this.createEl('div', "category-".concat(i), 'category'); + category.innerText = c; - setTimeout(function () { - e.target.shadowRoot.getElementById('unreadMarker').style.display = 'none'; - }, 1000); - } else { - console.log('Notifiction viewed event will be raised at run time with payload ::', { - msgId: e.target.campaignId, - pivotId: e.target.pivotId - }); - } + if (i === 0) { + this.selectedCategoryRef = category; + } - _this8.unviewedCounter--; + categoriesWrapper.appendChild(category); + }); - _this8.updateUnviewedBadgeCounter(); + categoriesContainer.appendChild(categoriesWrapper); + const rightArrow = this.createEl('div', 'rightArrow'); + rightArrow.innerHTML = arrowSvg; + rightArrow.addEventListener('click', () => { + this.shadowRoot.getElementById('categoriesWrapper').scrollBy(70, 0); + }); + categoriesContainer.appendChild(rightArrow); + const options = { + root: categoriesContainer, + threshold: 0.9 + }; + const firstCategory = categoriesWrapper.children[0]; + const lastCategory = categoriesWrapper.children[this.config.categories.length]; + const firstCategoryObserver = new IntersectionObserver(e => { + this.categoryObserverCb(leftArrow, e[0].intersectionRatio >= 0.9); + }, options); + firstCategoryObserver.observe(firstCategory); + const lastCategoryObserver = new IntersectionObserver(e => { + this.categoryObserverCb(rightArrow, e[0].intersectionRatio >= 0.9); + }, options); + lastCategoryObserver.observe(lastCategory); + return categoriesContainer; + } - delete _this8.unviewedMessages[e.target.id]; - } - }); - } + categoryObserverCb(el, hide) { + if (!el) { + return; } - }, { - key: "updateMessageInLS", - value: function updateMessageInLS(key, value) { - if (!this.isPreview) { - var messages = getInboxMessages(); - messages[key] = value; - saveInboxMessages(messages); - } - } // create a separte fn fro refactoring - - }, { - key: "toggleInbox", - value: function toggleInbox(e) { - this.isInboxOpen = !this.isInboxOpen; - this.isInboxFromFlutter = !!(e === null || e === void 0 ? void 0 : e.rect); - - if (this.isInboxOpen) { - this.inboxCard.scrollTop = 0; - !this.isPreview && this.deleteExpiredAndGetUnexpiredMsgs(); - this.inbox.style.display = 'block'; - this.inbox.style.zIndex = '2147483647'; // zIndex should be max for the inbox to be rendered on top of all elements - - if (this.config.categories.length) { - this.selectedCategoryRef.setAttribute('selected', 'false'); - this.selectedCategoryRef = this.shadowRoot.getElementById('category-0'); - this.updateActiveCategory(this.selectedCategoryRef.innerText); - this.shadowRoot.getElementById('categoriesWrapper').scrollLeft -= this.shadowRoot.getElementById('categoriesWrapper').scrollWidth; + + el.style.display = hide ? 'none' : 'flex'; + } + + updateActiveCategory(activeCategory) { + this.selectedCategory = activeCategory; + this.inboxCard.scrollTop = 0; + let counter = 0; + this.prevCategoryRef && this.prevCategoryRef.setAttribute('selected', 'false'); + this.selectedCategoryRef.setAttribute('selected', 'true'); + this.inboxCard.childNodes.forEach(c => { + if (c.getAttribute('id') !== 'emptyInboxMsg') { + c.style.display = this.selectedCategory === 'All' || c.getAttribute('category') === this.selectedCategory ? 'block' : 'none'; + + if (c.style.display === 'block') { + counter++; } + } + }); + + if (counter === 0) { + this.emptyInboxMsg.innerText = "".concat(activeCategory, " messages will be displayed here."); + this.emptyInboxMsg.style.display = 'block'; + } else { + this.emptyInboxMsg.style.display = 'none'; + } + } - this.setInboxPosition(e); + buildUIForMessages() { + var _this$config$maxMsgsI; + + let messages = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + !this.isPreview && this.updateTSForRenderedMsgs(); + this.inboxCard.scrollTop = 0; + const maxMsgsInInbox = (_this$config$maxMsgsI = this.config.maxMsgsInInbox) !== null && _this$config$maxMsgsI !== void 0 ? _this$config$maxMsgsI : MAX_INBOX_MSG; + const firstChild = this.inboxCard.firstChild; + const sortedMsgs = Object.values(messages).sort((a, b) => b.date - a.date).map(m => m.id); + + for (const m of sortedMsgs) { + const item = new Message(this.config, messages[m]); + item.setAttribute('id', messages[m].id); + item.setAttribute('pivot', messages[m].wzrk_pivot); + item.setAttribute('part', 'ct-inbox-message'); + + if (this.config.categories.length > 0) { + item.setAttribute('category', messages[m].tags[0] || ''); + item.style.display = this.selectedCategory === 'All' || messages[m].category === this.selectedCategory ? 'block' : 'none'; } else { - this.inbox.style.display = 'none'; + item.style.display = 'block'; } + + this.inboxCard.insertBefore(item, firstChild); + this.observer.observe(item); } - }, { - key: "setInboxPosition", - value: function setInboxPosition(e) { - var windowWidth = window.outerWidth; - var customInboxStyles = getComputedStyle($ct.inbox); - var top = customInboxStyles.getPropertyValue('--inbox-top'); - var bottom = customInboxStyles.getPropertyValue('--inbox-bottom'); - var left = customInboxStyles.getPropertyValue('--inbox-left'); - var right = customInboxStyles.getPropertyValue('--inbox-right'); - var hasPositionDefined = top || bottom || left || right; - if (windowWidth > 481 && !hasPositionDefined) { - var res = getInboxPosition(e, this.inbox.clientHeight, this.inbox.clientWidth); - var xPos = res.xPos; - var yPos = res.yPos; - this.inbox.style.top = yPos + 'px'; - this.inbox.style.left = xPos + 'px'; + let msgTotalCount = this.inboxCard.querySelectorAll('ct-inbox-message').length; + + while (msgTotalCount > maxMsgsInInbox) { + const ctInboxMsgs = this.inboxCard.querySelectorAll('ct-inbox-message'); + + if (ctInboxMsgs.length > 0) { + ctInboxMsgs[ctInboxMsgs.length - 1].remove(); } + + msgTotalCount--; } - /** - * Updates the UI with the number of unviewed messages - * If there are more than 9 unviewed messages, we show the count as 9+ - */ - }, { - key: "updateUnviewedBadgeCounter", - value: function updateUnviewedBadgeCounter() { - if (this.isPreview) { - this.setBadgeStyle(this.unviewedCounter); - return; - } + const hasMessages = this.inboxCard.querySelectorAll('ct-inbox-message[style*="display: block"]').length; + this.emptyInboxMsg.style.display = hasMessages ? 'none' : 'block'; + } + /** + * Adds a click listener on the document. For every click we check + * 1. if the click has happenned within the inbox + * - on close button, we close the inbox + * - on any of the category, we set that as the activeCategory + * - on any of the message, we mark raise notification clicked event. To identify the clicks on a button, we have p.id.startsWith('button-') + * 2. if the user has clicked on the inboxSelector, we toggle inbox + * 3. if the click is anywhere else on the UI and the inbox is open, we simply close it + */ - var counter = 0; - this.inboxCard.querySelectorAll('ct-inbox-message').forEach(function (m) { - var messages = getInboxMessages(); - if (messages[m.id] && messages[m.id].viewed === 0) { - counter++; + /** + * This function will be called every time when a message comes into the inbox viewport and it's visibility increases to 50% or drops below 50% + * If a msg is 50% visible in the UI, we need to mark the message as viewed in LS and raise notification viewed event + */ + handleMessageViewed(entries) { + const raiseViewedEvent = !this.isPreview; + + if (this.isInboxOpen) { + entries.forEach(e => { + if (e.isIntersecting && this.unviewedMessages.hasOwnProperty(e.target.id) && e.target.message.viewed === 0) { + e.target.message.viewed = 1; + + if (raiseViewedEvent) { + window.clevertap.renderNotificationViewed({ + msgId: e.target.campaignId, + pivotId: e.target.pivotId + }); + this.updateMessageInLS(e.target.id, { ...e.target.message, + viewed: 1 + }); + setTimeout(() => { + e.target.shadowRoot.getElementById('unreadMarker').style.display = 'none'; + }, 1000); + } else { + console.log('Notifiction viewed event will be raised at run time with payload ::', { + msgId: e.target.campaignId, + pivotId: e.target.pivotId + }); + } + + this.unviewedCounter--; + this.updateUnviewedBadgeCounter(); + delete this.unviewedMessages[e.target.id]; } }); - this.setBadgeStyle(counter); - } - }, { - key: "updateTSForRenderedMsgs", - value: function updateTSForRenderedMsgs() { - this.inboxCard.querySelectorAll('ct-inbox-message').forEach(function (m) { - var ts = m.id.split('_')[1]; - m.shadow.getElementById('timeStamp').firstChild.innerText = determineTimeStampText(ts); - }); } - }, { - key: "getInboxStyles", - value: function getInboxStyles() { - var headerHeight = 36; - var categoriesHeight = this.config.categories.length ? 64 : 16; - var styles = { - panelBackgroundColor: this.config.styles.panelBackgroundColor, - panelBorderColor: this.config.styles.panelBorderColor, - headerBackgroundColor: this.config.styles.header.backgroundColor, - headerTitleColor: this.config.styles.header.titleColor, - closeIconColor: this.config.styles.closeIconColor, - categoriesTabColor: this.config.styles.categories.tabColor, - categoriesTitleColor: this.config.styles.categories.titleColor, - selectedCategoryTabColor: this.config.styles.categories.selectedTab.tabColor, - selectedCategoryTitleColor: this.config.styles.categories.selectedTab.titleColor, - headerCategoryHeight: headerHeight + categoriesHeight - }; + } + + updateMessageInLS(key, value) { + if (!this.isPreview) { + const messages = getInboxMessages(); + messages[key] = value; + saveInboxMessages(messages); + } + } // create a separte fn fro refactoring - if (this.config.styles.categories.borderColor) { - styles.categoriesBorderColor = this.config.styles.categories.borderColor; - } - if (this.config.styles.categories.selectedTab.borderColor) { - styles.selectedCategoryBorderColor = this.config.styles.categories.selectedTab.borderColor; + toggleInbox(e) { + this.isInboxOpen = !this.isInboxOpen; + this.isInboxFromFlutter = !!(e === null || e === void 0 ? void 0 : e.rect); + + if (this.isInboxOpen) { + this.inboxCard.scrollTop = 0; + !this.isPreview && this.deleteExpiredAndGetUnexpiredMsgs(); + this.inbox.style.display = 'block'; + this.inbox.style.zIndex = '2147483647'; // zIndex should be max for the inbox to be rendered on top of all elements + + if (this.config.categories.length) { + this.selectedCategoryRef.setAttribute('selected', 'false'); + this.selectedCategoryRef = this.shadowRoot.getElementById('category-0'); + this.updateActiveCategory(this.selectedCategoryRef.innerText); + this.shadowRoot.getElementById('categoriesWrapper').scrollLeft -= this.shadowRoot.getElementById('categoriesWrapper').scrollWidth; } - var inboxStyles = inboxContainerStyles(styles); - var cardStyles = this.config.styles.cards; - var msgStyles = messageStyles({ - backgroundColor: cardStyles.backgroundColor, - borderColor: cardStyles.borderColor, - titleColor: cardStyles.titleColor, - descriptionColor: cardStyles.descriptionColor, - buttonColor: cardStyles.buttonColor, - buttonTextColor: cardStyles.buttonTextColor, - unreadMarkerColor: cardStyles.unreadMarkerColor - }); - return inboxStyles + msgStyles; - } - }, { - key: "incomingMessages", - get: function get() { - return []; - }, - set: function set() { - var msgs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - - if (msgs.length > 0 && this.inbox) { - this.updateInboxMessages(msgs); - } - } - }, { - key: "incomingMessagesForPreview", - get: function get() { - return []; - }, - set: function set() { - var _this9 = this; - - var msgs = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : []; - var previewMsgs = {}; - - if (msgs.length > 0 && this.inbox) { - this.isPreview = true; - this.unviewedCounter = 0; - msgs.forEach(function (m) { - var key = "".concat(m.wzrk_id.split('_')[0], "_").concat(Date.now()); - m.id = key; - previewMsgs[key] = m; - _this9.unviewedMessages[key] = m; - _this9.unviewedCounter++; - }); - this.buildUIForMessages(previewMsgs); - this.updateUnviewedBadgeCounter(); + this.setInboxPosition(e); + } else { + this.inbox.style.display = 'none'; + } + } + + setInboxPosition(e) { + const windowWidth = window.outerWidth; + const customInboxStyles = getComputedStyle($ct.inbox); + const top = customInboxStyles.getPropertyValue('--inbox-top'); + const bottom = customInboxStyles.getPropertyValue('--inbox-bottom'); + const left = customInboxStyles.getPropertyValue('--inbox-left'); + const right = customInboxStyles.getPropertyValue('--inbox-right'); + const hasPositionDefined = top || bottom || left || right; + + if (windowWidth > 481 && !hasPositionDefined) { + const res = getInboxPosition(e, this.inbox.clientHeight, this.inbox.clientWidth); + const xPos = res.xPos; + const yPos = res.yPos; + this.inbox.style.top = yPos + 'px'; + this.inbox.style.left = xPos + 'px'; + } + } + /** + * Updates the UI with the number of unviewed messages + * If there are more than 9 unviewed messages, we show the count as 9+ + */ + + + updateUnviewedBadgeCounter() { + if (this.isPreview) { + this.setBadgeStyle(this.unviewedCounter); + return; + } + + let counter = 0; + this.inboxCard.querySelectorAll('ct-inbox-message').forEach(m => { + const messages = getInboxMessages(); + + if (messages[m.id] && messages[m.id].viewed === 0) { + counter++; } + }); + this.setBadgeStyle(counter); + } + + updateTSForRenderedMsgs() { + this.inboxCard.querySelectorAll('ct-inbox-message').forEach(m => { + const ts = m.id.split('_')[1]; + m.shadow.getElementById('timeStamp').firstChild.innerText = determineTimeStampText(ts); + }); + } + + getInboxStyles() { + const headerHeight = 36; + const categoriesHeight = this.config.categories.length ? 64 : 16; + const styles = { + panelBackgroundColor: this.config.styles.panelBackgroundColor, + panelBorderColor: this.config.styles.panelBorderColor, + headerBackgroundColor: this.config.styles.header.backgroundColor, + headerTitleColor: this.config.styles.header.titleColor, + closeIconColor: this.config.styles.closeIconColor, + categoriesTabColor: this.config.styles.categories.tabColor, + categoriesTitleColor: this.config.styles.categories.titleColor, + selectedCategoryTabColor: this.config.styles.categories.selectedTab.tabColor, + selectedCategoryTitleColor: this.config.styles.categories.selectedTab.titleColor, + headerCategoryHeight: headerHeight + categoriesHeight + }; + + if (this.config.styles.categories.borderColor) { + styles.categoriesBorderColor = this.config.styles.categories.borderColor; } - }]); - return Inbox; - }( /*#__PURE__*/_wrapNativeSuper(HTMLElement)); + if (this.config.styles.categories.selectedTab.borderColor) { + styles.selectedCategoryBorderColor = this.config.styles.categories.selectedTab.borderColor; + } + + const inboxStyles = inboxContainerStyles(styles); + const cardStyles = this.config.styles.cards; + const msgStyles = messageStyles({ + backgroundColor: cardStyles.backgroundColor, + borderColor: cardStyles.borderColor, + titleColor: cardStyles.titleColor, + descriptionColor: cardStyles.descriptionColor, + buttonColor: cardStyles.buttonColor, + buttonTextColor: cardStyles.buttonTextColor, + unreadMarkerColor: cardStyles.unreadMarkerColor + }); + return inboxStyles + msgStyles; + } - var processWebInboxSettings = function processWebInboxSettings(webInboxSetting) { - var isPreview = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; + } + + const processWebInboxSettings = function (webInboxSetting) { + let isPreview = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; - var _settings = StorageManager.readFromLSorCookie(WEBINBOX_CONFIG) || {}; + const _settings = StorageManager.readFromLSorCookie(WEBINBOX_CONFIG) || {}; if (isPreview) { $ct.inbox.inboxConfigForPreview = webInboxSetting; @@ -4858,26 +4254,26 @@ $ct.inbox && $ct.inbox.init(); } }; - var processInboxNotifs = function processInboxNotifs(msg) { + const processInboxNotifs = msg => { if (msg.inbox_preview) { $ct.inbox.incomingMessagesForPreview = msg.inbox_notifs; } else { $ct.inbox.incomingMessages = msg; } }; - var addWebInbox = function addWebInbox(logger) { + const addWebInbox = logger => { checkAndRegisterWebInboxElements(); $ct.inbox = new Inbox({ - logger: logger + logger }); document.body.appendChild($ct.inbox); }; - var getAndMigrateInboxMessages = function getAndMigrateInboxMessages(guid) { - var messages = StorageManager.readFromLSorCookie(WEBINBOX) || {}; // Doing this to migrate message to guid level + const getAndMigrateInboxMessages = guid => { + const messages = StorageManager.readFromLSorCookie(WEBINBOX) || {}; // Doing this to migrate message to guid level if (Object.keys(messages).length > 0 && Object.keys(messages)[0].includes('_')) { - var gudInboxObj = {}; + const gudInboxObj = {}; gudInboxObj[guid] = messages; StorageManager.saveToLSorCookie(WEBINBOX, gudInboxObj); return gudInboxObj; @@ -4886,38 +4282,38 @@ return messages; }; - var getInboxMessages = function getInboxMessages() { - var guid = JSON.parse(decodeURIComponent(StorageManager.read(GCOOKIE_NAME))); + const getInboxMessages = () => { + const guid = JSON.parse(decodeURIComponent(StorageManager.read(GCOOKIE_NAME))); if (!isValueValid(guid)) { return {}; } - var messages = getAndMigrateInboxMessages(guid); + const messages = getAndMigrateInboxMessages(guid); return messages.hasOwnProperty(guid) ? messages[guid] : {}; }; - var saveInboxMessages = function saveInboxMessages(messages) { - var guid = JSON.parse(decodeURIComponent(StorageManager.read(GCOOKIE_NAME))); + const saveInboxMessages = messages => { + const guid = JSON.parse(decodeURIComponent(StorageManager.read(GCOOKIE_NAME))); if (!isValueValid(guid)) { return; } - var storedInboxObj = getAndMigrateInboxMessages(guid); - - var newObj = _objectSpread2(_objectSpread2({}, storedInboxObj), {}, _defineProperty({}, guid, messages)); - + const storedInboxObj = getAndMigrateInboxMessages(guid); + const newObj = { ...storedInboxObj, + [guid]: messages + }; StorageManager.saveToLSorCookie(WEBINBOX, newObj); }; - var initializeWebInbox = function initializeWebInbox(logger) { - return new Promise(function (resolve, reject) { + const initializeWebInbox = logger => { + return new Promise((resolve, reject) => { if (document.readyState === 'complete') { addWebInbox(logger); resolve(); } else { - var config = StorageManager.readFromLSorCookie(WEBINBOX_CONFIG) || {}; + const config = StorageManager.readFromLSorCookie(WEBINBOX_CONFIG) || {}; - var onLoaded = function onLoaded() { + const onLoaded = () => { /** * We need this null check here because $ct.inbox could be initialised via init method too on document load. * In that case we don't need to call addWebInbox method @@ -4929,7 +4325,7 @@ resolve(); }; - window.addEventListener('load', function () { + window.addEventListener('load', () => { /** * Scripts can be loaded layzily, we may not get element from dom as it may not be mounted yet * We will to check element for 10 seconds and give up @@ -4938,10 +4334,10 @@ onLoaded(); } else { // check for element for next 10 seconds - var count = 0; + let count = 0; if (count < 20) { - var t = setInterval(function () { + const t = setInterval(() => { if (document.getElementById(config.inboxSelector)) { onLoaded(); clearInterval(t); @@ -4959,36 +4355,36 @@ } }); }; - var checkAndRegisterWebInboxElements = function checkAndRegisterWebInboxElements() { + const checkAndRegisterWebInboxElements = () => { if (customElements.get('ct-web-inbox') === undefined) { customElements.define('ct-web-inbox', Inbox); customElements.define('ct-inbox-message', Message); } }; - var getInboxPosition = function getInboxPosition(e, inboxHeight, inboxWidth) { - var horizontalScroll = document.scrollingElement.scrollLeft; - var verticalScroll = document.scrollingElement.scrollTop; - var windowWidth = window.innerWidth + horizontalScroll; - var windowHeight = window.innerHeight + verticalScroll; - var selectorRect = e.rect || e.target.getBoundingClientRect(); - var selectorX = selectorRect.x + horizontalScroll; - var selectorY = selectorRect.y + verticalScroll; - var selectorLeft = selectorRect.left + horizontalScroll; - var selectorRight = selectorRect.right + horizontalScroll; - var selectorTop = selectorRect.top + verticalScroll; // const selectorBottom = selectorRect.bottom + verticalScroll - - var selectorBottom = selectorRect.bottom; - var selectorHeight = selectorRect.height; - var selectorWidth = selectorRect.width; - var selectorCenter = { + const getInboxPosition = (e, inboxHeight, inboxWidth) => { + const horizontalScroll = document.scrollingElement.scrollLeft; + const verticalScroll = document.scrollingElement.scrollTop; + const windowWidth = window.innerWidth + horizontalScroll; + const windowHeight = window.innerHeight + verticalScroll; + const selectorRect = e.rect || e.target.getBoundingClientRect(); + const selectorX = selectorRect.x + horizontalScroll; + const selectorY = selectorRect.y + verticalScroll; + const selectorLeft = selectorRect.left + horizontalScroll; + const selectorRight = selectorRect.right + horizontalScroll; + const selectorTop = selectorRect.top + verticalScroll; // const selectorBottom = selectorRect.bottom + verticalScroll + + const selectorBottom = selectorRect.bottom; + const selectorHeight = selectorRect.height; + const selectorWidth = selectorRect.width; + const selectorCenter = { x: selectorX + selectorWidth / 2, y: selectorY + selectorHeight / 2 }; - var halfOfInboxHeight = inboxHeight / 2; - var halfOfInboxWidth = inboxWidth / 2; - var inboxOnSide = false; - var xPos, yPos; - var padding = 16; + const halfOfInboxHeight = inboxHeight / 2; + const halfOfInboxWidth = inboxWidth / 2; + let inboxOnSide = false; + let xPos, yPos; + const padding = 16; /** * y co-ordinates: * Try to push the card downwards @@ -5011,13 +4407,12 @@ if (selectorBottom + inboxHeight <= windowHeight) { // try to place the card down - var availableHeight = windowHeight - (selectorBottom + inboxHeight); + const availableHeight = windowHeight - (selectorBottom + inboxHeight); yPos = availableHeight >= padding ? selectorBottom + padding : selectorBottom + availableHeight; } else if (selectorTop - inboxHeight >= verticalScroll) { // try to place the card up - var _availableHeight = selectorTop - inboxHeight; - - yPos = _availableHeight >= padding ? selectorTop - inboxHeight - padding : selectorTop - inboxHeight - _availableHeight; + const availableHeight = selectorTop - inboxHeight; + yPos = availableHeight >= padding ? selectorTop - inboxHeight - padding : selectorTop - inboxHeight - availableHeight; } else { inboxOnSide = true; yPos = selectorCenter.y - halfOfInboxHeight; // with this the y co-ordinate of the selector center and the inbox card center become the same @@ -5031,17 +4426,15 @@ if (inboxOnSide) { // See if we can place the card to the right of the selector - var inboxRight = selectorRight + inboxWidth; + const inboxRight = selectorRight + inboxWidth; if (inboxRight <= windowWidth) { - var availableWidth = inboxRight + padding <= windowWidth ? padding : windowWidth - inboxRight; + const availableWidth = inboxRight + padding <= windowWidth ? padding : windowWidth - inboxRight; xPos = selectorRight + availableWidth; } else { - var inboxLeft = selectorLeft - inboxWidth; - - var _availableWidth = inboxLeft - padding >= horizontalScroll ? padding : inboxLeft - horizontalScroll; - - xPos = inboxLeft - _availableWidth; + const inboxLeft = selectorLeft - inboxWidth; + const availableWidth = inboxLeft - padding >= horizontalScroll ? padding : inboxLeft - horizontalScroll; + xPos = inboxLeft - availableWidth; } } else { xPos = selectorCenter.x - halfOfInboxWidth; @@ -5062,13 +4455,13 @@ } return { - xPos: xPos, - yPos: yPos + xPos, + yPos }; }; - var determineTimeStampText = function determineTimeStampText(ts) { - var now = Date.now(); - var diff = Math.floor((now - ts) / 60000); + const determineTimeStampText = ts => { + const now = Date.now(); + let diff = Math.floor((now - ts) / 60000); if (diff < 5) { return 'Just now'; @@ -5087,38 +4480,32 @@ diff = Math.floor(diff / 24); return "".concat(diff, " day").concat(diff > 1 ? 's' : '', " ago"); }; - var hasWebInboxSettingsInLS = function hasWebInboxSettingsInLS() { + const hasWebInboxSettingsInLS = () => { return Object.keys(StorageManager.readFromLSorCookie(WEBINBOX_CONFIG) || {}).length > 0; }; - var arrowSvg = "\n"; - var greenTickSvg = "\n"; - - // clevertap-handler.js - var ctEventhandler = function ctEventhandler(html) { - var ctScript = "\n var clevertap = {\n event: {\n push: (eventName) => {\n window.parent.postMessage({\n action: 'Event',\n value: eventName\n },'*');\n }\n },\n profile: {\n push: (eventName) => {\n window.parent.postMessage({\n action: 'Profile',\n value: eventName\n },'*');\n }\n },\n onUserLogin: {\n push: (eventName) => {\n window.parent.postMessage({\n action: 'OUL',\n value: eventName\n },'*');\n }\n },\n closeBoxPopUp: () => {\n window.parent.postMessage({\n action: 'closeBoxPopUp',\n value: 'closeBoxPopUp'\n },'*');\n },\n closeBannerPopUp: () => {\n window.parent.postMessage({\n action: 'closeBannerPopUp',\n value: 'closeBannerPopUp'\n },'*');\n },\n closeInterstitialPopUp: () => {\n window.parent.postMessage({\n action: 'closeInterstitialPopUp',\n value: 'closeInterstitialPopUp'\n },'*');\n }\n }\n "; - var insertPosition = html.indexOf('\n "); - return html.replace(/(<\s*\/\s*body)/, "".concat(script, "\n$1")); + const appendScriptForCustomEvent = (targetingMsgJson, doc) => { + const script = doc.createElement('script'); + script.innerHTML = "\n const ct__camapignId = '".concat(targetingMsgJson.wzrk_id, "';\n const ct__formatVal = (v) => {\n return v && v.trim().substring(0, 20);\n }\n const ct__parentOrigin = window.parent.origin;\n document.body.addEventListener('click', (event) => {\n const elem = event.target.closest?.('a[wzrk_c2a], button[wzrk_c2a]');\n if (elem) {\n const {innerText, id, name, value, href} = elem;\n const clickAttr = elem.getAttribute('onclick') || elem.getAttribute('click');\n const onclickURL = clickAttr?.match(/(window.open)[(](\"|')(.*)(\"|',)/)?.[3] || clickAttr?.match(/(location.href *= *)(\"|')(.*)(\"|')/)?.[3];\n const props = {innerText, id, name, value};\n let msgCTkv = Object.keys(props).reduce((acc, c) => {\n const formattedVal = ct__formatVal(props[c]);\n formattedVal && (acc['wzrk_click_' + c] = formattedVal);\n return acc;\n }, {});\n if(onclickURL) { msgCTkv['wzrk_click_' + 'url'] = onclickURL; }\n if(href) { msgCTkv['wzrk_click_' + 'c2a'] = href; }\n const notifData = { msgId: ct__camapignId, msgCTkv, pivotId: '").concat(targetingMsgJson.wzrk_pivot, "' };\n window.parent.clevertap.renderNotificationClicked(notifData);\n }\n });\n "); + doc.body.appendChild(script); }; - var _callBackCalled = false; + let _callBackCalled = false; - var showFooterNotification = function showFooterNotification(targetingMsgJson) { - var onClick = targetingMsgJson.display.onClick; // TODO: Needs wizrocket as a global variable + const showFooterNotification = targetingMsgJson => { + let onClick = targetingMsgJson.display.onClick; // TODO: Needs wizrocket as a global variable if (window.clevertap.hasOwnProperty('notificationCallback') && typeof window.clevertap.notificationCallback !== 'undefined' && typeof window.clevertap.notificationCallback === 'function') { - var notificationCallback = window.clevertap.notificationCallback; + const notificationCallback = window.clevertap.notificationCallback; if (!_callBackCalled) { - var inaObj = {}; + const inaObj = {}; inaObj.msgContent = targetingMsgJson.msgContent; inaObj.msgId = targetingMsgJson.wzrk_id; @@ -5747,9 +5092,9 @@ inaObj.kv = targetingMsgJson.display.kv; } - window.clevertap.raiseNotificationClicked = function () { + window.clevertap.raiseNotificationClicked = () => { if (onClick !== '' && onClick != null) { - var jsFunc = targetingMsgJson.display.jsFunc; + const jsFunc = targetingMsgJson.display.jsFunc; onClick += getCookieParams(); // invoke js function call if (jsFunc != null) { @@ -5768,7 +5113,7 @@ } }; - window.clevertap.raiseNotificationViewed = function () { + window.clevertap.raiseNotificationViewed = () => { incrementImpression(targetingMsgJson); }; @@ -5780,13 +5125,13 @@ renderFooterNotification(targetingMsgJson); if (window.clevertap.hasOwnProperty('popupCallbacks') && typeof window.clevertap.popupCallbacks !== 'undefined' && typeof window.clevertap.popupCallbacks[targetingMsgJson.wzrk_id] === 'function') { - var popupCallback = window.clevertap.popupCallbacks[targetingMsgJson.wzrk_id]; - var _inaObj = {}; - _inaObj.msgContent = targetingMsgJson.msgContent; - _inaObj.msgId = targetingMsgJson.wzrk_id; + const popupCallback = window.clevertap.popupCallbacks[targetingMsgJson.wzrk_id]; + const inaObj = {}; + inaObj.msgContent = targetingMsgJson.msgContent; + inaObj.msgId = targetingMsgJson.wzrk_id; if (targetingMsgJson.wzrk_pivot) { - _inaObj.pivotId = targetingMsgJson.wzrk_pivot; + inaObj.pivotId = targetingMsgJson.wzrk_pivot; } var msgCTkv = []; @@ -5794,66 +5139,61 @@ for (var wzrkPrefixKey in targetingMsgJson) { // ADD WZRK PREFIX KEY VALUE PAIRS if (wzrkPrefixKey.startsWith(WZRK_PREFIX) && wzrkPrefixKey !== WZRK_ID) { - var wzrkJson = _defineProperty({}, wzrkPrefixKey, targetingMsgJson[wzrkPrefixKey]); - + const wzrkJson = { + [wzrkPrefixKey]: targetingMsgJson[wzrkPrefixKey] + }; msgCTkv.push(wzrkJson); } } if (msgCTkv.length > 0) { - _inaObj.msgCTkv = msgCTkv; + inaObj.msgCTkv = msgCTkv; } if (targetingMsgJson.display.kv != null) { - _inaObj.kv = targetingMsgJson.display.kv; + inaObj.kv = targetingMsgJson.display.kv; } // PUBLIC API TO RECORD CLICKED EVENT - window.clevertap.raisePopupNotificationClicked = function (notificationData) { + window.clevertap.raisePopupNotificationClicked = notificationData => { if (!notificationData || !notificationData.msgId) { return; } - var eventData = {}; + const eventData = {}; eventData.type = 'event'; eventData.evtName = NOTIFICATION_CLICKED; - eventData.evtData = _defineProperty({}, WZRK_ID, notificationData.msgId); + eventData.evtData = { + [WZRK_ID]: notificationData.msgId + }; if (targetingMsgJson.wzrk_pivot) { - eventData.evtData = _objectSpread2(_objectSpread2({}, eventData.evtData), {}, { + eventData.evtData = { ...eventData.evtData, wzrk_pivot: notificationData.pivotId - }); + }; } // WZRK PREFIX KEY VALUE PAIRS if (notificationData.msgCTkv) { - var _iterator = _createForOfIteratorHelper(notificationData.msgCTkv), - _step; - - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var wzrkPrefixObj = _step.value; - eventData.evtData = _objectSpread2(_objectSpread2({}, eventData.evtData), wzrkPrefixObj); - } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); + for (var wzrkPrefixObj of notificationData.msgCTkv) { + eventData.evtData = { ...eventData.evtData, + ...wzrkPrefixObj + }; } } _request.processEvent(eventData); }; - popupCallback(_inaObj); + popupCallback(inaObj); } } }; - var exitintentObj; + let exitintentObj; - var showExitIntent = function showExitIntent(event, targetObj) { - var targetingMsgJson; + const showExitIntent = (event, targetObj) => { + let targetingMsgJson; if (event != null && event.clientY > 0) { return; @@ -5866,7 +5206,7 @@ } if ($ct.dismissSpamControl && targetingMsgJson.display.wtarget_type === 0 && document.getElementById('intentPreview') != null && document.getElementById('intentOpacityDiv') != null) { - var element = document.getElementById('intentPreview'); + const element = document.getElementById('intentPreview'); element.remove(); document.getElementById('intentOpacityDiv').remove(); } // ImageOnly campaign and Interstitial/Exit Intent shouldn't coexist @@ -5885,16 +5225,16 @@ return; } - var campaignId = targetingMsgJson.wzrk_id.split('_')[0]; + const campaignId = targetingMsgJson.wzrk_id.split('_')[0]; $ct.campaignDivMap[campaignId] = 'intentPreview'; - var legacy = false; - var opacityDiv = document.createElement('div'); + let legacy = false; + const opacityDiv = document.createElement('div'); opacityDiv.id = 'intentOpacityDiv'; - var opacity = targetingMsgJson.display.opacity || 0.7; - var rgbaColor = "rgba(0,0,0,".concat(opacity, ")"); + const opacity = targetingMsgJson.display.opacity || 0.7; + const rgbaColor = "rgba(0,0,0,".concat(opacity, ")"); opacityDiv.setAttribute('style', "position: fixed;top: 0;bottom: 0;left: 0;width: 100%;height: 100%;z-index: 2147483646;background: ".concat(rgbaColor, ";")); document.body.appendChild(opacityDiv); - var msgDiv = document.createElement('div'); + const msgDiv = document.createElement('div'); msgDiv.id = 'intentPreview'; if (targetingMsgJson.display.proto == null) { @@ -5905,37 +5245,29 @@ } document.body.appendChild(msgDiv); - var iframe = document.createElement('iframe'); - var borderRadius = targetingMsgJson.display.br === false ? '0' : '8'; - var displayObj = targetingMsgJson.display; + const iframe = document.createElement('iframe'); + const borderRadius = targetingMsgJson.display.br === false ? '0' : '8'; iframe.frameborder = '0px'; iframe.marginheight = '0px'; iframe.marginwidth = '0px'; iframe.scrolling = 'no'; - iframe.id = WIZ_IFRAME_INTENT; - var html = targetingMsgJson.msgContent.html; - - if (displayObj['custom-editor'] && !displayObj['bee-editor'] && displayObj['custom-html-sandbox']) { - // sandbox the iframe only for custom html - iframe.sandbox = 'allow-scripts allow-popups allow-popups-to-escape-sandbox allow-forms'; // allow popup to open url in new page - - html = ctEventhandler(html); - } - - var onClick = targetingMsgJson.display.onClick; - var pointerCss = ''; + iframe.id = 'wiz-iframe-intent'; + const onClick = targetingMsgJson.display.onClick; + let pointerCss = ''; if (onClick !== '' && onClick != null) { pointerCss = 'cursor:pointer;'; - } // direct html + } + let html; // direct html if (targetingMsgJson.msgContent.type === 1) { + html = targetingMsgJson.msgContent.html; html = html.replace(/##campaignId##/g, campaignId); html = html.replace(/##campaignId_batchId##/g, targetingMsgJson.wzrk_id); } else { - var css = '' + ''; - var bgColor, textColor, btnBg, btColor; + const css = '' + ''; + let bgColor, textColor, btnBg, btColor; if (targetingMsgJson.display.theme === 'dark') { bgColor = '#2d2d2e'; @@ -5949,78 +5281,43 @@ btColor = '#ffffff'; } - var titleText = targetingMsgJson.msgContent.title; - var descriptionText = targetingMsgJson.msgContent.description; - var ctaText = ''; + const titleText = targetingMsgJson.msgContent.title; + const descriptionText = targetingMsgJson.msgContent.description; + let ctaText = ''; if (targetingMsgJson.msgContent.ctaText != null && targetingMsgJson.msgContent.ctaText !== '') { ctaText = "\" +\n \" \" + titleText + ' '\n const body = \"\" + descriptionText + ' |