From 1d2b7da481b8830b532ad6caaa2456ed2050e881 Mon Sep 17 00:00:00 2001 From: Nishant Kumar Date: Wed, 29 May 2024 14:40:17 +0530 Subject: [PATCH 01/16] fix(SDK-3836): Fixes channel invoke method from native iOS to Flutter on a non-platform thread issue - Added channel invoke method to iOS main thread. - Fixes iOS sample Runner app pod install issue. --- example/ios/Flutter/AppFrameworkInfo.plist | 2 +- example/ios/Podfile | 2 + example/ios/Podfile.lock | 134 ++++++++++++++++++ example/ios/Runner.xcodeproj/project.pbxproj | 2 +- .../xcshareddata/xcschemes/Runner.xcscheme | 2 +- .../contents.xcworkspacedata | 10 ++ .../xcshareddata/IDEWorkspaceChecks.plist | 8 ++ example/lib/main.dart | 24 ++-- ios/Classes/CleverTapPlugin.m | 13 +- 9 files changed, 179 insertions(+), 18 deletions(-) create mode 100644 example/ios/Podfile.lock create mode 100644 example/ios/Runner.xcworkspace/contents.xcworkspacedata create mode 100644 example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist diff --git a/example/ios/Flutter/AppFrameworkInfo.plist b/example/ios/Flutter/AppFrameworkInfo.plist index 4f8d4d24..8c6e5614 100644 --- a/example/ios/Flutter/AppFrameworkInfo.plist +++ b/example/ios/Flutter/AppFrameworkInfo.plist @@ -21,6 +21,6 @@ CFBundleVersion 1.0 MinimumOSVersion - 11.0 + 12.0 diff --git a/example/ios/Podfile b/example/ios/Podfile index b331c7b2..1d466540 100644 --- a/example/ios/Podfile +++ b/example/ios/Podfile @@ -3,6 +3,8 @@ platform :ios, '12.0' # CocoaPods analytics sends network stats synchronously affecting flutter build latency. ENV['COCOAPODS_DISABLE_STATS'] = 'true' +ENV['SWIFT_VERSION'] = '5' +use_modular_headers! project 'Runner', { 'Debug' => :debug, diff --git a/example/ios/Podfile.lock b/example/ios/Podfile.lock new file mode 100644 index 00000000..9c311304 --- /dev/null +++ b/example/ios/Podfile.lock @@ -0,0 +1,134 @@ +PODS: + - CleverTap-iOS-SDK (6.2.1): + - SDWebImage (~> 5.11) + - clevertap_plugin (2.4.0): + - CleverTap-iOS-SDK (= 6.2.1) + - Flutter + - Firebase/CoreOnly (10.25.0): + - FirebaseCore (= 10.25.0) + - Firebase/Messaging (10.25.0): + - Firebase/CoreOnly + - FirebaseMessaging (~> 10.25.0) + - firebase_core (2.32.0): + - Firebase/CoreOnly (= 10.25.0) + - Flutter + - firebase_messaging (14.9.4): + - Firebase/Messaging (= 10.25.0) + - firebase_core + - Flutter + - FirebaseCore (10.25.0): + - FirebaseCoreInternal (~> 10.0) + - GoogleUtilities/Environment (~> 7.12) + - GoogleUtilities/Logger (~> 7.12) + - FirebaseCoreInternal (10.25.0): + - "GoogleUtilities/NSData+zlib (~> 7.8)" + - FirebaseInstallations (10.25.0): + - FirebaseCore (~> 10.0) + - GoogleUtilities/Environment (~> 7.8) + - GoogleUtilities/UserDefaults (~> 7.8) + - PromisesObjC (~> 2.1) + - FirebaseMessaging (10.25.0): + - FirebaseCore (~> 10.0) + - FirebaseInstallations (~> 10.0) + - GoogleDataTransport (~> 9.3) + - GoogleUtilities/AppDelegateSwizzler (~> 7.8) + - GoogleUtilities/Environment (~> 7.8) + - GoogleUtilities/Reachability (~> 7.8) + - GoogleUtilities/UserDefaults (~> 7.8) + - nanopb (< 2.30911.0, >= 2.30908.0) + - Flutter (1.0.0) + - GoogleDataTransport (9.4.1): + - GoogleUtilities/Environment (~> 7.7) + - nanopb (< 2.30911.0, >= 2.30908.0) + - PromisesObjC (< 3.0, >= 1.2) + - GoogleUtilities/AppDelegateSwizzler (7.13.3): + - GoogleUtilities/Environment + - GoogleUtilities/Logger + - GoogleUtilities/Network + - GoogleUtilities/Privacy + - GoogleUtilities/Environment (7.13.3): + - GoogleUtilities/Privacy + - PromisesObjC (< 3.0, >= 1.2) + - GoogleUtilities/Logger (7.13.3): + - GoogleUtilities/Environment + - GoogleUtilities/Privacy + - GoogleUtilities/Network (7.13.3): + - GoogleUtilities/Logger + - "GoogleUtilities/NSData+zlib" + - GoogleUtilities/Privacy + - GoogleUtilities/Reachability + - "GoogleUtilities/NSData+zlib (7.13.3)": + - GoogleUtilities/Privacy + - GoogleUtilities/Privacy (7.13.3) + - GoogleUtilities/Reachability (7.13.3): + - GoogleUtilities/Logger + - GoogleUtilities/Privacy + - GoogleUtilities/UserDefaults (7.13.3): + - GoogleUtilities/Logger + - GoogleUtilities/Privacy + - nanopb (2.30910.0): + - nanopb/decode (= 2.30910.0) + - nanopb/encode (= 2.30910.0) + - nanopb/decode (2.30910.0) + - nanopb/encode (2.30910.0) + - PromisesObjC (2.4.0) + - SDWebImage (5.19.2): + - SDWebImage/Core (= 5.19.2) + - SDWebImage/Core (5.19.2) + - workmanager (0.0.1): + - Flutter + +DEPENDENCIES: + - clevertap_plugin (from `.symlinks/plugins/clevertap_plugin/ios`) + - firebase_core (from `.symlinks/plugins/firebase_core/ios`) + - firebase_messaging (from `.symlinks/plugins/firebase_messaging/ios`) + - Flutter (from `Flutter`) + - workmanager (from `.symlinks/plugins/workmanager/ios`) + +SPEC REPOS: + trunk: + - CleverTap-iOS-SDK + - Firebase + - FirebaseCore + - FirebaseCoreInternal + - FirebaseInstallations + - FirebaseMessaging + - GoogleDataTransport + - GoogleUtilities + - nanopb + - PromisesObjC + - SDWebImage + +EXTERNAL SOURCES: + clevertap_plugin: + :path: ".symlinks/plugins/clevertap_plugin/ios" + firebase_core: + :path: ".symlinks/plugins/firebase_core/ios" + firebase_messaging: + :path: ".symlinks/plugins/firebase_messaging/ios" + Flutter: + :path: Flutter + workmanager: + :path: ".symlinks/plugins/workmanager/ios" + +SPEC CHECKSUMS: + CleverTap-iOS-SDK: 78ea6d752d84918f0426f7b3959777d862bcb348 + clevertap_plugin: 81d30133ce84661238d3dc02d1321e15cfe46e12 + Firebase: 0312a2352584f782ea56f66d91606891d4607f06 + firebase_core: a626d00494efa398e7c54f25f1454a64c8abf197 + firebase_messaging: 06391e8f35dc65a00c56580266285263d2861f10 + FirebaseCore: 7ec4d0484817f12c3373955bc87762d96842d483 + FirebaseCoreInternal: 910a81992c33715fec9263ca7381d59ab3a750b7 + FirebaseInstallations: 91950fe859846fff0fbd296180909dd273103b09 + FirebaseMessaging: 88950ba9485052891ebe26f6c43a52bb62248952 + Flutter: e0871f40cf51350855a761d2e70bf5af5b9b5de7 + GoogleDataTransport: 6c09b596d841063d76d4288cc2d2f42cc36e1e2a + GoogleUtilities: ea963c370a38a8069cc5f7ba4ca849a60b6d7d15 + nanopb: 438bc412db1928dac798aa6fd75726007be04262 + PromisesObjC: f5707f49cb48b9636751c5b2e7d227e43fba9f47 + SDWebImage: dfe95b2466a9823cf9f0c6d01217c06550d7b29a + workmanager: 0afdcf5628bbde6924c21af7836fed07b42e30e6 + +PODFILE CHECKSUM: 0f6bc49bdce139b03138f6131a854cc8a065453f + +COCOAPODS: 1.13.0 diff --git a/example/ios/Runner.xcodeproj/project.pbxproj b/example/ios/Runner.xcodeproj/project.pbxproj index a5c12a31..ffcfc855 100644 --- a/example/ios/Runner.xcodeproj/project.pbxproj +++ b/example/ios/Runner.xcodeproj/project.pbxproj @@ -174,7 +174,7 @@ 97C146E61CF9000F007C117D /* Project object */ = { isa = PBXProject; attributes = { - LastUpgradeCheck = 1430; + LastUpgradeCheck = 1510; ORGANIZATIONNAME = CleverTap; TargetAttributes = { 97C146ED1CF9000F007C117D = { diff --git a/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme index a6b826db..5e31d3d3 100644 --- a/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme +++ b/example/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -1,6 +1,6 @@ + + + + + + diff --git a/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100644 index 00000000..18d98100 --- /dev/null +++ b/example/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/example/lib/main.dart b/example/lib/main.dart index 03b885b9..68b2871d 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -46,18 +46,20 @@ void _firebaseForegroundMessageHandler(RemoteMessage remoteMessage) { void main() async { WidgetsFlutterBinding.ensureInitialized(); - Workmanager().initialize( - callbackDispatcher, // The top level function, aka callbackDispatcher - isInDebugMode: true // If enabled it will post a notification whenever the task is running. Handy for debugging tasks - ); - Workmanager().registerOneOffTask( - "periodic-task-identifier", - "simplePeriodicTask" - ); + if (!Platform.isIOS) { + Workmanager().initialize( + callbackDispatcher, // The top level function, aka callbackDispatcher + isInDebugMode: true // If enabled it will post a notification whenever the task is running. Handy for debugging tasks + ); + Workmanager().registerOneOffTask( + "periodic-task-identifier", + "simplePeriodicTask" + ); - await Firebase.initializeApp(); - FirebaseMessaging.onMessage.listen(_firebaseForegroundMessageHandler); - FirebaseMessaging.onBackgroundMessage(_firebaseBackgroundMessageHandler); + await Firebase.initializeApp(); + FirebaseMessaging.onMessage.listen(_firebaseForegroundMessageHandler); + FirebaseMessaging.onBackgroundMessage(_firebaseBackgroundMessageHandler); + } CleverTapPlugin.onKilledStateNotificationClicked( onKilledStateNotificationClickedHandler); diff --git a/ios/Classes/CleverTapPlugin.m b/ios/Classes/CleverTapPlugin.m index 853d54e3..8448a5ec 100644 --- a/ios/Classes/CleverTapPlugin.m +++ b/ios/Classes/CleverTapPlugin.m @@ -1024,18 +1024,23 @@ - (NSMutableDictionary *)getVariableValues { #pragma mark - Notifications - (void)emitEventInternal:(NSNotification *)notification { - - [self.nativeToDartMethodChannel invokeMethod:notification.name arguments:notification.userInfo]; + dispatch_async(dispatch_get_main_queue(), ^{ + [self.nativeToDartMethodChannel invokeMethod:notification.name arguments:notification.userInfo]; + }); } - (void)emitEventPushPermissionResponse:(NSNotification *)notification { // Passed boolean value of `accepted` directly. - [self.nativeToDartMethodChannel invokeMethod:notification.name arguments:notification.userInfo[@"accepted"]]; + dispatch_async(dispatch_get_main_queue(), ^{ + [self.nativeToDartMethodChannel invokeMethod:notification.name arguments:notification.userInfo[@"accepted"]]; + }); } - (void)emitEventDisplayUnitsLoaded:(NSNotification *)notification { // Passed CleverTapDisplayUnit Array directly. - [self.nativeToDartMethodChannel invokeMethod:notification.name arguments:notification.userInfo[@"adUnits"]]; + dispatch_async(dispatch_get_main_queue(), ^{ + [self.nativeToDartMethodChannel invokeMethod:notification.name arguments:notification.userInfo[@"adUnits"]]; + }); } - (void)addObservers { From 60d845b36e10c0aa2cff14f39db61bde411a3e5e Mon Sep 17 00:00:00 2001 From: KambleSonam Date: Fri, 23 Aug 2024 15:15:07 +0530 Subject: [PATCH 02/16] Adds the method getKVPairData() for custom KV pair and updates the Web SDK version to 1.9.0 --- CHANGELOG.md | 7 + README.md | 2 +- android/build.gradle | 2 +- assets/clevertap.js | 7980 ++++++++++----------- assets/clevertap_support.js | 36 - doc/Usage-Web.md | 24 +- example/lib/main.dart | 35 +- ios/clevertap_plugin.podspec | 2 +- lib/clevertap_plugin.dart | 14 +- lib/clevertap_plugin_web.dart | 21 +- lib/src/clevertap_plugin_web_binding.dart | 3 + pubspec.yaml | 2 +- 12 files changed, 3876 insertions(+), 4252 deletions(-) delete mode 100644 assets/clevertap_support.js diff --git a/CHANGELOG.md b/CHANGELOG.md index eb0f47ab..397db19c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ ## CHANGE LOG +### Version 2.4.1 *(26th August 2024)* +------------------------------------------- +**Bug Fixes** +* **[Web Platform]** + * Adds the method 'getKVPairData()' to get the custom KV Pair data + * Supports [CleverTap Web SDK v1.9.0](https://github.com/CleverTap/clevertap-web-sdk/releases/tag/v1.9.0) + ### Version 2.4.0 *(10th May 2024)* ------------------------------------------- **What's new** diff --git a/README.md b/README.md index 175ac171..317220c0 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ To get started, sign up [here](https://clevertap.com/live-product-demo/). ```yaml dependencies: -clevertap_plugin: 2.4.0 +clevertap_plugin: 2.4.1 ``` - Run `flutter packages get` to install the SDK diff --git a/android/build.gradle b/android/build.gradle index aa395dc8..cc5051be 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -3,7 +3,7 @@ plugins { } group 'com.clevertap.clevertap_plugin' -version '2.4.0' +version '2.4.1' rootProject.allprojects { repositories { diff --git a/assets/clevertap.js b/assets/clevertap.js index daca985a..7728d672 100644 --- a/assets/clevertap.js +++ b/assets/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,159 +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"); + } + + 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"); + } + + } - 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 SYSTEM_EVENTS = ['Stayed', 'UTM Visited', 'App Launched', 'Notification Sent', NOTIFICATION_VIEWED, NOTIFICATION_CLICKED]; - - var isString = function isString(input) { + 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; } @@ -549,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) { @@ -581,7 +259,7 @@ } } } else { - var val; + let val; if (isString(o)) { val = sanitize(o, unsupportedValueCharRegex); @@ -599,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 = ''; - value = encodeURIComponent(value); - document.cookie = name + '=' + value + expires + domainStr + '; path=/'; + if (seconds) { + const date = new Date(); + date.setTime(date.getTime() + seconds * 1000); + expires = '; expires=' + date.toGMTString(); } - }, { - 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]; + if (domain) { + domainStr = '; domain=' + domain; + } - while (c.charAt(0) === ' ') { - c = c.substring(1, c.length); - } // eslint-disable-next-line eqeqeq + value = encodeURIComponent(value); + document.cookie = name + '=' + value + expires + domainStr + '; path=/'; + } + static readCookie(name) { + const nameEQ = name + '='; + const ca = document.cookie.split(';'); - if (c.indexOf(nameEQ) == 0) { - return decodeURIComponent(c.substring(nameEQ.length, c.length)); - } - } + for (let idx = 0; idx < ca.length; idx++) { + let c = ca[idx]; - return null; + while (c.charAt(0) === ' ') { + c = c.substring(1, c.length); + } // eslint-disable-next-line eqeqeq + + + 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, @@ -956,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 }); @@ -968,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]; @@ -990,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.saveCacheToLS(this.cache); + this.cache[key] = value; + + 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); + } + + saveCacheToLS(cache) { + const objToArray = []; - for (var index in allKeys) { - if (allKeys.hasOwnProperty(index)) { - var temp = []; - temp.push(allKeys[index]); - temp.push(cache[allKeys[index]]); - objToArray.push(temp); - } + 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]]; @@ -1118,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 @@ -1159,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 @@ -1299,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) { @@ -1389,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)) { @@ -1422,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); @@ -1455,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)) { @@ -1569,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 @@ -1604,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); @@ -1636,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 = {}, @@ -1928,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); @@ -1947,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; @@ -1995,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)); } @@ -2086,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); @@ -2111,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; } @@ -2150,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); } @@ -2165,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'); @@ -2191,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, '\"')); @@ -2212,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; @@ -2270,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))); @@ -2281,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; @@ -2315,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]; @@ -2399,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) { @@ -2416,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'; @@ -2453,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'; @@ -2472,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; @@ -2508,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; @@ -2520,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'; @@ -2530,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]); } @@ -2546,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); @@ -2558,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]; } @@ -2569,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; @@ -2586,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 = {}; @@ -2603,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'; @@ -2616,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]; @@ -2650,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 @@ -2674,7 +2292,7 @@ data[categoryLongKey] = $ct.updatedCategoryLong; } - var url = account.emailURL; + let url = account.emailURL; if (fetchGroups) { url = addToURL(url, 'fetchGroups', fetchGroups); @@ -2716,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); - } + // 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'); + 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 { - // 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; - } + $ct.globalProfileMap[key] = $ct.globalProfileMap[key] - value; + } - StorageManager.saveToLSorCookie(PR_COOKIE, $ct.globalProfileMap); // Send the updated value to LC + StorageManager.saveToLSorCookie(PR_COOKIE, $ct.globalProfileMap); // Send the updated value to LC - var data = {}; - var profileObj = {}; - data.type = 'profile'; - profileObj[key] = _defineProperty({}, command, value); + let data = {}; + const profileObj = {}; + data.type = 'profile'; + profileObj[key] = { + [command]: value + }; - 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 (profileObj.tz == null) { + // try to auto capture user timezone if not present + profileObj.tz = new Date().toString().match(/([A-Z]+[\+-][0-9]+)/)[1]; + } - data.profile = profileObj; - data = _classPrivateFieldLooseBase(this, _request$2)[_request$2].addSystemDataToObject(data, true); + data.profile = profileObj; + data = _classPrivateFieldLooseBase(this, _request$2)[_request$2].addSystemDataToObject(data, true); - _classPrivateFieldLooseBase(this, _request$2)[_request$2].addFlags(data); + _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); + pageLoadUrl = addToURL(pageLoadUrl, 'type', EVT_PUSH); + pageLoadUrl = addToURL(pageLoadUrl, 'd', compressedData); - _classPrivateFieldLooseBase(this, _request$2)[_request$2].saveAndFireRequest(pageLoadUrl, $ct.blockRequest); - } + _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 - */ - - }, { - key: "_handleMultiValueSet", - value: function _handleMultiValueSet(key, arrayVal, command) { - var array = []; + } + /** + * + * @param {any} key + * @param {array} arrayVal + * @param {string} command + * overwrites/sets new value(s) against a key/property in profile object + */ - 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; + _handleMultiValueSet(key, arrayVal, command) { + const array = []; - $ct.globalProfileMap = (_StorageManager$readF = StorageManager.readFromLSorCookie(PR_COOKIE)) !== null && _StorageManager$readF !== void 0 ? _StorageManager$readF : {}; + 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'); } + } - $ct.globalProfileMap[key] = array; - StorageManager.saveToLSorCookie(PR_COOKIE, $ct.globalProfileMap); - this.sendMultiValueData(key, arrayVal, command); + if ($ct.globalProfileMap == null) { + var _StorageManager$readF; + + $ct.globalProfileMap = (_StorageManager$readF = StorageManager.readFromLSorCookie(PR_COOKIE)) !== null && _StorageManager$readF !== void 0 ? _StorageManager$readF : {}; } - /** - * - * @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 + $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 + */ + - if ($ct.globalProfileMap == null) { - $ct.globalProfileMap = StorageManager.readFromLSorCookie(PR_COOKIE) || {}; - } // Check if the value to be set is either string or number + _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 (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; + _handleMultiValueRemove(propKey, propVal, command) { + var _$ct$globalProfileMap2; + + if ($ct.globalProfileMap == null) { + $ct.globalProfileMap = StorageManager.readFromLSorCookie(PR_COOKIE); + } - if ($ct.globalProfileMap == null) { - $ct.globalProfileMap = StorageManager.readFromLSorCookie(PR_COOKIE); - } + 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 === 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.")); + if (index !== -1) { + $ct.globalProfileMap[propKey].splice(index, 1); + } } else { - if (typeof propVal === 'string' || typeof propVal === 'number') { - var index = $ct.globalProfileMap[propKey].indexOf(propVal); - - 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]); + 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); - } + 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 @@ -3060,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, { @@ -3090,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); @@ -3124,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 = {}; @@ -3238,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]; @@ -3259,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; @@ -3276,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; } @@ -3315,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 @@ -3332,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, { @@ -3357,7 +2942,7 @@ } data.profile = profileObj; - var ids = []; + const ids = []; if (StorageManager._isLocalStorageSupported()) { if (profileObj.Identity) { @@ -3393,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) @@ -3463,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(); @@ -3480,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 || ''; + } - this.shadow.innerHTML = this.getBannerContent(); + set details(val) { + if (this._details === null) { + this._details = val; + this.renderBanner(); + } + } - if (this.trackClick !== false) { - this.addEventListener('click', function () { - var onClickUrl = _this2.details.onClick; + renderBanner() { + this.shadow.innerHTML = this.getBannerContent(); - if (onClickUrl) { - _this2.details.window ? window.open(onClickUrl, '_blank') : window.parent.location.href = onClickUrl; - } + if (this.trackClick !== false) { + this.addEventListener('click', () => { + const onClickUrl = this.details.onClick; - window.clevertap.renderNotificationClicked({ - msgId: _this2.msgId, - pivotId: _this2.pivotId - }); - }); - } + if (onClickUrl) { + this.details.window ? window.open(onClickUrl, '_blank') : window.parent.location.href = onClickUrl; + } - window.clevertap.renderNotificationViewed({ - msgId: this.msgId, - pivotId: this.pivotId + window.clevertap.renderNotificationClicked({ + msgId: this.msgId, + pivotId: this.pivotId + }); }); } - }, { - key: "getBannerContent", - value: function getBannerContent() { - return "\n \n
\n \n \n \n \"Please\n \n ").concat(this.details.html ? this.details.html : '', "\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 \n \n \n \"Please\n \n ").concat(this.details.html ? this.details.html : '', "\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); + } - _this.renderMessage(message); + get pivotId() { + return this.message.wzrk_pivot; + } - return _this; + get campaignId() { + return this.message.wzrk_id; } - _createClass(Message, [{ - key: "createEl", - value: function createEl(type, id, part) { - var _el = document.createElement(type); + createEl(type, id, part) { + const _el = document.createElement(type); - _el.setAttribute('id', id); + _el.setAttribute('id', id); - _el.setAttribute('part', part || id); + _el.setAttribute('part', part || id); - return _el; - } - }, { - key: "renderMessage", - value: function renderMessage(msg) { - this.wrapper = this.createEl('div', 'messageWrapper'); + return _el; + } - 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); - } - } + renderMessage(msg) { + this.wrapper = this.createEl('div', 'messageWrapper'); - var timeStamp = this.createEl('div', 'timeStamp'); - timeStamp.innerHTML = "".concat(determineTimeStampText(msg.id.split('_')[1]), ""); + 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); + } + } - if (!msg.viewed) { - var unreadMarker = this.createEl('span', 'unreadMarker'); - timeStamp.appendChild(unreadMarker); - } + const timeStamp = this.createEl('div', 'timeStamp'); + timeStamp.innerHTML = "".concat(determineTimeStampText(msg.id.split('_')[1]), ""); - this.wrapper.appendChild(timeStamp); - this.shadow.appendChild(this.wrapper); + if (!msg.viewed) { + const unreadMarker = this.createEl('span', 'unreadMarker'); + timeStamp.appendChild(unreadMarker); } - }, { - 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); - } - var iconTitleDescWrapper = this.createEl('div', 'iconTitleDescWrapper'); + this.wrapper.appendChild(timeStamp); + this.shadow.appendChild(this.wrapper); + } - if (msg.iconUrl) { - var iconContainer = this.addImage(msg.iconUrl, 'iconImg'); - iconTitleDescWrapper.appendChild(iconContainer); - } + prepareBasicMessage(msg) { + const message = this.createEl('div', 'message'); - var titleDescWrapper = this.createEl('div', 'titleDescWrapper'); + if (msg.imageUrl) { + const imageContainer = this.addImage(msg.imageUrl, 'mainImg'); + message.appendChild(imageContainer); + } - if (msg.title) { - var title = this.createEl('div', 'title'); - title.innerText = msg.title; - titleDescWrapper.appendChild(title); - } + const iconTitleDescWrapper = this.createEl('div', 'iconTitleDescWrapper'); - if (msg.description) { - var description = this.createEl('div', 'description'); - description.innerText = msg.description; - titleDescWrapper.appendChild(description); - } + if (msg.iconUrl) { + const iconContainer = this.addImage(msg.iconUrl, 'iconImg'); + iconTitleDescWrapper.appendChild(iconContainer); + } - if (msg.title || msg.description) { - iconTitleDescWrapper.appendChild(titleDescWrapper); - } + const titleDescWrapper = this.createEl('div', 'titleDescWrapper'); - if (msg.iconUrl || msg.title || msg.description) { - message.appendChild(iconTitleDescWrapper); - } + if (msg.title) { + const title = this.createEl('div', 'title'); + title.innerText = msg.title; + titleDescWrapper.appendChild(title); + } - if (msg.buttons && msg.buttons.length) { - var buttonsContainer = this.addButtons(msg.buttons); - message.appendChild(buttonsContainer); - } + if (msg.description) { + const description = this.createEl('div', 'description'); + description.innerText = msg.description; + titleDescWrapper.appendChild(description); + } - return message; + if (msg.title || msg.description) { + iconTitleDescWrapper.appendChild(titleDescWrapper); } - }, { - 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'); + if (msg.iconUrl || msg.title || msg.description) { + message.appendChild(iconTitleDescWrapper); + } - button.innerText = b.text; + if (msg.buttons && msg.buttons.length) { + const buttonsContainer = this.addButtons(msg.buttons); + message.appendChild(buttonsContainer); + } - if (i > 0) { - button.style.cssText += 'margin-left: 2px;'; - } + return message; + } - if (b.action === 'copy') { - hasCopyAction = true; - } + 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; - buttonsContainer.appendChild(button); - }); + if (i > 0) { + button.style.cssText += 'margin-left: 2px;'; + } - 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); - } + if (b.action === 'copy') { + hasCopyAction = true; } + + buttonsContainer.appendChild(button); + }); + + if (hasCopyAction) { + this.addSnackbar(buttonsContainer); } - }, { - key: "raiseClickedForBasicTemplates", - value: function raiseClickedForBasicTemplates(path, isPreview) { - var _this3 = this; - var msg = this.message.msg[0]; - var payload = { - msgId: this.campaignId, - pivotId: this.pivotId - }; + return buttonsContainer; + } - if (path.tagName === 'BUTTON') { - var id = path.id.split('-')[1]; - var button = msg.buttons[id]; - payload.kv = { - wzrk_c2a: button.text - }; + 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); + } + + 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 - 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); + image.setAttribute('loading', 'lazy'); + imageContainer.appendChild(image); + return imageContainer; + } + + raiseClickedEvent(path, isPreview) { + switch (this.message.templateType) { + case 'text-only': + case 'text-with-icon': + case 'text-with-icon-and-image': + { + this.raiseClickedForBasicTemplates(path, isPreview); } - } else if (path.tagName === 'CT-INBOX-MESSAGE' && msg.onClickUrl) { - msg.openUrlInNewTab ? window.open(msg.onClickUrl, '_blank') : window.location = msg.onClickUrl; - } + } + } - if (isPreview) { - console.log('Notifiction clicked event will be raised at run time with payload ::', payload); - } else { - window.clevertap.renderNotificationClicked(payload); + raiseClickedForBasicTemplates(path, isPreview) { + const msg = this.message.msg[0]; + const payload = { + msgId: this.campaignId, + pivotId: this.pivotId + }; + + if (path.tagName === 'BUTTON') { + const id = path.id.split('-')[1]; + const button = msg.buttons[id]; + payload.kv = { + wzrk_c2a: button.text + }; + + 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); - - if (this.inboxSelector === null) { - return; - } - - if (this.config.styles.notificationsBadge) { - this.addUnviewedBadge(); - } else if (this.unviewedBadge) { - this.unviewedBadge.remove(); - } - - 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 incomingMessages() { + 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 incomingMessages(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; - } - msgIds.forEach(function (m) { - if (!messages[m].viewed) { - _this2.unviewedMessages[m] = messages[m]; - _this2.unviewedCounter++; - } - }); - this.buildUIForMessages(messages); - this.updateUnviewedBadgeCounter(); + if (msgs.length > 0 && this.inbox) { + this.updateInboxMessages(msgs); } - /** - * @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(); - } - } + get incomingMessagesForPreview() { + return []; + } - delete messages[msg]; - } - } + set incomingMessagesForPreview(msgs) { + if (msgs === void 0) { + msgs = []; + } - 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; - }, {}); - } + const previewMsgs = {}; - 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++; + 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++; }); - saveInboxMessages(inboxMsgs); - this.buildUIForMessages(incomingMsgs); + this.buildUIForMessages(previewMsgs); this.updateUnviewedBadgeCounter(); } - }, { - key: "createEl", - value: function createEl(type, id, part) { - var _el = document.createElement(type); + } - _el.setAttribute('id', id); + connectedCallback() { + this.init(); + } - _el.setAttribute('part', part || id); + init() { + this.config = this.isPreview ? this.inboxConfigForPreview : StorageManager.readFromLSorCookie(WEBINBOX_CONFIG) || {}; - return _el; + if (Object.keys(this.config).length === 0) { + return; } - }, { - 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.inboxSelector = document.getElementById(this.config.inboxSelector); - 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); - } - - this.updateUnviewedBadgePosition(); // called when user switches b/w portrait and landscape mode. - - window.addEventListener('resize', function () { - _this4.updateUnviewedBadgePosition(); - }); + if (this.inboxSelector === null) { + 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); - } - 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 + if (this.config.styles.notificationsBadge) { + this.addUnviewedBadge(); + } else if (this.unviewedBadge) { + this.unviewedBadge.remove(); + } - 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'); + 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. + */ - var _categories = ['All'].concat(_toConsumableArray(this.config.categories)); + 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); + } - _categories.forEach(function (c, i) { - var category = _this6.createEl('div', "category-".concat(i), 'category'); + addMsgsToInboxFromLS() { + const messages = this.deleteExpiredAndGetUnexpiredMsgs(false); + const msgIds = messages ? Object.keys(messages) : []; - category.innerText = c; + if (msgIds.length === 0) { + return; + } - if (i === 0) { - _this6.selectedCategoryRef = category; - } + 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. + */ - 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 - }; + } - if (this.config.styles.categories.borderColor) { - styles.categoriesBorderColor = this.config.styles.categories.borderColor; - } + updateMessageInLS(key, value) { + if (!this.isPreview) { + const messages = getInboxMessages(); + messages[key] = value; + saveInboxMessages(messages); + } + } // create a separte fn fro refactoring + + + 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.styles.categories.selectedTab.borderColor) { - styles.selectedCategoryBorderColor = this.config.styles.categories.selectedTab.borderColor; + 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; + } + + if (this.config.styles.categories.selectedTab.borderColor) { + styles.selectedCategoryBorderColor = this.config.styles.categories.selectedTab.borderColor; } - }]); - return Inbox; - }( /*#__PURE__*/_wrapNativeSuper(HTMLElement)); + 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; @@ -4846,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; @@ -4874,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 @@ -4917,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 @@ -4926,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); @@ -4947,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 @@ -4999,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 @@ -5019,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; @@ -5050,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'; @@ -5075,30 +4480,325 @@ 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\n\n"; - var greenTickSvg = "\n\n\n"; - - var _tr = function _tr(msg, _ref) { - var device = _ref.device, - session = _ref.session, - request = _ref.request, - logger = _ref.logger; - var _device = device; - var _session = session; - var _request = request; - var _logger = logger; - var _wizCounter = 0; // Campaign House keeping - - var doCampHouseKeeping = function doCampHouseKeeping(targetingMsgJson) { - var campaignId = targetingMsgJson.wzrk_id.split('_')[0]; - var today = getToday(); - - var incrCount = function incrCount(obj, campaignId, excludeFromFreqCaps) { - var currentCount = 0; - var totalCount = 0; + const arrowSvg = "\n\n\n"; + const greenTickSvg = "\n\n\n"; + + const OVERLAY_PATH = 'https://web-native-display-campaign.clevertap.com/production/lib-overlay/overlay.js'; + const CSS_PATH = 'https://web-native-display-campaign.clevertap.com/production/lib-overlay/style.css'; + + const updateFormData = (element, formStyle) => { + // Update the element style + if (formStyle.style !== undefined) { + Object.keys(formStyle.style).forEach(property => { + element.style.setProperty(property, formStyle.style[property]); + }); + } // Update underline for element + + + if (formStyle.underline !== undefined) { + const curTextDecoration = element.style.textDecoration; + + if (formStyle.underline) { + element.style.textDecoration = "".concat(curTextDecoration, " underline").trim(); + } else { + element.style.textDecoration = curTextDecoration.replace('underline', '').trim(); + } + } // Update element text + + + if (formStyle.text !== undefined) { + element.innerText = formStyle.text; + } // Handle element onClick + + + if (formStyle.clickDetails !== undefined) { + const url = formStyle.clickDetails.clickUrl; + element.onclick = formStyle.clickDetails.newTab ? () => window.open(url, '_blank').focus() : () => { + window.location.href = url; + }; + } // Set the image source + + + if (formStyle.imgURL !== undefined && element.tagName.toLowerCase() === 'img') { + element.src = formStyle.imgURL; + } // Handle elementCss + + + if (formStyle.elementCss !== undefined) { + const style = document.createElement('style'); + style.innerHTML = formStyle.elementCss; + document.head.appendChild(style); + } + }; + + const checkBuilder = logger => { + const search = window.location.search; + const parentWindow = window.opener; + + if (search === '?ctBuilder') { + // open in visual builder mode + logger.debug('open in visual builder mode'); + window.addEventListener('message', handleMessageEvent, false); + + if (parentWindow) { + parentWindow.postMessage('builder', '*'); + } + + return; + } + + if (search === '?ctBuilderPreview') { + window.addEventListener('message', handleMessageEvent, false); + + if (parentWindow) { + parentWindow.postMessage('preview', '*'); + } + } + }; + + const handleMessageEvent = event => { + if (event.data && event.data.message) { + if (event.data.message === 'Dashboard' && event.data.url) { + var _event$data$variant, _event$data$details; + + initialiseCTBuilder(event.data.url, (_event$data$variant = event.data.variant) !== null && _event$data$variant !== void 0 ? _event$data$variant : null, (_event$data$details = event.data.details) !== null && _event$data$details !== void 0 ? _event$data$details : {}); + } else if (event.data.message === 'Overlay') { + renderVisualBuilder(event.data, true); + } + } + }; + /** + * Initializes the Clevertap builder. + * @param {string} url - The URL to initialize the builder. + * @param {string} variant - The variant of the builder. + * @param {Object} details - The details object. + */ + + + const initialiseCTBuilder = (url, variant, details) => { + if (document.readyState === 'loading') { + document.addEventListener('DOMContentLoaded', () => onContentLoad(url, variant, details)); + } else { + onContentLoad(url, variant, details); + } + }; + + let container; + let contentLoaded = false; + /** + * Handles content load for Clevertap builder. + */ + + function onContentLoad(url, variant, details) { + if (!contentLoaded) { + document.body.innerHTML = ''; + container = document.createElement('div'); + container.id = 'overlayDiv'; + container.style.position = 'relative'; // Ensure relative positioning for absolute positioning of form + + container.style.display = 'flex'; + document.body.appendChild(container); + const overlayPath = OVERLAY_PATH; + loadOverlayScript(overlayPath, url, variant, details).then(() => { + console.log('Overlay script loaded successfully.'); + contentLoaded = true; + }).catch(error => { + console.error('Error loading overlay script:', error); + }); + loadCSS(); + loadTypeKit(); + } + } + /** + * Loads CSS file. + */ + + + function loadCSS() { + var link = document.createElement('link'); + link.rel = 'stylesheet'; + link.type = 'text/css'; + link.href = CSS_PATH; + document.head.appendChild(link); + } + /** + * Loads the overlay script. + * @param {string} overlayPath - The path to overlay script. + * @param {string} url - The URL. + * @param {string} variant - The variant. + * @param {Object} details - The details object. + * @returns {Promise} A promise. + */ + + + function loadOverlayScript(overlayPath, url, variant, details) { + return new Promise((resolve, reject) => { + var script = document.createElement('script'); + script.type = 'module'; + script.src = overlayPath; + + script.onload = function () { + if (typeof window.Overlay === 'function') { + window.Overlay({ + id: '#overlayDiv', + url, + variant, + details + }); + resolve(); + } else { + reject(new Error('ContentLayout not found in overlay.js')); + } + }; + + script.onerror = function (error) { + reject(error); + }; + + document.head.appendChild(script); + }); + } + /** + * Loads TypeKit script. + */ + + + function loadTypeKit() { + const config = { + kitId: 'eqj6nom', + scriptTimeout: 3000, + async: true + }; + const docElement = document.documentElement; + const timeoutId = setTimeout(function () { + docElement.className = docElement.className.replace(/\bwf-loading\b/g, '') + ' wf-inactive'; + }, config.scriptTimeout); + const typeKitScript = document.createElement('script'); + let scriptLoaded = false; + const firstScript = document.getElementsByTagName('script')[0]; + let scriptReadyState; + docElement.className += ' wf-loading'; + typeKitScript.src = 'https://use.typekit.net/' + config.kitId + '.js'; + typeKitScript.async = true; + + typeKitScript.onload = typeKitScript.onreadystatechange = function () { + scriptReadyState = this.readyState; + if (scriptLoaded || scriptReadyState && scriptReadyState !== 'complete' && scriptReadyState !== 'loaded') return; + scriptLoaded = true; + clearTimeout(timeoutId); + + try { + // eslint-disable-next-line no-undef + Typekit.load(config); + } catch (e) {} + }; + + firstScript.parentNode.insertBefore(typeKitScript, firstScript); + } + /** + * Renders the visual builder. + * @param {Object} targetingMsgJson - The point and click campaign JSON object. + * @param {boolean} isPreview - Indicates if it's a preview. + */ + + + const renderVisualBuilder = (targetingMsgJson, isPreview) => { + const details = isPreview ? targetingMsgJson.details[0] : targetingMsgJson.display.details[0]; + const siteUrl = Object.keys(details)[0]; + const selectors = details[siteUrl]; + let elementDisplayed = false; + if (siteUrl !== window.location.href.split('?')[0]) return; + + const processElement = (element, selector) => { + if (selectors[selector].html) { + element.outerHTML = selectors[selector].html; + } else if (selectors[selector].json) { + dispatchJsonData(targetingMsgJson, selectors[selector]); + } else { + updateFormData(element, selectors[selector].form); + } + }; + + const tryFindingElement = selector => { + let count = 0; + const intervalId = setInterval(() => { + const retryElement = document.querySelector(selector); + + if (retryElement) { + processElement(retryElement, selector); + clearInterval(intervalId); + } else if (++count >= 20) { + console.log("No element present on DOM with selector '".concat(selector, "'.")); + clearInterval(intervalId); + } + }, 500); + }; + + Object.keys(selectors).forEach(selector => { + const element = document.querySelector(selector); + + if (element) { + processElement(element, selector); + elementDisplayed = true; + } else { + tryFindingElement(selector); + } + }); + + if (elementDisplayed && !isPreview) { + window.clevertap.renderNotificationViewed({ + msgId: targetingMsgJson.wzrk_id, + pivotId: targetingMsgJson.wzrk_pivot + }); + } + }; + /** + * Dispatches JSON data. + * @param {Object} targetingMsgJson - The point and click campaign JSON object. + * @param {Object} selector - The selector object. + */ + + function dispatchJsonData(targetingMsgJson, selector) { + const inaObj = {}; + inaObj.msgId = targetingMsgJson.wzrk_id; + + if (targetingMsgJson.wzrk_pivot) { + inaObj.pivotId = targetingMsgJson.wzrk_pivot; + } + + if (selector.json != null) { + inaObj.json = selector.json; + } + + const kvPairsEvent = new CustomEvent('CT_web_native_display_buider', { + detail: inaObj + }); + document.dispatchEvent(kvPairsEvent); + } + + const _tr = (msg, _ref) => { + let { + device, + session, + request, + logger + } = _ref; + const _device = device; + const _session = session; + const _request = request; + const _logger = logger; + let _wizCounter = 0; // Campaign House keeping + + const doCampHouseKeeping = targetingMsgJson => { + const campaignId = targetingMsgJson.wzrk_id.split('_')[0]; + const today = getToday(); + + const incrCount = (obj, campaignId, excludeFromFreqCaps) => { + let currentCount = 0; + let totalCount = 0; if (obj[campaignId] != null) { currentCount = obj[campaignId]; @@ -5122,7 +4822,7 @@ if (StorageManager._isLocalStorageSupported()) { delete sessionStorage[CAMP_COOKIE_NAME]; var campTypeObj = {}; - var campObj = getCampaignObject(); + const campObj = getCampaignObject(); if (targetingMsgJson.display.wtarget_type === 3 && campObj.hasOwnProperty('wi')) { campTypeObj = campObj.wi; @@ -5148,16 +4848,16 @@ var excludeFromFreqCaps = -1; // efc - Exclude from frequency caps - var campaignSessionLimit = -1; // mdc - Once per session + let campaignSessionLimit = -1; // mdc - Once per session - var campaignDailyLimit = -1; // tdc - Once per day + let campaignDailyLimit = -1; // tdc - Once per day - var campaignTotalLimit = -1; // tlc - Once per user for the duration of campaign + let campaignTotalLimit = -1; // tlc - Once per user for the duration of campaign - var totalDailyLimit = -1; - var totalSessionLimit = -1; // wmc - Web Popup Global Session Limit + let totalDailyLimit = -1; + let totalSessionLimit = -1; // wmc - Web Popup Global Session Limit - var totalInboxSessionLimit = -1; // wimc - Web Inbox Global Session Limit + let totalInboxSessionLimit = -1; // wimc - Web Inbox Global Session Limit if (targetingMsgJson[DISPLAY].efc != null) { // exclude from frequency cap @@ -5198,8 +4898,8 @@ var sessionObj = campTypeObj[_session.sessionId]; if (sessionObj) { - var campaignSessionCount = sessionObj[campaignId]; - var totalSessionCount = sessionObj.tc; // dnd + const campaignSessionCount = sessionObj[campaignId]; + const totalSessionCount = sessionObj.tc; // dnd if (campaignSessionCount === 'dnd' && !$ct.dismissSpamControl) { return false; @@ -5230,8 +4930,8 @@ var dailyObj = campTypeObj[today]; if (dailyObj != null) { - var campaignDailyCount = dailyObj[campaignId]; - var totalDailyCount = dailyObj.tc; // daily + const campaignDailyCount = dailyObj[campaignId]; + const totalDailyCount = dailyObj.tc; // daily if (totalDailyLimit > 0 && totalDailyCount >= totalDailyLimit && excludeFromFreqCaps < 0) { return false; @@ -5249,7 +4949,7 @@ var globalObj = campTypeObj[GLOBAL]; if (globalObj != null) { - var campaignTotalCount = globalObj[campaignId]; // campaign total + const campaignTotalCount = globalObj[campaignId]; // campaign total if (campaignTotalLimit > 0 && campaignTotalCount >= campaignTotalLimit) { return false; @@ -5262,7 +4962,7 @@ if (targetingMsgJson[DISPLAY].delay != null && targetingMsgJson[DISPLAY].delay > 0) { - var delay = targetingMsgJson[DISPLAY].delay; + const delay = targetingMsgJson[DISPLAY].delay; targetingMsgJson[DISPLAY].delay = 0; setTimeout(_tr, delay * 1000, msg, { device: _device, @@ -5276,32 +4976,34 @@ incrCount(sessionObj, campaignId, excludeFromFreqCaps); incrCount(dailyObj, campaignId, excludeFromFreqCaps); incrCount(globalObj, campaignId, excludeFromFreqCaps); - var campKey = 'wp'; + let campKey = 'wp'; if (targetingMsgJson[DISPLAY].wtarget_type === 3) { campKey = 'wi'; } // get ride of stale sessions and day entries - var newCampObj = {}; + const newCampObj = {}; newCampObj[_session.sessionId] = sessionObj; newCampObj[today] = dailyObj; newCampObj[GLOBAL] = globalObj; - saveCampaignObject(_defineProperty({}, campKey, newCampObj)); + saveCampaignObject({ + [campKey]: newCampObj + }); }; - var getCookieParams = function getCookieParams() { - var gcookie = _device.getGuid(); + const getCookieParams = () => { + const gcookie = _device.getGuid(); - var scookieObj = _session.getSessionCookieObject(); + const scookieObj = _session.getSessionCookieObject(); return '&t=wc&d=' + encodeURIComponent(compressToBase64(gcookie + '|' + scookieObj.p + '|' + scookieObj.s)); }; - var setupClickEvent = function setupClickEvent(onClick, targetingMsgJson, contentDiv, divId, isLegacy) { + const setupClickEvent = (onClick, targetingMsgJson, contentDiv, divId, isLegacy) => { if (onClick !== '' && onClick != null) { - var ctaElement; - var jsCTAElements; + let ctaElement; + let jsCTAElements; if (isLegacy) { ctaElement = contentDiv; @@ -5313,15 +5015,15 @@ } } - var jsFunc = targetingMsgJson.display.jsFunc; - var isPreview = targetingMsgJson.display.preview; + const jsFunc = targetingMsgJson.display.jsFunc; + const isPreview = targetingMsgJson.display.preview; if (isPreview == null) { onClick += getCookieParams(); } if (ctaElement != null) { - ctaElement.onclick = function () { + ctaElement.onclick = () => { // invoke js function call if (jsFunc != null) { // track notification clicked event @@ -5346,8 +5048,8 @@ } }; - var invokeExternalJs = function invokeExternalJs(jsFunc, targetingMsgJson) { - var func = window.parent[jsFunc]; + const invokeExternalJs = (jsFunc, targetingMsgJson) => { + const func = window.parent[jsFunc]; if (typeof func === 'function') { if (targetingMsgJson.display.kv != null) { @@ -5358,79 +5060,81 @@ } }; - var setupClickUrl = function setupClickUrl(onClick, targetingMsgJson, contentDiv, divId, isLegacy) { + const setupClickUrl = (onClick, targetingMsgJson, contentDiv, divId, isLegacy) => { incrementImpression(targetingMsgJson); setupClickEvent(onClick, targetingMsgJson, contentDiv, divId, isLegacy); }; - var incrementImpression = function incrementImpression(targetingMsgJson) { - var data = {}; + const incrementImpression = targetingMsgJson => { + const data = {}; data.type = 'event'; data.evtName = NOTIFICATION_VIEWED; - data.evtData = _defineProperty({}, WZRK_ID, targetingMsgJson.wzrk_id); + data.evtData = { + [WZRK_ID]: targetingMsgJson.wzrk_id + }; if (targetingMsgJson.wzrk_pivot) { - data.evtData = _objectSpread2(_objectSpread2({}, data.evtData), {}, { + data.evtData = { ...data.evtData, wzrk_pivot: targetingMsgJson.wzrk_pivot - }); + }; } _request.processEvent(data); }; - var renderPersonalisationBanner = function renderPersonalisationBanner(targetingMsgJson) { + const renderPersonalisationBanner = targetingMsgJson => { var _targetingMsgJson$dis; if (customElements.get('ct-web-personalisation-banner') === undefined) { customElements.define('ct-web-personalisation-banner', CTWebPersonalisationBanner); } - var divId = (_targetingMsgJson$dis = targetingMsgJson.display.divId) !== null && _targetingMsgJson$dis !== void 0 ? _targetingMsgJson$dis : targetingMsgJson.display.divSelector; - var bannerEl = document.createElement('ct-web-personalisation-banner'); + const divId = (_targetingMsgJson$dis = targetingMsgJson.display.divId) !== null && _targetingMsgJson$dis !== void 0 ? _targetingMsgJson$dis : targetingMsgJson.display.divSelector; + const bannerEl = document.createElement('ct-web-personalisation-banner'); bannerEl.msgId = targetingMsgJson.wzrk_id; bannerEl.pivotId = targetingMsgJson.wzrk_pivot; bannerEl.divHeight = targetingMsgJson.display.divHeight; bannerEl.details = targetingMsgJson.display.details[0]; - var containerEl = targetingMsgJson.display.divId ? document.getElementById(divId) : document.querySelector(divId); + const containerEl = targetingMsgJson.display.divId ? document.getElementById(divId) : document.querySelector(divId); containerEl.innerHTML = ''; containerEl.appendChild(bannerEl); }; - var renderPersonalisationCarousel = function renderPersonalisationCarousel(targetingMsgJson) { + const renderPersonalisationCarousel = targetingMsgJson => { var _targetingMsgJson$dis2; if (customElements.get('ct-web-personalisation-carousel') === undefined) { customElements.define('ct-web-personalisation-carousel', CTWebPersonalisationCarousel); } - var divId = (_targetingMsgJson$dis2 = targetingMsgJson.display.divId) !== null && _targetingMsgJson$dis2 !== void 0 ? _targetingMsgJson$dis2 : targetingMsgJson.display.divSelector; - var carousel = document.createElement('ct-web-personalisation-carousel'); + const divId = (_targetingMsgJson$dis2 = targetingMsgJson.display.divId) !== null && _targetingMsgJson$dis2 !== void 0 ? _targetingMsgJson$dis2 : targetingMsgJson.display.divSelector; + const carousel = document.createElement('ct-web-personalisation-carousel'); carousel.target = targetingMsgJson; - var container = targetingMsgJson.display.divId ? document.getElementById(divId) : document.querySelector(divId); + const container = targetingMsgJson.display.divId ? document.getElementById(divId) : document.querySelector(divId); container.innerHTML = ''; container.appendChild(carousel); }; - var renderPopUpImageOnly = function renderPopUpImageOnly(targetingMsgJson) { - var divId = 'wzrkImageOnlyDiv'; - var popupImageOnly = document.createElement('ct-web-popup-imageonly'); + const renderPopUpImageOnly = targetingMsgJson => { + const divId = 'wzrkImageOnlyDiv'; + const popupImageOnly = document.createElement('ct-web-popup-imageonly'); popupImageOnly.session = _session; popupImageOnly.target = targetingMsgJson; - var containerEl = document.getElementById(divId); + const containerEl = document.getElementById(divId); containerEl.innerHTML = ''; containerEl.style.visibility = 'hidden'; containerEl.appendChild(popupImageOnly); }; - var renderFooterNotification = function renderFooterNotification(targetingMsgJson) { - var campaignId = targetingMsgJson.wzrk_id.split('_')[0]; - var displayObj = targetingMsgJson.display; + const renderFooterNotification = targetingMsgJson => { + const campaignId = targetingMsgJson.wzrk_id.split('_')[0]; + const displayObj = targetingMsgJson.display; if (displayObj.wtarget_type === 2) { // Handling Web Native display // Logic for kv pair data if (targetingMsgJson.msgContent.type === 1) { - var inaObj = {}; + const inaObj = {}; inaObj.msgId = targetingMsgJson.wzrk_id; if (targetingMsgJson.wzrk_pivot) { @@ -5441,7 +5145,7 @@ inaObj.kv = targetingMsgJson.msgContent.kv; } - var kvPairsEvent = new CustomEvent('CT_web_native_display', { + const kvPairsEvent = new CustomEvent('CT_web_native_display', { detail: inaObj }); document.dispatchEvent(kvPairsEvent); @@ -5456,26 +5160,25 @@ if (displayObj.layout === 3) { // Handling Web Popup Image Only - var _divId = 'wzrkImageOnlyDiv'; + const divId = 'wzrkImageOnlyDiv'; if (doCampHouseKeeping(targetingMsgJson) === false) { return; } - if ($ct.dismissSpamControl && document.getElementById(_divId) != null) { - var element = document.getElementById(_divId); + if ($ct.dismissSpamControl && document.getElementById(divId) != null) { + const element = document.getElementById(divId); element.remove(); } // ImageOnly campaign and Interstitial/Exit Intent shouldn't coexist - if (document.getElementById(_divId) != null || document.getElementById('intentPreview') != null) { + if (document.getElementById(divId) != null || document.getElementById('intentPreview') != null) { return; } - var _msgDiv = document.createElement('div'); - - _msgDiv.id = _divId; - document.body.appendChild(_msgDiv); + const msgDiv = document.createElement('div'); + msgDiv.id = divId; + document.body.appendChild(msgDiv); if (customElements.get('ct-web-popup-imageonly') === undefined) { customElements.define('ct-web-popup-imageonly', CTWebPopupImageOnly); @@ -5488,12 +5191,11 @@ return; } - var divId = 'wizParDiv' + displayObj.layout; + const divId = 'wizParDiv' + displayObj.layout; if ($ct.dismissSpamControl && document.getElementById(divId) != null) { - var _element = document.getElementById(divId); - - _element.remove(); + const element = document.getElementById(divId); + element.remove(); } if (document.getElementById(divId) != null) { @@ -5501,20 +5203,20 @@ } $ct.campaignDivMap[campaignId] = divId; - var isBanner = displayObj.layout === 2; - var msgDiv = document.createElement('div'); + const isBanner = displayObj.layout === 2; + const msgDiv = document.createElement('div'); msgDiv.id = divId; - var viewHeight = window.innerHeight; - var viewWidth = window.innerWidth; - var legacy = false; + const viewHeight = window.innerHeight; + const viewWidth = window.innerWidth; + let legacy = false; if (!isBanner) { - var marginBottom = viewHeight * 5 / 100; + const marginBottom = viewHeight * 5 / 100; var contentHeight = 10; - var right = viewWidth * 5 / 100; - var bottomPosition = contentHeight + marginBottom; - var width = viewWidth * 30 / 100 + 20; - var widthPerct = 'width:30%;'; // for small devices - mobile phones + let right = viewWidth * 5 / 100; + let bottomPosition = contentHeight + marginBottom; + let width = viewWidth * 30 / 100 + 20; + let widthPerct = 'width:30%;'; // for small devices - mobile phones if ((/mobile/i.test(navigator.userAgent) || /mini/i.test(navigator.userAgent)) && /iPad/i.test(navigator.userAgent) === false) { width = viewWidth * 85 / 100 + 20; @@ -5540,29 +5242,33 @@ } document.body.appendChild(msgDiv); - var iframe = document.createElement('iframe'); - var borderRadius = displayObj.br === false ? '0' : '8'; + const iframe = document.createElement('iframe'); + const borderRadius = displayObj.br === false ? '0' : '8'; iframe.frameborder = '0px'; iframe.marginheight = '0px'; iframe.marginwidth = '0px'; iframe.scrolling = 'no'; iframe.id = 'wiz-iframe'; - var onClick = targetingMsgJson.display.onClick; - var pointerCss = ''; + const onClick = targetingMsgJson.display.onClick; + let pointerCss = ''; if (onClick !== '' && onClick != null) { pointerCss = 'cursor:pointer;'; } - var html; // direct html + if (displayObj.preview && displayObj['custom-editor']) { + iframe.sandbox = 'allow-scripts allow-popups allow-popups-to-escape-sandbox'; + } + + 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, leftTd, btColor; + const css = '' + ''; + let bgColor, textColor, btnBg, leftTd, btColor; if (targetingMsgJson.display.theme === 'dark') { bgColor = '#2d2d2e'; @@ -5578,38 +5284,34 @@ btColor = '#ffffff'; } - var titleText = targetingMsgJson.msgContent.title; - var descriptionText = targetingMsgJson.msgContent.description; - var imageTd = ''; + const titleText = targetingMsgJson.msgContent.title; + const descriptionText = targetingMsgJson.msgContent.description; + let imageTd = ''; if (targetingMsgJson.msgContent.imageUrl != null && targetingMsgJson.msgContent.imageUrl !== '') { imageTd = ""; } - var onClickStr = 'parent.$WZRK_WR.closeIframe(' + campaignId + ",'" + divId + "');"; - var title = "
" + "×" + "
" + "" + // ""+ + const onClickStr = 'parent.$WZRK_WR.closeIframe(' + campaignId + ",'" + divId + "');"; + const title = "
" + "×" + "
" + "
" + // ""+ '' + imageTd + "
" + "
" + titleText + '
'; - var body = "
" + descriptionText + '
'; + const body = "
" + descriptionText + '
'; html = css + title + body; } iframe.setAttribute('style', 'z-index: 2147483647; display:block; width: 100% !important; border:0px !important; border-color:none !important;'); - msgDiv.appendChild(iframe); - var ifrm = iframe.contentWindow ? iframe.contentWindow : iframe.contentDocument.document ? iframe.contentDocument.document : iframe.contentDocument; - var doc = ifrm.document; // Dispatch event for popup box/banner close + msgDiv.appendChild(iframe); // Dispatch event for popup box/banner close - var closeCampaign = new Event('CT_campaign_rendered'); + const closeCampaign = new Event('CT_campaign_rendered'); document.dispatchEvent(closeCampaign); - doc.open(); - doc.write(html); if (displayObj['custom-editor']) { - appendScriptForCustomEvent(targetingMsgJson, doc); + html = appendScriptForCustomEvent(targetingMsgJson, html); } - doc.close(); + iframe.srcdoc = html; - var adjustIFrameHeight = function adjustIFrameHeight() { + const adjustIFrameHeight = () => { // adjust iframe and body height of html inside correctly contentHeight = document.getElementById('wiz-iframe').contentDocument.getElementById('contentDiv').scrollHeight; @@ -5621,57 +5323,54 @@ document.getElementById('wiz-iframe').style.height = contentHeight + 'px'; }; - var ua = navigator.userAgent.toLowerCase(); + const ua = navigator.userAgent.toLowerCase(); if (ua.indexOf('safari') !== -1) { if (ua.indexOf('chrome') > -1) { - iframe.onload = function () { + iframe.onload = () => { adjustIFrameHeight(); - var contentDiv = document.getElementById('wiz-iframe').contentDocument.getElementById('contentDiv'); + const contentDiv = document.getElementById('wiz-iframe').contentDocument.getElementById('contentDiv'); setupClickUrl(onClick, targetingMsgJson, contentDiv, divId, legacy); }; } else { - var inDoc = iframe.contentDocument || iframe.contentWindow; + let inDoc = iframe.contentDocument || iframe.contentWindow; if (inDoc.document) inDoc = inDoc.document; // safari iphone 7+ needs this. - adjustIFrameHeight(); - - var _timer = setInterval(function () { + const _timer = setInterval(() => { if (inDoc.readyState === 'complete') { clearInterval(_timer); // adjust iframe and body height of html inside correctly adjustIFrameHeight(); - var contentDiv = document.getElementById('wiz-iframe').contentDocument.getElementById('contentDiv'); + const contentDiv = document.getElementById('wiz-iframe').contentDocument.getElementById('contentDiv'); setupClickUrl(onClick, targetingMsgJson, contentDiv, divId, legacy); } - }, 10); + }, 300); } } else { - iframe.onload = function () { + iframe.onload = () => { // adjust iframe and body height of html inside correctly adjustIFrameHeight(); - var contentDiv = document.getElementById('wiz-iframe').contentDocument.getElementById('contentDiv'); + const contentDiv = document.getElementById('wiz-iframe').contentDocument.getElementById('contentDiv'); setupClickUrl(onClick, targetingMsgJson, contentDiv, divId, legacy); }; } }; - var appendScriptForCustomEvent = function appendScriptForCustomEvent(targetingMsgJson, doc) { - var 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); + const appendScriptForCustomEvent = (targetingMsgJson, html) => { + const script = "\n "); + return html.replace(/(<\s*\/\s*body)/, "".concat(script, "\n$1")); }; - 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; @@ -5683,9 +5382,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) { @@ -5704,7 +5403,7 @@ } }; - window.clevertap.raiseNotificationViewed = function () { + window.clevertap.raiseNotificationViewed = () => { incrementImpression(targetingMsgJson); }; @@ -5716,13 +5415,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 = []; @@ -5730,66 +5429,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; @@ -5802,7 +5496,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 @@ -5821,16 +5515,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) { @@ -5841,29 +5535,33 @@ } document.body.appendChild(msgDiv); - var iframe = document.createElement('iframe'); - var borderRadius = targetingMsgJson.display.br === false ? '0' : '8'; + 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 onClick = targetingMsgJson.display.onClick; - var pointerCss = ''; + const onClick = targetingMsgJson.display.onClick; + let pointerCss = ''; if (onClick !== '' && onClick != null) { pointerCss = 'cursor:pointer;'; } - var html; // direct html + if (targetingMsgJson.display.preview && targetingMsgJson.display['custom-editor']) { + iframe.sandbox = 'allow-scripts allow-popups allow-popups-to-escape-sandbox'; + } + + 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'; @@ -5877,43 +5575,42 @@ 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 = "'; } - var imageTd = ''; + let imageTd = ''; if (targetingMsgJson.msgContent.imageUrl != null && targetingMsgJson.msgContent.imageUrl !== '') { imageTd = "
 + titleText + ' /></div>';
         }
 
-        var onClickStr = 'parent.$WZRK_WR.closeIframe(' + campaignId + " + "×" + "
" + "
" + titleText + '
'; - var body = "
" + descriptionText + '
' + imageTd + ctaText + '
'; + const onClickStr = 'parent.$WZRK_WR.closeIframe(' + campaignId + ",'intentPreview');"; + const title = "
" + "×" + "
" + "
" + titleText + '
'; + const body = "
" + descriptionText + '
' + imageTd + ctaText + '
'; html = css + title + body; } iframe.setAttribute('style', 'z-index: 2147483647; display:block; height: 100% !important; width: 100% !important;min-height:80px !important;border:0px !important; border-color:none !important;'); - msgDiv.appendChild(iframe); - var ifrm = iframe.contentWindow ? iframe.contentWindow : iframe.contentDocument.document ? iframe.contentDocument.document : iframe.contentDocument; - var doc = ifrm.document; // Dispatch event for interstitial/exit intent close + msgDiv.appendChild(iframe); // Dispatch event for interstitial/exit intent close - var closeCampaign = new Event('CT_campaign_rendered'); + const closeCampaign = new Event('CT_campaign_rendered'); document.dispatchEvent(closeCampaign); - doc.open(); - doc.write(html); if (targetingMsgJson.display['custom-editor']) { - appendScriptForCustomEvent(targetingMsgJson, doc); + html = appendScriptForCustomEvent(targetingMsgJson, html); } - doc.close(); - var contentDiv = document.getElementById('wiz-iframe-intent').contentDocument.getElementById('contentDiv'); - setupClickUrl(onClick, targetingMsgJson, contentDiv, 'intentPreview', legacy); + iframe.srcdoc = html; + + iframe.onload = () => { + const contentDiv = document.getElementById('wiz-iframe-intent').contentDocument.getElementById('contentDiv'); + setupClickUrl(onClick, targetingMsgJson, contentDiv, 'intentPreview', legacy); + }; }; if (!document.body) { @@ -5930,8 +5627,8 @@ return; } - var processNativeDisplayArr = function processNativeDisplayArr(arrInAppNotifs) { - Object.keys(arrInAppNotifs).map(function (key) { + const processNativeDisplayArr = arrInAppNotifs => { + Object.keys(arrInAppNotifs).map(key => { var elementId, id; if (arrInAppNotifs[key].display.divId) { @@ -5949,12 +5646,12 @@ }); }; - var addLoadListener = function addLoadListener(arrInAppNotifs) { - window.addEventListener('load', function () { - var count = 0; + const addLoadListener = arrInAppNotifs => { + window.addEventListener('load', () => { + let count = 0; if (count < 20) { - var t = setInterval(function () { + const t = setInterval(() => { processNativeDisplayArr(arrInAppNotifs); if (Object.keys(arrInAppNotifs).length === 0 || count === 20) { @@ -5969,10 +5666,10 @@ }; if (msg.inapp_notifs != null) { - var arrInAppNotifs = {}; + const arrInAppNotifs = {}; - for (var index = 0; index < msg.inapp_notifs.length; index++) { - var targetNotif = msg.inapp_notifs[index]; + for (let index = 0; index < msg.inapp_notifs.length; index++) { + const targetNotif = msg.inapp_notifs[index]; if (targetNotif.display.wtarget_type == null || targetNotif.display.wtarget_type === 0) { showFooterNotification(targetNotif); @@ -5984,13 +5681,15 @@ // if display['wtarget_type']==2 then web native display if (targetNotif.msgContent.type === 2 || targetNotif.msgContent.type === 3) { // Check for banner and carousel - var element = targetNotif.display.divId ? document.getElementById(targetNotif.display.divId) : document.querySelector(targetNotif.display.divSelector); + const element = targetNotif.display.divId ? document.getElementById(targetNotif.display.divId) : document.querySelector(targetNotif.display.divSelector); if (element !== null) { targetNotif.msgContent.type === 2 ? renderPersonalisationBanner(targetNotif) : renderPersonalisationCarousel(targetNotif); } else { arrInAppNotifs[targetNotif.wzrk_id.split('_')[0]] = targetNotif; // Add targetNotif to object } + } else if (targetNotif.msgContent.type === 4) { + renderVisualBuilder(targetNotif, false); } else { showFooterNotification(targetNotif); } @@ -6007,7 +5706,7 @@ } } - var mergeEventMap = function mergeEventMap(newEvtMap) { + const mergeEventMap = newEvtMap => { if ($ct.globalEventsMap == null) { $ct.globalEventsMap = StorageManager.readFromLSorCookie(EV_COOKIE); @@ -6017,10 +5716,10 @@ } } - for (var key in newEvtMap) { + for (const key in newEvtMap) { if (newEvtMap.hasOwnProperty(key)) { - var oldEvtObj = $ct.globalEventsMap[key]; - var newEvtObj = newEvtMap[key]; + const oldEvtObj = $ct.globalEventsMap[key]; + const newEvtObj = newEvtMap[key]; if ($ct.globalEventsMap[key] != null) { if (newEvtObj[0] != null && newEvtObj[0] > oldEvtObj[0]) { @@ -6033,18 +5732,18 @@ } }; - var handleInboxNotifications = function handleInboxNotifications() { + const handleInboxNotifications = () => { if (msg.inbox_preview) { processInboxNotifs(msg); return; } if (msg.inbox_notifs) { - var msgArr = []; + const msgArr = []; - for (var _index = 0; _index < msg.inbox_notifs.length; _index++) { - if (doCampHouseKeeping(msg.inbox_notifs[_index]) !== false) { - msgArr.push(msg.inbox_notifs[_index]); + for (let index = 0; index < msg.inbox_notifs.length; index++) { + if (doCampHouseKeeping(msg.inbox_notifs[index]) !== false) { + msgArr.push(msg.inbox_notifs[index]); } } @@ -6064,9 +5763,9 @@ if ($ct.inbox === null) { msg.webInboxSetting && processWebInboxSettings(msg.webInboxSetting); - initializeWebInbox(_logger).then(function () { + initializeWebInbox(_logger).then(() => { handleInboxNotifications(); - }).catch(function (e) {}); + }).catch(e => {}); } else { handleInboxNotifications(); } @@ -6077,18 +5776,18 @@ return; } - var staleDataUpdate = function staleDataUpdate(staledata, campType) { - var campObj = getCampaignObject(); - var globalObj = campObj[campType].global; + const staleDataUpdate = (staledata, campType) => { + const campObj = getCampaignObject(); + const globalObj = campObj[campType].global; if (globalObj != null && campType) { - for (var idx in staledata) { + for (const idx in staledata) { if (staledata.hasOwnProperty(idx)) { delete globalObj[staledata[idx]]; if (StorageManager.read(CAMP_COOKIE_G)) { - var guidCampObj = JSON.parse(decodeURIComponent(StorageManager.read(CAMP_COOKIE_G))); - var guid = JSON.parse(decodeURIComponent(StorageManager.read(GCOOKIE_NAME))); + const guidCampObj = JSON.parse(decodeURIComponent(StorageManager.read(CAMP_COOKIE_G))); + const guid = JSON.parse(decodeURIComponent(StorageManager.read(GCOOKIE_NAME))); if (guidCampObj[guid] && guidCampObj[guid][campType] && guidCampObj[guid][campType][staledata[idx]]) { delete guidCampObj[guid][campType][staledata[idx]]; @@ -6105,10 +5804,10 @@ if (StorageManager._isLocalStorageSupported()) { try { if (msg.evpr != null) { - var eventsMap = msg.evpr.events; - var profileMap = msg.evpr.profile; - var syncExpiry = msg.evpr.expires_in; - var now = getNow(); + const eventsMap = msg.evpr.events; + const profileMap = msg.evpr.profile; + const syncExpiry = msg.evpr.expires_in; + const now = getNow(); StorageManager.setMetaProp('lsTime', now); StorageManager.setMetaProp('exTs', syncExpiry); mergeEventMap(eventsMap); @@ -6142,12 +5841,11 @@ var _isPersonalisationActive$2 = _classPrivateFieldLooseKey("isPersonalisationActive"); - var User = /*#__PURE__*/function () { - function User(_ref) { - var isPersonalisationActive = _ref.isPersonalisationActive; - - _classCallCheck(this, User); - + class User { + constructor(_ref) { + let { + isPersonalisationActive + } = _ref; Object.defineProperty(this, _isPersonalisationActive$2, { writable: true, value: void 0 @@ -6155,40 +5853,35 @@ _classPrivateFieldLooseBase(this, _isPersonalisationActive$2)[_isPersonalisationActive$2] = isPersonalisationActive; } - _createClass(User, [{ - key: "getTotalVisits", - value: function getTotalVisits() { - if (!_classPrivateFieldLooseBase(this, _isPersonalisationActive$2)[_isPersonalisationActive$2]()) { - return; - } + getTotalVisits() { + if (!_classPrivateFieldLooseBase(this, _isPersonalisationActive$2)[_isPersonalisationActive$2]()) { + return; + } - var visitCount = StorageManager.getMetaProp('sc'); + let visitCount = StorageManager.getMetaProp('sc'); - if (visitCount == null) { - visitCount = 1; - } + if (visitCount == null) { + visitCount = 1; + } + + return visitCount; + } - return visitCount; + getLastVisit() { + if (!_classPrivateFieldLooseBase(this, _isPersonalisationActive$2)[_isPersonalisationActive$2]()) { + return; } - }, { - key: "getLastVisit", - value: function getLastVisit() { - if (!_classPrivateFieldLooseBase(this, _isPersonalisationActive$2)[_isPersonalisationActive$2]()) { - return; - } - var prevSession = StorageManager.getMetaProp('ps'); + const prevSession = StorageManager.getMetaProp('ps'); - if (prevSession != null) { - return new Date(prevSession * 1000); - } + if (prevSession != null) { + return new Date(prevSession * 1000); } - }]); + } - return User; - }(); + } - var logLevels = { + const logLevels = { DISABLE: 0, ERROR: 1, INFO: 2, @@ -6202,10 +5895,8 @@ var _isLegacyDebug = _classPrivateFieldLooseKey("isLegacyDebug"); - var Logger = /*#__PURE__*/function () { - function Logger(logLevel) { - _classCallCheck(this, Logger); - + class Logger { + constructor(logLevel) { Object.defineProperty(this, _isLegacyDebug, { get: _get_isLegacyDebug, set: void 0 @@ -6222,64 +5913,56 @@ this.wzrkError = {}; } - _createClass(Logger, [{ - key: "error", - value: function error(message) { - if (_classPrivateFieldLooseBase(this, _logLevel)[_logLevel] >= logLevels.ERROR) { - _classPrivateFieldLooseBase(this, _log)[_log]('error', message); - } - } - }, { - key: "info", - value: function info(message) { - if (_classPrivateFieldLooseBase(this, _logLevel)[_logLevel] >= logLevels.INFO) { - _classPrivateFieldLooseBase(this, _log)[_log]('log', message); - } - } - }, { - key: "debug", - value: function debug(message) { - if (_classPrivateFieldLooseBase(this, _logLevel)[_logLevel] >= logLevels.DEBUG || _classPrivateFieldLooseBase(this, _isLegacyDebug)[_isLegacyDebug]) { - _classPrivateFieldLooseBase(this, _log)[_log]('debug', message); - } + get logLevel() { + return _classPrivateFieldLooseBase(this, _logLevel)[_logLevel]; + } + + set logLevel(logLevel) { + _classPrivateFieldLooseBase(this, _logLevel)[_logLevel] = logLevel; + } + + error(message) { + if (_classPrivateFieldLooseBase(this, _logLevel)[_logLevel] >= logLevels.ERROR) { + _classPrivateFieldLooseBase(this, _log)[_log]('error', message); } - }, { - key: "debugPE", - value: function debugPE(message) { - if (_classPrivateFieldLooseBase(this, _logLevel)[_logLevel] >= logLevels.DEBUG_PE) { - _classPrivateFieldLooseBase(this, _log)[_log]('debug_pe', message); - } + } + + info(message) { + if (_classPrivateFieldLooseBase(this, _logLevel)[_logLevel] >= logLevels.INFO) { + _classPrivateFieldLooseBase(this, _log)[_log]('log', message); } - }, { - key: "reportError", - value: function reportError(code, description) { - this.wzrkError.c = code; - this.wzrkError.d = description; - this.error("".concat(CLEVERTAP_ERROR_PREFIX, " ").concat(code, ": ").concat(description)); + } + + debug(message) { + if (_classPrivateFieldLooseBase(this, _logLevel)[_logLevel] >= logLevels.DEBUG || _classPrivateFieldLooseBase(this, _isLegacyDebug)[_isLegacyDebug]) { + _classPrivateFieldLooseBase(this, _log)[_log]('debug', message); } - }, { - key: "logLevel", - get: function get() { - return _classPrivateFieldLooseBase(this, _logLevel)[_logLevel]; - }, - set: function set(logLevel) { - _classPrivateFieldLooseBase(this, _logLevel)[_logLevel] = logLevel; + } + + debugPE(message) { + if (_classPrivateFieldLooseBase(this, _logLevel)[_logLevel] >= logLevels.DEBUG_PE) { + _classPrivateFieldLooseBase(this, _log)[_log]('debug_pe', message); } - }]); + } - return Logger; - }(); + reportError(code, description) { + this.wzrkError.c = code; + this.wzrkError.d = description; + this.error("".concat(CLEVERTAP_ERROR_PREFIX, " ").concat(code, ": ").concat(description)); + } + + } var _log2 = function _log2(level, message) { if (window.console) { try { - var ts = new Date().getTime(); + const ts = new Date().getTime(); console[level]("CleverTap [".concat(ts, "]: ").concat(message)); } catch (e) {} } }; - var _get_isLegacyDebug = function _get_isLegacyDebug() { + var _get_isLegacyDebug = function () { return typeof sessionStorage !== 'undefined' && sessionStorage.WZRK_D === ''; }; @@ -6289,14 +5972,13 @@ var _isPersonalisationActive$3 = _classPrivateFieldLooseKey("isPersonalisationActive"); - var SessionManager = /*#__PURE__*/function () { + class SessionManager { // SCOOKIE_NAME - function SessionManager(_ref) { - var logger = _ref.logger, - isPersonalisationActive = _ref.isPersonalisationActive; - - _classCallCheck(this, SessionManager); - + constructor(_ref) { + let { + logger, + isPersonalisationActive + } = _ref; Object.defineProperty(this, _logger$5, { writable: true, value: void 0 @@ -6316,120 +5998,112 @@ _classPrivateFieldLooseBase(this, _isPersonalisationActive$3)[_isPersonalisationActive$3] = isPersonalisationActive; } - _createClass(SessionManager, [{ - key: "getSessionCookieObject", - value: function getSessionCookieObject() { - var scookieStr = StorageManager.readCookie(this.cookieName); - var obj = {}; + get sessionId() { + return _classPrivateFieldLooseBase(this, _sessionId)[_sessionId]; + } - if (scookieStr != null) { - // converting back single quotes to double for JSON parsing - http://www.iandevlin.com/blog/2012/04/html5/cookies-json-localstorage-and-opera - scookieStr = scookieStr.replace(singleQuoteRegex, '"'); - obj = JSON.parse(scookieStr); + set sessionId(sessionId) { + _classPrivateFieldLooseBase(this, _sessionId)[_sessionId] = sessionId; + } - if (!isObject(obj)) { - obj = {}; - } else { - if (typeof obj.t !== 'undefined') { - // check time elapsed since last request - var lastTime = obj.t; - var now = getNow(); - - if (now - lastTime > SCOOKIE_EXP_TIME_IN_SECS + 60) { - // adding 60 seconds to compensate for in-journey requests - // ideally the cookie should've died after SCOOKIE_EXP_TIME_IN_SECS but it's still around as we can read - // hence we shouldn't use it. - obj = {}; - } + getSessionCookieObject() { + let scookieStr = StorageManager.readCookie(this.cookieName); + let obj = {}; + + if (scookieStr != null) { + // converting back single quotes to double for JSON parsing - http://www.iandevlin.com/blog/2012/04/html5/cookies-json-localstorage-and-opera + scookieStr = scookieStr.replace(singleQuoteRegex, '"'); + obj = JSON.parse(scookieStr); + + if (!isObject(obj)) { + obj = {}; + } else { + if (typeof obj.t !== 'undefined') { + // check time elapsed since last request + const lastTime = obj.t; + const now = getNow(); + + if (now - lastTime > SCOOKIE_EXP_TIME_IN_SECS + 60) { + // adding 60 seconds to compensate for in-journey requests + // ideally the cookie should've died after SCOOKIE_EXP_TIME_IN_SECS but it's still around as we can read + // hence we shouldn't use it. + obj = {}; } } } + } - this.scookieObj = obj; - return obj; - } - }, { - key: "setSessionCookieObject", - value: function setSessionCookieObject(obj) { - var objStr = JSON.stringify(obj); - StorageManager.createBroadCookie(this.cookieName, objStr, SCOOKIE_EXP_TIME_IN_SECS, getHostName()); - } - }, { - key: "manageSession", - value: function manageSession(session) { - // first time. check if current session id in localstorage is same - // if not same then prev = current and current = this new session - if (typeof this.sessionId === 'undefined' || this.sessionId !== session) { - var currentSessionInLS = StorageManager.getMetaProp('cs'); // if sessionId in meta is undefined - set current to both - - if (typeof currentSessionInLS === 'undefined') { - StorageManager.setMetaProp('ps', session); - StorageManager.setMetaProp('cs', session); - StorageManager.setMetaProp('sc', 1); - } else if (currentSessionInLS !== session) { - // not same as session in local storage. new session - StorageManager.setMetaProp('ps', currentSessionInLS); - StorageManager.setMetaProp('cs', session); - var sessionCount = StorageManager.getMetaProp('sc'); - - if (typeof sessionCount === 'undefined') { - sessionCount = 0; - } + this.scookieObj = obj; + return obj; + } + + setSessionCookieObject(obj) { + const objStr = JSON.stringify(obj); + StorageManager.createBroadCookie(this.cookieName, objStr, SCOOKIE_EXP_TIME_IN_SECS, getHostName()); + } + + manageSession(session) { + // first time. check if current session id in localstorage is same + // if not same then prev = current and current = this new session + if (typeof this.sessionId === 'undefined' || this.sessionId !== session) { + const currentSessionInLS = StorageManager.getMetaProp('cs'); // if sessionId in meta is undefined - set current to both - StorageManager.setMetaProp('sc', sessionCount + 1); + if (typeof currentSessionInLS === 'undefined') { + StorageManager.setMetaProp('ps', session); + StorageManager.setMetaProp('cs', session); + StorageManager.setMetaProp('sc', 1); + } else if (currentSessionInLS !== session) { + // not same as session in local storage. new session + StorageManager.setMetaProp('ps', currentSessionInLS); + StorageManager.setMetaProp('cs', session); + let sessionCount = StorageManager.getMetaProp('sc'); + + if (typeof sessionCount === 'undefined') { + sessionCount = 0; } - this.sessionId = session; - } - } - }, { - key: "getTimeElapsed", - value: function getTimeElapsed() { - if (!_classPrivateFieldLooseBase(this, _isPersonalisationActive$3)[_isPersonalisationActive$3]()) { - return; + StorageManager.setMetaProp('sc', sessionCount + 1); } - if (this.scookieObj != null) { - // TODO: check logic? - this.scookieObj = this.getSessionCookieObject(); - } + this.sessionId = session; + } + } - var sessionStart = this.scookieObj.s; + getTimeElapsed() { + if (!_classPrivateFieldLooseBase(this, _isPersonalisationActive$3)[_isPersonalisationActive$3]()) { + return; + } - if (sessionStart != null) { - var ts = getNow(); - return Math.floor(ts - sessionStart); - } + if (this.scookieObj != null) { + // TODO: check logic? + this.scookieObj = this.getSessionCookieObject(); } - }, { - key: "getPageCount", - value: function getPageCount() { - if (!_classPrivateFieldLooseBase(this, _isPersonalisationActive$3)[_isPersonalisationActive$3]()) { - return; - } - if (this.scookieObj != null) { - // TODO: check logic - this.scookieObj = this.getSessionCookieObject(); - } + const sessionStart = this.scookieObj.s; + + if (sessionStart != null) { + const ts = getNow(); + return Math.floor(ts - sessionStart); + } + } - return this.scookieObj.p; + getPageCount() { + if (!_classPrivateFieldLooseBase(this, _isPersonalisationActive$3)[_isPersonalisationActive$3]()) { + return; } - }, { - key: "sessionId", - get: function get() { - return _classPrivateFieldLooseBase(this, _sessionId)[_sessionId]; - }, - set: function set(sessionId) { - _classPrivateFieldLooseBase(this, _sessionId)[_sessionId] = sessionId; + + if (this.scookieObj != null) { + // TODO: check logic + this.scookieObj = this.getSessionCookieObject(); } - }]); - return SessionManager; - }(); + return this.scookieObj.p; + } + + } - var seqNo = 0; - var requestTime = 0; + let seqNo = 0; + let requestTime = 0; var _logger$6 = _classPrivateFieldLooseKey("logger"); @@ -6445,16 +6119,15 @@ var _addToLocalEventMap = _classPrivateFieldLooseKey("addToLocalEventMap"); - var RequestManager = /*#__PURE__*/function () { - function RequestManager(_ref) { - var logger = _ref.logger, - account = _ref.account, - device = _ref.device, - session = _ref.session, - isPersonalisationActive = _ref.isPersonalisationActive; - - _classCallCheck(this, RequestManager); - + class RequestManager { + constructor(_ref) { + let { + logger, + account, + device, + session, + isPersonalisationActive + } = _ref; Object.defineProperty(this, _addToLocalEventMap, { value: _addToLocalEventMap2 }); @@ -6493,234 +6166,222 @@ RequestDispatcher.account = account; } - _createClass(RequestManager, [{ - key: "processBackupEvents", - value: function processBackupEvents() { - var backupMap = StorageManager.readFromLSorCookie(LCOOKIE_NAME); - - if (typeof backupMap === 'undefined' || backupMap === null) { - return; - } + processBackupEvents() { + const backupMap = StorageManager.readFromLSorCookie(LCOOKIE_NAME); - this.processingBackup = true; + if (typeof backupMap === 'undefined' || backupMap === null) { + return; + } - for (var idx in backupMap) { - if (backupMap.hasOwnProperty(idx)) { - var backupEvent = backupMap[idx]; + this.processingBackup = true; - if (typeof backupEvent.fired === 'undefined') { - _classPrivateFieldLooseBase(this, _logger$6)[_logger$6].debug('Processing backup event : ' + backupEvent.q); + for (const idx in backupMap) { + if (backupMap.hasOwnProperty(idx)) { + const backupEvent = backupMap[idx]; - if (typeof backupEvent.q !== 'undefined') { - RequestDispatcher.fireRequest(backupEvent.q); - } + if (typeof backupEvent.fired === 'undefined') { + _classPrivateFieldLooseBase(this, _logger$6)[_logger$6].debug('Processing backup event : ' + backupEvent.q); - backupEvent.fired = true; + if (typeof backupEvent.q !== 'undefined') { + RequestDispatcher.fireRequest(backupEvent.q); } + + backupEvent.fired = true; } } + } + + StorageManager.saveToLSorCookie(LCOOKIE_NAME, backupMap); + this.processingBackup = false; + } - StorageManager.saveToLSorCookie(LCOOKIE_NAME, backupMap); - this.processingBackup = false; + addSystemDataToObject(dataObject, ignoreTrim) { + // ignore trim for chrome notifications; undefined everywhere else + if (typeof ignoreTrim === 'undefined') { + dataObject = removeUnsupportedChars(dataObject, _classPrivateFieldLooseBase(this, _logger$6)[_logger$6]); } - }, { - key: "addSystemDataToObject", - value: function addSystemDataToObject(dataObject, ignoreTrim) { - // ignore trim for chrome notifications; undefined everywhere else - if (typeof ignoreTrim === 'undefined') { - dataObject = removeUnsupportedChars(dataObject, _classPrivateFieldLooseBase(this, _logger$6)[_logger$6]); - } - if (!isObjectEmpty(_classPrivateFieldLooseBase(this, _logger$6)[_logger$6].wzrkError)) { - dataObject.wzrk_error = _classPrivateFieldLooseBase(this, _logger$6)[_logger$6].wzrkError; - _classPrivateFieldLooseBase(this, _logger$6)[_logger$6].wzrkError = {}; - } + if (!isObjectEmpty(_classPrivateFieldLooseBase(this, _logger$6)[_logger$6].wzrkError)) { + dataObject.wzrk_error = _classPrivateFieldLooseBase(this, _logger$6)[_logger$6].wzrkError; + _classPrivateFieldLooseBase(this, _logger$6)[_logger$6].wzrkError = {}; + } - dataObject.id = _classPrivateFieldLooseBase(this, _account$2)[_account$2].id; + dataObject.id = _classPrivateFieldLooseBase(this, _account$2)[_account$2].id; - if (isValueValid(_classPrivateFieldLooseBase(this, _device$2)[_device$2].gcookie)) { - dataObject.g = _classPrivateFieldLooseBase(this, _device$2)[_device$2].gcookie; - } + if (isValueValid(_classPrivateFieldLooseBase(this, _device$2)[_device$2].gcookie)) { + dataObject.g = _classPrivateFieldLooseBase(this, _device$2)[_device$2].gcookie; + } - var obj = _classPrivateFieldLooseBase(this, _session$2)[_session$2].getSessionCookieObject(); + const obj = _classPrivateFieldLooseBase(this, _session$2)[_session$2].getSessionCookieObject(); - dataObject.s = obj.s; // session cookie + dataObject.s = obj.s; // session cookie - dataObject.pg = typeof obj.p === 'undefined' ? 1 : obj.p; // Page count + dataObject.pg = typeof obj.p === 'undefined' ? 1 : obj.p; // Page count - var proto = document.location.protocol; - proto = proto.replace(':', ''); - dataObject.af = _objectSpread2({ - lib: 'web-sdk-v1.7.3', - protocol: proto - }, $ct.flutterVersion); // app fields + let proto = document.location.protocol; + proto = proto.replace(':', ''); + dataObject.af = { ...dataObject.af, + lib: 'web-sdk-v1.9.0', + protocol: proto, + ...$ct.flutterVersion + }; // app fields - if (sessionStorage.hasOwnProperty('WZRK_D')) { - dataObject.debug = true; - } + if (sessionStorage.hasOwnProperty('WZRK_D')) { + dataObject.debug = true; + } + + return dataObject; + } + + addFlags(data) { + // check if cookie should be cleared. + _classPrivateFieldLooseBase(this, _clearCookie)[_clearCookie] = StorageManager.getAndClearMetaProp(CLEAR); - return dataObject; + if (_classPrivateFieldLooseBase(this, _clearCookie)[_clearCookie] !== undefined && _classPrivateFieldLooseBase(this, _clearCookie)[_clearCookie]) { + data.rc = true; + + _classPrivateFieldLooseBase(this, _logger$6)[_logger$6].debug('reset cookie sent in request and cleared from meta for future requests.'); } - }, { - key: "addFlags", - value: function addFlags(data) { - // check if cookie should be cleared. - _classPrivateFieldLooseBase(this, _clearCookie)[_clearCookie] = StorageManager.getAndClearMetaProp(CLEAR); - if (_classPrivateFieldLooseBase(this, _clearCookie)[_clearCookie] !== undefined && _classPrivateFieldLooseBase(this, _clearCookie)[_clearCookie]) { - data.rc = true; + if (_classPrivateFieldLooseBase(this, _isPersonalisationActive$4)[_isPersonalisationActive$4]()) { + const lastSyncTime = StorageManager.getMetaProp('lsTime'); + const expirySeconds = StorageManager.getMetaProp('exTs'); // dsync not found in local storage - get data from server - _classPrivateFieldLooseBase(this, _logger$6)[_logger$6].debug('reset cookie sent in request and cleared from meta for future requests.'); + if (typeof lastSyncTime === 'undefined' || typeof expirySeconds === 'undefined') { + data.dsync = true; + return; } - if (_classPrivateFieldLooseBase(this, _isPersonalisationActive$4)[_isPersonalisationActive$4]()) { - var lastSyncTime = StorageManager.getMetaProp('lsTime'); - var expirySeconds = StorageManager.getMetaProp('exTs'); // dsync not found in local storage - get data from server + const now = getNow(); // last sync time has expired - get fresh data from server - if (typeof lastSyncTime === 'undefined' || typeof expirySeconds === 'undefined') { - data.dsync = true; - return; - } + if (lastSyncTime + expirySeconds < now) { + data.dsync = true; + } + } + } // saves url to backup cache and fires the request - var now = getNow(); // last sync time has expired - get fresh data from server + /** + * + * @param {string} url + * @param {boolean} override whether the request can go through or not + * @param {Boolean} sendOULFlag - true in case of a On User Login request + */ - if (lastSyncTime + expirySeconds < now) { - data.dsync = true; - } - } - } // saves url to backup cache and fires the request - /** - * - * @param {string} url - * @param {boolean} override whether the request can go through or not - * @param {Boolean} sendOULFlag - true in case of a On User Login request - */ + saveAndFireRequest(url, override, sendOULFlag, evtName) { + const now = getNow(); + url = addToURL(url, 'rn', ++$ct.globalCache.REQ_N); + const data = url + '&i=' + now + '&sn=' + seqNo; + StorageManager.backupEvent(data, $ct.globalCache.REQ_N, _classPrivateFieldLooseBase(this, _logger$6)[_logger$6]); // if offline is set to true, save the request in backup and return - }, { - key: "saveAndFireRequest", - value: function saveAndFireRequest(url, override, sendOULFlag, evtName) { - var now = getNow(); - url = addToURL(url, 'rn', ++$ct.globalCache.REQ_N); - var data = url + '&i=' + now + '&sn=' + seqNo; - StorageManager.backupEvent(data, $ct.globalCache.REQ_N, _classPrivateFieldLooseBase(this, _logger$6)[_logger$6]); // if offline is set to true, save the request in backup and return - - if ($ct.offline) return; // if there is no override - // and an OUL request is not in progress - // then process the request as it is - // else block the request - // note - $ct.blockRequest should ideally be used for override - - if ((!override || _classPrivateFieldLooseBase(this, _clearCookie)[_clearCookie] !== undefined && _classPrivateFieldLooseBase(this, _clearCookie)[_clearCookie]) && !window.isOULInProgress) { - if (now === requestTime) { - seqNo++; - } else { - requestTime = now; - seqNo = 0; - } + if ($ct.offline) return; // if there is no override + // and an OUL request is not in progress + // then process the request as it is + // else block the request + // note - $ct.blockRequest should ideally be used for override - window.oulReqN = $ct.globalCache.REQ_N; - RequestDispatcher.fireRequest(data, false, sendOULFlag, evtName); + if ((!override || _classPrivateFieldLooseBase(this, _clearCookie)[_clearCookie] !== undefined && _classPrivateFieldLooseBase(this, _clearCookie)[_clearCookie]) && !window.isOULInProgress) { + if (now === requestTime) { + seqNo++; } else { - _classPrivateFieldLooseBase(this, _logger$6)[_logger$6].debug("Not fired due to override - ".concat($ct.blockRequest, " or clearCookie - ").concat(_classPrivateFieldLooseBase(this, _clearCookie)[_clearCookie], " or OUL request in progress - ").concat(window.isOULInProgress)); + requestTime = now; + seqNo = 0; } + + window.oulReqN = $ct.globalCache.REQ_N; + RequestDispatcher.fireRequest(data, false, sendOULFlag, evtName); + } else { + _classPrivateFieldLooseBase(this, _logger$6)[_logger$6].debug("Not fired due to override - ".concat($ct.blockRequest, " or clearCookie - ").concat(_classPrivateFieldLooseBase(this, _clearCookie)[_clearCookie], " or OUL request in progress - ").concat(window.isOULInProgress)); } - }, { - key: "unregisterTokenForGuid", - value: function unregisterTokenForGuid(givenGUID) { - var payload = StorageManager.readFromLSorCookie(PUSH_SUBSCRIPTION_DATA); // Send unregister event only when token is available + } - if (payload) { - var data = {}; - data.type = 'data'; + unregisterTokenForGuid(givenGUID) { + const payload = StorageManager.readFromLSorCookie(PUSH_SUBSCRIPTION_DATA); // Send unregister event only when token is available - if (isValueValid(givenGUID)) { - data.g = givenGUID; - } + if (payload) { + const data = {}; + data.type = 'data'; - data.action = 'unregister'; - data.id = _classPrivateFieldLooseBase(this, _account$2)[_account$2].id; + if (isValueValid(givenGUID)) { + data.g = givenGUID; + } - var obj = _classPrivateFieldLooseBase(this, _session$2)[_session$2].getSessionCookieObject(); + data.action = 'unregister'; + data.id = _classPrivateFieldLooseBase(this, _account$2)[_account$2].id; - data.s = obj.s; // session cookie + const obj = _classPrivateFieldLooseBase(this, _session$2)[_session$2].getSessionCookieObject(); - var compressedData = compressData(JSON.stringify(data), _classPrivateFieldLooseBase(this, _logger$6)[_logger$6]); + data.s = obj.s; // session cookie - var pageLoadUrl = _classPrivateFieldLooseBase(this, _account$2)[_account$2].dataPostURL; + const compressedData = compressData(JSON.stringify(data), _classPrivateFieldLooseBase(this, _logger$6)[_logger$6]); - pageLoadUrl = addToURL(pageLoadUrl, 'type', 'data'); - pageLoadUrl = addToURL(pageLoadUrl, 'd', compressedData); - RequestDispatcher.fireRequest(pageLoadUrl, true); - StorageManager.saveToLSorCookie(FIRE_PUSH_UNREGISTERED, false); - } // REGISTER TOKEN + let pageLoadUrl = _classPrivateFieldLooseBase(this, _account$2)[_account$2].dataPostURL; + pageLoadUrl = addToURL(pageLoadUrl, 'type', 'data'); + pageLoadUrl = addToURL(pageLoadUrl, 'd', compressedData); + RequestDispatcher.fireRequest(pageLoadUrl, true); + StorageManager.saveToLSorCookie(FIRE_PUSH_UNREGISTERED, false); + } // REGISTER TOKEN - this.registerToken(payload); - } - }, { - key: "registerToken", - value: function registerToken(payload) { - if (!payload) return; // add gcookie etc to the payload - payload = this.addSystemDataToObject(payload, true); - payload = JSON.stringify(payload); + this.registerToken(payload); + } + + registerToken(payload) { + if (!payload) return; // add gcookie etc to the payload - var pageLoadUrl = _classPrivateFieldLooseBase(this, _account$2)[_account$2].dataPostURL; + payload = this.addSystemDataToObject(payload, true); + payload = JSON.stringify(payload); - pageLoadUrl = addToURL(pageLoadUrl, 'type', 'data'); - pageLoadUrl = addToURL(pageLoadUrl, 'd', compressData(payload, _classPrivateFieldLooseBase(this, _logger$6)[_logger$6])); - RequestDispatcher.fireRequest(pageLoadUrl); // set in localstorage + let pageLoadUrl = _classPrivateFieldLooseBase(this, _account$2)[_account$2].dataPostURL; - StorageManager.save(WEBPUSH_LS_KEY, 'ok'); - } - }, { - key: "processEvent", - value: function processEvent(data) { - _classPrivateFieldLooseBase(this, _addToLocalEventMap)[_addToLocalEventMap](data.evtName); + pageLoadUrl = addToURL(pageLoadUrl, 'type', 'data'); + pageLoadUrl = addToURL(pageLoadUrl, 'd', compressData(payload, _classPrivateFieldLooseBase(this, _logger$6)[_logger$6])); + RequestDispatcher.fireRequest(pageLoadUrl); // set in localstorage + + StorageManager.save(WEBPUSH_LS_KEY, 'ok'); + } - data = this.addSystemDataToObject(data, undefined); - this.addFlags(data); - data[CAMP_COOKIE_NAME] = getCampaignObjForLc(); - var compressedData = compressData(JSON.stringify(data), _classPrivateFieldLooseBase(this, _logger$6)[_logger$6]); + processEvent(data) { + _classPrivateFieldLooseBase(this, _addToLocalEventMap)[_addToLocalEventMap](data.evtName); - var pageLoadUrl = _classPrivateFieldLooseBase(this, _account$2)[_account$2].dataPostURL; + data = this.addSystemDataToObject(data, undefined); + this.addFlags(data); + data[CAMP_COOKIE_NAME] = getCampaignObjForLc(); + const compressedData = compressData(JSON.stringify(data), _classPrivateFieldLooseBase(this, _logger$6)[_logger$6]); - pageLoadUrl = addToURL(pageLoadUrl, 'type', EVT_PUSH); - pageLoadUrl = addToURL(pageLoadUrl, 'd', compressedData); - this.saveAndFireRequest(pageLoadUrl, $ct.blockRequest, false, data.evtName); - } - }, { - key: "post", - value: function post(url, body) { - var _this = this; - - return fetch(url, { - method: 'post', - headers: { - 'Content-Type': 'application/json' - }, - body: body - }).then(function (response) { - if (response.ok) { - return response.json(); - } + let pageLoadUrl = _classPrivateFieldLooseBase(this, _account$2)[_account$2].dataPostURL; - throw response; - }).then(function (data) { - _classPrivateFieldLooseBase(_this, _logger$6)[_logger$6].debug('Sync data successful', data); + pageLoadUrl = addToURL(pageLoadUrl, 'type', EVT_PUSH); + pageLoadUrl = addToURL(pageLoadUrl, 'd', compressedData); + this.saveAndFireRequest(pageLoadUrl, $ct.blockRequest, false, data.evtName); + } - return data; - }).catch(function (e) { - _classPrivateFieldLooseBase(_this, _logger$6)[_logger$6].debug('Error in syncing variables', e); + post(url, body) { + return fetch(url, { + method: 'post', + headers: { + 'Content-Type': 'application/json' + }, + body: body + }).then(response => { + if (response.ok) { + return response.json(); + } - throw e; - }); - } - }]); + throw response; + }).then(data => { + _classPrivateFieldLooseBase(this, _logger$6)[_logger$6].debug('Sync data successful', data); + + return data; + }).catch(e => { + _classPrivateFieldLooseBase(this, _logger$6)[_logger$6].debug('Error in syncing variables', e); + + throw e; + }); + } - return RequestManager; - }(); + } var _addToLocalEventMap2 = function _addToLocalEventMap2(evtName) { if (StorageManager._isLocalStorageSupported()) { @@ -6732,8 +6393,8 @@ } } - var nowTs = getNow(); - var evtDetail = $ct.globalEventsMap[evtName]; + const nowTs = getNow(); + let evtDetail = $ct.globalEventsMap[evtName]; if (typeof evtDetail !== 'undefined') { evtDetail[2] = nowTs; @@ -6760,85 +6421,70 @@ var _processPrivacyArray = _classPrivateFieldLooseKey("processPrivacyArray"); - var Privacy = /*#__PURE__*/function (_Array) { - _inherits(Privacy, _Array); - - var _super = _createSuper(Privacy); - - function Privacy(_ref, values) { - var _this; - - var request = _ref.request, - account = _ref.account, - logger = _ref.logger; - - _classCallCheck(this, Privacy); - - _this = _super.call(this); - Object.defineProperty(_assertThisInitialized(_this), _processPrivacyArray, { + class Privacy extends Array { + constructor(_ref, values) { + let { + request, + account, + logger + } = _ref; + super(); + Object.defineProperty(this, _processPrivacyArray, { value: _processPrivacyArray2 }); - Object.defineProperty(_assertThisInitialized(_this), _request$4, { + Object.defineProperty(this, _request$4, { writable: true, value: void 0 }); - Object.defineProperty(_assertThisInitialized(_this), _account$3, { + Object.defineProperty(this, _account$3, { writable: true, value: void 0 }); - Object.defineProperty(_assertThisInitialized(_this), _oldValues$3, { + Object.defineProperty(this, _oldValues$3, { writable: true, value: void 0 }); - Object.defineProperty(_assertThisInitialized(_this), _logger$7, { + Object.defineProperty(this, _logger$7, { writable: true, value: void 0 }); - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _logger$7)[_logger$7] = logger; - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _request$4)[_request$4] = request; - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _account$3)[_account$3] = account; - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _oldValues$3)[_oldValues$3] = values; - return _this; + _classPrivateFieldLooseBase(this, _logger$7)[_logger$7] = logger; + _classPrivateFieldLooseBase(this, _request$4)[_request$4] = request; + _classPrivateFieldLooseBase(this, _account$3)[_account$3] = account; + _classPrivateFieldLooseBase(this, _oldValues$3)[_oldValues$3] = values; } - _createClass(Privacy, [{ - key: "push", - value: function push() { - for (var _len = arguments.length, privacyArr = new Array(_len), _key = 0; _key < _len; _key++) { - privacyArr[_key] = arguments[_key]; - } + push() { + for (var _len = arguments.length, privacyArr = new Array(_len), _key = 0; _key < _len; _key++) { + privacyArr[_key] = arguments[_key]; + } - if ($ct.isPrivacyArrPushed) { - _classPrivateFieldLooseBase(this, _processPrivacyArray)[_processPrivacyArray]($ct.privacyArray.length > 0 ? $ct.privacyArray : privacyArr); - } else { - var _$ct$privacyArray; + if ($ct.isPrivacyArrPushed) { + _classPrivateFieldLooseBase(this, _processPrivacyArray)[_processPrivacyArray]($ct.privacyArray.length > 0 ? $ct.privacyArray : privacyArr); + } else { + $ct.privacyArray.push(...privacyArr); + } - (_$ct$privacyArray = $ct.privacyArray).push.apply(_$ct$privacyArray, privacyArr); - } + return 0; + } - return 0; + _processOldValues() { + if (_classPrivateFieldLooseBase(this, _oldValues$3)[_oldValues$3]) { + _classPrivateFieldLooseBase(this, _processPrivacyArray)[_processPrivacyArray](_classPrivateFieldLooseBase(this, _oldValues$3)[_oldValues$3]); } - }, { - key: "_processOldValues", - value: function _processOldValues() { - if (_classPrivateFieldLooseBase(this, _oldValues$3)[_oldValues$3]) { - _classPrivateFieldLooseBase(this, _processPrivacyArray)[_processPrivacyArray](_classPrivateFieldLooseBase(this, _oldValues$3)[_oldValues$3]); - } - _classPrivateFieldLooseBase(this, _oldValues$3)[_oldValues$3] = null; - } - }]); + _classPrivateFieldLooseBase(this, _oldValues$3)[_oldValues$3] = null; + } - return Privacy; - }( /*#__PURE__*/_wrapNativeSuper(Array)); + } var _processPrivacyArray2 = function _processPrivacyArray2(privacyArr) { if (Array.isArray(privacyArr) && privacyArr.length > 0) { - var privacyObj = privacyArr.reduce(function (prev, curr) { - return _objectSpread2(_objectSpread2({}, prev), curr); - }, {}); - var data = {}; - var profileObj = {}; + const privacyObj = privacyArr.reduce((prev, curr) => ({ ...prev, + ...curr + }), {}); + let data = {}; + const profileObj = {}; var optOut = false; if (privacyObj.hasOwnProperty(OPTOUT_KEY)) { @@ -6852,8 +6498,8 @@ } if (privacyObj.hasOwnProperty(USEIP_KEY)) { - var useIP = privacyObj[USEIP_KEY]; - var shouldUseIP = typeof useIP === 'boolean' ? useIP : false; + const useIP = privacyObj[USEIP_KEY]; + const shouldUseIP = typeof useIP === 'boolean' ? useIP : false; StorageManager.setMetaProp(USEIP_KEY, shouldUseIP); } @@ -6861,9 +6507,9 @@ data.type = 'profile'; data.profile = profileObj; data = _classPrivateFieldLooseBase(this, _request$4)[_request$4].addSystemDataToObject(data, undefined); - var compressedData = compressData(JSON.stringify(data), _classPrivateFieldLooseBase(this, _logger$7)[_logger$7]); + const compressedData = compressData(JSON.stringify(data), _classPrivateFieldLooseBase(this, _logger$7)[_logger$7]); - var pageLoadUrl = _classPrivateFieldLooseBase(this, _account$3)[_account$3].dataPostURL; + let pageLoadUrl = _classPrivateFieldLooseBase(this, _account$3)[_account$3].dataPostURL; pageLoadUrl = addToURL(pageLoadUrl, 'type', EVT_PUSH); pageLoadUrl = addToURL(pageLoadUrl, 'd', compressedData); @@ -6904,118 +6550,104 @@ var _handleNotificationRegistration = _classPrivateFieldLooseKey("handleNotificationRegistration"); - var NotificationHandler = /*#__PURE__*/function (_Array) { - _inherits(NotificationHandler, _Array); - - var _super = _createSuper(NotificationHandler); - - function NotificationHandler(_ref, values) { - var _this; - - var logger = _ref.logger, - session = _ref.session, - request = _ref.request, - account = _ref.account; - - _classCallCheck(this, NotificationHandler); - - _this = _super.call(this); - Object.defineProperty(_assertThisInitialized(_this), _handleNotificationRegistration, { + class NotificationHandler extends Array { + constructor(_ref, values) { + let { + logger, + session, + request, + account + } = _ref; + super(); + Object.defineProperty(this, _handleNotificationRegistration, { value: _handleNotificationRegistration2 }); - Object.defineProperty(_assertThisInitialized(_this), _removeWizAlertJS, { + Object.defineProperty(this, _removeWizAlertJS, { value: _removeWizAlertJS2 }); - Object.defineProperty(_assertThisInitialized(_this), _addWizAlertJS, { + Object.defineProperty(this, _addWizAlertJS, { value: _addWizAlertJS2 }); - Object.defineProperty(_assertThisInitialized(_this), _setUpChromeFirefoxNotifications, { + Object.defineProperty(this, _setUpChromeFirefoxNotifications, { value: _setUpChromeFirefoxNotifications2 }); - Object.defineProperty(_assertThisInitialized(_this), _setUpSafariNotifications, { + Object.defineProperty(this, _setUpSafariNotifications, { value: _setUpSafariNotifications2 }); - Object.defineProperty(_assertThisInitialized(_this), _setApplicationServerKey, { + Object.defineProperty(this, _setApplicationServerKey, { value: _setApplicationServerKey2 }); - Object.defineProperty(_assertThisInitialized(_this), _setUpWebPushNotifications, { + Object.defineProperty(this, _setUpWebPushNotifications, { value: _setUpWebPushNotifications2 }); - Object.defineProperty(_assertThisInitialized(_this), _setUpWebPush, { + Object.defineProperty(this, _setUpWebPush, { value: _setUpWebPush2 }); - Object.defineProperty(_assertThisInitialized(_this), _oldValues$4, { + Object.defineProperty(this, _oldValues$4, { writable: true, value: void 0 }); - Object.defineProperty(_assertThisInitialized(_this), _logger$8, { + Object.defineProperty(this, _logger$8, { writable: true, value: void 0 }); - Object.defineProperty(_assertThisInitialized(_this), _request$5, { + Object.defineProperty(this, _request$5, { writable: true, value: void 0 }); - Object.defineProperty(_assertThisInitialized(_this), _account$4, { + Object.defineProperty(this, _account$4, { writable: true, value: void 0 }); - Object.defineProperty(_assertThisInitialized(_this), _wizAlertJSPath, { + Object.defineProperty(this, _wizAlertJSPath, { writable: true, value: void 0 }); - Object.defineProperty(_assertThisInitialized(_this), _fcmPublicKey, { + Object.defineProperty(this, _fcmPublicKey, { writable: true, value: void 0 }); - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _wizAlertJSPath)[_wizAlertJSPath] = 'https://d2r1yp2w7bby2u.cloudfront.net/js/wzrk_dialog.min.js'; - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _fcmPublicKey)[_fcmPublicKey] = null; - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _oldValues$4)[_oldValues$4] = values; - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _logger$8)[_logger$8] = logger; - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _request$5)[_request$5] = request; - _classPrivateFieldLooseBase(_assertThisInitialized(_this), _account$4)[_account$4] = account; - return _this; + _classPrivateFieldLooseBase(this, _wizAlertJSPath)[_wizAlertJSPath] = 'https://d2r1yp2w7bby2u.cloudfront.net/js/wzrk_dialog.min.js'; + _classPrivateFieldLooseBase(this, _fcmPublicKey)[_fcmPublicKey] = null; + _classPrivateFieldLooseBase(this, _oldValues$4)[_oldValues$4] = values; + _classPrivateFieldLooseBase(this, _logger$8)[_logger$8] = logger; + _classPrivateFieldLooseBase(this, _request$5)[_request$5] = request; + _classPrivateFieldLooseBase(this, _account$4)[_account$4] = account; } - _createClass(NotificationHandler, [{ - key: "push", - value: function push() { - for (var _len = arguments.length, displayArgs = new Array(_len), _key = 0; _key < _len; _key++) { - displayArgs[_key] = arguments[_key]; - } + push() { + for (var _len = arguments.length, displayArgs = new Array(_len), _key = 0; _key < _len; _key++) { + displayArgs[_key] = arguments[_key]; + } - _classPrivateFieldLooseBase(this, _setUpWebPush)[_setUpWebPush](displayArgs); + _classPrivateFieldLooseBase(this, _setUpWebPush)[_setUpWebPush](displayArgs); - return 0; - } - }, { - key: "_processOldValues", - value: function _processOldValues() { - if (_classPrivateFieldLooseBase(this, _oldValues$4)[_oldValues$4]) { - _classPrivateFieldLooseBase(this, _setUpWebPush)[_setUpWebPush](_classPrivateFieldLooseBase(this, _oldValues$4)[_oldValues$4]); - } + return 0; + } - _classPrivateFieldLooseBase(this, _oldValues$4)[_oldValues$4] = null; + _processOldValues() { + if (_classPrivateFieldLooseBase(this, _oldValues$4)[_oldValues$4]) { + _classPrivateFieldLooseBase(this, _setUpWebPush)[_setUpWebPush](_classPrivateFieldLooseBase(this, _oldValues$4)[_oldValues$4]); } - }, { - key: "_enableWebPush", - value: function _enableWebPush(enabled, applicationServerKey) { - $ct.webPushEnabled = enabled; - if (applicationServerKey != null) { - _classPrivateFieldLooseBase(this, _setApplicationServerKey)[_setApplicationServerKey](applicationServerKey); - } + _classPrivateFieldLooseBase(this, _oldValues$4)[_oldValues$4] = null; + } - if ($ct.webPushEnabled && $ct.notifApi.notifEnabledFromApi) { - _classPrivateFieldLooseBase(this, _handleNotificationRegistration)[_handleNotificationRegistration]($ct.notifApi.displayArgs); - } else if (!$ct.webPushEnabled && $ct.notifApi.notifEnabledFromApi) { - _classPrivateFieldLooseBase(this, _logger$8)[_logger$8].error('Ensure that web push notifications are fully enabled and integrated before requesting them'); - } + _enableWebPush(enabled, applicationServerKey) { + $ct.webPushEnabled = enabled; + + if (applicationServerKey != null) { + _classPrivateFieldLooseBase(this, _setApplicationServerKey)[_setApplicationServerKey](applicationServerKey); + } + + if ($ct.webPushEnabled && $ct.notifApi.notifEnabledFromApi) { + _classPrivateFieldLooseBase(this, _handleNotificationRegistration)[_handleNotificationRegistration]($ct.notifApi.displayArgs); + } else if (!$ct.webPushEnabled && $ct.notifApi.notifEnabledFromApi) { + _classPrivateFieldLooseBase(this, _logger$8)[_logger$8].error('Ensure that web push notifications are fully enabled and integrated before requesting them'); } - }]); + } - return NotificationHandler; - }( /*#__PURE__*/_wrapNativeSuper(Array)); + } var _setUpWebPush2 = function _setUpWebPush2(displayArgs) { if ($ct.webPushEnabled && displayArgs.length > 0) { @@ -7041,8 +6673,6 @@ }; var _setUpSafariNotifications2 = function _setUpSafariNotifications2(subscriptionCallback, apnsWebPushId, apnsServiceUrl) { - var _this2 = this; - // ensure that proper arguments are passed if (typeof apnsWebPushId === 'undefined') { _classPrivateFieldLooseBase(this, _logger$8)[_logger$8].error('Ensure that APNS Web Push ID is supplied'); @@ -7053,82 +6683,70 @@ } if ('safari' in window && 'pushNotification' in window.safari) { - window.safari.pushNotification.requestPermission(apnsServiceUrl, apnsWebPushId, {}, function (subscription) { + window.safari.pushNotification.requestPermission(apnsServiceUrl, apnsWebPushId, {}, subscription => { if (subscription.permission === 'granted') { - var subscriptionData = JSON.parse(JSON.stringify(subscription)); + const subscriptionData = JSON.parse(JSON.stringify(subscription)); subscriptionData.endpoint = subscription.deviceToken; subscriptionData.browser = 'Safari'; StorageManager.saveToLSorCookie(PUSH_SUBSCRIPTION_DATA, subscriptionData); - _classPrivateFieldLooseBase(_this2, _request$5)[_request$5].registerToken(subscriptionData); + _classPrivateFieldLooseBase(this, _request$5)[_request$5].registerToken(subscriptionData); - _classPrivateFieldLooseBase(_this2, _logger$8)[_logger$8].info('Safari Web Push registered. Device Token: ' + subscription.deviceToken); + _classPrivateFieldLooseBase(this, _logger$8)[_logger$8].info('Safari Web Push registered. Device Token: ' + subscription.deviceToken); } else if (subscription.permission === 'denied') { - _classPrivateFieldLooseBase(_this2, _logger$8)[_logger$8].info('Error subscribing to Safari web push'); + _classPrivateFieldLooseBase(this, _logger$8)[_logger$8].info('Error subscribing to Safari web push'); } }); } }; var _setUpChromeFirefoxNotifications2 = function _setUpChromeFirefoxNotifications2(subscriptionCallback, serviceWorkerPath) { - var _this3 = this; - - var registrationScope = ''; + let registrationScope = ''; if ('serviceWorker' in navigator) { - navigator.serviceWorker.register(serviceWorkerPath).then(function (registration) { + navigator.serviceWorker.register(serviceWorkerPath).then(registration => { if (typeof __wzrk_account_id !== 'undefined') { // eslint-disable-line // shopify accounts , since the service worker is not at root, serviceWorker.ready is never resolved. // hence add a timeout and hope serviceWroker is ready within that time. - return new Promise(function (resolve) { - return setTimeout(function () { - return resolve(registration); - }, 5000); - }); + return new Promise(resolve => setTimeout(() => resolve(registration), 5000)); } registrationScope = registration.scope; // IF SERVICE WORKER IS AT ROOT, RETURN THE READY PROMISE // ELSE IF CHROME RETURN PROMISE AFTER 5 SECONDS // OR getRegistrations PROMISE IF ITS FIREFOX - var rootDirRegex = /^(\.?)(\/?)([^/]*).js$/; - var isServiceWorkerAtRoot = rootDirRegex.test(serviceWorkerPath); + const rootDirRegex = /^(\.?)(\/?)([^/]*).js$/; + const isServiceWorkerAtRoot = rootDirRegex.test(serviceWorkerPath); if (isServiceWorkerAtRoot) { return navigator.serviceWorker.ready; } else { if (navigator.userAgent.indexOf('Chrome') !== -1) { - return new Promise(function (resolve) { - return setTimeout(function () { - return resolve(registration); - }, 5000); - }); + return new Promise(resolve => setTimeout(() => resolve(registration), 5000)); } else { return navigator.serviceWorker.getRegistrations(); } } - }).then(function (serviceWorkerRegistration) { + }).then(serviceWorkerRegistration => { // ITS AN ARRAY IN CASE OF FIREFOX, SO USE THE REGISTRATION WITH PROPER SCOPE if (navigator.userAgent.indexOf('Firefox') !== -1 && Array.isArray(serviceWorkerRegistration)) { - serviceWorkerRegistration = serviceWorkerRegistration.filter(function (i) { - return i.scope === registrationScope; - })[0]; + serviceWorkerRegistration = serviceWorkerRegistration.filter(i => i.scope === registrationScope)[0]; } - var subscribeObj = { + const subscribeObj = { userVisibleOnly: true }; - if (_classPrivateFieldLooseBase(_this3, _fcmPublicKey)[_fcmPublicKey] != null) { - subscribeObj.applicationServerKey = urlBase64ToUint8Array(_classPrivateFieldLooseBase(_this3, _fcmPublicKey)[_fcmPublicKey]); + if (_classPrivateFieldLooseBase(this, _fcmPublicKey)[_fcmPublicKey] != null) { + subscribeObj.applicationServerKey = urlBase64ToUint8Array(_classPrivateFieldLooseBase(this, _fcmPublicKey)[_fcmPublicKey]); } - serviceWorkerRegistration.pushManager.subscribe(subscribeObj).then(function (subscription) { - _classPrivateFieldLooseBase(_this3, _logger$8)[_logger$8].info('Service Worker registered. Endpoint: ' + subscription.endpoint); // convert the subscription keys to strings; this sets it up nicely for pushing to LC + serviceWorkerRegistration.pushManager.subscribe(subscribeObj).then(subscription => { + _classPrivateFieldLooseBase(this, _logger$8)[_logger$8].info('Service Worker registered. Endpoint: ' + subscription.endpoint); // convert the subscription keys to strings; this sets it up nicely for pushing to LC - var subscriptionData = JSON.parse(JSON.stringify(subscription)); // remove the common chrome/firefox endpoint at the beginning of the token + const subscriptionData = JSON.parse(JSON.stringify(subscription)); // remove the common chrome/firefox endpoint at the beginning of the token if (navigator.userAgent.indexOf('Chrome') !== -1) { subscriptionData.endpoint = subscriptionData.endpoint.split('/').pop(); @@ -7140,35 +6758,35 @@ StorageManager.saveToLSorCookie(PUSH_SUBSCRIPTION_DATA, subscriptionData); - _classPrivateFieldLooseBase(_this3, _request$5)[_request$5].registerToken(subscriptionData); + _classPrivateFieldLooseBase(this, _request$5)[_request$5].registerToken(subscriptionData); if (typeof subscriptionCallback !== 'undefined' && typeof subscriptionCallback === 'function') { subscriptionCallback(); } - }).catch(function (error) { - _classPrivateFieldLooseBase(_this3, _logger$8)[_logger$8].error('Error subscribing: ' + error); // unsubscribe from webpush if error + }).catch(error => { + _classPrivateFieldLooseBase(this, _logger$8)[_logger$8].error('Error subscribing: ' + error); // unsubscribe from webpush if error - serviceWorkerRegistration.pushManager.getSubscription().then(function (subscription) { + serviceWorkerRegistration.pushManager.getSubscription().then(subscription => { if (subscription !== null) { - subscription.unsubscribe().then(function (successful) { + subscription.unsubscribe().then(successful => { // You've successfully unsubscribed - _classPrivateFieldLooseBase(_this3, _logger$8)[_logger$8].info('Unsubscription successful'); - }).catch(function (e) { + _classPrivateFieldLooseBase(this, _logger$8)[_logger$8].info('Unsubscription successful'); + }).catch(e => { // Unsubscription failed - _classPrivateFieldLooseBase(_this3, _logger$8)[_logger$8].error('Error unsubscribing: ' + e); + _classPrivateFieldLooseBase(this, _logger$8)[_logger$8].error('Error unsubscribing: ' + e); }); } }); }); - }).catch(function (err) { - _classPrivateFieldLooseBase(_this3, _logger$8)[_logger$8].error('error registering service worker: ' + err); + }).catch(err => { + _classPrivateFieldLooseBase(this, _logger$8)[_logger$8].error('error registering service worker: ' + err); }); } }; var _addWizAlertJS2 = function _addWizAlertJS2() { - var scriptTag = document.createElement('script'); + const scriptTag = document.createElement('script'); scriptTag.setAttribute('type', 'text/javascript'); scriptTag.setAttribute('id', 'wzrk-alert-js'); scriptTag.setAttribute('src', _classPrivateFieldLooseBase(this, _wizAlertJSPath)[_wizAlertJSPath]); // add the script tag to the end of the body @@ -7178,33 +6796,31 @@ }; var _removeWizAlertJS2 = function _removeWizAlertJS2() { - var scriptTag = document.getElementById('wzrk-alert-js'); + const scriptTag = document.getElementById('wzrk-alert-js'); scriptTag.parentNode.removeChild(scriptTag); }; var _handleNotificationRegistration2 = function _handleNotificationRegistration2(displayArgs) { - var _this4 = this; - // make sure everything is specified - var titleText; - var bodyText; - var okButtonText; - var rejectButtonText; - var okButtonColor; - var skipDialog; - var askAgainTimeInSeconds; - var okCallback; - var rejectCallback; - var subscriptionCallback; - var serviceWorkerPath; - var httpsPopupPath; - var httpsIframePath; - var apnsWebPushId; - var apnsWebPushServiceUrl; + let titleText; + let bodyText; + let okButtonText; + let rejectButtonText; + let okButtonColor; + let skipDialog; + let askAgainTimeInSeconds; + let okCallback; + let rejectCallback; + let subscriptionCallback; + let serviceWorkerPath; + let httpsPopupPath; + let httpsIframePath; + let apnsWebPushId; + let apnsWebPushServiceUrl; if (displayArgs.length === 1) { if (isObject(displayArgs[0])) { - var notifObj = displayArgs[0]; + const notifObj = displayArgs[0]; titleText = notifObj.titleText; bodyText = notifObj.bodyText; okButtonText = notifObj.okButtonText; @@ -7244,7 +6860,7 @@ return; } - var isHTTP = httpsPopupPath != null && httpsIframePath != null; // make sure the site is on https for chrome notifications + const isHTTP = httpsPopupPath != null && httpsIframePath != null; // make sure the site is on https for chrome notifications if (window.location.protocol !== 'https:' && document.location.hostname !== 'localhost' && !isHTTP) { _classPrivateFieldLooseBase(this, _logger$8)[_logger$8].error('Make sure you are https or localhost to register for notifications'); @@ -7254,19 +6870,19 @@ if (navigator.userAgent.indexOf('Chrome') !== -1) { - var chromeAgent = navigator.userAgent.match(/Chrome\/(\d+)/); + const chromeAgent = navigator.userAgent.match(/Chrome\/(\d+)/); if (chromeAgent == null || parseInt(chromeAgent[1], 10) < 50) { return; } } else if (navigator.userAgent.indexOf('Firefox') !== -1) { - var firefoxAgent = navigator.userAgent.match(/Firefox\/(\d+)/); + const firefoxAgent = navigator.userAgent.match(/Firefox\/(\d+)/); if (firefoxAgent == null || parseInt(firefoxAgent[1], 10) < 50) { return; } } else if (navigator.userAgent.indexOf('Safari') !== -1) { - var safariAgent = navigator.userAgent.match(/Safari\/(\d+)/); + const safariAgent = navigator.userAgent.match(/Safari\/(\d+)/); if (safariAgent == null || parseInt(safariAgent[1], 10) < 50) { return; @@ -7312,7 +6928,7 @@ } // make sure the user isn't asked for notifications more than askAgainTimeInSeconds - var now = new Date().getTime() / 1000; + const now = new Date().getTime() / 1000; if (StorageManager.getMetaProp('notif_last_time') == null) { StorageManager.setMetaProp('notif_last_time', now); @@ -7332,13 +6948,13 @@ if (isHTTP) { // add the https iframe - var httpsIframe = document.createElement('iframe'); + const httpsIframe = document.createElement('iframe'); httpsIframe.setAttribute('style', 'display:none;'); httpsIframe.setAttribute('src', httpsIframePath); document.body.appendChild(httpsIframe); - window.addEventListener('message', function (event) { + window.addEventListener('message', event => { if (event.data != null) { - var obj = {}; + let obj = {}; try { obj = JSON.parse(event.data); @@ -7349,7 +6965,7 @@ if (obj.state != null) { if (obj.from === 'ct' && obj.state === 'not') { - _classPrivateFieldLooseBase(_this4, _addWizAlertJS)[_addWizAlertJS]().onload = function () { + _classPrivateFieldLooseBase(this, _addWizAlertJS)[_addWizAlertJS]().onload = () => { // create our wizrocket popup window.wzrkPermissionPopup.wizAlert({ title: titleText, @@ -7357,7 +6973,7 @@ confirmButtonText: okButtonText, confirmButtonColor: okButtonColor, rejectButtonText: rejectButtonText - }, function (enabled) { + }, enabled => { // callback function if (enabled) { // the user accepted on the dialog box @@ -7373,7 +6989,7 @@ } } - _classPrivateFieldLooseBase(_this4, _removeWizAlertJS)[_removeWizAlertJS](); + _classPrivateFieldLooseBase(this, _removeWizAlertJS)[_removeWizAlertJS](); }); }; } @@ -7381,7 +6997,7 @@ } }, false); } else { - _classPrivateFieldLooseBase(this, _addWizAlertJS)[_addWizAlertJS]().onload = function () { + _classPrivateFieldLooseBase(this, _addWizAlertJS)[_addWizAlertJS]().onload = () => { // create our wizrocket popup window.wzrkPermissionPopup.wizAlert({ title: titleText, @@ -7389,7 +7005,7 @@ confirmButtonText: okButtonText, confirmButtonColor: okButtonColor, rejectButtonText: rejectButtonText - }, function (enabled) { + }, enabled => { // callback function if (enabled) { // the user accepted on the dialog box @@ -7397,14 +7013,14 @@ okCallback(); } - _classPrivateFieldLooseBase(_this4, _setUpWebPushNotifications)[_setUpWebPushNotifications](subscriptionCallback, serviceWorkerPath, apnsWebPushId, apnsWebPushServiceUrl); + _classPrivateFieldLooseBase(this, _setUpWebPushNotifications)[_setUpWebPushNotifications](subscriptionCallback, serviceWorkerPath, apnsWebPushId, apnsWebPushServiceUrl); } else { if (typeof rejectCallback === 'function') { rejectCallback(); } } - _classPrivateFieldLooseBase(_this4, _removeWizAlertJS)[_removeWizAlertJS](); + _classPrivateFieldLooseBase(this, _removeWizAlertJS)[_removeWizAlertJS](); }); }; } @@ -7412,7 +7028,7 @@ var _variableStore = _classPrivateFieldLooseKey("variableStore"); - var Variable = /*#__PURE__*/function () { + class Variable { /** * Creates an instance of the Variable class. * @@ -7425,11 +7041,10 @@ * @param {boolean} options.hadStarted - A flag indicating whether the variable has started (used internally). * @param {Function[]} options.valueChangedCallbacks - Array to store callbacks to be executed when the variable value changes. */ - function Variable(_ref) { - var variableStore = _ref.variableStore; - - _classCallCheck(this, Variable); - + constructor(_ref) { + let { + variableStore + } = _ref; Object.defineProperty(this, _variableStore, { writable: true, value: void 0 @@ -7443,151 +7058,138 @@ _classPrivateFieldLooseBase(this, _variableStore)[_variableStore] = variableStore; } - _createClass(Variable, [{ - key: "getValue", - value: function getValue() { - return this.value; - } - }, { - key: "getdefaultValue", - value: function getdefaultValue() { - return this.defaultValue; + getValue() { + return this.value; + } + + getdefaultValue() { + return this.defaultValue; + } + /** + * Defines a new variable with the provided name, default value, and variable store. + * @static + * @param {string} name - The name of the variable. + * @param {*} defaultValue - The default value of the variable. + * @param {VariableStore} variableStore - The VariableStore instance for registration. + * @returns {Variable|null} - The created Variable instance or null if invalid parameters are provided. + */ + + + static define(name, defaultValue, variableStore) { + if (!name || typeof name !== 'string') { + console.error('Empty or invalid name parameter provided.'); + return null; } - /** - * Defines a new variable with the provided name, default value, and variable store. - * @static - * @param {string} name - The name of the variable. - * @param {*} defaultValue - The default value of the variable. - * @param {VariableStore} variableStore - The VariableStore instance for registration. - * @returns {Variable|null} - The created Variable instance or null if invalid parameters are provided. - */ - }, { - key: "update", + if (name.startsWith('.') || name.endsWith('.')) { + console.error('Variable name starts or ends with a `.` which is not allowed: ' + name); + return null; + } - /** - * Updates the variable's value, triggering callbacks if hasVarsRequestCompleted is returned true. - * @param {*} newValue - The new value to be assigned to the variable. - */ - value: function update(newValue) { - var oldValue = this.value; - this.value = newValue; + const typeOfDefaultValue = typeof defaultValue; - if (newValue === null && oldValue === null) { - return; - } + if (typeOfDefaultValue !== 'string' && typeOfDefaultValue !== 'number' && typeOfDefaultValue !== 'boolean') { + console.error('Only primitive types (string, number, boolean) are accepted as value'); + return null; + } - if (newValue !== null && newValue === oldValue && this.hadStarted) { - return; - } + const existing = variableStore.getVariable(name); - if (_classPrivateFieldLooseBase(this, _variableStore)[_variableStore].hasVarsRequestCompleted()) { - this.hadStarted = true; - this.triggerValueChanged(); - } + if (existing) { + return existing; } - /** - * Invokes all registered callbacks when the variable value changes. - */ - }, { - key: "triggerValueChanged", - value: function triggerValueChanged() { - var _this = this; + const varInstance = new Variable({ + variableStore + }); - this.valueChangedCallbacks.forEach(function (onValueChanged) { - onValueChanged(_this); - }); + try { + varInstance.name = name; + varInstance.defaultValue = defaultValue; + varInstance.value = defaultValue; + varInstance.type = typeOfDefaultValue; + variableStore.registerVariable(varInstance); + varInstance.update(defaultValue); + } catch (error) { + console.error(error); } - /** - * Adds a callback function to the array and triggers it immediately if variable requests have completed. - * @param {Function} onValueChanged - The callback function to be added. - */ - }, { - key: "addValueChangedCallback", - value: function addValueChangedCallback(onValueChanged) { - if (!onValueChanged) { - console.log('Invalid callback parameter provided.'); - return; - } + return varInstance; + } + /** + * Updates the variable's value, triggering callbacks if hasVarsRequestCompleted is returned true. + * @param {*} newValue - The new value to be assigned to the variable. + */ - this.valueChangedCallbacks.push(onValueChanged); - if (_classPrivateFieldLooseBase(this, _variableStore)[_variableStore].hasVarsRequestCompleted()) { - onValueChanged(this); - } + update(newValue) { + const oldValue = this.value; + this.value = newValue; + + if (newValue === null && oldValue === null) { + return; } - /** - * Removes a callback function from the array. - * @param {Function} onValueChanged - The callback function to be removed. - */ - }, { - key: "removeValueChangedCallback", - value: function removeValueChangedCallback(onValueChanged) { - var index = this.valueChangedCallbacks.indexOf(onValueChanged); + if (newValue !== null && newValue === oldValue && this.hadStarted) { + return; + } + + if (_classPrivateFieldLooseBase(this, _variableStore)[_variableStore].hasVarsRequestCompleted()) { + this.hadStarted = true; + this.triggerValueChanged(); + } + } + /** + * Invokes all registered callbacks when the variable value changes. + */ + + + triggerValueChanged() { + this.valueChangedCallbacks.forEach(onValueChanged => { + onValueChanged(this); + }); + } + /** + * Adds a callback function to the array and triggers it immediately if variable requests have completed. + * @param {Function} onValueChanged - The callback function to be added. + */ - if (index !== -1) { - this.valueChangedCallbacks.splice(index, 1); - } - } - /** - * Resets the `hadStarted` flag to false. - */ - }, { - key: "clearStartFlag", - value: function clearStartFlag() { - this.hadStarted = false; + addValueChangedCallback(onValueChanged) { + if (!onValueChanged) { + console.log('Invalid callback parameter provided.'); + return; } - }], [{ - key: "define", - value: function define(name, defaultValue, variableStore) { - if (!name || typeof name !== 'string') { - console.error('Empty or invalid name parameter provided.'); - return null; - } - - if (name.startsWith('.') || name.endsWith('.')) { - console.error('Variable name starts or ends with a `.` which is not allowed: ' + name); - return null; - } - var typeOfDefaultValue = _typeof(defaultValue); + this.valueChangedCallbacks.push(onValueChanged); - if (typeOfDefaultValue !== 'string' && typeOfDefaultValue !== 'number' && typeOfDefaultValue !== 'boolean') { - console.error('Only primitive types (string, number, boolean) are accepted as value'); - return null; - } + if (_classPrivateFieldLooseBase(this, _variableStore)[_variableStore].hasVarsRequestCompleted()) { + onValueChanged(this); + } + } + /** + * Removes a callback function from the array. + * @param {Function} onValueChanged - The callback function to be removed. + */ - var existing = variableStore.getVariable(name); - if (existing) { - return existing; - } + removeValueChangedCallback(onValueChanged) { + const index = this.valueChangedCallbacks.indexOf(onValueChanged); - var varInstance = new Variable({ - variableStore: variableStore - }); + if (index !== -1) { + this.valueChangedCallbacks.splice(index, 1); + } + } + /** + * Resets the `hadStarted` flag to false. + */ - try { - varInstance.name = name; - varInstance.defaultValue = defaultValue; - varInstance.value = defaultValue; - varInstance.type = typeOfDefaultValue; - variableStore.registerVariable(varInstance); - varInstance.update(defaultValue); - } catch (error) { - console.error(error); - } - return varInstance; - } - }]); + clearStartFlag() { + this.hadStarted = false; + } - return Variable; - }(); + } var _logger$9 = _classPrivateFieldLooseKey("logger"); @@ -7611,15 +7213,14 @@ var _runVariablesChangedCallback = _classPrivateFieldLooseKey("runVariablesChangedCallback"); - var VariableStore = /*#__PURE__*/function () { - function VariableStore(_ref) { - var logger = _ref.logger, - request = _ref.request, - account = _ref.account, - event = _ref.event; - - _classCallCheck(this, VariableStore); - + class VariableStore { + constructor(_ref) { + let { + logger, + request, + account, + event + } = _ref; Object.defineProperty(this, _runVariablesChangedCallback, { value: _runVariablesChangedCallback2 }); @@ -7679,211 +7280,178 @@ */ - _createClass(VariableStore, [{ - key: "registerVariable", - value: function registerVariable(varInstance) { - var name = varInstance.name; - _classPrivateFieldLooseBase(this, _variables)[_variables][name] = varInstance; - console.log('registerVariable', _classPrivateFieldLooseBase(this, _variables)[_variables]); - } - /** - * Retrieves a variable by its name. - * @param {string} name - The name of the variable to retrieve. - * @returns {Object} - The variable instance. - */ + registerVariable(varInstance) { + const { + name + } = varInstance; + _classPrivateFieldLooseBase(this, _variables)[_variables][name] = varInstance; + console.log('registerVariable', _classPrivateFieldLooseBase(this, _variables)[_variables]); + } + /** + * Retrieves a variable by its name. + * @param {string} name - The name of the variable to retrieve. + * @returns {Object} - The variable instance. + */ - }, { - key: "getVariable", - value: function getVariable(name) { - return _classPrivateFieldLooseBase(this, _variables)[_variables][name]; - } - }, { - key: "hasVarsRequestCompleted", - value: function hasVarsRequestCompleted() { - return _classPrivateFieldLooseBase(this, _hasVarsRequestCompleted)[_hasVarsRequestCompleted]; - } - /** - * Synchronizes variables with the server. - * @param {Function} onSyncSuccess - Callback function on successful synchronization. - * @param {Function} onSyncFailure - Callback function on synchronization failure. - * @throws Will throw an error if the account token is missing. - * @returns {Promise} - The result of the synchronization request. - */ - }, { - key: "syncVariables", - value: function syncVariables(onSyncSuccess, onSyncFailure) { - var _this = this; + getVariable(name) { + return _classPrivateFieldLooseBase(this, _variables)[_variables][name]; + } + + hasVarsRequestCompleted() { + return _classPrivateFieldLooseBase(this, _hasVarsRequestCompleted)[_hasVarsRequestCompleted]; + } + /** + * Synchronizes variables with the server. + * @param {Function} onSyncSuccess - Callback function on successful synchronization. + * @param {Function} onSyncFailure - Callback function on synchronization failure. + * @throws Will throw an error if the account token is missing. + * @returns {Promise} - The result of the synchronization request. + */ + - if (!_classPrivateFieldLooseBase(this, _account$5)[_account$5].token) { - var m = 'Account token is missing.'; + syncVariables(onSyncSuccess, onSyncFailure) { + if (!_classPrivateFieldLooseBase(this, _account$5)[_account$5].token) { + const m = 'Account token is missing.'; - _classPrivateFieldLooseBase(this, _logger$9)[_logger$9].error(m); + _classPrivateFieldLooseBase(this, _logger$9)[_logger$9].error(m); - return Promise.reject(new Error(m)); - } + return Promise.reject(new Error(m)); + } + + const payload = { + type: 'varsPayload', + vars: {} + }; - var payload = { - type: 'varsPayload', - vars: {} + for (const name in _classPrivateFieldLooseBase(this, _variables)[_variables]) { + payload.vars[name] = { + defaultValue: _classPrivateFieldLooseBase(this, _variables)[_variables][name].defaultValue, + type: _classPrivateFieldLooseBase(this, _variables)[_variables][name].type }; + } // Check if payload.vars is empty - for (var name in _classPrivateFieldLooseBase(this, _variables)[_variables]) { - payload.vars[name] = { - defaultValue: _classPrivateFieldLooseBase(this, _variables)[_variables][name].defaultValue, - type: _classPrivateFieldLooseBase(this, _variables)[_variables][name].type - }; - } // Check if payload.vars is empty + if (Object.keys(payload.vars).length === 0) { + const m = 'No variables are defined.'; - if (Object.keys(payload.vars).length === 0) { - var _m = 'No variables are defined.'; + _classPrivateFieldLooseBase(this, _logger$9)[_logger$9].error(m); - _classPrivateFieldLooseBase(this, _logger$9)[_logger$9].error(_m); + return Promise.reject(new Error(m)); + } + + let meta = {}; + meta = _classPrivateFieldLooseBase(this, _request$6)[_request$6].addSystemDataToObject(meta, undefined); + meta.tk = _classPrivateFieldLooseBase(this, _account$5)[_account$5].token; + meta.type = 'meta'; + const body = JSON.stringify([meta, payload]); - return Promise.reject(new Error(_m)); + const url = _classPrivateFieldLooseBase(this, _account$5)[_account$5].dataPostPEURL; + + return _classPrivateFieldLooseBase(this, _request$6)[_request$6].post(url, body).then(r => { + if (onSyncSuccess && typeof onSyncSuccess === 'function') { + onSyncSuccess(r); } - var meta = {}; - meta = _classPrivateFieldLooseBase(this, _request$6)[_request$6].addSystemDataToObject(meta, undefined); - meta.tk = _classPrivateFieldLooseBase(this, _account$5)[_account$5].token; - meta.type = 'meta'; - var body = JSON.stringify([meta, payload]); + return r; + }).catch(e => { + if (onSyncFailure && typeof onSyncFailure === 'function') { + onSyncFailure(e); + } - var url = _classPrivateFieldLooseBase(this, _account$5)[_account$5].dataPostPEURL; + if (e.status === 400) { + _classPrivateFieldLooseBase(this, _logger$9)[_logger$9].error('Invalid sync payload or clear the existing draft'); + } else if (e.status === 401) { + _classPrivateFieldLooseBase(this, _logger$9)[_logger$9].error('This is not a test profile'); + } else { + _classPrivateFieldLooseBase(this, _logger$9)[_logger$9].error('Sync variable failed'); + } - return _classPrivateFieldLooseBase(this, _request$6)[_request$6].post(url, body).then(function (r) { - if (onSyncSuccess && typeof onSyncSuccess === 'function') { - onSyncSuccess(r); - } + throw e; + }); + } + /** + * Fetches variables from the server. + * @param {Function} onFetchCallback - Callback function on fetch completion. + */ - return r; - }).catch(function (e) { - if (onSyncFailure && typeof onSyncFailure === 'function') { - onSyncFailure(e); - } - if (e.status === 400) { - _classPrivateFieldLooseBase(_this, _logger$9)[_logger$9].error('Invalid sync payload or clear the existing draft'); - } else if (e.status === 401) { - _classPrivateFieldLooseBase(_this, _logger$9)[_logger$9].error('This is not a test profile'); - } else { - _classPrivateFieldLooseBase(_this, _logger$9)[_logger$9].error('Sync variable failed'); - } + fetchVariables(onFetchCallback) { + _classPrivateFieldLooseBase(this, _event)[_event].push(WZRK_FETCH, { + t: 4 + }); - throw e; - }); + if (onFetchCallback && typeof onFetchCallback === 'function') { + _classPrivateFieldLooseBase(this, _fetchCallback)[_fetchCallback] = onFetchCallback; } - /** - * Fetches variables from the server. - * @param {Function} onFetchCallback - Callback function on fetch completion. - */ + } - }, { - key: "fetchVariables", - value: function fetchVariables(onFetchCallback) { - _classPrivateFieldLooseBase(this, _event)[_event].push(WZRK_FETCH, { - t: 4 - }); + mergeVariables(vars) { + console.log('msg vars is ', vars); + _classPrivateFieldLooseBase(this, _hasVarsRequestCompleted)[_hasVarsRequestCompleted] = true; + StorageManager.saveToLSorCookie(VARIABLES, vars); + _classPrivateFieldLooseBase(this, _remoteVariables)[_remoteVariables] = vars; - if (onFetchCallback && typeof onFetchCallback === 'function') { - _classPrivateFieldLooseBase(this, _fetchCallback)[_fetchCallback] = onFetchCallback; + for (const name in _classPrivateFieldLooseBase(this, _variables)[_variables]) { + if (vars.hasOwnProperty(name)) { + _classPrivateFieldLooseBase(this, _variables)[_variables][name].update(vars[name]); } } - }, { - key: "mergeVariables", - value: function mergeVariables(vars) { - console.log('msg vars is ', vars); - _classPrivateFieldLooseBase(this, _hasVarsRequestCompleted)[_hasVarsRequestCompleted] = true; - StorageManager.saveToLSorCookie(VARIABLES, vars); - _classPrivateFieldLooseBase(this, _remoteVariables)[_remoteVariables] = vars; - for (var name in _classPrivateFieldLooseBase(this, _variables)[_variables]) { - if (vars.hasOwnProperty(name)) { - _classPrivateFieldLooseBase(this, _variables)[_variables][name].update(vars[name]); - } - } + if (_classPrivateFieldLooseBase(this, _fetchCallback)[_fetchCallback]) { + _classPrivateFieldLooseBase(this, _fetchCallback)[_fetchCallback](); + } - if (_classPrivateFieldLooseBase(this, _fetchCallback)[_fetchCallback]) { - _classPrivateFieldLooseBase(this, _fetchCallback)[_fetchCallback](); - } + _classPrivateFieldLooseBase(this, _runVariablesChangedCallback)[_runVariablesChangedCallback](); + } - _classPrivateFieldLooseBase(this, _runVariablesChangedCallback)[_runVariablesChangedCallback](); - } - }, { - key: "addVariablesChangedCallback", - value: function addVariablesChangedCallback(callback) { - if (callback && typeof callback === 'function') { - _classPrivateFieldLooseBase(this, _variablesChangedCallbacks)[_variablesChangedCallbacks].push(callback); + addVariablesChangedCallback(callback) { + if (callback && typeof callback === 'function') { + _classPrivateFieldLooseBase(this, _variablesChangedCallbacks)[_variablesChangedCallbacks].push(callback); - if (this.hasVarsRequestCompleted()) { - callback(); - } - } else { - _classPrivateFieldLooseBase(this, _logger$9)[_logger$9].error('callback is not a function'); - } - } - }, { - key: "addOneTimeVariablesChangedCallback", - value: function addOneTimeVariablesChangedCallback(callback) { - if (callback && typeof callback === 'function') { - if (this.hasVarsRequestCompleted()) { - callback(); - } else { - _classPrivateFieldLooseBase(this, _oneTimeVariablesChangedCallbacks)[_oneTimeVariablesChangedCallbacks].push(callback); - } + if (this.hasVarsRequestCompleted()) { + callback(); } + } else { + _classPrivateFieldLooseBase(this, _logger$9)[_logger$9].error('callback is not a function'); } - }, { - key: "removeVariablesChangedCallback", - value: function removeVariablesChangedCallback(callback) { - var index = _classPrivateFieldLooseBase(this, _variablesChangedCallbacks)[_variablesChangedCallbacks].indexOf(callback); + } - if (index !== -1) { - _classPrivateFieldLooseBase(this, _variablesChangedCallbacks)[_variablesChangedCallbacks].splice(index, 1); + addOneTimeVariablesChangedCallback(callback) { + if (callback && typeof callback === 'function') { + if (this.hasVarsRequestCompleted()) { + callback(); + } else { + _classPrivateFieldLooseBase(this, _oneTimeVariablesChangedCallbacks)[_oneTimeVariablesChangedCallbacks].push(callback); } } - }, { - key: "removeOneTimeVariablesChangedCallback", - value: function removeOneTimeVariablesChangedCallback(callback) { - var index = _classPrivateFieldLooseBase(this, _oneTimeVariablesChangedCallbacks)[_oneTimeVariablesChangedCallbacks].indexOf(callback); + } - if (index !== -1) { - _classPrivateFieldLooseBase(this, _oneTimeVariablesChangedCallbacks)[_oneTimeVariablesChangedCallbacks].splice(index, 1); - } - } - }]); + removeVariablesChangedCallback(callback) { + const index = _classPrivateFieldLooseBase(this, _variablesChangedCallbacks)[_variablesChangedCallbacks].indexOf(callback); - return VariableStore; - }(); + if (index !== -1) { + _classPrivateFieldLooseBase(this, _variablesChangedCallbacks)[_variablesChangedCallbacks].splice(index, 1); + } + } - var _runVariablesChangedCallback2 = function _runVariablesChangedCallback2() { - var _iterator = _createForOfIteratorHelper(_classPrivateFieldLooseBase(this, _variablesChangedCallbacks)[_variablesChangedCallbacks]), - _step; + removeOneTimeVariablesChangedCallback(callback) { + const index = _classPrivateFieldLooseBase(this, _oneTimeVariablesChangedCallbacks)[_oneTimeVariablesChangedCallbacks].indexOf(callback); - try { - for (_iterator.s(); !(_step = _iterator.n()).done;) { - var callback = _step.value; - callback(); + if (index !== -1) { + _classPrivateFieldLooseBase(this, _oneTimeVariablesChangedCallbacks)[_oneTimeVariablesChangedCallbacks].splice(index, 1); } - } catch (err) { - _iterator.e(err); - } finally { - _iterator.f(); } - var _iterator2 = _createForOfIteratorHelper(_classPrivateFieldLooseBase(this, _oneTimeVariablesChangedCallbacks)[_oneTimeVariablesChangedCallbacks]), - _step2; + } - try { - for (_iterator2.s(); !(_step2 = _iterator2.n()).done;) { - var callBack = _step2.value; - callBack(); - } - } catch (err) { - _iterator2.e(err); - } finally { - _iterator2.f(); + var _runVariablesChangedCallback2 = function _runVariablesChangedCallback2() { + for (var callback of _classPrivateFieldLooseBase(this, _variablesChangedCallbacks)[_variablesChangedCallbacks]) { + callback(); + } + + for (var callBack of _classPrivateFieldLooseBase(this, _oneTimeVariablesChangedCallbacks)[_oneTimeVariablesChangedCallbacks]) { + callBack(); } _classPrivateFieldLooseBase(this, _oneTimeVariablesChangedCallbacks)[_oneTimeVariablesChangedCallbacks].length = 0; @@ -7925,50 +7493,45 @@ var _overrideDSyncFlag = _classPrivateFieldLooseKey("overrideDSyncFlag"); - var CleverTap = /*#__PURE__*/function () { - _createClass(CleverTap, [{ - key: "spa", - get: function get() { - return _classPrivateFieldLooseBase(this, _isSpa)[_isSpa]; - }, - set: function set(value) { - var isSpa = value === true; - - if (_classPrivateFieldLooseBase(this, _isSpa)[_isSpa] !== isSpa && _classPrivateFieldLooseBase(this, _onloadcalled)[_onloadcalled] === 1) { - // if clevertap.spa is changed after init has been called then update the click listeners - if (isSpa) { - document.addEventListener('click', _classPrivateFieldLooseBase(this, _boundCheckPageChanged)[_boundCheckPageChanged]); - } else { - document.removeEventListener('click', _classPrivateFieldLooseBase(this, _boundCheckPageChanged)[_boundCheckPageChanged]); - } - } + var _sendLocationData = _classPrivateFieldLooseKey("sendLocationData"); - _classPrivateFieldLooseBase(this, _isSpa)[_isSpa] = isSpa; - } - }, { - key: "dismissSpamControl", - get: function get() { - return _classPrivateFieldLooseBase(this, _dismissSpamControl)[_dismissSpamControl]; - }, - set: function set(value) { - var dismissSpamControl = value === true; - _classPrivateFieldLooseBase(this, _dismissSpamControl)[_dismissSpamControl] = dismissSpamControl; - $ct.dismissSpamControl = dismissSpamControl; + class CleverTap { + get spa() { + return _classPrivateFieldLooseBase(this, _isSpa)[_isSpa]; + } + + set spa(value) { + const isSpa = value === true; + + if (_classPrivateFieldLooseBase(this, _isSpa)[_isSpa] !== isSpa && _classPrivateFieldLooseBase(this, _onloadcalled)[_onloadcalled] === 1) { + // if clevertap.spa is changed after init has been called then update the click listeners + if (isSpa) { + document.addEventListener('click', _classPrivateFieldLooseBase(this, _boundCheckPageChanged)[_boundCheckPageChanged]); + } else { + document.removeEventListener('click', _classPrivateFieldLooseBase(this, _boundCheckPageChanged)[_boundCheckPageChanged]); + } } - }]); - function CleverTap() { - var _clevertap$account, - _clevertap$account2, - _clevertap$account3, - _clevertap$account4, - _this = this, - _clevertap$account5; + _classPrivateFieldLooseBase(this, _isSpa)[_isSpa] = isSpa; + } + + get dismissSpamControl() { + return _classPrivateFieldLooseBase(this, _dismissSpamControl)[_dismissSpamControl]; + } - var clevertap = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + set dismissSpamControl(value) { + const dismissSpamControl = value === true; + _classPrivateFieldLooseBase(this, _dismissSpamControl)[_dismissSpamControl] = dismissSpamControl; + $ct.dismissSpamControl = dismissSpamControl; + } - _classCallCheck(this, CleverTap); + constructor() { + var _clevertap$account, _clevertap$account2, _clevertap$account3, _clevertap$account4, _clevertap$account5; + let clevertap = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; + Object.defineProperty(this, _sendLocationData, { + value: _sendLocationData2 + }); Object.defineProperty(this, _overrideDSyncFlag, { value: _overrideDSyncFlag2 }); @@ -8041,7 +7604,7 @@ _classPrivateFieldLooseBase(this, _onloadcalled)[_onloadcalled] = 0; this._isPersonalisationActive = this._isPersonalisationActive.bind(this); - this.raiseNotificationClicked = function () {}; + this.raiseNotificationClicked = () => {}; _classPrivateFieldLooseBase(this, _logger$a)[_logger$a] = new Logger(logLevels.INFO); _classPrivateFieldLooseBase(this, _account$6)[_account$6] = new Account((_clevertap$account = clevertap.account) === null || _clevertap$account === void 0 ? void 0 : _clevertap$account[0], clevertap.region || ((_clevertap$account2 = clevertap.account) === null || _clevertap$account2 === void 0 ? void 0 : _clevertap$account2[1]), clevertap.targetDomain || ((_clevertap$account3 = clevertap.account) === null || _clevertap$account3 === void 0 ? void 0 : _clevertap$account3[2]), clevertap.token || ((_clevertap$account4 = clevertap.account) === null || _clevertap$account4 === void 0 ? void 0 : _clevertap$account4[3])); @@ -8049,6 +7612,7 @@ logger: _classPrivateFieldLooseBase(this, _logger$a)[_logger$a] }); _classPrivateFieldLooseBase(this, _dismissSpamControl)[_dismissSpamControl] = clevertap.dismissSpamControl || false; + this.shpfyProxyPath = clevertap.shpfyProxyPath || ''; _classPrivateFieldLooseBase(this, _session$3)[_session$3] = new SessionManager({ logger: _classPrivateFieldLooseBase(this, _logger$a)[_logger$a], isPersonalisationActive: this._isPersonalisationActive @@ -8107,54 +7671,56 @@ isPersonalisationActive: this._isPersonalisationActive }); this.session = { - getTimeElapsed: function getTimeElapsed() { - return _classPrivateFieldLooseBase(_this, _session$3)[_session$3].getTimeElapsed(); + getTimeElapsed: () => { + return _classPrivateFieldLooseBase(this, _session$3)[_session$3].getTimeElapsed(); }, - getPageCount: function getPageCount() { - return _classPrivateFieldLooseBase(_this, _session$3)[_session$3].getPageCount(); + getPageCount: () => { + return _classPrivateFieldLooseBase(this, _session$3)[_session$3].getPageCount(); } }; - this.logout = function () { - _classPrivateFieldLooseBase(_this, _logger$a)[_logger$a].debug('logout called'); + this.logout = () => { + _classPrivateFieldLooseBase(this, _logger$a)[_logger$a].debug('logout called'); StorageManager.setInstantDeleteFlagInK(); }; - this.clear = function () { - _this.onUserLogin.clear(); + this.clear = () => { + this.onUserLogin.clear(); }; - this.getCleverTapID = function () { - return _classPrivateFieldLooseBase(_this, _device$3)[_device$3].getGuid(); + this.getCleverTapID = () => { + return _classPrivateFieldLooseBase(this, _device$3)[_device$3].getGuid(); }; - this.getAccountID = function () { - return _classPrivateFieldLooseBase(_this, _account$6)[_account$6].id; + this.getAccountID = () => { + return _classPrivateFieldLooseBase(this, _account$6)[_account$6].id; }; - this.getSCDomain = function () { - return _classPrivateFieldLooseBase(_this, _account$6)[_account$6].finalTargetDomain; + this.getSCDomain = () => { + return _classPrivateFieldLooseBase(this, _account$6)[_account$6].finalTargetDomain; }; - this.setLibrary = function (libName, libVersion) { - $ct.flutterVersion = _defineProperty({}, libName, libVersion); + this.setLibrary = (libName, libVersion) => { + $ct.flutterVersion = { + [libName]: libVersion + }; }; // Set the Signed Call sdk version and fire request - this.setSCSDKVersion = function (ver) { - _classPrivateFieldLooseBase(_this, _account$6)[_account$6].scSDKVersion = ver; - var data = {}; + this.setSCSDKVersion = ver => { + _classPrivateFieldLooseBase(this, _account$6)[_account$6].scSDKVersion = ver; + const data = {}; data.af = { - scv: 'sc-sdk-v' + _classPrivateFieldLooseBase(_this, _account$6)[_account$6].scSDKVersion + scv: 'sc-sdk-v' + _classPrivateFieldLooseBase(this, _account$6)[_account$6].scSDKVersion }; - var pageLoadUrl = _classPrivateFieldLooseBase(_this, _account$6)[_account$6].dataPostURL; + let pageLoadUrl = _classPrivateFieldLooseBase(this, _account$6)[_account$6].dataPostURL; pageLoadUrl = addToURL(pageLoadUrl, 'type', 'page'); - pageLoadUrl = addToURL(pageLoadUrl, 'd', compressData(JSON.stringify(data), _classPrivateFieldLooseBase(_this, _logger$a)[_logger$a])); + pageLoadUrl = addToURL(pageLoadUrl, 'd', compressData(JSON.stringify(data), _classPrivateFieldLooseBase(this, _logger$a)[_logger$a])); - _classPrivateFieldLooseBase(_this, _request$7)[_request$7].saveAndFireRequest(pageLoadUrl, $ct.blockRequest); + _classPrivateFieldLooseBase(this, _request$7)[_request$7].saveAndFireRequest(pageLoadUrl, $ct.blockRequest); }; if (hasWebInboxSettingsInLS()) { @@ -8163,53 +7729,53 @@ } // Get Inbox Message Count - this.getInboxMessageCount = function () { - var msgCount = getInboxMessages(); + this.getInboxMessageCount = () => { + const msgCount = getInboxMessages(); return Object.keys(msgCount).length; }; // Get Inbox Unread Message Count - this.getInboxMessageUnreadCount = function () { + this.getInboxMessageUnreadCount = () => { if ($ct.inbox) { return $ct.inbox.unviewedCounter; } else { - _classPrivateFieldLooseBase(_this, _logger$a)[_logger$a].debug('No unread messages'); + _classPrivateFieldLooseBase(this, _logger$a)[_logger$a].debug('No unread messages'); } }; // Get All Inbox messages - this.getAllInboxMessages = function () { + this.getAllInboxMessages = () => { return getInboxMessages(); }; // Get only Unread messages - this.getUnreadInboxMessages = function () { + this.getUnreadInboxMessages = () => { if ($ct.inbox) { return $ct.inbox.unviewedMessages; } else { - _classPrivateFieldLooseBase(_this, _logger$a)[_logger$a].debug('No unread messages'); + _classPrivateFieldLooseBase(this, _logger$a)[_logger$a].debug('No unread messages'); } }; // Get message object belonging to the given message id only. Message id should be a String - this.getInboxMessageForId = function (messageId) { - var messages = getInboxMessages(); + this.getInboxMessageForId = messageId => { + const messages = getInboxMessages(); if ((messageId !== null || messageId !== '') && messages.hasOwnProperty(messageId)) { return messages[messageId]; } else { - _classPrivateFieldLooseBase(_this, _logger$a)[_logger$a].error('No message available for message Id ' + messageId); + _classPrivateFieldLooseBase(this, _logger$a)[_logger$a].error('No message available for message Id ' + messageId); } }; // Delete message from the Inbox. Message id should be a String // If the message to be deleted is unviewed then decrement the badge count, delete the message from unviewedMessages list // Then remove the message from local storage and update cookie - this.deleteInboxMessage = function (messageId) { - var messages = getInboxMessages(); + this.deleteInboxMessage = messageId => { + const messages = getInboxMessages(); if ((messageId !== null || messageId !== '') && messages.hasOwnProperty(messageId)) { - var el = document.querySelector('ct-web-inbox').shadowRoot.getElementById(messageId); + const el = document.querySelector('ct-web-inbox').shadowRoot.getElementById(messageId); if (messages[messageId].viewed === 0) { $ct.inbox.unviewedCounter--; @@ -8222,7 +7788,7 @@ delete messages[messageId]; saveInboxMessages(messages); } else { - _classPrivateFieldLooseBase(_this, _logger$a)[_logger$a].error('No message available for message Id ' + messageId); + _classPrivateFieldLooseBase(this, _logger$a)[_logger$a].error('No message available for message Id ' + messageId); } }; /* Mark Message as Read. Message id should be a String @@ -8231,12 +7797,12 @@ - renderNotificationViewed */ - this.markReadInboxMessage = function (messageId) { - var unreadMsg = $ct.inbox.unviewedMessages; - var messages = getInboxMessages(); + this.markReadInboxMessage = messageId => { + const unreadMsg = $ct.inbox.unviewedMessages; + const messages = getInboxMessages(); if ((messageId !== null || messageId !== '') && unreadMsg.hasOwnProperty(messageId)) { - var el = document.querySelector('ct-web-inbox').shadowRoot.getElementById(messageId); + const el = document.querySelector('ct-web-inbox').shadowRoot.getElementById(messageId); if (el !== null) { el.shadowRoot.getElementById('unreadMarker').style.display = 'none'; @@ -8258,16 +7824,16 @@ delete $ct.inbox.unviewedMessages[messageId]; saveInboxMessages(messages); } else { - _classPrivateFieldLooseBase(_this, _logger$a)[_logger$a].error('No message available for message Id ' + messageId); + _classPrivateFieldLooseBase(this, _logger$a)[_logger$a].error('No message available for message Id ' + messageId); } }; /* Mark Message as Read. messageIds should be a an array of string */ - this.markReadInboxMessagesForIds = function (messageIds) { + this.markReadInboxMessagesForIds = messageIds => { if (Array.isArray(messageIds)) { for (var id = 0; id < messageIds.length; id++) { - _this.markReadInboxMessage(messageIds[id]); + this.markReadInboxMessage(messageIds[id]); } } }; @@ -8277,14 +7843,14 @@ */ - this.markReadAllInboxMessage = function () { - var unreadMsg = $ct.inbox.unviewedMessages; - var messages = getInboxMessages(); + this.markReadAllInboxMessage = () => { + const unreadMsg = $ct.inbox.unviewedMessages; + const messages = getInboxMessages(); if (Object.keys(unreadMsg).length > 0) { - var msgIds = Object.keys(unreadMsg); - msgIds.forEach(function (key) { - var el = document.querySelector('ct-web-inbox').shadowRoot.getElementById(key); + const msgIds = Object.keys(unreadMsg); + msgIds.forEach(key => { + const el = document.querySelector('ct-web-inbox').shadowRoot.getElementById(key); if (el !== null) { el.shadowRoot.getElementById('unreadMarker').style.display = 'none'; @@ -8302,71 +7868,77 @@ $ct.inbox.unviewedCounter = 0; $ct.inbox.unviewedMessages = {}; } else { - _classPrivateFieldLooseBase(_this, _logger$a)[_logger$a].debug('All messages are already read'); + _classPrivateFieldLooseBase(this, _logger$a)[_logger$a].debug('All messages are already read'); } }; - this.toggleInbox = function (e) { + this.toggleInbox = e => { var _$ct$inbox; return (_$ct$inbox = $ct.inbox) === null || _$ct$inbox === void 0 ? void 0 : _$ct$inbox.toggleInbox(e); }; // method for notification viewed - this.renderNotificationViewed = function (detail) { + this.renderNotificationViewed = detail => { processNotificationEvent(NOTIFICATION_VIEWED, detail); }; // method for notification clicked - this.renderNotificationClicked = function (detail) { + this.renderNotificationClicked = detail => { processNotificationEvent(NOTIFICATION_CLICKED, detail); }; - var processNotificationEvent = function processNotificationEvent(eventName, eventDetail) { + const processNotificationEvent = (eventName, eventDetail) => { if (!eventDetail || !eventDetail.msgId) { return; } - var data = {}; + const data = {}; data.type = 'event'; data.evtName = eventName; - data.evtData = _defineProperty({}, WZRK_ID, eventDetail.msgId); + data.evtData = { + [WZRK_ID]: eventDetail.msgId + }; if (eventDetail.pivotId) { - data.evtData = _objectSpread2(_objectSpread2({}, data.evtData), {}, { + data.evtData = { ...data.evtData, wzrk_pivot: eventDetail.pivotId - }); + }; } if (eventDetail.wzrk_slideNo) { - data.evtData = _objectSpread2(_objectSpread2({}, data.evtData), {}, { + data.evtData = { ...data.evtData, wzrk_slideNo: eventDetail.wzrk_slideNo - }); + }; } // Adding kv pair to event data if (eventDetail.kv && eventDetail.kv !== null && eventDetail.kv !== undefined) { - for (var key in eventDetail.kv) { + for (const key in eventDetail.kv) { if (key.startsWith(WZRK_PREFIX)) { - data.evtData = _objectSpread2(_objectSpread2({}, data.evtData), {}, _defineProperty({}, key, eventDetail.kv[key])); + data.evtData = { ...data.evtData, + [key]: eventDetail.kv[key] + }; } } } // Adding msgCTkv to event data if (eventDetail.msgCTkv && eventDetail.msgCTkv !== null && eventDetail.msgCTkv !== undefined) { - for (var _key in eventDetail.msgCTkv) { - if (_key.startsWith(WZRK_PREFIX)) { - data.evtData = _objectSpread2(_objectSpread2({}, data.evtData), {}, _defineProperty({}, _key, eventDetail.msgCTkv[_key])); + for (const key in eventDetail.msgCTkv) { + if (key.startsWith(WZRK_PREFIX)) { + data.evtData = { ...data.evtData, + [key]: eventDetail.msgCTkv[key] + }; } } } - _classPrivateFieldLooseBase(_this, _request$7)[_request$7].processEvent(data); + _classPrivateFieldLooseBase(this, _request$7)[_request$7].processEvent(data); }; - this.setLogLevel = function (l) { - _classPrivateFieldLooseBase(_this, _logger$a)[_logger$a].logLevel = Number(l); + this.setLogLevel = l => { + _classPrivateFieldLooseBase(this, _logger$a)[_logger$a].logLevel = Number(l); if (l === 3) { sessionStorage.WZRK_D = ''; @@ -8380,60 +7952,60 @@ */ - this.handleIncrementValue = function (key, value) { - _this.profile._handleIncrementDecrementValue(key, value, COMMAND_INCREMENT); + this.handleIncrementValue = (key, value) => { + this.profile._handleIncrementDecrementValue(key, value, COMMAND_INCREMENT); }; - this.handleDecrementValue = function (key, value) { - _this.profile._handleIncrementDecrementValue(key, value, COMMAND_DECREMENT); + this.handleDecrementValue = (key, value) => { + this.profile._handleIncrementDecrementValue(key, value, COMMAND_DECREMENT); }; - this.setMultiValuesForKey = function (key, value) { + this.setMultiValuesForKey = (key, value) => { if (Array.isArray(value)) { - _this.profile._handleMultiValueSet(key, value, COMMAND_SET); + this.profile._handleMultiValueSet(key, value, COMMAND_SET); } else { console.error('setMultiValuesForKey should be called with a value of type array'); } }; - this.addMultiValueForKey = function (key, value) { + this.addMultiValueForKey = (key, value) => { if (typeof value === 'string' || typeof value === 'number') { - _this.profile._handleMultiValueAdd(key, value, COMMAND_ADD); + this.profile._handleMultiValueAdd(key, value, COMMAND_ADD); } else { console.error('addMultiValueForKey should be called with a value of type string or number.'); } }; - this.addMultiValuesForKey = function (key, value) { + this.addMultiValuesForKey = (key, value) => { if (Array.isArray(value)) { - _this.profile._handleMultiValueAdd(key, value, COMMAND_ADD); + this.profile._handleMultiValueAdd(key, value, COMMAND_ADD); } else { console.error('addMultiValuesForKey should be called with a value of type array.'); } }; - this.removeMultiValueForKey = function (key, value) { + this.removeMultiValueForKey = (key, value) => { if (typeof value === 'string' || typeof value === 'number') { - _this.profile._handleMultiValueRemove(key, value, COMMAND_REMOVE); + this.profile._handleMultiValueRemove(key, value, COMMAND_REMOVE); } else { console.error('removeMultiValueForKey should be called with a value of type string or number.'); } }; - this.removeMultiValuesForKey = function (key, value) { + this.removeMultiValuesForKey = (key, value) => { if (Array.isArray(value)) { - _this.profile._handleMultiValueRemove(key, value, COMMAND_REMOVE); + this.profile._handleMultiValueRemove(key, value, COMMAND_REMOVE); } else { console.error('removeMultiValuesForKey should be called with a value of type array.'); } }; - this.removeValueForKey = function (key) { - _this.profile._handleMultiValueDelete(key, COMMAND_DELETE); + this.removeValueForKey = key => { + this.profile._handleMultiValueDelete(key, COMMAND_DELETE); }; - var _handleEmailSubscription = function _handleEmailSubscription(subscription, reEncoded, fetchGroups) { - handleEmailSubscription(subscription, reEncoded, fetchGroups, _classPrivateFieldLooseBase(_this, _account$6)[_account$6], _classPrivateFieldLooseBase(_this, _logger$a)[_logger$a]); + const _handleEmailSubscription = (subscription, reEncoded, fetchGroups) => { + handleEmailSubscription(subscription, reEncoded, fetchGroups, _classPrivateFieldLooseBase(this, _account$6)[_account$6], _classPrivateFieldLooseBase(this, _logger$a)[_logger$a]); }; /** * @@ -8468,7 +8040,8 @@ Latitude: lat, Longitude: lng }; - this.sendLocationData({ + + _classPrivateFieldLooseBase(this, _sendLocationData)[_sendLocationData]({ Latitude: lat, Longitude: lng }); @@ -8488,7 +8061,8 @@ Latitude: lat, Longitude: lng }; - this.sendLocationData({ + + _classPrivateFieldLooseBase(this, _sendLocationData)[_sendLocationData]({ Latitude: lat, Longitude: lng }); @@ -8514,57 +8088,57 @@ } } - var api = _classPrivateFieldLooseBase(this, _api)[_api]; + const api = _classPrivateFieldLooseBase(this, _api)[_api]; api.logout = this.logout; api.clear = this.clear; - api.closeIframe = function (campaignId, divIdIgnored) { - closeIframe(campaignId, divIdIgnored, _classPrivateFieldLooseBase(_this, _session$3)[_session$3].sessionId); + api.closeIframe = (campaignId, divIdIgnored) => { + closeIframe(campaignId, divIdIgnored, _classPrivateFieldLooseBase(this, _session$3)[_session$3].sessionId); }; - api.enableWebPush = function (enabled, applicationServerKey) { - _this.notifications._enableWebPush(enabled, applicationServerKey); + api.enableWebPush = (enabled, applicationServerKey) => { + this.notifications._enableWebPush(enabled, applicationServerKey); }; - api.tr = function (msg) { + api.tr = msg => { _tr(msg, { - device: _classPrivateFieldLooseBase(_this, _device$3)[_device$3], - session: _classPrivateFieldLooseBase(_this, _session$3)[_session$3], - request: _classPrivateFieldLooseBase(_this, _request$7)[_request$7], - logger: _classPrivateFieldLooseBase(_this, _logger$a)[_logger$a] + device: _classPrivateFieldLooseBase(this, _device$3)[_device$3], + session: _classPrivateFieldLooseBase(this, _session$3)[_session$3], + request: _classPrivateFieldLooseBase(this, _request$7)[_request$7], + logger: _classPrivateFieldLooseBase(this, _logger$a)[_logger$a] }); }; - api.setEnum = function (enumVal) { - setEnum(enumVal, _classPrivateFieldLooseBase(_this, _logger$a)[_logger$a]); + api.setEnum = enumVal => { + setEnum(enumVal, _classPrivateFieldLooseBase(this, _logger$a)[_logger$a]); }; - api.is_onloadcalled = function () { - return _classPrivateFieldLooseBase(_this, _onloadcalled)[_onloadcalled] === 1; + api.is_onloadcalled = () => { + return _classPrivateFieldLooseBase(this, _onloadcalled)[_onloadcalled] === 1; }; - api.subEmail = function (reEncoded) { + api.subEmail = reEncoded => { _handleEmailSubscription('1', reEncoded); }; - api.getEmail = function (reEncoded, withGroups) { + api.getEmail = (reEncoded, withGroups) => { _handleEmailSubscription('-1', reEncoded, withGroups); }; - api.unSubEmail = function (reEncoded) { + api.unSubEmail = reEncoded => { _handleEmailSubscription('0', reEncoded); }; - api.unsubEmailGroups = function (reEncoded) { + api.unsubEmailGroups = reEncoded => { $ct.unsubGroups = []; - var elements = document.getElementsByClassName('ct-unsub-group-input-item'); + const elements = document.getElementsByClassName('ct-unsub-group-input-item'); - for (var i = 0; i < elements.length; i++) { - var element = elements[i]; + for (let i = 0; i < elements.length; i++) { + const element = elements[i]; if (element.name) { - var data = { + const data = { name: element.name, isUnsubscribed: element.checked }; @@ -8575,29 +8149,29 @@ _handleEmailSubscription(GROUP_SUBSCRIPTION_REQUEST_ID, reEncoded); }; - api.setSubscriptionGroups = function (value) { + api.setSubscriptionGroups = value => { $ct.unsubGroups = value; }; - api.getSubscriptionGroups = function () { + api.getSubscriptionGroups = () => { return $ct.unsubGroups; }; - api.changeSubscriptionGroups = function (reEncoded, updatedGroups) { + api.changeSubscriptionGroups = (reEncoded, updatedGroups) => { api.setSubscriptionGroups(updatedGroups); _handleEmailSubscription(GROUP_SUBSCRIPTION_REQUEST_ID, reEncoded); }; - api.isGlobalUnsubscribe = function () { + api.isGlobalUnsubscribe = () => { return $ct.globalUnsubscribe; }; - api.setIsGlobalUnsubscribe = function (value) { + api.setIsGlobalUnsubscribe = value => { $ct.globalUnsubscribe = value; }; - api.setUpdatedCategoryLong = function (profile) { + api.setUpdatedCategoryLong = profile => { if (profile[categoryLongKey]) { $ct.updatedCategoryLong = profile[categoryLongKey]; } @@ -8614,288 +8188,237 @@ } // starts here - _createClass(CleverTap, [{ - key: "init", - value: function init(accountId, region, targetDomain, token) { - var _this2 = this; - - if (_classPrivateFieldLooseBase(this, _onloadcalled)[_onloadcalled] === 1) { - // already initailsed - return; - } - - StorageManager.removeCookie('WZRK_P', window.location.hostname); + init(accountId, region, targetDomain, token) { + if (_classPrivateFieldLooseBase(this, _onloadcalled)[_onloadcalled] === 1) { + // already initailsed + return; + } - if (!_classPrivateFieldLooseBase(this, _account$6)[_account$6].id) { - if (!accountId) { - _classPrivateFieldLooseBase(this, _logger$a)[_logger$a].error(EMBED_ERROR); + checkBuilder(_classPrivateFieldLooseBase(this, _logger$a)[_logger$a]); + StorageManager.removeCookie('WZRK_P', window.location.hostname); - return; - } + if (!_classPrivateFieldLooseBase(this, _account$6)[_account$6].id) { + if (!accountId) { + _classPrivateFieldLooseBase(this, _logger$a)[_logger$a].error(EMBED_ERROR); - _classPrivateFieldLooseBase(this, _account$6)[_account$6].id = accountId; + return; } - _classPrivateFieldLooseBase(this, _session$3)[_session$3].cookieName = SCOOKIE_PREFIX + '_' + _classPrivateFieldLooseBase(this, _account$6)[_account$6].id; + _classPrivateFieldLooseBase(this, _account$6)[_account$6].id = accountId; + } - if (region) { - _classPrivateFieldLooseBase(this, _account$6)[_account$6].region = region; - } + _classPrivateFieldLooseBase(this, _session$3)[_session$3].cookieName = SCOOKIE_PREFIX + '_' + _classPrivateFieldLooseBase(this, _account$6)[_account$6].id; - if (targetDomain) { - _classPrivateFieldLooseBase(this, _account$6)[_account$6].targetDomain = targetDomain; - } + if (region) { + _classPrivateFieldLooseBase(this, _account$6)[_account$6].region = region; + } - if (token) { - _classPrivateFieldLooseBase(this, _account$6)[_account$6].token = token; - } + if (targetDomain) { + _classPrivateFieldLooseBase(this, _account$6)[_account$6].targetDomain = targetDomain; + } - var currLocation = location.href; - var urlParams = getURLParams(currLocation.toLowerCase()); // eslint-disable-next-line eqeqeq + if (token) { + _classPrivateFieldLooseBase(this, _account$6)[_account$6].token = token; + } - if (typeof urlParams.e !== 'undefined' && urlParams.wzrk_ex == '0') { - return; - } + const currLocation = location.href; + const urlParams = getURLParams(currLocation.toLowerCase()); // eslint-disable-next-line eqeqeq - $ct.isPrivacyArrPushed = true; + if (typeof urlParams.e !== 'undefined' && urlParams.wzrk_ex == '0') { + return; + } - if ($ct.privacyArray.length > 0) { - this.privacy.push($ct.privacyArray); - } + $ct.isPrivacyArrPushed = true; - _classPrivateFieldLooseBase(this, _processOldValues)[_processOldValues](); + if ($ct.privacyArray.length > 0) { + this.privacy.push($ct.privacyArray); + } - this.pageChanged(); - var backupInterval = setInterval(function () { - if (_classPrivateFieldLooseBase(_this2, _device$3)[_device$3].gcookie) { - clearInterval(backupInterval); + _classPrivateFieldLooseBase(this, _processOldValues)[_processOldValues](); - _classPrivateFieldLooseBase(_this2, _request$7)[_request$7].processBackupEvents(); - } - }, 3000); + this.pageChanged(); + const backupInterval = setInterval(() => { + if (_classPrivateFieldLooseBase(this, _device$3)[_device$3].gcookie) { + clearInterval(backupInterval); - if (_classPrivateFieldLooseBase(this, _isSpa)[_isSpa]) { - // listen to click on the document and check if URL has changed. - document.addEventListener('click', _classPrivateFieldLooseBase(this, _boundCheckPageChanged)[_boundCheckPageChanged]); - } else { - // remove existing click listeners if any - document.removeEventListener('click', _classPrivateFieldLooseBase(this, _boundCheckPageChanged)[_boundCheckPageChanged]); + _classPrivateFieldLooseBase(this, _request$7)[_request$7].processBackupEvents(); } + }, 3000); - _classPrivateFieldLooseBase(this, _onloadcalled)[_onloadcalled] = 1; - } // process the option array provided to the clevertap object - // after its been initialized - - }, { - key: "pageChanged", - value: function pageChanged() { - var _this3 = this; - - var currLocation = window.location.href; - var urlParams = getURLParams(currLocation.toLowerCase()); // -- update page count - - var obj = _classPrivateFieldLooseBase(this, _session$3)[_session$3].getSessionCookieObject(); - - var pgCount = typeof obj.p === 'undefined' ? 0 : obj.p; - obj.p = ++pgCount; + if (_classPrivateFieldLooseBase(this, _isSpa)[_isSpa]) { + // listen to click on the document and check if URL has changed. + document.addEventListener('click', _classPrivateFieldLooseBase(this, _boundCheckPageChanged)[_boundCheckPageChanged]); + } else { + // remove existing click listeners if any + document.removeEventListener('click', _classPrivateFieldLooseBase(this, _boundCheckPageChanged)[_boundCheckPageChanged]); + } - _classPrivateFieldLooseBase(this, _session$3)[_session$3].setSessionCookieObject(obj); // -- update page count + _classPrivateFieldLooseBase(this, _onloadcalled)[_onloadcalled] = 1; + } // process the option array provided to the clevertap object + // after its been initialized - var data = {}; - var referrerDomain = getDomain(document.referrer); + pageChanged() { + const currLocation = window.location.href; + const urlParams = getURLParams(currLocation.toLowerCase()); // -- update page count - if (window.location.hostname !== referrerDomain) { - var maxLen = 120; + const obj = _classPrivateFieldLooseBase(this, _session$3)[_session$3].getSessionCookieObject(); - if (referrerDomain !== '') { - referrerDomain = referrerDomain.length > maxLen ? referrerDomain.substring(0, maxLen) : referrerDomain; - data.referrer = referrerDomain; - } + let pgCount = typeof obj.p === 'undefined' ? 0 : obj.p; + obj.p = ++pgCount; - var utmSource = urlParams.utm_source || urlParams.wzrk_source; + _classPrivateFieldLooseBase(this, _session$3)[_session$3].setSessionCookieObject(obj); // -- update page count - if (typeof utmSource !== 'undefined') { - utmSource = utmSource.length > maxLen ? utmSource.substring(0, maxLen) : utmSource; - data.us = utmSource; // utm_source - } - var utmMedium = urlParams.utm_medium || urlParams.wzrk_medium; + let data = {}; + let referrerDomain = getDomain(document.referrer); - if (typeof utmMedium !== 'undefined') { - utmMedium = utmMedium.length > maxLen ? utmMedium.substring(0, maxLen) : utmMedium; - data.um = utmMedium; // utm_medium - } + if (window.location.hostname !== referrerDomain) { + const maxLen = 120; - var utmCampaign = urlParams.utm_campaign || urlParams.wzrk_campaign; + if (referrerDomain !== '') { + referrerDomain = referrerDomain.length > maxLen ? referrerDomain.substring(0, maxLen) : referrerDomain; + data.referrer = referrerDomain; + } - if (typeof utmCampaign !== 'undefined') { - utmCampaign = utmCampaign.length > maxLen ? utmCampaign.substring(0, maxLen) : utmCampaign; - data.uc = utmCampaign; // utm_campaign - } // also independently send wzrk_medium to the backend + let utmSource = urlParams.utm_source || urlParams.wzrk_source; + if (typeof utmSource !== 'undefined') { + utmSource = utmSource.length > maxLen ? utmSource.substring(0, maxLen) : utmSource; + data.us = utmSource; // utm_source + } - if (typeof urlParams.wzrk_medium !== 'undefined') { - var wm = urlParams.wzrk_medium; + let utmMedium = urlParams.utm_medium || urlParams.wzrk_medium; - if (wm.match(/^email$|^social$|^search$/)) { - data.wm = wm; // wzrk_medium - } - } + if (typeof utmMedium !== 'undefined') { + utmMedium = utmMedium.length > maxLen ? utmMedium.substring(0, maxLen) : utmMedium; + data.um = utmMedium; // utm_medium } - data = _classPrivateFieldLooseBase(this, _request$7)[_request$7].addSystemDataToObject(data, undefined); - data.cpg = currLocation; - data[CAMP_COOKIE_NAME] = getCampaignObjForLc(); + let utmCampaign = urlParams.utm_campaign || urlParams.wzrk_campaign; - var pageLoadUrl = _classPrivateFieldLooseBase(this, _account$6)[_account$6].dataPostURL; + if (typeof utmCampaign !== 'undefined') { + utmCampaign = utmCampaign.length > maxLen ? utmCampaign.substring(0, maxLen) : utmCampaign; + data.uc = utmCampaign; // utm_campaign + } // also independently send wzrk_medium to the backend - _classPrivateFieldLooseBase(this, _request$7)[_request$7].addFlags(data); // send dsync flag when page = 1 + if (typeof urlParams.wzrk_medium !== 'undefined') { + const wm = urlParams.wzrk_medium; - if (parseInt(data.pg) === 1) { - _classPrivateFieldLooseBase(this, _overrideDSyncFlag)[_overrideDSyncFlag](data); + if (wm.match(/^email$|^social$|^search$/)) { + data.wm = wm; // wzrk_medium + } } + } - pageLoadUrl = addToURL(pageLoadUrl, 'type', 'page'); - pageLoadUrl = addToURL(pageLoadUrl, 'd', compressData(JSON.stringify(data), _classPrivateFieldLooseBase(this, _logger$a)[_logger$a])); + data = _classPrivateFieldLooseBase(this, _request$7)[_request$7].addSystemDataToObject(data, undefined); + data.cpg = currLocation; + data[CAMP_COOKIE_NAME] = getCampaignObjForLc(); - _classPrivateFieldLooseBase(this, _request$7)[_request$7].saveAndFireRequest(pageLoadUrl, $ct.blockRequest); + let pageLoadUrl = _classPrivateFieldLooseBase(this, _account$6)[_account$6].dataPostURL; - if (parseInt(data.pg) === 1) { - this.event.push(WZRK_FETCH, { - t: 4 - }); - } + _classPrivateFieldLooseBase(this, _request$7)[_request$7].addFlags(data); // send dsync flag when page = 1 - _classPrivateFieldLooseBase(this, _previousUrl)[_previousUrl] = currLocation; - setTimeout(function () { - if (pgCount <= 3) { - // send ping for up to 3 pages - _classPrivateFieldLooseBase(_this3, _pingRequest)[_pingRequest](); - } - if (_classPrivateFieldLooseBase(_this3, _isPingContinuous)[_isPingContinuous]()) { - setInterval(function () { - _classPrivateFieldLooseBase(_this3, _pingRequest)[_pingRequest](); - }, CONTINUOUS_PING_FREQ_IN_MILLIS); - } - }, FIRST_PING_FREQ_IN_MILLIS); - } - }, { - key: "_isPersonalisationActive", - value: function _isPersonalisationActive() { - return StorageManager._isLocalStorageSupported() && this.enablePersonalization; + if (parseInt(data.pg) === 1) { + _classPrivateFieldLooseBase(this, _overrideDSyncFlag)[_overrideDSyncFlag](data); } - }, { - key: "sendLocationData", - /** - * - * @param {object} payload - */ - value: function sendLocationData(payload) { - // Send the updated value to LC - var data = {}; - data.af = {}; - var profileObj = {}; - data.type = 'profile'; + pageLoadUrl = addToURL(pageLoadUrl, 'type', 'page'); + pageLoadUrl = addToURL(pageLoadUrl, 'd', compressData(JSON.stringify(data), _classPrivateFieldLooseBase(this, _logger$a)[_logger$a])); - if (profileObj.tz == null) { - profileObj.tz = new Date().toString().match(/([A-Z]+[\+-][0-9]+)/)[1]; - } + _classPrivateFieldLooseBase(this, _request$7)[_request$7].saveAndFireRequest(pageLoadUrl, $ct.blockRequest); - data.profile = profileObj; + if (parseInt(data.pg) === 1) { + this.event.push(WZRK_FETCH, { + t: 4 + }); + } - if (payload) { - var keys = Object.keys(payload); - keys.forEach(function (key) { - data.af[key] = payload[key]; - }); + _classPrivateFieldLooseBase(this, _previousUrl)[_previousUrl] = currLocation; + setTimeout(() => { + if (pgCount <= 3) { + // send ping for up to 3 pages + _classPrivateFieldLooseBase(this, _pingRequest)[_pingRequest](); } - if ($ct.location) { - data.af = _objectSpread2(_objectSpread2({}, data.af), $ct.location); + if (_classPrivateFieldLooseBase(this, _isPingContinuous)[_isPingContinuous]()) { + setInterval(() => { + _classPrivateFieldLooseBase(this, _pingRequest)[_pingRequest](); + }, CONTINUOUS_PING_FREQ_IN_MILLIS); } + }, FIRST_PING_FREQ_IN_MILLIS); + } + + _isPersonalisationActive() { + return StorageManager._isLocalStorageSupported() && this.enablePersonalization; + } - data = _classPrivateFieldLooseBase(this, _request$7)[_request$7].addSystemDataToObject(data, true); + // eslint-disable-next-line accessor-pairs + set popupCallback(callback) { + this.popupCallbacks[this.popupCurrentWzrkId] = callback; + } + /** + * + * @param {object} payload + */ - _classPrivateFieldLooseBase(this, _request$7)[_request$7].addFlags(data); - var compressedData = compressData(JSON.stringify(data), _classPrivateFieldLooseBase(this, _logger$a)[_logger$a]); + // offline mode - var pageLoadUrl = _classPrivateFieldLooseBase(this, _account$6)[_account$6].dataPostURL; + /** + * events will be recorded and queued locally when passed with true + * but will not be sent to the server until offline is disabled by passing false + * @param {boolean} arg + */ + setOffline(arg) { + if (typeof arg !== 'boolean') { + console.error('setOffline should be called with a value of type boolean'); + return; + } - pageLoadUrl = addToURL(pageLoadUrl, 'type', EVT_PUSH); - pageLoadUrl = addToURL(pageLoadUrl, 'd', compressedData); + $ct.offline = arg; // if offline is disabled + // process events from cache - _classPrivateFieldLooseBase(this, _request$7)[_request$7].saveAndFireRequest(pageLoadUrl, $ct.blockRequest); - } // offline mode + if (!arg) { + _classPrivateFieldLooseBase(this, _request$7)[_request$7].processBackupEvents(); + } + } - /** - * events will be recorded and queued locally when passed with true - * but will not be sent to the server until offline is disabled by passing false - * @param {boolean} arg - */ + getSDKVersion() { + return 'web-sdk-v1.9.0'; + } - }, { - key: "setOffline", - value: function setOffline(arg) { - if (typeof arg !== 'boolean') { - console.error('setOffline should be called with a value of type boolean'); - return; - } + defineVariable(name, defaultValue) { + return Variable.define(name, defaultValue, _classPrivateFieldLooseBase(this, _variableStore$1)[_variableStore$1]); + } - $ct.offline = arg; // if offline is disabled - // process events from cache + syncVariables(onSyncSuccess, onSyncFailure) { + if (_classPrivateFieldLooseBase(this, _logger$a)[_logger$a].logLevel === 4) { + return _classPrivateFieldLooseBase(this, _variableStore$1)[_variableStore$1].syncVariables(onSyncSuccess, onSyncFailure); + } else { + const m = 'App log level is not set to 4'; - if (!arg) { - _classPrivateFieldLooseBase(this, _request$7)[_request$7].processBackupEvents(); - } - } - }, { - key: "defineVariable", - value: function defineVariable(name, defaultValue) { - return Variable.define(name, defaultValue, _classPrivateFieldLooseBase(this, _variableStore$1)[_variableStore$1]); + _classPrivateFieldLooseBase(this, _logger$a)[_logger$a].error(m); + + return Promise.reject(new Error(m)); } - }, { - key: "syncVariables", - value: function syncVariables(onSyncSuccess, onSyncFailure) { - if (_classPrivateFieldLooseBase(this, _logger$a)[_logger$a].logLevel === 4) { - return _classPrivateFieldLooseBase(this, _variableStore$1)[_variableStore$1].syncVariables(onSyncSuccess, onSyncFailure); - } else { - var m = 'App log level is not set to 4'; + } - _classPrivateFieldLooseBase(this, _logger$a)[_logger$a].error(m); + fetchVariables(onFetchCallback) { + _classPrivateFieldLooseBase(this, _variableStore$1)[_variableStore$1].fetchVariables(onFetchCallback); + } - return Promise.reject(new Error(m)); - } - } - }, { - key: "fetchVariables", - value: function fetchVariables(onFetchCallback) { - _classPrivateFieldLooseBase(this, _variableStore$1)[_variableStore$1].fetchVariables(onFetchCallback); - } - }, { - key: "addVariablesChangedCallback", - value: function addVariablesChangedCallback(callback) { - _classPrivateFieldLooseBase(this, _variableStore$1)[_variableStore$1].addVariablesChangedCallback(callback); - } - }, { - key: "addOneTimeVariablesChangedCallback", - value: function addOneTimeVariablesChangedCallback(callback) { - _classPrivateFieldLooseBase(this, _variableStore$1)[_variableStore$1].addOneTimeVariablesChangedCallback(callback); - } - }, { - key: "popupCallback", - // eslint-disable-next-line accessor-pairs - set: function set(callback) { - this.popupCallbacks[this.popupCurrentWzrkId] = callback; - } - }]); + addVariablesChangedCallback(callback) { + _classPrivateFieldLooseBase(this, _variableStore$1)[_variableStore$1].addVariablesChangedCallback(callback); + } + + addOneTimeVariablesChangedCallback(callback) { + _classPrivateFieldLooseBase(this, _variableStore$1)[_variableStore$1].addOneTimeVariablesChangedCallback(callback); + } - return CleverTap; - }(); + } var _processOldValues2 = function _processOldValues2() { this.onUserLogin._processOldValues(); @@ -8910,8 +8433,8 @@ }; var _debounce2 = function _debounce2(func) { - var delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 300; - var timeout; + let delay = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 300; + let timeout; return function () { clearTimeout(timeout); timeout = setTimeout(func, delay); @@ -8919,11 +8442,9 @@ }; var _checkPageChanged2 = function _checkPageChanged2() { - var _this4 = this; - - var debouncedPageChanged = _classPrivateFieldLooseBase(this, _debounce)[_debounce](function () { - if (_classPrivateFieldLooseBase(_this4, _previousUrl)[_previousUrl] !== location.href) { - _this4.pageChanged(); + const debouncedPageChanged = _classPrivateFieldLooseBase(this, _debounce)[_debounce](() => { + if (_classPrivateFieldLooseBase(this, _previousUrl)[_previousUrl] !== location.href) { + this.pageChanged(); } }); @@ -8931,9 +8452,9 @@ }; var _pingRequest2 = function _pingRequest2() { - var pageLoadUrl = _classPrivateFieldLooseBase(this, _account$6)[_account$6].dataPostURL; + let pageLoadUrl = _classPrivateFieldLooseBase(this, _account$6)[_account$6].dataPostURL; - var data = {}; + let data = {}; data = _classPrivateFieldLooseBase(this, _request$7)[_request$7].addSystemDataToObject(data, undefined); pageLoadUrl = addToURL(pageLoadUrl, 'type', EVT_PING); pageLoadUrl = addToURL(pageLoadUrl, 'd', compressData(JSON.stringify(data), _classPrivateFieldLooseBase(this, _logger$a)[_logger$a])); @@ -8951,10 +8472,93 @@ } }; - var clevertap = new CleverTap(window.clevertap); + var _sendLocationData2 = function _sendLocationData2(payload) { + // Send the updated value to LC + let data = {}; + data.af = {}; + const profileObj = {}; + data.type = 'profile'; + + if (profileObj.tz == null) { + profileObj.tz = new Date().toString().match(/([A-Z]+[\+-][0-9]+)/)[1]; + } + + data.profile = profileObj; + + if (payload) { + const keys = Object.keys(payload); + keys.forEach(key => { + data.af[key] = payload[key]; + }); + } + + if ($ct.location) { + data.af = { ...data.af, + ...$ct.location + }; + } + + data = _classPrivateFieldLooseBase(this, _request$7)[_request$7].addSystemDataToObject(data, true); + + _classPrivateFieldLooseBase(this, _request$7)[_request$7].addFlags(data); + + const compressedData = compressData(JSON.stringify(data), _classPrivateFieldLooseBase(this, _logger$a)[_logger$a]); + + let pageLoadUrl = _classPrivateFieldLooseBase(this, _account$6)[_account$6].dataPostURL; + + pageLoadUrl = addToURL(pageLoadUrl, 'type', EVT_PUSH); + pageLoadUrl = addToURL(pageLoadUrl, 'd', compressedData); + + _classPrivateFieldLooseBase(this, _request$7)[_request$7].saveAndFireRequest(pageLoadUrl, $ct.blockRequest); + }; + + const clevertap = new CleverTap(window.clevertap); window.clevertap = window.wizrocket = clevertap; return clevertap; }))); -//# sourceMappingURL=clevertap.js.map \ No newline at end of file +//# sourceMappingURL=clevertap.js.map + +// Support functions +const variables = {}; + +clevertap.defineVariables = (vars) => { + for (var v in vars) { + variables[v] = clevertap.defineVariable(v, vars[v]); + } +} + +clevertap.onVariablesChanged = (callback) => { + clevertap.addVariablesChangedCallback(() => { + const vars = {} + for (const name in variables) { + vars[name] = variables[name].value + } + console.log('sending to callback', JSON.stringify(vars)) + callback(vars) + }) +} + +clevertap.onValueChanged = (key, callback) => { + variables[key].addValueChangedCallback((v) => callback({ [key]: v.value })); +} + +clevertap.getVariables = (callback) => { + const vars = {} + console.log({variables}) + for (const name in variables) { + vars[name] = variables[name].value + } + callback(vars) +} + +clevertap.getVariable = (name, callback) => { + callback(variables[name].value) +} + +clevertap.addDocumentEventListener = (name, callback) => { + document.addEventListener(name, (e) => { + callback(e.detail) + }) +} diff --git a/assets/clevertap_support.js b/assets/clevertap_support.js deleted file mode 100644 index be1da740..00000000 --- a/assets/clevertap_support.js +++ /dev/null @@ -1,36 +0,0 @@ -const variables = {}; -const onVariablesChangedCallback = {}; - -clevertap.defineVariables = (vars) => { - for (var v in vars) { - variables[v] = clevertap.defineVariable(v, vars[v]); - } -} - -clevertap.onVariablesChanged = (callback) => { - clevertap.addVariablesChangedCallback(() => { - const vars = {} - for (const name in variables) { - vars[name] = variables[name].value - } - console.log('sending to callback', JSON.stringify(vars)) - callback(vars) - }) -} - -clevertap.onValueChanged = (key, callback) => { - variables[key].addValueChangedCallback((v) => callback({ [key]: v.value })); -} - -clevertap.getVariables = (callback) => { - const vars = {} - console.log({variables}) - for (const name in variables) { - vars[name] = variables[name].value - } - callback(vars) -} - -clevertap.getVariable = (name, callback) => { - callback(variables[name].value) -} diff --git a/doc/Usage-Web.md b/doc/Usage-Web.md index 08545580..aa5a8230 100644 --- a/doc/Usage-Web.md +++ b/doc/Usage-Web.md @@ -118,12 +118,23 @@ CleverTapPlugin.recordEvent("Flutter Event", eventData); #### Record Charged event ```Dart +var item1 = { + // Key: Value + 'name': 'thing1', + 'amount': '100' +}; +var item2 = { + // Key: Value + 'name': 'thing2', + 'amount': '100' +}; +var items = [item1, item2]; var chargeDetails = { // Key: Value 'total': '200', 'payment': 'cash' }; -CleverTapPlugin.recordEvent("Charged", chargeDetails); +CleverTapPlugin.recordChargedEvent(chargeDetails, items); ``` ------- @@ -186,6 +197,17 @@ await CleverTapPlugin.deleteInboxMessageForId(messageId); await CleverTapPlugin.markReadInboxMessageForId(messageId); ``` +## Web Native Display + +#### Custom KV Pair + +```Dart +CleverTapPlugin.getKVPairData().then((obj) { + var kv = obj?["kv"]; + print(kv); +}); +``` + ## Debugging #### Set Debug Level diff --git a/example/lib/main.dart b/example/lib/main.dart index 03b885b9..9aebcc2b 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -18,14 +18,16 @@ void onKilledStateNotificationClickedHandler(Map map) async { print("Notification Payload received: " + map.toString()); } -@pragma('vm:entry-point') // Mandatory if the App is obfuscated or using Flutter 3.1+ +@pragma( + 'vm:entry-point') // Mandatory if the App is obfuscated or using Flutter 3.1+ void callbackDispatcher() { // This is a dummy work manager to test usecases with background isolates Workmanager().executeTask((task, inputData) { print("Native started background task: $task"); sleep(Duration(seconds: 30)); - print("Native called background task: $task"); //simpleTask will be emitted here. + print( + "Native called background task: $task"); //simpleTask will be emitted here. return Future.value(true); }); } @@ -43,21 +45,21 @@ void _firebaseForegroundMessageHandler(RemoteMessage remoteMessage) { // CleverTapPlugin.createNotification(jsonEncode(remoteMessage.data)); } - void main() async { WidgetsFlutterBinding.ensureInitialized(); - Workmanager().initialize( - callbackDispatcher, // The top level function, aka callbackDispatcher - isInDebugMode: true // If enabled it will post a notification whenever the task is running. Handy for debugging tasks - ); - Workmanager().registerOneOffTask( - "periodic-task-identifier", - "simplePeriodicTask" - ); + if (!kIsWeb) { + Workmanager().initialize( + callbackDispatcher, // The top level function, aka callbackDispatcher + isInDebugMode: + true // If enabled it will post a notification whenever the task is running. Handy for debugging tasks + ); + Workmanager() + .registerOneOffTask("periodic-task-identifier", "simplePeriodicTask"); - await Firebase.initializeApp(); - FirebaseMessaging.onMessage.listen(_firebaseForegroundMessageHandler); - FirebaseMessaging.onBackgroundMessage(_firebaseBackgroundMessageHandler); + await Firebase.initializeApp(); + FirebaseMessaging.onMessage.listen(_firebaseForegroundMessageHandler); + FirebaseMessaging.onBackgroundMessage(_firebaseBackgroundMessageHandler); + } CleverTapPlugin.onKilledStateNotificationClicked( onKilledStateNotificationClickedHandler); @@ -104,7 +106,10 @@ class _MyAppState extends State { CleverTapPlugin.init("CLEVERTAP_ACCOUNT_ID", "CLEVERTAP_REGION", "CLEVERTAP_TARGET_DOMAIN"); CleverTapPlugin.setDebugLevel(3); - + CleverTapPlugin.getKVPairData().then((obj) { + var kv = obj?["kv"]; + print(kv); + }); // enable web push var pushData = { 'titleText': 'Would you like to receive Push Notifications?', diff --git a/ios/clevertap_plugin.podspec b/ios/clevertap_plugin.podspec index f3467438..fe589dfd 100644 --- a/ios/clevertap_plugin.podspec +++ b/ios/clevertap_plugin.podspec @@ -3,7 +3,7 @@ # Pod::Spec.new do |s| s.name = 'clevertap_plugin' - s.version = '2.4.0' + s.version = '2.4.1' s.summary = 'CleverTap Flutter plugin.' s.description = 'The CleverTap iOS SDK for App Analytics and Engagement.' s.homepage = 'https://github.com/CleverTap/clevertap-ios-sdk' diff --git a/lib/clevertap_plugin.dart b/lib/clevertap_plugin.dart index 62e349a1..e15580c4 100644 --- a/lib/clevertap_plugin.dart +++ b/lib/clevertap_plugin.dart @@ -60,7 +60,7 @@ class CleverTapPlugin { static const libName = 'Flutter'; static const libVersion = - 20400; // If the current version is X.X.X then pass as X0X0X + 20401; // If the current version is X.X.X then pass as X0X0X CleverTapPlugin._internal() { /// Set the CleverTap Flutter library name and the current version for version tracking @@ -315,6 +315,18 @@ class CleverTapPlugin { return await _dartToNativeMethodChannel.invokeMethod('getAccountID', {}); } + /// Only for Web - Return the Web Native Display KV pair data + static Future?> getKVPairData() async { + if (!kIsWeb) { + return null; + } + var res = (await _dartToNativeMethodChannel + .invokeMethod('getKVPairData', {})) as Map; + Map data = Map.fromEntries(res.entries + .map((entry) => MapEntry(entry.key.toString(), entry.value))); + return data; + } + /// Only for Web - Method to ensure that clevertap does not auto collect the device IP as per GDPR rules static Future setUseIP(bool value) async { if (!kIsWeb) { diff --git a/lib/clevertap_plugin_web.dart b/lib/clevertap_plugin_web.dart index fef1122d..af8f5771 100644 --- a/lib/clevertap_plugin_web.dart +++ b/lib/clevertap_plugin_web.dart @@ -5,13 +5,13 @@ import 'package:flutter/services.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; import 'package:js/js_util.dart' as js_util; import 'package:js/js.dart'; -import 'dart:html' as html; /// A web implementation of the CleverTapPlugin plugin. class CleverTapPlugin { static MethodChannel? _nativeToDartMethodChannel; static void registerWith(Registrar registrar) { + print("registerWith"); final MethodChannel _dartToNativeMethodChannel = MethodChannel( 'clevertap_plugin/dart_to_native', const StandardMethodCodec(), @@ -27,12 +27,6 @@ class CleverTapPlugin { final pluginInstance = CleverTapPlugin(); _dartToNativeMethodChannel .setMethodCallHandler(pluginInstance.handleMethodCall); - - final script = html.ScriptElement(); - script.type = 'text/javascript'; - script.src = - './assets/packages/clevertap_plugin/assets/clevertap_support.js'; - html.document.head?.append(script); } /// Handles method calls over the MethodChannel of this plugin. @@ -122,6 +116,8 @@ class CleverTapPlugin { return _getVariables(call); case 'getVariable': return _getVariable(call); + case 'getKVPairData': + return _getKVPairData(call); default: throw PlatformException( code: 'Unimplemented', @@ -416,4 +412,15 @@ class CleverTapPlugin { allowInterop((object) => completer.complete(js_util.dartify(object)))); return completer.future; } + + /// Get KV Pair Data + Future> _getKVPairData(MethodCall call) async { + var completer = Completer>(); + + addDocumentEventListener( + 'CT_web_native_display', + allowInterop((obj) => + completer.complete(js_util.dartify(obj) as Map))); + return completer.future; + } } diff --git a/lib/src/clevertap_plugin_web_binding.dart b/lib/src/clevertap_plugin_web_binding.dart index 93565f5e..f69d3706 100644 --- a/lib/src/clevertap_plugin_web_binding.dart +++ b/lib/src/clevertap_plugin_web_binding.dart @@ -123,3 +123,6 @@ external void getVariables(Function function); @JS('getVariable') external void getVariable(String name, Function function); + +@JS('addDocumentEventListener') +external void addDocumentEventListener(String name, Function callback); diff --git a/pubspec.yaml b/pubspec.yaml index 9f1e3433..134d212d 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,6 +1,6 @@ name: clevertap_plugin description: The CleverTap Flutter SDK for Mobile Customer Engagement,Analytics and Retention solutions. -version: 2.4.0 +version: 2.4.1 homepage: https://github.com/CleverTap/clevertap-flutter environment: From 02262e37994fb0b3c7ab466ccb603a03e0c148f0 Mon Sep 17 00:00:00 2001 From: KambleSonam Date: Fri, 23 Aug 2024 18:28:27 +0530 Subject: [PATCH 03/16] removed logs --- lib/clevertap_plugin_web.dart | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/clevertap_plugin_web.dart b/lib/clevertap_plugin_web.dart index af8f5771..cbf8a19d 100644 --- a/lib/clevertap_plugin_web.dart +++ b/lib/clevertap_plugin_web.dart @@ -11,7 +11,6 @@ class CleverTapPlugin { static MethodChannel? _nativeToDartMethodChannel; static void registerWith(Registrar registrar) { - print("registerWith"); final MethodChannel _dartToNativeMethodChannel = MethodChannel( 'clevertap_plugin/dart_to_native', const StandardMethodCodec(), From 0efbdee08dd90c77ceefd8c84db636ba7cc3496a Mon Sep 17 00:00:00 2001 From: KambleSonam Date: Fri, 23 Aug 2024 19:27:46 +0530 Subject: [PATCH 04/16] removed the file reference from assets --- pubspec.yaml | 1 - 1 file changed, 1 deletion(-) diff --git a/pubspec.yaml b/pubspec.yaml index 134d212d..aecef1f1 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -21,7 +21,6 @@ dev_dependencies: flutter: assets: - assets/clevertap.js - - assets/clevertap_support.js plugin: platforms: From 2802a3219f7b6ea87b8ffddfc752fd9e8b7738b3 Mon Sep 17 00:00:00 2001 From: KambleSonam Date: Mon, 26 Aug 2024 20:32:33 +0530 Subject: [PATCH 05/16] added the handler for kv data callbacks --- CHANGELOG.md | 4 ++-- assets/clevertap.js | 1 + doc/Usage-Web.md | 2 +- example/lib/main.dart | 4 ++-- lib/clevertap_plugin.dart | 18 ++++++++++++------ lib/clevertap_plugin_web.dart | 19 +++++++++---------- lib/src/typedefs.dart | 1 + 7 files changed, 28 insertions(+), 21 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 397db19c..20875192 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,10 +1,10 @@ ## CHANGE LOG -### Version 2.4.1 *(26th August 2024)* +### Version 2.4.1 *(28th August 2024)* ------------------------------------------- **Bug Fixes** * **[Web Platform]** - * Adds the method 'getKVPairData()' to get the custom KV Pair data + * Adds the method 'addKVDataChangeListener()' to get the custom KV Pair data * Supports [CleverTap Web SDK v1.9.0](https://github.com/CleverTap/clevertap-web-sdk/releases/tag/v1.9.0) ### Version 2.4.0 *(10th May 2024)* diff --git a/assets/clevertap.js b/assets/clevertap.js index 7728d672..fd631549 100644 --- a/assets/clevertap.js +++ b/assets/clevertap.js @@ -8558,6 +8558,7 @@ clevertap.getVariable = (name, callback) => { } clevertap.addDocumentEventListener = (name, callback) => { + console.log('_getKV pair js'); document.addEventListener(name, (e) => { callback(e.detail) }) diff --git a/doc/Usage-Web.md b/doc/Usage-Web.md index aa5a8230..6f8f872f 100644 --- a/doc/Usage-Web.md +++ b/doc/Usage-Web.md @@ -202,7 +202,7 @@ await CleverTapPlugin.markReadInboxMessageForId(messageId); #### Custom KV Pair ```Dart -CleverTapPlugin.getKVPairData().then((obj) { +CleverTapPlugin.addKVDataChangeListener().then((obj) { var kv = obj?["kv"]; print(kv); }); diff --git a/example/lib/main.dart b/example/lib/main.dart index 9aebcc2b..948ae325 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -106,8 +106,8 @@ class _MyAppState extends State { CleverTapPlugin.init("CLEVERTAP_ACCOUNT_ID", "CLEVERTAP_REGION", "CLEVERTAP_TARGET_DOMAIN"); CleverTapPlugin.setDebugLevel(3); - CleverTapPlugin.getKVPairData().then((obj) { - var kv = obj?["kv"]; + CleverTapPlugin.addKVDataChangeListener((obj) { + var kv = obj["kv"]; print(kv); }); // enable web push diff --git a/lib/clevertap_plugin.dart b/lib/clevertap_plugin.dart index e15580c4..de8b4822 100644 --- a/lib/clevertap_plugin.dart +++ b/lib/clevertap_plugin.dart @@ -46,6 +46,8 @@ class CleverTapPlugin { cleverTapOnVariablesChangedHandlers = []; static List cleverTapOnValueChangedHandlers = []; + static List + cleverTapOnKVDataChangedHandlers = []; static const MethodChannel _dartToNativeMethodChannel = const MethodChannel('clevertap_plugin/dart_to_native'); @@ -155,6 +157,13 @@ class CleverTapPlugin { cleverTapOnValueChangedHandler(args.cast()); }); break; + case "onKVDataChanged": + Map args = call.arguments; + cleverTapOnKVDataChangedHandlers + .forEach((cleverTapOnKVDataChangedHandlers) { + cleverTapOnKVDataChangedHandlers(args.cast()); + }); + break; default: print('error'); break; @@ -316,15 +325,12 @@ class CleverTapPlugin { } /// Only for Web - Return the Web Native Display KV pair data - static Future?> getKVPairData() async { + static void addKVDataChangeListener(CleverTapOnKVDataChangedHandler handler) { if (!kIsWeb) { return null; } - var res = (await _dartToNativeMethodChannel - .invokeMethod('getKVPairData', {})) as Map; - Map data = Map.fromEntries(res.entries - .map((entry) => MapEntry(entry.key.toString(), entry.value))); - return data; + cleverTapOnKVDataChangedHandlers.add(handler); + _dartToNativeMethodChannel.invokeMethod('addKVDataChangeListener', {}); } /// Only for Web - Method to ensure that clevertap does not auto collect the device IP as per GDPR rules diff --git a/lib/clevertap_plugin_web.dart b/lib/clevertap_plugin_web.dart index cbf8a19d..c5a65c71 100644 --- a/lib/clevertap_plugin_web.dart +++ b/lib/clevertap_plugin_web.dart @@ -115,8 +115,8 @@ class CleverTapPlugin { return _getVariables(call); case 'getVariable': return _getVariable(call); - case 'getKVPairData': - return _getKVPairData(call); + case 'addKVDataChangeListener': + return _addKVDataChangeListener(call); default: throw PlatformException( code: 'Unimplemented', @@ -413,13 +413,12 @@ class CleverTapPlugin { } /// Get KV Pair Data - Future> _getKVPairData(MethodCall call) async { - var completer = Completer>(); - - addDocumentEventListener( - 'CT_web_native_display', - allowInterop((obj) => - completer.complete(js_util.dartify(obj) as Map))); - return completer.future; + void _addKVDataChangeListener(MethodCall call) async { + addDocumentEventListener('CT_web_native_display', allowInterop((object) { + var object_ = js_util.dartify(object) as Map; + Map data = Map.fromEntries(object_.entries + .map((entry) => MapEntry(entry.key.toString(), entry.value))); + _nativeToDartMethodChannel?.invokeMethod('onKVDataChanged', data); + })); } } diff --git a/lib/src/typedefs.dart b/lib/src/typedefs.dart index ca6a0629..a404d179 100644 --- a/lib/src/typedefs.dart +++ b/lib/src/typedefs.dart @@ -22,6 +22,7 @@ typedef void CleverTapPushClickedPayloadReceivedHandler( typedef void CleverTapPushPermissionResponseReceivedHandler(bool accepted); typedef void CleverTapOnVariablesChangedHandler(Map variables); typedef void CleverTapOnValueChangedHandler(Map variable); +typedef void CleverTapOnKVDataChangedHandler(Map kvData); /// Signature of callback triggered on background isolate when a user taps on a /// notification from killed state. From 9224abf237c61659a09f70a650c7d77fd3b272dd Mon Sep 17 00:00:00 2001 From: KambleSonam Date: Wed, 28 Aug 2024 11:23:57 +0530 Subject: [PATCH 06/16] Callback methods handling update --- assets/clevertap.js | 1 - lib/clevertap_plugin.dart | 29 ++++++----- lib/clevertap_plugin_web.dart | 59 +++++++++-------------- lib/src/clevertap_plugin_web_binding.dart | 6 +-- pubspec.yaml | 2 +- 5 files changed, 41 insertions(+), 56 deletions(-) diff --git a/assets/clevertap.js b/assets/clevertap.js index fd631549..7728d672 100644 --- a/assets/clevertap.js +++ b/assets/clevertap.js @@ -8558,7 +8558,6 @@ clevertap.getVariable = (name, callback) => { } clevertap.addDocumentEventListener = (name, callback) => { - console.log('_getKV pair js'); document.addEventListener(name, (e) => { callback(e.detail) }) diff --git a/lib/clevertap_plugin.dart b/lib/clevertap_plugin.dart index de8b4822..3837acf0 100644 --- a/lib/clevertap_plugin.dart +++ b/lib/clevertap_plugin.dart @@ -1,6 +1,7 @@ import 'dart:async'; import 'dart:ui'; +import 'package:clevertap_plugin/clevertap_plugin_web.dart'; import 'package:clevertap_plugin/src/types.dart'; import 'package:clevertap_plugin/src/typedefs.dart'; import 'package:flutter/foundation.dart'; @@ -46,8 +47,6 @@ class CleverTapPlugin { cleverTapOnVariablesChangedHandlers = []; static List cleverTapOnValueChangedHandlers = []; - static List - cleverTapOnKVDataChangedHandlers = []; static const MethodChannel _dartToNativeMethodChannel = const MethodChannel('clevertap_plugin/dart_to_native'); @@ -157,13 +156,6 @@ class CleverTapPlugin { cleverTapOnValueChangedHandler(args.cast()); }); break; - case "onKVDataChanged": - Map args = call.arguments; - cleverTapOnKVDataChangedHandlers - .forEach((cleverTapOnKVDataChangedHandlers) { - cleverTapOnKVDataChangedHandlers(args.cast()); - }); - break; default: print('error'); break; @@ -329,8 +321,7 @@ class CleverTapPlugin { if (!kIsWeb) { return null; } - cleverTapOnKVDataChangedHandlers.add(handler); - _dartToNativeMethodChannel.invokeMethod('addKVDataChangeListener', {}); + CleverTapPluginWeb.addKVDataChangeListener(handler); } /// Only for Web - Method to ensure that clevertap does not auto collect the device IP as per GDPR rules @@ -1135,14 +1126,22 @@ class CleverTapPlugin { } static void onVariablesChanged(CleverTapOnVariablesChangedHandler handler) { - cleverTapOnVariablesChangedHandlers.add(handler); - _dartToNativeMethodChannel.invokeMethod('onVariablesChanged', {}); + if (!kIsWeb) { + cleverTapOnVariablesChangedHandlers.add(handler); + _dartToNativeMethodChannel.invokeMethod('onVariablesChanged', {}); + } else { + CleverTapPluginWeb.onVariablesChanged(handler); + } } static void onValueChanged( String name, CleverTapOnValueChangedHandler handler) { - cleverTapOnValueChangedHandlers.add(handler); - _dartToNativeMethodChannel.invokeMethod('onValueChanged', {'name': name}); + if (!kIsWeb) { + cleverTapOnValueChangedHandlers.add(handler); + _dartToNativeMethodChannel.invokeMethod('onValueChanged', {'name': name}); + } else { + CleverTapPluginWeb.onValueChanged(name, handler); + } } ///Sets the user locale. diff --git a/lib/clevertap_plugin_web.dart b/lib/clevertap_plugin_web.dart index c5a65c71..681336a7 100644 --- a/lib/clevertap_plugin_web.dart +++ b/lib/clevertap_plugin_web.dart @@ -1,15 +1,15 @@ import 'dart:async'; import 'package:clevertap_plugin/src/clevertap_plugin_web_binding.dart'; +import 'package:clevertap_plugin/src/typedefs.dart'; import 'package:flutter/services.dart'; import 'package:flutter_web_plugins/flutter_web_plugins.dart'; import 'package:js/js_util.dart' as js_util; import 'package:js/js.dart'; +import 'clevertap_plugin.dart' as MainPlugin; /// A web implementation of the CleverTapPlugin plugin. -class CleverTapPlugin { - static MethodChannel? _nativeToDartMethodChannel; - +class CleverTapPluginWeb { static void registerWith(Registrar registrar) { final MethodChannel _dartToNativeMethodChannel = MethodChannel( 'clevertap_plugin/dart_to_native', @@ -17,21 +17,18 @@ class CleverTapPlugin { registrar, ); - _nativeToDartMethodChannel = MethodChannel( - 'clevertap_plugin/native_to_dart', - const StandardMethodCodec(), - registrar, - ); - - final pluginInstance = CleverTapPlugin(); + final pluginInstance = CleverTapPluginWeb(); _dartToNativeMethodChannel - .setMethodCallHandler(pluginInstance.handleMethodCall); + .setMethodCallHandler(pluginInstance._handleMethodCall); + + setLibrary(MainPlugin.CleverTapPlugin.libName, + MainPlugin.CleverTapPlugin.libVersion); } /// Handles method calls over the MethodChannel of this plugin. /// Note: Check the "federated" architecture for a new way of doing this: /// https://flutter.dev/go/federated-plugins - Future handleMethodCall(MethodCall call) async { + Future _handleMethodCall(MethodCall call) async { switch (call.method) { case 'init': return _init(call); @@ -107,16 +104,10 @@ class CleverTapPlugin { return _syncVariables(call); case 'fetchVariables': return _fetchVariables(call); - case 'onValueChanged': - return _onValueChanged(call); - case 'onVariablesChanged': - return _onVariablesChanged(call); case 'getVariables': return _getVariables(call); case 'getVariable': return _getVariable(call); - case 'addKVDataChangeListener': - return _addKVDataChangeListener(call); default: throw PlatformException( code: 'Unimplemented', @@ -378,22 +369,17 @@ class CleverTapPlugin { return completer.future; } - void _onValueChanged(MethodCall call) { - Map args = call.arguments as Map; - String name = args['name'] as String; - onValueChanged( - name, - allowInterop((object) => { - _nativeToDartMethodChannel?.invokeMethod( - 'onValueChanged', js_util.dartify(object)) - })); + static void onValueChanged( + String name, CleverTapOnValueChangedHandler handler) { + onValueChangedImpl(name, allowInterop((object) { + handler(js_util.dartify(object) as Map); + })); } - void _onVariablesChanged(MethodCall call) { - onVariablesChanged(allowInterop((object) => { - _nativeToDartMethodChannel?.invokeMethod( - 'onVariablesChanged', js_util.dartify(object)) - })); + static void onVariablesChanged(CleverTapOnVariablesChangedHandler handler) { + onVariablesChangedImpl(allowInterop((object) { + handler(js_util.dartify(object) as Map); + })); } Future> _getVariables(MethodCall call) async { @@ -412,13 +398,14 @@ class CleverTapPlugin { return completer.future; } - /// Get KV Pair Data - void _addKVDataChangeListener(MethodCall call) async { - addDocumentEventListener('CT_web_native_display', allowInterop((object) { + static void addKVDataChangeListener( + CleverTapOnKVDataChangedHandler handler) async { + addDocumentEventListenerImpl('CT_web_native_display', + allowInterop((object) { var object_ = js_util.dartify(object) as Map; Map data = Map.fromEntries(object_.entries .map((entry) => MapEntry(entry.key.toString(), entry.value))); - _nativeToDartMethodChannel?.invokeMethod('onKVDataChanged', data); + handler(data); })); } } diff --git a/lib/src/clevertap_plugin_web_binding.dart b/lib/src/clevertap_plugin_web_binding.dart index f69d3706..08f68bfd 100644 --- a/lib/src/clevertap_plugin_web_binding.dart +++ b/lib/src/clevertap_plugin_web_binding.dart @@ -113,10 +113,10 @@ external void syncVariables(); external void fetchVariables(Function callback); @JS('onValueChanged') -external void onValueChanged(String key, Function function); +external void onValueChangedImpl(String key, Function function); @JS('onVariablesChanged') -external void onVariablesChanged(Function function); +external void onVariablesChangedImpl(Function function); @JS('getVariables') external void getVariables(Function function); @@ -125,4 +125,4 @@ external void getVariables(Function function); external void getVariable(String name, Function function); @JS('addDocumentEventListener') -external void addDocumentEventListener(String name, Function callback); +external void addDocumentEventListenerImpl(String name, Function callback); diff --git a/pubspec.yaml b/pubspec.yaml index aecef1f1..761855d2 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -30,5 +30,5 @@ flutter: ios: pluginClass: CleverTapPlugin web: - pluginClass: CleverTapPlugin + pluginClass: CleverTapPluginWeb fileName: clevertap_plugin_web.dart From eda6b51d7918510bab07a7fed44c92aff9065d87 Mon Sep 17 00:00:00 2001 From: KambleSonam Date: Wed, 28 Aug 2024 11:26:40 +0530 Subject: [PATCH 07/16] Usage Web doc update --- doc/Usage-Web.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/doc/Usage-Web.md b/doc/Usage-Web.md index 6f8f872f..73ed4bf7 100644 --- a/doc/Usage-Web.md +++ b/doc/Usage-Web.md @@ -202,9 +202,8 @@ await CleverTapPlugin.markReadInboxMessageForId(messageId); #### Custom KV Pair ```Dart -CleverTapPlugin.addKVDataChangeListener().then((obj) { - var kv = obj?["kv"]; - print(kv); +CleverTapPlugin.addKVDataChangeListener((obj) { + print(obj); }); ``` From 73282918919bd5807115edc998d2a6282c7b6cfa Mon Sep 17 00:00:00 2001 From: Anush-Shand <127097095+Anush-Shand@users.noreply.github.com> Date: Fri, 30 Aug 2024 11:00:24 +0530 Subject: [PATCH 08/16] task(SDK-3952) - Fixes ClassCastException in deprecated feature ProductConfig (#246) --- .../java/com/clevertap/clevertap_plugin/CleverTapPlugin.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/android/src/main/java/com/clevertap/clevertap_plugin/CleverTapPlugin.java b/android/src/main/java/com/clevertap/clevertap_plugin/CleverTapPlugin.java index 4262298c..36678923 100644 --- a/android/src/main/java/com/clevertap/clevertap_plugin/CleverTapPlugin.java +++ b/android/src/main/java/com/clevertap/clevertap_plugin/CleverTapPlugin.java @@ -1817,7 +1817,7 @@ private void setLocation(MethodCall call, Result result) { } private void setMinimumFetchIntervalInSeconds(MethodCall call, Result result) { - long interval = call.argument("interval"); + int interval = call.argument("interval"); if (isCleverTapNotNull(cleverTapAPI)) { cleverTapAPI.productConfig().setMinimumFetchIntervalInSeconds(interval); result.success(null); From f5f9fd5739ba5dd9048709334090fb618c7c2c5c Mon Sep 17 00:00:00 2001 From: Anush-Shand <127097095+Anush-Shand@users.noreply.github.com> Date: Fri, 30 Aug 2024 11:04:43 +0530 Subject: [PATCH 09/16] task(SDK-3976) - Adds support for missing profileGetProperty (#247) * task(SDK-3976) - Adds support for missing profileGetProperty - Adds support in plugin.dart - Adds example usage to the example app * task(SDK-3976) - Adds support for missing profileGetProperty - Removes unnecessary changes * task(SDK-3976) - Adds support for missing profileGetProperty - Adds comments --- example/lib/main.dart | 23 +++++++++++++++++++++++ lib/clevertap_plugin.dart | 6 ++++++ 2 files changed, 29 insertions(+) diff --git a/example/lib/main.dart b/example/lib/main.dart index 03b885b9..99875f58 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -657,6 +657,17 @@ class _MyAppState extends State { ), ), ), + Card( + color: Colors.grey.shade300, + child: Padding( + padding: const EdgeInsets.all(4.0), + child: ListTile( + title: Text("Get Profile Property"), + subtitle: Text("Returns the specified Profile Property"), + onTap: getProfileProperty, + ), + ), + ), Card( color: Colors.grey.shade300, child: Padding( @@ -2200,6 +2211,18 @@ class _MyAppState extends State { }); } + void getProfileProperty() { + var propertyName = "Email"; + CleverTapPlugin.profileGetProperty(propertyName).then((prop) { + if(prop == null) { + showToast("Property not found"); + return; + } + showToast("Email Profile Property = " + prop.toString()); + print("Email Profile Property = " + prop.toString()); + }); + } + void onUserLogin() { var stuff = ["bags", "shoes"]; var profile = { diff --git a/lib/clevertap_plugin.dart b/lib/clevertap_plugin.dart index 62e349a1..0b048b63 100644 --- a/lib/clevertap_plugin.dart +++ b/lib/clevertap_plugin.dart @@ -611,6 +611,12 @@ class CleverTapPlugin { 'setLocation', {'latitude': latitude, 'longitude': longitude}); } + /// Returns the user profile property value for the specified key. + static Future profileGetProperty(String propertyName) async { + return await _dartToNativeMethodChannel + .invokeMethod('profileGetProperty', {'propertyName': propertyName}); + } + @Deprecated( "This method is deprecated since v1.3.0. Use getCleverTapID() instead") From 981f7e831da5691b90e70c27be990a1820f77963 Mon Sep 17 00:00:00 2001 From: Anush-Shand <127097095+Anush-Shand@users.noreply.github.com> Date: Fri, 30 Aug 2024 12:53:35 +0530 Subject: [PATCH 10/16] task(SDK-3974) - Fixes an issue where dates before 1970 were sent incorrectly to the BE (#245) - Sends the timestamp is seconds and not ms --- lib/clevertap_plugin.dart | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/clevertap_plugin.dart b/lib/clevertap_plugin.dart index 0b048b63..09fe9d15 100644 --- a/lib/clevertap_plugin.dart +++ b/lib/clevertap_plugin.dart @@ -1054,7 +1054,7 @@ class CleverTapPlugin { } static String getCleverTapDate(DateTime dateTime) { - return '\$D_' + dateTime.millisecondsSinceEpoch.toString(); + return '\$D_' + (dateTime.millisecondsSinceEpoch~/1000).toString(); } // Push Primer From 92f5045c9912970f04ce434faa190fd8169b06b1 Mon Sep 17 00:00:00 2001 From: KambleSonam Date: Mon, 2 Sep 2024 12:13:02 +0530 Subject: [PATCH 11/16] onVariableChanged and onValueChanged logic update and added condition in main.dart for workManager --- example/lib/main.dart | 2 +- lib/clevertap_plugin_web.dart | 10 ++++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/example/lib/main.dart b/example/lib/main.dart index 948ae325..8751f39a 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -47,7 +47,7 @@ void _firebaseForegroundMessageHandler(RemoteMessage remoteMessage) { void main() async { WidgetsFlutterBinding.ensureInitialized(); - if (!kIsWeb) { + if (!kIsWeb && !Platform.isIOS) { Workmanager().initialize( callbackDispatcher, // The top level function, aka callbackDispatcher isInDebugMode: diff --git a/lib/clevertap_plugin_web.dart b/lib/clevertap_plugin_web.dart index 681336a7..cbda8425 100644 --- a/lib/clevertap_plugin_web.dart +++ b/lib/clevertap_plugin_web.dart @@ -372,13 +372,19 @@ class CleverTapPluginWeb { static void onValueChanged( String name, CleverTapOnValueChangedHandler handler) { onValueChangedImpl(name, allowInterop((object) { - handler(js_util.dartify(object) as Map); + var dartObject = js_util.dartify(object); + var convertedMap = (dartObject as Map) + .map((key, value) => MapEntry(key.toString(), value as dynamic)); + handler(convertedMap.cast()); })); } static void onVariablesChanged(CleverTapOnVariablesChangedHandler handler) { onVariablesChangedImpl(allowInterop((object) { - handler(js_util.dartify(object) as Map); + var dartObject = js_util.dartify(object); + var convertedMap = (dartObject as Map) + .map((key, value) => MapEntry(key.toString(), value as dynamic)); + handler(convertedMap.cast()); })); } From ec492b924aaffebcbe41cb5923ac1f08db642950 Mon Sep 17 00:00:00 2001 From: KambleSonam Date: Mon, 2 Sep 2024 12:15:17 +0530 Subject: [PATCH 12/16] Updated release date --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 20875192..4858d523 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,6 @@ ## CHANGE LOG -### Version 2.4.1 *(28th August 2024)* +### Version 2.4.1 *(2nd September 2024)* ------------------------------------------- **Bug Fixes** * **[Web Platform]** From 1340c3429026cd205dd152b084cc47448928bc8f Mon Sep 17 00:00:00 2001 From: Nishant Kumar Date: Mon, 2 Sep 2024 13:09:47 +0530 Subject: [PATCH 13/16] Removed iOS platform check as it is already added in web PR. --- example/lib/main.dart | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/example/lib/main.dart b/example/lib/main.dart index 68b2871d..03b885b9 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -46,20 +46,18 @@ void _firebaseForegroundMessageHandler(RemoteMessage remoteMessage) { void main() async { WidgetsFlutterBinding.ensureInitialized(); - if (!Platform.isIOS) { - Workmanager().initialize( - callbackDispatcher, // The top level function, aka callbackDispatcher - isInDebugMode: true // If enabled it will post a notification whenever the task is running. Handy for debugging tasks - ); - Workmanager().registerOneOffTask( - "periodic-task-identifier", - "simplePeriodicTask" - ); + Workmanager().initialize( + callbackDispatcher, // The top level function, aka callbackDispatcher + isInDebugMode: true // If enabled it will post a notification whenever the task is running. Handy for debugging tasks + ); + Workmanager().registerOneOffTask( + "periodic-task-identifier", + "simplePeriodicTask" + ); - await Firebase.initializeApp(); - FirebaseMessaging.onMessage.listen(_firebaseForegroundMessageHandler); - FirebaseMessaging.onBackgroundMessage(_firebaseBackgroundMessageHandler); - } + await Firebase.initializeApp(); + FirebaseMessaging.onMessage.listen(_firebaseForegroundMessageHandler); + FirebaseMessaging.onBackgroundMessage(_firebaseBackgroundMessageHandler); CleverTapPlugin.onKilledStateNotificationClicked( onKilledStateNotificationClickedHandler); From a3bf91fde1e469dda9e9fb47a8a36b1ee3eb7f58 Mon Sep 17 00:00:00 2001 From: KambleSonam Date: Mon, 2 Sep 2024 15:04:39 +0530 Subject: [PATCH 14/16] created a wrapper to handle conditional imports --- lib/clevertap_plugin.dart | 2 +- lib/clevertap_plugin_web_wrapper.dart | 2 ++ lib/src/clevertap_plugin_web_stub.dart | 11 +++++++++++ 3 files changed, 14 insertions(+), 1 deletion(-) create mode 100644 lib/clevertap_plugin_web_wrapper.dart create mode 100644 lib/src/clevertap_plugin_web_stub.dart diff --git a/lib/clevertap_plugin.dart b/lib/clevertap_plugin.dart index 1ac8605a..0a7e51c4 100644 --- a/lib/clevertap_plugin.dart +++ b/lib/clevertap_plugin.dart @@ -1,7 +1,7 @@ import 'dart:async'; import 'dart:ui'; -import 'package:clevertap_plugin/clevertap_plugin_web.dart'; +import 'package:clevertap_plugin/clevertap_plugin_web_wrapper.dart'; import 'package:clevertap_plugin/src/types.dart'; import 'package:clevertap_plugin/src/typedefs.dart'; import 'package:flutter/foundation.dart'; diff --git a/lib/clevertap_plugin_web_wrapper.dart b/lib/clevertap_plugin_web_wrapper.dart new file mode 100644 index 00000000..c42ced9a --- /dev/null +++ b/lib/clevertap_plugin_web_wrapper.dart @@ -0,0 +1,2 @@ +export 'src/clevertap_plugin_web_stub.dart' + if (dart.library.html) 'package:clevertap_plugin/clevertap_plugin_web.dart'; diff --git a/lib/src/clevertap_plugin_web_stub.dart b/lib/src/clevertap_plugin_web_stub.dart new file mode 100644 index 00000000..e3484019 --- /dev/null +++ b/lib/src/clevertap_plugin_web_stub.dart @@ -0,0 +1,11 @@ +import 'package:clevertap_plugin/src/typedefs.dart'; + +class CleverTapPluginWeb { + static void onValueChanged( + String name, CleverTapOnValueChangedHandler handler) {} + + static void onVariablesChanged(CleverTapOnVariablesChangedHandler handler) {} + + static void addKVDataChangeListener( + CleverTapOnKVDataChangedHandler handler) {} +} From 975a0849b3b212f9ca687d3b3b4e70d2c6bbcd2f Mon Sep 17 00:00:00 2001 From: Anush-Shand <127097095+Anush-Shand@users.noreply.github.com> Date: Mon, 2 Sep 2024 16:03:10 +0530 Subject: [PATCH 15/16] docs - Adds docs for v2.4.1 android (#255) * docs - Adds docs for v2.4.1 android * docs - Adds docs for v2.4.1 - Adds change related to iOS * docs - Adds docs for v2.4.1 - Adds change related to iOS * Added docs for iOS platform thread fix. --------- Co-authored-by: Nishant Kumar --- CHANGELOG.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4858d523..18252f71 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ * Adds the method 'addKVDataChangeListener()' to get the custom KV Pair data * Supports [CleverTap Web SDK v1.9.0](https://github.com/CleverTap/clevertap-web-sdk/releases/tag/v1.9.0) +* **[Android Platform]** + * Fixes a date conversion issue for dates before January 1, 1970. + * Fixes a `ClassCastException` for `setMinimumFetchIntervalInSeconds` in `ProductConfig`. + * Fixes the missing support for `profileGetProperty`. + +* **[iOS Platform]** + * Fixes iOS platform channel messages must be sent on the platform thread issue. + * Fixes the missing support for `profileGetProperty`. + ### Version 2.4.0 *(10th May 2024)* ------------------------------------------- **What's new** From 69e3b715c2977306f9b8ceeecc90cf54d968adff Mon Sep 17 00:00:00 2001 From: KambleSonam Date: Mon, 2 Sep 2024 16:16:45 +0530 Subject: [PATCH 16/16] Added support to web sdk version v1.9.1 --- CHANGELOG.md | 2 +- assets/clevertap.js | 43 +++++++++++++++++++++++++++++++++---------- 2 files changed, 34 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 18252f71..2ab2ab3d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,7 +5,7 @@ **Bug Fixes** * **[Web Platform]** * Adds the method 'addKVDataChangeListener()' to get the custom KV Pair data - * Supports [CleverTap Web SDK v1.9.0](https://github.com/CleverTap/clevertap-web-sdk/releases/tag/v1.9.0) + * Supports [CleverTap Web SDK v1.9.1](https://github.com/CleverTap/clevertap-web-sdk/releases/tag/v1.9.1) * **[Android Platform]** * Fixes a date conversion issue for dates before January 1, 1970. diff --git a/assets/clevertap.js b/assets/clevertap.js index 7728d672..0c06c376 100644 --- a/assets/clevertap.js +++ b/assets/clevertap.js @@ -4544,7 +4544,10 @@ window.addEventListener('message', handleMessageEvent, false); if (parentWindow) { - parentWindow.postMessage('builder', '*'); + parentWindow.postMessage({ + message: 'builder', + originUrl: window.location.href + }, '*'); } return; @@ -4554,20 +4557,31 @@ window.addEventListener('message', handleMessageEvent, false); if (parentWindow) { - parentWindow.postMessage('preview', '*'); + parentWindow.postMessage({ + message: 'preview', + originUrl: window.location.href + }, '*'); } } }; const handleMessageEvent = event => { - if (event.data && event.data.message) { - if (event.data.message === 'Dashboard' && event.data.url) { - var _event$data$variant, _event$data$details; + if (event.data && isValidUrl(event.data.originUrl)) { + const msgOrigin = new URL(event.data.originUrl).origin; - initialiseCTBuilder(event.data.url, (_event$data$variant = event.data.variant) !== null && _event$data$variant !== void 0 ? _event$data$variant : null, (_event$data$details = event.data.details) !== null && _event$data$details !== void 0 ? _event$data$details : {}); - } else if (event.data.message === 'Overlay') { - renderVisualBuilder(event.data, true); + if (event.origin !== msgOrigin) { + return; } + } else { + return; + } + + if (event.data.message === 'Dashboard') { + var _event$data$variant, _event$data$details; + + initialiseCTBuilder(event.data.url, (_event$data$variant = event.data.variant) !== null && _event$data$variant !== void 0 ? _event$data$variant : null, (_event$data$details = event.data.details) !== null && _event$data$details !== void 0 ? _event$data$details : {}); + } else if (event.data.message === 'Overlay') { + renderVisualBuilder(event.data, true); } }; /** @@ -4779,6 +4793,15 @@ document.dispatchEvent(kvPairsEvent); } + function isValidUrl(string) { + try { + const url = new URL(string); + return Boolean(url); + } catch (_err) { + return false; + } + } + const _tr = (msg, _ref) => { let { device, @@ -6221,7 +6244,7 @@ let proto = document.location.protocol; proto = proto.replace(':', ''); dataObject.af = { ...dataObject.af, - lib: 'web-sdk-v1.9.0', + lib: 'web-sdk-v1.9.1', protocol: proto, ...$ct.flutterVersion }; // app fields @@ -8387,7 +8410,7 @@ } getSDKVersion() { - return 'web-sdk-v1.9.0'; + return 'web-sdk-v1.9.1'; } defineVariable(name, defaultValue) {