PageSourceSearch

https://weather.com/wx-next-web/static/vendor/@mparticle/[email protected]/dist/mparticle.min.js

js weather.com collected 2026-10-09 21:28:56 UTC 494,951 bytes, 11,623 lines download raw bytes

1"use strict";
2var mParticle = (function() {
3  var Base64$1 = {
4    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
5    // Input must be a string
6    encode: function encode(input) {
7      try {
8        if (window.btoa && window.atob) {
9          return window.btoa(unescape(encodeURIComponent(input)));
10        }
11      } catch (e) {
12        console.error("Error encoding cookie values into Base64:" + e);
13      }
14      return this._encode(input);
15    },
16    _encode: function _encode(input) {
17      var output = "";
18      var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
19      var i = 0;
20      input = UTF8.encode(input);
21      while (i < input.length) {
22        chr1 = input.charCodeAt(i++);
23        chr2 = input.charCodeAt(i++);
24        chr3 = input.charCodeAt(i++);
25        enc1 = chr1 >> 2;
26        enc2 = (chr1 & 3) << 4 | chr2 >> 4;
27        enc3 = (chr2 & 15) << 2 | chr3 >> 6;
28        enc4 = chr3 & 63;
29        if (isNaN(chr2)) {
30          enc3 = enc4 = 64;
31        } else if (isNaN(chr3)) {
32          enc4 = 64;
33        }
34        output = output + Base64$1._keyStr.charAt(enc1) + Base64$1._keyStr.charAt(enc2) + Base64$1._keyStr.charAt(enc3) + Base64$1._keyStr.charAt(enc4);
35      }
36      return output;
37    },
38    decode: function decode(input) {
39      try {
40        if (window.btoa && window.atob) {
41          return decodeURIComponent(escape(window.atob(input)));
42        }
43      } catch (e) {
44      }
45      return Base64$1._decode(input);
46    },
47    _decode: function _decode(input) {
48      var output = "";
49      var chr1, chr2, chr3;
50      var enc1, enc2, enc3, enc4;
51      var i = 0;
52      input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
53      while (i < input.length) {
54        enc1 = Base64$1._keyStr.indexOf(input.charAt(i++));
55        enc2 = Base64$1._keyStr.indexOf(input.charAt(i++));
56        enc3 = Base64$1._keyStr.indexOf(input.charAt(i++));
57        enc4 = Base64$1._keyStr.indexOf(input.charAt(i++));
58        chr1 = enc1 << 2 | enc2 >> 4;
59        chr2 = (enc2 & 15) << 4 | enc3 >> 2;
60        chr3 = (enc3 & 3) << 6 | enc4;
61        output = output + String.fromCharCode(chr1);
62        if (enc3 !== 64) {
63          output = output + String.fromCharCode(chr2);
64        }
65        if (enc4 !== 64) {
66          output = output + String.fromCharCode(chr3);
67        }
68      }
69      output = UTF8.decode(output);
70      return output;
71    }
72  };
73  var UTF8 = {
74    encode: function encode(s) {
75      var utftext = "";
76      for (var n = 0; n < s.length; n++) {
77        var c = s.charCodeAt(n);
78        if (c < 128) {
79          utftext += String.fromCharCode(c);
80        } else if (c > 127 && c < 2048) {
81          utftext += String.fromCharCode(c >> 6 | 192);
82          utftext += String.fromCharCode(c & 63 | 128);
83        } else {
84          utftext += String.fromCharCode(c >> 12 | 224);
85          utftext += String.fromCharCode(c >> 6 & 63 | 128);
86          utftext += String.fromCharCode(c & 63 | 128);
87        }
88      }
89      return utftext;
90    },
91    decode: function decode(utftext) {
92      var s = "";
93      var i = 0;
94      var c = 0, c1 = 0, c2 = 0;
95      while (i < utftext.length) {
96        c = utftext.charCodeAt(i);
97        if (c < 128) {
98          s += String.fromCharCode(c);
99          i++;
100        } else if (c > 191 && c < 224) {
101          c1 = utftext.charCodeAt(i + 1);
102          s += String.fromCharCode((c & 31) << 6 | c1 & 63);
103          i += 2;
104        } else {
105          c1 = utftext.charCodeAt(i + 1);
106          c2 = utftext.charCodeAt(i + 2);
107          s += String.fromCharCode((c & 15) << 12 | (c1 & 63) << 6 | c2 & 63);
108          i += 3;
109        }
110      }
111      return s;
112    }
113  };
114  var Polyfill = {
115    // forEach polyfill
116    // Production steps of ECMA-262, Edition 5, 15.4.4.18
117    // Reference: http://es5.github.io/#x15.4.4.18
118    forEach: function forEach(callback, thisArg) {
119      var T, k;
120      if (this == null) {
121        throw new TypeError(" this is null or not defined");
122      }
123      var O = Object(this);
124      var len = O.length >>> 0;
125      if (typeof callback !== "function") {
126        throw new TypeError(callback + " is not a function");
127      }
128      if (arguments.length > 1) {
129        T = thisArg;
130      }
131      k = 0;
132      while (k < len) {
133        var kValue = void 0;
134        if (k in O) {
135          kValue = O[k];
136          callback.call(T, kValue, k, O);
137        }
138        k++;
139      }
140    },
141    // map polyfill
142    // Production steps of ECMA-262, Edition 5, 15.4.4.19
143    // Reference: http://es5.github.io/#x15.4.4.19
144    map: function map(callback, thisArg) {
145      var T, A, k;
146      if (this === null) {
147        throw new TypeError(" this is null or not defined");
148      }
149      var O = Object(this);
150      var len = O.length >>> 0;
151      if (typeof callback !== "function") {
152        throw new TypeError(callback + " is not a function");
153      }
154      if (arguments.length > 1) {
155        T = thisArg;
156      }
157      A = new Array(len);
158      k = 0;
159      while (k < len) {
160        var kValue = void 0, mappedValue = void 0;
161        if (k in O) {
162          kValue = O[k];
163          mappedValue = callback.call(T, kValue, k, O);
164          A[k] = mappedValue;
165        }
166        k++;
167      }
168      return A;
169    },
170    // filter polyfill
171    // Prodcution steps of ECMA-262, Edition 5
172    // Reference: http://es5.github.io/#x15.4.4.20
173    filter: function filter(fun) {
174      if (this === void 0 || this === null) {
175        throw new TypeError();
176      }
177      var t = Object(this);
178      var len = t.length >>> 0;
179      if (typeof fun !== "function") {
180        throw new TypeError();
181      }
182      var res = [];
183      var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
184      for (var i = 0; i < len; i++) {
185        if (i in t) {
186          var val = t[i];
187          if (fun.call(thisArg, val, i, t)) {
188            res.push(val);
189          }
190        }
191      }
192      return res;
193    },
194    // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray
195    isArray: function isArray(arg) {
196      return Object.prototype.toString.call(arg) === "[object Array]";
197    },
198    Base64: Base64$1
199  };
200  var version = "2.81.0";
201  var Constants = {
202    sdkVersion: version,
203    sdkVendor: "mparticle",
204    platform: "web",
205    Messages: {
206      DeprecationMessages: {
207        MethodHasBeenDeprecated: "has been deprecated.",
208        MethodMarkedForDeprecationPostfix: "is a deprecated method and will be removed in future releases.",
209        AlternativeMethodPrefix: "Please use the alternate method:"
210      },
211      ErrorMessages: {
212        NoToken: "A token must be specified.",
213        EventNameInvalidType: "Event name must be a valid string value.",
214        EventDataInvalidType: "Event data must be a valid object hash.",
215        LoggingDisabled: "Event logging is currently disabled.",
216        CookieParseError: "Could not parse cookie",
217        EventEmpty: "Event object is null or undefined, cancelling send",
218        APIRequestEmpty: "APIRequest is null or undefined, cancelling send",
219        NoEventType: "Event type must be specified.",
220        TransactionIdRequired: "Transaction ID is required",
221        TransactionRequired: "A transaction attributes object is required",
222        PromotionIdRequired: "Promotion ID is required",
223        BadAttribute: "Attribute value cannot be object or array",
224        BadKey: "Key value cannot be object or array",
225        BadLogPurchase: "Transaction attributes and a product are both required to log a purchase, https://docs.mparticle.com/?javascript#measuring-transactions",
226        AudienceAPINotEnabled: "Your workspace is not enabled to retrieve user audiences."
227      },
228      InformationMessages: {
229        CookieSearch: "Searching for cookie",
230        CookieFound: "Cookie found, parsing values",
231        CookieNotFound: "Cookies not found",
232        CookieSet: "Setting cookie",
233        CookieSync: "Performing cookie sync",
234        SendBegin: "Starting to send event",
235        SendIdentityBegin: "Starting to send event to identity server",
236        SendWindowsPhone: "Sending event to Windows Phone container",
237        SendIOS: "Calling iOS path: ",
238        SendAndroid: "Calling Android JS interface method: ",
239        SendHttp: "Sending event to mParticle HTTP service",
240        SendAliasHttp: "Sending alias request to mParticle HTTP service",
241        SendIdentityHttp: "Sending event to mParticle HTTP service",
242        StartingNewSession: "Starting new Session",
243        StartingLogEvent: "Starting to log event",
244        StartingLogOptOut: "Starting to log user opt in/out",
245        StartingEndSession: "Starting to end session",
246        StartingInitialization: "Starting to initialize",
247        StartingLogCommerceEvent: "Starting to log commerce event",
248        StartingAliasRequest: "Starting to Alias MPIDs",
249        LoadingConfig: "Loading configuration options",
250        AbandonLogEvent: "Cannot log event, logging disabled or developer token not set",
251        AbandonAliasUsers: "Cannot Alias Users, logging disabled or developer token not set",
252        AbandonStartSession: "Cannot start session, logging disabled or developer token not set",
253        AbandonEndSession: "Cannot end session, logging disabled or developer token not set",
254        NoSessionToEnd: "Cannot end session, no active session found"
255      },
256      ValidationMessages: {
257        ModifyIdentityRequestUserIdentitiesPresent: "identityRequests to modify require userIdentities to be present. Request not sent to server. Please fix and try again",
258        IdentityRequesetInvalidKey: "There is an invalid key on your identityRequest object. It can only contain a `userIdentities` object and a `onUserAlias` function. Request not sent to server. Please fix and try again.",
259        OnUserAliasType: "The onUserAlias value must be a function.",
260        UserIdentities: "The userIdentities key must be an object with keys of identityTypes and values of strings. Request not sent to server. Please fix and try again.",
261        UserIdentitiesInvalidKey: "There is an invalid identity key on your `userIdentities` object within the identityRequest. Request not sent to server. Please fix and try again.",
262        UserIdentitiesInvalidValues: "All user identity values must be strings or null. Request not sent to server. Please fix and try again.",
263        AliasMissingMpid: "Alias Request must contain both a destinationMpid and a sourceMpid",
264        AliasNonUniqueMpid: "Alias Request's destinationMpid and sourceMpid must be unique",
265        AliasMissingTime: "Alias Request must have both a startTime and an endTime",
266        AliasStartBeforeEndTime: "Alias Request's endTime must be later than its startTime"
267      }
268    },
269    NativeSdkPaths: {
270      LogEvent: "logEvent",
271      SetUserTag: "setUserTag",
272      RemoveUserTag: "removeUserTag",
273      SetUserAttribute: "setUserAttribute",
274      RemoveUserAttribute: "removeUserAttribute",
275      SetSessionAttribute: "setSessionAttribute",
276      AddToCart: "addToCart",
277      RemoveFromCart: "removeFromCart",
278      ClearCart: "clearCart",
279      LogOut: "logOut",
280      SetUserAttributeList: "setUserAttributeList",
281      RemoveAllUserAttributes: "removeAllUserAttributes",
282      GetUserAttributesLists: "getUserAttributesLists",
283      GetAllUserAttributes: "getAllUserAttributes",
284      Identify: "identify",
285      Logout: "logout",
286      Login: "login",
287      Modify: "modify",
288      Alias: "aliasUsers",
289      Upload: "upload"
290    },
291    StorageNames: {
292      localStorageName: "mprtcl-api",
293      localStorageNameV3: "mprtcl-v3",
294      cookieName: "mprtcl-api",
295      cookieNameV2: "mprtcl-v2",
296      cookieNameV3: "mprtcl-v3",
297      localStorageNameV4: "mprtcl-v4",
298      localStorageProductsV4: "mprtcl-prodv4",
299      cookieNameV4: "mprtcl-v4",
300      currentStorageName: "mprtcl-v4",
301      currentStorageProductsName: "mprtcl-prodv4"
302    },
303    DefaultConfig: {
304      cookieDomain: null,
305      cookieExpiration: 365,
306      logLevel: null,
307      timeout: 300,
308      sessionTimeout: 30,
309      maxProducts: 20,
310      forwarderStatsTimeout: 5e3,
311      integrationDelayTimeout: 5e3,
312      maxCookieSize: 3e3,
313      aliasMaxWindow: 90,
314      uploadInterval: 0
315      // Maximum milliseconds in between batch uploads, below 500 will mean immediate upload.  The server returns this as a string, but we are using it as a number internally
316    },
317    DefaultBaseUrls: {
318      v1SecureServiceUrl: "jssdks.mparticle.com/v1/JS/",
319      v2SecureServiceUrl: "jssdks.mparticle.com/v2/JS/",
320      v3SecureServiceUrl: "jssdks.mparticle.com/v3/JS/",
321      configUrl: "jssdkcdns.mparticle.com/JS/v2/",
322      identityUrl: "identity.mparticle.com/v1/",
323      aliasUrl: "jssdks.mparticle.com/v1/identity/",
324      userAudienceUrl: "nativesdks.mparticle.com/v1/"
325    },
326    // These are the paths that are used to construct the CNAME urls
327    CNAMEUrlPaths: {
328      v1SecureServiceUrl: "/webevents/v1/JS/",
329      v2SecureServiceUrl: "/webevents/v2/JS/",
330      v3SecureServiceUrl: "/webevents/v3/JS/",
331      configUrl: "/tags/JS/v2/",
332      identityUrl: "/identity/v1/",
333      aliasUrl: "/webevents/v1/identity/"
334    },
335    Base64CookieKeys: {
336      csm: 1,
337      sa: 1,
338      ss: 1,
339      lsa: 1,
340      ua: 1,
341      ui: 1,
342      csd: 1,
343      ia: 1,
344      con: 1
345    },
346    // https://go.mparticle.com/work/SQDSDKS-6039
347    SDKv2NonMPIDCookieKeys: {
348      gs: 1,
349      cu: 1,
350      l: 1,
351      globalSettings: 1,
352      currentUserMPID: 1
353    },
354    HTTPCodes: {
355      noHttpCoverage: -1,
356      activeIdentityRequest: -2,
357      activeSession: -3,
358      validationIssue: -4,
359      nativeIdentityRequest: -5,
360      loggingDisabledOrMissingAPIKey: -6,
361      tooManyRequests: 429
362    },
363    FeatureFlags: {
364      ReportBatching: "reportBatching",
365      EventBatchingIntervalMillis: "eventBatchingIntervalMillis",
366      OfflineStorage: "offlineStorage",
367      DirectUrlRouting: "directURLRouting",
368      CacheIdentity: "cacheIdentity",
369      AudienceAPI: "audienceAPI",
370      // CaptureIntegrationSpecificIds (legacy): boolean flag from server/UI
371      //   - 'True'  → capture all integration-specific IDs
372      //   - 'False' → capture none
373      CaptureIntegrationSpecificIds: "captureIntegrationSpecificIds",
374      // CaptureIntegrationSpecificIdsV2 (new): string mode from server
375      //   - 'all'      → capture all IDs
376      //   - 'none'     → capture none
377      //   - 'roktonly' → capture only Rokt-related IDs
378      CaptureIntegrationSpecificIdsV2: "captureIntegrationSpecificIds.V2",
379      AstBackgroundEvents: "astBackgroundEvents",
380      AutoLogPageView: "autoLogPageView"
381    },
382    DefaultInstance: "default_instance",
383    CCPAPurpose: "data_sale_opt_out",
384    IdentityMethods: {
385      Modify: "modify",
386      Logout: "logout",
387      Login: "login",
388      Identify: "identify"
389    },
390    Environment: {
391      Development: "development",
392      Production: "production"
393    },
394    CaptureIntegrationSpecificIdsV2Modes: {
395      All: "all",
396      None: "none",
397      RoktOnly: "roktonly"
398    },
399    Rokt: {
400      LauncherInstanceGuidKey: "__rokt_li_guid__"
401    }
402  };
403  var ONE_DAY_IN_SECONDS = 60 * 60 * 24;
404  var MILLIS_IN_ONE_SEC = 1e3;
405  var NO_TARGETING_ATTRIBUTE = "$NoTargeting";
406  var HTTP_OK = 200;
407  var HTTP_ACCEPTED = 202;
408  var HTTP_BAD_REQUEST = 400;
409  var HTTP_NOT_FOUND = 404;
410  var HTTP_SERVER_ERROR = 500;
411  function _typeof(o) {
412    "@babel/helpers - typeof";
413    return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(o2) {
414      return typeof o2;
415    } : function(o2) {
416      return o2 && "function" == typeof Symbol && o2.constructor === Symbol && o2 !== Symbol.prototype ? "symbol" : typeof o2;
417    }, _typeof(o);
418  }
419  var extendStatics = function(d, b) {
420    extendStatics = Object.setPrototypeOf || { __proto__: [] } instanceof Array && function(d2, b2) {
421      d2.__proto__ = b2;
422    } || function(d2, b2) {
423      for (var p in b2) if (Object.prototype.hasOwnProperty.call(b2, p)) d2[p] = b2[p];
424    };
425    return extendStatics(d, b);
426  };
427  function __extends(d, b) {
428    if (typeof b !== "function" && b !== null)
429      throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
430    extendStatics(d, b);
431    function __() {
432      this.constructor = d;
433    }
434    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
435  }
436  var __assign = function() {
437    __assign = Object.assign || function __assign2(t) {
438      for (var s, i = 1, n = arguments.length; i < n; i++) {
439        s = arguments[i];
440        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
441      }
442      return t;
443    };
444    return __assign.apply(this, arguments);
445  };
446  function __awaiter(thisArg, _arguments, P, generator) {
447    function adopt(value) {
448      return value instanceof P ? value : new P(function(resolve) {
449        resolve(value);
450      });
451    }
452    return new (P || (P = Promise))(function(resolve, reject) {
453      function fulfilled(value) {
454        try {
455          step(generator.next(value));
456        } catch (e) {
457          reject(e);
458        }
459      }
460      function rejected(value) {
461        try {
462          step(generator["throw"](value));
463        } catch (e) {
464          reject(e);
465        }
466      }
467      function step(result) {
468        result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected);
469      }
470      step((generator = generator.apply(thisArg, _arguments || [])).next());
471    });
472  }
473  function __generator(thisArg, body) {
474    var _ = { label: 0, sent: function() {
475      if (t[0] & 1) throw t[1];
476      return t[1];
477    }, trys: [], ops: [] }, f, y, t, g;
478    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() {
479      return this;
480    }), g;
481    function verb(n) {
482      return function(v) {
483        return step([n, v]);
484      };
485    }
486    function step(op) {
487      if (f) throw new TypeError("Generator is already executing.");
488      while (g && (g = 0, op[0] && (_ = 0)), _) try {
489        if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
490        if (y = 0, t) op = [op[0] & 2, t.value];
491        switch (op[0]) {
492          case 0:
493          case 1:
494            t = op;
495            break;
496          case 4:
497            _.label++;
498            return { value: op[1], done: false };
499          case 5:
500            _.label++;
501            y = op[1];
502            op = [0];
503            continue;
504          case 7:
505            op = _.ops.pop();
506            _.trys.pop();
507            continue;
508          default:
509            if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
510              _ = 0;
511              continue;
512            }
513            if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {
514              _.label = op[1];
515              break;
516            }
517            if (op[0] === 6 && _.label < t[1]) {
518              _.label = t[1];
519              t = op;
520              break;
521            }
522            if (t && _.label < t[2]) {
523              _.label = t[2];
524              _.ops.push(op);
525              break;
526            }
527            if (t[2]) _.ops.pop();
528            _.trys.pop();
529            continue;
530        }
531        op = body.call(thisArg, _);
532      } catch (e) {
533        op = [6, e];
534        y = 0;
535      } finally {
536        f = t = 0;
537      }
538      if (op[0] & 5) throw op[1];
539      return { value: op[0] ? op[1] : void 0, done: true };
540    }
541  }
542  function __spreadArray(to, from, pack) {
543    if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
544      if (ar || !(i in from)) {
545        if (!ar) ar = Array.prototype.slice.call(from, 0, i);
546        ar[i] = from[i];
547      }
548    }
549    return to.concat(ar || Array.prototype.slice.call(from));
550  }
551  typeof SuppressedError === "function" ? SuppressedError : function(error, suppressed, message) {
552    var e = new Error(message);
553    return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
554  };
555  var Messages$a = Constants.Messages;
556  var createCookieString = function createCookieString2(value) {
557    return replaceCommasWithPipes(replaceQuotesWithApostrophes(value));
558  };
559  var revertCookieString = function revertCookieString2(value) {
560    return replacePipesWithCommas(replaceApostrophesWithQuotes(value));
561  };
562  var inArray = function inArray2(items, name) {
563    if (!items) {
564      return false;
565    }
566    var i = 0;
567    if (Array.prototype.indexOf) {
568      return items.indexOf(name, 0) >= 0;
569    } else {
570      for (var n = items.length; i < n; i++) {
571        if (i in items && items[i] === name) {
572          return true;
573        }
574      }
575    }
576    return false;
577  };
578  var findKeyInObject = function findKeyInObject2(obj, key) {
579    if (key && obj) {
580      for (var prop in obj) {
581        if (obj.hasOwnProperty(prop) && prop.toLowerCase() === key.toLowerCase()) {
582          return prop;
583        }
584      }
585    }
586    return null;
587  };
588  var generateDeprecationMessage = function generateDeprecationMessage2(methodName, isDeprecated, alternateMethod, docsUrl) {
589    var messageArray = [methodName];
590    if (isDeprecated) {
591      messageArray.push(Messages$a.DeprecationMessages.MethodHasBeenDeprecated);
592    } else {
593      messageArray.push(Messages$a.DeprecationMessages.MethodMarkedForDeprecationPostfix);
594    }
595    if (alternateMethod) {
596      messageArray.push(Messages$a.DeprecationMessages.AlternativeMethodPrefix);
597      messageArray.push(alternateMethod + ".");
598    }
599    if (docsUrl) {
600      messageArray.push("See - " + docsUrl);
601    }
602    return messageArray.join(" ");
603  };
604  function generateHash(name) {
605    var hash = 0;
606    var character;
607    if (name === void 0 || name === null) {
608      return 0;
609    }
610    name = name.toString().toLowerCase();
611    if (Array.prototype.reduce) {
612      return name.split("").reduce(function(a, b) {
613        a = (a << 5) - a + b.charCodeAt(0);
614        return a & a;
615      }, 0);
616    }
617    if (name.length === 0) {
618      return hash;
619    }
620    for (var i = 0; i < name.length; i++) {
621      character = name.charCodeAt(i);
622      hash = (hash << 5) - hash + character;
623      hash = hash & hash;
624    }
625    return hash;
626  }
627  var generateRandomValue = function generateRandomValue2(value) {
628    var randomValue;
629    var a;
630    if (window.crypto && window.crypto.getRandomValues) {
631      randomValue = window.crypto.getRandomValues(new Uint8Array(1));
632    }
633    if (randomValue) {
634      return (a ^ randomValue[0] % 16 >> a / 4).toString(16);
635    }
636    return (a ^ Math.random() * 16 >> a / 4).toString(16);
637  };
638  var generateUniqueId = function generateUniqueId2(a) {
639    if (a === void 0) {
640      a = "";
641    }
642    return a ? generateRandomValue() : (
643      // [1e7] -> // 10000000 +
644      // -1e3  -> // -1000 +
645      // -4e3  -> // -4000 +
646      // -8e3  -> // -80000000 +
647      // -1e11 -> //-100000000000,
648      "".concat(1e7, "-").concat(1e3, "-").concat(4e3, "-").concat(8e3, "-").concat(1e11).replace(
649        /[018]/g,
650        // zeroes, ones, and eights with
651        generateUniqueId2
652        // random hex digits
653      )
654    );
655  };
656  var getRampNumber = function getRampNumber2(value) {
657    if (!value) {
658      return 100;
659    }
660    var hash = generateHash(value);
661    return Math.abs(hash % 100) + 1;
662  };
663  var isObject = function isObject2(value) {
664    var objType = Object.prototype.toString.call(value);
665    return objType === "[object Object]" || objType === "[object Error]";
666  };
667  var parseNumber = function parseNumber2(value) {
668    if (isNaN(value) || !isFinite(value)) {
669      return 0;
670    }
671    var floatValue = parseFloat(value);
672    return isNaN(floatValue) ? 0 : floatValue;
673  };
674  var parseSettingsString = function parseSettingsString2(settingsString) {
675    try {
676      return settingsString ? JSON.parse(settingsString.replace(/&quot;/g, '"')) : [];
677    } catch (error) {
678      throw new Error("Settings string contains invalid JSON");
679    }
680  };
681  var parseStringOrNumber = function parseStringOrNumber2(value) {
682    if (isStringOrNumber(value)) {
683      return value;
684    } else {
685      return null;
686    }
687  };
688  var replaceCommasWithPipes = function replaceCommasWithPipes2(value) {
689    return value.replace(/,/g, "|");
690  };
691  var replacePipesWithCommas = function replacePipesWithCommas2(value) {
692    return value.replace(/\|/g, ",");
693  };
694  var replaceApostrophesWithQuotes = function replaceApostrophesWithQuotes2(value) {
695    return value.replace(/\'/g, '"');
696  };
697  var replaceQuotesWithApostrophes = function replaceQuotesWithApostrophes2(value) {
698    return value.replace(/\"/g, "'");
699  };
700  var replaceMPID = function replaceMPID2(value, mpid) {
701    return value.replace("%%mpid%%", mpid);
702  };
703  var replaceAmpWithAmpersand = function replaceAmpWithAmpersand2(value) {
704    return value.replace(/&amp;/g, "&");
705  };
706  var createCookieSyncUrl = function createCookieSyncUrl2(mpid, pixelUrl, redirectUrl, domain, base64Mpid) {
707    var modifiedPixelUrl = replaceAmpWithAmpersand(pixelUrl);
708    var modifiedDirectUrl = redirectUrl ? replaceAmpWithAmpersand(redirectUrl) : null;
709    var url = replaceMPID(modifiedPixelUrl, mpid);
710    var redirect = modifiedDirectUrl ? replaceMPID(modifiedDirectUrl, mpid) : "";
711    var fullUrl = url + encodeURIComponent(redirect);
712    if (domain) {
713      var separator = fullUrl.includes("?") ? "&" : "?";
714      fullUrl += "".concat(separator, "domain=").concat(domain);
715    }
716    if (base64Mpid) {
717      var separator = fullUrl.includes("?") ? "&" : "?";
718      fullUrl += "".concat(separator, "google_hm=").concat(base64Mpid);
719    }
720    return fullUrl;
721  };
722  var WEB_SAFE_BASE64_REPLACEMENTS = {
723    "+": "-",
724    "/": "_",
725    "=": ""
726  };
727  var toWebSafeBase64 = function toWebSafeBase642(value) {
728    return btoa(value).replace(/[+/=]/g, function(c) {
729      return WEB_SAFE_BASE64_REPLACEMENTS[c];
730    });
731  };
732  var returnConvertedBoolean = function returnConvertedBoolean2(data) {
733    if (data === "false" || data === "0") {
734      return false;
735    } else {
736      return Boolean(data);
737    }
738  };
739  var decoded = function decoded2(s) {
740    return decodeURIComponent(s.replace(/\+/g, " "));
741  };
742  var converted = function converted2(s) {
743    if (s.indexOf('"') === 0) {
744      s = s.slice(1, -1).replace(/\\"/g, '"').replace(/\\\\/g, "\\");
745    }
746    return s;
747  };
748  var isString = function isString2(value) {
749    return typeof value === "string";
750  };
751  var isNumber = function isNumber2(value) {
752    return typeof value === "number";
753  };
754  var isBoolean = function isBoolean2(value) {
755    return typeof value === "boolean";
756  };
757  var isFunction = function isFunction2(fn) {
758    return typeof fn === "function";
759  };
760  var isValidAttributeValue = function isValidAttributeValue2(value) {
761    return value !== void 0 && !isObject(value) && !Array.isArray(value);
762  };
763  var isValidCustomFlagProperty = function isValidCustomFlagProperty2(value) {
764    return isNumber(value) || isString(value) || isBoolean(value);
765  };
766  var toDataPlanSlug = function toDataPlanSlug2(value) {
767    return isStringOrNumber(value) ? value.toString().toLowerCase().replace(/[^0-9a-zA-Z]+/g, "_") : "";
768  };
769  var isDataPlanSlug = function isDataPlanSlug2(str) {
770    return str === toDataPlanSlug(str);
771  };
772  var isStringOrNumber = function isStringOrNumber2(value) {
773    return isString(value) || isNumber(value);
774  };
775  var isEmpty = function isEmpty2(value) {
776    return value == null || !(Object.keys(value) || value).length;
777  };
778  var moveElementToEnd = function moveElementToEnd2(array, index) {
779    return array.slice(0, index).concat(array.slice(index + 1), array[index]);
780  };
781  var queryStringParser = function queryStringParser2(url, keys) {
782    if (keys === void 0) {
783      keys = [];
784    }
785    var urlParams;
786    var results = {};
787    var lowerCaseUrlParams = {};
788    if (!url) return results;
789    if (typeof URL !== "undefined" && typeof URLSearchParams !== "undefined") {
790      var urlObject = new URL(url);
791      urlParams = new URLSearchParams(urlObject.search);
792    } else {
793      urlParams = queryStringParserFallback(url);
794    }
795    urlParams.forEach(function(value, key) {
796      lowerCaseUrlParams[key.toLowerCase()] = value;
797    });
798    if (isEmpty(keys)) {
799      return lowerCaseUrlParams;
800    } else {
801      keys.forEach(function(key) {
802        var value = lowerCaseUrlParams[key.toLowerCase()];
803        if (value) {
804          results[key] = value;
805        }
806      });
807    }
808    return results;
809  };
810  var queryStringParserFallback = function queryStringParserFallback2(url) {
811    var params = {};
812    var queryString = url.split("?")[1] || "";
813    var pairs = queryString.split("&");
814    pairs.forEach(function(pair) {
815      var _a2 = pair.split("="), key = _a2[0], valueParts = _a2.slice(1);
816      var value = valueParts.join("=");
817      if (key && value !== void 0) {
818        try {
819          params[key] = decodeURIComponent(value || "");
820        } catch (e) {
821          console.error("Failed to decode value for key ".concat(key, ": ").concat(e));
822        }
823      }
824    });
825    return {
826      get: function get(key) {
827        return params[key];
828      },
829      forEach: function forEach(callback) {
830        for (var key in params) {
831          if (params.hasOwnProperty(key)) {
832            callback(params[key], key);
833          }
834        }
835      }
836    };
837  };
838  var getCookies = function getCookies2(keys) {
839    var parseCookies = function parseCookies2() {
840      try {
841        if (typeof window === "undefined") {
842          return [];
843        }
844        return window.document.cookie.split(";").map(function(cookie) {
845          return cookie.trim();
846        });
847      } catch (e) {
848        console.error("Unable to parse cookies", e);
849        return [];
850      }
851    };
852    var filterCookies = function filterCookies2(cookies, keys2) {
853      var results = {};
854      for (var _i = 0, cookies_1 = cookies; _i < cookies_1.length; _i++) {
855        var cookie = cookies_1[_i];
856        var _a2 = cookie.split("="), key = _a2[0], value = _a2[1];
857        if (!keys2 || keys2.includes(key)) {
858          results[key] = value;
859        }
860      }
861      return results;
862    };
863    var parsedCookies = parseCookies();
864    return filterCookies(parsedCookies, keys);
865  };
866  var getHref = function getHref2() {
867    return typeof window !== "undefined" && window.location ? window.location.href : "";
868  };
869  var filterDictionaryWithHash = function filterDictionaryWithHash2(dictionary, filterList, hashFn) {
870    var filtered = {};
871    if (!isEmpty(dictionary)) {
872      for (var key in dictionary) {
873        if (dictionary.hasOwnProperty(key)) {
874          var hashedKey = hashFn(key);
875          if (!inArray(filterList, hashedKey)) {
876            filtered[key] = dictionary[key];
877          }
878        }
879      }
880    }
881    return filtered;
882  };
883  var parseConfig = function parseConfig2(config, moduleName, moduleId) {
884    var _a2;
885    return ((_a2 = config.kitConfigs) === null || _a2 === void 0 ? void 0 : _a2.find(function(kitConfig) {
886      return kitConfig.name === moduleName && kitConfig.moduleId === moduleId;
887    })) || null;
888  };
889  var obfuscateData = function obfuscateData2(value) {
890    if (value === null || value === void 0) {
891      return value;
892    }
893    if (Array.isArray(value)) {
894      return value.map(function(item) {
895        return obfuscateData2(item);
896      });
897    }
898    if (isObject(value)) {
899      var obfuscated = {};
900      for (var key in value) {
901        if (value.hasOwnProperty(key)) {
902          obfuscated[key] = obfuscateData2(value[key]);
903        }
904      }
905      return obfuscated;
906    }
907    return _typeof(value);
908  };
909  var obfuscateDevData = function obfuscateDevData2(data, isDevelopmentMode) {
910    return isDevelopmentMode ? data : obfuscateData(data);
911  };
912  function extend() {
913    var args = [];
914    for (var _i = 0; _i < arguments.length; _i++) {
915      args[_i] = arguments[_i];
916    }
917    var objectHelper = {
918      hasOwn: Object.prototype.hasOwnProperty,
919      class2type: {},
920      type: function type(obj) {
921        return obj == null ? String(obj) : objectHelper.class2type[Object.prototype.toString.call(obj)] || "object";
922      },
923      isPlainObject: function isPlainObject(obj) {
924        if (!obj || objectHelper.type(obj) !== "object" || obj.nodeType || objectHelper.isWindow(obj)) {
925          return false;
926        }
927        try {
928          if (obj.constructor && !objectHelper.hasOwn.call(obj, "constructor") && !objectHelper.hasOwn.call(obj.constructor.prototype, "isPrototypeOf")) {
929            return false;
930          }
931        } catch (e) {
932          return false;
933        }
934        var key;
935        for (key in obj) {
936        }
937        return key === void 0 || objectHelper.hasOwn.call(obj, key);
938      },
939      isArray: Array.isArray || function(obj) {
940        return objectHelper.type(obj) === "array";
941      },
942      isFunction: function isFunction2(obj) {
943        return objectHelper.type(obj) === "function";
944      },
945      isWindow: function isWindow(obj) {
946        return obj != null && obj == obj.window;
947      }
948    };
949    var options, name, src, copy, copyIsArray, clone, target = args[0] || {}, i = 1, deep = false;
950    var length = args.length;
951    if (typeof target === "boolean") {
952      deep = target;
953      target = args[1] || {};
954      i = 2;
955    }
956    if (_typeof(target) !== "object" && !objectHelper.isFunction(target)) {
957      target = {};
958    }
959    if (length === i) {
960      target = {};
961      --i;
962    }
963    for (; i < length; i++) {
964      if ((options = args[i]) != null) {
965        for (name in options) {
966          if (name === "__proto__" || name === "constructor" || name === "prototype") {
967            continue;
968          }
969          if (!Object.prototype.hasOwnProperty.call(options, name)) {
970            continue;
971          }
972          src = target[name];
973          copy = options[name];
974          if (target === copy) {
975            continue;
976          }
977          if (deep && copy && (objectHelper.isPlainObject(copy) || (copyIsArray = objectHelper.isArray(copy)))) {
978            if (copyIsArray) {
979              copyIsArray = false;
980              clone = src && objectHelper.isArray(src) ? src : [];
981            } else {
982              clone = src && objectHelper.isPlainObject(src) ? src : {};
983            }
984            target[name] = extend(deep, clone, copy);
985          } else if (copy !== void 0) {
986            target[name] = copy;
987          }
988        }
989      }
990    }
991    return target;
992  }
993  var getErrorMessage = function getErrorMessage2(e, fallback) {
994    if (fallback === void 0) {
995      fallback = "unknown error";
996    }
997    if (e instanceof Error) {
998      return e.message;
999    }
1000    if (typeof e === "string") {
1001      return e;
1002    }
1003    if (e && _typeof(e) === "object" && typeof e.message === "string") {
1004      return e.message;
1005    }
1006    return fallback;
1007  };
1008  var MessageType$1 = {
1009    SessionStart: 1,
1010    SessionEnd: 2,
1011    PageView: 3,
1012    PageEvent: 4,
1013    CrashReport: 5,
1014    OptOut: 6,
1015    AppStateTransition: 10,
1016    Profile: 14,
1017    Commerce: 16,
1018    Media: 20,
1019    UserAttributeChange: 17,
1020    UserIdentityChange: 18
1021  };
1022  var EventType = {
1023    Unknown: 0,
1024    Navigation: 1,
1025    Location: 2,
1026    Search: 3,
1027    Transaction: 4,
1028    UserContent: 5,
1029    UserPreference: 6,
1030    Social: 7,
1031    Other: 8,
1032    Media: 9,
1033    getName: function getName(id) {
1034      switch (id) {
1035        case EventType.Unknown:
1036          return "Unknown";
1037        case EventType.Navigation:
1038          return "Navigation";
1039        case EventType.Location:
1040          return "Location";
1041        case EventType.Search:
1042          return "Search";
1043        case EventType.Transaction:
1044          return "Transaction";
1045        case EventType.UserContent:
1046          return "User Content";
1047        case EventType.UserPreference:
1048          return "User Preference";
1049        case EventType.Social:
1050          return "Social";
1051        case CommerceEventType.ProductAddToCart:
1052          return "Product Added to Cart";
1053        case CommerceEventType.ProductAddToWishlist:
1054          return "Product Added to Wishlist";
1055        case CommerceEventType.ProductCheckout:
1056          return "Product Checkout";
1057        case CommerceEventType.ProductCheckoutOption:
1058          return "Product Checkout Options";
1059        case CommerceEventType.ProductClick:
1060          return "Product Click";
1061        case CommerceEventType.ProductImpression:
1062          return "Product Impression";
1063        case CommerceEventType.ProductPurchase:
1064          return "Product Purchased";
1065        case CommerceEventType.ProductRefund:
1066          return "Product Refunded";
1067        case CommerceEventType.ProductRemoveFromCart:
1068          return "Product Removed From Cart";
1069        case CommerceEventType.ProductRemoveFromWishlist:
1070          return "Product Removed from Wishlist";
1071        case CommerceEventType.ProductViewDetail:
1072          return "Product View Details";
1073        case CommerceEventType.PromotionClick:
1074          return "Promotion Click";
1075        case CommerceEventType.PromotionView:
1076          return "Promotion View";
1077        default:
1078          return "Other";
1079      }
1080    }
1081  };
1082  var CommerceEventType = {
1083    ProductAddToCart: 10,
1084    ProductRemoveFromCart: 11,
1085    ProductCheckout: 12,
1086    ProductCheckoutOption: 13,
1087    ProductClick: 14,
1088    ProductViewDetail: 15,
1089    ProductPurchase: 16,
1090    ProductRefund: 17,
1091    PromotionView: 18,
1092    PromotionClick: 19,
1093    ProductAddToWishlist: 20,
1094    ProductRemoveFromWishlist: 21,
1095    ProductImpression: 22
1096  };
1097  var IdentityType = {
1098    Other: 0,
1099    CustomerId: 1,
1100    Facebook: 2,
1101    Twitter: 3,
1102    Google: 4,
1103    Microsoft: 5,
1104    Yahoo: 6,
1105    Email: 7,
1106    FacebookCustomAudienceId: 9,
1107    Other2: 10,
1108    Other3: 11,
1109    Other4: 12,
1110    Other5: 13,
1111    Other6: 14,
1112    Other7: 15,
1113    Other8: 16,
1114    Other9: 17,
1115    Other10: 18,
1116    MobileNumber: 19,
1117    PhoneNumber2: 20,
1118    PhoneNumber3: 21,
1119    isValid: function isValid(identityType) {
1120      if (typeof identityType === "number") {
1121        for (var prop in IdentityType) {
1122          if (IdentityType.hasOwnProperty(prop)) {
1123            if (IdentityType[prop] === identityType) {
1124              return true;
1125            }
1126          }
1127        }
1128      }
1129      return false;
1130    },
1131    getName: function getName(identityType) {
1132      switch (identityType) {
1133        case window.mParticle.IdentityType.CustomerId:
1134          return "Customer ID";
1135        case window.mParticle.IdentityType.Facebook:
1136          return "Facebook ID";
1137        case window.mParticle.IdentityType.Twitter:
1138          return "Twitter ID";
1139        case window.mParticle.IdentityType.Google:
1140          return "Google ID";
1141        case window.mParticle.IdentityType.Microsoft:
1142          return "Microsoft ID";
1143        case window.mParticle.IdentityType.Yahoo:
1144          return "Yahoo ID";
1145        case window.mParticle.IdentityType.Email:
1146          return "Email";
1147        case window.mParticle.IdentityType.FacebookCustomAudienceId:
1148          return "Facebook App User ID";
1149        default:
1150          return "Other ID";
1151      }
1152    },
1153    getIdentityType: function getIdentityType(identityName) {
1154      switch (identityName) {
1155        case "other":
1156          return IdentityType.Other;
1157        case "customerid":
1158          return IdentityType.CustomerId;
1159        case "facebook":
1160          return IdentityType.Facebook;
1161        case "twitter":
1162          return IdentityType.Twitter;
1163        case "google":
1164          return IdentityType.Google;
1165        case "microsoft":
1166          return IdentityType.Microsoft;
1167        case "yahoo":
1168          return IdentityType.Yahoo;
1169        case "email":
1170          return IdentityType.Email;
1171        case "facebookcustomaudienceid":
1172          return IdentityType.FacebookCustomAudienceId;
1173        case "other2":
1174          return IdentityType.Other2;
1175        case "other3":
1176          return IdentityType.Other3;
1177        case "other4":
1178          return IdentityType.Other4;
1179        case "other5":
1180          return IdentityType.Other5;
1181        case "other6":
1182          return IdentityType.Other6;
1183        case "other7":
1184          return IdentityType.Other7;
1185        case "other8":
1186          return IdentityType.Other8;
1187        case "other9":
1188          return IdentityType.Other9;
1189        case "other10":
1190          return IdentityType.Other10;
1191        case "mobile_number":
1192          return IdentityType.MobileNumber;
1193        case "phone_number_2":
1194          return IdentityType.PhoneNumber2;
1195        case "phone_number_3":
1196          return IdentityType.PhoneNumber3;
1197        case "email_sha256":
1198          return IdentityType.Other;
1199        case "mobile_sha256":
1200          return IdentityType.Other2;
1201        default:
1202          return false;
1203      }
1204    },
1205    getIdentityName: function getIdentityName(identityType) {
1206      switch (identityType) {
1207        case IdentityType.Other:
1208          return "other";
1209        case IdentityType.CustomerId:
1210          return "customerid";
1211        case IdentityType.Facebook:
1212          return "facebook";
1213        case IdentityType.Twitter:
1214          return "twitter";
1215        case IdentityType.Google:
1216          return "google";
1217        case IdentityType.Microsoft:
1218          return "microsoft";
1219        case IdentityType.Yahoo:
1220          return "yahoo";
1221        case IdentityType.Email:
1222          return "email";
1223        case IdentityType.FacebookCustomAudienceId:
1224          return "facebookcustomaudienceid";
1225        case IdentityType.Other2:
1226          return "other2";
1227        case IdentityType.Other3:
1228          return "other3";
1229        case IdentityType.Other4:
1230          return "other4";
1231        case IdentityType.Other5:
1232          return "other5";
1233        case IdentityType.Other6:
1234          return "other6";
1235        case IdentityType.Other7:
1236          return "other7";
1237        case IdentityType.Other8:
1238          return "other8";
1239        case IdentityType.Other9:
1240          return "other9";
1241        case IdentityType.Other10:
1242          return "other10";
1243        case IdentityType.MobileNumber:
1244          return "mobile_number";
1245        case IdentityType.PhoneNumber2:
1246          return "phone_number_2";
1247        case IdentityType.PhoneNumber3:
1248          return "phone_number_3";
1249        default:
1250          return null;
1251      }
1252    },
1253    // Strips out functions from Identity Types for easier lookups
1254    getValuesAsStrings: function getValuesAsStrings() {
1255      return Object.values(IdentityType).map(function(value) {
1256        return isNumber(value) ? value.toString() : void 0;
1257      }).filter(function(value) {
1258        return value !== void 0;
1259      });
1260    },
1261    getNewIdentitiesByName: function getNewIdentitiesByName(newIdentitiesByType) {
1262      var newIdentitiesByName = {};
1263      var identityTypeValuesAsStrings = IdentityType.getValuesAsStrings();
1264      for (var key in newIdentitiesByType) {
1265        if (identityTypeValuesAsStrings.includes(key)) {
1266          var identityNameKey = IdentityType.getIdentityName(parseNumber(key));
1267          newIdentitiesByName[identityNameKey] = newIdentitiesByType[key];
1268        }
1269      }
1270      return newIdentitiesByName;
1271    }
1272  };
1273  var ProductActionType = {
1274    Unknown: 0,
1275    AddToCart: 1,
1276    RemoveFromCart: 2,
1277    Checkout: 3,
1278    CheckoutOption: 4,
1279    Click: 5,
1280    ViewDetail: 6,
1281    Purchase: 7,
1282    Refund: 8,
1283    AddToWishlist: 9,
1284    RemoveFromWishlist: 10,
1285    // Rokt Brain commerce-adjacent types
1286    ViewCart: 11,
1287    AddShippingInfo: 12,
1288    AddPaymentInfo: 13,
1289    PaymentMethodSelected: 14,
1290    PaymentAttempted: 15,
1291    PaymentSucceeded: 16,
1292    PaymentFailed: 17,
1293    RefundInitiated: 18,
1294    isRoktCommerceType: function isRoktCommerceType(id) {
1295      return id >= ProductActionType.ViewCart && id <= ProductActionType.RefundInitiated;
1296    },
1297    getName: function getName(id) {
1298      switch (id) {
1299        case ProductActionType.AddToCart:
1300          return "Add to Cart";
1301        case ProductActionType.RemoveFromCart:
1302          return "Remove from Cart";
1303        case ProductActionType.Checkout:
1304          return "Checkout";
1305        case ProductActionType.CheckoutOption:
1306          return "Checkout Option";
1307        case ProductActionType.Click:
1308          return "Click";
1309        case ProductActionType.ViewDetail:
1310          return "View Detail";
1311        case ProductActionType.Purchase:
1312          return "Purchase";
1313        case ProductActionType.Refund:
1314          return "Refund";
1315        case ProductActionType.AddToWishlist:
1316          return "Add to Wishlist";
1317        case ProductActionType.RemoveFromWishlist:
1318          return "Remove from Wishlist";
1319        case ProductActionType.ViewCart:
1320          return "View Cart";
1321        case ProductActionType.AddShippingInfo:
1322          return "Add Shipping Info";
1323        case ProductActionType.AddPaymentInfo:
1324          return "Add Payment Info";
1325        case ProductActionType.PaymentMethodSelected:
1326          return "Payment Method Selected";
1327        case ProductActionType.PaymentAttempted:
1328          return "Payment Attempted";
1329        case ProductActionType.PaymentSucceeded:
1330          return "Payment Succeeded";
1331        case ProductActionType.PaymentFailed:
1332          return "Payment Failed";
1333        case ProductActionType.RefundInitiated:
1334          return "Refund Initiated";
1335        default:
1336          return "Unknown";
1337      }
1338    },
1339    // these are the action names used by server and mobile SDKs when expanding a CommerceEvent
1340    getExpansionName: function getExpansionName(id) {
1341      switch (id) {
1342        case ProductActionType.AddToCart:
1343          return "add_to_cart";
1344        case ProductActionType.RemoveFromCart:
1345          return "remove_from_cart";
1346        case ProductActionType.Checkout:
1347          return "checkout";
1348        case ProductActionType.CheckoutOption:
1349          return "checkout_option";
1350        case ProductActionType.Click:
1351          return "click";
1352        case ProductActionType.ViewDetail:
1353          return "view_detail";
1354        case ProductActionType.Purchase:
1355          return "purchase";
1356        case ProductActionType.Refund:
1357          return "refund";
1358        case ProductActionType.AddToWishlist:
1359          return "add_to_wishlist";
1360        case ProductActionType.RemoveFromWishlist:
1361          return "remove_from_wishlist";
1362        case ProductActionType.ViewCart:
1363          return "view_cart";
1364        case ProductActionType.AddShippingInfo:
1365          return "add_shipping_info";
1366        case ProductActionType.AddPaymentInfo:
1367          return "add_payment_info";
1368        case ProductActionType.PaymentMethodSelected:
1369          return "payment_method_selected";
1370        case ProductActionType.PaymentAttempted:
1371          return "payment_attempted";
1372        case ProductActionType.PaymentSucceeded:
1373          return "payment_succeeded";
1374        case ProductActionType.PaymentFailed:
1375          return "payment_failed";
1376        case ProductActionType.RefundInitiated:
1377          return "refund_initiated";
1378        default:
1379          return "unknown";
1380      }
1381    }
1382  };
1383  var RoktEvents = {
1384    SignUp: "sign_up",
1385    Subscribe: "subscribe",
1386    StartTrial: "start_trial",
1387    GenerateLead: "generate_lead",
1388    Search: "search",
1389    Upsell: "upsell",
1390    EarnVirtualCurrency: "earn_virtual_currency",
1391    DwellTime: "dwell_time",
1392    Hover: "hover",
1393    Scroll: "scroll",
1394    ClickToExpand: "click_to_expand"
1395  };
1396  var PromotionActionType = {
1397    Unknown: 0,
1398    PromotionView: 1,
1399    PromotionClick: 2,
1400    getName: function getName(id) {
1401      switch (id) {
1402        case PromotionActionType.PromotionView:
1403          return "view";
1404        case PromotionActionType.PromotionClick:
1405          return "click";
1406        default:
1407          return "unknown";
1408      }
1409    },
1410    // these are the names that the server and mobile SDKs use while expanding CommerceEvent
1411    getExpansionName: function getExpansionName(id) {
1412      switch (id) {
1413        case PromotionActionType.PromotionView:
1414          return "view";
1415        case PromotionActionType.PromotionClick:
1416          return "click";
1417        default:
1418          return "unknown";
1419      }
1420    }
1421  };
1422  var ProfileMessageType = {
1423    Logout: 3
1424  };
1425  var ApplicationTransitionType$1 = {
1426    AppInit: 1
1427  };
1428  var PerformanceMarkType = {
1429    SdkStart: "mp:sdkStart",
1430    JointSdkSelectPlacements: "mp:jointSdkSelectPlacements",
1431    JointSdkRoktKitInit: "mp:jointSdkRoktKitInit"
1432  };
1433  var Types = {
1434    MessageType: MessageType$1,
1435    EventType,
1436    CommerceEventType,
1437    IdentityType,
1438    ProfileMessageType,
1439    ApplicationTransitionType: ApplicationTransitionType$1,
1440    ProductActionType,
1441    PromotionActionType,
1442    RoktEvents,
1443    Environment: Constants.Environment
1444  };
1445  var SDKProductActionType;
1446  (function(SDKProductActionType2) {
1447    SDKProductActionType2[SDKProductActionType2["Unknown"] = 0] = "Unknown";
1448    SDKProductActionType2[SDKProductActionType2["AddToCart"] = 1] = "AddToCart";
1449    SDKProductActionType2[SDKProductActionType2["RemoveFromCart"] = 2] = "RemoveFromCart";
1450    SDKProductActionType2[SDKProductActionType2["Checkout"] = 3] = "Checkout";
1451    SDKProductActionType2[SDKProductActionType2["CheckoutOption"] = 4] = "CheckoutOption";
1452    SDKProductActionType2[SDKProductActionType2["Click"] = 5] = "Click";
1453    SDKProductActionType2[SDKProductActionType2["ViewDetail"] = 6] = "ViewDetail";
1454    SDKProductActionType2[SDKProductActionType2["Purchase"] = 7] = "Purchase";
1455    SDKProductActionType2[SDKProductActionType2["Refund"] = 8] = "Refund";
1456    SDKProductActionType2[SDKProductActionType2["AddToWishlist"] = 9] 
1456= "AddToWishlist";
1457    SDKProductActionType2[SDKProductActionType2["RemoveFromWishlist"] = 10] = "RemoveFromWishlist";
1458    SDKProductActionType2[SDKProductActionType2["ViewCart"] = 11] = "ViewCart";
1459    SDKProductActionType2[SDKProductActionType2["AddShippingInfo"] = 12] = "AddShippingInfo";
1460    SDKProductActionType2[SDKProductActionType2["AddPaymentInfo"] = 13] = "AddPaymentInfo";
1461    SDKProductActionType2[SDKProductActionType2["PaymentMethodSelected"] = 14] = "PaymentMethodSelected";
1462    SDKProductActionType2[SDKProductActionType2["PaymentAttempted"] = 15] = "PaymentAttempted";
1463    SDKProductActionType2[SDKProductActionType2["PaymentSucceeded"] = 16] = "PaymentSucceeded";
1464    SDKProductActionType2[SDKProductActionType2["PaymentFailed"] = 17] = "PaymentFailed";
1465    SDKProductActionType2[SDKProductActionType2["RefundInitiated"] = 18] = "RefundInitiated";
1466  })(SDKProductActionType || (SDKProductActionType = {}));
1467  var LogLevelType = {
1468    None: "none",
1469    Verbose: "verbose",
1470    Warning: "warning",
1471    Error: "error"
1472  };
1473  var dist = {};
1474  (function(exports) {
1475    Object.defineProperty(exports, "__esModule", { value: true });
1476    (function(ApplicationInformationOsEnum) {
1477      ApplicationInformationOsEnum["unknown"] = "Unknown";
1478      ApplicationInformationOsEnum["iOS"] = "IOS";
1479      ApplicationInformationOsEnum["android"] = "Android";
1480      ApplicationInformationOsEnum["windowsPhone"] = "WindowsPhone";
1481      ApplicationInformationOsEnum["mobileWeb"] = "MobileWeb";
1482      ApplicationInformationOsEnum["unityIOS"] = "UnityIOS";
1483      ApplicationInformationOsEnum["unityAndroid"] = "UnityAndroid";
1484      ApplicationInformationOsEnum["desktop"] = "Desktop";
1485      ApplicationInformationOsEnum["tvOS"] = "TVOS";
1486      ApplicationInformationOsEnum["roku"] = "Roku";
1487      ApplicationInformationOsEnum["outOfBand"] = "OutOfBand";
1488      ApplicationInformationOsEnum["alexa"] = "Alexa";
1489      ApplicationInformationOsEnum["smartTV"] = "SmartTV";
1490      ApplicationInformationOsEnum["fireTV"] = "FireTV";
1491      ApplicationInformationOsEnum["xbox"] = "Xbox";
1492    })(exports.ApplicationInformationOsEnum || (exports.ApplicationInformationOsEnum = {}));
1493    (function(ApplicationStateTransitionEventEventTypeEnum) {
1494      ApplicationStateTransitionEventEventTypeEnum["applicationStateTransition"] = "application_state_transition";
1495    })(exports.ApplicationStateTransitionEventEventTypeEnum || (exports.ApplicationStateTransitionEventEventTypeEnum = {}));
1496    (function(ApplicationStateTransitionEventDataApplicationTransitionTypeEnum) {
1497      ApplicationStateTransitionEventDataApplicationTransitionTypeEnum["applicationInitialized"] = "application_initialized";
1498      ApplicationStateTransitionEventDataApplicationTransitionTypeEnum["applicationExit"] = "application_exit";
1499      ApplicationStateTransitionEventDataApplicationTransitionTypeEnum["applicationBackground"] = "application_background";
1500      ApplicationStateTransitionEventDataApplicationTransitionTypeEnum["applicationForeground"] = "application_foreground";
1501    })(exports.ApplicationStateTransitionEventDataApplicationTransitionTypeEnum || (exports.ApplicationStateTransitionEventDataApplicationTransitionTypeEnum = {}));
1502    (function(BatchEnvironmentEnum) {
1503      BatchEnvironmentEnum["unknown"] = "unknown";
1504      BatchEnvironmentEnum["development"] = "development";
1505      BatchEnvironmentEnum["production"] = "production";
1506    })(exports.BatchEnvironmentEnum || (exports.BatchEnvironmentEnum = {}));
1507    (function(BreadcrumbEventEventTypeEnum) {
1508      BreadcrumbEventEventTypeEnum["breadcrumb"] = "breadcrumb";
1509    })(exports.BreadcrumbEventEventTypeEnum || (exports.BreadcrumbEventEventTypeEnum = {}));
1510    (function(CommerceEventEventTypeEnum) {
1511      CommerceEventEventTypeEnum["commerceEvent"] = "commerce_event";
1512    })(exports.CommerceEventEventTypeEnum || (exports.CommerceEventEventTypeEnum = {}));
1513    (function(CommerceEventDataCustomEventTypeEnum) {
1514      CommerceEventDataCustomEventTypeEnum["addToCart"] = "add_to_cart";
1515      CommerceEventDataCustomEventTypeEnum["removeFromCart"] = "remove_from_cart";
1516      CommerceEventDataCustomEventTypeEnum["checkout"] = "checkout";
1517      CommerceEventDataCustomEventTypeEnum["checkoutOption"] = "checkout_option";
1518      CommerceEventDataCustomEventTypeEnum["click"] = "click";
1519      CommerceEventDataCustomEventTypeEnum["viewDetail"] = "view_detail";
1520      CommerceEventDataCustomEventTypeEnum["purchase"] = "purchase";
1521      CommerceEventDataCustomEventTypeEnum["refund"] = "refund";
1522      CommerceEventDataCustomEventTypeEnum["promotionView"] = "promotion_view";
1523      CommerceEventDataCustomEventTypeEnum["promotionClick"] = "promotion_click";
1524      CommerceEventDataCustomEventTypeEnum["addToWishlist"] = "add_to_wishlist";
1525      CommerceEventDataCustomEventTypeEnum["removeFromWishlist"] = "remove_from_wishlist";
1526      CommerceEventDataCustomEventTypeEnum["impression"] = "impression";
1527    })(exports.CommerceEventDataCustomEventTypeEnum || (exports.CommerceEventDataCustomEventTypeEnum = {}));
1528    (function(CrashReportEventEventTypeEnum) {
1529      CrashReportEventEventTypeEnum["crashReport"] = "crash_report";
1530    })(exports.CrashReportEventEventTypeEnum || (exports.CrashReportEventEventTypeEnum = {}));
1531    (function(CustomEventEventTypeEnum) {
1532      CustomEventEventTypeEnum["customEvent"] = "custom_event";
1533    })(exports.CustomEventEventTypeEnum || (exports.CustomEventEventTypeEnum = {}));
1534    (function(CustomEventDataCustomEventTypeEnum) {
1535      CustomEventDataCustomEventTypeEnum["navigation"] = "navigation";
1536      CustomEventDataCustomEventTypeEnum["location"] = "location";
1537      CustomEventDataCustomEventTypeEnum["search"] = "search";
1538      CustomEventDataCustomEventTypeEnum["transaction"] = "transaction";
1539      CustomEventDataCustomEventTypeEnum["userContent"] = "user_content";
1540      CustomEventDataCustomEventTypeEnum["userPreference"] = "user_preference";
1541      CustomEventDataCustomEventTypeEnum["social"] = "social";
1542      CustomEventDataCustomEventTypeEnum["media"] = "media";
1543      CustomEventDataCustomEventTypeEnum["other"] = "other";
1544      CustomEventDataCustomEventTypeEnum["unknown"] = "unknown";
1545    })(exports.CustomEventDataCustomEventTypeEnum || (exports.CustomEventDataCustomEventTypeEnum = {}));
1546    (function(DeviceCurrentStateDeviceOrientationEnum) {
1547      DeviceCurrentStateDeviceOrientationEnum["portrait"] = "portrait";
1548      DeviceCurrentStateDeviceOrientationEnum["portraitUpsideDown"] = "portrait_upside_down";
1549      DeviceCurrentStateDeviceOrientationEnum["landscape"] = "landscape";
1550      DeviceCurrentStateDeviceOrientationEnum["landscapeLeft"] = "LandscapeLeft";
1551      DeviceCurrentStateDeviceOrientationEnum["landscapeRight"] = "LandscapeRight";
1552      DeviceCurrentStateDeviceOrientationEnum["faceUp"] = "FaceUp";
1553      DeviceCurrentStateDeviceOrientationEnum["faceDown"] = "FaceDown";
1554      DeviceCurrentStateDeviceOrientationEnum["square"] = "Square";
1555    })(exports.DeviceCurrentStateDeviceOrientationEnum || (exports.DeviceCurrentStateDeviceOrientationEnum = {}));
1556    (function(DeviceCurrentStateStatusBarOrientationEnum) {
1557      DeviceCurrentStateStatusBarOrientationEnum["portrait"] = "portrait";
1558      DeviceCurrentStateStatusBarOrientationEnum["portraitUpsideDown"] = "portrait_upside_down";
1559      DeviceCurrentStateStatusBarOrientationEnum["landscape"] = "landscape";
1560      DeviceCurrentStateStatusBarOrientationEnum["landscapeLeft"] = "LandscapeLeft";
1561      DeviceCurrentStateStatusBarOrientationEnum["landscapeRight"] = "LandscapeRight";
1562      DeviceCurrentStateStatusBarOrientationEnum["faceUp"] = "FaceUp";
1563      DeviceCurrentStateStatusBarOrientationEnum["faceDown"] = "FaceDown";
1564      DeviceCurrentStateStatusBarOrientationEnum["square"] = "Square";
1565    })(exports.DeviceCurrentStateStatusBarOrientationEnum || (exports.DeviceCurrentStateStatusBarOrientationEnum = {}));
1566    (function(DeviceInformationPlatformEnum) {
1567      DeviceInformationPlatformEnum["iOS"] = "iOS";
1568      DeviceInformationPlatformEnum["android"] = "Android";
1569      DeviceInformationPlatformEnum["web"] = "web";
1570      DeviceInformationPlatformEnum["desktop"] = "desktop";
1571      DeviceInformationPlatformEnum["tvOS"] = "tvOS";
1572      DeviceInformationPlatformEnum["roku"] = "roku";
1573      DeviceInformationPlatformEnum["outOfBand"] = "out_of_band";
1574      DeviceInformationPlatformEnum["smartTV"] = "smart_tv";
1575      DeviceInformationPlatformEnum["xbox"] = "xbox";
1576    })(exports.DeviceInformationPlatformEnum || (exports.DeviceInformationPlatformEnum = {}));
1577    (function(EventTypeEnum) {
1578      EventTypeEnum["unknown"] = "unknown";
1579      EventTypeEnum["sessionStart"] = "session_start";
1580      EventTypeEnum["sessionEnd"] = "session_end";
1581      EventTypeEnum["screenView"] = "screen_view";
1582      EventTypeEnum["customEvent"] = "custom_event";
1583      EventTypeEnum["crashReport"] = "crash_report";
1584      EventTypeEnum["optOut"] = "opt_out";
1585      EventTypeEnum["firstRun"] = "first_run";
1586      EventTypeEnum["preAttribution"] = "pre_attribution";
1587      EventTypeEnum["pushRegistration"] = "push_registration";
1588      EventTypeEnum["applicationStateTransition"] = "application_state_transition";
1589      EventTypeEnum["pushMessage"] = "push_message";
1590      EventTypeEnum["networkPerformance"] = "network_performance";
1591      EventTypeEnum["breadcrumb"] = "breadcrumb";
1592      EventTypeEnum["profile"] = "profile";
1593      EventTypeEnum["pushReaction"] = "push_reaction";
1594      EventTypeEnum["commerceEvent"] = "commerce_event";
1595      EventTypeEnum["userAttributeChange"] = "user_attribute_change";
1596      EventTypeEnum["userIdentityChange"] = "user_identity_change";
1597      EventTypeEnum["uninstall"] = "uninstall";
1598      EventTypeEnum["validationResult"] = "validation_result";
1599    })(exports.EventTypeEnum || (exports.EventTypeEnum = {}));
1600    (function(IdentityTypeEnum) {
1601      IdentityTypeEnum["other"] = "other";
1602      IdentityTypeEnum["customerId"] = "customer_id";
1603      IdentityTypeEnum["facebook"] = "facebook";
1604      IdentityTypeEnum["twitter"] = "twitter";
1605      IdentityTypeEnum["google"] = "google";
1606      IdentityTypeEnum["microsoft"] = "microsoft";
1607      IdentityTypeEnum["yahoo"] = "yahoo";
1608      IdentityTypeEnum["email"] = "email";
1609      IdentityTypeEnum["alias"] = "alias";
1610      IdentityTypeEnum["facebookCustomAudienceId"] = "facebook_custom_audience_id";
1611      IdentityTypeEnum["otherId2"] = "other_id_2";
1612      IdentityTypeEnum["otherId3"] = "other_id_3";
1613      IdentityTypeEnum["otherId4"] = "other_id_4";
1614      IdentityTypeEnum["otherId5"] = "other_id_5";
1615      IdentityTypeEnum["otherId6"] = "other_id_6";
1616      IdentityTypeEnum["otherId7"] = "other_id_7";
1617      IdentityTypeEnum["otherId8"] = "other_id_8";
1618      IdentityTypeEnum["otherId9"] = "other_id_9";
1619      IdentityTypeEnum["otherId10"] = "other_id_10";
1620      IdentityTypeEnum["mobileNumber"] = "mobile_number";
1621      IdentityTypeEnum["phoneNumber2"] = "phone_number_2";
1622      IdentityTypeEnum["phoneNumber3"] = "phone_number_3";
1623    })(exports.IdentityTypeEnum || (exports.IdentityTypeEnum = {}));
1624    (function(NetworkPerformanceEventEventTypeEnum) {
1625      NetworkPerformanceEventEventTypeEnum["networkPerformance"] = "network_performance";
1626    })(exports.NetworkPerformanceEventEventTypeEnum || (exports.NetworkPerformanceEventEventTypeEnum = {}));
1627    (function(OptOutEventEnum) {
1628      OptOutEventEnum["optOut"] = "opt_out";
1629    })(exports.OptOutEventEnum || (exports.OptOutEventEnum = {}));
1630    (function(ProductActionActionEnum) {
1631      ProductActionActionEnum["unknown"] = "unknown";
1632      ProductActionActionEnum["addToCart"] = "add_to_cart";
1633      ProductActionActionEnum["removeFromCart"] = "remove_from_cart";
1634      ProductActionActionEnum["checkout"] = "checkout";
1635      ProductActionActionEnum["checkoutOption"] = "checkout_option";
1636      ProductActionActionEnum["click"] = "click";
1637      ProductActionActionEnum["viewDetail"] = "view_detail";
1638      ProductActionActionEnum["purchase"] = "purchase";
1639      ProductActionActionEnum["refund"] = "refund";
1640      ProductActionActionEnum["addToWishlist"] = "add_to_wishlist";
1641      ProductActionActionEnum["removeFromWishlist"] = "remove_from_wish_list";
1642    })(exports.ProductActionActionEnum || (exports.ProductActionActionEnum = {}));
1643    (function(ProfileEventEventTypeEnum) {
1644      ProfileEventEventTypeEnum["profile"] = "profile";
1645    })(exports.ProfileEventEventTypeEnum || (exports.ProfileEventEventTypeEnum = {}));
1646    (function(ProfileEventDataProfileEventTypeEnum) {
1647      ProfileEventDataProfileEventTypeEnum["signup"] = "signup";
1648      ProfileEventDataProfileEventTypeEnum["login"] = "login";
1649      ProfileEventDataProfileEventTypeEnum["logout"] = "logout";
1650      ProfileEventDataProfileEventTypeEnum["update"] = "update";
1651      ProfileEventDataProfileEventTypeEnum["delete"] = "delete";
1652    })(exports.ProfileEventDataProfileEventTypeEnum || (exports.ProfileEventDataProfileEventTypeEnum = {}));
1653    (function(PromotionActionActionEnum) {
1654      PromotionActionActionEnum["view"] = "view";
1655      PromotionActionActionEnum["click"] = "click";
1656    })(exports.PromotionActionActionEnum || (exports.PromotionActionActionEnum = {}));
1657    (function(PushMessageEventEventTypeEnum) {
1658      PushMessageEventEventTypeEnum["pushMessage"] = "push_message";
1659    })(exports.PushMessageEventEventTypeEnum || (exports.PushMessageEventEventTypeEnum = {}));
1660    (function(PushMessageEventDataPushMessageTypeEnum) {
1661      PushMessageEventDataPushMessageTypeEnum["sent"] = "sent";
1662      PushMessageEventDataPushMessageTypeEnum["received"] = "received";
1663      PushMessageEventDataPushMessageTypeEnum["action"] = "action";
1664    })(exports.PushMessageEventDataPushMessageTypeEnum || (exports.PushMessageEventDataPushMessageTypeEnum = {}));
1665    (function(PushMessageEventDataApplicationStateEnum) {
1666      PushMessageEventDataApplicationStateEnum["notRunning"] = "not_running";
1667      PushMessageEventDataApplicationStateEnum["background"] = "background";
1668      PushMessageEventDataApplicationStateEnum["foreground"] = "foreground";
1669    })(exports.PushMessageEventDataApplicationStateEnum || (exports.PushMessageEventDataApplicationStateEnum = {}));
1670    (function(PushMessageEventDataPushMessageBehaviorEnum) {
1671      PushMessageEventDataPushMessageBehaviorEnum["received"] = "Received";
1672      PushMessageEventDataPushMessageBehaviorEnum["directOpen"] = "DirectOpen";
1673      PushMessageEventDataPushMessageBehaviorEnum["read"] = "Read";
1674      PushMessageEventDataPushMessageBehaviorEnum["influencedOpen"] = "InfluencedOpen";
1675      PushMessageEventDataPushMessageBehaviorEnum["displayed"] = "Dis
1675played";
1676    })(exports.PushMessageEventDataPushMessageBehaviorEnum || (exports.PushMessageEventDataPushMessageBehaviorEnum = {}));
1677    (function(PushRegistrationEventEventTypeEnum) {
1678      PushRegistrationEventEventTypeEnum["pushRegistration"] = "push_registration";
1679    })(exports.PushRegistrationEventEventTypeEnum || (exports.PushRegistrationEventEventTypeEnum = {}));
1680    (function(SessionEndEventEventTypeEnum) {
1681      SessionEndEventEventTypeEnum["sessionEnd"] = "session_end";
1682    })(exports.SessionEndEventEventTypeEnum || (exports.SessionEndEventEventTypeEnum = {}));
1683    (function(SessionStartEventEventTypeEnum) {
1684      SessionStartEventEventTypeEnum["sessionStart"] = "session_start";
1685    })(exports.SessionStartEventEventTypeEnum || (exports.SessionStartEventEventTypeEnum = {}));
1686    (function(SourceInformationChannelEnum) {
1687      SourceInformationChannelEnum["native"] = "native";
1688      SourceInformationChannelEnum["javascript"] = "javascript";
1689      SourceInformationChannelEnum["pixel"] = "pixel";
1690      SourceInformationChannelEnum["desktop"] = "desktop";
1691      SourceInformationChannelEnum["partner"] = "partner";
1692      SourceInformationChannelEnum["serverToServer"] = "server_to_server";
1693    })(exports.SourceInformationChannelEnum || (exports.SourceInformationChannelEnum = {}));
1694    (function(UserAttributeChangeEventEventTypeEnum) {
1695      UserAttributeChangeEventEventTypeEnum["userAttributeChange"] = "user_attribute_change";
1696    })(exports.UserAttributeChangeEventEventTypeEnum || (exports.UserAttributeChangeEventEventTypeEnum = {}));
1697    (function(UserIdentityChangeEventEventTypeEnum) {
1698      UserIdentityChangeEventEventTypeEnum["userIdentityChange"] = "user_identity_change";
1699    })(exports.UserIdentityChangeEventEventTypeEnum || (exports.UserIdentityChangeEventEventTypeEnum = {}));
1700  })(dist);
1701  var SDKIdentityTypeEnum;
1702  (function(SDKIdentityTypeEnum2) {
1703    SDKIdentityTypeEnum2["other"] = "other";
1704    SDKIdentityTypeEnum2["customerId"] = "customerid";
1705    SDKIdentityTypeEnum2["facebook"] = "facebook";
1706    SDKIdentityTypeEnum2["twitter"] = "twitter";
1707    SDKIdentityTypeEnum2["google"] = "google";
1708    SDKIdentityTypeEnum2["microsoft"] = "microsoft";
1709    SDKIdentityTypeEnum2["yahoo"] = "yahoo";
1710    SDKIdentityTypeEnum2["email"] = "email";
1711    SDKIdentityTypeEnum2["alias"] = "alias";
1712    SDKIdentityTypeEnum2["facebookCustomAudienceId"] = "facebookcustomaudienceid";
1713    SDKIdentityTypeEnum2["otherId2"] = "other2";
1714    SDKIdentityTypeEnum2["otherId3"] = "other3";
1715    SDKIdentityTypeEnum2["otherId4"] = "other4";
1716    SDKIdentityTypeEnum2["otherId5"] = "other5";
1717    SDKIdentityTypeEnum2["otherId6"] = "other6";
1718    SDKIdentityTypeEnum2["otherId7"] = "other7";
1719    SDKIdentityTypeEnum2["otherId8"] = "other8";
1720    SDKIdentityTypeEnum2["otherId9"] = "other9";
1721    SDKIdentityTypeEnum2["otherId10"] = "other10";
1722    SDKIdentityTypeEnum2["mobileNumber"] = "mobile_number";
1723    SDKIdentityTypeEnum2["phoneNumber2"] = "phone_number_2";
1724    SDKIdentityTypeEnum2["phoneNumber3"] = "phone_number_3";
1725  })(SDKIdentityTypeEnum || (SDKIdentityTypeEnum = {}));
1726  var FeatureFlags$2 = Constants.FeatureFlags;
1727  var CaptureIntegrationSpecificIds$1 = FeatureFlags$2.CaptureIntegrationSpecificIds, CaptureIntegrationSpecificIdsV2$1 = FeatureFlags$2.CaptureIntegrationSpecificIdsV2;
1728  function convertEvents(mpid, sdkEvents, mpInstance) {
1729    if (!mpid) {
1730      return null;
1731    }
1732    if (!sdkEvents || sdkEvents.length < 1) {
1733      return null;
1734    }
1735    var _IntegrationCapture = mpInstance._IntegrationCapture, _Helpers = mpInstance._Helpers;
1736    var getFeatureFlag = _Helpers.getFeatureFlag;
1737    var user = mpInstance.Identity.getCurrentUser();
1738    var uploadEvents = [];
1739    var lastEvent = null;
1740    for (var _i = 0, sdkEvents_1 = sdkEvents; _i < sdkEvents_1.length; _i++) {
1741      var sdkEvent = sdkEvents_1[_i];
1742      if (sdkEvent) {
1743        lastEvent = sdkEvent;
1744        var baseEvent = convertEvent(sdkEvent);
1745        if (baseEvent) {
1746          uploadEvents.push(baseEvent);
1747        }
1748      }
1749    }
1750    if (!lastEvent) {
1751      return null;
1752    }
1753    var currentConsentState = null;
1754    if (!isEmpty(lastEvent.ConsentState)) {
1755      currentConsentState = lastEvent.ConsentState;
1756    } else if (!isEmpty(user)) {
1757      currentConsentState = user.getConsentState();
1758    }
1759    var upload = {
1760      source_request_id: mpInstance._Helpers.generateUniqueId(),
1761      mpid,
1762      timestamp_unixtime_ms: (/* @__PURE__ */ new Date()).getTime(),
1763      environment: lastEvent.Debug ? dist.BatchEnvironmentEnum.development : dist.BatchEnvironmentEnum.production,
1764      events: uploadEvents,
1765      mp_deviceid: lastEvent.DeviceId,
1766      sdk_version: lastEvent.SDKVersion,
1767      // TODO: Refactor this to read from _Store or a global config
1768      application_info: {
1769        application_version: lastEvent.AppVersion,
1770        application_name: lastEvent.AppName,
1771        "package": lastEvent.Package,
1772        sideloaded_kits_count: mpInstance._Store.sideloadedKitsCount
1773      },
1774      device_info: {
1775        platform: dist.DeviceInformationPlatformEnum.web,
1776        screen_width: typeof window !== "undefined" && typeof window.screen !== "undefined" ? window.screen.width : 0,
1777        screen_height: typeof window !== "undefined" && typeof window.screen !== "undefined" ? window.screen.height : 0
1778      },
1779      user_attributes: lastEvent.UserAttributes,
1780      user_identities: convertUserIdentities(lastEvent.UserIdentities),
1781      consent_state: convertConsentState(currentConsentState),
1782      integration_attributes: lastEvent.IntegrationAttributes
1783    };
1784    if (lastEvent.DataPlan && lastEvent.DataPlan.PlanId) {
1785      upload.context = {
1786        data_plan: {
1787          plan_id: lastEvent.DataPlan.PlanId,
1788          plan_version: lastEvent.DataPlan.PlanVersion || void 0
1789        }
1790      };
1791    }
1792    var integrationSpecificIds = getFeatureFlag && Boolean(getFeatureFlag(CaptureIntegrationSpecificIds$1));
1793    var integrationSpecificIdsV2 = getFeatureFlag && getFeatureFlag(CaptureIntegrationSpecificIdsV2$1);
1794    var isIntegrationCaptureEnabled = integrationSpecificIdsV2 && integrationSpecificIdsV2 !== Constants.CaptureIntegrationSpecificIdsV2Modes.None || integrationSpecificIds === true;
1795    if (isIntegrationCaptureEnabled) {
1796      var capturedPartnerIdentities = _IntegrationCapture === null || _IntegrationCapture === void 0 ? void 0 : _IntegrationCapture.getClickIdsAsPartnerIdentities();
1797      if (!isEmpty(capturedPartnerIdentities)) {
1798        upload.partner_identities = capturedPartnerIdentities;
1799      }
1800    }
1801    return upload;
1802  }
1803  function convertConsentState(sdkConsentState) {
1804    if (isEmpty(sdkConsentState)) {
1805      return null;
1806    }
1807    var consentState = {
1808      gdpr: convertGdprConsentState(sdkConsentState.getGDPRConsentState()),
1809      ccpa: convertCcpaConsentState(sdkConsentState.getCCPAConsentState())
1810    };
1811    return consentState;
1812  }
1813  function convertGdprConsentState(sdkGdprConsentState) {
1814    if (!sdkGdprConsentState) {
1815      return null;
1816    }
1817    var state = {};
1818    for (var purpose in sdkGdprConsentState) {
1819      if (sdkGdprConsentState.hasOwnProperty(purpose)) {
1820        state[purpose] = {
1821          consented: sdkGdprConsentState[purpose].Consented,
1822          hardware_id: sdkGdprConsentState[purpose].HardwareId,
1823          document: sdkGdprConsentState[purpose].ConsentDocument,
1824          timestamp_unixtime_ms: sdkGdprConsentState[purpose].Timestamp,
1825          location: sdkGdprConsentState[purpose].Location
1826        };
1827      }
1828    }
1829    return state;
1830  }
1831  function convertCcpaConsentState(sdkCcpaConsentState) {
1832    if (!sdkCcpaConsentState) {
1833      return null;
1834    }
1835    var state = {
1836      data_sale_opt_out: {
1837        consented: sdkCcpaConsentState.Consented,
1838        hardware_id: sdkCcpaConsentState.HardwareId,
1839        document: sdkCcpaConsentState.ConsentDocument,
1840        timestamp_unixtime_ms: sdkCcpaConsentState.Timestamp,
1841        location: sdkCcpaConsentState.Location
1842      }
1843    };
1844    return state;
1845  }
1846  function convertUserIdentities(sdkUserIdentities) {
1847    if (!sdkUserIdentities || !sdkUserIdentities.length) {
1848      return null;
1849    }
1850    var batchIdentities = {};
1851    for (var _i = 0, sdkUserIdentities_1 = sdkUserIdentities; _i < sdkUserIdentities_1.length; _i++) {
1852      var identity = sdkUserIdentities_1[_i];
1853      switch (identity.Type) {
1854        case Types.IdentityType.CustomerId:
1855          batchIdentities.customer_id = identity.Identity;
1856          break;
1857        case Types.IdentityType.Email:
1858          batchIdentities.email = identity.Identity;
1859          break;
1860        case Types.IdentityType.Facebook:
1861          batchIdentities.facebook = identity.Identity;
1862          break;
1863        case Types.IdentityType.FacebookCustomAudienceId:
1864          batchIdentities.facebook_custom_audience_id = identity.Identity;
1865          break;
1866        case Types.IdentityType.Google:
1867          batchIdentities.google = identity.Identity;
1868          break;
1869        case Types.IdentityType.Microsoft:
1870          batchIdentities.microsoft = identity.Identity;
1871          break;
1872        case Types.IdentityType.Other:
1873          batchIdentities.other = identity.Identity;
1874          break;
1875        case Types.IdentityType.Other2:
1876          batchIdentities.other_id_2 = identity.Identity;
1877          break;
1878        case Types.IdentityType.Other3:
1879          batchIdentities.other_id_3 = identity.Identity;
1880          break;
1881        case Types.IdentityType.Other4:
1882          batchIdentities.other_id_4 = identity.Identity;
1883          break;
1884        case Types.IdentityType.Other5:
1885          batchIdentities.other_id_5 = identity.Identity;
1886          break;
1887        case Types.IdentityType.Other6:
1888          batchIdentities.other_id_6 = identity.Identity;
1889          break;
1890        case Types.IdentityType.Other7:
1891          batchIdentities.other_id_7 = identity.Identity;
1892          break;
1893        case Types.IdentityType.Other8:
1894          batchIdentities.other_id_8 = identity.Identity;
1895          break;
1896        case Types.IdentityType.Other9:
1897          batchIdentities.other_id_9 = identity.Identity;
1898          break;
1899        case Types.IdentityType.Other10:
1900          batchIdentities.other_id_10 = identity.Identity;
1901          break;
1902        case Types.IdentityType.MobileNumber:
1903          batchIdentities.mobile_number = identity.Identity;
1904          break;
1905        case Types.IdentityType.PhoneNumber2:
1906          batchIdentities.phone_number_2 = identity.Identity;
1907          break;
1908        case Types.IdentityType.PhoneNumber3:
1909          batchIdentities.phone_number_3 = identity.Identity;
1910          break;
1911      }
1912    }
1913    return batchIdentities;
1914  }
1915  function convertEvent(sdkEvent) {
1916    if (!sdkEvent) {
1917      return null;
1918    }
1919    switch (sdkEvent.EventDataType) {
1920      case Types.MessageType.AppStateTransition:
1921        return convertAST(sdkEvent);
1922      case Types.MessageType.Commerce:
1923        return convertCommerceEvent(sdkEvent);
1924      case Types.MessageType.CrashReport:
1925        return convertCrashReportEvent(sdkEvent);
1926      case Types.MessageType.OptOut:
1927        return convertOptOutEvent(sdkEvent);
1928      case Types.MessageType.PageEvent:
1929        return convertCustomEvent(sdkEvent);
1930      case Types.MessageType.PageView:
1931        return convertPageViewEvent(sdkEvent);
1932      case Types.MessageType.Profile:
1933        return null;
1934      case Types.MessageType.SessionEnd:
1935        return convertSessionEndEvent(sdkEvent);
1936      case Types.MessageType.SessionStart:
1937        return convertSessionStartEvent(sdkEvent);
1938      case Types.MessageType.UserAttributeChange:
1939        return convertUserAttributeChangeEvent(sdkEvent);
1940      case Types.MessageType.UserIdentityChange:
1941        return convertUserIdentityChangeEvent(sdkEvent);
1942    }
1943    return null;
1944  }
1945  function convertProductActionType(actionType) {
1946    if (!actionType) {
1947      return dist.ProductActionActionEnum.unknown;
1948    }
1949    switch (actionType) {
1950      case SDKProductActionType.AddToCart:
1951        return dist.ProductActionActionEnum.addToCart;
1952      case SDKProductActionType.AddToWishlist:
1953        return dist.ProductActionActionEnum.addToWishlist;
1954      case SDKProductActionType.Checkout:
1955        return dist.ProductActionActionEnum.checkout;
1956      case SDKProductActionType.CheckoutOption:
1957        return dist.ProductActionActionEnum.checkoutOption;
1958      case SDKProductActionType.Click:
1959        return dist.ProductActionActionEnum.click;
1960      case SDKProductActionType.Purchase:
1961        return dist.ProductActionActionEnum.purchase;
1962      case SDKProductActionType.Refund:
1963        return dist.ProductActionActionEnum.refund;
1964      case SDKProductActionType.RemoveFromCart:
1965        return dist.ProductActionActionEnum.removeFromCart;
1966      case SDKProductActionType.RemoveFromWishlist:
1967        return dist.ProductActionActionEnum.removeFromWishlist;
1968      case SDKProductActionType.ViewDetail:
1969        return dist.ProductActionActionEnum.viewDetail;
1970      default:
1971        return dist.ProductActionActionEnum.unknown;
1972    }
1973  }
1974  function convertProductAction(sdkEvent) {
1975    if (!sdkEvent.ProductAction) {
1976      return null;
1977    }
1978    var productAction = {
1979      action: convertProductActionType(sdkEvent.ProductAction.ProductActionType),
1980      checkout_step: sdkEvent.ProductAction.CheckoutStep,
1981      checkout_options: sdkEvent.ProductAction.CheckoutOptions,
1982      transaction_id: sdkEvent.ProductAction.TransactionId,
1983      affiliation: sdkEvent.ProductAction.Affiliation,
1984      total_amount: sdkEvent.ProductAction.TotalAmount,
1985      tax_amount: sdkEvent.ProductAction.TaxAmount,
1986      shipping_amount: sdkEvent.ProductAction.ShippingAmount,
1987      coupon_code: sdkEvent.ProductAction.CouponCode,
1988      products: convertProducts(sdkEvent.ProductAction.ProductList)
1989    };
1990    return productAction;
1991  }
1992  function convertProducts(sdkProducts) {
1993    if (!sdkProducts || !sdkProducts.length) {
1994      return null;
1995    }
1996    var products = [];
1997    for (var _i = 0, sdkProducts_1 = sdkProducts; _i < sdkProducts_1.length; _i++) {
1998      var sdkProduct = sdkProducts_1[_i];
1999      var product = {
2000        id: sdkProduct.Sku,
2001        name: sdkProduct.Name,
2002        brand: sdkProduct.Brand,
2003        category: sdkProduct.Category,
2004        variant: sdkProduct.Variant,
2005        total_product_amount: sdkProduct.TotalAmount,
2006        position: sdkProduct.Position,
2007        price: sdkProduct.Price,
2008        quantity: sdkProduct.Quantity,
2009        coupon_code: sdkProduct.CouponCode,
2010        custom_attributes: sdkProduct.Attributes
2011      };
2012      products.push(product);
2013    }
2014    return products;
2015  }
2016  function convertPromotionAction(sdkEvent) {
2017    if (!sdkEvent.PromotionAction) {
2018      return null;
2019    }
2020    var promotionAction = {
2021      action: sdkEvent.PromotionAction.PromotionActionType,
2022      promotions: convertPromotions(sdkEvent.PromotionAction.PromotionList)
2023    };
2024    return promotionAction;
2025  }
2026  function convertPromotions(sdkPromotions) {
2027    if (!sdkPromotions || !sdkPromotions.length) {
2028      return null;
2029    }
2030    var promotions = [];
2031    for (var _i = 0, sdkPromotions_1 = sdkPromotions; _i < sdkPromotions_1.length; _i++) {
2032      var sdkPromotion = sdkPromotions_1[_i];
2033      var promotion = {
2034        id: sdkPromotion.Id,
2035        name: sdkPromotion.Name,
2036        creative: sdkPromotion.Creative,
2037        position: sdkPromotion.Position
2038      };
2039      promotions.push(promotion);
2040    }
2041    return promotions;
2042  }
2043  function convertImpressions(sdkEvent) {
2044    if (!sdkEvent.ProductImpressions) {
2045      return null;
2046    }
2047    var impressions = [];
2048    for (var _i = 0, _a2 = sdkEvent.ProductImpressions; _i < _a2.length; _i++) {
2049      var sdkImpression = _a2[_i];
2050      var impression = {
2051        product_impression_list: sdkImpression.ProductImpressionList,
2052        products: convertProducts(sdkImpression.ProductList)
2053      };
2054      impressions.push(impression);
2055    }
2056    return impressions;
2057  }
2058  function convertShoppingCart(sdkEvent) {
2059    if (!sdkEvent.ShoppingCart || !sdkEvent.ShoppingCart.ProductList || !sdkEvent.ShoppingCart.ProductList.length) {
2060      return null;
2061    }
2062    var shoppingCart = {
2063      products: convertProducts(sdkEvent.ShoppingCart.ProductList)
2064    };
2065    return shoppingCart;
2066  }
2067  function convertCommerceEvent(sdkEvent) {
2068    var commonEventData = convertBaseEventData(sdkEvent);
2069    var commerceEventData = {
2070      custom_flags: sdkEvent.CustomFlags,
2071      product_action: convertProductAction(sdkEvent),
2072      promotion_action: convertPromotionAction(sdkEvent),
2073      product_impressions: convertImpressions(sdkEvent),
2074      shopping_cart: convertShoppingCart(sdkEvent),
2075      currency_code: sdkEvent.CurrencyCode
2076    };
2077    commerceEventData = Object.assign(commerceEventData, commonEventData);
2078    return {
2079      event_type: dist.EventTypeEnum.commerceEvent,
2080      data: commerceEventData
2081    };
2082  }
2083  function convertCrashReportEvent(sdkEvent) {
2084    var commonEventData = convertBaseEventData(sdkEvent);
2085    var crashReportEventData = {
2086      message: sdkEvent.EventName
2087    };
2088    crashReportEventData = Object.assign(crashReportEventData, commonEventData);
2089    return {
2090      event_type: dist.EventTypeEnum.crashReport,
2091      data: crashReportEventData
2092    };
2093  }
2094  function convertAST(sdkEvent) {
2095    var commonEventData = convertBaseEventData(sdkEvent);
2096    var _a2 = dist.ApplicationStateTransitionEventDataApplicationTransitionTypeEnum, applicationBackgroun
2096d = _a2.applicationBackground, applicationInitialized = _a2.applicationInitialized;
2097    var transitionType = sdkEvent.IsBackgroundAST ? applicationBackground : applicationInitialized;
2098    var astEventData = {
2099      application_transition_type: transitionType,
2100      is_first_run: sdkEvent.IsFirstRun,
2101      is_upgrade: false,
2102      launch_referral: sdkEvent.LaunchReferral
2103    };
2104    astEventData = Object.assign(astEventData, commonEventData);
2105    return {
2106      event_type: dist.EventTypeEnum.applicationStateTransition,
2107      data: astEventData
2108    };
2109  }
2110  function convertSessionEndEvent(sdkEvent) {
2111    var commonEventData = convertBaseEventData(sdkEvent);
2112    var sessionEndEventData = {
2113      session_duration_ms: sdkEvent.SessionLength
2114      //note: External Events DTO does not support the session mpids array as of this time.
2115      //spanning_mpids: sdkEvent.SessionMpids
2116    };
2117    sessionEndEventData = Object.assign(sessionEndEventData, commonEventData);
2118    return {
2119      event_type: dist.EventTypeEnum.sessionEnd,
2120      data: sessionEndEventData
2121    };
2122  }
2123  function convertSessionStartEvent(sdkEvent) {
2124    var commonEventData = convertBaseEventData(sdkEvent);
2125    var sessionStartEventData = {};
2126    sessionStartEventData = Object.assign(sessionStartEventData, commonEventData);
2127    return {
2128      event_type: dist.EventTypeEnum.sessionStart,
2129      data: sessionStartEventData
2130    };
2131  }
2132  function convertPageViewEvent(sdkEvent) {
2133    var commonEventData = convertBaseEventData(sdkEvent);
2134    var screenViewEventData = {
2135      custom_flags: sdkEvent.CustomFlags,
2136      screen_name: sdkEvent.EventName
2137    };
2138    screenViewEventData = Object.assign(screenViewEventData, commonEventData);
2139    return {
2140      event_type: dist.EventTypeEnum.screenView,
2141      data: screenViewEventData
2142    };
2143  }
2144  function convertOptOutEvent(sdkEvent) {
2145    var commonEventData = convertBaseEventData(sdkEvent);
2146    var optOutEventData = {
2147      is_opted_out: sdkEvent.OptOut
2148    };
2149    optOutEventData = Object.assign(optOutEventData, commonEventData);
2150    return {
2151      event_type: dist.EventTypeEnum.optOut,
2152      data: optOutEventData
2153    };
2154  }
2155  function convertCustomEvent(sdkEvent) {
2156    var commonEventData = convertBaseEventData(sdkEvent);
2157    var customEventData = {
2158      custom_event_type: convertSdkEventType(sdkEvent.EventCategory),
2159      custom_flags: sdkEvent.CustomFlags,
2160      event_name: sdkEvent.EventName
2161    };
2162    customEventData = Object.assign(customEventData, commonEventData);
2163    return {
2164      event_type: dist.EventTypeEnum.customEvent,
2165      data: customEventData
2166    };
2167  }
2168  function convertSdkEventType(sdkEventType) {
2169    switch (sdkEventType) {
2170      case Types.EventType.Other:
2171        return dist.CustomEventDataCustomEventTypeEnum.other;
2172      case Types.EventType.Location:
2173        return dist.CustomEventDataCustomEventTypeEnum.location;
2174      case Types.EventType.Navigation:
2175        return dist.CustomEventDataCustomEventTypeEnum.navigation;
2176      case Types.EventType.Search:
2177        return dist.CustomEventDataCustomEventTypeEnum.search;
2178      case Types.EventType.Social:
2179        return dist.CustomEventDataCustomEventTypeEnum.social;
2180      case Types.EventType.Transaction:
2181        return dist.CustomEventDataCustomEventTypeEnum.transaction;
2182      case Types.EventType.UserContent:
2183        return dist.CustomEventDataCustomEventTypeEnum.userContent;
2184      case Types.EventType.UserPreference:
2185        return dist.CustomEventDataCustomEventTypeEnum.userPreference;
2186      case Types.EventType.Media:
2187        return dist.CustomEventDataCustomEventTypeEnum.media;
2188      case Types.CommerceEventType.ProductAddToCart:
2189        return dist.CommerceEventDataCustomEventTypeEnum.addToCart;
2190      case Types.CommerceEventType.ProductAddToWishlist:
2191        return dist.CommerceEventDataCustomEventTypeEnum.addToWishlist;
2192      case Types.CommerceEventType.ProductCheckout:
2193        return dist.CommerceEventDataCustomEventTypeEnum.checkout;
2194      case Types.CommerceEventType.ProductCheckoutOption:
2195        return dist.CommerceEventDataCustomEventTypeEnum.checkoutOption;
2196      case Types.CommerceEventType.ProductClick:
2197        return dist.CommerceEventDataCustomEventTypeEnum.click;
2198      case Types.CommerceEventType.ProductImpression:
2199        return dist.CommerceEventDataCustomEventTypeEnum.impression;
2200      case Types.CommerceEventType.ProductPurchase:
2201        return dist.CommerceEventDataCustomEventTypeEnum.purchase;
2202      case Types.CommerceEventType.ProductRefund:
2203        return dist.CommerceEventDataCustomEventTypeEnum.refund;
2204      case Types.CommerceEventType.ProductRemoveFromCart:
2205        return dist.CommerceEventDataCustomEventTypeEnum.removeFromCart;
2206      case Types.CommerceEventType.ProductRemoveFromWishlist:
2207        return dist.CommerceEventDataCustomEventTypeEnum.removeFromWishlist;
2208      case Types.CommerceEventType.ProductViewDetail:
2209        return dist.CommerceEventDataCustomEventTypeEnum.viewDetail;
2210      case Types.CommerceEventType.PromotionClick:
2211        return dist.CommerceEventDataCustomEventTypeEnum.promotionClick;
2212      case Types.CommerceEventType.PromotionView:
2213        return dist.CommerceEventDataCustomEventTypeEnum.promotionView;
2214      default:
2215        return dist.CustomEventDataCustomEventTypeEnum.unknown;
2216    }
2217  }
2218  function convertBaseEventData(sdkEvent) {
2219    var commonEventData = {
2220      timestamp_unixtime_ms: sdkEvent.Timestamp,
2221      session_uuid: sdkEvent.SessionId,
2222      session_start_unixtime_ms: sdkEvent.SessionStartDate,
2223      custom_attributes: sdkEvent.EventAttributes,
2224      location: convertSDKLocation(sdkEvent.Location),
2225      source_message_id: sdkEvent.SourceMessageId,
2226      active_time_on_site_ms: sdkEvent.ActiveTimeOnSite,
2227      total_time_on_site_ms: sdkEvent.TotalTimeOnSite,
2228      page_url: sdkEvent.PageUrl
2229    };
2230    return commonEventData;
2231  }
2232  function convertSDKLocation(sdkEventLocation) {
2233    if (sdkEventLocation && Object.keys(sdkEventLocation).length) {
2234      return {
2235        latitude: sdkEventLocation.lat,
2236        longitude: sdkEventLocation.lng
2237      };
2238    }
2239    return null;
2240  }
2241  function convertUserAttributeChangeEvent(sdkEvent) {
2242    var commonEventData = convertBaseEventData(sdkEvent);
2243    var userAttributeChangeEvent = {
2244      user_attribute_name: sdkEvent.UserAttributeChanges.UserAttributeName,
2245      "new": sdkEvent.UserAttributeChanges.New,
2246      old: sdkEvent.UserAttributeChanges.Old,
2247      deleted: sdkEvent.UserAttributeChanges.Deleted,
2248      is_new_attribute: sdkEvent.UserAttributeChanges.IsNewAttribute
2249    };
2250    userAttributeChangeEvent = __assign(__assign({}, userAttributeChangeEvent), commonEventData);
2251    return {
2252      event_type: dist.EventTypeEnum.userAttributeChange,
2253      data: userAttributeChangeEvent
2254    };
2255  }
2256  function convertUserIdentityChangeEvent(sdkEvent) {
2257    var commonEventData = convertBaseEventData(sdkEvent);
2258    var userIdentityChangeEvent = {
2259      "new": {
2260        identity_type: convertUserIdentityTypeToServerIdentityType(sdkEvent.UserIdentityChanges.New.IdentityType),
2261        identity: sdkEvent.UserIdentityChanges.New.Identity || null,
2262        timestamp_unixtime_ms: sdkEvent.Timestamp,
2263        created_this_batch: sdkEvent.UserIdentityChanges.New.CreatedThisBatch
2264      },
2265      old: {
2266        identity_type: convertUserIdentityTypeToServerIdentityType(sdkEvent.UserIdentityChanges.Old.IdentityType),
2267        identity: sdkEvent.UserIdentityChanges.Old.Identity || null,
2268        timestamp_unixtime_ms: sdkEvent.Timestamp,
2269        created_this_batch: sdkEvent.UserIdentityChanges.Old.CreatedThisBatch
2270      }
2271    };
2272    userIdentityChangeEvent = Object.assign(userIdentityChangeEvent, commonEventData);
2273    return {
2274      event_type: dist.EventTypeEnum.userIdentityChange,
2275      data: userIdentityChangeEvent
2276    };
2277  }
2278  function convertUserIdentityTypeToServerIdentityType(identityType) {
2279    switch (identityType) {
2280      case SDKIdentityTypeEnum.other:
2281        return dist.IdentityTypeEnum.other;
2282      case SDKIdentityTypeEnum.customerId:
2283        return dist.IdentityTypeEnum.customerId;
2284      case SDKIdentityTypeEnum.facebook:
2285        return dist.IdentityTypeEnum.facebook;
2286      case SDKIdentityTypeEnum.twitter:
2287        return dist.IdentityTypeEnum.twitter;
2288      case SDKIdentityTypeEnum.google:
2289        return dist.IdentityTypeEnum.google;
2290      case SDKIdentityTypeEnum.microsoft:
2291        return dist.IdentityTypeEnum.microsoft;
2292      case SDKIdentityTypeEnum.yahoo:
2293        return dist.IdentityTypeEnum.yahoo;
2294      case SDKIdentityTypeEnum.email:
2295        return dist.IdentityTypeEnum.email;
2296      case SDKIdentityTypeEnum.alias:
2297        return dist.IdentityTypeEnum.alias;
2298      case SDKIdentityTypeEnum.facebookCustomAudienceId:
2299        return dist.IdentityTypeEnum.facebookCustomAudienceId;
2300      case SDKIdentityTypeEnum.otherId2:
2301        return dist.IdentityTypeEnum.otherId2;
2302      case SDKIdentityTypeEnum.otherId3:
2303        return dist.IdentityTypeEnum.otherId3;
2304      case SDKIdentityTypeEnum.otherId4:
2305        return dist.IdentityTypeEnum.otherId4;
2306      case SDKIdentityTypeEnum.otherId5:
2307        return dist.IdentityTypeEnum.otherId5;
2308      case SDKIdentityTypeEnum.otherId6:
2309        return dist.IdentityTypeEnum.otherId6;
2310      case SDKIdentityTypeEnum.otherId7:
2311        return dist.IdentityTypeEnum.otherId7;
2312      case SDKIdentityTypeEnum.otherId8:
2313        return dist.IdentityTypeEnum.otherId8;
2314      case SDKIdentityTypeEnum.otherId9:
2315        return dist.IdentityTypeEnum.otherId9;
2316      case SDKIdentityTypeEnum.otherId10:
2317        return dist.IdentityTypeEnum.otherId10;
2318      case SDKIdentityTypeEnum.mobileNumber:
2319        return dist.IdentityTypeEnum.mobileNumber;
2320      case SDKIdentityTypeEnum.phoneNumber2:
2321        return dist.IdentityTypeEnum.phoneNumber2;
2322      case SDKIdentityTypeEnum.phoneNumber3:
2323        return dist.IdentityTypeEnum.phoneNumber3;
2324    }
2325  }
2326  var StorageResult;
2327  (function(StorageResult2) {
2328    StorageResult2["Success"] = "Success";
2329    StorageResult2["QuotaExceeded"] = "QuotaExceeded";
2330    StorageResult2["Unavailable"] = "Unavailable";
2331  })(StorageResult || (StorageResult = {}));
2332  var isQuotaExceededError = function isQuotaExceededError2(e) {
2333    return e instanceof DOMException && // Standard quota errors, plus Firefox's legacy name/code.
2334    (e.code === 22 || e.code === 1014 || e.name === "QuotaExceededError" || e.name === "NS_ERROR_DOM_QUOTA_REACHED");
2335  };
2336  var BaseVault = (
2337    /** @class */
2338    (function() {
2339      function BaseVault2(storageKey, storageObject) {
2340        this._storageKey = storageKey;
2341        this.storageObject = storageObject;
2342        this.contents = this.retrieve();
2343      }
2344      BaseVault2.prototype.store = function(item) {
2345        var stringifiedItem;
2346        try {
2347          if (isNumber(item) || !isEmpty(item)) {
2348            stringifiedItem = JSON.stringify(item);
2349          } else {
2350            stringifiedItem = "";
2351          }
2352          this.storageObject.setItem(this._storageKey, stringifiedItem);
2353          this.contents = item;
2354          return StorageResult.Success;
2355        } catch (e) {
2356          return isQuotaExceededError(e) ? StorageResult.QuotaExceeded : StorageResult.Unavailable;
2357        }
2358      };
2359      BaseVault2.prototype.retrieve = function() {
2360        try {
2361          var item = this.storageObject.getItem(this._storageKey);
2362          this.contents = item ? JSON.parse(item) : null;
2363        } catch (e) {
2364          this.contents = null;
2365        }
2366        return this.contents;
2367      };
2368      BaseVault2.prototype.purge = function() {
2369        this.contents = null;
2370        try {
2371          this.storageObject.removeItem(this._storageKey);
2372        } catch (e) {
2373        }
2374      };
2375      return BaseVault2;
2376    })()
2377  );
2378  var LocalStorageVault = (
2379    /** @class */
2380    (function(_super) {
2381      __extends(LocalStorageVault2, _super);
2382      function LocalStorageVault2(storageKey) {
2383        return _super.call(this, storageKey, window.localStorage) || this;
2384      }
2385      return LocalStorageVault2;
2386    })(BaseVault)
2387  );
2388  var SessionStorageVault = (
2389    /** @class */
2390    (function(_super) {
2391      __extends(SessionStorageVault2, _super);
2392      function SessionStorageVault2(storageKey) {
2393        return _super.call(this, storageKey, window.sessionStorage) || this;
2394      }
2395      return SessionStorageVault2;
2396    })(BaseVault)
2397  );
2398  var DisabledVault = (
2399    /** @class */
2400    (function(_super) {
2401      __extends(DisabledVault2, _super);
2402      function DisabledVault2(storageKey) {
2403        var _this = _super.call(this, storageKey, window.localStorage) || this;
2404        _this.contents = null;
2405        _this.storageObject.removeItem(_this._storageKey);
2406        return _this;
2407      }
2408      DisabledVault2.prototype.store = function(_item) {
2409        this.contents = null;
2410        return StorageResult.Success;
2411      };
2412      DisabledVault2.prototype.retrieve = function() {
2413        return this.contents;
2414      };
2415      DisabledVault2.prototype.purge = function() {
2416        this.contents = null;
2417      };
2418      return DisabledVault2;
2419    })(BaseVault)
2420  );
2421  var AsyncUploader = (
2422    /** @class */
2423    /* @__PURE__ */ (function() {
2424      function AsyncUploader2(url) {
2425        this.url = url;
2426      }
2427      return AsyncUploader2;
2428    })()
2429  );
2430  var FetchUploader = (
2431    /** @class */
2432    (function(_super) {
2433      __extends(FetchUploader2, _super);
2434      function FetchUploader2() {
2435        return _super !== null && _super.apply(this, arguments) || this;
2436      }
2437      FetchUploader2.prototype.upload = function(fetchPayload, _url) {
2438        return __awaiter(this, void 0, void 0, function() {
2439          var url;
2440          return __generator(this, function(_a2) {
2441            switch (_a2.label) {
2442              case 0:
2443                url = _url || this.url;
2444                return [4, fetch(url, fetchPayload)];
2445              case 1:
2446                return [2, _a2.sent()];
2447            }
2448          });
2449        });
2450      };
2451      return FetchUploader2;
2452    })(AsyncUploader)
2453  );
2454  var XHRUploader = (
2455    /** @class */
2456    (function(_super) {
2457      __extends(XHRUploader2, _super);
2458      function XHRUploader2() {
2459        return _super !== null && _super.apply(this, arguments) || this;
2460      }
2461      XHRUploader2.prototype.upload = function(fetchPayload) {
2462        return __awaiter(this, void 0, void 0, function() {
2463          var response;
2464          return __generator(this, function(_a2) {
2465            switch (_a2.label) {
2466              case 0:
2467                return [4, this.makeRequest(this.url, fetchPayload.body, fetchPayload.method, fetchPayload.headers)];
2468              case 1:
2469                response = _a2.sent();
2470                return [2, response];
2471            }
2472          });
2473        });
2474      };
2475      XHRUploader2.prototype.makeRequest = function(url, data, method, headers) {
2476        if (method === void 0) {
2477          method = "post";
2478        }
2479        if (headers === void 0) {
2480          headers = {};
2481        }
2482        return __awaiter(this, void 0, void 0, function() {
2483          var xhr;
2484          return __generator(this, function(_a2) {
2485            xhr = new XMLHttpRequest();
2486            return [2, new Promise(function(resolve, reject) {
2487              xhr.onreadystatechange = function() {
2488                if (xhr.readyState !== 4) return;
2489                resolve(xhr);
2490              };
2491              xhr.onerror = function() {
2492                reject(xhr);
2493              };
2494              xhr.open(method, url);
2495              for (var key in headers) {
2496                if (headers.hasOwnProperty(key)) {
2497                  xhr.setRequestHeader(key, headers[key]);
2498                }
2499              }
2500              xhr.send(data);
2501            })];
2502          });
2503        });
2504      };
2505      return XHRUploader2;
2506    })(AsyncUploader)
2507  );
2508  function hasMPIDAndUserLoginChanged(previousUser, newUser) {
2509    return !previousUser || newUser.getMPID() !== previousUser.getMPID() || previousUser.isLoggedIn() !== newUser.isLoggedIn();
2510  }
2511  function hasMPIDChanged(prevUser, identityApiResult) {
2512    return !prevUser || prevUser.getMPID() && identityApiResult.mpid && identityApiResult.mpid !== prevUser.getMPID();
2513  }
2514  function appendUserInfo(user, event) {
2515    if (!event) {
2516      return;
2517    }
2518    if (!user) {
2519      event.MPID = null;
2520      event.ConsentState = null;
2521      event.UserAttributes = null;
2522      event.UserIdentities = null;
2523      return;
2524    }
2525    if (event.MPID && event.MPID === user.getMPID()) {
2526      return;
2527    }
2528    event.MPID = user.getMPID();
2529    event.ConsentState = user.getConsentState();
2530    event.UserAttributes = user.getAllUserAttributes();
2531    var userIdentities = user.getUserIdentities().userIdentities;
2532    var dtoUserIdentities = {};
2533    for (var identityKey in userIdentities) {
2534      var identityType = Types.IdentityType.getIdentityType(identityKey);
2535      if (identityType !== false) {
2536        dtoUserIdentities[identityType] = userIdentities[identityKey];
2537      }
2538    }
2539    var validUserIdentities = [];
2540    if (isObject(dtoUserIdentities)) {
2541      if (Object.keys(dtoUserIdentities).length) {
2542        for (var key in dtoUserIdentities) {
2543          var userIdentity = {};
2544          userIdentity.Identity = dtoUserIdentities[key];
2545          userIdentity.Type = parseNumber(key);
2546          validUserIdentities.push(userIdentity);
2547        }
2548      }
2549    }
2550    event.UserIdentities = validUserIdentities;
2551  }
2552  var BatchUploader = (
2553    /** @class */
2554    (function() {
2555      function BatchUploader2(mpInstance, uploadInterval) {
2556        var _a2;
2557        var _b2, _c;
2558        this.offlineStorageEnabled = false;
2559        this.lastASTEventTime = 0;
2560        this.AST_DEBOUNCE_MS = 1e3;
2561        this.uploadIntervalTimerId = null;
2562        this.exitHandler = null;
2563        this.visibilityChangeHandler = null;
2564        this.destroyed = false;
2565        this.mpInstance = mpInstance;
2566        this.uploadIntervalMillis = uploadInterval;
2567        this.batchingEnabled = uploadInterval >= BatchUploader2.MINIMUM_INTERVAL_MILLIS;
2568        if (this.uploadIntervalMillis < BatchUploader2.MINIMUM_INTERVAL_MILLIS) {
2569          this.uploadIntervalMillis = BatchUploader2.MINIMUM_INTERVAL_MILLIS;
2570        }
2571        this.eventsQueuedForProcessing = [];
2572        this.batchesQueuedForProcessing = [];
2573        this.offlineStorageEnabled = this.isOfflineStorageAvailable();
2574        var noFunctional = (_b2 = mpInstance._CookieConsentManager) === null || _b2 === void 0 ? void 0 : _b2.getNoFunctional();
2575        if (this.offlineStorageEnabled && !noFunctional) {
2576          this.eventVault = new SessionStorageVault("".concat(mpInstance._Store.storageName, "-events"));
2577          this.batchVault = new LocalStorageVault("".concat(mpInstance._Store.storageName, "-batches"));
2578          (_a2 = this.eventsQueuedForProcessing).push.apply(_a2, (_c = this.eventVault.retrieve()) !== null && _c !== void 0 ? _c : []);
2579        }
2580        var _d = this.mpInstance._Store, SDKConfig = _d.SDKConfig, devToken = _d.devToken;
2581        var baseUrl = this.mpInstance._Helpers.createServiceUrl(SDKConfig.v3SecureServiceUrl, devToken);
2582        this.uploadUrl = "".concat(baseUrl, "/events");
2583        this.uploader = window.fetch ? new FetchUploader(this.uploadUrl) : new XHRUploader(this.uploadUrl);
2584        this.triggerUploadInterval(true, false);
2585        this.addEventListeners();
2586      }
2587      BatchUploader2.prototype.destroy = function() {
2588        this.destroyed = true;
2589        if (this.uploadIntervalTimerId !== null) {
2590          clearTimeout(this.uploadIntervalTimerId);
2591          this.uploadIntervalTimerId = null;
2592        }
2593        if (this.visibilityChangeHandler) {
2594          document.removeEventListener("visibilitychange", this.visibilityChangeHandler);
2595        }
2596        if (this.exitHandler) {
2597          window.removeEventListener("beforeunload", this.exitHandler);
2598          window.removeEventListener("pagehide", this.exitHandler);
2599        }
2600        this.exitHandler = null;
2601        this.visibilityChangeHandler = null;
2602      };
2603      BatchUploader2.prototype.isOfflineStorageAvailable = function() {
2604        var _a2 = this.mpInstance, getFeatureFlag = _a2._Helpers.getFeatureFlag, deviceId = _a2._Store.deviceId;
2605        var offlineStorageFeatureFlagValue = getFeatureFlag(Constants.FeatureFlags.OfflineStorage);
2606        var offlineStoragePercentage = parseInt(offlineStorageFeatureFlagValue, 10);
2607        var rampNumber = getRampNumber(deviceId);
2608        return offlineStoragePercentage >= rampNumber;
2609      };
2610      BatchUploader2.prototype.shouldDebounceAndUpdateLastASTTime = function() {
2611        var now = Date.now();
2612        if (now - this.lastASTEventTime < this.AST_DEBOUNCE_MS) {
2613          return true;
2614        }
2615        this.lastASTEventTime = now;
2616        return false;
2617      };
2618      BatchUploader2.prototype.createBackgroundASTEvent = function() {
2619        var _a2;
2620        var now = Date.now();
2621        var _b2 = this.mpInstance, _Store = _b2._Store, Identity2 = _b2.Identity, _timeOnSiteTimer = _b2._timeOnSiteTimer, _Helpers = _b2._Helpers;
2622        var sessionId = _Store.sessionId, deviceId = _Store.deviceId, sessionStartDate = _Store.sessionStartDate, SDKConfig = _Store.SDKConfig;
2623        var generateUniqueId2 = _Helpers.generateUniqueId, getFeatureFlag = _Helpers.getFeatureFlag;
2624        var getCurrentUser = Identity2.getCurrentUser;
2625        var event = {
2626          AppName: SDKConfig.appName,
2627          AppVersion: SDKConfig.appVersion,
2628          Package: SDKConfig["package"],
2629          EventDataType: MessageType$1.AppStateTransition,
2630          Timestamp: now,
2631          SessionId: sessionId,
2632          DeviceId: deviceId,
2633          IsFirstRun: false,
2634          SourceMessageId: generateUniqueId2(),
2635          SDKVersion: Constants.sdkVersion,
2636          CustomFlags: {},
2637          EventAttributes: {},
2638          SessionStartDate: (sessionStartDate === null || sessionStartDate === void 0 ? void 0 : sessionStartDate.getTime()) || now,
2639          Debug: SDKConfig.isDevelopmentMode,
2640          ActiveTimeOnSite: (_timeOnSiteTimer === null || _timeOnSiteTimer === void 0 ? void 0 : _timeOnSiteTimer.getTimeInForeground()) || 0,
2641          TotalTimeOnSite: ((_a2 = _Store.getTotalTimeOnSite) === null || _a2 === void 0 ? void 0 : _a2.call(_Store)) || 0,
2642          PageUrl: getHref() || null,
2643          IsBackgroundAST: true
2644        };
2645        var customFlags = __assign({}, event.CustomFlags);
2646        var integrationAttributes = _Store.integrationAttributes;
2647        var integrationSpecificIds = getFeatureFlag(Constants.FeatureFlags.CaptureIntegrationSpecificIds);
2648        var integrationSpecificIdsV2 = getFeatureFlag(Constants.FeatureFlags.CaptureIntegrationSpecificIdsV2) || "";
2649        var isIntegrationCaptureEnabled = integrationSpecificIdsV2 && integrationSpecificIdsV2 !== Constants.CaptureIntegrationSpecificIdsV2Modes.None || integrationSpecificIds === true;
2650        if (isIntegrationCaptureEnabled) {
2651          this.mpInstance._IntegrationCapture.capture();
2652          var transformedClickIDs = this.mpInstance._IntegrationCapture.getClickIdsAsCustomFlags();
2653          customFlags = __assign(__assign({}, transformedClickIDs), customFlags);
2654          var transformedIntegrationAttributes = this.mpInstance._IntegrationCapture.getClickIdsAsIntegrationAttributes();
2655          integrationAttributes = __assign(__assign({}, transformedIntegrationAttributes), integrationAttributes);
2656        }
2657        event.CustomFlags = customFlags;
2658        event.IntegrationAttributes = integrationAttributes;
2659        appendUserInfo(getCurrentUser(), event);
2660        return event;
2661      };
2662      BatchUploader2.prototype.addEventListeners = function() {
2663        var _this_1 = this;
2664        var _this = this;
2665        var handleExit = function handleExit2() {
2666          var getFeatureFlag = _this_1.mpInstance._Helpers.getFeatureFlag;
2667          var AstBackgroundEvents = Constants.FeatureFlags.AstBackgroundEvents;
2668          if (getFeatureFlag(AstBackgroundEvents)) {
2669            if (_this.shouldDebounceAndUpdateLastASTTime()) {
2670              return;
2671            }
2672            var event_1 = _this.createBackgroundASTEvent();
2673            _this.queueEvent(event_1);
2674          }
2675          _this.prepareAndUpload(false, _this.isBeaconAvailable());
2676        };
2677        this.exitHandler = handleExit;
2678        this.visibilityChangeHandler = function() {
2679          if (document.visibilityState === "hidden") {
2680            handleExit();
2681          }
2682        };
2683        document.addEventListener("visibilitychange", this.visibilityChangeHandler);
2684        window.addEventListener("beforeunload", handleExit);
2685        window.addEventListener("pagehide", handleExit);
2686      };
2687      BatchUploader2.prototype.isBeaconAvailable = function() {
2688        if (navigator.sendBeacon) {
2689          return true;
2690        }
2691        return false;
2692      };
2693      BatchUploader2.prototype.triggerUploadInterval = function(triggerFuture, useBeacon) {
2694        var _this_1 = this;
2695        if (triggerFuture === void 0) {
2696          triggerFuture = false;
2697        }
2698        if (useBeacon === void 0) {
2699          useBeacon = false;
2700        }
2701        this.uploadIntervalTimerId = setTimeout(function() {
2702          _this_1.prepareAndUpload(triggerFuture, useBeacon);
2703        }, this.uploadIntervalMillis);
2704      };
2705      BatchUploader2.prototype.queueEvent = function(event) {
2706        if (isEmpty(event)) {
2707          return;
2708        }
2709        this.eventsQueuedForProcessing.push(event);
2710        if (this.offlineStorageEnabled && this.eventVault) {
2711          this.eventVault.store(this.eventsQueuedForProcessing);
2712        }
2713        if (this.mpInstance.Logger.isVerbose()) {
2714          var eventToLog = obfuscateDevData(event, this.mpInstance._Store.SDKConfig.isDevelopmentMode);
2715          this.mpInstance.Logger.verbose("Queuing event: ".concat(JSON.stringify(eventToLog)));
2716          this.mpInstance.Logger.verbose("Queued event count: ".concat(this.eventsQueuedForProcessing.length));
2717        }
2718        if (this.shouldTriggerImmediateUpload(event.EventDataType)) {
2719          this.prepareAndUpload(false, false);
2720        }
2721      };
2722      BatchUploader2.prototype.shouldTriggerImmediateUpload = function(eventDataType) {
2723        var priorityEvents = [MessageType$1.Commerce, MessageType$1.UserIdentityChange];
2724        return !this.batchingEnabled || priorityEvents.includes(eventDataType);
2725      };
2726      BatchUploader2.createNewBatches = function(sdkEvents, defaultUser, mpInstance) {
2727        if (!defaultUser || !sdkEvents || !sdkEvents.length) {
2728          return null;
2729        }
2730        var newUploads = [];
2731        var eventsByUser = /* @__PURE__ */ new Map();
2732        for (var _i = 0, sdkEvents_1 = sdkEvents; _i < sdkEvents_1.length; _i++) {
2733          var sdkEvent = sdkEvents_1[_i];
2734          if (!sdkEvent.MPID) {
2735            var mpid = defaultUser.getMPID();
2736            sdkEvent.MPID = mpid;
2737          }
2738          var events = eventsByUser.get(sdkEvent.MPID);
2739          if (!events) {
2740            events = [];
2741          }
2742          events.push(sdkEvent);
2743          eventsByUser.set(sdkEvent.MPID, events);
2744        }
2745        for (var _a2 = 0, _b2 = Array.from(eventsByUser.entries()); _a2 < _b2.length; _a2++) {
2746          var entry = _b2[_a2];
2747          var mpid = entry[0];
2748          var userEvents = entry[1];
2749          var eventsBySession = /* @__PURE__ */ new Map();
2750          for (var _c = 0, userEvents_1 = userEvents; _c < userEvents_1.length; _c++) {
2751            var sdkEvent = userEvents_1[_c];
2752            var events = eventsBySession.get(sdkEvent.SessionId);
2753            if (!events) {
2754              events = [];
2755            }
2756            events.push(sdkEvent);
2757            eventsBySession.set(sdkEvent.SessionId, events);
2758          }
2759          for (var _d = 0, _e = Array.from(eventsBySession.entries()); _d < _e.length; _d++) {
2760            var entry_1 = _e[_d];
2761            var uploadBatchObject = convertEvents(mpid, entry_1[1], mpInstance);
2762            var onCreateBatchCallback = mpInstance._Store.SDKConfig.onCreateBatch;
2763            if (onCreateBatchCallback) {
2764              uploadBatchObject = onCreateBatchCallback(uploadBatchObject);
2765              if (uploadBatchObject) {
2766                uploadBatchObject.modified = true;
2767              } else {
2768                mpInstance.Logger.warning("Skiping batch upload because no batch was returned from onCreateBatch callback");
2769              }
2770            }
2771            if (uploadBatchObject) {
2772              newUploads.push(uploadBatchObject);
2773            }
2774          }
2775        }
2776        return newUploads;
2777      };
2778      BatchUploader2.prototype.prepareAndUpload = function(triggerFuture, useBeacon) {
2779        var _a2;
2780        if (triggerFuture === void 0) {
2781          triggerFuture = false;
2782        }
2783        if (useBeacon === void 0) {
2784          useBeacon = false;
2785        }
2786        return __awaiter(this, void 0, void 0, function() {
2787          var currentUser, currentEvents, newBatches, batchesToUpload, batchesThatDidNotUpload;
2788          var _b2, _c, _d;
2789          return __generator(this, function(_e) {
2790            switch (_e.label) {
2791              case 0:
2792                currentUser = this.mpInstance.Identity.getCurrentUser();
2793                currentEvents = this.eventsQueuedForProcessing;
2794                this.eventsQueuedForProcessing = [];
2795                if (this.offlineStorageEnabled && this.eventVault) {
2796                  this.eventVault.store([]);
2797                }
2798                newBatches = [];
2799                if (!isEmpty(currentEvents)) {
2800                  newBatches = BatchUploader2.createNewBatches(currentEvents, currentUser, this.mpInstance);
2801                }
2802                if (this.offlineStorageEnabled && this.batchVault) {
2803                  (_b2 = this.batchesQueuedForProcessing).unshift.apply(_b2, (_a2 = this.batchVault.retrieve()) !== null && _a2 !== void 0 ? _a2 : []);
2804                  this.batchVault.purge();
2805                }
2806                if (!isEmpty(newBatches)) {
2807                  (_c = this.batchesQueuedForProcessing).push.apply(_c, newBatches);
2808                }
2809                batchesToUpload = this.batchesQueuedForProcessing;
2810                this.batchesQueuedForProcessing = [];
2811                return [4, this.uploadBatches(batchesToUpload, useBeacon)];
2812              case 1:
2813                batchesThatDidNotUpload = _e.sent();
2814                if (!isEmpty(batchesThatDidNotUpload)) {
2815                  (_d = this.batchesQueuedForProcessing).unshift.apply(_d, batchesThatDidNotUpload);
2816                }
2817                if (!useBeacon && this.offlineStorageEnabled && this.batchVault) {
2818                  this.storeBatchesQueuedForProcessing();
2819                }
2820                if (triggerFuture && !this.destroyed) {
2821                  this.triggerUploadInterval(triggerFuture, false);
2822                }
2823                return [
2824                  2
2825                  /*return*/
2826                ];
2827            }
2828          });
2829        });
2830      };
2831      BatchUploader2.prototype.storeBatchesQueuedForProcessing = function() {
2832        var batches = this.batchesQueuedForProcessing;
2833        if (isEmpty(batches)) {
2834          this.batchVault.store([]);
2835          this.batchesQueuedForProcessing = [];
2836          return;
2837        }
2838        for (var dropped = 0; dropped < batches.length; dropped++) {
2839          var result = this.batchVault.store(batches.slice(dropped));
2840          if (result === StorageResult.Success) {
2841            this.logDroppedOfflineBatches(dropped);
2842            this.batchesQueuedForProcessing = [];
2843            return;
2844          }
2845          if (result === StorageResult.Unavailable) {
2846            this.mpInstance.Logger.warning("Offline batch storage is unavailable. Retaining batches in memory.");
2847            return;
2848          }
2849        }
2850        this.mpInstance.Logger.warning("Offline batch storage is over quota. Retaining batches in memory.");
2851      };
2852      BatchUploader2.prototype.logDroppedOfflineBatches = function(droppedBatchCount) {
2853        if (droppedBatchCount > 0) {
2854          this.mpInstance.Logger.warning("Offline batch storage is over quota. Dropped " + "".concat(droppedBatchCount, " oldest batch(es)."));
2855        }
2856      };
2857      BatchUploader2.prototype.uploadBatches = function(batches, useBeacon) {
2858        return __awaiter(this, void 0, void 0, function() {
2859          var uploads, uploadsToLog, i, fetchPayload, blob, response, e_1;
2860          return __generator(this, function(_a2) {
2861            switch (_a2.label) {
2862              case 0:
2863                uploads = batches.filter(function(batch) {
2864                  return !isEmpty(batch.events);
2865                });
2866                if (isEmpty(uploads)) {
2867                  return [2, null];
2868                }
2869                if (this.mpInstance.Logger.isVerbose()) {
2870                  uploadsToLog = obfuscateDevData(uploads, this.mpInstance._Store.SDKConfig.isDevelopmentMode);
2871                  this.mpInstance.Logger.verbose("Uploading batches: ".concat(JSON.stringify(uploadsToLog)));
2872                  this.mpInstance.Logger.verbose("Batch count: ".concat(uploads.length));
2873                }
2874                i = 0;
2875                _a2.label = 1;
2876              case 1:
2877                if (!(i < uploads.length)) return [3, 6];
2878                fetchPayload = {
2879                  method: "POST",
2880                  headers: {
2881                    Accept: BatchUploader2.CONTENT_TYPE,
2882                    "Content-Type": "text/plain;charset=UTF-8"
2883                  },
2884                  body: JSON.stringify(uploads[i])
2885                };
2886                if (!(useBeacon && this.isBeaconAvailable())) return [3, 2];
2887                blob = new Blob([fetchPayload.body], {
2888                  type: "text/plain;charset=UTF-8"
2889                });
2890                navigator.sendBeacon(this.uploadUrl, blob);
2891                return [3, 5];
2892              case 2:
2893                _a2.trys.push([2, 4, , 5]);
2894                return [4, this.uploader.upload(fetchPayload)];
2895              case 3:
2896                response = _a2.sent();
2897                if (response.status >= 200 && response.status < 300) {
2898                  this.mpInstance.Logger.verbose("Upload success for request ID: ".concat(uploads[i].source_request_id));
2899                } else if (response.status >= 500 || response.status === 429) {
2900                  this.mpInstance.Logger.error("HTTP error status ".concat(response.status, " received"));
2901                  return [2, uploads.slice(i, uploads.length)];
2902                } else if (response.status >= 401) {
2903                  this.mpInstance.Logger.error("HTTP error status ".concat(response.status, " while uploading - please verify your API key."));
2904                  return [2, null];
2905                } else {
2906                  console.error("HTTP error status ".concat(response.status, " while uploading events."), response);
2907                  throw new Error("Uncaught HTTP Error ".concat(response.status, ".  Batch upload will be re-attempted."));
2908                }
2909                return [3, 5];
2910              case 4:
2911                e_1 = _a2.sent();
2912                this.mpInstance.Logger.error("Error sending event to mParticle servers. ".concat(e_1));
2913                return [2, uploads.slice(i, uploads.length)];
2914              case 5:
2915                i++;
2916                return [3, 1];
2917              case 6:
2918                return [2, null];
2919            }
2920          });
2921        });
2922      };
2923      BatchUploader2.CONTENT_TYPE = "text/plain;charset=UTF-8";
2924      BatchUploader2.MINIMUM_INTERVAL_MILLIS = 500;
2925      return BatchUploader2;
2926    })()
2927  );
2928  var ErrorCodes = {
2929    UNKNOWN_ERROR: "UNKNOWN_ERROR",
2930    UNHANDLED_EXCEPTION: "UNHANDLED_EXCEPTION",
2931    IDENTITY_REQUEST: "IDENTITY_REQUEST",
2932    IDENTITY_MISMATCH: "IDENTITY_MISMATCH",
2933    MP_DEPRECATED_METHOD_USAGE: "MP_DEPRECATED_METHOD_USAGE"
2934  };
2935  var WSDKErrorSeverity = {
2936    ERROR: "ERROR",
2937    INFO: "INFO",
2938    WARNING: "WARNING"
2939  };
2940  var Modify$4 = Constants.IdentityMethods.Modify;
2941  var Validators = {
2942    // From ./utils
2943    // Utility Functions for backwards compatability
2944    isNumber,
2945    isFunction,
2946    isStringOrNumber,
2947    // Validator Functions
2948    isValidAttributeValue,
2949    // Validator Functions
2950    // Neither null nor undefined can be a valid Key
2951    isValidKeyValue: function isValidKeyValue(key) {
2952      return Boolean(key && !isObject(key) && !Array.isArray(key) && !this.isFunction(key));
2953    },
2954    removeFalsyIdentityValues: function removeFalsyIdentityValues(identityApiData, logger) {
2955      if (!identityApiData || !identityApiData.userIdentities) {
2956        return identityApiData;
2957      }
2958      var cleanedData = {};
2959      var cleanedUserIdentities = __assign({}, identityApiData.userIdentities);
2960      for (var identityType in identityApiData.userIdentities) {
2961        if (identityApiData.userIdentities.hasOwnProperty(identityType)) {
2962          var value = identityApiData.userIdentities[identityType];
2963          if (value !== null && !value) {
2964            logger.warning("Identity value for '".concat(identityType, "' is falsy (").concat(value, "). This value will be removed from the request."));
2965            delete cleanedUserIdentities[identityType];
2966          }
2967        }
2968      }
2969      cleanedData.userIdentities = cleanedUserIdentities;
2970      return cleanedData;
2971    },
2972    validateIdentities: function validateIdentities(identityApiData, method) {
2973      var validIdentityRequestKeys = {
2974        userIdentities: 1,
2975        onUserAlias: 1,
2976        copyUserAttributes: 1
2977      };
2978      if (identityApiData) {
2979        if (method === Modify$4) {
2980          if (isObject(identityApiData.userIdentities) && !Object.keys(identityApiData.userIdentities).length || !isObject(identityApiData.userIdentities)) {
2981            return {
2982              valid: false,
2983              error: Constants.Messages.ValidationMessages.ModifyIdentityRequestUserIdentitiesPresent
2984            };
2985          }
2986        }
2987        for (var key in identityApiData) {
2988          if (identityApiData.hasOwnProperty(key)) {
2989            if (!validIdentityRequestKeys[key]) {
2990              return {
2991                valid: false,
2992                error: Constants.Messages.ValidationMessages.IdentityRequesetInvalidKey
2993              };
2994            }
2995            if (key === "onUserAlias" && !Validators.isFunction(identityApiData[key])) {
2996              return {
2997                valid: false,
2998                error: Constants.Messages.ValidationMessages.OnUserAliasType
2999              };
3000            }
3001          }
3002        }
3003        if (Object.keys(identityApiData).length === 0) {
3004          return {
3005            valid: true
3006          };
3007        } else {
3008          if (identityApiData.userIdentities === void 0) {
3009            return {
3010              valid: false,
3011              error: Constants.Messages.ValidationMessages.UserIdentities
3012            };
3013          } else if (identityApiData.userIdentities !== null && !isObject(identityApiData.userIdentities)) {
3014            return {
3015              valid: false,
3016              error: Constants.Messages.ValidationMessages.UserIdentities
3017            };
3018          }
3019          if (isObject(identityApiData.userIdentities) && Object.keys(identityApiData.userIdentities).length) {
3020            for (var identityType in identityApiData.userIdentities) {
3021              if (identityApiData.userIdentities.hasOwnProperty(identityType)) {
3022                if (Types.IdentityType.getIdentityType(identityType) === false) {
3023                  return {
3024                    valid: false,
3025                    error: Constants.Messages.ValidationMessages.UserIdentitiesInvalidKey
3026                  };
3027                }
3028                if (!(typeof identityApiData.userIdentities[identityType] === "string" || identityApiData.userIdentities[identityType] === null)) {
3029                  return {
3030                    valid: false,
3031                    error: Constants.Messages.ValidationMessages.UserIdentitiesInvalidValues
3032                  };
3033                }
3034              }
3035            }
3036          }
3037        }
3038      }
3039      return {
3040        valid: true
3041      };
3042    }
3043  };
3044  var HTTPCodes$4 = Constants.HTTPCodes;
3045  var sendSearchRequest = function sendSearchRequest2(knownIdentities, apiKey, requestBuilder, searchUrl, callback, logger, uploader, errorReporter) {
3046    return __awaiter(void 0, void 0, void 0, function() {
3047      var safeInvoke, cleanedKnownIdentities, requestEnvelope, requestBody, fetchPayload, api, response, body, xhrLike, e_2, message, reportMessage;
3048      return __generator(this, function(_a2) {
3049        switch (_a2.label) {
3050          case 0:
3051            if (!isFunction(callback)) {
3052              logger.error("search called without a callback function; skipping request.");
3053              return [
3054                2
3055                /*return*/
3056              ];
3057            }
3058            safeInvoke = function safeInvoke2(result) {
3059              try {
3060                callback(result);
3061              } catch (e) {
3062                logger.error("Error invoking search callback: " + getErrorMessage(e));
3063              }
3064            };
3065            cleanedKnownIdentities = Validators.removeFalsyIdentityValues({
3066              userIdentities: knownIdentities !== null && knownIdentities !== void 0 ? knownIdentities : {}
3067            }, logger).userIdentities;
3068            if (!Object.values(cleanedKnownIdentities !== null && cleanedKnownIdentities !== void 0 ? cleanedKnownIdentities : {}).some(function(v) {
3069              return typeof v === "string" && v.length > 0;
3070            })) {
3071              logger.verbose("Identity search called with empty identifiers; skipping request.");
3072              safeInvoke({
3073                httpCode: HTTPCodes$4.noHttpCoverage
3074              });
3075              return [
3076                2
3077                /*return*/
3078              ];
3079            }
3080            if (!apiKey) {
3081              logger.verbose("search called without a workspace API key; skipping request.");
3082              safeInvoke({
3083                httpCode: HTTPCodes$4.noHttpCoverage
3084              });
3085              return [
3086                2
3087                /*return*/
3088              ];
3089            }
3090            _a2.label = 1;
3091          case 1:
3092            _a2.trys.push([1, 9, , 10]);
3093            requestEnvelope = requestBuilder();
3094            requestBody = __assign(__assign({}, requestEnvelope), {
3095              known_identities: __assign({}, cleanedKnownIdentities)
3096            });
3097            fetchPayload = {
3098              method: "post",
3099              headers: {
3100                Accept: "application/json",
3101                "Content-Type": "application/json",
3102                "x-mp-key": apiKey
3103              },
3104              body: JSON.stringify(requestBody)
3105            };
3106            api = uploader || (window.fetch ? new FetchUploader(searchUrl) : new XHRUploader(searchUrl));
3107            logger.verbose("Sending search request to " + searchUrl);
3108            return [4, api.upload(fetchPayload, searchUrl)];
3109          case 2:
3110            response = _a2.sent();
3111            body = void 0;
3112            if (!isFunction(response.json)) return [3, 7];
3113            _a2.label = 3;
3114          case 3:
3115            _a2.trys.push([3, 5, , 6]);
3116            return [4, response.json()];
3117          case 4:
3118            body = _a2.sent();
3119            return [3, 6];
3120          case 5:
3121            _a2.sent();
3122            logger.verbose("search response had no parseable JSON body.");
3123            return [3, 6];
3124          case 6:
3125            return [3, 8];
3126          case 7:
3127            xhrLike = response;
3128            if (xhrLike === null || xhrLike === void 0 ? void 0 : xhrLike.responseText) {
3129              try {
3130                body = JSON.parse(xhrLike.responseText);
3131              } catch (e) {
3132                logger.verbose("search XHR response was not valid JSON.");
3133              }
3134            }
3135            _a2.label = 8;
3136          case 8:
3137            if (response.status === HTTP_OK) {
3138              logger.verbose("search received 200 OK.");
3139            } else if (response.status === HTTP_NOT_FOUND) {
3140              logger.verbose("search received 404 (no match).");
3141            } else {
3142              logger.verbose("search received non-success status " + response.status);
3143            }
3144            safeInvoke({
3145              httpCode: response.status,
3146              body
3147            });
3148            return [3, 10];
3149          case 9:
3150            e_2 = _a2.sent();
3151            message = getErrorMessage(e_2);
3152            reportMessage = "Error sending search request: " + message;
3153            logger.error(reportMessage);
3154            errorReporter === null || errorReporter === void 0 ? void 0 : errorReporter.report({
3155              message: reportMessage,
3156              code: ErrorCodes.IDENTITY_REQUEST,
3157              severity: WSDKErrorSeverity.ERROR
3158            });
3159            safeInvoke({
3160              httpCode: HTTPCodes$4.noHttpCoverage
3161            });
3162            return [3, 10];
3163          case 10:
3164            return [
3165              2
3166              /*return*/
3167            ];
3168        }
3169      });
3170    });
3171  };
3172  var _a$1 = Constants.IdentityMethods, Identify$2 = _a$1.Identify, Modify$3 = _a$1.Modify, Login$2 = _a$1.Login, Logout$2 = _a$1.Logout;
3173  var HTTPCodes$3 = Constants.HTTPCodes, Messages$9 = Constants.Messages;
3174  var CACHE_HEADER = "x-mp-max-age";
3175  var cacheOrClearIdCache = function cacheOrClearIdCache2(method, knownIdentities, idCache, identityResponse, parsingCachedResponse) {
3176    if (parsingCachedResponse) {
3177      return;
3178    }
3179    var expireTimestamp = getExpireTimestamp(identityResponse === null || identityResponse === void 0 ? void 0 : identityResponse.cacheMaxAge);
3180    switch (method) {
3181      case Login$2:
3182      case Identify$2:
3183        cacheIdentityRequest(method, knownIdentities, expireTimestamp, idCache, identityResponse);
3184        break;
3185      case Modify$3:
3186      case Logout$2:
3187        idCache.purge();
3188        break;
3189    }
3190  };
3191  var cacheIdentityRequest = function cacheIdentityRequest2(method, identities, expireTimestamp, idCache, identityResponse) {
3192    var responseText = identityResponse.responseText, status = identityResponse.status;
3193    var cache = idCache.retrieve() || {};
3194    var cacheKey = concatenateIdentities(method, identities);
3195    var hashedKey = generateHash(cacheKey);
3196    var mpid = responseText.mpid, is_logged_in = responseText.is_logged_in;
3197    var cachedResponseBody = {
3198      mpid,
3199      is_logged_in
3200    };
3201    cache[hashedKey] = {
3202      responseText: JSON.stringify(cachedResponseBody),
3203      status,
3204      expireTimestamp
3205    };
3206    idCache.store(cache);
3207  };
3208  var concatenateIdentities = function concatenateIdentities2(method, userIdentities) {
3209    var DEVICE_APPLICATION_STAMP = "device_application_stamp";
3210    var cacheKey = "".concat(method, ":").concat(DEVICE_APPLICATION_STAMP, "=").concat(userIdentities.device_application_stamp, ";");
3211    var idLength = Object.keys(userIdentities).length;
3212    var concatenatedIdentities = "";
3213    if (idLength) {
3214      var userIDArray = new Array();
3215      for (var key in userIdentities) {
3216        if (key === DEVICE_APPLICATION_STAMP) {
3217          continue;
3218        } else {
3219          userIDArray[Types.IdentityType.getIdentityType(key)] = userIdentities[key];
3220        }
3221      }
3222      concatenatedIdentities = userIDArray.reduce(function(prevValue, currentValue, index) {
3223        var idName = Types.IdentityType.getIdentityName(index);
3224        return "".concat(prevValue).concat(idName, "=").concat(currentValue, ";");
3225      }, cacheKey);
3226    }
3227    return concatenatedIdentities;
3228  };
3229  var hasValidCachedIdentity = function hasValidCachedIdentity2(method, proposedUserIdentities, idCache) {
3230    var cache = idCache === null || idCache === void 0 ? void 0 : idCache.retrieve();
3231    if (!cache) {
3232      return false;
3233    }
3234    var cacheKey = concatenateIdentities(method, proposedUserIdentities);
3235    var hashedKey = generateHash(cacheKey);
3236    if (!cache.hasOwnProperty(hashedKey)) {
3237      return false;
3238    }
3239    var expireTimestamp = cache[hashedKey].expireTimestamp;
3240    if (expireTimestamp < (/* @__PURE__ */ new Date()).getTime()) {
3241      return false;
3242    } else {
3243      return true;
3244    }
3245  };
3246  var getCachedIdentity = function getCachedIdentity2(method, proposedUserIdentities, idCache) {
3247    var cacheKey = concatenateIdentities(method, proposedUserIdentities);
3248    var hashedKey = generateHash(cacheKey);
3249    var cache = idCache.retrieve();
3250    var cachedIdentity = cache ? cache[hashedKey] : null;
3251    return {
3252      responseText: parseIdentityResponse(cachedIdentity.responseText),
3253      expireTimestamp: cachedIdentity.expireTimestamp,
3254      status: cachedIdentity.status
3255    };
3256  };
3257  var createKnownIdentities = function createKnownIdentities2(identityApiData, deviceId) {
3258    var identitiesResult = {};
3259    if (isObject(identityApiData === null || identityApiData === void 0 ? void 0 : identityApiData.userIdentities)) {
3260      for (var identity in identityApiData.userIdentities) {
3261        identitiesResult[identity] = identityApiData.userIdentities[identity];
3262      }
3263    }
3264    identitiesResult.device_application_stamp = deviceId;
3265    return identitiesResult;
3266  };
3267  var removeExpiredIdentityCacheDates = function removeExpiredIdentityCacheDates2(idCache) {
3268    var cache = idCache.retrieve() || {};
3269    var currentTime = (/* @__PURE__ */ new Date()).getTime();
3270    for (var key in cache) {
3271      if (cache[key].expireTimestamp < currentTime) {
3272        delete cache[key];
3273      }
3274    }
3275    idCache.store(cache);
3276  };
3277  var tryCacheIdentity = function tryCacheIdentity2(knownIdentities, idCache, parseIdentityResponse2, mpid, callback, identityApiData, identityMethod) {
3278    var shouldReturnCachedIdentity = hasValidCachedIdentity(identityMethod, knownIdentities, idCache);
3279    if (shouldReturnCachedIdentity) {
3280      var cachedIdentity = getCachedIdentity(identityMethod, knownIdentities, idCache);
3281      parseIdentityResponse2(cachedIdentity, mpid, callback, identityApiData, identityMethod, knownIdentities, true);
3282      return true;
3283    }
3284    return false;
3285  };
3286  var getExpireTimestamp = function getExpireTimestamp2(maxAge) {
3287    if (maxAge === void 0) {
3288      maxAge = ONE_DAY_IN_SECONDS;
3289    }
3290    return (/* @__PURE__ */ new Date()).getTime() + maxAge * MILLIS_IN_ONE_SEC;
3291  };
3292  var parseIdentityResponse = function parseIdentityResponse2(responseText) {
3293    return responseText ? JSON.parse(responseText) : {};
3294  };
3295  var SHA256_IDENTITY_ALIASES = {
3296    email_sha256: "other",
3297    mobile_sha256: "other2"
3298  };
3299  var normalizeUserIdentityKeys = function normalizeUserIdentityKeys2(userIdentities) {
3300    var normalized = __assign({}, userIdentities);
3301    Object.keys(SHA256_IDENTITY_ALIASES).forEach(function(alias) {
3302      if (alias in normalized) {
3303        var value = normalized[alias];
3304        delete normalized[alias];
3305        normalized[SHA256_IDENTITY_ALIASES[alias]] = value;
3306      }
3307    });
3308    return normalized;
3309  };
3310  var identitiesEqual = function identitiesEqual2(a, b) {
3311    var aKeys = Object.keys(a !== null && a !== void 0 ? a : {});
3312    var bKeys = Object.keys(b !== null && b !== void 0 ? b : {});
3313    if (aKeys.length !== bKeys.length) return false;
3314    return aKeys.every(function(key) {
3315      return a[key] === b[key];
3316    });
3317  };
3318  var hasIdentityRequestChanged = function hasIdentityRequestChanged2(currentUser, newIdentityRequest) {
3319    if (!currentUser || !(newIdentityRequest === null || newIdentityRequest === void 0 ? void 0 : newIdentityRequest.userIdentities)) {
3320      return false;
3321    }
3322    var currentUserIdentities = currentUser.getUserIdentities().userIdentities;
3323    var newIdentities = normalizeUserIdentityKeys(newIdentityRequest.userIdentities);
3324    return !identitiesEqual(currentUserIdentities, newIdentities);
3325  };
3326  var hasExplicitIdentifier = function hasExplicitIdentifier2(store) {
3327    var _a2, _b2, _c;
3328    var userIdentities = (_b2 = (_a2 = store === null || store === void 0 ? void 0 : store.SDKConfig) === null || _a2 === void 0 ? void 0 : _a2.identifyRequest) === null || _b2 === void 0 ? void 0 : _b2.userIdentities;
3329    if (userIdentities && isObject(userIdentities) && !isEmpty(userIdentities) && Object.values(userIdentities).some(Boolean)) {
3330      return true;
3331    }
3332    return !!((_c = store === null || store === void 0 ? void 0 : store.SDKConfig) === null || _c === void 0 ? void 0 : _c.deviceId);
3333  };
3334  var buildIdentitySearchEnvelope = function buildIdentitySearchEnvelope2(environment) {
3335    return {
3336      client_sdk: {
3337        platform: Constants.platform,
3338        sdk_vendor: Constants.sdkVendor,
3339        sdk_version: Constants.sdkVersion
3340      },
3341      environment,
3342      request_id: generateUniqueId(),
3343      request_timestamp_ms: Date.now()
3344    };
3345  };
3346  var executeSearchRequest = function executeSearchRequest2(mpInstance, workspaceApiKey, knownIdentities, callback) {
3347    var _Helpers = mpInstance._Helpers, _Store = mpInstance._Store, Logger2 = mpInstance.Logger, _ErrorReportingDispatcher = mpInstance._ErrorReportingDispatcher;
3348    var _a2 = _Store.SDKConfig, identityUrl = _a2.identityUrl, isDevelopmentMode = _a2.isDevelopmentMode;
3349    if (!_Helpers.canLog()) {
3350      Logger2.verbose(Messages$9.InformationMessages.AbandonLogEvent);
3351      if (isFunction(callback)) {
3352        try {
3353          callback({
3354            httpCode: HTTPCodes$3.loggingDisabledOrMissingAPIKey
3355          });
3356        } catch (e) {
3357          Logger2.error("Error invoking search callback: " + getErrorMessage(e));
3358        }
3359      }
3360      return;
3361    }
3362    var serviceUrl = _Helpers.createServiceUrl(identityUrl);
3363    var searchUrl = serviceUrl + "search?cb=1";
3364    var environment = isDevelopmentMode ? "development" : "production";
3365    sendSearchRequest(knownIdentities, workspaceApiKey, function() {
3366      return buildIdentitySearchEnvelope(environment);
3367    }, searchUrl, callback, Logger2, void 0, _ErrorReportingDispatcher);
3368  };
3369  function APIClient(mpInstance, kitBlocker) {
3370    this.uploader = null;
3371    var self = this;
3372    this.queueEventForBatchUpload = function(event) {
3373      if (!this.uploader) {
3374        var millis = parseNumber(mpInstance._Helpers.getFeatureFlag(Constants.FeatureFlags.EventBatchingIntervalMillis));
3375        this.uploader = new BatchUploader(mpInstance, millis);
3376      }
3377      this.uploader.queueEvent(event);
3378      mpInstance._Persistence.update();
3379    };
3380    this.processQueuedEvents = function() {
3381      var mpid, currentUser = mpInstance.Identity.getCurrentUser();
3382      if (currentUser) {
3383        mpid = currentUser.getMPID();
3384      }
3385      if (mpInstance._Store.eventQueue.length && mpid) {
3386        var localQueueCopy = mpInstance._Store.eventQueue;
3387        mpInstance._Store.eventQueue = [];
3388        this.appendUserInfoToEvents(currentUser, localQueueCopy);
3389        localQueueCopy.forEach(function(event) {
3390          self.sendEventToServer(event);
3391        });
3392      }
3393    };
3394    this.appendUserInfoToEvents = function(user, events) {
3395      events.forEach(function(event) {
3396        if (!event.MPID) {
3397          appendUserInfo(user, event);
3398        }
3399      });
3400    };
3401    var handleNoFunctionalPreMpidEvent = function handleNoFunctionalPreMpidEvent2(event, mpid) {
3402      var _a2;
3403      var noFunctionalWithoutId = ((_a2 = mpInstance._CookieConsentManager) === null || _a2 === void 0 ? void 0 : _a2.getNoFunctional()) && !hasExplicitIdentifier(mpInstance._Store);
3404      if (!noFunctionalWithoutId || mpid || !mpInstance._Store.configurationLoaded || mpInstance._Store.requireDelay) {
3405        return false;
3406      }
3407      var forwarderEvent = event;
3408      if (kitBlocker === null || kitBlocker === void 0 ? void 0 : kitBlocker.kitBlockingEnabled) {
3409        forwarderEvent = kitBlocker.createBlockedEvent(event);
3410      }
3411      if (forwarderEvent) {
3412        mpInstance._Forwarders.sendEventToForwarders(forwarderEvent);
3413        event.AlreadySentToForwarders = true;
3414      }
3415      mpInstance.Logger.verbose("noFunctional event forwarded to kits and queued for MP server upload when MPID is available.");
3416      mpInstance._Store.eventQueue.push(event);
3417      return true;
3418    };
3419    this.sendEventToServer = function(event, _options) {
3420      var defaultOptions = {
3421        shouldUploadEvent: true
3422      };
3423      var options = extend(defaultOptions, _options);
3424      if (mpInstance._Store.webviewBridgeEnabled) {
3425        mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.LogEvent, JSON.stringify(event));
3426        return;
3427      }
3428      var mpid, currentUser = mpInstance.Identity.getCurrentUser();
3429      if (currentUser) {
3430        mpid = currentUser.getMPID();
3431      }
3432      mpInstance._Store.requireDelay = mpInstance._Helpers.isDelayedByIntegration(mpInstance._preInit.integrationDelays, mpInstance._Store.integrationDelayTimeoutStart, Date.now());
3433      if (handleNoFunctionalPreMpidEvent(event, mpid)) {
3434        return;
3435      }
3436      if (!mpid || mpInstance._Store.requireDelay || !mpInstance._Store.configurationLoaded) {
3437        mpInstance.Logger.verbose("Event was added to eventQueue. eventQueue will be processed once a valid MPID is returned or there is no more integration imposed delay.");
3438        mpInstance._Store.eventQueue.push(event);
3439        return;
3440      }
3441      this.processQueuedEvents();
3442      if (isEmpty(event)) {
3443        return;
3444      }
3445      if (options.shouldUploadEvent) {
3446        this.queueEventForBatchUpload(event);
3447      }
3448      if (event.EventName !== String(Types.MessageType.AppStateTransition)) {
3449        if (kitBlocker && kitBlocker.kitBlockingEnabled) {
3450          event = kitBlocker.createBlockedEvent(event);
3451        }
3452        if (event && !event.AlreadySentToForwarders) {
3453          mpInstance._Forwarders.sendEventToForwarders(event);
3454        }
3455      }
3456    };
3457    this.sendBatchForwardingStatsToServer = function(forwardingStatsData, xhr) {
3458      var url;
3459      var data;
3460      try {
3461        url = mpInstance._Helpers.createServiceUrl(mpInstance._Store.SDKConfig.v2SecureServiceUrl, mpInstance._Store.devToken);
3462        data = {
3463          uuid: mpInstance._Helpers.generateUniqueId(),
3464          data: forwardingStatsData
3465        };
3466        if (xhr) {
3467          xhr.open("post", url + "/Forwarding");
3468          xhr.send(JSON.stringify(data));
3469        }
3470      } catch (e) {
3471        mpInstance.Logger.error("Error sending forwarding stats to mParticle servers.");
3472      }
3473    };
3474    this.initializeForwarderStatsUploader = function() {
3475      var forwardingDomain = mpInstance._Store.SDKConfig.v1SecureServiceUrl;
3476      var devToken = mpInstance._Store.devToken;
3477      var uploadUrl = "https://".concat(forwardingDomain).concat(devToken, "/Forwarding");
3478      var uploader = window.fetch ? new FetchUploader(uploadUrl) : new XHRUploader(uploadUrl);
3479      return uploader;
3480    };
3481    this.prepareForwardingStats = function(forwarder, event) {
3482      var forwardingStatsData;
3483      var queue = mpInstance._Forwarders.getForwarderStatsQueue();
3484      if (forwarder && forwarder.isVisible) {
3485        forwardingStatsData = {
3486          mid: forwarder.id,
3487          esid: forwarder.eventSubscriptionId,
3488          n: event.EventName,
3489          attrs: event.EventAttributes,
3490          sdk: event.SDKVersion,
3491          dt: event.EventDataType,
3492          et: event.EventCategory,
3493          dbg: event.Debug,
3494          ct: event.Timestamp,
3495          eec: event.ExpandedEventCount,
3496          dp: event.DataPlan
3497        };
3498        var _a2 = mpInstance._Forwarders, sendSingleForwardingStatsToServer = _a2.sendSingleForwardingStatsToServer, setForwarderStatsQueue = _a2.setForwarderStatsQueue;
3499        if (mpInstance._Helpers.getFeatureFlag(Constants.FeatureFlags.ReportBatching)) {
3500          queue.push(forwardingStatsData);
3501          setForwarderStatsQueue(queue);
3502        } else {
3503          sendSingleForwardingStatsToServer(forwardingStatsData);
3504        }
3505      }
3506    };
3507  }
3508  var KitFilterHelper = (
3509    /** @class */
3510    (function() {
3511      function KitFilterHelper2() {
3512      }
3513      KitFilterHelper2.hashEventType = function(eventType) {
3514        return generateHash(eventType);
3515      };
3516      KitFilterHelper2.hashEventName = function(eventName, eventType) {
3517        return generateHash(eventType + eventName);
3518      };
3519      KitFilterHelper2.hashEventAttributeKey = function(eventType, eventName, customAttributeName) {
3520        return generateHash(eventType + eventName + customAttributeName);
3521      };
3522      KitFilterHelper2.hashUserAttribute = function(userAttributeKey) {
3523        return generateHash(userAttributeKey);
3524      };
3525      KitFilterHelper2.hashUserIdentity = function(userIdentity) {
3526        return userIdentity;
3527      };
3528      KitFilterHelper2.hashConsentPurpose = function(prefix, purpose) {
3529        return generateHash(prefix + purpose);
3530      };
3531      KitFilterHelper2.hashAttributeConditionalForwarding = function(attribute) {
3532        return generateHash(attribute).toString();
3533      };
3534      KitFilterHelper2.hashConsentPurposeConditionalForwarding = function(prefix, purpose) {
3535        return this.hashConsentPurpose(prefix, purpose).toString();
3536      };
3537      var _a2;
3538      _a2 = KitFilterHelper2;
3539      KitFilterHelper2.filterUserAttributes = function(userAttributes, filterList) {
3540        return filterDictionaryWithHash(userAttributes, filterList, function(key) {
3541          return _a2.hashUserAttribute(key);
3542        });
3543      };
3544      KitFilterHelper2.filterUserIdentities = function(userIdentities, filterList) {
3545        return filterDictionaryWithHash(userIdentities, filterList, function(key) {
3546          return _a2.hashUserIdentity(IdentityType.getIdentityType(key));
3547        });
3548      };
3549      KitFilterHelper2.isFilteredUserAttribute = function(userAttributeKey, filterList) {
3550        var hashedUserAttribute = _a2.hashUserAttribute(userAttributeKey);
3551        return filterList && inArray(filterList, hashedUserAttribute);
3552      };
3553      return KitFilterHelper2;
3554    })()
3555  );
3556  var StorageNames$1 = Constants.StorageNames;
3557  function appendFilteredUserIdentity(filteredUserIdentities, identity, userIdentityType) {
3558    if (userIdentityType === Types.IdentityType.CustomerId) {
3559      filteredUserIdentities.unshift(identity);
3560    } else {
3561      filteredUserIdentities.push(identity);
3562    }
3563  }
3564  function buildFilteredUserIdentities$1(userIdentitiesObject, filterList, inArray2) {
3565    var filteredUserIdentities = [];
3566    if (!userIdentitiesObject || !Object.keys(userIdentitiesObject).length) {
3567      return filteredUserIdentities;
3568    }
3569    for (var userIdentityName in userIdentitiesObject) {
3570      if (!userIdentitiesObject.hasOwnProperty(userIdentityName)) {
3571        continue;
3572      }
3573      var userIdentityType = Types.IdentityType.getIdentityType(userIdentityName);
3574      if (inArray2(filterList, userIdentityType)) {
3575        continue;
3576      }
3577      appendFilteredUserIdentity(filteredUserIdentities, {
3578        Type: userIdentityType,
3579        Identity: userIdentitiesObject[userIdentityName]
3580      }, userIdentityType);
3581    }
3582    return filteredUserIdentities;
3583  }
3584  function Helpers(mpInstance) {
3585    var self = this;
3586    this.canLog = function() {
3587      if (mpInstance._Store.isEnabled && (mpInstance._Store.devToken || mpInstance._Store.webviewBridgeEnabled)) {
3588        return true;
3589      }
3590      return false;
3591    };
3592    this.getFeatureFlag = function(feature) {
3593      if (mpInstance._Store.SDKConfig.flags.hasOwnProperty(feature)) {
3594        return mpInstance._Store.SDKConfig.flags[feature];
3595      }
3596      return null;
3597    };
3598    this.invokeCallback = function(callback, code, body, mParticleUser, previousMpid) {
3599      if (!callback) {
3600        mpInstance.Logger.warning("There is no callback provided");
3601      }
3602      try {
3603        if (self.Validators.isFunction(callback)) {
3604          callback({
3605            httpCode: code,
3606            body,
3607            getUser: function getUser() {
3608              if (mParticleUser) {
3609                return mParticleUser;
3610              } else {
3611                return mpInstance.Identity.getCurrentUser();
3612              }
3613            },
3614            getPreviousUser: function getPreviousUser() {
3615              if (!previousMpid) {
3616                var users = mpInstance.Identity.getUsers();
3617                var mostRecentUser = users.shift();
3618                var currentUser = mParticleUser || mpInstance.Identity.getCurrentUser();
3619                if (mostRecentUser && currentUser && mostRecentUser.getMPID() === currentUser.getMPID()) {
3620                  mostRecentUser = users.shift();
3621                }
3622                return mostRecentUser || null;
3623              } else {
3624                return mpInstance.Identity.getUser(previousMpid);
3625              }
3626            }
3627          });
3628        }
3629      } catch (e) {
3630        mpInstance.Logger.error("There was an error with your callback: " + e);
3631      }
3632    };
3633    this.invokeAliasCallback = function(callback, code, message) {
3634      if (!callback) {
3635        mpInstance.Logger.warning("There is no callback provided");
3636      }
3637      try {
3638        if (self.Validators.isFunction(callback)) {
3639          var callbackMessage = {
3640            httpCode: code
3641          };
3642          if (message) {
3643            callbackMessage.message = message;
3644          }
3645          callback(callbackMessage);
3646        }
3647      } catch (e) {
3648        mpInstance.Logger.error("There was an error with your callback: " + e);
3649      }
3650    };
3651    this.extend = extend;
3652    this.createServiceUrl = function(secureServiceUrl, devToken) {
3653      var serviceScheme = window.mParticle && mpInstance._Store.SDKConfig.forceHttps ? "https://" : window.location.protocol + "//";
3654      var baseUrl;
3655      if (mpInstance._Store.SDKConfig.forceHttps) {
3656        baseUrl = "https://" + secureServiceUrl;
3657      } else {
3658        baseUrl = serviceScheme + secureServiceUrl;
3659      }
3660      if (devToken) {
3661        baseUrl = baseUrl + devToken;
3662      }
3663      return baseUrl;
3664    };
3665    this.createXHR = function(cb) {
3666      var xhr;
3667      try {
3668        xhr = new window.XMLHttpRequest();
3669      } catch (e) {
3670        mpInstance.Logger.error("Error creating XMLHttpRequest object.");
3671      }
3672      if (xhr && cb && "withCredentials" in xhr) {
3673        xhr.onreadystatechange = cb;
3674      } else if (typeof window.XDomainRequest !== "undefined") {
3675        mpInstance.Logger.verbose("Creating XDomainRequest object");
3676        try {
3677          xhr = new window.XDomainRequest();
3678          xhr.onload = cb;
3679        } catch (e) {
3680          mpInstance.Logger.error("Error creating XDomainRequest object");
3681        }
3682      }
3683      return xhr;
3684    };
3685    this.filterUserIdentities = function(userIdentitiesObject, filterList) {
3686      return buildFilteredUserIdentities$1(userIdentitiesObject, filterList, self.inArray);
3687    };
3688    this.filterUserIdentitiesForForwarders = KitFilterHelper.filterUserIdentities;
3689    this.filterUserAttributes = KitFilterHelper.filterUserAttributes;
3690    this.isEventType = function(type) {
3691      for (var prop in Types.EventType) {
3692        if (Types.EventType.hasOwnProperty(prop)) {
3693          if (Types.EventType[prop] === type) {
3694            return true;
3695          }
3696        }
3697      }
3698      return false;
3699    };
3700    this.sanitizeAttributes = function(attrs, name) {
3701      if (!attrs || !self.isObject(attrs)) {
3702        return null;
3703      }
3704      var sanitizedAttrs = {};
3705      for (var prop in attrs) {
3706        if (attrs.hasOwnProperty(prop) && self.Validators.isValidAttributeValue(attrs[prop])) {
3707          sanitizedAttrs[prop] = attrs[prop];
3708        } else {
3709          mpInstance.Logger.warning("For '" + name + "', the corresponding attribute value of '" + prop + "' must be a string, number, boolean, or null.");
3710        }
3711      }
3712      return sanitizedAttrs;
3713    };
3714    this.isDelayedByIntegration = function(delayedIntegrations, timeoutStart, now) {
3715      if (now - timeoutStart > mpInstance._Store.SDKConfig.integrationDelayTimeout) {
3716        return false;
3717      }
3718      for (var integration in delayedIntegrations) {
3719        if (delayedIntegrations[integration] === true) {
3720          return true;
3721        } else {
3722          continue;
3723        }
3724      }
3725      return false;
3726    };
3727    this.createMainStorageName = function(workspaceToken) {
3728      if (workspaceToken) {
3729        return StorageNames$1.currentStorageName + "_" + workspaceToken;
3730      } else {
3731        return StorageNames$1.currentStorageName;
3732      }
3733    };
3734    this.converted = converted;
3735    this.findKeyInObject = findKeyInObject;
3736    this.parseNumber = parseNumber;
3737    this.inArray = inArray;
3738    this.isObject = isObject;
3739    this.decoded = decoded;
3740    this.parseStringOrNumber = parseStringOrNumber;
3741    this.generateHash = generateHash;
3742    this.generateUniqueId = generateUniqueId;
3743    this.Validators = Validators;
3744  }
3745  var Messages$8 = Constants.Messages;
3746  var androidBridgeNameBase = "mParticleAndroid";
3747  var iosBridgeNameBase = "mParticle";
3748  function getAndroidBridge(name) {
3749    if (!Object.prototype.hasOwnProperty.call(window, name)) {
3750      return void 0;
3751    }
3752    return window[name];
3753  }
3754  function getInstanceNamedValue(instance, name) {
3755    return instance[name];
3756  }
3757  function NativeSdkHelpers(mpInstance) {
3758    var self = this;
3759    this.initializeSessionAttributes = function(apiKey) {
3760      var SetSessionAttribute = Constants.NativeSdkPaths.SetSessionAttribute;
3761      var env = JSON.stringify({
3762        key: "$src_env",
3763        value: "webview"
3764      });
3765      var key = JSON.stringify({
3766        key: "$src_key",
3767        value: apiKey
3768      });
3769      self.sendToNative(SetSessionAttribute, env);
3770      if (apiKey) {
3771        self.sendToNative(SetSessionAttribute, key);
3772      }
3773    };
3774    this.isBridgeV2Available = function(bridgeName) {
3775      var _a2, _b2;
3776      if (!bridgeName) {
3777        return false;
3778      }
3779      var androidBridgeName = androidBridgeNameBase + "_" + bridgeName + "_v2";
3780      var iosBridgeName = iosBridgeNameBase + "_" + bridgeName + "_v2";
3781      if ((_b2 = (_a2 = window.webkit) === null || _a2 === void 0 ? void 0 : _a2.messageHandlers) === null || _b2 === void 0 ? void 0 : _b2.hasOwnProperty(iosBridgeName)) {
3782        return true;
3783      }
3784      if (window.mParticle && window.mParticle.uiwebviewBridgeName && window.mParticle.uiwebviewBridgeName === iosBridgeName) {
3785        return true;
3786      }
3787      if (window.hasOwnProperty(androidBridgeName)) {
3788        return true;
3789      }
3790      return false;
3791    };
3792    this.isWebviewEnabled = function(requiredWebviewBridgeName, minWebviewBridgeVersion) {
3793      mpInstance._Store.bridgeV2Available = self.isBridgeV2Available(requiredWebviewBridgeName);
3794      mpInstance._Store.bridgeV1Available = self.isBridgeV1Available();
3795      if (minWebviewBridgeVersion === 2) {
3796        return mpInstance._Store.bridgeV2Available;
3797      }
3798      if (window.mParticle) {
3799        if (window.mParticle.uiwebviewBridgeName && window.mParticle.uiwebviewBridgeName !== iosBridgeNameBase + "_" + requiredWebviewBridgeName + "_v2") {
3800          return false;
3801        }
3802      }
3803      if (minWebviewBridgeVersion < 2) {
3804        return mpInstance._Store.bridgeV2Available || mpInstance._Store.bridgeV1Available;
3805      }
3806      return false;
3807    };
3808    this.isBridgeV1Available = function() {
3809      if (mpInstance._Store.SDKConfig.useNativeSdk || window.mParticleAndroid || mpInstance._Store.SDKConfig.isIOS) {
3810        return true;
3811      }
3812      return false;
3813    };
3814    this.sendToNative = function(path, value) {
3815      if (mpInstance._Store.bridgeV2Available && mpInstance._Store.SDKConfig.minWebviewBridgeVersion === 2) {
3816        self.sendViaBridgeV2(path, value, mpInstance._Store.SDKConfig.requiredWebviewBridgeName);
3817        return;
3818      }
3819      if (mpInstance._Store.bridgeV2Available && mpInstance._Store.SDKConfig.minWebviewBridgeVersion < 2) {
3820        self.sendViaBridgeV2(path, value, mpInstance._Store.SDKConfig.requiredWebviewBridgeName);
3821        return;
3822      }
3823      if (mpInstance._Store.bridgeV1Available && mpInstance._Store.SDKConfig.minWebviewBridgeVersion < 2) {
3824        self.sendViaBridgeV1(path, value);
3825        return;
3826      }
3827    };
3828    this.sendViaBridgeV1 = function(path, value) {
3829      if (window.mParticleAndroid && window.mParticleAndroid.hasOwnProperty(path)) {
3830        mpInstance.Logger.verbose(Messages$8.InformationMessages.SendAndroid + path);
3831        window.mParticleAndroid[path](value);
3832      } else if (mpInstance._Store.SDKConfig.isIOS) {
3833        mpInstance.Logger.verbose(Messages$8.InformationMessages.SendIOS + path);
3834        self.sendViaIframeToIOS(path, value);
3835      }
3836    };
3837    this.sendViaIframeToIOS = function(path, value) {
3838      var iframe = document.createElement("IFRAME");
3839      iframe.setAttribute("src", "mp-sdk://" + path + "/" + encodeURIComponent(value));
3840      document.documentElement.appendChild(iframe);
3841      iframe.parentNode.removeChild(iframe);
3842    };
3843    this.sendViaBridgeV2 = function(path, value, requiredWebviewBridgeName) {
3844      var _a2, _b2;
3845      if (!requiredWebviewBridgeName) {
3846        return;
3847      }
3848      var androidBridgeName = androidBridgeNameBase + "_" + requiredWebviewBridgeName + "_v2", androidBridge = getAndroidBridge(androidBridgeName), iosBridgeName = iosBridgeNameBase + "_" + requiredWebviewBridgeName + "_v2";
3849      var iOSBridgeMessageHandler, iOSBridgeNonMessageHandler;
3850      if ((_b2 = (_a2 = window.webkit) === null || _a2 === void 0 ? void 0 : _a2.messageHandlers) === null || _b2 === void 0 ? void 0 : _b2[iosBridgeName]) {
3851        iOSBridgeMessageHandler = window.webkit.messageHandlers[iosBridgeName];
3852      }
3853      if (mpInstance.uiwebviewBridgeName === iosBridgeName) {
3854        iOSBridgeNonMessageHandler = getInstanceNamedValue(mpInstance, iosBridgeName);
3855      }
3856      if (androidBridge && androidBridge.hasOwnProperty(path)) {
3857        mpInstance.Logger.verbose(Messages$8.InformationMessages.SendAndroid + path);
3858        androidBridge[path](value);
3859        return;
3860      } else if (iOSBridgeMessageHandler) {
3861        mpInstance.Logger.verbose(Messages$8.InformationMessages.SendIOS + path);
3862        iOSBridgeMessageHandler.postMessage(JSON.stringify({
3863          path,
3864          value: value ? JSON.parse(value) : null
3865        }));
3866      } else if (iOSBridgeNonMessageHandler) {
3867        mpInstance.Logger.verbose(Messages$8.InformationMessages.SendIOS + path);
3868        self.sendViaIframeToIOS(path, value);
3869      }
3870    };
3871  }
3872  var Messages$7 = Constants.Messages;
3873  var InformationMessages = Messages$7.InformationMessages;
3874  var DAYS_IN_MILLISECONDS = 1e3 * 60 * 60 * 24;
3875  var PARTNER_MODULE_IDS = {
3876    AdobeEventForwarder: 11,
3877    DoubleclickDFP: 41,
3878    AppNexus: 50,
3879    Lotame: 58,
3880    TradeDesk: 103,
3881    VerizonMedia: 155,
3882    Rokt: 1277
3883  };
3884  function CookieSyncManager(mpInstance) {
3885    var self = this;
3886    this.attemptCookieSync = function(mpid, mpidIsNotInCookies) {
3887      var _a2;
3888      var _b2 = mpInstance._Store, pixelConfigurations = _b2.pixelConfigurations, webviewBridgeEnabled = _b2.webviewBridgeEnabled;
3889      if (!mpid || webviewBridgeEnabled) {
3890        return;
3891      }
3892      if ((_a2 = mpInstance._CookieConsentManager) === null || _a2 === void 0 ? void 0 : _a2.getNoFunctional()) {
3893        return;
3894      }
3895      var persistence = mpInstance._Persistence.getPersistence();
3896      if (isEmpty(persistence)) {
3897        return;
3898      }
3899      pixelConfigurations.forEach(function(pixelSettings) {
3900        var _a3, _b3, _c;
3901        var requiresConsent = false;
3902        var filteringConsentRuleValues = pixelSettings.filteringConsentRuleValues, pixelUrl = pixelSettings.pixelUrl, redirectUrl = pixelSettings.redirectUrl, moduleId = pixelSettings.moduleId, settings = pixelSettings.settings, frequencyCap = pixelSettings.frequencyCap;
3903        var values = (filteringConsentRuleValues || {}).values;
3904        if (isEmpty(pixelUrl)) {
3905          return;
3906        }
3907        if (!isEmpty(values)) {
3908          requiresConsent = true;
3909        }
3910        if (requiresConsent && mpidIsNotInCookies) {
3911          return;
3912        }
3913        if (moduleId === PARTNER_MODULE_IDS.Rokt && mpInstance._CookieConsentManager.getNoTargeting()) {
3914          return;
3915        }
3916        var isEnabledForUserConsent = mpInstance._Consent.isEnabledForUserConsent;
3917        if (!isEnabledForUserConsent(filteringConsentRuleValues, mpInstance.Identity.getCurrentUser())) {
3918          return;
3919        }
3920        var cookieSyncDates = (_b3 = (_a3 = persistence[mpid]) === null || _a3 === void 0 ? void 0 : _a3.csd) !== null && _b3 !== void 0 ? _b3 : {};
3921        var lastSyncDateForModule = cookieSyncDates[moduleId] || null;
3922        if (!isLastSyncDateExpired(frequencyCap, lastSyncDateForModule)) {
3923          return;
3924        }
3925        var domain = moduleId === PARTNER_MODULE_IDS.TradeDesk ? window.location.hostname : void 0;
3926        var enableHmTag = ((_c = settings === null || settings === void 0 ? void 0 : settings.enableHmTag) === null || _c === void 0 ? void 0 : _c.toLowerCase()) === "true";
3927        var isDoubleClickModule = moduleId === PARTNER_MODULE_IDS.DoubleclickDFP;
3928        var base64Mpid = isDoubleClickModule && enableHmTag ? toWebSafeBase64(mpid) : void 0;
3929        var fullUrl = createCookieSyncUrl(mpid, pixelUrl, redirectUrl, domain, base64Mpid);
3930        self.performCookieSync(fullUrl, moduleId.toString(), mpid, cookieSyncDates);
3931      });
3932    };
3933    this.performCookieSync = function(url, moduleId, mpid, cookieSyncDates) {
3934      var img = document.createElement("img");
3935      mpInstance.Logger.verbose(InformationMessages.CookieSync);
3936      img.onload = function() {
3937        cookieSyncDates[moduleId] = (/* @__PURE__ */ new Date()).getTime();
3938        mpInstance._Persistence.saveUserCookieSyncDatesToPersistence(mpid, cookieSyncDates);
3939      };
3940      img.src = url;
3941    };
3942  }
3943  var isLastSyncDateExpired = function isLastSyncDateExpired2(frequencyCap, lastSyncDate) {
3944    if (!lastSyncDate) {
3945      return true;
3946    }
3947    return (/* @__PURE__ */ new Date()).getTime() > new Date(lastSyncDate).getTime() + frequencyCap * DAYS_IN_MILLISECONDS;
3948  };
3949  function logDeprecatedMethodUsage(usage, logger, errorReporter) {
3950    logger.warning(usage.warningMessage);
3951    errorReporter === null || errorReporter === void 0 ? void 0 : errorReporter.report({
3952      message: usage.methodName,
3953      code: ErrorCodes.MP_DEPRECATED_METHOD_USAGE,
3954      severity: WSDKErrorSeverity.WARNING
3955    });
3956  }
3957  var Messages$6 = Constants.Messages;
3958  function SessionManager(mpInstance) {
3959    var self = this;
3960    this.initialize = function() {
3961      var _a2;
3962      if (mpInstance._Store.sessionId) {
3963        var _b2 = mpInstance._Store, dateLastEventSent = _b2.dateLastEventSent, SDKConfig = _b2.SDKConfig;
3964        var sessionTimeout = SDKConfig.sessionTimeout;
3965        if (hasSessionTimedOut(dateLastEventSent === null || dateLastEventSent === void 0 ? void 0 : dateLastEventSent.getTime(), sessionTimeout)) {
3966          self.endSession();
3967          self.startNewSession();
3968        } else {
3969          var currentUser = mpInstance.Identity.getCurrentUser();
3970          var sdkIdentityRequest = SDKConfig.identifyRequest;
3971          var shouldSuppressIdentify = ((_a2 = mpInstance._CookieConsentManager) === null || _a2 === void 0 ? void 0 : _a2.getNoFunctional()) && !hasExplicitIdentifier(mpInstance._Store);
3972          if (!shouldSuppressIdentify && hasIdentityRequestChanged(currentUser, sdkIdentityRequest)) {
3973            mpInstance.Identity.identify(sdkIdentityRequest, SDKConfig.identityCallback);
3974            mpInstance._Store.identifyCalled = true;
3975            mpInstance._Store.SDKConfig.identityCallback = null;
3976          }
3977        }
3978      } else {
3979        self.startNewSession();
3980      }
3981    };
3982    this.getSession = function() {
3983      logDeprecatedMethodUsage({
3984        methodName: "SessionManager.getSession()",
3985        warningMessage: generateDeprecationMessage("SessionManager.getSession()", false, "SessionManager.getSessionId()")
3986      }, mpInstance.Logger, mpInstance._ErrorReportingDispatcher);
3987      return this.getSessionId();
3988    };
3989    this.getSessionId = function() {
3990      return mpInstance._Store.sessionId;
3991    };
3992    this.startNewSession = function() {
3993      var _a2;
3994      mpInstance.Logger.verbose(Messages$6.InformationMessages.StartingNewSession);
3995      if (mpInstance._Helpers.canLog()) {
3996        mpInstance._Store.sessionId = mpInstance._Helpers.generateUniqueId().toUpperCase();
3997        var currentUser = mpInstance.Identity.getCurrentUser();
3998        var mpid = currentUser ? currentUser.getMPID() : null;
3999        if (mpid) {
4000          mpInstance._Store.currentSessionMPIDs = [mpid];
4001        }
4002        if (!mpInstance._Store.sessionStartDate) {
4003          var date = /* @__PURE__ */ new Date();
4004          mpInstance._Store.sessionStartDate = date;
4005          mpInstance._Store.dateLastEventSent = date;
4006        }
4007        self.setSessionTimer();
4008        var shouldSuppressIdentify = ((_a2 = mpInstance._CookieConsentManager) === null || _a2 === void 0 ? void 0 : _a2.getNoFunctional()) && !hasExplicitIdentifier(mpInstance._Store);
4009        if (!mpInstance._Store.identifyCalled && !shouldSuppressIdentify) {
4010          mpInstance.Identity.identify(mpInstance._Store.SDKConfig.identifyRequest, mpInstance._Store.SDKConfig.identityCallback);
4011          mpInstance._Store.identifyCalled = true;
4012          mpInstance._Store.SDKConfig.identityCallback = null;
4013        }
4014        mpInstance._Events.logEvent({
4015          messageType: Types.MessageType.SessionStart
4016        });
4017      } else {
4018        mpInstance.Logger.verbose(Messages$6.InformationMessages.AbandonStartSession);
4019      }
4020    };
4021    this.endSession = function(override) {
4022      var _a2, _b2, _c, _d;
4023      mpInstance.Logger.verbose(Messages$6.InformationMessages.StartingEndSession);
4024      if (override) {
4025        performSessionEnd();
4026        return;
4027      }
4028      if (!mpInstance._Helpers.canLog()) {
4029        mpInstance.Logger.verbose(Messages$6.InformationMessages.AbandonEndSession);
4030        (_a2 = mpInstance._timeOnSiteTimer) === null || _a2 === void 0 ? void 0 : _a2.resetTimer();
4031        return;
4032      }
4033      var cookies = mpInstance._Persistence.getPersistence();
4034      if (!cookies || cookies.gs && !cookies.gs.sid) {
4035        mpInstance.Logger.verbose(Messages$6.InformationMessages.NoSessionToEnd);
4036        (_b2 = mpInstance._timeOnSiteTimer) === null || _b2 === void 0 ? void 0 : _b2.resetTimer();
4037        return;
4038      }
4039      if (cookies.gs.sid && mpInstance._Store.sessionId !== cookies.gs.sid) {
4040        mpInstance._Store.sessionId = cookies.gs.sid;
4041      }
4042      if ((_c = cookies === null || cookies === void 0 ? void 0 : cookies.gs) === null || _c === void 0 ? void 0 : _c.les) {
4043        var sessionTimeout = mpInstance._Store.SDKConfig.sessionTimeout;
4044        if (hasSessionTimedOut(cookies.gs.les, sessionTimeout)) {
4045          performSessionEnd();
4046        } else {
4047          self.setSessionTimer();
4048          (_d = mpInstance._timeOnSiteTimer) === null || _d === void 0 ? void 0 : _d.resetTimer();
4049        }
4050      }
4051    };
4052    this.setSessionTimer = function() {
4053      var sessionTimeoutInMilliseconds = mpInstance._Store.SDKConfig.sessionTimeout * 6e4;
4054      mpInstance._Store.globalTimer = window.setTimeout(function() {
4055        self.endSession();
4056      }, sessionTimeoutInMilliseconds);
4057    };
4058    this.resetSessionTimer = function() {
4059      if (!mpInstance._Store.webviewBridgeEnabled) {
4060        if (!mpInstance._Store.sessionId) {
4061          self.startNewSession();
4062        }
4063        self.clearSessionTimeout();
4064        self.setSessionTimer();
4065      }
4066      self.startNewSessionIfNeeded();
4067    };
4068    this.clearSessionTimeout = function() {
4069      clearTimeout(mpInstance._Store.globalTimer);
4070    };
4071    this.startNewSessionIfNeeded = function() {
4072      if (!mpInstance._Store.webviewBridgeEnabled) {
4073        var persistence = mpInstance._Persistence.getPersistence();
4074        if (!mpInstance._Store.sessionId && persistence) {
4075          if (persistence.sid) {
4076            mpInstance._Store.sessionId = persistence.sid;
4077          } else {
4078            self.startNewSession();
4079          }
4080        }
4081      }
4082    };
4083    function hasSessionTimedOut(lastEventTimestamp, sessionTimeout) {
4084      if (!lastEventTimestamp || !sessionTimeout || sessionTimeout <= 0) {
4085        return false;
4086      }
4087      var sessionTimeoutInMilliseconds = sessionTimeout * 6e4;
4088      var timeSinceLastEvent = Date.now() - lastEventTimestamp;
4089      return timeSinceLastEvent >= sessionTimeoutInMilliseconds;
4090    }
4091    function performSessionEnd() {
4092      var _a2;
4093      mpInstance._Events.logEvent({
4094        messageType: Types.MessageType.SessionEnd
4095      });
4096      mpInstance._Store.nullifySession();
4097      (_a2 = mpInstance._timeOnSiteTimer) === null || _a2 === void 0 ? void 0 : _a2.resetTimer();
4098    }
4099  }
4100  var Messages$5 = Constants.Messages;
4101  function Ecommerce(mpInstance) {
4102    var self = this;
4103    this.convertTransactionAttributesToProductAction = function(transactionAttributes, productAction) {
4104      if (transactionAttributes.hasOwnProperty("Id")) {
4105        productAction.TransactionId = transactionAttributes.Id;
4106      }
4107      if (transactionAttributes.hasOwnProperty("Affiliation")) {
4108        productAction.Affiliation = transactionAttributes.Affiliation;
4109      }
4110      if (transactionAttributes.hasOwnProperty("CouponCode")) {
4111        productAction.CouponCode = transactionAttributes.CouponCode;
4112      }
4113      if (transactionAttributes.hasOwnProperty("Revenue")) {
4114        productAction.TotalAmount = this.sanitizeAmount(transactionAttributes.Revenue, "Revenue");
4115      }
4116      if (transactionAttributes.hasOwnProperty("Shipping")) {
4117        productAction.ShippingAmount = this.sanitizeAmount(transactionAttributes.Shipping, "Shipping");
4118      }
4119      if (transactionAttributes.hasOwnProperty("Tax")) {
4120        productAction.TaxAmount = this.sanitizeAmount(transactionAttributes.Tax, "Tax");
4121      }
4122      if (transactionAttributes.hasOwnProperty("Step")) {
4123        productAction.CheckoutStep = transactionAttributes.Step;
4124      }
4125      if (transactionAttributes.hasOwnProperty("Option")) {
4126        productAction.CheckoutOptions = transactionAttributes.Option;
4127      }
4128    };
4129    this.calculateProductActionTotalAmount = function(productAction) {
4130      if (!productAction || productAction.TotalAmount != null) {
4131        return productAction;
4132      }
4133      var totalAmount = 0;
4134      if (Array.isArray(productAction.ProductList)) {
4135        productAction.ProductList.forEach(function(product) {
4136          totalAmount += parseNumber(product.Quantity) * parseNumber(product.Price);
4137        });
4138      }
4139      totalAmount += parseNumber(productAction.ShippingAmount) + parseNumber(productAction.TaxAmount);
4140      productAction.TotalAmount = totalAmount;
4141      return productAction;
4142    };
4143    this.getProductActionEventName = function(productActionType) {
4144      switch (productActionType) {
4145        case Types.ProductActionType.AddToCart:
4146          return "AddToCart";
4147        case Types.ProductActionType.AddToWishlist:
4148          return "AddToWishlist";
4149        case Types.ProductActionType.Checkout:
4150          return "Checkout";
4151        case Types.ProductActionType.CheckoutOption:
4152          return "CheckoutOption";
4153        case Types.ProductActionType.Click:
4154          return "Click";
4155        case Types.ProductActionType.Purchase:
4156          return "Purchase";
4157        case Types.ProductActionType.Refund:
4158          return "Refund";
4159        case Types.ProductActionType.RemoveFromCart:
4160          return "RemoveFromCart";
4161        case Types.ProductActionType.RemoveFromWishlist:
4162          return "RemoveFromWishlist";
4163        case Types.ProductActionType.ViewDetail:
4164          return "ViewDetail";
4165        case Types.ProductActionType.ViewCart:
4166          return "ViewCart";
4167        case Types.ProductActionType.AddShippingInfo:
4168          return "AddShippingInfo";
4169        case Types.ProductActionType.AddPaymentInfo:
4170          return "AddPaymentInfo";
4171        case Types.ProductActionType.PaymentMethodSelected:
4172          return "PaymentMethodSelected";
4173        case Types.ProductActionType.PaymentAttempted:
4174          return "PaymentAttempted";
4175        case Types.ProductActionType.PaymentSucceeded:
4176          return "PaymentSucceeded";
4177        case Types.ProductActionType.PaymentFailed:
4178          return "PaymentFailed";
4179        case Types.ProductActionType.RefundInitiated:
4180          return "RefundInitiated";
4181        case Types.ProductActionType.Unknown:
4182        default:
4183          return "Unknown";
4184      }
4185    };
4186    this.getPromotionActionEventName = function(promotionActionType) {
4187      switch (promotionActionType) {
4188        case Types.PromotionActionType.PromotionClick:
4189          return "PromotionClick";
4190        case Types.PromotionActionType.PromotionView:
4191          return "PromotionView";
4192        default:
4193          return "Unknown";
4194      }
4195    };
4196    this.convertProductActionToEventType = function(productActionType) {
4197      switch (productActionType) {
4198        case Types.ProductActionType.AddToCart:
4199          return Types.CommerceEventType.ProductAddToCart;
4200        case Types.ProductActionType.AddToWishlist:
4201          return Types.CommerceEventType.ProductAddToWishlist;
4202        case Types.ProductActionType.Checkout:
4203          return Types.CommerceEventType.ProductCheckout;
4204        case Types.ProductActionType.CheckoutOption:
4205          return Types.CommerceEventType.ProductCheckoutOption;
4206        case Types.ProductActionType.Click:
4207          return Types.CommerceEventType.ProductClick;
4208        case Types.ProductActionType.Purchase:
4209          return Types.CommerceEventType.ProductPurchase;
4210        case Types.ProductActionType.Refund:
4211          return Types.CommerceEventType.ProductRefund;
4212        case Types.ProductActionType.RemoveFromCart:
4213          return Types.CommerceEventType.ProductRemoveFromCart;
4214        case Types.ProductActionType.RemoveFromWishlist:
4215          return Types.CommerceEventType.ProductRemoveFromWishlist;
4216        // https://go.mparticle.com/work/SQDSDKS-4801
4217        case Types.ProductActionType.Unknown:
4218          return Types.EventType.Unknown;
4219        case Types.ProductActionType.ViewDetail:
4220          return Types.CommerceEventType.ProductViewDetail;
4221        // Rokt Brain commerce-adjacent types map to Unknown on server
4222        case Types.ProductActionType.ViewCart:
4223        case Types.ProductActionType.AddShippingInfo:
4224        case Types.ProductActionType.AddPaymentInfo:
4225        case Types.ProductActionType.PaymentMethodSelected:
4226        case Types.ProductActionType.PaymentAttempted:
4227        case Types.ProductActionType.PaymentSucceeded:
4228        case Types.ProductActionType.PaymentFailed:
4229        case Types.ProductActionType.RefundInitiated:
4230          return Types.EventType.Unknown;
4231        default:
4232          mpInstance.Logger.error("Could not convert product action type " + productActionType + " to event type");
4233          return null;
4234      }
4235    };
4236    this.convertPromotionActionToEventType = function(promotionActionType) {
4237      switch (promotionActionType) {
4238        case Types.PromotionActionType.PromotionClick:
4239          return Types.CommerceEventType.PromotionClick;
4240        case Types.PromotionActionType.PromotionView:
4241          return Types.CommerceEventType.PromotionView;
4242        default:
4243          mpInstance.Logger.error("Could not convert promotion action type " + promotionActionType + " to event type");
4244          return null;
4245      }
4246    };
4247    this.generateExpandedEcommerceName = function(eventName, plusOne) {
4248      return "eCommerce - " + eventName + " - " + (plusOne ? "Total" : "Item");
4249    };
4250    this.extractProductAttributes = function(attributes, product) {
4251      if (product.CouponCode) {
4252        attributes["Coupon Code"] = product.CouponCode;
4253      }
4254      if (product.Brand) {
4255        attributes["Brand"] = product.Brand;
4256      }
4257      if (product.Category) {
4258        attributes["Category"] = product.Category;
4259      }
4260      if (product.Name) {
4261        attributes["Name"] = product.Name;
4262      }
4263      if (product.Sku) {
4264        attributes["Id"] = product.Sku;
4265      }
4266      if (product.Price) {
4267        attributes["Item Price"] = product.Price;
4268      }
4269      if (product.Quantity) {
4270        attributes["Quantity"] = product.Quantity;
4271      }
4272      if (product.Position) {
4273        attributes["Position"] = product.Position;
4274      }
4275      if (product.Variant) {
4276        attributes["Variant"] = product.Variant;
4277      }
4278      attributes["Total Product Amount"] = product.TotalAmount || 0;
4279    };
4280    this.extractTransactionId = function(attributes, productAction) {
4281      if (productAction.TransactionId) {
4282        attributes["Transaction Id"] = productAction.TransactionId;
4283      }
4284    };
4285    this.extractActionAttributes = function(attributes, productAction) {
4286      self.extractTransactionId(attributes, productAction);
4287      if (productAction.Affiliation) {
4288        attributes["Affiliation"] = productAction.Affiliation;
4289      }
4290      if (productAction.CouponCode) {
4291        attributes["Coupon Code"] = productAction.CouponCode;
4292      }
4293      if (productAction.TotalAmount) {
4294        attributes["Total Amount"] = productAction.TotalAmount;
4295      }
4296      if (productAction.ShippingAmount) {
4297        attributes["Shipping Amount"] = productAction.ShippingAmount;
4298      }
4299      if (productAction.TaxAmount) {
4300        attributes["Tax Amount"] = productAction.TaxAmount;
4301      }
4302      if (productAction.CheckoutOptions) {
4303        attributes["Checkout Options"] = productAction.CheckoutOptions;
4304      }
4305      if (productAction.CheckoutStep) {
4306        attributes["Checkout Step"] = productAction.CheckoutStep;
4307      }
4308    };
4309    this.extractPromotionAttributes = function(attributes, promotion) {
4310      if (promotion.Id) {
4311        attributes["Id"] = promotion.Id;
4312      }
4313      if (promotion.Creative) {
4314        attributes["Creative"] = promotion.Creative;
4315      }
4316      if (promotion.Name) {
4317        attributes["Name"] = promotion.Name;
4318      }
4319      if (promotion.Position) {
4320        attributes["Position"] = promotion.Position;
4321      }
4322    };
4323    this.buildProductList = function(event, product) {
4324      if (product) {
4325        if (Array.isArray(product)) {
4326          return product;
4327        }
4328        return [product];
4329      }
4330      return event.ShoppingCart.ProductList;
4331    };
4332    this.createProduct = function(name, sku, price, quantity, variant, category, brand, position, couponCode, attributes) {
4333      attributes = mpInstance._Helpers.sanitizeAttributes(attributes, name);
4334      if (typeof name !== "string") {
4335        mpInstance.Logger.error("Name is required when creating a product");
4336        return null;
4337      }
4338      if (!mpInstance._Helpers.Validators.isStringOrNumber(sku)) {
4339        mpInstance.Logger.error("SKU is required when creating a product, and must be a string or a number");
4340        return null;
4341      }
4342      if (!mpInstance._Helpers.Validators.isStringOrNumber(price)) {
4343        mpInstance.Logger.error("Price is required when creating a product, and must be a string or a number");
4344        return null;
4345      } else {
4346        price = mpInstance._Helpers.parseNumber(price);
4347      }
4348      if (position && !mpInstance._Helpers.Validators.isNumber(position)) {
4349        mpInstance.Logger.error("Position must be a number, it will be set to null.");
4350        position = null;
4351      }
4352      if (!mpInstance._Helpers.Validators.isStringOrNumber(quantity)) {
4353        quantity = 1;
4354      } else {
4355        quantity = mpInstance._Helpers.parseNumber(quantity);
4356      }
4357      return {
4358        Name: name,
4359        Sku: sku,
4360        Price: price,
4361        Quantity: quantity,
4362        Brand: brand,
4363        Variant: variant,
4364        Category: category,
4365        Position: position,
4366        CouponCode: couponCode,
4367        TotalAmount: quantity * price,
4368        Attributes: attributes
4369      };
4370    };
4371    this.createPromotion = function(id, creative, name, position) {
4372      if (!mpInstance._Helpers.Validators.isStringOrNumber(id)) {
4373        mpInstance.Logger.error(Messages$5.ErrorMessages.PromotionIdRequired);
4374        return null;
4375      }
4376      return {
4377        Id: id,
4378        Creative: creative,
4379        Name: name,
4380        Position: position
4381      };
4382    };
4383    this.createImpression = function(name, product) {
4384      if (typeof name !== "string") {
4385        mpInstance.Logger.error("Name is required when creating an impression.");
4386        return null;
4387      }
4388      if (!product) {
4389        mpInstance.Logger.error("Product is required when creating an impression.");
4390        return null;
4391      }
4392      return {
4393        Name: name,
4394        Product: product
4395      };
4396    };
4397    this.createTransactionAttributes = function(id, affiliation, couponCode, revenue, shipping, tax) {
4398      if (!mpInstance._Helpers.Validators.isStringOrNumber(id)) {
4399        mpInstance.Logger.error(Messages$5.ErrorMessages.TransactionIdRequired);
4400        return null;
4401      }
4402      return {
4403        Id: id,
4404        Affiliation: affiliation,
4405        CouponCode: couponCode,
4406        Revenue: revenue,
4407        Shipping: shipping,
4408        Tax: tax
4409      };
4410    };
4411    this.expandProductImpression = function(commerceEvent) {
4412      var appEvents = [];
4413      if (!commerceEvent.ProductImpressions) {
4414        return appEvents;
4415      }
4416      commerceEvent.ProductImpressions.forEach(function(productImpression) {
4417        if (productImpression.ProductList) {
4418          productImpression.ProductList.forEach(function(product) {
4419            var attributes = extend(false, {}, commerceEvent.EventAttributes);
4420            if (product.Attributes) {
4421              for (var attribute in product.Attributes) {
4422                attributes[attribute] = product.Attributes[attribute];
4423              }
4424            }
4425            self.extractProductAttributes(attributes, product);
4426            if (productImpression.ProductImpressionList) {
4427              attributes["Product Impression List"] = productImpression.ProductImpressionList;
4428            }
4429            var appEvent = mpInstance._ServerModel.createEventObject({
4430              messageType: Types.MessageType.PageEvent,
4431              name: self.generateExpandedEcommerceName("Impression"),
4432              data: attributes,
4433              eventType: Types.EventType.Transaction
4434            });
4435            appEvents.push(appEvent);
4436          });
4437        }
4438      });
4439      return appEvents;
4440    };
4441    this.expandCommerceEvent = function(event) {
4442      if (!event) {
4443        return null;
4444      }
4445      return self.expandProductAction(event).concat(self.expandPromotionAction(event)).concat(self.expandProductImpression(event));
4446    };
4447    this.expandPromotionAction = function(commerceEvent) {
4448      var appEvents = [];
4449      if (!commerceEvent.PromotionAction) {
4450        return appEvents;
4451      }
4452      var promotions = commerceEvent.PromotionAction.PromotionList;
4453      promotions.forEach(function(promotion) {
4454        var attributes = extend(false, {}, commerceEvent.EventAttributes);
4455        self.extractPromotionAttributes(attributes, promotion);
4456        var appEvent = mpInstance._ServerModel.createEventObject({
4457          messageType: Types.MessageType.PageEvent,
4458          name: self.generateExpandedEcommerceName(Types.PromotionActionType.getExpansionName(commerceEvent.PromotionAction.PromotionActionType)),
4459          data: attributes,
4460          eventType: Types.EventType.Transaction
4461        });
4462        appEvents.push(appEvent);
4463      });
4464      return appEvents;
4465    };
4466    this.expandProductAction = function(commerceEvent) {
4467      var appEvents = [];
4468      if (!commerceEvent.ProductAction) {
4469        return appEvents;
4470      }
4471      var shouldExtractActionAttributes = false;
4472      if (commerceEvent.ProductAction.ProductActionType === Types.ProductActionType.Purchase || commerceEvent.ProductAction.ProductActionType === Types.ProductActionType.Refund) {
4473        var attributes = extend(false, {}, commerceEvent.EventAttributes);
4474        attributes["Product Count"] = commerceEvent.ProductAction.ProductList ? commerceEvent.ProductAction.ProductList.length : 0;
4475        self.extractActionAttributes(attributes, commerceEvent.ProductAction);
4476        if (commerceEvent.CurrencyCode) {
4477          attributes["Currency Code"] = commerceEvent.CurrencyCode;
4478        }
4479        var plusOneEvent = mpInstance._ServerModel.createEventObject({
4480          messageType: Types.MessageType.PageEvent,
4481          name: self.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(commerceEvent.ProductAction.ProductActionType), true),
4482          data: attributes,
4483          eventType: Types.EventType.Transaction
4484        });
4485        appEvents.push(plusOneEvent);
4486      } else {
4487        shouldExtractActionAttributes = true;
4488      }
4489      var products = commerceEvent.ProductAction.ProductList;
4490      if (!products) {
4491        return appEvents;
4492      }
4493      products.forEach(function(product) {
4494        var attributes2 = extend(false, commerceEvent.EventAttributes, product.Attributes);
4495        if (shouldExtractActionAttributes) {
4496          self.extractActionAttributes(attributes2, commerceEvent.ProductAction);
4497        } else {
4498          self.extractTransactionId(attributes2, commerceEvent.ProductAction);
4499        }
4500        self.extractProductAttributes(attributes2, product);
4501        var productEvent = mpInstance._ServerModel.createEventObject({
4502          messageType: Types.MessageType.PageEvent,
4503          name: self.generateExpandedEcommerceName(Types.ProductActionType.getExpansionName(commerceEvent.ProductAction.ProductActionType)),
4504          data: attributes2,
4505          eventType: Types.EventType.Transaction
4506        });
4507        appEvents.push(productEvent);
4508      });
4509      return appEvents;
4510    };
4511    this.createCommerceEventObject = function(customFlags, options) {
4512      var baseEvent;
4513      var extend2 = mpInstance._Helpers.extend;
4514      mpInstance.Logger.verbose(Messages$5.InformationMessages.StartingLogCommerceEvent);
4515      if (mpInstance._Helpers.canLog()) {
4516        baseEvent = mpInstance._ServerModel.createEventObject({
4517          messageType: Types.MessageType.Commerce,
4518          sourceMessageId: options === null || options === void 0 ? void 0 : options.sourceMessageId
4519        });
4520        baseEvent.EventName = "eCommerce - ";
4521        baseEvent.CurrencyCode = mpInstance._Store.currencyCode;
4522        baseEvent.ShoppingCart = [];
4523        baseEvent.CustomFlags = extend2(baseEvent.CustomFlags, customFlags);
4524        return baseEvent;
4525      } else {
4526        mpInstance.Logger.verbose(Messages$5.InformationMessages.AbandonLogEvent);
4527      }
4528      return null;
4529    };
4530    this.sanitizeAmount = function(amount, category) {
4531      if (!mpInstance._Helpers.Validators.isStringOrNumber(amount)) {
4532        var message = [category, "must be of type number. A", _typeof(amount), "was passed. Converting to 0"].join(" ");
4533        mpInstance.Logger.warning(message);
4534        return 0;
4535      }
4536      return mpInstance._Helpers.parseNumber(amount);
4537    };
4538  }
4539  var ForegroundTimeTracker = (
4540    /** @class */
4541    (function() {
4542      function ForegroundTimeTracker2(timerKey, noFunctional) {
4543        if (noFunctional === void 0) {
4544          noFunctional = false;
4545        }
4546        this.noFunctional = noFunctional;
4547        this.isTrackerActive = false;
4548        this.localStorageName = "";
4549        this.startTime = 0;
4550        this.totalTime = 0;
4551        this.localStorageName = "mprtcl-tos-".concat(timerKey);
4552        this.timerVault = new LocalStorageVault(this.localStorageName);
4553        if (!this.noFunctional) {
4554          this.loadTimeFromStorage();
4555        }
4556        this.addHandlers();
4557        if (document.hidden === false) {
4558          this.startTracking();
4559        }
4560      }
4561      ForegroundTimeTracker2.prototype.addHandlers = function() {
4562        var _this = this;
4563        document.addEventListener("visibilitychange", function() {
4564          return _this.handleVisibilityChange();
4565        });
4566        window.addEventListener("blur", function() {
4567          return _this.handleWindowBlur();
4568        });
4569        window.addEventListener("focus", function() {
4570          return _this.handleWindowFocus();
4571        });
4572        window.addEventListener("storage", function(event) {
4573          return _this.syncAcrossTabs(event);
4574        });
4575        window.addEventListener("beforeunload", function() {
4576          return _this.updateTimeInPersistence();
4577        });
4578      };
4579      ForegroundTimeTracker2.prototype.handleVisibilityChange = function() {
4580        if (document.hidden) {
4581          this.stopTracking();
4582        } else {
4583          this.startTracking();
4584        }
4585      };
4586      ForegroundTimeTracker2.prototype.handleWindowBlur = function() {
4587        if (this.isTrackerActive) {
4588          this.stopTracking();
4589        }
4590      };
4591      ForegroundTimeTracker2.prototype.handleWindowFocus = function() {
4592        if (!this.isTrackerActive) {
4593          this.startTracking();
4594        }
4595      };
4596      ForegroundTimeTracker2.prototype.syncAcrossTabs = function(event) {
4597        if (event.key === this.localStorageName && event.newValue !== null) {
4598          var newTime = parseFloat(event.newValue) || 0;
4599          this.totalTime = newTime;
4600        }
4601      };
4602      ForegroundTimeTracker2.prototype.updateTimeInPersistence = function() {
4603        if (this.isTrackerActive && !this.noFunctional) {
4604          this.timerVault.store(Math.round(this.totalTime));
4605        }
4606      };
4607      ForegroundTimeTracker2.prototype.loadTimeFromStorage = function() {
4608        var storedTime = this.timerVault.retrieve();
4609        if (isNumber(storedTime) && storedTime !== null) {
4610          this.totalTime = storedTime;
4611        }
4612      };
4613      ForegroundTimeTracker2.prototype.startTracking = function() {
4614        if (!document.hidden) {
4615          this.startTime = Math.floor(performance.now());
4616          this.isTrackerActive = true;
4617        }
4618      };
4619      ForegroundTimeTracker2.prototype.stopTracking = function() {
4620        if (this.isTrackerActive) {
4621          this.setTotalTime();
4622          this.updateTimeInPersistence();
4623          this.isTrackerActive = false;
4624        }
4625      };
4626      ForegroundTimeTracker2.prototype.setTotalTime = function() {
4627        if (this.isTrackerActive) {
4628          var now = Math.floor(performance.now());
4629          this.totalTime += now - this.startTime;
4630          this.startTime = now;
4631        }
4632      };
4633      ForegroundTimeTracker2.prototype.getTimeInForeground = function() {
4634        this.setTotalTime();
4635        this.updateTimeInPersistence();
4636        return this.totalTime;
4637      };
4638      ForegroundTimeTracker2.prototype.resetTimer = function() {
4639        this.totalTime = 0;
4640        this.updateTimeInPersistence();
4641      };
4642      return ForegroundTimeTracker2;
4643    })()
4644  );
4645  function normalizeRoktLauncherOptions(launcherOptions) {
4646    var normalizedOptions = launcherOptions ? __assign({}, launcherOptions) : {};
4647    var hasNoDeviceId = normalizedOptions.noDeviceId === true || normalizedOptions.noDeviceID === true;
4648    if (hasNoDeviceId) {
4649      normalizedOptions.noDeviceId = true;
4650      normalizedOptions.noFunctional = true;
4651      normalizedOptions.noTargeting = true;
4652    }
4653    return normalizedOptions;
4654  }
4655  function createSDKConfig(config) {
4656    var sdkConfig = {};
4657    for (var prop in Constants.DefaultConfig) {
4658      if (Constants.DefaultConfig.hasOwnProperty(prop)) {
4659        sdkConfig[prop] = Constants.DefaultConfig[prop];
4660      }
4661    }
4662    if (config) {
4663      for (var prop in config) {
4664        if (config.hasOwnProperty(prop)) {
4665          sdkConfig[prop] = config[prop];
4666        }
4667      }
4668    }
4669    for (var prop in Constants.DefaultBaseUrls) {
4670      sdkConfig[prop] = Constants.DefaultBaseUrls[prop];
4671    }
4672    sdkConfig.flags = sdkConfig.flags || {};
4673    return sdkConfig;
4674  }
4675  function Store(config, mpInstance, apiKey) {
4676    var _this = this;
4677    var createMainStorageName = mpInstance._Helpers.createMainStorageName;
4678    var isWebviewEnabled = mpInstance._NativeSdkHelpers.isWebviewEnabled;
4679    var defaultStore = {
4680      isEnabled: true,
4681      sessionAttributes: {},
4682      localSessionAttributes: {},
4683      currentSessionMPIDs: [],
4684      consentState: null,
4685      sessionId: null,
4686      isFirstRun: null,
4687      clientId: null,
4688      deviceId: null,
4689      devToken: null,
4690      serverSettings: {},
4691      dateLastEventSent: null,
4692      sessionStartDate: null,
4693      currentPosition: null,
4694      isTracking: false,
4695      watchPositionId: null,
4696      cartProducts: [],
4697      eventQueue: [],
4698      currencyCode: null,
4699      globalTimer: null,
4700      context: null,
4701      configurationLoaded: false,
4702      identityCallInFlight: false,
4703      identityCallFailed: false,
4704      identifyRequestCount: 0,
4705      SDKConfig: {},
4706      nonCurrentUserMPIDs: {},
4707      identifyCalled: false,
4708      isLoggedIn: false,
4709      cookieSyncDates: {},
4710      integrationAttributes: {},
4711      requireDelay: true,
4712      isLocalStorageAvailable: null,
4713      storageName: null,
4714      activeForwarders: [],
4715      kits: {},
4716      sideloadedKits: [],
4717      configuredForwarders: [],
4718      pixelConfigurations: [],
4719      wrapperSDKInfo: {
4720        name: "none",
4721        version: null,
4722        isInfoSet: false
4723      },
4724      roktAccountId: null,
4725      integrationName: null,
4726      // Placeholder for in-memory persistence model
4727      persistenceData: {
4728        gs: {}
4729      }
4730    };
4731    for (var key in defaultStore) {
4732      this[key] = defaultStore[key];
4733    }
4734    this.devToken = apiKey || null;
4735    this.integrationDelayTimeoutStart = Date.now();
4736    this.SDKConfig = createSDKConfig(config);
4737    if (config) {
4738      if (!config.hasOwnProperty("flags")) {
4739        this.SDKConfig.flags = {};
4740      }
4741      this.SDKConfig.flags = processFlags(config);
4742      if (config.deviceId) {
4743        this.deviceId = config.deviceId;
4744      }
4745      if (config.hasOwnProperty("isDevelopmentMode")) {
4746        this.SDKConfig.isDevelopmentMode = returnConvertedBoolean(config.isDevelopmentMode);
4747      } else {
4748        this.SDKConfig.isDevelopmentMode = false;
4749      }
4750      var baseUrls = processBaseUrls(config, this.SDKConfig.flags, apiKey);
4751      for (var baseUrlKeys in baseUrls) {
4752        this.SDKConfig[baseUrlKeys] = baseUrls[baseUrlKeys];
4753      }
4754      this.SDKConfig.useNativeSdk = !!config.useNativeSdk;
4755      this.SDKConfig.kits = config.kits || {};
4756      this.SDKConfig.sideloadedKits = config.sideloadedKits || [];
4757      if (config.hasOwnProperty("isIOS")) {
4758        this.SDKConfig.isIOS = config.isIOS;
4759      } else {
4760        this.SDKConfig.isIOS = window.mParticle && window.mParticle.isIOS ? window.mParticle.isIOS : false;
4761      }
4762      if (config.hasOwnProperty("useCookieStorage")) {
4763        this.SDKConfig.useCookieStorage = config.useCookieStorage;
4764      } else {
4765        this.SDKConfig.useCookieStorage = false;
4766      }
4767      if (config.hasOwnProperty("maxProducts")) {
4768        this.SDKConfig.maxProducts = config.maxProducts;
4769      } else {
4770        this.SDKConfig.maxProducts = Constants.DefaultConfig.maxProducts;
4771      }
4772      if (config.hasOwnProperty("maxCookieSize")) {
4773        this.SDKConfig.maxCookieSize = config.maxCookieSize;
4774      } else {
4775        this.SDKConfig.maxCookieSize = Constants.DefaultConfig.maxCookieSize;
4776      }
4777      if (config.hasOwnProperty("appName")) {
4778        this.SDKConfig.appName = config.appName;
4779      }
4780      if (config.hasOwnProperty("package")) {
4781        this.SDKConfig["package"] = config["package"];
4782      }
4783      if (config.hasOwnProperty("integrationDelayTimeout")) {
4784        this.SDKConfig.integrationDelayTimeout = config.integrationDelayTimeout;
4785      } else {
4786        this.SDKConfig.integrationDelayTimeout = Constants.DefaultConfig.integrationDelayTimeout;
4787      }
4788      if (config.hasOwnProperty("identifyRequest")) {
4789        this.SDKConfig.identifyRequest = config.identifyRequest;
4790      }
4791      if (config.hasOwnProperty("identityCallback")) {
4792        var callback = config.identityCallback;
4793        if (mpInstance._Helpers.Validators.isFunction(callback)) {
4794          this.SDKConfig.identityCallback = config.identityCallback;
4795        } else {
4796          mpInstance.Logger.warning("The optional callback must be a function. You tried entering a(n) " + _typeof(callback) + " . Callback not set. Please set your callback again.");
4797        }
4798      }
4799      if (config.hasOwnProperty("appVersion")) {
4800        this.SDKConfig.appVersion = config.appVersion;
4801      }
4802      if (config.hasOwnProperty("appName")) {
4803        this.SDKConfig.appName = config.appName;
4804      }
4805      if (config.hasOwnProperty("sessionTimeout")) {
4806        this.SDKConfig.sessionTimeout = config.sessionTimeout;
4807      }
4808      if (config.hasOwnProperty("dataPlan")) {
4809        this.SDKConfig.dataPlan = {
4810          PlanVersion: null,
4811          PlanId: null
4812        };
4813        var dataPlan = config.dataPlan;
4814        if (dataPlan.planId) {
4815          if (isDataPlanSlug(dataPlan.planId)) {
4816            this.SDKConfig.dataPlan.PlanId = dataPlan.planId;
4817          } else {
4818            mpInstance.Logger.error("Your data plan id must be a string and match the data plan slug format (i.e. under_case_slug)");
4819          }
4820        }
4821        if (dataPlan.planVersion) {
4822          if (isNumber(dataPlan.planVersion)) {
4823            this.SDKConfig.dataPlan.PlanVersion = dataPlan.planVersion;
4824          } else {
4825            mpInstance.Logger.error("Your data plan version must be a number");
4826          }
4827        }
4828      } else {
4829        this.SDKConfig.dataPlan = {};
4830      }
4831      if (config.hasOwnProperty("forceHttps")) {
4832        this.SDKConfig.forceHttps = config.forceHttps;
4833      } else {
4834        this.SDKConfig.forceHttps = true;
4835      }
4836      this.SDKConfig.customFlags = config.customFlags || {};
4837      if (config.hasOwnProperty("minWebviewBridgeVersion")) {
4838        this.SDKConfig.minWebviewBridgeVersion = config.minWebviewBridgeVersion;
4839      } else {
4840        this.SDKConfig.minWebviewBridgeVersion = 1;
4841      }
4842      if (config.hasOwnProperty("aliasMaxWindow")) {
4843        this.SDKConfig.aliasMaxWindow = config.aliasMaxWindow;
4844      } else {
4845        this.SDKConfig.aliasMaxWindow = Constants.DefaultConfig.aliasMaxWindow;
4846      }
4847      if (config.hasOwnProperty("dataPlanOptions")) {
4848        var dataPlanOptions = config.dataPlanOptions;
4849        if (!dataPlanOptions.hasOwnProperty("dataPlanVersion") || !dataPlanOptions.hasOwnProperty("blockUserAttributes") || !dataPlanOptions.hasOwnProperty("blockEventAttributes") || !dataPlanOptions.hasOwnProperty("blockEvents") || !dataPlanOptions.hasOwnProperty("blockUserIdentities")) {
4850          mpInstance.Logger.error('Ensure your config.dataPlanOptions object has the following keys: a "dataPlanVersion" object, and "blockUserAttributes", "blockEventAttributes", "blockEvents", "blockUserIdentities" booleans');
4851        }
4852      }
4853      if (config.hasOwnProperty("onCreateBatch")) {
4854        if (typeof config.onCreateBatch === "function") {
4855          this.SDKConfig.onCreateBatch = config.onCreateBatch;
4856        } else {
4857          mpInstance.Logger.error("config.onCreateBatch must be a function");
4858          this.SDKConfig.onCreateBatch = void 0;
4859        }
4860      }
4861    }
4862    this._getFromPersistence = function(mpid, key2) {
4863      if (!mpid) {
4864        return null;
4865      }
4866      _this.syncPersistenceData();
4867      if (_this.persistenceData && _this.persistenceData[mpid] && _this.persistenceData[mpid][key2]) {
4868        return _this.persistenceData[mpid][key2];
4869      } else {
4870        return null;
4871      }
4872    };
4873    this._setPersistence = function(mpid, key2, value) {
4874      var _a2;
4875      if (!mpid) {
4876        return;
4877      }
4878      _this.syncPersistenceData();
4879      if (_this.persistenceData) {
4880        if (_this.persistenceData[mpid]) {
4881          _this.persistenceData[mpid][key2] = value;
4882        } else {
4883          _this.persistenceData[mpid] = (_a2 = {}, _a2[key2] = value, _a2);
4884        }
4885        if (isObject(_this.persistenceData[mpid][key2]) && isEmpty(_this.persistenceData[mpid][key2])) {
4886          delete _this.persistenceData[mpid][key2];
4887        }
4888        mpInstance._Persistence.savePersistence(_this.persistenceData);
4889      }
4890    };
4891    this.hasInvalidIdentifyRequest = function() {
4892      var identifyRequest = _this.SDKConfig.identifyRequest;
4893      return isObject(identifyRequest) && isObject(identifyRequest.userIdentities) && isEmpty(identifyRequest.userIdentities) || !identifyRequest;
4894    };
4895    this.getConsentState = function(mpid) {
4896      var fromMinifiedJsonObject = mpInstance._Consent.ConsentSerialization.fromMinifiedJsonObject;
4897      var serializedConsentState = _this._getFromPersistence(mpid, "con");
4898      if (!isEmpty(serializedConsentState)) {
4899        return fromMinifiedJsonObject(serializedConsentState);
4900      }
4901      return null;
4902    };
4903    this.setConsentState = function(mpid, consentState) {
4904      var toMinifiedJsonObject = mpInstance._Consent.ConsentSerialization.toMinifiedJsonObject;
4905      if (consentState || consentState === null) {
4906        _this._setPersistence(mpid, "con", toMinifiedJsonObject(consentState));
4907      }
4908    };
4909    this.getDeviceId = function() {
4910      return _this.deviceId;
4911    };
4912    this.setDeviceId = function(deviceId) {
4913      _this.deviceId = deviceId;
4914      _this.persistenceData.gs.das = deviceId;
4915      mpInstance._Persistence.update();
4916    };
4917    this.getFirstSeenTime = function(mpid) {
4918      return _this._getFromPersistence(mpid, "fst");
4919    };
4920    this.setFirstSeenTime = function(mpid, _time) {
4921      if (!mpid) {
4922        return;
4923      }
4924      var time = _time || (/* @__PURE__ */ new Date()).getTime();
4925      _this._setPersistence(mpid, "fst", time);
4926    };
4927    this.getLastSeenTime = function(mpid) {
4928      if (!mpid) {
4929        return null;
4930      }
4931      var currentUser = mpInstance.Identity.getCurrentUser();
4932      if (mpid === (currentUser === null || currentUser === void 0 ? void 0 : currentUser.getMPID())) {
4933        return (/* @__PURE__ */ new Date()).getTime();
4934      }
4935      return _this._getFromPersistence(mpid, "lst");
4936    };
4937    this.setLastSeenTime = function(mpid, _time) {
4938      if (!mpid) {
4939        return;
4940      }
4941      var time = _time || (/* @__PURE__ */ new Date()).getTime();
4942      _this._setPersistence(mpid, "lst", time);
4943    };
4944    this.getLocalSessionAttributes = function() {
4945      return _this.localSessionAttributes || {};
4946    };
4947    this.setLocalSessionAttribute = function(key2, value) {
4948      var _a2;
4949      _this.localSessionAttributes[key2] = value;
4950      _this.persistenceData.gs.lsa = __assign(__assign({}, _this.persistenceData.gs.lsa || {}), (_a2 = {}, _a2[key2] = value, _a2));
4951      mpInstance._Persistence.savePersistence(_this.persistenceData);
4952    };
4953    this.syncPersistenceData = function() {
4954      var persistenceData = mpInstance._Persistence.getPersistence();
4955      _this.persistenceData = extend({}, _this.persistenceData, persistenceData);
4956    };
4957    this.getUserAttributes = function(mpid) {
4958      return _this._getFromPersistence(mpid, "ua") || {};
4959    };
4960    this.setUserAttributes = function(mpid, userAttributes) {
4961      return _this._setPersistence(mpid, "ua", userAttributes);
4962    };
4963    this.getUserIdentities = function(mpid) {
4964      return _this._getFromPersistence(mpid, "ui") || {};
4965    };
4966    this.setUserIdentities = function(mpid, userIdentities) {
4967      _this._setPersistence(mpid, "ui", userIdentities);
4968    };
4969    this.getRoktAccountId = function() {
4970      return _this.roktAccountId;
4971    };
4972    this.setRoktAccountId = function(accountId) {
4973      _this.roktAccountId = accountId;
4974    };
4975    this.getIntegrationName = function() {
4976      return _this.integrationName;
4977    };
4978    this.setIntegrationName = function(integrationName) {
4979      _this.integrationName = integrationName;
4980    };
4981    this.getTimeOnSite = function() {
4982      var _a2;
4983      return (_a2 = mpInstance._timeOnSiteTimer) === null || _a2 === void 0 ? void 0 : _a2.getTimeInForeground();
4984    };
4985    this.getTotalTimeOnSite = function() {
4986      return _this.sessionStartDate ? Date.now() - _this.sessionStartDate.getTime() : void 0;
4987    };
4988    this.addMpidToSessionHistory = function(mpid, previousMPID) {
4989      var indexOfMPID = _this.currentSessionMPIDs.indexOf(mpid);
4990      if (mpid && previousMPID !== mpid && indexOfMPID < 0) {
4991        _this.currentSessionMPIDs.push(mpid);
4992        return;
4993      }
4994      if (indexOfMPID >= 0) {
4995        _this.currentSessionMPIDs = moveElementToEnd(_this.currentSessionMPIDs, indexOfMPID);
4996      }
4997    };
4998    this.nullifySession = function() {
4999      _this.sessionId = null;
5000      _this.dateLastEventSent = null;
5001      _this.sessionStartDate = null;
5002      _this.sessionAttributes = {};
5003      _this.localSessionAttributes = {};
5004      mpInstance._Persistence.update();
5005    };
5006    this.processConfig = function(config2) {
5007      var workspaceToken = config2.workspaceToken, requiredWebviewBridgeName = config2.requiredWebviewBridgeName;
5008      if (config2.flags) {
5009        _this.SDKConfig.flags = processFlags(config2);
5010      }
5011      var baseUrls2 = processBaseUrls(config2, _this.SDKConfig.flags, apiKey);
5012      for (var baseUrlKeys2 in baseUrls2) {
5013        _this.SDKConfig[baseUrlKeys2] = baseUrls2[baseUrlKeys2];
5014      }
5015      if (workspaceToken) {
5016        _this.SDKConfig.workspaceToken = workspaceToken;
5017        var noFunctional = normalizeRoktLauncherOptions(config2 === null || config2 === void 0 ? void 0 : config2.launcherOptions).noFunctional;
5018        mpInstance._timeOnSiteTimer = new ForegroundTimeTracker(workspaceToken, noFunctional);
5019      } else {
5020        mpInstance.Logger.warning("You should have a workspaceToken on your config object for security purposes.");
5021      }
5022      _this.storageName = createMainStorageName(workspaceToken);
5023      _this.SDKConfig.requiredWebviewBridgeName = requiredWebviewBridgeName || workspaceToken;
5024      _this.webviewBridgeEnabled = isWebviewEnabled(_this.SDKConfig.requiredWebviewBridgeName, _this.SDKConfig.minWebviewBridgeVersion);
5025      _this.configurationLoaded = true;
5026    };
5027  }
5028  function processFlags(config) {
5029    var flags = {};
5030    var _a2 = Constants.FeatureFlags, ReportBatching2 = _a2.ReportBatching, EventBatchingIntervalMillis = _a2.EventBatchingIntervalMillis, OfflineStorage = _a2.OfflineStorage, DirectUrlRouting = _a2.DirectUrlRouting, CacheIdentity2 = _a2.CacheIdentity, AudienceAPI = _a2.AudienceAPI, CaptureIntegrationSpecificIds2 = _a2.CaptureIntegrationSpecificIds, CaptureIntegrationSpecificIdsV22 = _a2.CaptureIntegrationSpecificIdsV2, AstBackgroundEvents = _a2.AstBackgroundEvents, AutoLogPageView = _a2.AutoLogPageView;
5031    if (!config.flags) {
5032      return {};
5033    }
5034    flags[ReportBatching2] = config.flags[ReportBatching2] || false;
5035    flags[EventBatchingIntervalMillis] = parseNumber(config.flags[EventBatchingIntervalMillis]
5035) || Constants.DefaultConfig.uploadInterval;
5036    flags[OfflineStorage] = config.flags[OfflineStorage] || "0";
5037    flags[DirectUrlRouting] = config.flags[DirectUrlRouting] === "True";
5038    flags[CacheIdentity2] = config.flags[CacheIdentity2] === "True";
5039    flags[AudienceAPI] = config.flags[AudienceAPI] === "True";
5040    flags[CaptureIntegrationSpecificIds2] = config.flags[CaptureIntegrationSpecificIds2] === "True";
5041    flags[CaptureIntegrationSpecificIdsV22] = config.flags[CaptureIntegrationSpecificIdsV22] || "none";
5042    flags[AstBackgroundEvents] = config.flags[AstBackgroundEvents] === "True";
5043    flags[AutoLogPageView] = config.flags[AutoLogPageView] === "True";
5044    return flags;
5045  }
5046  function processBaseUrls(config, flags, apiKey) {
5047    if (!apiKey) {
5048      return {};
5049    }
5050    if (!isEmpty(config.domain)) {
5051      return processCustomBaseUrls(config);
5052    }
5053    if (flags.directURLRouting) {
5054      return processDirectBaseUrls(config, apiKey);
5055    } else {
5056      return processCustomBaseUrls(config);
5057    }
5058  }
5059  function processCustomBaseUrls(config) {
5060    var defaultBaseUrls = Constants.DefaultBaseUrls;
5061    var CNAMEUrlPaths = Constants.CNAMEUrlPaths;
5062    var newBaseUrls = {};
5063    if (!isEmpty(config.domain)) {
5064      for (var pathKey in CNAMEUrlPaths) {
5065        newBaseUrls[pathKey] = "".concat(config.domain).concat(CNAMEUrlPaths[pathKey]);
5066      }
5067      return newBaseUrls;
5068    }
5069    for (var baseUrlKey in defaultBaseUrls) {
5070      newBaseUrls[baseUrlKey] = config[baseUrlKey] || defaultBaseUrls[baseUrlKey];
5071    }
5072    return newBaseUrls;
5073  }
5074  function processDirectBaseUrls(config, apiKey) {
5075    var defaultBaseUrls = Constants.DefaultBaseUrls;
5076    var directBaseUrls = {};
5077    var DEFAULT_SILO = "us1";
5078    var splitKey = apiKey.split("-");
5079    var routingPrefix = splitKey.length <= 1 ? DEFAULT_SILO : splitKey[0];
5080    for (var baseUrlKey in defaultBaseUrls) {
5081      if (baseUrlKey === "configUrl") {
5082        directBaseUrls[baseUrlKey] = config[baseUrlKey] || defaultBaseUrls[baseUrlKey];
5083        continue;
5084      }
5085      if (config.hasOwnProperty(baseUrlKey)) {
5086        directBaseUrls[baseUrlKey] = config[baseUrlKey];
5087      } else {
5088        var urlparts = defaultBaseUrls[baseUrlKey].split(".");
5089        directBaseUrls[baseUrlKey] = __spreadArray([urlparts[0], routingPrefix], urlparts.slice(1), true).join(".");
5090      }
5091    }
5092    return directBaseUrls;
5093  }
5094  var Logger = (
5095    /** @class */
5096    (function() {
5097      function Logger2(config) {
5098        var _a2, _b2;
5099        this.logLevel = (_a2 = config.logLevel) !== null && _a2 !== void 0 ? _a2 : LogLevelType.Warning;
5100        this.logger = (_b2 = config.logger) !== null && _b2 !== void 0 ? _b2 : new ConsoleLogger();
5101      }
5102      Logger2.prototype.verbose = function(msg) {
5103        if (this.logLevel === LogLevelType.None) return;
5104        if (this.logger.verbose && this.logLevel === LogLevelType.Verbose) {
5105          this.logger.verbose(msg);
5106        }
5107      };
5108      Logger2.prototype.warning = function(msg) {
5109        if (this.logLevel === LogLevelType.None) return;
5110        if (this.logger.warning && (this.logLevel === LogLevelType.Verbose || this.logLevel === LogLevelType.Warning)) {
5111          this.logger.warning(msg);
5112        }
5113      };
5114      Logger2.prototype.error = function(msg) {
5115        if (this.logLevel === LogLevelType.None) return;
5116        if (this.logger.error) {
5117          this.logger.error(msg);
5118        }
5119      };
5120      Logger2.prototype.isVerbose = function() {
5121        return this.logLevel === LogLevelType.Verbose;
5122      };
5123      Logger2.prototype.setLogLevel = function(newLogLevel) {
5124        this.logLevel = newLogLevel;
5125      };
5126      return Logger2;
5127    })()
5128  );
5129  var ConsoleLogger = (
5130    /** @class */
5131    (function() {
5132      function ConsoleLogger2() {
5133      }
5134      ConsoleLogger2.prototype.verbose = function(msg) {
5135        if (console && console.info) {
5136          console.info(msg);
5137        }
5138      };
5139      ConsoleLogger2.prototype.error = function(msg) {
5140        if (console && console.error) {
5141          console.error(msg);
5142        }
5143      };
5144      ConsoleLogger2.prototype.warning = function(msg) {
5145        if (console && console.warn) {
5146          console.warn(msg);
5147        }
5148      };
5149      return ConsoleLogger2;
5150    })()
5151  );
5152  var Base64 = Polyfill.Base64, Messages$4 = Constants.Messages, Base64CookieKeys = Constants.Base64CookieKeys, SDKv2NonMPIDCookieKeys = Constants.SDKv2NonMPIDCookieKeys, StorageNames = Constants.StorageNames;
5153  function getMParticleManager() {
5154    return window.mParticle;
5155  }
5156  function _Persistence(mpInstance) {
5157    var self = this;
5158    this.useLocalStorage = function() {
5159      return !mpInstance._Store.SDKConfig.useCookieStorage && mpInstance._Store.isLocalStorageAvailable;
5160    };
5161    function setFirstRunFromExistingData(localStorageData, cookies) {
5162      if (!localStorageData && !cookies) {
5163        mpInstance._Store.isFirstRun = true;
5164        mpInstance._Store.mpid = 0;
5165        return;
5166      }
5167      mpInstance._Store.isFirstRun = false;
5168    }
5169    function mergeStorageSources(localStorageData, cookies) {
5170      if (localStorageData && cookies) {
5171        return extend(false, localStorageData, cookies);
5172      }
5173      return localStorageData || cookies;
5174    }
5175    function migrateLocalStorageToCookies(storage, localStorageData, cookies) {
5176      var allData;
5177      if (localStorageData) {
5178        allData = mergeStorageSources(localStorageData, cookies);
5179        storage.removeItem(mpInstance._Store.storageName);
5180      } else if (cookies) {
5181        allData = cookies;
5182      }
5183      self.storeDataInMemory(allData);
5184      return allData;
5185    }
5186    function migrateCookiesToLocalStorage(localStorageData, cookies) {
5187      if (!cookies) {
5188        self.storeDataInMemory(localStorageData);
5189        return;
5190      }
5191      var allData = mergeStorageSources(localStorageData, cookies);
5192      self.storeDataInMemory(allData);
5193      self.expireCookies(mpInstance._Store.storageName);
5194      return allData;
5195    }
5196    function loadPersistenceIntoMemory(localStorageData, cookies) {
5197      if (!mpInstance._Store.isLocalStorageAvailable) {
5198        self.storeDataInMemory(cookies);
5199        return;
5200      }
5201      if (mpInstance._Store.SDKConfig.useCookieStorage) {
5202        return migrateLocalStorageToCookies(window.localStorage, localStorageData, cookies);
5203      }
5204      return migrateCookiesToLocalStorage(localStorageData, cookies);
5205    }
5206    function copyNonCurrentUserMpids(allData) {
5207      for (var key in allData) {
5208        if (allData.hasOwnProperty(key) && !SDKv2NonMPIDCookieKeys[key]) {
5209          mpInstance._Store.nonCurrentUserMPIDs[key] = allData[key];
5210        }
5211      }
5212    }
5213    function clearCorruptStorage() {
5214      if (self.useLocalStorage() && mpInstance._Store.isLocalStorageAvailable) {
5215        localStorage.removeItem(mpInstance._Store.storageName);
5216        return;
5217      }
5218      self.expireCookies(mpInstance._Store.storageName);
5219    }
5220    this.initializeStorage = function() {
5221      try {
5222        var localStorageData = self.getLocalStorage();
5223        var cookies = self.getCookie();
5224        setFirstRunFromExistingData(localStorageData, cookies);
5225        if (!mpInstance._Store.isLocalStorageAvailable) {
5226          mpInstance._Store.SDKConfig.useCookieStorage = true;
5227        }
5228        var allData = loadPersistenceIntoMemory(localStorageData, cookies);
5229        copyNonCurrentUserMpids(allData);
5230        self.update();
5231      } catch (e) {
5232        clearCorruptStorage();
5233        mpInstance.Logger.error("Error initializing storage: " + e);
5234      }
5235    };
5236    this.update = function() {
5237      if (!mpInstance._Store.webviewBridgeEnabled) {
5238        if (mpInstance._Store.SDKConfig.useCookieStorage) {
5239          self.setCookie();
5240        }
5241        self.setLocalStorage();
5242      }
5243    };
5244    function applyEmptyPersistenceDefaults() {
5245      mpInstance.Logger.verbose(Messages$4.InformationMessages.CookieNotFound);
5246      mpInstance._Store.clientId = mpInstance._Store.clientId || mpInstance._Helpers.generateUniqueId();
5247      mpInstance._Store.deviceId = mpInstance._Store.deviceId || mpInstance._Helpers.generateUniqueId();
5248    }
5249    function hydrateStoreFromPersistence(obj, currentMPID) {
5250      if (currentMPID) {
5251        mpInstance._Store.mpid = currentMPID;
5252      } else {
5253        mpInstance._Store.mpid = obj.cu || 0;
5254      }
5255      obj.gs = obj.gs || {};
5256      mpInstance._Store.sessionId = obj.gs.sid || mpInstance._Store.sessionId;
5257      mpInstance._Store.isEnabled = typeof obj.gs.ie !== "undefined" ? obj.gs.ie : mpInstance._Store.isEnabled;
5258      mpInstance._Store.sessionAttributes = obj.gs.sa || mpInstance._Store.sessionAttributes;
5259      mpInstance._Store.localSessionAttributes = obj.gs.lsa || mpInstance._Store.localSessionAttributes;
5260      mpInstance._Store.serverSettings = obj.gs.ss || mpInstance._Store.serverSettings;
5261      mpInstance._Store.devToken = mpInstance._Store.devToken || obj.gs.dt;
5262      mpInstance._Store.SDKConfig.appVersion = mpInstance._Store.SDKConfig.appVersion || obj.gs.av;
5263      mpInstance._Store.clientId = obj.gs.cgid || mpInstance._Store.clientId || mpInstance._Helpers.generateUniqueId();
5264      mpInstance._Store.deviceId = mpInstance._Store.deviceId || obj.gs.das || mpInstance._Helpers.generateUniqueId();
5265      mpInstance._Store.integrationAttributes = obj.gs.ia || {};
5266      mpInstance._Store.context = obj.gs.c || mpInstance._Store.context;
5267      mpInstance._Store.currentSessionMPIDs = obj.gs.csm || mpInstance._Store.currentSessionMPIDs;
5268      mpInstance._Store.isLoggedIn = obj.l === true;
5269      if (obj.gs.les) {
5270        mpInstance._Store.dateLastEventSent = new Date(obj.gs.les);
5271      }
5272      mpInstance._Store.sessionStartDate = obj.gs.ssd ? new Date(obj.gs.ssd) : /* @__PURE__ */ new Date();
5273      if (currentMPID) {
5274        obj = obj[currentMPID];
5275      } else {
5276        obj = obj[obj.cu];
5277      }
5278    }
5279    this.storeDataInMemory = function(obj, currentMPID) {
5280      try {
5281        if (!obj) {
5282          applyEmptyPersistenceDefaults();
5283          return;
5284        }
5285        hydrateStoreFromPersistence(obj, currentMPID);
5286      } catch (e) {
5287        mpInstance.Logger.error(Messages$4.ErrorMessages.CookieParseError);
5288      }
5289    };
5290    this.determineLocalStorageAvailability = function(storage) {
5291      var mParticleManager2 = getMParticleManager();
5292      if (mParticleManager2 === null || mParticleManager2 === void 0 ? void 0 : mParticleManager2._forceNoLocalStorage) {
5293        return false;
5294      }
5295      try {
5296        storage.setItem("mparticle", "test");
5297        var result = storage.getItem("mparticle") === "test";
5298        storage.removeItem("mparticle");
5299        return Boolean(result && storage);
5300      } catch (e) {
5301        return false;
5302      }
5303    };
5304    this.setLocalStorage = function() {
5305      var _a2;
5306      if (!mpInstance._Store.isLocalStorageAvailable) {
5307        return;
5308      }
5309      if ((_a2 = mpInstance._CookieConsentManager) === null || _a2 === void 0 ? void 0 : _a2.getNoFunctional()) {
5310        return;
5311      }
5312      var key = mpInstance._Store.storageName, localStorageData = self.getLocalStorage() || {}, currentUser = mpInstance.Identity.getCurrentUser(), mpid = currentUser ? currentUser.getMPID() : null;
5313      if (!mpInstance._Store.SDKConfig.useCookieStorage) {
5314        localStorageData.gs = localStorageData.gs || {};
5315        localStorageData.l = mpInstance._Store.isLoggedIn ? 1 : 0;
5316        if (mpInstance._Store.sessionId) {
5317          localStorageData.gs.csm = mpInstance._Store.currentSessionMPIDs;
5318        }
5319        localStorageData.gs.ie = mpInstance._Store.isEnabled;
5320        if (mpid) {
5321          localStorageData.cu = mpid;
5322        }
5323        if (Object.keys(mpInstance._Store.nonCurrentUserMPIDs).length) {
5324          localStorageData = extend({}, localStorageData, mpInstance._Store.nonCurrentUserMPIDs);
5325          mpInstance._Store.nonCurrentUserMPIDs = {};
5326        }
5327        localStorageData = setGlobalStorageAttributes(localStorageData);
5328        try {
5329          window.localStorage.setItem(encodeURIComponent(key), self.encodePersistence(JSON.stringify(localStorageData)));
5330        } catch (e) {
5331          mpInstance.Logger.error("Error with setting localStorage item.");
5332        }
5333      }
5334    };
5335    function setGlobalStorageAttributes(data) {
5336      var store = mpInstance._Store;
5337      data.gs.sid = store.sessionId;
5338      data.gs.ie = store.isEnabled;
5339      data.gs.sa = store.sessionAttributes;
5340      data.gs.lsa = store.localSessionAttributes;
5341      data.gs.ss = store.serverSettings;
5342      data.gs.dt = store.devToken;
5343      data.gs.les = store.dateLastEventSent ? store.dateLastEventSent.getTime() : null;
5344      data.gs.av = store.SDKConfig.appVersion;
5345      data.gs.cgid = store.clientId;
5346      data.gs.das = store.deviceId;
5347      data.gs.c = store.context;
5348      data.gs.ssd = store.sessionStartDate ? store.sessionStartDate.getTime() : 0;
5349      data.gs.ia = store.integrationAttributes;
5350      return data;
5351    }
5352    this.getLocalStorage = function() {
5353      if (!mpInstance._Store.isLocalStorageAvailable) {
5354        return null;
5355      }
5356      var key = mpInstance._Store.storageName;
5357      var decodedPersistence = self.decodePersistence(window.localStorage.getItem(key));
5358      if (!decodedPersistence) {
5359        return null;
5360      }
5361      var parsedPersistence = JSON.parse(decodedPersistence);
5362      var obj = {};
5363      for (var key_1 in parsedPersistence) {
5364        if (parsedPersistence.hasOwnProperty(key_1)) {
5365          obj[key_1] = parsedPersistence[key_1];
5366        }
5367      }
5368      if (Object.keys(obj).length) {
5369        return obj;
5370      }
5371      return null;
5372    };
5373    this.expireCookies = function(cookieName) {
5374      var date = /* @__PURE__ */ new Date(), expires, domain, cookieDomain;
5375      cookieDomain = self.getCookieDomain();
5376      if (cookieDomain === "") {
5377        domain = "";
5378      } else {
5379        domain = ";domain=" + cookieDomain;
5380      }
5381      date.setTime(date.getTime() - 24 * 60 * 60 * 1e3);
5382      expires = "; expires=" + date.toUTCString();
5383      document.cookie = cookieName + "=" + expires + "; path=/" + domain;
5384    };
5385    this.getCookie = function() {
5386      var cookies, key = mpInstance._Store.storageName, i, l, parts, name, cookie, result = key ? void 0 : {};
5387      mpInstance.Logger.verbose(Messages$4.InformationMessages.CookieSearch);
5388      try {
5389        cookies = window.document.cookie.split("; ");
5390      } catch (e) {
5391        mpInstance.Logger.verbose("Unable to parse undefined cookie");
5392        return null;
5393      }
5394      for (i = 0, l = cookies.length; i < l; i++) {
5395        try {
5396          parts = cookies[i].split("=");
5397          name = parts.shift();
5398          cookie = parts.join("=");
5399        } catch (e) {
5400          mpInstance.Logger.verbose("Unable to parse cookie: " + name + ". Skipping.");
5401        }
5402        if (key && key === name) {
5403          result = mpInstance._Helpers.converted(cookie);
5404          break;
5405        }
5406        if (!key) {
5407          result[name] = mpInstance._Helpers.converted(cookie);
5408        }
5409      }
5410      if (result) {
5411        mpInstance.Logger.verbose(Messages$4.InformationMessages.CookieFound);
5412        return JSON.parse(self.decodePersistence(result));
5413      } else {
5414        return null;
5415      }
5416    };
5417    this.setCookie = function() {
5418      var _a2;
5419      if ((_a2 = mpInstance._CookieConsentManager) === null || _a2 === void 0 ? void 0 : _a2.getNoFunctional()) {
5420        return;
5421      }
5422      var mpid, currentUser = mpInstance.Identity.getCurrentUser();
5423      if (currentUser) {
5424        mpid = currentUser.getMPID();
5425      }
5426      var date = /* @__PURE__ */ new Date(), key = mpInstance._Store.storageName, cookies = self.getCookie() || {}, expires = new Date(date.getTime() + mpInstance._Store.SDKConfig.cookieExpiration * 24 * 60 * 60 * 1e3).toUTCString(), cookieDomain, domain, encodedCookiesWithExpirationAndPath;
5427      cookieDomain = self.getCookieDomain();
5428      if (cookieDomain === "") {
5429        domain = "";
5430      } else {
5431        domain = ";domain=" + cookieDomain;
5432      }
5433      cookies.gs = cookies.gs || {};
5434      if (mpInstance._Store.sessionId) {
5435        cookies.gs.csm = mpInstance._Store.currentSessionMPIDs;
5436      }
5437      if (mpid) {
5438        cookies.cu = mpid;
5439      }
5440      cookies.l = mpInstance._Store.isLoggedIn ? 1 : 0;
5441      cookies = setGlobalStorageAttributes(cookies);
5442      if (Object.keys(mpInstance._Store.nonCurrentUserMPIDs).length) {
5443        cookies = extend({}, cookies, mpInstance._Store.nonCurrentUserMPIDs);
5444        mpInstance._Store.nonCurrentUserMPIDs = {};
5445      }
5446      encodedCookiesWithExpirationAndPath = self.reduceAndEncodePersistence(cookies, expires, domain, mpInstance._Store.SDKConfig.maxCookieSize);
5447      mpInstance.Logger.verbose(Messages$4.InformationMessages.CookieSet);
5448      window.document.cookie = encodeURIComponent(key) + "=" + encodedCookiesWithExpirationAndPath;
5449    };
5450    function isEncodedCookieTooLarge(encoded, maxCookieSize) {
5451      return encoded.length > maxCookieSize;
5452    }
5453    function removeUnsessionedMpidsWhenOversized(persistence, expires, domain, maxCookieSize) {
5454      var encodedCookiesWithExpirationAndPath;
5455      for (var key in persistence) {
5456        if (!persistence.hasOwnProperty(key)) {
5457          continue;
5458        }
5459        encodedCookiesWithExpirationAndPath = createFullEncodedCookie(persistence, expires, domain);
5460        if (!isEncodedCookieTooLarge(encodedCookiesWithExpirationAndPath, maxCookieSize)) {
5461          continue;
5462        }
5463        if (SDKv2NonMPIDCookieKeys[key] || key === persistence.cu) {
5464          continue;
5465        }
5466        delete persistence[key];
5467      }
5468      return encodedCookiesWithExpirationAndPath;
5469    }
5470    function collectRemovableMpids(persistence) {
5471      var MPIDsOnCookie = {};
5472      for (var potentialMPID in persistence) {
5473        if (!persistence.hasOwnProperty(potentialMPID)) {
5474          continue;
5475        }
5476        if (SDKv2NonMPIDCookieKeys[potentialMPID] || potentialMPID === persistence.cu) {
5477          continue;
5478        }
5479        MPIDsOnCookie[potentialMPID] = 1;
5480      }
5481      return MPIDsOnCookie;
5482    }
5483    function removeMpidsNotInCurrentSession(persistence, MPIDsOnCookie, currentSessionMPIDs, expires, domain, maxCookieSize) {
5484      var encodedCookiesWithExpirationAndPath;
5485      for (var mpid in MPIDsOnCookie) {
5486        encodedCookiesWithExpirationAndPath = createFullEncodedCookie(persistence, expires, domain);
5487        if (!isEncodedCookieTooLarge(encodedCookiesWithExpirationAndPath, maxCookieSize)) {
5488          continue;
5489        }
5490        if (!MPIDsOnCookie.hasOwnProperty(mpid)) {
5491          continue;
5492        }
5493        if (currentSessionMPIDs.indexOf(mpid) === -1) {
5494          delete persistence[mpid];
5495        }
5496      }
5497      return encodedCookiesWithExpirationAndPath;
5498    }
5499    function logAndRemoveOversizedMpid(persistence, MPIDtoRemove, maxCookieSize) {
5500      if (persistence[MPIDtoRemove]) {
5501        mpInstance.Logger.verbose("Size of new encoded cookie is larger than maxCookieSize setting of " + maxCookieSize + ". Removing from cookie the earliest logged in MPID containing: " + JSON.stringify(persistence[MPIDtoRemove], null, 2));
5502        delete persistence[MPIDtoRemove];
5503        return;
5504      }
5505      mpInstance.Logger.error("Unable to save MPID data to cookies because the resulting encoded cookie is larger than the maxCookieSize setting of " + maxCookieSize + ". We recommend using a maxCookieSize of 1500.");
5506    }
5507    function removeCurrentSessionMpidsByAge(persistence, currentSessionMPIDs, expires, domain, maxCookieSize) {
5508      var encodedCookiesWithExpirationAndPath;
5509      for (var i = 0; i < currentSessionMPIDs.length; i++) {
5510        encodedCookiesWithExpirationAndPath = createFullEncodedCookie(persistence, expires, domain);
5511        if (!isEncodedCookieTooLarge(encodedCookiesWithExpirationAndPath, maxCookieSize)) {
5512          break;
5513        }
5514        logAndRemoveOversizedMpid(persistence, currentSessionMPIDs[i], maxCookieSize);
5515      }
5516      return encodedCookiesWithExpirationAndPath;
5517    }
5518    this.reduceAndEncodePersistence = function(persistence, expires, domain, maxCookieSize) {
5519      var currentSessionMPIDs = persistence.gs.csm ? persistence.gs.csm : [];
5520      if (!currentSessionMPIDs.length) {
5521        return removeUnsessionedMpidsWhenOversized(persistence, expires, domain, maxCookieSize);
5522      }
5523      var MPIDsOnCookie = collectRemovableMpids(persistence);
5524      if (Object.keys(MPIDsOnCookie).length) {
5525        removeMpidsNotInCurrentSession(persistence, MPIDsOnCookie, currentSessionMPIDs, expires, domain, maxCookieSize);
5526      }
5527      return removeCurrentSessionMpidsByAge(persistence, currentSessionMPIDs, expires, domain, maxCookieSize);
5528    };
5529    function createFullEncodedCookie(persistence, expires, domain) {
5530      return self.encodePersistence(JSON.stringify(persistence)) + ";expires=" + expires + ";path=/" + domain;
5531    }
5532    function cookieUiMatchesRequestedIdentity(cookieUIs, requestedIdentityType, requestedValue) {
5533      for (var cookieUIType in cookieUIs) {
5534        if (requestedIdentityType === cookieUIType && requestedValue === cookieUIs[cookieUIType]) {
5535          return true;
5536        }
5537      }
5538      return false;
5539    }
5540    function findMpidForRequestedIdentity(persistence, requestedIdentityType, requestedValue) {
5541      var matchedUser;
5542      for (var key in persistence) {
5543        if (!persistence[key].mpid) {
5544          continue;
5545        }
5546        if (cookieUiMatchesRequestedIdentity(persistence[key].ui, requestedIdentityType, requestedValue)) {
5547          matchedUser = key;
5548        }
5549      }
5550      return matchedUser;
5551    }
5552    function findMpidMatchingIdentities(persistence, identityApiData) {
5553      var matchedUser;
5554      for (var requestedIdentityType in identityApiData.userIdentities) {
5555        if (!persistence || !Object.keys(persistence).length) {
5556          continue;
5557        }
5558        var match = findMpidForRequestedIdentity(persistence, requestedIdentityType, identityApiData.userIdentities[requestedIdentityType]);
5559        if (match) {
5560          matchedUser = match;
5561        }
5562      }
5563      return matchedUser;
5564    }
5565    this.findPrevCookiesBasedOnUI = function(identityApiData) {
5566      var persistence = mpInstance._Persistence.getPersistence();
5567      if (!identityApiData) {
5568        return;
5569      }
5570      var matchedUser = findMpidMatchingIdentities(persistence, identityApiData);
5571      if (matchedUser) {
5572        self.storeDataInMemory(persistence, matchedUser);
5573      }
5574    };
5575    function isNonEmptyArrayOrObject(value) {
5576      if (Array.isArray(value)) {
5577        return value.length > 0;
5578      }
5579      if (!mpInstance._Helpers.isObject(value)) {
5580        return false;
5581      }
5582      return Object.keys(value).length > 0;
5583    }
5584    function encodeGsBase64Field(gs, key) {
5585      if (!gs[key] || !isNonEmptyArrayOrObject(gs[key])) {
5586        delete gs[key];
5587        return;
5588      }
5589      gs[key] = Base64.encode(JSON.stringify(gs[key]));
5590    }
5591    function encodeGlobalSettings(gs) {
5592      for (var key in gs) {
5593        if (!gs.hasOwnProperty(key)) {
5594          continue;
5595        }
5596        if (Base64CookieKeys[key]) {
5597          encodeGsBase64Field(gs, key);
5598          continue;
5599        }
5600        if (key === "ie") {
5601          gs[key] = gs[key] ? 1 : 0;
5602          continue;
5603        }
5604        if (!gs[key]) {
5605          delete gs[key];
5606        }
5607      }
5608    }
5609    function encodeMpidBase64Field(container, key) {
5610      var value = container[key];
5611      if (mpInstance._Helpers.isObject(value) && Object.keys(value).length) {
5612        container[key] = Base64.encode(JSON.stringify(value));
5613        return;
5614      }
5615      delete container[key];
5616    }
5617    function encodeMpidRecord(record) {
5618      for (var key in record) {
5619        if (!record.hasOwnProperty(key)) {
5620          continue;
5621        }
5622        if (Base64CookieKeys[key]) {
5623          encodeMpidBase64Field(record, key);
5624        }
5625      }
5626    }
5627    function encodeMpidRecords(persistence) {
5628      for (var mpid in persistence) {
5629        if (!persistence.hasOwnProperty(mpid)) {
5630          continue;
5631        }
5632        if (SDKv2NonMPIDCookieKeys[mpid]) {
5633          continue;
5634        }
5635        encodeMpidRecord(persistence[mpid]);
5636      }
5637    }
5638    this.encodePersistence = function(persistenceString) {
5639      var persistence = JSON.parse(persistenceString);
5640      encodeGlobalSettings(persistence.gs);
5641      encodeMpidRecords(persistence);
5642      return createCookieString(JSON.stringify(persistence));
5643    };
5644    function decodeGlobalSettings(gs) {
5645      for (var key in gs) {
5646        if (!gs.hasOwnProperty(key)) {
5647          continue;
5648        }
5649        if (Base64CookieKeys[key]) {
5650          gs[key] = JSON.parse(Base64.decode(gs[key]));
5651          continue;
5652        }
5653        if (key === "ie") {
5654          gs[key] = Boolean(gs[key]);
5655        }
5656      }
5657    }
5658    function decodeMpidRecord(record) {
5659      for (var key in record) {
5660        if (!record.hasOwnProperty(key)) {
5661          continue;
5662        }
5663        if (!Base64CookieKeys[key]) {
5664          continue;
5665        }
5666        if (record[key].length) {
5667          record[key] = JSON.parse(Base64.decode(record[key]));
5668        }
5669      }
5670    }
5671    function decodeMpidRecords(persistence) {
5672      for (var mpid in persistence) {
5673        if (!persistence.hasOwnProperty(mpid)) {
5674          continue;
5675        }
5676        if (!SDKv2NonMPIDCookieKeys[mpid]) {
5677          decodeMpidRecord(persistence[mpid]);
5678          continue;
5679        }
5680        if (mpid === "l") {
5681          persistence[mpid] = Boolean(persistence[mpid]);
5682        }
5683      }
5684    }
5685    this.decodePersistence = function(persistenceString) {
5686      try {
5687        if (!persistenceString) {
5688          return;
5689        }
5690        var persistence = JSON.parse(revertCookieString(persistenceString));
5691        if (mpInstance._Helpers.isObject(persistence) && Object.keys(persistence).length) {
5692          decodeGlobalSettings(persistence.gs);
5693          decodeMpidRecords(persistence);
5694        }
5695        return JSON.stringify(persistence);
5696      } catch (e) {
5697        mpInstance.Logger.error("Problem with decoding cookie");
5698      }
5699    };
5700    this.getCookieDomain = function() {
5701      if (mpInstance._Store.SDKConfig.cookieDomain) {
5702        return mpInstance._Store.SDKConfig.cookieDomain;
5703      } else {
5704        var rootDomain = self.getDomain(document, location.hostname);
5705        if (rootDomain === "") {
5706          return "";
5707        } else {
5708          return "." + rootDomain;
5709        }
5710      }
5711    };
5712    this.getDomain = function(doc, locationHostname) {
5713      var i, testParts, mpTest = "mptest=cookie", hostname = locationHostname.split(".");
5714      for (i = hostname.length - 1; i >= 0; i--) {
5715        testParts = hostname.slice(i).join(".");
5716        doc.cookie = mpTest + ";domain=." + testParts + ";";
5717        if (doc.cookie.indexOf(mpTest) > -1) {
5718          doc.cookie = mpTest.split("=")[0] + "=;domain=." + testParts + ";expires=Thu, 01 Jan 1970 00:00:01 GMT;";
5719          return testParts;
5720        }
5721      }
5722      return "";
5723    };
5724    this.saveUserCookieSyncDatesToPersistence = function(mpid, csd) {
5725      if (csd) {
5726        var persistence = self.getPersistence();
5727        if (persistence) {
5728          if (persistence[mpid]) {
5729            persistence[mpid].csd = csd;
5730          } else {
5731            persistence[mpid] = {
5732              csd
5733            };
5734          }
5735        }
5736        self.savePersistence(persistence);
5737      }
5738    };
5739    this.swapCurrentUser = function(previousMPID, currentMPID, currentSessionMPIDs) {
5740      if (previousMPID && currentMPID && previousMPID !== currentMPID) {
5741        var persistence = self.getPersistence();
5742        if (persistence) {
5743          persistence.cu = currentMPID;
5744          persistence.gs.csm = currentSessionMPIDs;
5745          self.savePersistence(persistence);
5746        }
5747      }
5748    };
5749    this.savePersistence = function(persistence) {
5750      var _a2;
5751      if ((_a2 = mpInstance._CookieConsentManager) === null || _a2 === void 0 ? void 0 : _a2.getNoFunctional()) {
5752        return;
5753      }
5754      var encodedPersistence = self.encodePersistence(JSON.stringify(persistence)), date = /* @__PURE__ */ new Date(), key = mpInstance._Store.storageName, expires = new Date(date.getTime() + mpInstance._Store.SDKConfig.cookieExpiration * 24 * 60 * 60 * 1e3).toUTCString(), cookieDomain = self.getCookieDomain(), domain;
5755      if (cookieDomain === "") {
5756        domain = "";
5757      } else {
5758        domain = ";domain=" + cookieDomain;
5759      }
5760      if (mpInstance._Store.SDKConfig.useCookieStorage) {
5761        var encodedCookiesWithExpirationAndPath = self.reduceAndEncodePersistence(persistence, expires, domain, mpInstance._Store.SDKConfig.maxCookieSize);
5762        window.document.cookie = encodeURIComponent(key) + "=" + encodedCookiesWithExpirationAndPath;
5763      } else {
5764        if (mpInstance._Store.isLocalStorageAvailable) {
5765          try {
5766            localStorage.setItem(mpInstance._Store.storageName, encodedPersistence);
5767          } catch (e) {
5768            mpInstance.Logger.error("Error saving persistence to localStorage.");
5769          }
5770        }
5771      }
5772    };
5773    this.getPersistence = function() {
5774      var persistence = this.useLocalStorage() ? this.getLocalStorage() : this.getCookie();
5775      return persistence;
5776    };
5777    this.getFirstSeenTime = function(mpid) {
5778      if (!mpid) {
5779        return null;
5780      }
5781      var persistence = self.getPersistence();
5782      if (persistence && persistence[mpid] && persistence[mpid].fst) {
5783        return persistence[mpid].fst;
5784      } else {
5785        return null;
5786      }
5787    };
5788    this.setFirstSeenTime = function(mpid, time) {
5789      if (!mpid) {
5790        return;
5791      }
5792      if (!time) {
5793        time = (/* @__PURE__ */ new Date()).getTime();
5794      }
5795      var persistence = self.getPersistence();
5796      if (persistence) {
5797        if (!persistence[mpid]) {
5798          persistence[mpid] = {};
5799        }
5800        if (!persistence[mpid].fst) {
5801          persistence[mpid].fst = time;
5802          self.savePersistence(persistence);
5803        }
5804      }
5805    };
5806    this.getLastSeenTime = function(mpid) {
5807      if (!mpid) {
5808        return null;
5809      }
5810      if (mpid === mpInstance.Identity.getCurrentUser().getMPID()) {
5811        return (/* @__PURE__ */ new Date()).getTime();
5812      } else {
5813        var persistence = self.getPersistence();
5814        if (persistence && persistence[mpid] && persistence[mpid].lst) {
5815          return persistence[mpid].lst;
5816        }
5817        return null;
5818      }
5819    };
5820    this.setLastSeenTime = function(mpid, time) {
5821      if (!mpid) {
5822        return;
5823      }
5824      if (!time) {
5825        time = (/* @__PURE__ */ new Date()).getTime();
5826      }
5827      var persistence = self.getPersistence();
5828      if (persistence && persistence[mpid]) {
5829        persistence[mpid].lst = time;
5830        self.savePersistence(persistence);
5831      }
5832    };
5833    this.getDeviceId = function() {
5834      return mpInstance._Store.deviceId;
5835    };
5836    this.setDeviceId = function(guid) {
5837      mpInstance._Store.deviceId = guid;
5838      self.update();
5839    };
5840    this.resetPersistence = function() {
5841      localStorage.clear();
5842      self.expireCookies(StorageNames.cookieName);
5843      self.expireCookies(StorageNames.cookieNameV2);
5844      self.expireCookies(StorageNames.cookieNameV3);
5845      self.expireCookies(StorageNames.cookieNameV4);
5846      self.expireCookies(mpInstance._Store.storageName);
5847      var mParticleManager2 = getMParticleManager();
5848      if (mParticleManager2 === null || mParticleManager2 === void 0 ? void 0 : mParticleManager2._isTestEnv) {
5849        var testWorkspaceToken = "abcdef";
5850        localStorage.removeItem(mpInstance._Helpers.createMainStorageName(testWorkspaceToken));
5851        self.expireCookies(mpInstance._Helpers.createMainStorageName(testWorkspaceToken));
5852      }
5853    };
5854    this.forwardingStatsBatches = {
5855      uploadsTable: {},
5856      forwardingStatsEventQueue: []
5857    };
5858  }
5859  var HISTORY_METHODS = ["pushState", "replaceState"];
5860  var WRAPPED_MARKER = "__mpApvWrapped__";
5861  var WIN_APV_KEY = "__mpApv__";
5862  var ALLOWED_QUERY_PARAMS = [
5863    // Campaign attribution
5864    "utm_source",
5865    "utm_medium",
5866    "utm_campaign",
5867    "utm_term",
5868    "utm_content",
5869    "utm_id",
5870    // Ad-network click ids
5871    "gclid",
5872    "gbraid",
5873    "wbraid",
5874    "fbclid",
5875    "msclkid",
5876    "ttclid",
5877    "twclid",
5878    "li_fat_id",
5879    "dclid",
5880    // OAuth / OIDC — see the SECURITY note above
5881    "client_id",
5882    "redirect_uri",
5883    "response_type",
5884    "scope",
5885    "state",
5886    "code",
5887    "nonce",
5888    // Pagination and search
5889    "page",
5890    "limit",
5891    "offset",
5892    "cursor",
5893    "per_page",
5894    "q",
5895    "search",
5896    // Referral
5897    "ref",
5898    "referrer"
5899  ];
5900  var allowedQueryParams = function allowedQueryParams2(href) {
5901    return queryStringParser(href, ALLOWED_QUERY_PARAMS);
5902  };
5903  var capturedNames = function capturedNames2(params) {
5904    return ALLOWED_QUERY_PARAMS.filter(function(name) {
5905      return name in params;
5906    });
5907  };
5908  var pageKey = function pageKey2(page) {
5909    var query = capturedNames(page.params).map(function(name) {
5910      return "".concat(name, "=").concat(encodeURIComponent(page.params[name]));
5911    }).join("&");
5912    return query ? "".concat(page.path, "?").concat(query) : page.path;
5913  };
5914  var isNewPage = function isNewPage2(lastKey, candidateKey) {
5915    return candidateKey !== lastKey;
5916  };
5917  var supportsHistoryTracking = function supportsHistoryTracking2(win) {
5918    return !!win && win.history !== void 0 && typeof win.history.pushState === "function" && typeof win.addEventListener === "function";
5919  };
5920  var buildPageViewEvent = function buildPageViewEvent2(_a2) {
5921    var params = _a2.params, hostname = _a2.hostname, title = _a2.title, path = _a2.path;
5922    return {
5923      messageType: MessageType$1.PageView,
5924      name: "PageView",
5925      // Params spread first, then the core fields by name, so a core field always
5926      // wins. No allowlist entry collides with hostname/title/path today; naming
5927      // them here is what keeps a later addition from silently overwriting one.
5928      data: __assign(__assign({}, params), {
5929        hostname,
5930        title,
5931        path
5932      }),
5933      eventType: EventType.Unknown
5934    };
5935  };
5936  var apvWindow = function apvWindow2() {
5937    return typeof window === "undefined" ? null : window;
5938  };
5939  var freshState = function freshState2() {
5940    return {
5941      initialPageViewFired: false
5942    };
5943  };
5944  var readState = function readState2() {
5945    var win = apvWindow();
5946    return win ? win[WIN_APV_KEY] : void 0;
5947  };
5948  var writeState = function writeState2() {
5949    var win = apvWindow();
5950    if (!win) {
5951      return null;
5952    }
5953    if (!win[WIN_APV_KEY]) {
5954      win[WIN_APV_KEY] = freshState();
5955    }
5956    return win[WIN_APV_KEY];
5957  };
5958  var getActiveTracker = function getActiveTracker2() {
5959    var state = readState();
5960    return state ? state.tracker : void 0;
5961  };
5962  var hasInitialPageViewFired = function hasInitialPageViewFired2() {
5963    var state = readState();
5964    return !!(state && state.initialPageViewFired);
5965  };
5966  var markInitialPageViewFired = function markInitialPageViewFired2() {
5967    var state = writeState();
5968    if (state) {
5969      state.initialPageViewFired = true;
5970    }
5971  };
5972  var resetPageViewTracking = function resetPageViewTracking2() {
5973    var win = apvWindow();
5974    if (!win) {
5975      return;
5976    }
5977    var active = getActiveTracker();
5978    if (active) {
5979      active.teardown();
5980    }
5981    win[WIN_APV_KEY] = freshState();
5982  };
5983  var setActiveTracker = function setActiveTracker2(tracker) {
5984    var state = writeState();
5985    if (state) {
5986      state.tracker = tracker;
5987    }
5988  };
5989  var clearActiveTracker = function clearActiveTracker2(tracker) {
5990    var state = readState();
5991    if (state && state.tracker === tracker) {
5992      state.tracker = void 0;
5993    }
5994  };
5995  var currentPage = function currentPage2() {
5996    return {
5997      path: window.location.pathname,
5998      params: allowedQueryParams(getHref())
5999    };
6000  };
6001  var describePage = function describePage2(page) {
6002    if (!page) {
6003      return "";
6004    }
6005    var names = capturedNames(page.params);
6006    return names.length ? "".concat(page.path, " (params: ").concat(names.join(), ")") : page.path;
6007  };
6008  var patchHistory = function patchHistory2(onNavigate, log) {
6009    if (window.history.pushState[WRAPPED_MARKER]) {
6010      log("[patch] history already wrapped, skipping to avoid double-wrap \u2014 STACKED WRAPPER DET
6010ECTED");
6011      return null;
6012    }
6013    var originals = {};
6014    var wrappers = {};
6015    HISTORY_METHODS.forEach(function(name) {
6016      var original = window.history[name];
6017      originals[name] = original;
6018      var wrapper = function wrapper2() {
6019        var args = [];
6020        for (var _i = 0; _i < arguments.length; _i++) {
6021          args[_i] = arguments[_i];
6022        }
6023        var result = original.apply(this, args);
6024        onNavigate(name);
6025        return result;
6026      };
6027      Object.defineProperty(wrapper, WRAPPED_MARKER, {
6028        value: true,
6029        enumerable: false
6030      });
6031      wrappers[name] = wrapper;
6032    });
6033    var restore = function restore2() {
6034      return HISTORY_METHODS.forEach(function(name) {
6035        if (window.history[name] === wrappers[name]) {
6036          window.history[name] = originals[name];
6037          log("[teardown] restored original ".concat(name));
6038        } else {
6039          log("[teardown] ".concat(name, " no longer ours; leaving in place, gating callback to no-op"));
6040        }
6041      });
6042    };
6043    try {
6044      HISTORY_METHODS.forEach(function(name) {
6045        window.history[name] = wrappers[name];
6046      });
6047    } catch (e) {
6048      log("[error] failed to patch history methods (frozen/sealed), rolling back: ".concat(e));
6049      try {
6050        restore();
6051      } catch (restoreError) {
6052        log("[error] failed to restore history methods after patch failure: ".concat(restoreError));
6053      }
6054      return null;
6055    }
6056    return restore;
6057  };
6058  var PageViewTracker = (
6059    /** @class */
6060    (function() {
6061      function PageViewTracker2(mpInstance) {
6062        this.lastPage = null;
6063        this.active = false;
6064        this.pendingNavigations = [];
6065        this.undoHistoryPatch = null;
6066        this.popStateListener = null;
6067        this.mpInstance = mpInstance;
6068      }
6069      Object.defineProperty(PageViewTracker2.prototype, "isActive", {
6070        // True while this tracker owns the history patch and is listening for
6071        // navigations. Flips to false on teardown, including the teardown a
6072        // successor tracker performs during a handoff. Read-only, and the one thing
6073        // worth checking on `window.__mpApv__.tracker` from a console.
6074        get: function get() {
6075          return this.active;
6076        },
6077        enumerable: false,
6078        configurable: true
6079      });
6080      PageViewTracker2.prototype.init = function() {
6081        var _this = this;
6082        this.log("[init] PageViewTracker Init");
6083        if (!supportsHistoryTracking(apvWindow())) {
6084          this.log("[init] unsupported environment (no History API), not starting");
6085          return;
6086        }
6087        var active = getActiveTracker();
6088        var inheritedPages = this.retire(active);
6089        if (this.active && active !== this) {
6090          inheritedPages = inheritedPages.concat(this.retire(this));
6091        }
6092        this.active = true;
6093        this.lastPage = currentPage();
6094        this.log("[init] seeded lastPage: ".concat(describePage(this.lastPage)));
6095        this.undoHistoryPatch = patchHistory(function(source) {
6096          return _this.safeHandleNavigation(source);
6097        }, function(message) {
6098          return _this.log(message);
6099        });
6100        this.popStateListener = function() {
6101          return _this.safeHandleNavigation("popstate");
6102        };
6103        window.addEventListener("popstate", this.popStateListener);
6104        setActiveTracker(this);
6105        this.log("[init] patched pushState/replaceState + listening for popstate");
6106        inheritedPages.forEach(function(page) {
6107          return _this.scheduleFire(page);
6108        });
6109      };
6110      PageViewTracker2.prototype.teardown = function() {
6111        this.takePendingNavigations();
6112        if (this.popStateListener) {
6113          window.removeEventListener("popstate", this.popStateListener);
6114          this.popStateListener = null;
6115        }
6116        if (this.undoHistoryPatch) {
6117          this.undoHistoryPatch();
6118          this.undoHistoryPatch = null;
6119        }
6120        this.active = false;
6121        clearActiveTracker(this);
6122      };
6123      PageViewTracker2.prototype.retire = function(outgoing) {
6124        if (!outgoing) {
6125          return [];
6126        }
6127        this.log(outgoing === this ? "[init] retiring this tracker for a repeat mParticle.init() \u2014 transferring pending navigations and tearing down" : "[init] retiring a tracker from a previous module load \u2014 transferring pending navigations and tearing down");
6128        var pages = outgoing.takePendingNavigations();
6129        outgoing.teardown();
6130        return pages;
6131      };
6132      PageViewTracker2.prototype.takePendingNavigations = function() {
6133        var pending = this.pendingNavigations;
6134        this.pendingNavigations = [];
6135        pending.forEach(function(_a2) {
6136          var timeoutId = _a2.timeoutId;
6137          return clearTimeout(timeoutId);
6138        });
6139        return pending.map(function(_a2) {
6140          var page = _a2.page;
6141          return page;
6142        });
6143      };
6144      PageViewTracker2.prototype.safeHandleNavigation = function(source) {
6145        if (!this.active) {
6146          return;
6147        }
6148        try {
6149          this.handleNavigation(source);
6150        } catch (e) {
6151          this.log("[error] navigation handler threw (".concat(source, "), page view skipped: ").concat(e));
6152        }
6153      };
6154      PageViewTracker2.prototype.handleNavigation = function(source) {
6155        var candidate = currentPage();
6156        var lastKey = this.lastPage ? pageKey(this.lastPage) : null;
6157        this.log("[detect] navigation signal (source: ".concat(source, ", candidate: ").concat(describePage(candidate), ", last: ").concat(describePage(this.lastPage), ")"));
6158        if (!isNewPage(lastKey, pageKey(candidate))) {
6159          this.log("[dedupe] page unchanged, skipping (source: ".concat(source, ", page: ").concat(describePage(candidate), ")"));
6160          return;
6161        }
6162        this.log("[accept] page changed, scheduling fire (source: ".concat(source, ", from: ").concat(describePage(this.lastPage), ", to: ").concat(describePage(candidate), ")"));
6163        this.lastPage = candidate;
6164        this.scheduleFire(candidate);
6165      };
6166      PageViewTracker2.prototype.scheduleFire = function(page) {
6167        var _this = this;
6168        var timeoutId = setTimeout(function() {
6169          _this.pendingNavigations = _this.pendingNavigations.filter(function(p) {
6170            return p.timeoutId !== timeoutId;
6171          });
6172          if (!_this.active) {
6173            _this.log("[defer] fire aborted, tracker inactive (torn down before flush)");
6174            return;
6175          }
6176          _this.mpInstance._SessionManager.resetSessionTimer();
6177          _this.firePageView(page);
6178        }, 0);
6179        this.pendingNavigations.push({
6180          page,
6181          timeoutId
6182        });
6183      };
6184      PageViewTracker2.prototype.firePageView = function(page) {
6185        var title = window.document.title;
6186        var event = buildPageViewEvent(__assign(__assign({}, page), {
6187          hostname: window.location.hostname,
6188          title
6189        }));
6190        this.log("[fire] deferred flush -> _Events.logEvent(PageView) (page: ".concat(describePage(page), ", title: ").concat(title, ")"));
6191        this.mpInstance._Events.logEvent(event);
6192      };
6193      PageViewTracker2.prototype.log = function(message) {
6194        this.mpInstance.Logger.verbose("mParticle APV: ".concat(message));
6195      };
6196      return PageViewTracker2;
6197    })()
6198  );
6199  var Messages$3 = Constants.Messages;
6200  function Events(mpInstance) {
6201    var self = this;
6202    this.logEvent = function(event, options) {
6203      mpInstance.Logger.verbose(Messages$3.InformationMessages.StartingLogEvent + ": " + event.name);
6204      if (mpInstance._Helpers.canLog()) {
6205        var uploadObject = mpInstance._ServerModel.createEventObject(event);
6206        mpInstance._APIClient.sendEventToServer(uploadObject, options);
6207      } else {
6208        mpInstance.Logger.verbose(Messages$3.InformationMessages.AbandonLogEvent);
6209      }
6210    };
6211    this.startTracking = function(callback) {
6212      if (!mpInstance._Store.isTracking) {
6213        if ("geolocation" in navigator) {
6214          mpInstance._Store.watchPositionId = navigator.geolocation.watchPosition(successTracking, errorTracking);
6215        }
6216      } else {
6217        var position = {
6218          coords: {
6219            latitude: mpInstance._Store.currentPosition.lat,
6220            longitude: mpInstance._Store.currentPosition.lng
6221          }
6222        };
6223        triggerCallback(callback, position);
6224      }
6225      function successTracking(position2) {
6226        mpInstance._Store.currentPosition = {
6227          lat: position2.coords.latitude,
6228          lng: position2.coords.longitude
6229        };
6230        triggerCallback(callback, position2);
6231        callback = null;
6232        mpInstance._Store.isTracking = true;
6233      }
6234      function errorTracking() {
6235        triggerCallback(callback);
6236        callback = null;
6237        mpInstance._Store.isTracking = false;
6238      }
6239      function triggerCallback(callback2, position2) {
6240        if (callback2) {
6241          try {
6242            if (position2) {
6243              callback2(position2);
6244            } else {
6245              callback2();
6246            }
6247          } catch (e) {
6248            mpInstance.Logger.error("Error invoking the callback passed to startTrackingLocation.");
6249            mpInstance.Logger.error(e);
6250          }
6251        }
6252      }
6253    };
6254    this.stopTracking = function() {
6255      if (mpInstance._Store.isTracking) {
6256        navigator.geolocation.clearWatch(mpInstance._Store.watchPositionId);
6257        mpInstance._Store.currentPosition = null;
6258        mpInstance._Store.isTracking = false;
6259      }
6260    };
6261    this.logOptOut = function() {
6262      mpInstance.Logger.verbose(Messages$3.InformationMessages.StartingLogOptOut);
6263      var event = mpInstance._ServerModel.createEventObject({
6264        messageType: Types.MessageType.OptOut,
6265        eventType: Types.EventType.Other
6266      });
6267      mpInstance._APIClient.sendEventToServer(event);
6268    };
6269    this.logAST = function() {
6270      self.logEvent({
6271        messageType: Types.MessageType.AppStateTransition
6272      });
6273    };
6274    this.logPageView = function() {
6275      self.logEvent({
6276        messageType: Types.MessageType.PageView,
6277        name: "PageView",
6278        data: __assign(__assign({}, allowedQueryParams(getHref())), {
6279          hostname: window.location.hostname,
6280          title: window.document.title
6281        }),
6282        eventType: Types.EventType.Unknown
6283      });
6284    };
6285    this.logCheckoutEvent = function(step, option, attrs, customFlags) {
6286      var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags);
6287      if (event) {
6288        event.EventName += mpInstance._Ecommerce.getProductActionEventName(Types.ProductActionType.Checkout);
6289        event.EventCategory = Types.CommerceEventType.ProductCheckout;
6290        event.ProductAction = {
6291          ProductActionType: Types.ProductActionType.Checkout,
6292          CheckoutStep: step,
6293          CheckoutOptions: option,
6294          ProductList: []
6295        };
6296        self.logCommerceEvent(event, attrs);
6297      }
6298    };
6299    this.logProductActionEvent = function(productActionType, product, customAttrs, customFlags, transactionAttributes, options) {
6300      var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags, options);
6301      var productList = Array.isArray(product) ? product : [product];
6302      productList.forEach(function(product2) {
6303        if (product2.TotalAmount) {
6304          product2.TotalAmount = mpInstance._Ecommerce.sanitizeAmount(product2.TotalAmount, "TotalAmount");
6305        }
6306        if (product2.Position) {
6307          product2.Position = mpInstance._Ecommerce.sanitizeAmount(product2.Position, "Position");
6308        }
6309        if (product2.Price) {
6310          product2.Price = mpInstance._Ecommerce.sanitizeAmount(product2.Price, "Price");
6311        }
6312        if (product2.Quantity) {
6313          product2.Quantity = mpInstance._Ecommerce.sanitizeAmount(product2.Quantity, "Quantity");
6314        }
6315      });
6316      if (event) {
6317        event.EventCategory = mpInstance._Ecommerce.convertProductActionToEventType(productActionType);
6318        event.EventName += mpInstance._Ecommerce.getProductActionEventName(productActionType);
6319        event.ProductAction = {
6320          ProductActionType: productActionType,
6321          ProductList: productList
6322        };
6323        if (Types.ProductActionType.isRoktCommerceType(productActionType)) {
6324          event.CustomFlags = event.CustomFlags || {};
6325          event.CustomFlags["Rokt.CommerceEventType"] = Types.ProductActionType.getExpansionName(productActionType);
6326        }
6327        if (mpInstance._Helpers.isObject(transactionAttributes)) {
6328          mpInstance._Ecommerce.convertTransactionAttributesToProductAction(transactionAttributes, event.ProductAction);
6329        }
6330        self.logCommerceEvent(event, customAttrs, options);
6331      }
6332    };
6333    this.logPurchaseEvent = function(transactionAttributes, product, attrs, customFlags) {
6334      var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags);
6335      if (event) {
6336        event.EventName += mpInstance._Ecommerce.getProductActionEventName(Types.ProductActionType.Purchase);
6337        event.EventCategory = Types.CommerceEventType.ProductPurchase;
6338        event.ProductAction = {
6339          ProductActionType: Types.ProductActionType.Purchase
6340        };
6341        event.ProductAction.ProductList = mpInstance._Ecommerce.buildProductList(event, product);
6342        mpInstance._Ecommerce.convertTransactionAttributesToProductAction(transactionAttributes, event.ProductAction);
6343        self.logCommerceEvent(event, attrs);
6344      }
6345    };
6346    this.logRefundEvent = function(transactionAttributes, product, attrs, customFlags) {
6347      if (!transactionAttributes) {
6348        mpInstance.Logger.error(Messages$3.ErrorMessages.TransactionRequired);
6349        return;
6350      }
6351      var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags);
6352      if (event) {
6353        event.EventName += mpInstance._Ecommerce.getProductActionEventName(Types.ProductActionType.Refund);
6354        event.EventCategory = Types.CommerceEventType.ProductRefund;
6355        event.ProductAction = {
6356          ProductActionType: Types.ProductActionType.Refund
6357        };
6358        event.ProductAction.ProductList = mpInstance._Ecommerce.buildProductList(event, product);
6359        mpInstance._Ecommerce.convertTransactionAttributesToProductAction(transactionAttributes, event.ProductAction);
6360        self.logCommerceEvent(event, attrs);
6361      }
6362    };
6363    this.logPromotionEvent = function(promotionType, promotion, attrs, customFlags, eventOptions) {
6364      var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags);
6365      if (event) {
6366        event.EventName += mpInstance._Ecommerce.getPromotionActionEventName(promotionType);
6367        event.EventCategory = mpInstance._Ecommerce.convertPromotionActionToEventType(promotionType);
6368        event.PromotionAction = {
6369          PromotionActionType: promotionType,
6370          PromotionList: Array.isArray(promotion) ? promotion : [promotion]
6371        };
6372        self.logCommerceEvent(event, attrs, eventOptions);
6373      }
6374    };
6375    this.logImpressionEvent = function(impression, attrs, customFlags, options) {
6376      var event = mpInstance._Ecommerce.createCommerceEventObject(customFlags);
6377      if (event) {
6378        event.EventName += "Impression";
6379        event.EventCategory = Types.CommerceEventType.ProductImpression;
6380        if (!Array.isArray(impression)) {
6381          impression = [impression];
6382        }
6383        event.ProductImpressions = [];
6384        impression.forEach(function(impression2) {
6385          event.ProductImpressions.push({
6386            ProductImpressionList: impression2.Name,
6387            ProductList: Array.isArray(impression2.Product) ? impression2.Product : [impression2.Product]
6388          });
6389        });
6390        self.logCommerceEvent(event, attrs, options);
6391      }
6392    };
6393    this.logCommerceEvent = function(commerceEvent, attrs, options) {
6394      mpInstance.Logger.verbose(Messages$3.InformationMessages.StartingLogCommerceEvent);
6395      if (commerceEvent.ProductAction && commerceEvent.EventCategory === null) {
6396        mpInstance.Logger.error("Commerce event not sent.  The mParticle.ProductActionType you passed was invali
6396d. Re-check your code.");
6397        return;
6398      }
6399      var sanitizedAttrs = mpInstance._Helpers.sanitizeAttributes(attrs, commerceEvent.EventName);
6400      if (mpInstance._Helpers.canLog()) {
6401        if (mpInstance._Store.webviewBridgeEnabled) {
6402          commerceEvent.ShoppingCart = {};
6403        }
6404        if (sanitizedAttrs) {
6405          commerceEvent.EventAttributes = sanitizedAttrs;
6406        }
6407        if (commerceEvent.ProductAction) {
6408          mpInstance._Ecommerce.calculateProductActionTotalAmount(commerceEvent.ProductAction);
6409        }
6410        mpInstance._APIClient.sendEventToServer(commerceEvent, options);
6411        mpInstance._Persistence.update();
6412      } else {
6413        mpInstance.Logger.verbose(Messages$3.InformationMessages.AbandonLogEvent);
6414      }
6415    };
6416    this.addEventHandler = function(domEvent, selector, eventName, data, eventType) {
6417      var elements = [], handler = function handler2(e) {
6418        var timeoutHandler = function timeoutHandler2() {
6419          if (element.href) {
6420            window.location.href = element.href;
6421          } else if (element.submit) {
6422            element.submit();
6423          }
6424        };
6425        mpInstance.Logger.verbose("DOM event triggered, handling event");
6426        self.logEvent({
6427          messageType: Types.MessageType.PageEvent,
6428          name: typeof eventName === "function" ? eventName(element) : eventName,
6429          data: typeof data === "function" ? data(element) : data,
6430          eventType: eventType || Types.EventType.Other
6431        });
6432        if (element.href && element.target !== "_blank" || element.submit) {
6433          if (e.preventDefault) {
6434            e.preventDefault();
6435          } else {
6436            e.returnValue = false;
6437          }
6438          setTimeout(timeoutHandler, mpInstance._Store.SDKConfig.timeout);
6439        }
6440      }, element, i;
6441      if (!selector) {
6442        mpInstance.Logger.error("Can't bind event, selector is required");
6443        return;
6444      }
6445      if (typeof selector === "string") {
6446        elements = document.querySelectorAll(selector);
6447      } else if (selector.nodeType) {
6448        elements = [selector];
6449      }
6450      if (elements.length) {
6451        mpInstance.Logger.verbose("Found " + elements.length + " element" + (elements.length > 1 ? "s" : "") + ", attaching event handlers");
6452        for (i = 0; i < elements.length; i++) {
6453          element = elements[i];
6454          if (element.addEventListener) {
6455            element.addEventListener(domEvent, handler, false);
6456          } else if (element.attachEvent) {
6457            element.attachEvent("on" + domEvent, handler);
6458          } else {
6459            element["on" + domEvent] = handler;
6460          }
6461        }
6462      } else {
6463        mpInstance.Logger.verbose("No elements found");
6464      }
6465    };
6466  }
6467  function isAttributeKeyAllowed(kitBlocker, key) {
6468    return !(kitBlocker === null || kitBlocker === void 0 ? void 0 : kitBlocker.isAttributeKeyBlocked(key));
6469  }
6470  function isIdentityAllowed(kitBlocker, identityName) {
6471    return !(kitBlocker === null || kitBlocker === void 0 ? void 0 : kitBlocker.isIdentityBlocked(identityName));
6472  }
6473  function copyUserAttributeValue(value) {
6474    return Array.isArray(value) ? value.slice() : value;
6475  }
6476  function buildUserAttributesCopy(userAttributes, kitBlocker) {
6477    var userAttributesCopy = {};
6478    if (!userAttributes) {
6479      return userAttributesCopy;
6480    }
6481    for (var prop in userAttributes) {
6482      if (!userAttributes.hasOwnProperty(prop) || !isAttributeKeyAllowed(kitBlocker, prop)) {
6483        continue;
6484      }
6485      userAttributesCopy[prop] = copyUserAttributeValue(userAttributes[prop]);
6486    }
6487    return userAttributesCopy;
6488  }
6489  function buildUserAttributeLists(userAttributes, kitBlocker) {
6490    var userAttributesLists = {};
6491    for (var key in userAttributes) {
6492      if (!userAttributes.hasOwnProperty(key) || !Array.isArray(userAttributes[key]) || !isAttributeKeyAllowed(kitBlocker, key)) {
6493        continue;
6494      }
6495      userAttributesLists[key] = userAttributes[key].slice();
6496    }
6497    return userAttributesLists;
6498  }
6499  function buildFilteredUserIdentities(identities, kitBlocker, parseNumber2) {
6500    var currentUserIdentities = {};
6501    var identitiesByType = identities;
6502    for (var identityType in identitiesByType) {
6503      if (!identitiesByType.hasOwnProperty(identityType)) {
6504        continue;
6505      }
6506      var identityName = Types.IdentityType.getIdentityName(parseNumber2(identityType));
6507      if (!isIdentityAllowed(kitBlocker, identityName)) {
6508        continue;
6509      }
6510      currentUserIdentities[identityName] = identitiesByType[identityType];
6511    }
6512    return currentUserIdentities;
6513  }
6514  function filteredMparticleUser(mpid, forwarder, mpInstance, kitBlocker) {
6515    function getAllUserAttributes() {
6516      var userAttributesCopy = buildUserAttributesCopy(mpInstance._Store.getUserAttributes(mpid), kitBlocker);
6517      return mpInstance._Helpers.filterUserAttributes(userAttributesCopy, forwarder.userAttributeFilters);
6518    }
6519    return {
6520      getUserIdentities: function getUserIdentities() {
6521        var currentUserIdentities = buildFilteredUserIdentities(mpInstance._Store.getUserIdentities(mpid), kitBlocker, mpInstance._Helpers.parseNumber);
6522        currentUserIdentities = mpInstance._Helpers.filterUserIdentitiesForForwarders(currentUserIdentities, forwarder.userIdentityFilters);
6523        return {
6524          userIdentities: currentUserIdentities
6525        };
6526      },
6527      getMPID: function getMPID() {
6528        return mpid;
6529      },
6530      getUserAttributesLists: function getUserAttributesLists(forwarder2) {
6531        var userAttributesLists = buildUserAttributeLists(getAllUserAttributes(), kitBlocker);
6532        return mpInstance._Helpers.filterUserAttributes(userAttributesLists, forwarder2.userAttributeFilters);
6533      },
6534      getAllUserAttributes
6535    };
6536  }
6537  var FORWARDING_RULE_MESSAGE_TYPES = [Types.MessageType.PageEvent, Types.MessageType.PageView, Types.MessageType.Commerce];
6538  function inFilteredList(filterList, hash) {
6539    if (filterList && filterList.length) {
6540      return inArray(filterList, hash);
6541    }
6542    return false;
6543  }
6544  function isBlockedByForwardingRule(messageType, attributes, forwarder) {
6545    if (!FORWARDING_RULE_MESSAGE_TYPES.includes(messageType) || !forwarder.filteringEventAttributeValue || !forwarder.filteringEventAttributeValue.eventAttributeName || !forwarder.filteringEventAttributeValue.eventAttributeValue) {
6546      return false;
6547    }
6548    var foundProp = null;
6549    if (attributes) {
6550      for (var prop in attributes) {
6551        if (attributes.hasOwnProperty(prop)) {
6552          var hashedName = KitFilterHelper.hashAttributeConditionalForwarding(prop);
6553          if (hashedName === forwarder.filteringEventAttributeValue.eventAttributeName) {
6554            foundProp = {
6555              name: hashedName,
6556              value: KitFilterHelper.hashAttributeConditionalForwarding(attributes[prop])
6557            };
6558            break;
6559          }
6560        }
6561      }
6562    }
6563    var isMatch = foundProp !== null && foundProp.value === forwarder.filteringEventAttributeValue.eventAttributeValue;
6564    var shouldInclude = forwarder.filteringEventAttributeValue.includeOnMatch === true ? isMatch : !isMatch;
6565    return !shouldInclude;
6566  }
6567  function isBlockedByEventFilter(messageType, hashedEventName, hashedEventType, forwarder) {
6568    if (messageType === Types.MessageType.PageEvent && (inFilteredList(forwarder.eventNameFilters, hashedEventName) || inFilteredList(forwarder.eventTypeFilters, hashedEventType))) {
6569      return true;
6570    } else if (messageType === Types.MessageType.Commerce && inFilteredList(forwarder.eventTypeFilters, hashedEventType)) {
6571      return true;
6572    } else if (messageType === Types.MessageType.PageView && inFilteredList(forwarder.screenNameFilters, hashedEventName)) {
6573      return true;
6574    }
6575    return false;
6576  }
6577  function filterEventAttributes(messageType, eventCategory, eventName, attributes, forwarder) {
6578    if (!attributes) {
6579      return attributes;
6580    }
6581    var filterList;
6582    if (messageType === Types.MessageType.PageEvent) {
6583      filterList = forwarder.attributeFilters;
6584    } else if (messageType === Types.MessageType.PageView) {
6585      filterList = forwarder.screenAttributeFilters;
6586    }
6587    if (!filterList) {
6588      return attributes;
6589    }
6590    var filtered = {};
6591    for (var attrName in attributes) {
6592      if (attributes.hasOwnProperty(attrName)) {
6593        var hash = KitFilterHelper.hashEventAttributeKey(eventCategory, eventName, attrName);
6594        if (!inArray(filterList, hash)) {
6595          filtered[attrName] = attributes[attrName];
6596        }
6597      }
6598    }
6599    return filtered;
6600  }
6601  function filterUserIdentities(userIdentities, filterList) {
6602    if (!userIdentities || !userIdentities.length) {
6603      return userIdentities || [];
6604    }
6605    return userIdentities.filter(function(userIdentity) {
6606      return !inArray(filterList, KitFilterHelper.hashUserIdentity(userIdentity.Type));
6607    });
6608  }
6609  var _a;
6610  var _b = Constants.IdentityMethods, Modify$2 = _b.Modify, Identify$1 = _b.Identify, Login$1 = _b.Login, Logout$1 = _b.Logout;
6611  var identityCompleteKitMethods = (_a = {}, _a[Identify$1] = "onIdentifyComplete", _a[Login$1] = "onLoginComplete", _a[Logout$1] = "onLogoutComplete", _a[Modify$2] = "onModifyComplete", _a);
6612  function userAttributesMatchFilter(userAttributes, filterObject) {
6613    for (var attrName in userAttributes) {
6614      if (!userAttributes.hasOwnProperty(attrName)) {
6615        continue;
6616      }
6617      var attrHash = KitFilterHelper.hashAttributeConditionalForwarding(attrName);
6618      var valueHash = KitFilterHelper.hashAttributeConditionalForwarding(userAttributes[attrName]);
6619      if (attrHash === filterObject.userAttributeName && valueHash === filterObject.userAttributeValue) {
6620        return true;
6621      }
6622    }
6623    return false;
6624  }
6625  function Forwarders(mpInstance, kitBlocker) {
6626    var _this = this;
6627    var self = this;
6628    this.forwarderStatsUploader = new APIClient(mpInstance, kitBlocker).initializeForwarderStatsUploader();
6629    var UserAttributeActionTypes = {
6630      setUserAttribute: "setUserAttribute",
6631      removeUserAttribute: "removeUserAttribute"
6632    };
6633    this.initForwarders = function(userIdentities, forwardingStatsCallback) {
6634      var user = mpInstance.Identity.getCurrentUser();
6635      if (!mpInstance._Store.webviewBridgeEnabled && mpInstance._Store.configuredForwarders) {
6636        mpInstance._Store.configuredForwarders.sort(function(x, y) {
6637          x.settings.PriorityValue = x.settings.PriorityValue || 0;
6638          y.settings.PriorityValue = y.settings.PriorityValue || 0;
6639          return -1 * (x.settings.PriorityValue - y.settings.PriorityValue);
6640        });
6641        mpInstance._Store.activeForwarders = mpInstance._Store.configuredForwarders.filter(function(forwarder) {
6642          if (!mpInstance._Consent.isEnabledForUserConsent(forwarder.filteringConsentRuleValues, user)) {
6643            return false;
6644          }
6645          if (!self.isEnabledForUserAttributes(forwarder.filteringUserAttributeValue, user)) {
6646            return false;
6647          }
6648          if (!self.isEnabledForUnknownUser(forwarder.excludeAnonymousUser, user)) {
6649            return false;
6650          }
6651          var filteredUserIdentities = mpInstance._Helpers.filterUserIdentities(userIdentities, forwarder.userIdentityFilters);
6652          var filteredUserAttributes = KitFilterHelper.filterUserAttributes(user ? user.getAllUserAttributes() : {}, forwarder.userAttributeFilters);
6653          if (!forwarder.initialized) {
6654            forwarder.logger = mpInstance.Logger;
6655            forwarder.init(forwarder.settings, forwardingStatsCallback, false, null, filteredUserAttributes, filteredUserIdentities, mpInstance._Store.SDKConfig.appVersion, mpInstance._Store.SDKConfig.appName, mpInstance._Store.SDKConfig.customFlags, mpInstance._Store.clientId);
6656            forwarder.initialized = true;
6657          }
6658          return true;
6659        });
6660      }
6661    };
6662    this.isEnabledForUserAttributes = function(filterObject, user) {
6663      if (!filterObject || !mpInstance._Helpers.isObject(filterObject) || !Object.keys(filterObject).length) {
6664        return true;
6665      }
6666      if (!user) {
6667        return false;
6668      }
6669      var userAttributes = user.getAllUserAttributes();
6670      try {
6671        var hasUserAttributes = userAttributes && mpInstance._Helpers.isObject(userAttributes) && Object.keys(userAttributes).length > 0;
6672        var isMatch = hasUserAttributes ? userAttributesMatchFilter(userAttributes, filterObject) : false;
6673        return filterObject.includeOnMatch === isMatch;
6674      } catch (e) {
6675        return true;
6676      }
6677    };
6678    this.isEnabledForUnknownUser = function(excludeAnonymousUserBoolean, user) {
6679      if (!user || !user.isLoggedIn()) {
6680        if (excludeAnonymousUserBoolean) {
6681          return false;
6682        }
6683      }
6684      return true;
6685    };
6686    this.applyToForwarders = function(functionName, functionArgs) {
6687      if (mpInstance._Store.activeForwarders.length) {
6688        mpInstance._Store.activeForwarders.forEach(function(forwarder) {
6689          var forwarderFunction = forwarder[functionName];
6690          if (forwarderFunction) {
6691            try {
6692              var result = forwarder[functionName](functionArgs);
6693              if (result) {
6694                mpInstance.Logger.verbose(result);
6695              }
6696            } catch (e) {
6697              mpInstance.Logger.verbose(e);
6698            }
6699          }
6700        });
6701      }
6702    };
6703    this.sendEventToForwarders = function(event) {
6704      if (mpInstance._Store.webviewBridgeEnabled || !mpInstance._Store.activeForwarders) {
6705        return;
6706      }
6707      var hashedEventName = KitFilterHelper.hashEventName(event.EventName, event.EventCategory);
6708      var hashedEventType = KitFilterHelper.hashEventType(event.EventCategory);
6709      var forwardEvent = function forwardEvent2(forwarder) {
6710        if (isBlockedByForwardingRule(event.EventDataType, event.EventAttributes, forwarder)) {
6711          return;
6712        }
6713        var clonedEvent = extend(true, {}, event);
6714        if (isBlockedByEventFilter(event.EventDataType, hashedEventName, hashedEventType, forwarder)) {
6715          return;
6716        }
6717        clonedEvent.EventAttributes = filterEventAttributes(event.EventDataType, event.EventCategory, event.EventName, clonedEvent.EventAttributes, forwarder);
6718        clonedEvent.UserIdentities = filterUserIdentities(clonedEvent.UserIdentities, forwarder.userIdentityFilters);
6719        clonedEvent.UserAttributes = KitFilterHelper.filterUserAttributes(clonedEvent.UserAttributes, forwarder.userAttributeFilters);
6720        if (!forwarder.process) {
6721          return;
6722        }
6723        mpInstance.Logger.verbose("Sending message to forwarder: " + forwarder.name);
6724        var result = forwarder.process(clonedEvent);
6725        if (result) {
6726          mpInstance.Logger.verbose(result);
6727        }
6728      };
6729      mpInstance._Store.activeForwarders.forEach(function(forwarder) {
6730        forwardEvent(forwarder);
6731      });
6732    };
6733    this.handleForwarderUserAttributes = function(functionNameKey, key, value) {
6734      if (kitBlocker && kitBlocker.isAttributeKeyBlocked(key) || !mpInstance._Store.activeForwarders.length) {
6735        return;
6736      }
6737      mpInstance._Store.activeForwarders.forEach(function(forwarder) {
6738        var forwarderFunction = forwarder[functionNameKey];
6739        if (!forwarderFunction || KitFilterHelper.isFilteredUserAttribute(key, forwarder.userAttributeFilters)) {
6740          return;
6741        }
6742        try {
6743          var result = void 0;
6744          if (functionNameKey === UserAttributeActionTypes.setUserAttribute) {
6745            result = forwarder.setUserAttribute(key, value);
6746          } else if (functionNameKey === UserAttributeActionTypes.removeUserAttribute) {
6747            result = forwarder.removeUserAttribute(key);
6748          }
6749          if (result) {
6750            mpInstance.Logger.verbose(result);
6751          }
6752        } catch (e) {
6753          mpInstance.Logger.error(e);
6754        }
6755      });
6756    };
6757    this.setForwarderUserIdentities = function(userIdentities) {
6758      mpInstance._Store.activeForwarders.forEach(function(forwarder) {
6759        var filteredUserIdentities = mpInstance._Helpers.filterUserIdentities(userIdentities, forwarder.userIdentityFilters);
6760        if (forwarder.setUserIdentity) {
6761          filteredUserIdentities.forEach(function(identity) {
6762            var result = forwarder.setUserIdentity(identity.Identity, identity.Type);
6763            if (result) {
6764              mpInstance.Logger.verbose(result);
6765            }
6766          });
6767        }
6768      });
6769    };
6770    this.setForwarderOnUserIdentified = function(user) {
6771      mpInstance._Store.activeForwarders.forEach(function(forwarder) {
6772        var filteredUser = filteredMparticleUser(user.getMPID(), forwarder, mpInstance, kitBlocker);
6773        if (forwarder.onUserIdentified) {
6774          var result = forwarder.onUserIdentified(filteredUser);
6775          if (result) {
6776            mpInstance.Logger.verbose(result);
6777          }
6778        }
6779      });
6780    };
6781    this.setForwarderOnIdentityComplete = function(user, identityMethod) {
6782      var kitMethodName = identityCompleteKitMethods[identityMethod];
6783      if (!kitMethodName) {
6784        return;
6785      }
6786      mpInstance._Store.activeForwarders.forEach(function(forwarder) {
6787        var onIdentityComplete = forwarder[kitMethodName];
6788        if (!onIdentityComplete) {
6789          return;
6790        }
6791        var filteredUser = filteredMparticleUser(user.getMPID(), forwarder, mpInstance, kitBlocker);
6792        var result = onIdentityComplete.call(forwarder, filteredUser, filteredUser.getUserIdentities());
6793        if (result) {
6794          mpInstance.Logger.verbose(result);
6795        }
6796      });
6797    };
6798    this.getForwarderStatsQueue = function() {
6799      return mpInstance._Persistence.forwardingStatsBatches.forwardingStatsEventQueue;
6800    };
6801    this.setForwarderStatsQueue = function(queue) {
6802      mpInstance._Persistence.forwardingStatsBatches.forwardingStatsEventQueue = queue;
6803    };
6804    this.processForwarders = function(config, forwardingStatsCallback) {
6805      if (!config) {
6806        mpInstance.Logger.warning("No config was passed. Cannot process forwarders");
6807      } else {
6808        this.processUIEnabledKits(config);
6809        this.processSideloadedKits(config);
6810        self.initForwarders(mpInstance._Store.SDKConfig.identifyRequest.userIdentities, forwardingStatsCallback);
6811      }
6812    };
6813    this.processUIEnabledKits = function(config) {
6814      var kits = this.returnKitConstructors();
6815      try {
6816        if (Array.isArray(config.kitConfigs) && config.kitConfigs.length) {
6817          config.kitConfigs.forEach(function(kitConfig) {
6818            self.configureUIEnabledKit(kitConfig, kits);
6819          });
6820        }
6821      } catch (e) {
6822        mpInstance.Logger.error("MP Kits not configured propertly. Kits may not be initialized. " + e);
6823      }
6824    };
6825    this.returnKitConstructors = function() {
6826      var kits = {};
6827      if (!isEmpty(mpInstance._Store.SDKConfig.kits)) {
6828        kits = mpInstance._Store.SDKConfig.kits;
6829      } else if (!isEmpty(mpInstance._preInit.forwarderConstructors)) {
6830        mpInstance._preInit.forwarderConstructors.forEach(function(kitConstructor) {
6831          if (kitConstructor.suffix) {
6832            var kitNameWithConstructorSuffix = "".concat(kitConstructor.name, "-").concat(kitConstructor.suffix);
6833            kits[kitNameWithConstructorSuffix] = kitConstructor;
6834          } else {
6835            kits[kitConstructor.name] = kitConstructor;
6836          }
6837        });
6838      }
6839      return kits;
6840    };
6841    this.configureUIEnabledKit = function(configuration, kits) {
6842      var newKit = null;
6843      var config = configuration;
6844      for (var name_1 in kits) {
6845        var kitNameWithConfigSuffix = void 0;
6846        if (config.suffix) {
6847          kitNameWithConfigSuffix = "".concat(config.name, "-").concat(config.suffix);
6848        }
6849        if (name_1 === kitNameWithConfigSuffix || name_1 === config.name) {
6850          if (config.isDebug === mpInstance._Store.SDKConfig.isDevelopmentMode || config.isSandbox === mpInstance._Store.SDKConfig.isDevelopmentMode) {
6851            newKit = this.returnConfiguredKit(kits[name_1], config);
6852            mpInstance._Store.configuredForwarders.push(newKit);
6853            break;
6854          }
6855        }
6856      }
6857    };
6858    this.processSideloadedKits = function(mpConfig) {
6859      try {
6860        if (Array.isArray(mpConfig.sideloadedKits)) {
6861          var registeredSideloadedKits_1 = {
6862            kits: {}
6863          };
6864          var unregisteredSideloadedKits = mpConfig.sideloadedKits;
6865          unregisteredSideloadedKits.forEach(function(unregisteredKit) {
6866            try {
6867              unregisteredKit.kitInstance.register(registeredSideloadedKits_1);
6868              var kitName = unregisteredKit.kitInstance.name;
6869              registeredSideloadedKits_1.kits[kitName].filters = unregisteredKit.filterDictionary;
6870            } catch (e) {
6871              console.error("Error registering sideloaded kit " + unregisteredKit.kitInstance.name);
6872            }
6873          });
6874          for (var registeredKitKey in registeredSideloadedKits_1.kits) {
6875            var registeredKit = registeredSideloadedKits_1.kits[registeredKitKey];
6876            self.configureSideloadedKit(registeredKit);
6877          }
6878          if (!isEmpty(registeredSideloadedKits_1.kits)) {
6879            var kitKeys = Object.keys(registeredSideloadedKits_1.kits);
6880            mpInstance._Store.sideloadedKitsCount = kitKeys.length;
6881          }
6882        }
6883      } catch (e) {
6884        mpInstance.Logger.error("Sideloaded Kits not configured propertly. Kits may not be initialized. " + e);
6885      }
6886    };
6887    this.configureSideloadedKit = function(kitConstructor) {
6888      mpInstance._Store.configuredForwarders.push(this.returnConfiguredKit(kitConstructor, kitConstructor.filters));
6889    };
6890    this.returnConfiguredKit = function(forwarder, config) {
6891      if (config === void 0) {
6892        config = {};
6893      }
6894      var newForwarder = new forwarder.constructor();
6895      newForwarder.id = config.moduleId;
6896      newForwarder.isSandbox = config.isDebug || config.isSandbox;
6897      newForwarder.hasSandbox = config.hasDebugString === "true";
6898      newForwarder.isVisible = config.isVisible || true;
6899      newForwarder.settings = config.settings || {};
6900      newForwarder.eventNameFilters = config.eventNameFilters || [];
6901      newForwarder.eventTypeFilters = config.eventTypeFilters || [];
6902      newForwarder.attributeFilters = config.attributeFilters || [];
6903      newForwarder.screenNameFilters = config.screenNameFilters || [];
6904      newForwarder.screenAttributeFilters = config.screenAttributeFilters || [];
6905      newForwarder.userIdentityFilters = config.userIdentityFilters || [];
6906      newForwarder.userAttributeFilters = config.userAttributeFilters || [];
6907      newForwarder.filteringEventAttributeValue = config.filteringEventAttributeValue || {};
6908      newForwarder.filteringUserAttributeValue = config.filteringUserAttributeValue || {};
6909      newForwarder.eventSubscriptionId = config.eventSubscriptionId || null;
6910      newForwarder.filteringConsentRuleValues = config.filteringConsentRuleValues || {};
6911      newForwarder.excludeAnonymousUser = config.excludeAnonymousUser || false;
6912      return newForwarder;
6913    };
6914    this.configurePixel = function(settings) {
6915      if (settings.isDebug === mpInstance._Store.SDKConfig.isDevelopmentMode || settings.isProduction !== mpInstance._Store.SDKConfig.isDevelopmentMode) {
6916        mpInstance._Store.pixelConfigurations.push(settings);
6917      }
6918    };
6919    this.processPixelConfigs = function(config) {
6920      try {
6921        if (!isEmpty(config.pixelConfigs)) {
6922          config.pixelConfigs.forEach(function(pixelConfig) {
6923            self.configurePixel(pixelConfig);
6924          });
6925        }
6926      } catch (e) {
6927        mpInstance.Logger.error("Cookie Sync configs not configured propertly. Cookie Sync may not be initialized. " + e);
6928      }
6929    };
6930    this.sendSingleForwardingStatsToServer = function(forwardingStatsData) {
6931      return __awaiter(_this, void 0, void 0, function() {
6932        var fetchPayload, response, message;
6933        var _a2;
6934        return __generator(this, function(_b2) {
6935          switch (_b2.label) {
6936            case 0:
6937              fetchPayload = {
6938                method: "post",
6939                body: JSON.stringify(forwardingStatsData),
6940                headers: {
6941                  Accept: "text/plain;charset=UTF-8",
6942                  "Content-Type": "text/plain;charset=UTF-8"
6943                }
6944              };
6945              return [4, this.forwarderStatsUploader.upload(fetchPayload)];
6946            case 1:
6947              response = _b2.sent();
6948              if (response.status === 202) {
6949                message = "Successfully sent forwarding stats to mParticle Servers";
6950              } else {
6951                message = "Issue with forwarding stats to mParticle Servers, received HTTP Code of " + response.statusText;
6952              }
6953              (_a2 = mpInstance === null || mpInstance === void 0 ? void 0 : mpInstance.Logger) === null || _a2 === void 0 ? void 0 : _a2.verbose(message);
6954              return [
6955                2
6956                /*return*/
6957              ];
6958          }
6959        });
6960      });
6961    };
6962  }
6963  var MessageType = Types.MessageType;
6964  var ApplicationTransitionType = Types.ApplicationTransitionType;
6965  function convertCustomFlags(event, dto) {
6966    var valueArray = [];
6967    dto.flags = {};
6968    for (var prop in event.CustomFlags) {
6969      valueArray = [];
6970      if (event.CustomFlags.hasOwnProperty(prop)) {
6971        if (Array.isArray(event.CustomFlags[prop])) {
6972          event.CustomFlags[prop].forEach(function(customFlagProperty) {
6973            if (isValidCustomFlagProperty(customFlagProperty)) {
6974              valueArray.push(customFlagProperty.toString());
6975            }
6976          });
6977        } else if (isValidCustomFlagProperty(event.CustomFlags[prop])) {
6978          valueArray.push(event.CustomFlags[prop].toString());
6979        }
6980        if (valueArray.length) {
6981          dto.flags[prop] = valueArray;
6982        }
6983      }
6984    }
6985  }
6986  function convertProductToV2DTO(product) {
6987    return {
6988      id: parseStringOrNumber(product.Sku),
6989      nm: parseStringOrNumber(product.Name),
6990      pr: parseNumber(product.Price),
6991      qt: parseNumber(product.Quantity),
6992      br: parseStringOrNumber(product.Brand),
6993      va: parseStringOrNumber(product.Variant),
6994      ca: parseStringOrNumber(product.Category),
6995      ps: parseNumber(product.Position),
6996      cc: parseStringOrNumber(product.CouponCode),
6997      tpa: parseNumber(product.TotalAmount),
6998      attrs: product.Attributes
6999    };
7000  }
7001  function convertProductListToV2DTO(productList) {
7002    if (!productList) {
7003      return [];
7004    }
7005    return productList.map(function(product) {
7006      return convertProductToV2DTO(product);
7007    });
7008  }
7009  function ServerModel(mpInstance) {
7010    var self = this;
7011    this.convertToConsentStateV2DTO = function(state) {
7012      if (!state) {
7013        return null;
7014      }
7015      var jsonObject = {};
7016      var gdprConsentState = state.getGDPRConsentState();
7017      if (gdprConsentState) {
7018        var gdpr = {};
7019        jsonObject.gdpr = gdpr;
7020        for (var purpose in gdprConsentState) {
7021          if (gdprConsentState.hasOwnProperty(purpose)) {
7022            var gdprConsent = gdprConsentState[purpose];
7023            jsonObject.gdpr[purpose] = {};
7024            if (typeof gdprConsent.Consented === "boolean") {
7025              gdpr[purpose].c = gdprConsent.Consented;
7026            }
7027            if (typeof gdprConsent.Timestamp === "number") {
7028              gdpr[purpose].ts = gdprConsent.Timestamp;
7029            }
7030            if (typeof gdprConsent.ConsentDocument === "string") {
7031              gdpr[purpose].d = gdprConsent.ConsentDocument;
7032            }
7033            if (typeof gdprConsent.Location === "string") {
7034              gdpr[purpose].l = gdprConsent.Location;
7035            }
7036            if (typeof gdprConsent.HardwareId === "string") {
7037              gdpr[purpose].h = gdprConsent.HardwareId;
7038            }
7039          }
7040        }
7041      }
7042      var ccpaConsentState = state.getCCPAConsentState();
7043      if (ccpaConsentState) {
7044        jsonObject.ccpa = {
7045          data_sale_opt_out: {
7046            c: ccpaConsentState.Consented,
7047            ts: ccpaConsentState.Timestamp,
7048            d: ccpaConsentState.ConsentDocument,
7049            l: ccpaConsentState.Location,
7050            h: ccpaConsentState.HardwareId
7051          }
7052        };
7053      }
7054      return jsonObject;
7055    };
7056    this.createEventObject = function(event, user) {
7057      var _a2, _b2, _c;
7058      var uploadObject = {};
7059      var eventObject = {};
7060      var optOut = event.messageType === Types.MessageType.OptOut ? !mpInstance._Store.isEnabled : null;
7061      if (mpInstance._Store.sessionId || event.messageType === Types.MessageType.OptOut || mpInstance._Store.webviewBridgeEnabled) {
7062        var customFlags = __assign({}, event.customFlags);
7063        var integrationAttributes = mpInstance._Store.integrationAttributes;
7064        var getFeatureFlag = mpInstance._Helpers.getFeatureFlag;
7065        var integrationSpecificIds = getFeatureFlag && getFeatureFlag(Constants.FeatureFlags.CaptureIntegrationSpecificIds);
7066        var integrationSpecificIdsV2 = getFeatureFlag && (getFeatureFlag(Constants.FeatureFlags.CaptureIntegrationSpecificIdsV2) || "");
7067        var isIntegrationCaptureEnabled = integrationSpecificIdsV2 && integrationSpecificIdsV2 !== Constants.CaptureIntegrationSpecificIdsV2Modes.None || integrationSpecificIds === true;
7068        if (isIntegrationCaptureEnabled) {
7069          mpInstance._IntegrationCapture.capture();
7070          var transformedClickIDs = mpInstance._IntegrationCapture.getClickIdsAsCustomFlags();
7071          customFlags = __assign(__assign({}, transformedClickIDs), customFlags);
7072          var transformedIntegrationAttributes = mpInstance._IntegrationCapture.getClickIdsAsIntegrationAttributes();
7073          integrationAttributes = __assign(__assign({}, transformedIntegrationAttributes), integrationAttributes);
7074        }
7075        if (event.hasOwnProperty("toEventAPIObject")) {
7076          eventObject = event.toEventAPIObject();
7077        } else {
7078          eventObject = {
7079            // This is an artifact from v2 events where SessionStart/End and AST event
7080            //  names are numbers (1, 2, or 10), but going forward with v3, these lifecycle
7081            //  events do not have names, but are denoted by their `event_type`
7082            EventName: event.name || String(event.messageType),
7083            EventCategory: event.eventType,
7084            EventAttributes: mpInstance._Helpers.sanitizeAttributes(event.data, event.name),
7085            ActiveTimeOnSite: (_a2 = mpInstance._timeOnSiteTimer) === null || _a2 === void 0 ? void 0 : _a2.getTimeInForeground(),
7086            TotalTimeOnSite: (_c = (_b2 = mpInstance._Store).getTotalTimeOnSite) === null || _c === void 0 ? void 0 : _c.call(_b2),
7087            PageUrl: getHref() || null,
7088            SourceMessageId: event.sourceMessageId || mpInstance._Helpers.generateUniqueId(),
7089            EventDataType: event.messageType,
7090            CustomFlags: customFlags,
7091            UserAttributeChanges: event.userAttributeChanges,
7092            UserIdentityChanges: event.userIdentityChanges
7093          };
7094        }
7095        if (event.messageType !== Types.MessageType.SessionEnd) {
7096          mpInstance._Store.dateLastEventSent = /* @__PURE__ */ new Date();
7097        }
7098        uploadObject = {
7099          // FIXME: Deprecate when we get rid of V2
7100          Store: mpInstance._Store.serverSettings,
7101          SDKVersion: Constants.sdkVersion,
7102          SessionId: mpInstance._Store.sessionId,
7103          SessionStartDate: mpInstance._Store.sessionStartDate ? mpInstance._Store.sessionStartDate.getTime() : 0,
7104          Debug: mpInstance._Store.SDKConfig.isDevelopmentMode,
7105          Location: mpInstance._Store.currentPosition,
7106          OptOut: optOut,
7107          ExpandedEventCount: 0,
7108          AppVersion: mpInstance.getAppVersion(),
7109          AppName: mpInstance.getAppName(),
7110          Package: mpInstance._Store.SDKConfig["package"],
7111          ClientGeneratedId: mpInstance._Store.clientId,
7112          DeviceId: mpInstance._Store.deviceId,
7113          IntegrationAttributes: integrationAttributes,
7114          CurrencyCode: mpInstance._Store.currencyCode,
7115          DataPlan: mpInstance._Store.SDKConfig.dataPlan ? mpInstance._Store.SDKConfig.dataPlan : {}
7116        };
7117        if (eventObject.EventDataType === MessageType.AppStateTransition) {
7118          eventObject.IsFirstRun = mpInstance._Store.isFirstRun;
7119          eventObject.LaunchReferral = window.location.href || null;
7120        }
7121        eventObject.CurrencyCode = mpInstance._Store.currencyCode;
7122        var currentUser = user || mpInstance.Identity.getCurrentUser();
7123        appendUserInfo(currentUser, eventObject);
7124        if (event.messageType === Types.MessageType.SessionEnd) {
7125          eventObject.SessionLength = mpInstance._Store.dateLastEventSent.getTime() - mpInstance._Store.sessionStartDate.getTime();
7126          eventObject.currentSessionMPIDs = mpInstance._Store.currentSessionMPIDs;
7127          eventObject.EventAttributes = mpInstance._Store.sessionAttributes;
7128          mpInstance._Store.currentSessionMPIDs = [];
7129          mpInstance._Store.sessionStartDate = null;
7130        }
7131        uploadObject.Timestamp = mpInstance._Store.dateLastEventSent.getTime();
7132        return extend({}, eventObject, uploadObject);
7133      }
7134      return null;
7135    };
7136    this.convertEventToV2DTO = function(event) {
7137      var dto = {
7138        n: event.EventName,
7139        et: event.EventCategory,
7140        ua: event.UserAttributes,
7141        ui: event.UserIdentities,
7142        ia: event.IntegrationAttributes,
7143        str: event.Store,
7144        attrs: event.EventAttributes,
7145        sdk: event.SDKVersion,
7146        sid: event.SessionId,
7147        sl: event.SessionLength,
7148        ssd: event.SessionStartDate,
7149        dt: event.EventDataType,
7150        dbg: event.Debug,
7151        ct: event.Timestamp,
7152        lc: event.Location,
7153        o: event.OptOut,
7154        eec: event.ExpandedEventCount,
7155        av: event.AppVersion,
7156        cgid: event.ClientGeneratedId,
7157        das: event.DeviceId,
7158        mpid: event.MPID,
7159        smpids: event.currentSessionMPIDs
7160      };
7161      if (event.DataPlan && event.DataPlan.PlanId) {
7162        dto.dp_id = event.DataPlan.PlanId;
7163        if (event.DataPlan.PlanVersion) {
7164          dto.dp_v = event.DataPlan.PlanVersion;
7165        }
7166      }
7167      var consent = self.convertToConsentStateV2DTO(event.ConsentState);
7168      if (consent) {
7169        dto.con = consent;
7170      }
7171      if (event.EventDataType === MessageType.AppStateTransition) {
7172        dto.fr = event.IsFirstRun;
7173        dto.iu = false;
7174        dto.at = ApplicationTransitionType.AppInit;
7175        dto.lr = event.LaunchReferral;
7176        dto.attrs = null;
7177      }
7178      if (event.CustomFlags) {
7179        convertCustomFlags(event, dto);
7180      }
7181      if (event.EventDataType === MessageType.Commerce) {
7182        dto.cu = event.CurrencyCode;
7183        if (event.ShoppingCart) {
7184          dto.sc = {
7185            pl: convertProductListToV2DTO(event.ShoppingCart.ProductList)
7186          };
7187        }
7188        if (event.ProductAction) {
7189          dto.pd = {
7190            an: event.ProductAction.ProductActionType,
7191            cs: mpInstance._Helpers.parseNumber(event.ProductAction.CheckoutStep),
7192            co: event.ProductAction.CheckoutOptions,
7193            pl: convertProductListToV2DTO(event.ProductAction.ProductList),
7194            ti: event.ProductAction.TransactionId,
7195            ta: event.ProductAction.Affiliation,
7196            tcc: event.ProductAction.CouponCode,
7197            tr: mpInstance._Helpers.parseNumber(event.ProductAction.TotalAmount),
7198            ts: mpInstance._Helpers.parseNumber(event.ProductAction.ShippingAmount),
7199            tt: mpInstance._Helpers.parseNumber(event.ProductAction.TaxAmount)
7200          };
7201        } else if (event.PromotionAction) {
7202          dto.pm = {
7203            an: event.PromotionAction.PromotionActionType,
7204            pl: event.PromotionAction.PromotionList.map(function(promotion) {
7205              return {
7206                id: promotion.Id,
7207                nm: promotion.Name,
7208                cr: promotion.Creative,
7209                ps: promotion.Position ? promotion.Position : 0
7210              };
7211            })
7212          };
7213        } else if (event.ProductImpressions) {
7214          dto.pi = event.ProductImpressions.map(function(impression) {
7215            return {
7216              pil: impression.ProductImpressionList,
7217              pl: convertProductListToV2DTO(impression.ProductList)
7218            };
7219          });
7220        }
7221      } else if (event.EventDataType === MessageType.Profile) {
7222        dto.pet = event.ProfileMessageType;
7223      }
7224      return dto;
7225    };
7226  }
7227  function forwardingStatsUploader(mpInstance) {
7228    this.startForwardingStatsTimer = function() {
7229      window.mParticle._forwardingStatsTimer = setInterval(function() {
7230        prepareAndSendForwardingStatsBatch();
7231      }, mpInstance._Store.SDKConfig.forwarderStatsTimeout);
7232    };
7233    function prepareAndSendForwardingStatsBatch() {
7234      var forwarderQueue = mpInstance._Forwarders.getForwarderStatsQueue(), uploadsTable = mpInstance._Persistence.forwardingStatsBatches.uploadsTable, now = Date.now();
7235      if (forwarderQueue.length) {
7236        uploadsTable[now] = {
7237          uploading: false,
7238          data: forwarderQueue
7239        };
7240        mpInstance._Forwarders.setForwarderStatsQueue([]);
7241      }
7242      for (var date in uploadsTable) {
7243        (function(date2) {
7244          if (uploadsTable.hasOwnProperty(date2)) {
7245            if (uploadsTable[date2].uploading === false) {
7246              var xhrCallback = function xhrCallback2() {
7247                if (xhr_1.readyState === 4) {
7248                  if (xhr_1.status === 200 || xhr_1.status === 202) {
7249                    mpInstance.Logger.verbose("Successfully sent  " + xhr_1.statusText + " from server");
7250                    delete uploadsTable[date2];
7251                  } else if (xhr_1.status.toString()[0] === "4") {
7252                    if (xhr_1.status !== 429) {
7253                      delete uploadsTable[date2];
7254                    }
7255                  } else {
7256                    uploadsTable[date2].uploading = false;
7257                  }
7258                }
7259              };
7260              var xhr_1 = mpInstance._Helpers.createXHR(xhrCallback);
7261              var forwardingStatsData = uploadsTable[date2].data;
7262              uploadsTable[date2].uploading = true;
7263              mpInstance._APIClient.sendBatchForwardingStatsToServer(forwardingStatsData, xhr_1);
7264            }
7265          }
7266        })(date);
7267      }
7268    }
7269  }
7270  var AudienceManager = (
7271    /** @class */
7272    (function() {
7273      function AudienceManager2(userAudienceUrl, apiKey, logger) {
7274        this.url = "";
7275        this.logger = logger;
7276        this.url = "https://".concat(userAudienceUrl).concat(apiKey, "/audience");
7277        this.userAudienceAPI = window.fetch ? new FetchUploader(this.url) : new XHRUploader(this.url);
7278      }
7279      AudienceManager2.prototype.sendGetUserAudienceRequest = function(mpid, callback) {
7280        return __awaiter(this, void 0, void 0, function() {
7281          var fetchPayload, audienceURLWithMPID, userAudiencePromise, userAudienceMembershipsServerResponse, parsedUserAudienceMemberships, e_1;
7282          return __generator(this, function(_a2) {
7283            switch (_a2.label) {
7284              case 0:
7285                this.logger.verbose("Fetching user audiences from server");
7286                fetchPayload = {
7287                  method: "GET",
7288                  headers: {
7289                    Accept: "*/*"
7290                  }
7291                };
7292                audienceURLWithMPID = "".concat(this.url, "?mpid=").concat(mpid);
7293                _a2.label = 1;
7294              case 1:
7295                _a2.trys.push([1, 6, , 7]);
7296                return [4, this.userAudienceAPI.upload(fetchPayload, audienceURLWithMPID)];
7297              case 2:
7298                userAudiencePromise = _a2.sent();
7299                if (!(userAudiencePromise.status >= 200 && userAudiencePromise.status < 300)) return [3, 4];
7300                this.logger.verbose("User Audiences successfully received");
7301                return [4, userAudiencePromise.json()];
7302              case 3:
7303                userAudienceMembershipsServerResponse = _a2.sent();
7304                parsedUserAudienceMemberships = {
7305                  currentAudienceMemberships: userAudienceMembershipsServerResponse === null || userAudienceMembershipsServerResponse === void 0 ? void 0 : userAudienceMembershipsServerResponse.audience_memberships
7306                };
7307                try {
7308                  callback(parsedUserAudienceMemberships);
7309                } catch (e) {
7310                  throw new Error("Error invoking callback on user audience response.");
7311                }
7312                return [3, 5];
7313              case 4:
7314                if (userAudiencePromise.status === 401) {
7315                  throw new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your API key.`");
7316                } else if (userAudiencePromise.status === 403) {
7317                  throw new Error("`HTTP error status ${userAudiencePromise.status} while retrieving User Audiences - please verify your workspace is enabled for audiences.`");
7318                } else {
7319                  throw new Error("Uncaught HTTP Error ".concat(userAudiencePromise.status, "."));
7320                }
7321              case 5:
7322                return [3, 7];
7323              case 6:
7324                e_1 = _a2.sent();
7325                this.logger.error("Error retrieving audiences. ".concat(e_1));
7326                return [3, 7];
7327              case 7:
7328                return [
7329                  2
7330                  /*return*/
7331                ];
7332            }
7333          });
7334        });
7335      };
7336      return AudienceManager2;
7337    })()
7338  );
7339  var processReadyQueue = function processReadyQueue2(readyQueue, logger) {
7340    if (isEmpty(readyQueue)) {
7341      return [];
7342    }
7343    var items = readyQueue.splice(0, readyQueue.length);
7344    items.forEach(function(readyQueueItem) {
7345      try {
7346        if (isFunction(readyQueueItem)) {
7347          readyQueueItem();
7348        } else if (Array.isArray(readyQueueItem)) {
7349          processPreloadedItem(readyQueueItem);
7350        }
7351      } catch (e) {
7352        logger.error("Error processing ready queue item: " + getErrorMessage(e));
7353      }
7354    });
7355    return [];
7356  };
7357  var processPreloadedItem = function processPreloadedItem2(readyQueueItem) {
7358    var args = readyQueueItem.slice();
7359    var method = args.splice(0, 1)[0];
7360    if (typeof method !== "string" || method.length === 0) {
7361      return;
7362    }
7363    if (typeof window !== "undefined" && window.mParticle && window.mParticle[args[0]]) {
7364      window.mParticle[method].apply(window.mParticle, args);
7365    } else {
7366      var methodArray = method.split(".");
7367      try {
7368        var computedMPFunction = window.mParticle;
7369        var context_1 = window.mParticle;
7370        for (var _i = 0, methodArray_1 = methodArray; _i < methodArray_1.length; _i++) {
7371          var currentMethod = methodArray_1[_i];
7372          context_1 = computedMPFunction;
7373          computedMPFunction = computedMPFunction[currentMethod];
7374        }
7375        computedMPFunction.apply(context_1, args);
7376      } catch (e) {
7377        throw new Error("Unable to compute proper mParticle function " + e);
7378      }
7379    }
7380  };
7381  var Messages$2 = Constants.Messages, HTTPCodes$2 = Constants.HTTPCodes, FeatureFlags$1 = Constants.FeatureFlags, IdentityMethods$1 = Constants.IdentityMethods;
7382  var ErrorMessages = Messages$2.ErrorMessages;
7383  var CacheIdentity = FeatureFlags$1.CacheIdentity;
7384  var Identify = IdentityMethods$1.Identify, Modify$1 = IdentityMethods$1.Modify, Login = IdentityMethods$1.Login, Logout = IdentityMethods$1.Logout;
7385  function Identity(mpInstance) {
7386    var _a2 = mpInstance._Helpers, getFeatureFlag = _a2.getFeatureFlag, extend2 = _a2.extend;
7387    var self = this;
7388    this.idCache = null;
7389    this.audienceManager = null;
7390    this.IdentityRequest = {
7391      preProcessIdentityRequest: function preProcessIdentityRequest(identityApiData, callback, method) {
7392        mpInstance.Logger.verbose(Messages$2.InformationMessages.StartingLogEvent + ": " + method);
7393        var removedFalsyIdentityData = mpInstance._Helpers.Validators.removeFalsyIdentityValues(identityApiData, mpInstance.Logger);
7394        var cleanedIdentityApiData = (removedFalsyIdentityData === null || removedFalsyIdentityData === void 0 ? void 0 : removedFalsyIdentityData.userIdentities) ? __assign(__assign({}, removedFalsyIdentityData), {
7395          userIdentities: normalizeUserIdentityKeys(removedFalsyIdentityData.userIdentities)
7396        }) : removedFalsyIdentityData;
7397        var identityValidationResult = mpInstance._Helpers.Validators.validateIdentities(cleanedIdentityApiData, method);
7398        if (!identityValidationResult.valid) {
7399          mpInstance.Logger.error("ERROR: " + identityValidationResult.error);
7400          return {
7401            valid: false,
7402            error: identityValidationResult.error
7403          };
7404        }
7405        if (callback && !mpInstance._Helpers.Validators.isFunction(callback)) {
7406          var error = "The optional callback must be a function. You tried entering a(n) " + _typeof(callback);
7407          mpInstance.Logger.error(error);
7408          return {
7409            valid: false,
7410            error
7411          };
7412        }
7413        return {
7414          valid: true,
7415          cleanedIdentities: cleanedIdentityApiData
7416        };
7417      },
7418      createIdentityRequest: function createIdentityRequest(identityApiData, platform, sdkVendor, sdkVersion, deviceId, context, mpid) {
7419        var APIRequest = {
7420          client_sdk: {
7421            platform,
7422            sdk_vendor: sdkVendor,
7423            sdk_version: sdkVersion
7424          },
7425          context,
7426          environment: mpInstance._Store.SDKConfig.isDevelopmentMode ? "development" : "production",
7427          request_id: mpInstance._Helpers.generateUniqueId(),
7428          request_timestamp_ms: (/* @__PURE__ */ new Date()).getTime(),
7429          previous_mpid: mpid || null,
7430          known_identities: createKnownIdentities(identityApiData, deviceId)
7431        };
7432        return APIRequest;
7433      },
7434      createModifyIdentityRequest: function createModifyIdentityRequest(currentUserIdentities, newUserIdentities, platform, sdkVendor, sdkVersion, context) {
7435        return {
7436          client_sdk: {
7437            platform,
7438            sdk_vendor: sdkVendor,
7439            sdk_version: sdkVersion
7440          },
7441          context,
7442          environment: mpInstance._Store.SDKConfig.isDevelopmentMode ? "development" : "production",
7443          request_id: mpInstance._Helpers.generateUniqueId(),
7444          request_timestamp_ms: (/* @__PURE__ */ new Date()).getTime(),
7445          identity_changes: this.createIdentityChanges(currentUserIdentities, newUserIdentities)
7446        };
7447      },
7448      createIdentityChanges: function createIdentityChanges(previousIdentities, newIdentities) {
7449        var identityChanges = [];
7450        if (newIdentities && isObject(newIdentities) && previousIdentities && isObject(previousIdentities)) {
7451          for (var key in newIdentities) {
7452            identityChanges.push({
7453              old_value: previousIdentities[key] || null,
7454              new_value: newIdentities[key],
7455              identity_type: key
7456            });
7457          }
7458        }
7459        return identityChanges;
7460      },
7461      // takes 2 UI objects keyed by name, combines them, returns them keyed by type
7462      combineUserIdentities: function combineUserIdentities(previousUIByName, newUIByName) {
7463        var combinedUIByType = {};
7464        var combinedUIByName = extend2({}, previousUIByName, newUIByName);
7465        for (var key in combinedUIByName) {
7466          var type = Types.IdentityType.getIdentityType(key);
7467          if (type !== false && type >= 0) {
7468            combinedUIByType[Types.IdentityType.getIdentityType(key)] = combinedUIByName[key];
7469          }
7470        }
7471        return combinedUIByType;
7472      },
7473      createAliasNetworkRequest: function createAliasNetworkRequest(aliasRequest) {
7474        return {
7475          request_id: mpInstance._Helpers.generateUniqueId(),
7476          request_type: "alias",
7477          environment: mpInstance._Store.SDKConfig.isDevelopmentMode ? "development" : "production",
7478          api_key: mpInstance._Store.devToken,
7479          data: {
7480            destination_mpid: aliasRequest.destinationMpid,
7481            source_mpid: aliasRequest.sourceMpid,
7482            start_unixtime_ms: aliasRequest.startTime,
7483            end_unixtime_ms: aliasRequest.endTime,
7484            scope: aliasRequest.scope,
7485            device_application_stamp: mpInstance._Store.deviceId
7486          }
7487        };
7488      },
7489      convertAliasToNative: function convertAliasToNative(aliasRequest) {
7490        return {
7491          DestinationMpid: aliasRequest.destinationMpid,
7492          SourceMpid: aliasRequest.sourceMpid,
7493          StartUnixtimeMs: aliasRequest.startTime,
7494          EndUnixtimeMs: aliasRequest.endTime,
7495          Scope: aliasRequest.scope
7496        };
7497      },
7498      convertToNative: function convertToNative(identityApiData) {
7499        var nativeIdentityRequest = [];
7500        if (identityApiData === null || identityApiData === void 0 ? void 0 : identityApiData.userIdentities) {
7501          for (var key in identityApiData.userIdentities) {
7502            if (identityApiData.userIdentities.hasOwnProperty(key)) {
7503              nativeIdentityRequest.push({
7504                Type: Types.IdentityType.getIdentityType(key),
7505                Identity: identityApiData.userIdentities[key]
7506              });
7507            }
7508          }
7509          return {
7510            UserIdentities: nativeIdentityRequest
7511          };
7512        }
7513        return void 0;
7514      }
7515    };
7516    this.IdentityAPI = {
7517      HTTPCodes: HTTPCodes$2,
7518      /**
7519       * Initiate a logout request to the mParticle server
7520       * @method identify
7521       * @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk)
7522       * @param {Function} [callback] A callback function that is called when the identify request completes
7523       */
7524      identify: function identify(identityApiData, callback) {
7525        var mpid;
7526        var currentUser = mpInstance.Identity.getCurrentUser();
7527        var preProcessResult = mpInstance._Identity.IdentityRequest.preProcessIdentityRequest(identityApiData, callback, Identify);
7528        if (currentUser) {
7529          mpid = currentUser.getMPID();
7530        }
7531        if (preProcessResult.valid) {
7532          var identityApiRequest = mpInstance._Identity.IdentityRequest.createIdentityRequest(preProcessResult.cleanedIdentities, Constants.platform, Constants.sdkVendor, Constants.sdkVersion, mpInstance._Store.deviceId, mpInstance._Store.context, mpid);
7533          if (mpInstance._Helpers.getFeatureFlag(Constants.FeatureFlags.CacheIdentity)) {
7534            var successfullyCachedIdentity = tryCacheIdentity(identityApiRequest.known_identities, self.idCache, self.parseIdentityResponse, mpid, callback, identityApiData, Identify);
7535            if (successfullyCachedIdentity) {
7536              return;
7537            }
7538          }
7539          if (mpInstance._Helpers.canLog()) {
7540            if (mpInstance._Store.webviewBridgeEnabled) {
7541              mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Identify, JSON.stringify(mpInstance._Identity.IdentityRequest.convertToNative(identityApiData)));
7542              mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.nativeIdentityRequest, "Identify request sent to native sdk");
7543            } else {
7544              mpInstance._IdentityAPIClient.sendIdentityRequest(identityApiRequest, Identify, callback, identityApiData, self.parseIdentityResponse, mpid, identityApiRequest.known_identities);
7545            }
7546          } else {
7547            mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.loggingDisabledOrMissingAPIKey, Messages$2.InformationMessages.AbandonLogEvent);
7548            mpInstance.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent);
7549          }
7550        } else {
7551          mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.validationIssue, preProcessResult.error);
7552          mpInstance.Logger.verbose(preProcessResult);
7553        }
7554      },
7555      /**
7556       * Initiate a logout request to the mParticle server
7557       * @method logout
7558       * @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk)
7559       * @param {Function} [callback] A callback function that is called when the logout request completes
7560       */
7561      logout: function logout(identityApiData, callback) {
7562        var mpid;
7563        var currentUser = mpInstance.Identity.getCurrentUser();
7564        var preProcessResult = mpInstance._Identity.IdentityRequest.preProcessIdentityRequest(identityApiData, callback, Logout);
7565        if (currentUser) {
7566          mpid = currentUser.getMPID();
7567        }
7568        if (preProcessResult.valid) {
7569          var evt_1;
7570          var identityApiRequest = mpInstance._Identity.IdentityRequest.createIdentityRequest(preProcessResult.cleanedIdentities, Constants.platform, Constants.sdkVendor, Constants.sdkVersion, mpInstance._Store.deviceId, mpInstance._Store.context, mpid);
7571          if (mpInstance._Helpers.canLog()) {
7572            if (mpInstance._Store.webviewBridgeEnabled) {
7573              mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Logout, JSON.stringify(mpInstance._Identity.IdentityRequest.convertToNative(identityApiData)));
7574              mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.nativeIdentityRequest, "Logout request sent to native sdk");
7575            } else {
7576              mpInstance._IdentityAPIClient.sendIdentityRequest(identityApiRequest, Logout, callback, identityApiData, self.parseIdentityResponse, mpid);
7577              evt_1 = mpInstance._ServerModel.createEventObject({
7578                messageType: Types.MessageType.Profile
7579              });
7580              evt_1.ProfileMessageType = Types.ProfileMessageType.Logout;
7581              if (mpInstance._Store.activeForwarders.length) {
7582                mpInstance._Store.activeForwarders.forEach(function(forwarder) {
7583                  var kit = forwarder;
7584                  if (kit.logOut) {
7585                    kit.logOut(evt_1);
7586                  }
7587                });
7588              }
7589            }
7590          } else {
7591            mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.loggingDisabledOrMissingAPIKey, Messages$2.InformationMessages.AbandonLogEvent);
7592            mpInstance.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent);
7593          }
7594        } else {
7595          mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.validationIssue, preProcessResult.error);
7596          mpInstance.Logger.verbose(preProcessResult);
7597        }
7598      },
7599      /**
7600       * Initiate a login request to the mParticle server
7601       * @method login
7602       * @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk)
7603       * @param {Function} [callback] A callback function that is called when the login request completes
7604       */
7605      login: function login(identityApiData, callback) {
7606        var mpid;
7607        var currentUser = mpInstance.Identity.getCurrentUser();
7608        var preProcessResult = mpInstance._Identity.IdentityRequest.preProcessIdentityRequest(identityApiData, callback, Login);
7609        if (currentUser) {
7610          mpid = currentUser.getMPID();
7611        }
7612        if (preProcessResult.valid) {
7613          var identityApiRequest = mpInstance._Identity.IdentityRequest.createIdentityRequest(preProcessResult.cleanedIdentities, Constants.platform, Constants.sdkVendor, Constants.sdkVersion, mpInstance._Store.deviceId, mpInstance._Store.context, mpid);
7614          if (mpInstance._Helpers.getFeatureFlag(Constants.FeatureFlags.CacheIdentity)) {
7615            var successfullyCachedIdentity = tryCacheIdentity(identityApiRequest.known_identities, self.idCache, self.parseIdentityResponse, mpid, callback, identityApiData, Login);
7616            if (successfullyCachedIdentity) {
7617              return;
7618            }
7619          }
7620          if (mpInstance._Helpers.canLog()) {
7621            if (mpInstance._Store.webviewBridgeEnabled) {
7622              mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Login, JSON.stringify(mpInstance._Identity.IdentityRequest.convertToNative(identityApiData)));
7623              mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.nativeIdentityRequest, "Login request sent to native sdk");
7624            } else {
7625              mpInstance._IdentityAPIClient.sendIdentityRequest(identityApiRequest, Login, callback, identityApiData, self.parseIdentityResponse, mpid, identityApiRequest.known_identities);
7626            }
7627          } else {
7628            mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.loggingDisabledOrMissingAPIKey, Messages$2.InformationMessages.AbandonLogEvent);
7629            mpInstance.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent);
7630          }
7631        } else {
7632          mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.validationIssue, preProcessResult.error);
7633          mpInstance.Logger.verbose(preProcessResult);
7634        }
7635      },
7636      /**
7637       * Initiate a modify request to the mParticle server
7638       * @method modify
7639       * @param {Object} identityApiData The identityApiData object as indicated [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/README.md#1-customize-the-sdk)
7640       * @param {Function} [callback] A callback function that is called when the modify request completes
7641       */
7642      modify: function modify(identityApiData, callback) {
7643        var mpid;
7644        var currentUser = mpInstance.Identity.getCurrentUser();
7645        var preProcessResult = mpInstance._Identity.IdentityRequest.preProcessIdentityRequest(identityApiData, callback, Modify$1);
7646        if (currentUser) {
7647          mpid = currentUser.getMPID();
7648        }
7649        if (preProcessResult.valid) {
7650          var newUserIdentities = (identityApiData === null || identityApiData === void 0 ? void 0 : identityApiData.userIdentities) ? preProcessResult.cleanedIdentities.userIdentities : {};
7651          var identityApiRequest = mpInstance._Identity.IdentityRequest.createModifyIdentityRequest(currentUser ? currentUser.getUserIdentities().userIdentities : {}, newUserIdentities, Constants.platform, Constants.sdkVendor, Constants.sdkVersion, mpInstance._Store.context);
7652          if (mpInstance._Helpers.canLog()) {
7653            if (mpInstance._Store.webviewBridgeEnabled) {
7654              mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Modify, JSON.stringify(mpInstance._Identity.IdentityRequest.convertToNative(identityApiData)));
7655              mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.nativeIdentityRequest, "Modify request sent to native sdk");
7656            } else {
7657              mpInstance._IdentityAPIClient.sendIdentityRequest(identityApiRequest, Modify$1, callback, identityApiData, self.parseIdentityResponse, mpid);
7658            }
7659          } else {
7660            mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.loggingDisabledOrMissingAPIKey, Messages$2.InformationMessages.AbandonLogEvent);
7661            mpInstance.Logger.verbose(Messages$2.InformationMessages.AbandonLogEvent);
7662          }
7663        } else {
7664          mpInstance._Helpers.invokeCallback(callback, HTTPCodes$2.validationIssue, preProcessResult.error);
7665          mpInstance.Logger.verbose(preProcessResult);
7666        }
7667      },
7668      /**
7669       * Returns a user object with methods to interact with the current user
7670       * @method getCurrentUser
7671       * @return {Object} the current user object
7672       */
7673      getCurrentUser: function getCurrentUser() {
7674        var mpid;
7675        if (mpInstance._Store) {
7676          mpid = mpInstance._Store.mpid;
7677          if (mpid) {
7678            mpid = mpInstance._Store.mpid.slice();
7679            return self.mParticleUser(mpid, mpInstance._Store.isLoggedIn);
7680          } else if (mpInstance._Store.webviewBridgeEnabled) {
7681            return self.mParticleUser();
7682          } else {
7683            return null;
7684          }
7685        } else {
7686          return null;
7687        }
7688      },
7689      /**
7690       * Returns a the user object associated with the mpid parameter or 'null' if no such
7691       * user exists
7692       * @method getUser
7693       * @param {String} mpid of the desired user
7694       * @return {Object} the user for  mpid
7695       */
7696      getUser: function getUser(mpid) {
7697        var persistence = mpInstance._Persistence.getPersistence();
7698        if (persistence) {
7699          if (persistence[mpid] && !Constants.SDKv2NonMPIDCookieKeys.hasOwnProperty(mpid)) {
7700            return self.mParticleUser(mpid);
7701          } else {
7702            return null;
7703          }
7704        } else {
7705          return null;
7706        }
7707      },
7708      /**
7709       * Returns all users, including the current user and all previous users that are stored on the device.
7710       * @method getUsers
7711       * @return {Array} array of users
7712       */
7713      getUsers: function getUsers() {
7714        var persistence = mpInstance._Persistence.getPersistence();
7715        var users = [];
7716        if (persistence) {
7717          for (var key in persistence) {
7718            if (!Constants.SDKv2NonMPIDCookieKeys.hasOwnProperty(key)) {
7719              users.push(self.mParticleUser(key));
7720            }
7721          }
7722        }
7723        users.sort(function(a, b) {
7724          var aLastSeen = a.getLastSeenTime() || 0;
7725          var bLastSeen = b.getLastSeenTime() || 0;
7726          if (aLastSeen > bLastSeen) {
7727            return -1;
7728          } else {
7729            return 1;
7730          }
7731        });
7732        return users;
7733      },
7734      /**
7735       * Initiate an alias request to the mParticle server
7736       * @method aliasUsers
7737       * @param {Object} aliasRequest  object representing an AliasRequest
7738       * @param {Function} [callback] A callback function that is called when the aliasUsers request completes
7739       */
7740      aliasUsers: function aliasUsers(aliasRequest, callback) {
7741        var message;
7742        if (!aliasRequest.destinationMpid || !aliasRequest.sourceMpid) {
7743          message = Messages$2.ValidationMessages.AliasMissingMpid;
7744        }
7745        if (aliasRequest.destinationMpid === aliasRequest.sourceMpid) {
7746          message = Messages$2.ValidationMessages.AliasNonUniqueMpid;
7747        }
7748        if (!aliasRequest.startTime || !aliasRequest.endTime) {
7749          message = Messages$2.ValidationMessages.AliasMissingTime;
7750        }
7751        if (aliasRequest.startTime > aliasRequest.endTime) {
7752          message = Messages$2.ValidationMessages.AliasStartBeforeEndTime;
7753        }
7754        if (message) {
7755          mpInstance.Logger.warning(message);
7756          mpInstance._Helpers.invokeAliasCallback(callback, HTTPCodes$2.validationIssue, message);
7757          return;
7758        }
7759        if (mpInstance._Helpers.canLog()) {
7760          if (mpInstance._Store.webviewBridgeEnabled) {
7761            mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Alias, JSON.stringify(mpInstance._Identity.IdentityRequest.convertAliasToNative(aliasRequest)));
7762            mpInstance._Helpers.invokeAliasCallback(callback, HTTPCodes$2.nativeIdentityRequest, "Alias request sent to native sdk");
7763          } else {
7764            mpInstance.Logger.verbose(Messages$2.InformationMessages.StartingAliasRequest + ": " + aliasRequest.sourceMpid + " -> " + aliasRequest.destinationMpid);
7765            var aliasRequestMessage = mpInstance._Identity.IdentityRequest.createAliasNetworkRequest(aliasRequest);
7766            mpInstance._IdentityAPIClient.sendAliasRequest(aliasRequestMessage, callback);
7767          }
7768        } else {
7769          mpInstance._Helpers.invokeAliasCallback(callback, HTTPCodes$2.loggingDisabledOrMissingAPIKey, Messages$2.InformationMessages.AbandonAliasUsers);
7770          mpInstance.Logger.verbose(Messages$2.InformationMessages.AbandonAliasUsers);
7771        }
7772      },
7773      /**
7774       * Search the IDSync Workspace endpoint for a known identity.
7775       *
7776       * POSTs to mParticle's `/v1/search` endpoint and invokes `callback`
7777       * with `{ httpCode, body? }`.
7778       *
7779       * The `workspaceApiKey` is a workspace-specific API key supplied by
7780       * the caller (passed in from a kit's settings). It is intentionally
7781       * NOT read from the SDK's own workspace token, so that workspace
7782       * searches can be authorised independently of the host SDK's
7783       * workspace.
7784       *
7785       * @method search
7786       * @param {String} workspaceApiKey Workspace API key (sent as x-mp-key).
7787       * @param {Object} knownIdentities A `UserIdentities` map.
7788       * @param {Function} callback Invoked with the `IIdentitySearchResult`.
7789       */
7790      search: function search(workspaceApiKey, knownIdentities, callback) {
7791        executeSearchRequest(mpInstance, workspaceApiKey, knownIdentities, callback);
7792      },
7793      /**
7794       Create a default AliasRequest for 2 MParticleUsers. This will construct the request
7795      using the sourceUser's firstSeenTime as the startTime, and its lastSeenTime as the endTime.
7796      
7797      In the unlikely scenario that the sourceUser does not have a firstSeenTime, which will only
7798      be the case if they have not been the current user since this functionality was added, the
7799      startTime will be populated with the earliest firstSeenTime out of any stored user. Similarly,
7800      if the sourceUser does not have a lastSeenTime, the endTime will be populated with the current time
7801      
7802      There is a limit to how old the startTime can be, represented by the config field 'aliasMaxWindow', in days.
7803      If the startTime falls before the limit, it will be adjusted to the oldest allowed startTime.
7804      In rare cases, where the sourceUser's lastSeenTime also falls outside of the aliasMaxWindow limit,
7805      after applying this adjustment it will be impossible to create an aliasRequest passes the aliasUsers()
7806      validation that the startTime must be less than the endTime
7807      */
7808      createAliasRequest: function createAliasRequest(sourceUser, destinationUser, scope) {
7809        try {
7810          if (!destinationUser || !sourceUser) {
7811            mpInstance.Logger.error("'destinationUser' and 'sourceUser' must both be present");
7812            return null;
7813          }
7814          var startTime_1 = sourceUser.getFirstSeenTime();
7815          if (!startTime_1) {
7816            mpInstance.Identity.getUsers().forEach(function(user) {
7817              if (user.getFirstSeenTime() && (!startTime_1 || user.getFirstSeenTime() < startTime_1)) {
7818                startTime_1 = user.getFirstSeenTime();
7819              }
7820            });
7821          }
7822          var minFirstSeenTimeMs = (/* @__PURE__ */ new Date()).getTime() - mpInstance._Store.SDKConfig.aliasMaxWindow * 24 * 60 * 60 * 1e3;
7823          var endTime = sourceUser.getLastSeenTime() || (/* @__PURE__ */ new Date()).getTime();
7824          if (startTime_1 < minFirstSeenTimeMs) {
7825            startTime_1 = minFirstSeenTimeMs;
7826            if (endTime < startTime_1) {
7827              mpInstance.Logger.warning("Source User has not been seen in the last " + mpInstance._Store.SDKConfig.maxAliasWindow + " days, Alias Request will likely fail");
7828            }
7829          }
7830          return {
7831            destinationMpid: destinationUser.getMPID(),
7832            sourceMpid: sourceUser.getMPID(),
7833            startTime: startTime_1,
7834            endTime,
7835            scope: scope || "device"
7836          };
7837        } catch (e) {
7838          mpInstance.Logger.error("There was a problem with creating an alias request: " + e);
7839          return null;
7840        }
7841      }
7842    };
7843    this.mParticleUser = function(mpid, _isLoggedIn) {
7844      return {
7845        /**
7846         * Get user identities for current user
7847         * @method getUserIdentities
7848         * @return {Object} an object with userIdentities as its key
7849         */
7850        getUserIdentities: function getUserIdentities() {
7851          var currentUserIdentities = {};
7852          var identities = mpInstance._Store.getUserIdentities(mpid);
7853          for (var identityType in identities) {
7854            if (identities.hasOwnProperty(identityType)) {
7855              currentUserIdentities[Types.IdentityType.getIdentityName(mpInstance._Helpers.parseNumber(identityType))] = identities[identityType];
7856            }
7857          }
7858          return {
7859            userIdentities: currentUserIdentities
7860          };
7861        },
7862        /**
7863         * Get the MPID of the current user
7864         * @method getMPID
7865         * @return {String} the current user MPID as a string
7866         */
7867        getMPID: function getMPID() {
7868          return mpid;
7869        },
7870        /**
7871         * Sets a user tag
7872         * @method setUserTag
7873         * @param {String} tagName
7874         */
7875        setUserTag: function setUserTag(tagName) {
7876          if (!mpInstance._Helpers.Validators.isValidKeyValue(tagName)) {
7877            mpInstance.Logger.error(Messages$2.ErrorMessages.BadKey);
7878            return;
7879          }
7880          this.setUserAttribute(tagName, null);
7881        },
7882        /**
7883         * Removes a user tag
7884         * @method removeUserTag
7885         * @param {String} tagName
7886         */
7887        removeUserTag: function removeUserTag(tagName) {
7888          if (!mpInstance._Helpers.Validators.isValidKeyValue(tagName)) {
7889            mpInstance.Logger.error(Messages$2.ErrorMessages.BadKey);
7890            return;
7891          }
7892          this.removeUserAttribute(tagName);
7893        },
7894        /**
7895         * Sets a user attribute
7896         * @method setUserAttribute
7897         * @param {String} key
7898         * @param {String} value
7899         */
7900        // https://go.mparticle.com/work/SQDSDKS-4576
7901        // https://go.mparticle.com/work/SQDSDKS-6373
7902        setUserAttribute: function setUserAttribute(key, newValue) {
7903          mpInstance._SessionManager.resetSessionTimer();
7904          if (mpInstance._Helpers.canLog()) {
7905            if (!mpInstance._Helpers.Validators.isValidAttributeValue(newValue)) {
7906              mpInstance.Logger.error(Messages$2.ErrorMessages.BadAttribute);
7907              return;
7908            }
7909            if (!mpInstance._Helpers.Validators.isValidKeyValue(key)) {
7910              mpInstance.Logger.error(Messages$2.ErrorMessages.BadKey);
7911              return;
7912            }
7913            if (mpInstance._Store.webviewBridgeEnabled) {
7914              mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetUserAttribute, JSON.stringify({
7915                key,
7916                value: newValue
7917              }));
7918            } else {
7919              var userAttributes = this.getAllUserAttributes();
7920              var previousUserAttributeValue = void 0;
7921              var isNewAttribute = void 0;
7922              var existingProp = mpInstance._Helpers.findKeyInObject(userAttributes, key);
7923              if (existingProp) {
7924                isNewAttribute = false;
7925                previousUserAttributeValue = userAttributes[existingProp];
7926                delete userAttributes[existingProp];
7927              } else {
7928                isNewAttribute = true;
7929              }
7930              userAttributes[key] = newValue;
7931              mpInstance._Store.setUserAttributes(mpid, userAttributes);
7932              self.sendUserAttributeChangeEvent(key, newValue, previousUserAttributeValue, isNewAttribute, false, this);
7933              mpInstance._Forwarders.initForwarders(self.IdentityAPI.getCurrentUser().getUserIdentities(), mpInstance._APIClient.prepareForwardingStats);
7934              mpInstance._Forwarders.handleForwarderUserAttributes("setUserAttribute", key, newValue);
7935            }
7936          }
7937        },
7938        /**
7939         * Set multiple user attributes
7940         * @method setUserAttributes
7941         * @param {Object} user attribute object with keys of the attribute type, and value of the attribute value
7942         */
7943        // https://go.mparticle.com/work/SQDSDKS-6373
7944        setUserAttributes: function setUserAttributes(userAttributes) {
7945          mpInstance._SessionManager.resetSessionTimer();
7946          if (isObject(userAttributes)) {
7947            if (mpInstance._Helpers.canLog()) {
7948              for (var key in userAttributes) {
7949                if (userAttributes.hasOwnProperty(key)) {
7950                  this.setUserAttribute(key, userAttributes[key]);
7951                }
7952              }
7953            }
7954          } else {
7955            mpInstance.Logger.error("Must pass an object into setUserAttributes. You passed a " + _typeof(userAttributes));
7956          }
7957        },
7958        /**
7959         * Removes a specific user attribute
7960         * @method removeUserAttribute
7961         * @param {String} key
7962         */
7963        removeUserAttribute: function removeUserAttribute(key) {
7964          var cookies;
7965          var userAttributes;
7966          mpInstance._SessionManager.resetSessionTimer();
7967          if (!mpInstance._Helpers.Validators.isValidKeyValue(key)) {
7968            mpInstance.Logger.error(Messages$2.ErrorMessages.BadKey);
7969            return;
7970          }
7971          if (mpInstance._Store.webviewBridgeEnabled) {
7972            mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveUserAttribute, JSON.stringify({
7973              key,
7974              value: null
7975            }));
7976          } else {
7977            cookies = mpInstance._Persistence.getPersistence();
7978            userAttributes = this.getAllUserAttributes();
7979            var existingProp = mpInstance._Helpers.findKeyInObject(userAttributes, key);
7980            if (existingProp) {
7981              key = existingProp;
7982            }
7983            var deletedUAKeyCopy = userAttributes[key] ? userAttributes[key].toString() : null;
7984            delete userAttributes[key];
7985            if (cookies && cookies[mpid]) {
7986              cookies[mpid].ua = userAttributes;
7987              mpInstance._Persistence.savePersistence(cookies);
7988            }
7989            self.sendUserAttributeChangeEvent(key, null, deletedUAKeyCopy, false, true, this);
7990            mpInstance._Forwarders.initForwarders(self.IdentityAPI.getCurrentUser().getUserIdentities(), mpInstance._APIClient.prepareForwardingStats);
7991            mpInstance._Forwarders.handleForwarderUserAttributes("removeUserAttribute", key, null);
7992          }
7993        },
7994        /**
7995         * Sets a list of user attributes
7996         * @method setUserAttributeList
7997         * @param {String} key
7998         * @param {Array} value an array of values
7999         */
8000        // https://go.mparticle.com/work/SQDSDKS-6373
8001        setUserAttributeList: function setUserAttributeList(key, newValue) {
8002          mpInstance._SessionManager.resetSessionTimer();
8003          if (!mpInstance._Helpers.Validators.isValidKeyValue(key)) {
8004            mpInstance.Logger.error(Messages$2.ErrorMessages.BadKey);
8005            return;
8006          }
8007          if (!Array.isArray(newValue)) {
8008            mpInstance.Logger.error("The value you passed in to setUserAttributeList must be an array. You passed in a " + _typeof(newValue));
8009            return;
8010          }
8011          var arrayCopy = newValue.slice();
8012          if (mpInstance._Store.webviewBridgeEnabled) {
8013            mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetUserAttributeList, JSON.stringify({
8014              key,
8015              value: arrayCopy
8016            }));
8017          } else {
8018            var userAttributes = this.getAllUserAttributes();
8019            var previousUserAttributeValue = void 0;
8020            var isNewAttribute = void 0;
8021            var userAttributeChange = void 0;
8022            var existingProp = mpInstance._Helpers.findKeyInObject(userAttributes, key);
8023            if (existingProp) {
8024              isNewAttribute = false;
8025              previousUserAttributeValue = userAttributes[existingProp];
8026              delete userAttributes[existingProp];
8027            } else {
8028              isNewAttribute = true;
8029            }
8030            userAttributes[key] = arrayCopy;
8031            mpInstance._Store.setUserAttributes(mpid, userAttributes);
8032            if (!previousUserAttributeValue || !Array.isArray(previousUserAttributeValue)) {
8033              userAttributeChange = true;
8034            } else if (newValue.length !== previousUserAttributeValue.length) {
8035              userAttributeChange = true;
8036            } else {
8037              for (var i = 0; i < newValue.length; i++) {
8038                if (previousUserAttributeValue[i] !== newValue[i]) {
8039                  userAttributeChange = true;
8040                  break;
8041                }
8042              }
8043            }
8044            if (userAttributeChange) {
8045              self.sendUserAttributeChangeEvent(key, newValue, previousUserAttributeValue, isNewAttribute, false, this);
8046            }
8047            mpInstance._Forwarders.initForwarders(self.IdentityAPI.getCurrentUser().getUserIdentities(), mpInstance._APIClient.prepareForwardingStats);
8048            mpInstance._Forwarders.handleForwarderUserAttributes("setUserAttribute", key, arrayCopy);
8049          }
8050        },
8051        /**
8052         * Removes all user attributes
8053         * @method removeAllUserAttributes
8054         */
8055        removeAllUserAttributes: function removeAllUserAttributes() {
8056          var userAttributes;
8057          mpInstance._SessionManager.resetSessionTimer();
8058          if (mpInstance._Store.webviewBridgeEnabled) {
8059            mpInstance._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.RemoveAllUserAttributes);
8060          } else {
8061            userAttributes = this.getAllUserAttributes();
8062            mpInstance._Forwarders.initForwarders(self.IdentityAPI.getCurrentUser().getUserIdentities(), mpInstance._APIClient.prepareForwardingStats);
8063            if (userAttributes) {
8064              for (var prop in userAttributes) {
8065                if (userAttributes.hasOwnProperty(prop)) {
8066                  mpInstance._Forwarders.handleForwarderUserAttributes("removeUserAttribute", prop, null);
8067                }
8068                this.removeUserAttribute(prop);
8069              }
8070            }
8071          }
8072        },
8073        /**
8074         * Returns all user attribute keys that have values that are arrays
8075         * @method getUserAttributesLists
8076         * @return {Object} an object of only keys with array values. Example: { attr1: [1, 2, 3], attr2: ['a', 'b', 'c'] }
8077         */
8078        getUserAttributesLists: function getUserAttributesLists() {
8079          var userAttributes;
8080          var userAttributesLists = {};
8081          userAttributes = this.getAllUserAttributes();
8082          for (var key in userAttributes) {
8083            if (userAttributes.hasOwnProperty(key) && Array.isArray(userAttributes[key])) {
8084              userAttributesLists[key] = userAttributes[key].slice();
8085            }
8086          }
8087          return userAttributesLists;
8088        },
8089        /**
8090         * Returns all user attributes
8091         * @method getAllUserAttributes
8092         * @return {Object} an object of all user attributes. Example: { attr1: 'value1', attr2: ['a', 'b', 'c'] }
8093         */
8094        getAllUserAttributes: function getAllUserAttributes() {
8095          var getUserAttributes = mpInstance._Store.getUserAttributes;
8096          var userAttributesCopy = {};
8097          var userAttributes = getUserAttributes(mpid);
8098          if (userAttributes) {
8099            for (var prop in userAttributes) {
8100              if (userAttributes.hasOwnProperty(prop)) {
8101                var attrValue = userAttributes[prop];
8102                if (Array.isArray(attrValue)) {
8103                  userAttributesCopy[prop] = attrValue.slice();
8104                } else {
8105                  userAttributesCopy[prop] = attrValue;
8106                }
8107              }
8108            }
8109          }
8110          return userAttributesCopy;
8111        },
8112        /**
8113         * Returns the cart object for the current user
8114         * @method getCart
8115         * @return a cart object
8116         */
8117        getCart: function getCart() {
8118          logDeprecatedMethodUsage({
8119            methodName: "Identity.getCurrentUser().getCart()",
8120            warningMessage: "Deprecated function Identity.getCurrentUser().getCart() will be removed in future releases"
8121          }, mpInstance.Logger, mpInstance._ErrorReportingDispatcher);
8122          return self.mParticleUserCart();
8123        },
8124        /**
8125         * Returns the Consent State stored locally for this user.
8126         * @method getConsentState
8127         * @return a ConsentState object
8128         */
8129        getConsentState: function getConsentState() {
8130          return mpInstance._Store.getConsentState(mpid);
8131        },
8132        /**
8133         * Sets the Consent State stored locally for this user.
8134         * @method setConsentState
8135         * @param {Object} consent state
8136         */
8137        setConsentState: function setConsentState(state) {
8138          mpInstance._Store.setConsentState(mpid, state);
8139          mpInstance._Forwarders.initForwarders(this.getUserIdentities().userIdentities, mpInstance._APIClient.prepareForwardingStats);
8140          mpInstance._CookieSyncManager.attemptCookieSync(this.getMPID());
8141        },
8142        isLoggedIn: function isLoggedIn() {
8143          return _isLoggedIn;
8144        },
8145        getLastSeenTime: function getLastSeenTime() {
8146          return mpInstance._Persistence.getLastSeenTime(mpid);
8147        },
8148        getFirstSeenTime: function getFirstSeenTime() {
8149          return mpInstance._Persistence.getFirstSeenTime(mpid);
8150        },
8151        /**
8152         * Get user audiences
8153         * @method getuserAudiences
8154         * @param {Function} [callback] A callback function that is invoked when the user audience request completes
8155         */
8156        // https://go.mparticle.com/work/SQDSDKS-6436
8157        getUserAudiences: function getUserAudiences(callback) {
8158          if (!mpInstance._Helpers.getFeatureFlag(FeatureFlags$1.AudienceAPI)) {
8159            mpInstance.Logger.error(ErrorMessages.AudienceAPINotEnabled);
8160            return;
8161          }
8162          if (self.audienceManager === null) {
8163            self.audienceManager = new AudienceManager(mpInstance._Store.SDKConfig.userAudienceUrl, mpInstance._Store.devToken, mpInstance.Logger);
8164          }
8165          self.audienceManager.sendGetUserAudienceRequest(mpid, callback);
8166        }
8167      };
8168    };
8169    this.mParticleUserCart = function() {
8170      return {
8171        /**
8172         * Adds a cart product to the user cart
8173         * @method add
8174         * @deprecated
8175         */
8176        add: function add() {
8177          logDeprecatedMethodUsage({
8178            methodName: "Identity.getCurrentUser().getCart().add()",
8179            warningMessage: generateDeprecationMessage("Identity.getCurrentUser().getCart().add()", true, "eCommerce.logProductAction()", "https://docs.mparticle.com/developers/sdk/web/commerce-tracking")
8180          }, mpInstance.Logger, mpInstance._ErrorReportingDispatcher);
8181        },
8182        /**
8183         * Removes a cart product from the current user cart
8184         * @method remove
8185         * @deprecated
8186         */
8187        remove: function remove() {
8188          logDeprecatedMethodUsage({
8189            methodName: "Identity.getCurrentUser().getCart().remove()",
8190            warningMessage: generateDeprecationMessage("Identity.getCurrentUser().getCart().remove()", true, "eCommerce.logProductAction()", "https://docs.mparticle.com/developers/sdk/web/commerce-tracking")
8191          }, mpInstance.Logger, mpInstance._ErrorReportingDispatcher);
8192        },
8193        /**
8194         * Clears the user's cart
8195         * @method clear
8196         * @deprecated
8197         */
8198        clear: function clear() {
8199          logDeprecatedMethodUsage({
8200            methodName: "Identity.getCurrentUser().getCart().clear()",
8201            warningMessage: generateDeprecationMessage("Identity.getCurrentUser().getCart().clear()", true, "", "https://docs.mparticle.com/developers/sdk/web/commerce-tracking")
8202          }, mpInstance.Logger, mpInstance._ErrorReportingDispatcher);
8203        },
8204        /**
8205         * Returns all cart products
8206         * @method getCartProducts
8207         * @return {Array} array of cart products
8208         * @deprecated
8209         */
8210        getCartProducts: function getCartProducts() {
8211          logDeprecatedMethodUsage({
8212            methodName: "Identity.getCurrentUser().getCart().getCartProducts()",
8213            warningMessage: generateDeprecationMessage("Identity.getCurrentUser().getCart().getCartProducts()", true, "eCommerce.logProductAction()", "https://docs.mparticle.com/developers/sdk/web/commerce-tracking")
8214          }, mpInstance.Logger, mpInstance._ErrorReportingDispatcher);
8215          return [];
8216        }
8217      };
8218    };
8219    this.parseIdentityResponse = function(identityResponse, previousMPID, callback, identityApiData, method, knownIdentities, parsingCachedResponse) {
8220      var _a3, _b2, _c;
8221      var prevUser = mpInstance.Identity.getUser(previousMPID);
8222      var prevUserMPID = prevUser ? prevUser.getMPID() : null;
8223      var previousUIByName = prevUser ? prevUser.getUserIdentities().userIdentities : {};
8224      var mpidIsNotInCookies;
8225      var identityApiResult;
8226      var newUser;
8227      var newIdentitiesByType = {};
8228      mpInstance._Store.identityCallInFlight = false;
8229      try {
8230        mpInstance.Logger.verbose('Parsing "' + method + '" identity response from server');
8231        identityApiResult = (_a3 = identityResponse.responseText) !== null && _a3 !== void 0 ? _a3 : null;
8232        mpInstance._Store.isLoggedIn = (identityApiResult === null || identityApiResult === void 0 ? void 0 : identityApiResult.is_logged_in) || false;
8233        if (hasMPIDChanged(prevUser, identityApiResult)) {
8234          mpInstance._Store.mpid = identityApiResult.mpid;
8235          if (prevUser) {
8236            mpInstance._Persistence.setLastSeenTime(previousMPID);
8237          }
8238          mpidIsNotInCookies = !mpInstance._Persistence.getFirstSeenTime(identityApiResult.mpid);
8239          mpInstance._Persistence.setFirstSeenTime(identityApiResult.mpid);
8240        }
8241        if (identityResponse.status === HTTP_OK) {
8242          if (getFeatureFlag(CacheIdentity)) {
8243            cacheOrClearIdCache(method, knownIdentities, self.idCache, identityResponse, parsingCachedResponse);
8244          }
8245          var incomingUser = self.IdentityAPI.getUser(identityApiResult.mpid);
8246          var incomingUIByName = incomingUser ? incomingUser.getUserIdentities().userIdentities : {};
8247          if (method === Modify$1) {
8248            newIdentitiesByType = mpInstance._Identity.IdentityRequest.combineUserIdentities(previousUIByName, identityApiData.userIdentities);
8249            mpInstance._Store.setUserIdentities(previousMPID, newIdentitiesByType);
8250          } else {
8251            if (method === Identify && prevUser && identityApiResult.mpid === prevUserMPID) {
8252              mpInstance._Persistence.setFirstSeenTime(identityApiResult.mpid);
8253            }
8254            mpInstance._Store.addMpidToSessionHistory(identityApiResult.mpid, previousMPID);
8255            mpInstance._CookieSyncManager.attemptCookieSync(identityApiResult.mpid, mpidIsNotInCookies);
8256            mpInstance._Persistence.swapCurrentUser(previousMPID, identityApiResult.mpid, mpInstance._Store.currentSessionMPIDs);
8257            if (identityApiData && !isEmpty(identityApiData.userIdentities)) {
8258              newIdentitiesByType = self.IdentityRequest.combineUserIdentities(incomingUIByName, identityApiData.userIdentities);
8259            }
8260            mpInstance._Store.setUserIdentities(identityApiResult.mpid, newIdentitiesByType);
8261            mpInstance._Persistence.update();
8262            mpInstance._Store.syncPersistenceData();
8263            mpInstance._Persistence.findPrevCookiesBasedOnUI(identityApiData);
8264            mpInstance._Store.context = identityApiResult.context || mpInstance._Store.context;
8265          }
8266          newUser = mpInstance.Identity.getCurrentUser();
8267          tryOnUserAlias(prevUser, newUser, identityApiData, mpInstance.Logger, mpInstance._ErrorReportingDispatcher);
8268          var persistence = mpInstance._Persistence.getPersistence();
8269          if (newUser) {
8270            mpInstance._Persistence.storeDataInMemory(persistence, newUser.getMPID());
8271            self.reinitForwardersOnUserChange(prevUser, newUser);
8272            self.setForwarderCallbacks(newUser, method);
8273          }
8274          var newIdentitiesByName = IdentityType.getNewIdentitiesByName(newIdentitiesByType);
8275          var uiByName = method === Modify$1 ? previousUIByName : incomingUIByName;
8276          (_b2 = mpInstance._CookieConsentManager) === null || _b2 === void 0 ? void 0 : _b2.syncNoTargetingAttribute(newUser);
8277          self.sendUserIdentityChangeEvent(newIdentitiesByName, method, identityApiResult.mpid, uiByName);
8278        }
8279        if (callback) {
8280          var callbackCode = identityResponse.status === 0 ? HTTPCodes$2.noHttpCoverage : identityResponse.status;
8281          mpInstance._Helpers.invokeCallback(callback, callbackCode, identityApiResult || null, newUser);
8282        } else if (identityApiResult && !isEmpty(identityApiResult.errors)) {
8283          mpInstance.Logger.error("Received HTTP response code of " + identityResponse.status + " - " + identityApiResult.errors[0].message);
8284        }
8285        mpInstance.Logger.verbose("Successfully parsed Identity Response");
8286        (_c = mpInstance._APIClient) === null || _c === void 0 ? void 0 : _c.processQueuedEvents();
8287      } catch (e) {
8288        if (callback) {
8289          mpInstance._Helpers.invokeCallback(callback, identityResponse.status, identityApiResult || null);
8290        }
8291        mpInstance.Logger.error("Error parsing JSON response from Identity server: " + e);
8292      }
8293      mpInstance._Store.isInitialized = true;
8294      mpInstance._RoktManager.onIdentityComplete();
8295      mpInstance._preInit.readyQueue = processReadyQueue(mpInstance._preInit.readyQueue, mpInstance.Logger);
8296    };
8297    this.sendUserIdentityChangeEvent = function(newUserIdentities, method, mpid, prevUserIdentities) {
8298      var _a3;
8299      if (!mpid) {
8300        if (method !== Modify$1) {
8301          return;
8302        }
8303      }
8304      var currentUserInMemory = this.IdentityAPI.getUser(mpid);
8305      for (var identityType in newUserIdentities) {
8306        if (prevUserIdentities[identityType] !== newUserIdentities[identityType]) {
8307          var isNewUserIdentityType = !prevUserIdentities[identityType];
8308          var userIdentityChangeEvent = self.createUserIdentityChange(identityType, newUserIdentities[identityType], prevUserIdentities[identityType], isNewUserIdentityType, currentUserInMemory);
8309          (_a3 = mpInstance._APIClient) === null || _a3 === void 0 ? void 0 : _a3.sendEventToServer(userIdentityChangeEvent);
8310        }
8311      }
8312    };
8313    this.createUserIdentityChange = function(identityType, newIdentity, oldIdentity, isIdentityTypeNewToBatch, userInMemory) {
8314      var userIdentityChangeEvent;
8315      userIdentityChangeEvent = mpInstance._ServerModel.createEventObject({
8316        messageType: Types.MessageType.UserIdentityChange,
8317        userIdentityChanges: {
8318          New: {
8319            IdentityType: identityType,
8320            Identity: newIdentity,
8321            CreatedThisBatch: isIdentityTypeNewToBatch
8322          },
8323          Old: {
8324            IdentityType: identityType,
8325            Identity: oldIdentity,
8326            CreatedThisBatch: false
8327          }
8328        },
8329        userInMemory
8330      });
8331      return userIdentityChangeEvent;
8332    };
8333    this.sendUserAttributeChangeEvent = function(attributeKey, newUserAttributeValue, previousUserAttributeValue, isNewAttribute, deleted, user) {
8334      var _a3;
8335      var userAttributeChangeEvent = self.createUserAttributeChange(attributeKey, newUserAttributeValue, previousUserAttributeValue, isNewAttribute, deleted, user);
8336      if (userAttributeChangeEvent) {
8337        (_a3 = mpInstance._APIClient) === null || _a3 === void 0 ? void 0 : _a3.sendEventToServer(userAttributeChangeEvent);
8338      }
8339    };
8340    this.createUserAttributeChange = function(key, newValue, previousUserAttributeValue, isNewAttribute, deleted, user) {
8341      if (typeof previousUserAttributeValue === "undefined") {
8342        previousUserAttributeValue = null;
8343      }
8344      var userAttributeChangeEvent;
8345      if (newValue !== previousUserAttributeValue) {
8346        userAttributeChangeEvent = mpInstance._ServerModel.createEventObject({
8347          messageType: Types.MessageType.UserAttributeChange,
8348          userAttributeChanges: {
8349            UserAttributeName: key,
8350            New: newValue,
8351            Old: previousUserAttributeValue,
8352            Deleted: deleted,
8353            IsNewAttribute: isNewAttribute
8354          }
8355        }, user);
8356      }
8357      return userAttributeChangeEvent;
8358    };
8359    this.reinitForwardersOnUserChange = function(prevUser, newUser) {
8360      var _a3;
8361      if (hasMPIDAndUserLoginChanged(prevUser, newUser)) {
8362        (_a3 = mpInstance._Forwarders) === null || _a3 === void 0 ? void 0 : _a3.initForwarders(newUser.getUserIdentities().userIdentities, mpInstance._APIClient.prepareForwardingStats);
8363      }
8364    };
8365    this.setForwarderCallbacks = function(user, method) {
8366      var _a3, _b2, _c;
8367      (_a3 = mpInstance._Forwarders) === null || _a3 === void 0 ? void 0 : _a3.setForwarder
8367UserIdentities(user.getUserIdentities().userIdentities);
8368      (_b2 = mpInstance._Forwarders) === null || _b2 === void 0 ? void 0 : _b2.setForwarderOnIdentityComplete(user, method);
8369      (_c = mpInstance._Forwarders) === null || _c === void 0 ? void 0 : _c.setForwarderOnUserIdentified(user);
8370    };
8371  }
8372  function tryOnUserAlias(previousUser, newUser, identityApiData, logger, errorReporter) {
8373    if (identityApiData && identityApiData.onUserAlias && isFunction(identityApiData.onUserAlias)) {
8374      try {
8375        logDeprecatedMethodUsage({
8376          methodName: "onUserAlias",
8377          warningMessage: generateDeprecationMessage("onUserAlias")
8378        }, logger, errorReporter);
8379        identityApiData.onUserAlias(previousUser, newUser);
8380      } catch (e) {
8381        logger.error("There was an error with your onUserAlias function - " + e);
8382      }
8383    }
8384  }
8385  var CCPAPurpose = Constants.CCPAPurpose;
8386  function Consent(mpInstance) {
8387    var self = this;
8388    this.isEnabledForUserConsent = function(consentRules, user) {
8389      if (!consentRules || !consentRules.values || !consentRules.values.length) {
8390        return true;
8391      }
8392      if (!user) {
8393        return false;
8394      }
8395      var purposeHashes = {};
8396      var consentState = user.getConsentState();
8397      var purposeHash;
8398      if (consentState) {
8399        var GDPRConsentHashPrefix = "1";
8400        var CCPAHashPrefix = "2";
8401        var gdprConsentState = consentState.getGDPRConsentState();
8402        if (gdprConsentState) {
8403          for (var purpose in gdprConsentState) {
8404            if (gdprConsentState.hasOwnProperty(purpose)) {
8405              purposeHash = KitFilterHelper.hashConsentPurposeConditionalForwarding(GDPRConsentHashPrefix, purpose);
8406              purposeHashes[purposeHash] = gdprConsentState[purpose].Consented;
8407            }
8408          }
8409        }
8410        var CCPAConsentState = consentState.getCCPAConsentState();
8411        if (CCPAConsentState) {
8412          purposeHash = KitFilterHelper.hashConsentPurposeConditionalForwarding(CCPAHashPrefix, CCPAPurpose);
8413          purposeHashes[purposeHash] = CCPAConsentState.Consented;
8414        }
8415      }
8416      var isMatch = consentRules.values.some(function(consentRule) {
8417        var consentPurposeHash = consentRule.consentPurpose;
8418        var hasConsented = consentRule.hasConsented;
8419        if (purposeHashes.hasOwnProperty(consentPurposeHash)) {
8420          return purposeHashes[consentPurposeHash] === hasConsented;
8421        }
8422        return false;
8423      });
8424      return consentRules.includeOnMatch === isMatch;
8425    };
8426    this.createPrivacyConsent = function(consented, timestamp, consentDocument, location2, hardwareId) {
8427      if (typeof consented !== "boolean") {
8428        mpInstance.Logger.error("Consented boolean is required when constructing a Consent object.");
8429        return null;
8430      }
8431      if (timestamp && isNaN(timestamp)) {
8432        mpInstance.Logger.error("Timestamp must be a valid number when constructing a Consent object.");
8433        return null;
8434      }
8435      if (consentDocument && typeof consentDocument !== "string") {
8436        mpInstance.Logger.error("Document must be a valid string when constructing a Consent object.");
8437        return null;
8438      }
8439      if (location2 && typeof location2 !== "string") {
8440        mpInstance.Logger.error("Location must be a valid string when constructing a Consent object.");
8441        return null;
8442      }
8443      if (hardwareId && typeof hardwareId !== "string") {
8444        mpInstance.Logger.error("Hardware ID must be a valid string when constructing a Consent object.");
8445        return null;
8446      }
8447      return {
8448        Consented: consented,
8449        Timestamp: timestamp || Date.now(),
8450        ConsentDocument: consentDocument,
8451        Location: location2,
8452        HardwareId: hardwareId
8453      };
8454    };
8455    this.ConsentSerialization = {
8456      toMinifiedJsonObject: function toMinifiedJsonObject(state) {
8457        var _a2;
8458        var jsonObject = {};
8459        if (state) {
8460          var gdprConsentState = state.getGDPRConsentState();
8461          if (gdprConsentState) {
8462            jsonObject.gdpr = {};
8463            for (var purpose in gdprConsentState) {
8464              if (gdprConsentState.hasOwnProperty(purpose)) {
8465                var gdprConsent = gdprConsentState[purpose];
8466                jsonObject.gdpr[purpose] = {};
8467                if (typeof gdprConsent.Consented === "boolean") {
8468                  jsonObject.gdpr[purpose].c = gdprConsent.Consented;
8469                }
8470                if (typeof gdprConsent.Timestamp === "number") {
8471                  jsonObject.gdpr[purpose].ts = gdprConsent.Timestamp;
8472                }
8473                if (typeof gdprConsent.ConsentDocument === "string") {
8474                  jsonObject.gdpr[purpose].d = gdprConsent.ConsentDocument;
8475                }
8476                if (typeof gdprConsent.Location === "string") {
8477                  jsonObject.gdpr[purpose].l = gdprConsent.Location;
8478                }
8479                if (typeof gdprConsent.HardwareId === "string") {
8480                  jsonObject.gdpr[purpose].h = gdprConsent.HardwareId;
8481                }
8482              }
8483            }
8484          }
8485          var ccpaConsentState = state.getCCPAConsentState();
8486          if (ccpaConsentState) {
8487            jsonObject.ccpa = (_a2 = {}, _a2[CCPAPurpose] = {}, _a2);
8488            if (typeof ccpaConsentState.Consented === "boolean") {
8489              jsonObject.ccpa[CCPAPurpose].c = ccpaConsentState.Consented;
8490            }
8491            if (typeof ccpaConsentState.Timestamp === "number") {
8492              jsonObject.ccpa[CCPAPurpose].ts = ccpaConsentState.Timestamp;
8493            }
8494            if (typeof ccpaConsentState.ConsentDocument === "string") {
8495              jsonObject.ccpa[CCPAPurpose].d = ccpaConsentState.ConsentDocument;
8496            }
8497            if (typeof ccpaConsentState.Location === "string") {
8498              jsonObject.ccpa[CCPAPurpose].l = ccpaConsentState.Location;
8499            }
8500            if (typeof ccpaConsentState.HardwareId === "string") {
8501              jsonObject.ccpa[CCPAPurpose].h = ccpaConsentState.HardwareId;
8502            }
8503          }
8504        }
8505        return jsonObject;
8506      },
8507      fromMinifiedJsonObject: function fromMinifiedJsonObject(json) {
8508        var state = self.createConsentState();
8509        if (json.gdpr) {
8510          for (var purpose in json.gdpr) {
8511            if (json.gdpr.hasOwnProperty(purpose)) {
8512              var gdprConsent = self.createPrivacyConsent(json.gdpr[purpose].c, json.gdpr[purpose].ts, json.gdpr[purpose].d, json.gdpr[purpose].l, json.gdpr[purpose].h);
8513              state.addGDPRConsentState(purpose, gdprConsent);
8514            }
8515          }
8516        }
8517        if (json.ccpa) {
8518          if (json.ccpa.hasOwnProperty(CCPAPurpose)) {
8519            var ccpaConsent = self.createPrivacyConsent(json.ccpa[CCPAPurpose].c, json.ccpa[CCPAPurpose].ts, json.ccpa[CCPAPurpose].d, json.ccpa[CCPAPurpose].l, json.ccpa[CCPAPurpose].h);
8520            state.setCCPAConsentState(ccpaConsent);
8521          }
8522        }
8523        return state;
8524      }
8525    };
8526    this.createConsentState = function(consentState) {
8527      var gdpr = {};
8528      var ccpa = {};
8529      if (consentState) {
8530        var consentStateCopy = self.createConsentState();
8531        consentStateCopy.setGDPRConsentState(consentState.getGDPRConsentState());
8532        consentStateCopy.setCCPAConsentState(consentState.getCCPA
8532ConsentState());
8533        return consentStateCopy;
8534      }
8535      function canonicalizeForDeduplication(purpose) {
8536        if (typeof purpose !== "string") {
8537          return null;
8538        }
8539        var trimmedPurpose = purpose.trim();
8540        if (!trimmedPurpose.length) {
8541          return null;
8542        }
8543        return trimmedPurpose.toLowerCase();
8544      }
8545      function addGDPRConsentState(purpose, gdprConsent) {
8546        var normalizedPurpose = canonicalizeForDeduplication(purpose);
8547        if (!normalizedPurpose) {
8548          mpInstance.Logger.error("Purpose must be a string.");
8549          return this;
8550        }
8551        if (!isObject(gdprConsent)) {
8552          mpInstance.Logger.error("Invoked with a bad or empty consent object.");
8553          return this;
8554        }
8555        var gdprConsentCopy = self.createPrivacyConsent(gdprConsent.Consented, gdprConsent.Timestamp, gdprConsent.ConsentDocument, gdprConsent.Location, gdprConsent.HardwareId);
8556        if (gdprConsentCopy) {
8557          gdpr[normalizedPurpose] = gdprConsentCopy;
8558        }
8559        return this;
8560      }
8561      function setGDPRConsentState(gdprConsentState) {
8562        if (!gdprConsentState) {
8563          gdpr = {};
8564        } else if (isObject(gdprConsentState)) {
8565          gdpr = {};
8566          for (var purpose in gdprConsentState) {
8567            if (gdprConsentState.hasOwnProperty(purpose)) {
8568              this.addGDPRConsentState(purpose, gdprConsentState[purpose]);
8569            }
8570          }
8571        }
8572        return this;
8573      }
8574      function removeGDPRConsentState(purpose) {
8575        var normalizedPurpose = canonicalizeForDeduplication(purpose);
8576        if (!normalizedPurpose) {
8577          return this;
8578        }
8579        delete gdpr[normalizedPurpose];
8580        return this;
8581      }
8582      function getGDPRConsentState() {
8583        return Object.assign({}, gdpr);
8584      }
8585      function setCCPAConsentState(ccpaConsent) {
8586        if (!isObject(ccpaConsent)) {
8587          mpInstance.Logger.error("Invoked with a bad or empty CCPA consent object.");
8588          return this;
8589        }
8590        var ccpaConsentCopy = self.createPrivacyConsent(ccpaConsent.Consented, ccpaConsent.Timestamp, ccpaConsent.ConsentDocument, ccpaConsent.Location, ccpaConsent.HardwareId);
8591        if (ccpaConsentCopy) {
8592          ccpa[CCPAPurpose] = ccpaConsentCopy;
8593        }
8594        return this;
8595      }
8596      function getCCPAConsentState() {
8597        return ccpa[CCPAPurpose];
8598      }
8599      function removeCCPAConsentState() {
8600        delete ccpa[CCPAPurpose];
8601        return this;
8602      }
8603      function removeCCPAState() {
8604        logDeprecatedMethodUsage({
8605          methodName: "Consent.removeCCPAState",
8606          warningMessage: "removeCCPAState is deprecated and will be removed in a future release; use removeCCPAConsentState instead"
8607        }, mpInstance.Logger, mpInstance._ErrorReportingDispatcher);
8608        return removeCCPAConsentState();
8609      }
8610      return {
8611        setGDPRConsentState,
8612        addGDPRConsentState,
8613        setCCPAConsentState,
8614        getCCPAConsentState,
8615        getGDPRConsentState,
8616        removeGDPRConsentState,
8617        removeCCPAState,
8618        removeCCPAConsentState
8619      };
8620    };
8621  }
8622  var DataPlanMatchType = {
8623    ScreenView: "screen_view",
8624    CustomEvent: "custom_event",
8625    Commerce: "commerce",
8626    UserAttributes: "user_attributes",
8627    UserIdentities: "user_identities",
8628    ProductAction: "product_action",
8629    PromotionAction: "promotion_action",
8630    ProductImpression: "product_impression"
8631  };
8632  var KitBlocker = (
8633    /** @class */
8634    (function() {
8635      function KitBlocker2(dataPlan, mpInstance) {
8636        var _this = this;
8637        var _a2, _b2, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
8638        this.dataPlanMatchLookups = {};
8639        this.blockEvents = false;
8640        this.blockEventAttributes = false;
8641        this.blockUserAttributes = false;
8642        this.blockUserIdentities = false;
8643        this.kitBlockingEnabled = false;
8644        if (dataPlan && !dataPlan.document) {
8645          this.kitBlockingEnabled = false;
8646          return;
8647        }
8648        this.kitBlockingEnabled = true;
8649        this.mpInstance = mpInstance;
8650        this.blockEvents = (_c = (_b2 = (_a2 = dataPlan === null || dataPlan === void 0 ? void 0 : dataPlan.document) === null || _a2 === void 0 ? void 0 : _a2.dtpn) === null || _b2 === void 0 ? void 0 : _b2.blok) === null || _c === void 0 ? void 0 : _c.ev;
8651        this.blockEventAttributes = (_f = (_e = (_d = dataPlan === null || dataPlan === void 0 ? void 0 : dataPlan.document) === null || _d === void 0 ? void 0 : _d.dtpn) === null || _e === void 0 ? void 0 : _e.blok) === null || _f === void 0 ? void 0 : _f.ea;
8652        this.blockUserAttributes = (_j = (_h = (_g = dataPlan === null || dataPlan === void 0 ? void 0 : dataPlan.document) === null || _g === void 0 ? void 0 : _g.dtpn) === null || _h === void 0 ? void 0 : _h.blok) === null || _j === void 0 ? void 0 : _j.ua;
8653        this.blockUserIdentities = (_m = (_l = (_k = dataPlan === null || dataPlan === void 0 ? void 0 : dataPlan.document) === null || _k === void 0 ? void 0 : _k.dtpn) === null || _l === void 0 ? void 0 : _l.blok) === null || _m === void 0 ? void 0 : _m.id;
8654        var versionDocument = (_q = (_p = (_o = dataPlan === null || dataPlan === void 0 ? void 0 : dataPlan.document) === null || _o === void 0 ? void 0 : _o.dtpn) === null || _p === void 0 ? void 0 : _p.vers) === null || _q === void 0 ? void 0 : _q.version_document;
8655        var dataPoints = versionDocument === null || versionDocument === void 0 ? void 0 : versionDocument.data_points;
8656        if (versionDocument) {
8657          try {
8658            if ((dataPoints === null || dataPoints === void 0 ? void 0 : dataPoints.length) > 0) {
8659              dataPoints.forEach(function(point) {
8660                return _this.addToMatchLookups(point);
8661              });
8662            }
8663          } catch (e) {
8664            this.mpInstance.Logger.error("There was an issue with the data plan: " + e);
8665          }
8666        }
8667      }
8668      KitBlocker2.prototype.addToMatchLookups = function(point) {
8669        var _a2, _b2, _c;
8670        if (!point.match || !point.validator) {
8671          this.mpInstance.Logger.warning("Data Plan Point is not valid' + ".concat(point));
8672          return;
8673        }
8674        var matchKey = this.generateMatchKey(point.match);
8675        var properties = this.getPlannedProperties(point.match.type, point.validator);
8676        this.dataPlanMatchLookups[matchKey] = properties;
8677        if (((_a2 = point === null || point === void 0 ? void 0 : point.match) === null || _a2 === void 0 ? void 0 : _a2.type) === DataPlanMatchType.ProductImpression || ((_b2 = point === null || point === void 0 ? void 0 : point.match) === null || _b2 === void 0 ? void 0 : _b2.type) === DataPlanMatchType.ProductAction || ((_c = point === null || point === void 0 ? void 0 : point.match) === null || _c === void 0 ? void 0 : _c.type) === DataPlanMatchType.PromotionAction) {
8678          matchKey = this.generateProductAttributeMatchKey(point.match);
8679          properties = this.getProductProperties(point.match.type, point.validator);
8680          this.dataPlanMatchLookups[matchKey] = properties;
8681        }
8682      };
8683      KitBlocker2.prototype.generateMatchKey = function(match) {
8684        var criteria = match.criteria || "";
8685        switch (match.type) {
8686          case DataPlanMatchType.CustomEvent:
8687            var customEventCriteria = criteria;
8688            return [DataPlanMatchType.CustomEvent, customEventCriteria.custom_event_type, customEventCriteria.event_name].join(":");
8689          case DataPlanMatchType.ScreenView:
8690            var screenViewCriteria = criteria;
8691            return [DataPlanMatchType.ScreenView, "", screenViewCriteria.screen_name].join(":");
8692          case DataPlanMatchType.ProductAction:
8693            var productActionMatch = criteria;
8694            return [match.type, productActionMatch.action].join(":");
8695          case DataPlanMatchType.PromotionAction:
8696            var promoActionMatch = criteria;
8697            return [match.type, promoActionMatch.action].join(":");
8698          case DataPlanMatchType.ProductImpression:
8699            var productImpressionActionMatch = criteria;
8700            return [match.type, productImpressionActionMatch.action].join(":");
8701          case DataPlanMatchType.UserIdentities:
8702          case DataPlanMatchType.UserAttributes:
8703            return [match.type].join(":");
8704          default:
8705            return null;
8706        }
8707      };
8708      KitBlocker2.prototype.generateProductAttributeMatchKey = function(match) {
8709        var criteria = match.criteria || "";
8710        switch (match.type) {
8711          case DataPlanMatchType.ProductAction:
8712            var productActionMatch = criteria;
8713            return [match.type, productActionMatch.action, "ProductAttributes"].join(":");
8714          case DataPlanMatchType.PromotionAction:
8715            var promoActionMatch = criteria;
8716            return [match.type, promoActionMatch.action, "ProductAttributes"].join(":");
8717          case DataPlanMatchType.ProductImpression:
8718            return [match.type, "ProductAttributes"].join(":");
8719          default:
8720            return null;
8721        }
8722      };
8723      KitBlocker2.prototype.getPlannedProperties = function(type, validator) {
8724        var _a2, _b2, _c, _d, _e, _f, _g, _h;
8725        var customAttributes;
8726        var userAdditionalProperties;
8727        switch (type) {
8728          case DataPlanMatchType.CustomEvent:
8729          case DataPlanMatchType.ScreenView:
8730          case DataPlanMatchType.ProductAction:
8731          case DataPlanMatchType.PromotionAction:
8732          case DataPlanMatchType.ProductImpression:
8733            customAttributes = (_d = (_c = (_b2 = (_a2 = validator === null || validator === void 0 ? void 0 : validator.definition) === null || _a2 === void 0 ? void 0 : _a2.properties) === null || _b2 === void 0 ? void 0 : _b2.data) === null || _c === void 0 ? void 0 : _c.properties) === null || _d === void 0 ? void 0 : _d.custom_attributes;
8734            if (customAttributes) {
8735              if (customAttributes.additionalProperties === true || customAttributes.additionalProperties === void 0) {
8736                return true;
8737              } else {
8738                var properties = {};
8739                for (var _i = 0, _j = Object.keys(customAttributes.properties); _i < _j.length; _i++) {
8740                  var property = _j[_i];
8741                  properties[property] = true;
8742                }
8743                return properties;
8744              }
8745            } else {
8746              if (((_g = (_f = (_e = validator === null || validator === void 0 ? void 0 : validator.definition) === null || _e === void 0 ? void 0 : _e.properties) === null || _f === void 0 ? void 0 : _f.data) === null || _g === void 0 ? void 0 : _g.additionalProperties) === false) {
8747                return {};
8748              } else {
8749                return true;
8750              }
8751            }
8752          case DataPlanMatchType.UserAttributes:
8753          case DataPlanMatchType.UserIdentities:
8754            userAdditionalProperties = (_h = validator === null || validator === void 0 ? void 0 : validator.definition) === null || _h === void 0 ? void 0 : _h.additionalProperties;
8755            if (userAdditionalProperties === true || userAdditionalProperties === void 0) {
8756              return true;
8757            } else {
8758              var properties = {};
8759              var userProperties = validator.definition.properties;
8760              for (var _k = 0, _l = Object.keys(userProperties); _k < _l.length; _k++) {
8761                var property = _l[_k];
8762                properties[property] = true;
8763              }
8764              return properties;
8765            }
8766          default:
8767            return null;
8768        }
8769      };
8770      KitBlocker2.prototype.getProductProperties = function(type, validator) {
8771        var _a2, _b2, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u;
8772        var productCustomAttributes;
8773        switch (type) {
8774          case DataPlanMatchType.ProductImpression:
8775            productCustomAttributes = (_k = (_j = (_h = (_g = (_f = (_e = (_d = (_c = (_b2 = (_a2 = validator === null || validator === void 0 ? void 0 : validator.definition) === null || _a2 === void 0 ? void 0 : _a2.properties) === null || _b2 === void 0 ? void 0 : _b2.data) === null || _c === void 0 ? void 0 : _c.properties) === null || _d === void 0 ? void 0 : _d.product_impressions) === null || _e === void 0 ? void 0 : _e.items) === null || _f === void 0 ? void 0 : _f.properties) === null || _g === void 0 ? void 0 : _g.products) === null || _h === void 0 ? void 0 : _h.items) === null || _j === void 0 ? void 0 : _j.properties) === null || _k === void 0 ? void 0 : _k.custom_attributes;
8776            if ((productCustomAttributes === null || productCustomAttributes === void 0 ? void 0 : productCustomAttributes.additionalProperties) === false) {
8777              var properties = {};
8778              for (var _i = 0, _v = Object.keys(productCustomAttributes === null || productCustomAttributes === void 0 ? void 0 : productCustomAttributes.properties); _i < _v.length; _i++) {
8779                var property = _v[_i];
8780                properties[property] = true;
8781              }
8782              return properties;
8783            }
8784            return true;
8785          case DataPlanMatchType.ProductAction:
8786          case DataPlanMatchType.PromotionAction:
8787            productCustomAttributes = (_u = (_t = (_s = (_r = (_q = (_p = (_o = (_m = (_l = validator === null || validator === void 0 ? void 0 : validator.definition) === null || _l === void 0 ? void 0 : _l.properties) === null || _m === void 0 ? void 0 : _m.data) === null || _o === void 0 ? void 0 : _o.properties) === null || _p === void 0 ? void 0 : _p.product_action) === null || _q === void 0 ? void 0 : _q.properties) === null || _r === void 0 ? void 0 : _r.products) === null || _s === void 0 ? void 0 : _s.items) === null || _t === void 0 ? void 0 : _t.properties) === null || _u === void 0 ? void 0 : _u.custom_attributes;
8788            if (productCustomAttributes) {
8789              if (productCustomAttributes.additionalProperties === false) {
8790                var properties = {};
8791                for (var _w = 0, _x = Object.keys(productCustomAttributes === null || productCustomAttributes === void 0 ? void 0 : productCustomAttributes.properties); _w < _x.length; _w++) {
8792                  var property = _x[_w];
8793                  properties[property] = true;
8794                }
8795                return properties;
8796              }
8797            }
8798            return true;
8799          default:
8800            return null;
8801        }
8802      };
8803      KitBlocker2.prototype.getMatchKey = function(eventToMatch) {
8804        switch (eventToMatch.event_type) {
8805          case dist.EventTypeEnum.screenView:
8806            var screenViewEvent = eventToMatch;
8807            if (screenViewEvent.data) {
8808              return ["screen_view", "", screenViewEvent.data.screen_name].join(":");
8809            }
8810            return null;
8811          case dist.EventTypeEnum.commerceEvent:
8812            var commerceEvent = eventToMatch;
8813            var matchKey = [];
8814            if (commerceEvent && commerceEvent.data) {
8815              var _a2 = commerceEvent.data, product_action = _a2.product_action, product_impressions = _a2.product_impressions, promotion_action = _a2.promotion_action;
8816              if (product_action) {
8817                matchKey.push(DataPlanMatchType.ProductAction);
8818                matchKey.push(product_action.action);
8819              } else if (promotion_action) {
8820                matchKey.push(DataPlanMatchType.PromotionAction);
8821                matchKey.push(promotion_action.action);
8822              } else if (product_impressions) {
8823                matchKey.push(DataPlanMatchType.ProductImpression);
8824              }
8825            }
8826            return matchKey.join(":");
8827          case dist.EventTypeEnum.customEvent:
8828            var customEvent = eventToMatch;
8829            if (customEvent.data) {
8830              return ["custom_event", customEvent.data.custom_event_type, customEvent.data.event_name].join(":");
8831            }
8832            return null;
8833          default:
8834            return null;
8835        }
8836      };
8837      KitBlocker2.prototype.getProductAttributeMatchKey = function(eventToMatch) {
8838        switch (eventToMatch.event_type) {
8839          case dist.EventTypeEnum.commerceEvent:
8840            var commerceEvent = eventToMatch;
8841            var matchKey = [];
8842            var _a2 = commerceEvent.data, product_action = _a2.product_action, product_impressions = _a2.product_impressions, promotion_action = _a2.promotion_action;
8843            if (product_action) {
8844              matchKey.push(DataPlanMatchType.ProductAction);
8845              matchKey.push(product_action.action);
8846              matchKey.push("ProductAttributes");
8847            } else if (promotion_action) {
8848              matchKey.push(DataPlanMatchType.PromotionAction);
8849              matchKey.push(promotion_action.action);
8850              matchKey.push("ProductAttributes");
8851            } else if (product_impressions) {
8852              matchKey.push(DataPlanMatchType.ProductImpression);
8853              matchKey.push("ProductAttributes");
8854            }
8855            return matchKey.join(":");
8856          default:
8857            return null;
8858        }
8859      };
8860      KitBlocker2.prototype.createBlockedEvent = function(event) {
8861        try {
8862          if (event) {
8863            event = this.transformEventAndEventAttributes(event);
8864          }
8865          if (event && event.EventDataType === Types.MessageType.Commerce) {
8866            event = this.transformProductAttributes(event);
8867          }
8868          if (event) {
8869            event = this.transformUserAttributes(event);
8870            event = this.transformUserIdentities(event);
8871          }
8872          return event;
8873        } catch (e) {
8874          return event;
8875        }
8876      };
8877      KitBlocker2.prototype.transformEventAndEventAttributes = function(event) {
8878        var clonedEvent = __assign({}, event);
8879        var baseEvent = convertEvent(clonedEvent);
8880        var matchKey = this.getMatchKey(baseEvent);
8881        var matchedEvent = this.dataPlanMatchLookups[matchKey];
8882        if (this.blockEvents) {
8883          if (!matchedEvent) {
8884            return null;
8885          }
8886        }
8887        if (this.blockEventAttributes) {
8888          if (matchedEvent === true) {
8889            return clonedEvent;
8890          }
8891          if (matchedEvent) {
8892            for (var _i = 0, _a2 = Object.keys(clonedEvent.EventAttributes); _i < _a2.length; _i++) {
8893              var key = _a2[_i];
8894              if (!matchedEvent[key]) {
8895                delete clonedEvent.EventAttributes[key];
8896              }
8897            }
8898            return clonedEvent;
8899          } else {
8900            return clonedEvent;
8901          }
8902        }
8903        return clonedEvent;
8904      };
8905      KitBlocker2.prototype.transformProductAttributes = function(event) {
8906        var _a2;
8907        var clonedEvent = __assign({}, event);
8908        var baseEvent = convertEvent(clonedEvent);
8909        var matchKey = this.getProductAttributeMatchKey(baseEvent);
8910        var matchedEvent = this.dataPlanMatchLookups[matchKey];
8911        function removeAttribute(matchedEvent2, productList) {
8912          productList.forEach(function(product) {
8913            for (var _i = 0, _a3 = Object.keys(product.Attributes); _i < _a3.length; _i++) {
8914              var productKey = _a3[_i];
8915              if (!matchedEvent2[productKey]) {
8916                delete product.Attributes[productKey];
8917              }
8918            }
8919          });
8920        }
8921        if (this.blockEvents) {
8922          if (!matchedEvent) {
8923            return null;
8924          }
8925        }
8926        if (this.blockEventAttributes) {
8927          if (matchedEvent === true) {
8928            return clonedEvent;
8929          }
8930          if (matchedEvent) {
8931            switch (event.EventCategory) {
8932              case Types.CommerceEventType.ProductImpression:
8933                clonedEvent.ProductImpressions.forEach(function(impression) {
8934                  removeAttribute(matchedEvent, impression === null || impression === void 0 ? void 0 : impression.ProductList);
8935                });
8936                break;
8937              case Types.CommerceEventType.ProductPurchase:
8938                removeAttribute(matchedEvent, (_a2 = clonedEvent.ProductAction) === null || _a2 === void 0 ? void 0 : _a2.ProductList);
8939                break;
8940              default:
8941                this.mpInstance.Logger.warning("Product Not Supported ");
8942            }
8943            return clonedEvent;
8944          } else {
8945            return clonedEvent;
8946          }
8947        }
8948        return clonedEvent;
8949      };
8950      KitBlocker2.prototype.transformUserAttributes = function(event) {
8951        var clonedEvent = __assign({}, event);
8952        if (this.blockUserAttributes) {
8953          var matchedAttributes = this.dataPlanMatchLookups["user_attributes"];
8954          if (this.mpInstance._Helpers.isObject(matchedAttributes)) {
8955            for (var _i = 0, _a2 = Object.keys(clonedEvent.UserAttributes); _i < _a2.length; _i++) {
8956              var ua = _a2[_i];
8957              if (!matchedAttributes[ua]) {
8958                delete clonedEvent.UserAttributes[ua];
8959              }
8960            }
8961          }
8962        }
8963        return clonedEvent;
8964      };
8965      KitBlocker2.prototype.isAttributeKeyBlocked = function(key) {
8966        if (!this.blockUserAttributes) {
8967          return false;
8968        }
8969        var matchedAttributes = this.dataPlanMatchLookups["user_attributes"];
8970        if (typeof matchedAttributes === "boolean" && matchedAttributes) {
8971          return false;
8972        }
8973        if (_typeof(matchedAttributes) === "object") {
8974          if (matchedAttributes[key] === true) {
8975            return false;
8976          } else {
8977            return true;
8978          }
8979        }
8980        return false;
8981      };
8982      KitBlocker2.prototype.isIdentityBlocked = function(key) {
8983        if (!this.blockUserIdentities) {
8984          return false;
8985        }
8986        if (this.blockUserIdentities) {
8987          var matchedIdentities = this.dataPlanMatchLookups["user_identities"];
8988          if (matchedIdentities === true) {
8989            return false;
8990          }
8991          if (!matchedIdentities[key]) {
8992            return true;
8993          }
8994        } else {
8995          return false;
8996        }
8997        return false;
8998      };
8999      KitBlocker2.prototype.transformUserIdentities = function(event) {
9000        var _this = this;
9001        var _a2;
9002        var clonedEvent = __assign({}, event);
9003        if (this.blockUserIdentities) {
9004          var matchedIdentities_1 = this.dataPlanMatchLookups["user_identities"];
9005          if (this.mpInstance._Helpers.isObject(matchedIdentities_1)) {
9006            if ((_a2 = clonedEvent === null || clonedEvent === void 0 ? void 0 : clonedEvent.UserIdentities) === null || _a2 === void 0 ? void 0 : _a2.length) {
9007              clonedEvent.UserIdentities.forEach(function(uiByType, i) {
9008                var identityName = Types.IdentityType.getIdentityName(_this.mpInstance._Helpers.parseNumber(uiByType.Type));
9009                if (!matchedIdentities_1[identityName]) {
9010                  clonedEvent.UserIdentities.splice(i, 1);
9011                }
9012              });
9013            }
9014          }
9015        }
9016        return clonedEvent;
9017      };
9018      return KitBlocker2;
9019    })()
9020  );
9021  var buildUrl = function buildUrl2(configUrl, apiKey, dataPlanConfig, isDevelopmentMode) {
9022    var url = configUrl + apiKey + "/config";
9023    var env = isDevelopmentMode ? "1" : "0";
9024    var queryParams = ["env=".concat(env)];
9025    var _a2 = dataPlanConfig || {}, planId = _a2.planId, planVersion = _a2.planVersion;
9026    if (planId) {
9027      queryParams.push("plan_id=".concat(planId));
9028    }
9029    if (planVersion) {
9030      queryParams.push("plan_version=".concat(planVersion));
9031    }
9032    return "".concat(url, "?").concat(queryParams.join("&"));
9033  };
9034  function ConfigAPIClient(apiKey, config, mpInstance) {
9035    var _this = this;
9036    var baseUrl = "https://" + mpInstance._Store.SDKConfig.configUrl;
9037    var isDevelopmentMode = config.isDevelopmentMode;
9038    var dataPlan = config.dataPlan;
9039    var uploadUrl = buildUrl(baseUrl, apiKey, dataPlan, isDevelopmentMode);
9040    var uploader = window.fetch ? new FetchUploader(uploadUrl) : new XHRUploader(uploadUrl);
9041    this.getSDKConfiguration = function() {
9042      return __awaiter(_this, void 0, void 0, function() {
9043        var configResponse, fetchPayload, response, xhrResponse;
9044        var _a2, _b2, _c;
9045        return __generator(this, function(_d) {
9046          switch (_d.label) {
9047            case 0:
9048              fetchPayload = {
9049                method: "get",
9050                headers: {
9051                  Accept: "text/plain;charset=UTF-8",
9052                  "Content-Type": "text/plain;charset=UTF-8"
9053                },
9054                body: null
9055              };
9056              _d.label = 1;
9057            case 1:
9058              _d.trys.push([1, 6, , 7]);
9059              return [4, uploader.upload(fetchPayload)];
9060            case 2:
9061              response = _d.sent();
9062              if (!(response.status === 200)) return [3, 5];
9063              (_a2 = mpInstance === null || mpInstance === void 0 ? void 0 : mpInstance.Logger) === null || _a2 === void 0 ? void 0 : _a2.verbose("Successfully received configuration from server");
9064              if (!response.json) return [3, 4];
9065              return [4, response.json()];
9066            case 3:
9067              configResponse = _d.sent();
9068              return [2, configResponse];
9069            case 4:
9070              xhrResponse = response;
9071              configResponse = JSON.parse(xhrResponse.responseText);
9072              return [2, configResponse];
9073            case 5:
9074              (_b2 = mpInstance === null || mpInstance === void 0 ? void 0 : mpInstance.Logger) === null || _b2 === void 0 ? void 0 : _b2.verbose("Issue with receiving configuration from server, received HTTP Code of " + response.statusText);
9075              return [3, 7];
9076            case 6:
9077              _d.sent();
9078              (_c = mpInstance === null || mpInstance === void 0 ? void 0 : mpInstance.Logger) === null || _c === void 0 ? void 0 : _c.error("Error getting forwarder configuration from mParticle servers.");
9079              return [3, 7];
9080            case 7:
9081              return [2, config];
9082          }
9083        });
9084      });
9085    };
9086  }
9087  var HTTPCodes$1 = Constants.HTTPCodes, Messages$1 = Constants.Messages, IdentityMethods = Constants.IdentityMethods;
9088  var Modify = IdentityMethods.Modify;
9089  function IdentityAPIClient(mpInstance) {
9090    this.sendAliasRequest = function(aliasRequest, aliasCallback) {
9091      return __awaiter(this, void 0, void 0, function() {
9092        var Logger2, invokeAliasCallback, aliasUrl, apiKey, uploadUrl, uploader, uploadPayload, response, aliasResponseBody, message, errorMessage, _a2, xhrResponse, errorResponse, e_2, errorMessage;
9093        return __generator(this, function(_b2) {
9094          switch (_b2.label) {
9095            case 0:
9096              Logger2 = mpInstance.Logger;
9097              invokeAliasCallback = mpInstance._Helpers.invokeAliasCallback;
9098              aliasUrl = mpInstance._Store.SDKConfig.aliasUrl;
9099              apiKey = mpInstance._Store.devToken;
9100              Logger2.verbose(Messages$1.InformationMessages.SendAliasHttp);
9101              uploadUrl = "https://".concat(aliasUrl).concat(apiKey, "/Alias");
9102              uploader = window.fetch ? new FetchUploader(uploadUrl) : new XHRUploader(uploadUrl);
9103              uploadPayload = {
9104                method: "post",
9105                headers: {
9106                  Accept: "text/plain;charset=UTF-8",
9107                  "Content-Type": "application/json"
9108                },
9109                body: JSON.stringify(aliasRequest)
9110              };
9111              _b2.label = 1;
9112            case 1:
9113              _b2.trys.push([1, 13, , 14]);
9114              return [4, uploader.upload(uploadPayload)];
9115            case 2:
9116              response = _b2.sent();
9117              aliasResponseBody = void 0;
9118              message = void 0;
9119              errorMessage = void 0;
9120              _a2 = response.status;
9121              switch (_a2) {
9122                case HTTP_ACCEPTED:
9123                  return [3, 3];
9124                case HTTP_OK:
9125                  return [3, 3];
9126                case HTTP_BAD_REQUEST:
9127                  return [3, 4];
9128              }
9129              return [3, 11];
9130            case 3:
9131              message = "Received Alias Response from server: " + JSON.stringify(response.status);
9132              return [3, 12];
9133            case 4:
9134              if (!response.json) return [3, 9];
9135              _b2.label = 5;
9136            case 5:
9137              _b2.trys.push([5, 7, , 8]);
9138              return [4, response.json()];
9139            case 6:
9140              aliasResponseBody = _b2.sent();
9141              return [3, 8];
9142            case 7:
9143              _b2.sent();
9144              Logger2.verbose("The request has no response body");
9145              return [3, 8];
9146            case 8:
9147              return [3, 10];
9148            case 9:
9149              xhrResponse = response;
9150              aliasResponseBody = xhrResponse.responseText ? JSON.parse(xhrResponse.responseText) : "";
9151              _b2.label = 10;
9152            case 10:
9153              errorResponse = aliasResponseBody;
9154              if (errorResponse === null || errorResponse === void 0 ? void 0 : errorResponse.message) {
9155                errorMessage = errorResponse.message;
9156              }
9157              message = "Issue with sending Alias Request to mParticle Servers, received HTTP Code of " + response.status;
9158              if (errorResponse === null || errorResponse === void 0 ? void 0 : errorResponse.code) {
9159                message += " - " + errorResponse.code;
9160              }
9161              return [3, 12];
9162            case 11: {
9163              throw new Error("Received HTTP Code of " + response.status);
9164            }
9165            case 12:
9166              Logger2.verbose(message);
9167              invokeAliasCallback(aliasCallback, response.status, errorMessage);
9168              return [3, 14];
9169            case 13:
9170              e_2 = _b2.sent();
9171              errorMessage = getErrorMessage(e_2);
9172              Logger2.error("Error sending alias request to mParticle servers. " + errorMessage);
9173              invokeAliasCallback(aliasCallback, HTTPCodes$1.noHttpCoverage, errorMessage);
9174              return [3, 14];
9175            case 14:
9176              return [
9177                2
9178                /*return*/
9179              ];
9180          }
9181        });
9182      });
9183    };
9184    this.sendIdentityRequest = function(identityApiRequest, method, callback, originalIdentityApiData, parseIdentityResponse2, mpid, knownIdentities) {
9185      var _a2, _b2, _c, _d;
9186      return __awaiter(this, void 0, void 0, function() {
9187        var requestCount, invokeCallback, Logger2, errorReporter, previousMPID, uploadUrl, uploader, fetchPayload, response, identityResponse, message, _e, responseBody, errorResponse, errorMessage, responseText, isDevelopmentMode, responseToLog, errorMessage, requestCount, err_1, requestCount, errorMessage, msg;
9188        return __generator(this, function(_f) {
9189          switch (_f.label) {
9190            case 0:
9191              if ((_a2 = mpInstance._RoktManager) === null || _a2 === void 0 ? void 0 : _a2.isInitialized) {
9192                mpInstance._Store.identifyRequestCount = (mpInstance._Store.identifyRequestCount || 0) + 1;
9193                requestCount = mpInstance._Store.identifyRequestCount;
9194                mpInstance.captureTiming("".concat(requestCount, "-identityRequestStart"));
9195              }
9196              invokeCallback = mpInstance._Helpers.invokeCallback;
9197              Logger2 = mpInstance.Logger, errorReporter = mpInstance._ErrorReportingDispatcher;
9198              Logger2.verbose(Messages$1.InformationMessages.SendIdentityBegin);
9199              if (!identityApiRequest) {
9200                Logger2.error(Messages$1.ErrorMessages.APIRequestEmpty);
9201                return [
9202                  2
9203                  /*return*/
9204                ];
9205              }
9206              Logger2.verbose(Messages$1.InformationMessages.SendIdentityHttp);
9207              if (mpInstance._Store.identityCallInFlight) {
9208                invokeCallback(callback, HTTPCodes$1.activeIdentityRequest, "There is currently an Identity request processing. Please wait for this to return before requesting again");
9209                return [
9210                  2
9211                  /*return*/
9212                ];
9213              }
9214              previousMPID = mpid || null;
9215              uploadUrl = this.getUploadUrl(method, mpid);
9216              uploader = window.fetch ? new FetchUploader(uploadUrl) : new XHRUploader(uploadUrl);
9217              fetchPayload = {
9218                method: "post",
9219                headers: {
9220                  Accept: "text/plain;charset=UTF-8",
9221                  "Content-Type": "application/json",
9222                  "x-mp-key": mpInstance._Store.devToken
9223                },
9224                body: JSON.stringify(identityApiRequest)
9225              };
9226              mpInstance._Store.identityCallInFlight = true;
9227              _f.label = 1;
9228            case 1:
9229              _f.trys.push([1, 9, , 10]);
9230              return [4, uploader.upload(fetchPayload)];
9231            case 2:
9232              response = _f.sent();
9233              identityResponse = void 0;
9234              message = void 0;
9235              _e = response.status;
9236              switch (_e) {
9237                case HTTP_ACCEPTED:
9238                  return [3, 3];
9239                case HTTP_OK:
9240                  return [3, 3];
9241                case HTTP_BAD_REQUEST:
9242                  return [3, 3];
9243              }
9244              return [3, 7];
9245            case 3:
9246              if (!response.json) return [3, 5];
9247              return [4, response.json()];
9248            case 4:
9249              responseBody = _f.sent();
9250              identityResponse = this.getIdentityResponseFromFetch(response, responseBody);
9251              return [3, 6];
9252            case 5:
9253              identityResponse = this.getIdentityResponseFromXHR(response);
9254              _f.label = 6;
9255            case 6:
9256              if (identityResponse.status === HTTP_BAD_REQUEST) {
9257                errorResponse = identityResponse.responseText;
9258                message = "Issue with sending Identity Request to mParticle Servers, received HTTP Code of " + identityResponse.status;
9259                if (errorResponse === null || errorResponse === void 0 ? void 0 : errorResponse.Errors) {
9260                  errorMessage = errorResponse.Errors.map(function(error) {
9261                    return error.message;
9262                  }).join(", ");
9263                  message += " - " + errorMessage;
9264                }
9265              } else if (Logger2.isVerbose()) {
9266                responseText = identityResponse.responseText;
9267                isDevelopmentMode = mpInstance._Store.SDKConfig.isDevelopmentMode;
9268                responseToLog = responseText;
9269                if (!isDevelopmentMode && (responseText === null || responseText === void 0 ? void 0 : responseText.matched_identities)) {
9270                  responseToLog = __assign(__assign({}, responseText), {
9271                    matched_identities: obfuscateData(responseText.matched_identities)
9272                  });
9273                }
9274                message = "Received Identity Response from server: " + JSON.stringify(responseToLog);
9275              }
9276              return [3, 8];
9277            case 7: {
9278              if (response.status >= HTTP_SERVER_ERROR) {
9279                throw new Error("Received HTTP Code of " + response.status);
9280              }
9281              mpInstance._Store.identityCallInFlight = false;
9282              mpInstance._Store.identityCallFailed = false;
9283              errorMessage = "Received HTTP Code of " + response.status;
9284              Logger2.error("Error sending identity request to servers - " + errorMessage);
9285              invokeCallback(callback, HTTPCodes$1.noHttpCoverage, errorMessage);
9286              return [
9287                2
9288                /*return*/
9289              ];
9290            }
9291            case 8:
9292              mpInstance._Store.identityCallInFlight = false;
9293              mpInstance._Store.identityCallFailed = false;
9294              if (message) {
9295                Logger2.verbose(message);
9296              }
9297              if ((_b2 = mpInstance._RoktManager) === null || _b2 === void 0 ? void 0 : _b2.isInitialized) {
9298                requestCount = mpInstance._Store.identifyRequestCount;
9299                mpInstance.captureTiming("".concat(requestCount, "-identityRequestEnd"));
9300              }
9301              parseIdentityResponse2(identityResponse, previousMPID, callback, originalIdentityApiData, method, knownIdentities, false);
9302              return [3, 10];
9303            case 9:
9304              err_1 = _f.sent();
9305              mpInstance._Store.identityCallInFlight = false;
9306              mpInstance._Store.identityCallFailed = true;
9307              if ((_c = mpInstance._RoktManager) === null || _c === void 0 ? void 0 : _c.isInitialized) {
9308                requestCount = mpInstance._Store.identifyRequestCount;
9309                mpInstance.captureTiming("".concat(requestCount, "-identityRequestEnd"));
9310              }
9311              errorMessage = getErrorMessage(err_1);
9312              msg = "Error sending identity request to servers - " + errorMessage;
9313              Logger2.error(msg);
9314              errorReporter === null || errorReporter === void 0 ? void 0 : errorReporter.report({
9315                message: msg,
9316                code: ErrorCodes.IDENTITY_REQUEST,
9317                severity: WSDKErrorSeverity.ERROR
9318              });
9319              (_d = mpInstance.processQueueOnIdentityFailure) === null || _d === void 0 ? void 0 : _d.call(mpInstance);
9320              invokeCallback(callback, HTTPCodes$1.noHttpCoverage, errorMessage);
9321              return [3, 10];
9322            case 10:
9323              return [
9324                2
9325                /*return*/
9326              ];
9327          }
9328        });
9329      });
9330    };
9331    this.getUploadUrl = function(method, mpid) {
9332      var uploadServiceUrl = mpInstance._Helpers.createServiceUrl(mpInstance._Store.SDKConfig.identityUrl);
9333      var uploadUrl = method === Modify ? uploadServiceUrl + mpid + "/" + method : uploadServiceUrl + method;
9334      return uploadUrl;
9335    };
9336    this.getIdentityResponseFromFetch = function(response, responseBody) {
9337      return {
9338        status: response.status,
9339        responseText: responseBody,
9340        cacheMaxAge: parseInt(response.headers.get(CACHE_HEADER)) || 0,
9341        expireTimestamp: 0
9342      };
9343    };
9344    this.getIdentityResponseFromXHR = function(response) {
9345      return {
9346        status: response.status,
9347        responseText: response.responseText ? JSON.parse(response.responseText) : {},
9348        cacheMaxAge: parseNumber(response.getResponseHeader(CACHE_HEADER) || ""),
9349        expireTimestamp: 0
9350      };
9351    };
9352  }
9353  var facebookClickIdProcessor = function facebookClickIdProcessor2(clickId, url, timestamp) {
9354    if (!clickId || !url) {
9355      return "";
9356    }
9357    var urlSegments = url === null || url === void 0 ? void 0 : url.split("//");
9358    if (!urlSegments) {
9359      return "";
9360    }
9361    var urlParts = urlSegments[1].split("/");
9362    var domainParts = urlParts[0].split(".");
9363    var subdomainIndex = 1;
9364    if (domainParts.length >= 3) {
9365      subdomainIndex = 2;
9366    }
9367    var _timestamp = timestamp || Date.now();
9368    return "fb.".concat(subdomainIndex, ".").concat(_timestamp, ".").concat(clickId);
9369  };
9370  var IntegrationOutputs = {
9371    CUSTOM_FLAGS: "custom_flags",
9372    PARTNER_IDENTITIES: "partner_identities",
9373    INTEGRATION_ATTRIBUTES: "integration_attributes"
9374  };
9375  var integrationMappingExternal = {
9376    // Facebook / Meta
9377    fbclid: {
9378      mappedKey: "Facebook.ClickId",
9379      processor: facebookClickIdProcessor,
9380      output: IntegrationOutputs.CUSTOM_FLAGS
9381    },
9382    _fbp: {
9383      mappedKey: "Facebook.BrowserId",
9384      output: IntegrationOutputs.CUSTOM_FLAGS
9385    },
9386    _fbc: {
9387      mappedKey: "Facebook.ClickId",
9388      output: IntegrationOutputs.CUSTOM_FLAGS
9389    },
9390    // Google
9391    gclid: {
9392      mappedKey: "GoogleEnhancedConversions.Gclid",
9393      output: IntegrationOutputs.CUSTOM_FLAGS
9394    },
9395    gbraid: {
9396      mappedKey: "GoogleEnhancedConversions.Gbraid",
9397      output: IntegrationOutputs.CUSTOM_FLAGS
9398    },
9399    wbraid: {
9400      mappedKey: "GoogleEnhancedConversions.Wbraid",
9401      output: IntegrationOutputs.CUSTOM_FLAGS
9402    },
9403    // TIKTOK
9404    ttclid: {
9405      mappedKey: "TikTok.Callback",
9406      output: IntegrationOutputs.CUSTOM_FLAGS
9407    },
9408    _ttp: {
9409      mappedKey: "tiktok_cookie_id",
9410      output: IntegrationOutputs.PARTNER_IDENTITIES
9411    },
9412    // Snapchat
9413    // https://businesshelp.snapchat.com/s/article/troubleshooting-click-id?language=en_US
9414    ScCid: {
9415      mappedKey: "SnapchatConversions.ClickId",
9416      output: IntegrationOutputs.CUSTOM_FLAGS
9417    },
9418    // Snapchat
9419    // https://developers.snap.com/api/marketing-api/Conversions-API/UsingTheAPI#sending-click-id
9420    _scid: {
9421      mappedKey: "SnapchatConversions.Cookie1",
9422      output: IntegrationOutputs.CUSTOM_FLAGS
9423    }
9424  };
9425  var integrationMappingRokt = {
9426    // Rokt
9427    // https://docs.rokt.com/developers/integration-guides/web/advanced/rokt-id-tag/
9428    // https://go.mparticle.com/work/SQDSDKS-7167
9429    rtid: {
9430      mappedKey: "passbackconversiontrackingid",
9431      output: IntegrationOutputs.INTEGRATION_ATTRIBUTES,
9432      moduleId: 1277
9433    },
9434    rclid: {
9435      mappedKey: "passbackconversiontrackingid",
9436      output: IntegrationOutputs.INTEGRATION_ATTRIBUTES,
9437      moduleId: 1277
9438    },
9439    RoktTransactionId: {
9440      mappedKey: "passbackconversiontrackingid",
9441      output: IntegrationOutputs.INTEGRATION_ATTRIBUTES,
9442      moduleId: 1277
9443    }
9444  };
9445  var IntegrationCapture = (
9446    /** @class */
9447    (function() {
9448      function IntegrationCapture2(captureMode) {
9449        this.initialTimestamp = Date.now();
9450        this.captureMode = captureMode;
9451        this.filteredPartnerIdentityMappings = this.filterMappings(IntegrationOutputs.PARTNER_IDENTITIES);
9452        this.filteredCustomFlagMappings = this.filterMappings(IntegrationOutputs.CUSTOM_FLAGS);
9453        this.filteredIntegrationAttributeMappings = this.filterMappings(IntegrationOutputs.INTEGRATION_ATTRIBUTES);
9454      }
9455      IntegrationCapture2.prototype.capture = function() {
9456        var queryParams = this.captureQueryParams() || {};
9457        var cookies = this.captureCookies() || {};
9458        var localStorage2 = this.captureLocalStorage() || {};
9459        if (queryParams["fbclid"] && cookies["_fbc"]) {
9460          delete cookies["_fbc"];
9461        }
9462        var hasQueryParamId = queryParams["rtid"] || queryParams["rclid"];
9463        var hasLocalStorageId = localStorage2["RoktTransactionId"];
9464        var hasCookieId = cookies["RoktTransactionId"];
9465        if (hasQueryParamId) {
9466          if (hasLocalStorageId) {
9467            delete localStorage2["RoktTransactionId"];
9468          }
9469          if (hasCookieId) {
9470            delete cookies["RoktTransactionId"];
9471          }
9472        } else if (hasLocalStorageId && hasCookieId) {
9473          delete cookies["RoktTransactionId"];
9474        }
9475        this.clickIds = __assign(__assign(__assign(__assign({}, this.clickIds), queryParams), localStorage2), cookies);
9476      };
9477      IntegrationCapture2.prototype.captureCookies = function() {
9478        var integrationKeys = this.getAllowedKeysForMode();
9479        var cookies = getCookies(integrationKeys);
9480        return this.applyProcessors(cookies, getHref(), this.initialTimestamp);
9481      };
9482      IntegrationCapture2.prototype.captureQueryParams = function() {
9483        var queryParams = this.getQueryParams();
9484        return this.applyProcessors(queryParams, getHref(), this.initialTimestamp);
9485      };
9486      IntegrationCapture2.prototype.captureLocalStorage = function() {
9487        var integrationKeys = this.getAllowedKeysForMode();
9488        var localStorageItems = {};
9489        for (var _i = 0, integrationKeys_1 = integrationKeys; _i < integrationKeys_1.length; _i++) {
9490          var key = integrationKeys_1[_i];
9491          var localStorageItem = localStorage.getItem(key);
9492          if (localStorageItem) {
9493            localStorageItems[key] = localStorageItem;
9494          }
9495        }
9496        return this.applyProcessors(localStorageItems, getHref(), this.initialTimestamp);
9497      };
9498      IntegrationCapture2.prototype.getQueryParams = function() {
9499        var integrationKeys = this.getAllowedKeysForMode();
9500        return queryStringParser(getHref(), integrationKeys);
9501      };
9502      IntegrationCapture2.prototype.getClickIdsAsCustomFlags = function() {
9503        return this.getClickIds(this.clickIds, this.filteredCustomFlagMappings);
9504      };
9505      IntegrationCapture2.prototype.getClickIdsAsPartnerIdentities = function() {
9506        return this.getClickIds(this.clickIds, this.filteredPartnerIdentityMappings);
9507      };
9508      IntegrationCapture2.prototype.getClickIdsAsIntegrationAttributes = function() {
9509        var _a2;
9510        var _b2, _c;
9511        var mappedClickIds = {};
9512        for (var key in this.clickIds) {
9513          if (this.clickIds.hasOwnProperty(key)) {
9514            var value = this.clickIds[key];
9515            var mappingKey = (_b2 = this.filteredIntegrationAttributeMappings[key]) === null || _b2 === void 0 ? void 0 : _b2.mappedKey;
9516            if (!isEmpty(mappingKey)) {
9517              var moduleId = (_c = this.filteredIntegrationAttributeMappings[key]) === null || _c === void 0 ? void 0 : _c.moduleId;
9518              if (moduleId && !mappedClickIds[moduleId]) {
9519                mappedClickIds[moduleId] = (_a2 = {}, _a2[mappingKey] = value, _a2);
9520              }
9521            }
9522          }
9523        }
9524        return mappedClickIds;
9525      };
9526      IntegrationCapture2.prototype.getClickIds = function(clickIds, mappingList) {
9527        var _a2;
9528        var mappedClickIds = {};
9529        if (!clickIds) {
9530          return mappedClickIds;
9531        }
9532        for (var key in clickIds) {
9533          if (clickIds.hasOwnProperty(key)) {
9534            var value = clickIds[key];
9535            var mappedKey = (_a2 = mappingList[key]) === null || _a2 === void 0 ? void 0 : _a2.mappedKey;
9536            if (!isEmpty(mappedKey)) {
9537              mappedClickIds[mappedKey] = value;
9538            }
9539          }
9540        }
9541        return mappedClickIds;
9542      };
9543      IntegrationCapture2.prototype.applyProcessors = function(clickIds, url, timestamp) {
9544        var _a2;
9545        var processedClickIds = {};
9546        var integrationKeys = this.getActiveIntegrationMapping();
9547        for (var key in clickIds) {
9548          if (clickIds.hasOwnProperty(key)) {
9549            var value = clickIds[key];
9550            var processor = (_a2 = integrationKeys[key]) === null || _a2 === void 0 ? void 0 : _a2.processor;
9551            processedClickIds[key] = processor ? processor(value, url, timestamp) : value;
9552          }
9553        }
9554        return processedClickIds;
9555      };
9556      IntegrationCapture2.prototype.filterMappings = function(outputType) {
9557        var filteredMappings = {};
9558        var integrationKeys = this.getActiveIntegrationMapping();
9559        for (var key in integrationKeys) {
9560          if (integrationKeys[key].output === outputType) {
9561            filteredMappings[key] = integrationKeys[key];
9562          }
9563        }
9564        return filteredMappings;
9565      };
9566      IntegrationCapture2.prototype.getAllowedKeysForMode = function() {
9567        return Object.keys(this.getActiveIntegrationMapping());
9568      };
9569      IntegrationCapture2.prototype.getActiveIntegrationMapping = function() {
9570        if (this.captureMode === Constants.CaptureIntegrationSpecificIdsV2Modes.RoktOnly) {
9571          return integrationMappingRokt;
9572        }
9573        if (this.captureMode === Constants.CaptureIntegrationSpecificIdsV2Modes.All) {
9574          return __assign(__assign({}, integrationMappingExternal), integrationMappingRokt);
9575        }
9576        return {};
9577      };
9578      return IntegrationCapture2;
9579    })()
9580  );
9581  var PASSBACK_CONVERSION_TRACKING_ID = "passbackconversiontrackingid";
9582  var ON_SHOPPABLE_ADS_READY_METHOD = "onShoppableAdsReady";
9583  var RoktManager = (
9584    /** @class */
9585    (function() {
9586      function RoktManager2() {
9587        this.kit = null;
9588        this.filters = {};
9589        this.currentUser = null;
9590        this.messageQueue = /* @__PURE__ */ new Map();
9591        this.sandbox = null;
9592        this.placementAttributesMapping = [];
9593        this.onReadyCallback = null;
9594        this.initialized = false;
9595        this.isShoppableAdsLoaded = false;
9596      }
9597      RoktManager2.prototype.setOnReadyCallback = function(callback) {
9598        this.onReadyCallback = callback;
9599      };
9600      RoktManager2.prototype.init = function(roktConfig, filteredUser, identityService, store, logger, options, captureTiming, errorReporter, loggingService, integrationCapture) {
9601        var _a2, _b2;
9602        var _c = roktConfig || {}, userAttributeFilters = _c.userAttributeFilters, settings = _c.settings;
9603        var _d = settings || {}, placementAttributesMapping = _d.placementAttributesMapping, hashedEmailUserIdentityType = _d.hashedEmailUserIdentityType;
9604        this.mappedEmailShaIdentityType = (_a2 = hashedEmailUserIdentityType === null || hashedEmailUserIdentityType === void 0 ? void 0 : hashedEmailUserIdentityType.toLowerCase()) !== null && _a2 !== void 0 ? _a2 : null;
9605        this.identityService = identityService;
9606        this.store = store;
9607        this.logger = logger;
9608        this.errorReporter = errorReporter;
9609        this.loggingService = loggingService;
9610        this.captureTiming = captureTiming;
9611        this.integrationCapture = integrationCapture;
9612        (_b2 = this.captureTiming) === null || _b2 === void 0 ? void 0 : _b2.call(this, PerformanceMarkType.JointSdkRoktKitInit);
9613        this.filters = {
9614          userAttributeFilters,
9615          filterUserAttributes: KitFilterHelper.filterUserAttributes,
9616          filteredUser
9617        };
9618        try {
9619          this.placementAttributesMapping = parseSettingsString(placementAttributesMapping);
9620        } catch (error) {
9621          this.logger.error("Error parsing placement attributes mapping from config: " + error);
9622        }
9623        var sandbox = (options === null || options === void 0 ? void 0 : options.sandbox) || false;
9624        var launcherOptions = normalizeRoktLauncherOptions(options === null || options === void 0 ? void 0 : options.launcherOptions);
9625        this.launcherOptions = __assign({
9626          sandbox
9627        }, launcherOptions);
9628        if (options === null || options === void 0 ? void 0 : options.domain) {
9629          this.domain = options.domain;
9630        }
9631        this.initialized = true;
9632      };
9633      Object.defineProperty(RoktManager2.prototype, "isInitialized", {
9634        get: function get() {
9635          return this.initialized;
9636        },
9637        enumerable: false,
9638        configurable: true
9639      });
9640      RoktManager2.prototype.attachKit = function(kit) {
9641        var _a2, _b2, _c, _d;
9642        this.kit = kit;
9643        if ((_a2 = kit.settings) === null || _a2 === void 0 ? void 0 : _a2.accountId) {
9644          this.store.setRoktAccountId(kit.settings.accountId);
9645        }
9646        if (kit.integrationName) {
9647          (_b2 = this.store) === null || _b2 === void 0 ? void 0 : _b2.setIntegrationName(kit.integrationName);
9648        }
9649        this.processMessageQueue();
9650        try {
9651          (_c = this.onReadyCallback) === null || _c === void 0 ? void 0 : _c.call(this);
9652        } catch (e) {
9653          (_d = this.logger) === null || _d === void 0 ? void 0 : _d.error("RoktManager: Error in onReadyCallback: " + e);
9654        }
9655      };
9656      RoktManager2.prototype.selectPlacements = function(options) {
9657        var _a2, _b2, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
9658        return __awaiter(this, void 0, void 0, function() {
9659          var attributes, sandboxValue, mappedAttributes, attributesToLog, currentUserIdentities, currentEmail, newEmail, currentHashedEmail, newHashedEmail, isValidHashedEmailIdentityType, emailChanged, hashedEmailChanged, newIdentities, msg, msg, finalUserIdentities, timeOnSite, totalTimeOnSite, enrichedAttributes, hashedEmail, capturedAttrs, passbackId, enrichedOptions;
9660          var _this = this;
9661          return __generator(this, function(_s) {
9662            (_a2 = this.captureTiming) === null || _a2 === void 0 ? void 0 : _a2.call(this, PerformanceMarkType.JointSdkSelectPlacements);
9663            if (!this.isReady() || ((_b2 = this.store) === null || _b2 === void 0 ? void 0 : _b2.identityCallInFlight)) {
9664              return [2, this.deferredCall("selectPlacements", options)];
9665            }
9666            try {
9667              attributes = options.attributes;
9668              sandboxValue = (attributes === null || attributes === void 0 ? void 0 : attributes.sandbox) || null;
9669              mappedAttributes = this.mapPlacementAttributes(attributes, this.placementAttributesMapping);
9670              if ((_c = this.logger) === null || _c === void 0 ? void 0 : _c.isVerbose()) {
9671                attributesToLog = obfuscateDevData(attributes, (_e = (_d = this.store) === null || _d === void 0 ? void 0 : _d.SDKConfig) === null || _e === void 0 ? void 0 : _e.isDevelopmentMode);
9672                this.logger.verbose("mParticle.Rokt selectPlacements called with attributes:\n".concat(JSON.stringify(attributesToLog, null, 2)));
9673              }
9674              this.currentUser = this.identityService.getCurrentUser();
9675              currentUserIdentities = ((_g = (_f = this.currentUser) === null || _f === void 0 ? void 0 : _f.getUserIdentities()) === null || _g === void 0 ? void 0 : _g.userIdentities) || {};
9676              currentEmail = currentUserIdentities.email;
9677              newEmail = mappedAttributes.email;
9678              currentHashedEmail = void 0;
9679              newHashedEmail = void 0;
9680              isValidHashedEmailIdentityType = this.mappedEmailShaIdentityType && IdentityType.getIdentityType(this.mappedEmailShaIdentityType) !== false;
9681              if (isValidHashedEmailIdentityType) {
9682                currentHashedEmail = currentUserIdentities[this.mappedEmailShaIdentityType];
9683                newHashedEmail = mappedAttributes["emailsha256"] || mappedAttributes[this.mappedEmailShaIdentityType] || void 0;
9684              }
9685              emailChanged = this.hasIdentityChanged(currentEmail, newEmail);
9686              hashedEmailChanged = this.hasIdentityChanged(currentHashedEmail, newHashedEmail);
9687              newIdentities = {};
9688              if (emailChanged) {
9689                newIdentities.email = newEmail;
9690                if (newEmail) {
9691                  msg = "Email mismatch detected. Current email differs from email passed to selectPlacements call. Proceeding to call identify with email from selectPlacements call. Please verify your implementation.";
9692                  this.logger.warning(msg);
9693                  (_h = this.errorReporter) === null || _h === void 0 ? void 0 : _h.report({
9694                    message: msg,
9695                    code: ErrorCodes.IDENTITY_MISMATCH,
9696                    severity: WSDKErrorSeverity.WARNING
9697                  });
9698                }
9699              }
9700              if (hashedEmailChanged) {
9701                newIdentities[this.mappedEmailShaIdentityType] = newHashedEmail;
9702                msg = "emailsha256 mismatch detected. Current mParticle hashedEmail differs from hashedEmail passed to selectPlacements call. Proceeding to call identify with hashedEmail from selectPlacements call. Please verify your implementation.";
9703                this.logger.warning(msg);
9704                (_j = this.errorReporter) === null || _j === void 0 ? void 0 : _j.report({
9705                  message: msg,
9706                  code: ErrorCodes.IDENTITY_MISMATCH,
9707                  severity: WSDKErrorSeverity.WARNING
9708                });
9709              }
9710              if (!isEmpty(newIdentities)) {
9711                try {
9712                  this.identityService.identify({
9713                    userIdentities: __assign(__assign({}, currentUserIdentities), newIdentities)
9714                  }, function(result) {
9715                    var httpCode = Number(result === null || result === void 0 ? void 0 : result.httpCode);
9716                    if (httpCode && (httpCode >= 400 || httpCode < 0)) {
9717                      _this.logger.error("Background identify failed with HTTP " + httpCode);
9718                    }
9719                    _this.processMessageQueue();
9720                  });
9721                } catch (error) {
9722                  this.logger.error("Background identify threw an error: " + getErrorMessage(error));
9723                }
9724              }
9725              finalUserIdentities = __assign(__assign({}, currentUserIdentities), newIdentities);
9726              this.setUserAttributes(mappedAttributes);
9727              timeOnSite = (_l = (_k = this.store) === null || _k === void 0 ? void 0 : _k.getTimeOnSite) === null || _l === void 0 ? void 0 : _l.call(_k);
9728              totalTimeOnSite = (_o = (_m = this.store) === null || _m === void 0 ? void 0 : _m.getTotalTimeOnSite) === null || _o === void 0 ? void 0 : _o.call(_m);
9729              enrichedAttributes = __assign(__assign(__assign(__assign({}, mappedAttributes), sandboxValue !== null ? {
9730                sandbox: sandboxValue
9731              } : {}), timeOnSite ? {
9732                active_time_on_site_ms: timeOnSite
9733              } : {}), totalTimeOnSite ? {
9734                total_time_on_site_ms: totalTimeOnSite
9735              } : {});
9736              if (finalUserIdentities.email && !enrichedAttributes.email) {
9737                enrichedAttributes.email = finalUserIdentities.email;
9738              }
9739              if (isValidHashedEmailIdentityType) {
9740                hashedEmail = finalUserIdentities[this.mappedEmailShaIdentityType];
9741                if (hashedEmail && !enrichedAttributes.emailsha256 && !enrichedAttributes[this.mappedEmailShaIdentityType]) {
9742                  enrichedAttributes.emailsha256 = hashedEmail;
9743                }
9744              }
9745              if (!enrichedAttributes[PASSBACK_CONVERSION_TRACKING_ID]) {
9746                (_p = this.integrationCapture) === null || _p === void 0 ? void 0 : _p.capture();
9747                capturedAttrs = (_q = this.integrationCapture) === null || _q === void 0 ? void 0 : _q.getClickIdsAsIntegrationAttributes();
9748                passbackId = (_r = capturedAttrs === null || capturedAttrs === void 0 ? void 0 : capturedAttrs[PARTNER_MODULE_IDS.Rokt]) === null || _r === void 0 ? void 0 : _r[PASSBACK_CONVERSION_TRACKING_ID];
9749                if (passbackId) {
9750                  enrichedAttributes[PASSBACK_CONVERSION_TRACKING_ID] = passbackId;
9751                }
9752              }
9753              this.filters.filteredUser = this.currentUser || this.filters.filteredUser || null;
9754              enrichedOptions = __assign(__assign({}, options), {
9755                attributes: enrichedAttributes
9756              });
9757              return [2, this.kit.selectPlacements(enrichedOptions)];
9758            } catch (error) {
9759              return [2, Promise.reject(error instanceof Error ? error : new Error("Unknown error occurred"))];
9760            }
9761            return [
9762              2
9763              /*return*/
9764            ];
9765          });
9766        });
9767      };
9768      RoktManager2.prototype.hashAttributes = function(attributes) {
9769        return __awaiter(this, void 0, void 0, function() {
9770          var keys, hashPromises, results, hashedAttributes, _i, results_1, _a2, key, attributeValue, hashedValue, error_1;
9771          var _this = this;
9772          return __generator(this, function(_b2) {
9773            switch (_b2.label) {
9774              case 0:
9775                _b2.trys.push([0, 2, , 3]);
9776                if (!attributes || _typeof(attributes) !== "object") {
9777                  return [2, {}];
9778                }
9779                keys = Object.keys(attributes);
9780                if (keys.length === 0) {
9781                  return [2, {}];
9782                }
9783                hashPromises = keys.map(function(key2) {
9784                  return __awaiter(_this, void 0, void 0, function() {
9785                    var attributeValue2, hashedValue2;
9786                    return __generator(this, function(_a3) {
9787                      switch (_a3.label) {
9788                        case 0:
9789                          attributeValue2 = attributes[key2];
9790                          return [4, this.hashSha256(attributeValue2)];
9791                        case 1:
9792                          hashedValue2 = _a3.sent();
9793                          return [2, {
9794                            key: key2,
9795                            attributeValue: attributeValue2,
9796                            hashedValue: hashedValue2
9797                          }];
9798                      }
9799                    });
9800                  });
9801                });
9802                return [4, Promise.all(hashPromises)];
9803              case 1:
9804                results = _b2.sent();
9805                hashedAttributes = {};
9806                for (_i = 0, results_1 = results; _i < results_1.length; _i++) {
9807                  _a2 = results_1[_i], key = _a2.key, attributeValue = _a2.attributeValue, hashedValue = _a2.hashedValue;
9808                  hashedAttributes[key] = attributeValue;
9809                  if (hashedValue) {
9810                    hashedAttributes["".concat(key, "sha256")] = hashedValue;
9811                  }
9812                }
9813                return [2, hashedAttributes];
9814              case 2:
9815                error_1 = _b2.sent();
9816                this.logger.error("Failed to hashAttributes, returning an empty object: ".concat(getErrorMessage(error_1)));
9817                return [2, {}];
9818              case 3:
9819                return [
9820                  2
9821                  /*return*/
9822                ];
9823            }
9824          });
9825        });
9826      };
9827      RoktManager2.prototype.setExtensionData = function(extensionData) {
9828        if (!this.isReady()) {
9829          this.deferredCall("setExtensionData", extensionData);
9830          return;
9831        }
9832        try {
9833          this.kit.setExtensionData(extensionData);
9834        } catch (error) {
9835          throw new Error("Error setting extension data: " + getErrorMessage(error));
9836        }
9837      };
9838      RoktManager2.prototype.use = function(name) {
9839        if (!this.isReady()) {
9840          return this.deferredCall("use", name);
9841        }
9842        try {
9843          return this.kit.use(name);
9844        } catch (error) {
9845          return Promise.reject(error instanceof Error ? error : new Error("Error using extension: " + name));
9846        }
9847      };
9848      RoktManager2.prototype.terminate = function() {
9849        var _a2, _b2, _c;
9850        return __awaiter(this, void 0, void 0, function() {
9851          var error_2;
9852          return __generator(this, function(_d) {
9853            switch (_d.label) {
9854              case 0:
9855                if (!this.isReady()) {
9856                  (_a2 = this.logger) === null || _a2 === void 0 ? void 0 : _a2.verbose("mParticle.Rokt.terminate called before the Rokt kit was ready. Nothing to terminate.");
9857                  return [
9858                    2
9859                    /*return*/
9860                  ];
9861                }
9862                if (!isFunction(this.kit.terminate)) {
9863                  (_b2 = this.logger) === null || _b2 === void 0 ? void 0 : _b2.error("mParticle.Rokt.terminate is not supported by the attached Rokt Kit version.");
9864                  return [
9865                    2
9866                    /*return*/
9867                  ];
9868                }
9869                _d.label = 1;
9870              case 1:
9871                _d.trys.push([1, 3, , 4]);
9872                return [4, this.kit.terminate()];
9873              case 2:
9874                _d.sent();
9875                return [3, 4];
9876              case 3:
9877                error_2 = _d.sent();
9878                (_c = this.logger) === null || _c === void 0 ? void 0 : _c.error("Failed to terminate the Rokt launcher: ".concat(getErrorMessage(error_2)));
9879                return [3, 4];
9880              case 4:
9881                return [
9882                  2
9883                  /*return*/
9884                ];
9885            }
9886          });
9887        });
9888      };
9889      RoktManager2.prototype.onShoppableAdsReady = function(callback) {
9890        if (!this.kit || !this.isShoppableAdsLoaded) {
9891          this.deferredCall("onShoppableAdsReady", callback);
9892          return;
9893        }
9894        try {
9895          this.kit.onShoppableAdsReady(callback);
9896        } catch (error) {
9897          this.logger.error("Failed to register onShoppableAdsReady callback: ".concat(getErrorMessage(error)));
9898        }
9899      };
9900      RoktManager2.prototype.flushOnShoppableAdsReadyMessageQueue = function(kit) {
9901        var _this = this;
9902        this.kit = kit;
9903        this.messageQueue.forEach(function(message, key) {
9904          var _a2;
9905          if (message.methodName === ON_SHOPPABLE_ADS_READY_METHOD) {
9906            try {
9907              kit.onShoppableAdsReady(message.payload);
9908            } catch (e) {
9909              (_a2 = _this.logger) === null || _a2 === void 0 ? void 0 : _a2.error("RoktManager: Error flushing onShoppableAdsReady: " + e);
9910            }
9911            _this.messageQueue["delete"](key);
9912          }
9913        });
9914        this.isShoppableAdsLoaded = true;
9915      };
9916      RoktManager2.prototype.hashSha256 = function(attribute) {
9917        return __awaiter(this, void 0, void 0, function() {
9918          var normalizedValue, error_3;
9919          return __generator(this, function(_a2) {
9920            switch (_a2.label) {
9921              case 0:
9922                if (attribute === null || attribute === void 0) {
9923                  this.logger.warning("hashSha256 received null/undefined as input");
9924                  return [2, attribute];
9925                }
9926                _a2.label = 1;
9927              case 1:
9928                _a2.trys.push([1, 3, , 4]);
9929                normalizedValue = String(attribute).trim().toLocaleLowerCase();
9930                return [4, this.sha256Hex(normalizedValue)];
9931              case 2:
9932                return [2, _a2.sent()];
9933              case 3:
9934                error_3 = _a2.sent();
9935                this.logger.error("Failed to hashSha256, returning undefined: ".concat(getErrorMessage(error_3)));
9936                return [2, void 0];
9937              case 4:
9938                return [
9939                  2
9940                  /*return*/
9941                ];
9942            }
9943          });
9944        });
9945      };
9946      RoktManager2.prototype.getLocalSessionAttributes = function() {
9947        return this.store.getLocalSessionAttributes();
9948      };
9949      RoktManager2.prototype.setLocalSessionAttribute = function(key, value) {
9950        this.store.setLocalSessionAttribute(key, value);
9951      };
9952      RoktManager2.prototype.isReady = function() {
9953        return Boolean(this.kit && this.kit.launcher);
9954      };
9955      RoktManager2.prototype.setUserAttributes = function(attributes) {
9956        var reservedAttributes = ["sandbox"];
9957        var filteredAttributes = {};
9958        for (var key in attributes) {
9959          if (attributes.hasOwnProperty(key) && reservedAttributes.indexOf(key) === -1) {
9960            var value = attributes[key];
9961            filteredAttributes[key] = Array.isArray(value) ? JSON.stringify(value) : value;
9962          }
9963        }
9964        try {
9965          this.currentUser.setUserAttributes(filteredAttributes);
9966        } catch (error) {
9967          this.logger.error("Error setting user attributes: " + error);
9968        }
9969      };
9970      RoktManager2.prototype.mapPlacementAttributes = function(attributes, placementAttributesMapping) {
9971        var mappingLookup = {};
9972        for (var _i = 0, placementAttributesMapping_1 = placementAttributesMapping; _i < placementAttributesMapping_1.length; _i++) {
9973          var mapping = placementAttributesMapping_1[_i];
9974          mappingLookup[mapping.map] = mapping.value;
9975        }
9976        var mappedAttributes = {};
9977        for (var key in attributes) {
9978          if (attributes.hasOwnProperty(key)) {
9979            var newKey = mappingLookup[key] || key;
9980            mappedAttributes[newKey] = attributes[key];
9981          }
9982        }
9983        return mappedAttributes;
9984      };
9985      RoktManager2.prototype.onIdentityComplete = function() {
9986        if (this.isReady()) {
9987          this.currentUser = this.identityService.getCurrentUser();
9988          this.processMessageQueue();
9989        }
9990      };
9991      RoktManager2.prototype.processMessageQueue = function() {
9992        var _this = this;
9993        var _a2;
9994        if (!this.isReady() || this.messageQueue.size === 0) {
9995          return;
9996        }
9997        (_a2 = this.logger) === null || _a2 === void 0 ? void 0 : _a2.verbose("RoktManager: Processing ".concat(this.messageQueue.size, " queued messages"));
9998        var messagesToProcess = Array.from(this.messageQueue.values());
9999        this.messageQueue.clear();
10000        messagesToProcess.forEach(function(message) {
10001          var _a3, _b2, _c, _d;
10002          if (!(message.methodName in _this) || !isFunction(_this[message.methodName])) {
10003            (_a3 = _this.logger) === null || _a3 === void 0 ? void 0 : _a3.error("RoktManager: Method ".concat(message.methodName, " not found"));
10004            return;
10005          }
10006          if ((_b2 = _this.logger) === null || _b2 === void 0 ? void 0 : _b2.isVerbose()) {
10007            var payloadToLog = obfuscateDevData(message.payload, (_d = (_c = _this.store) === null || _c === void 0 ? void 0 : _c.SDKConfig) === null || _d === void 0 ? void 0 : _d.isDevelopmentMode);
10008            _this.logger.verbose("RoktManager: Processing queued message: ".concat(message.methodName, " with payload: ").concat(JSON.stringify(payloadToLog)));
10009          }
10010          var resolve = message.resolve;
10011          var reject = message.reject;
10012          var handleError = function handleError2(error) {
10013            var _a4;
10014            (_a4 = _this.logger) === null || _a4 === void 0 ? void 0 : _a4.error("RoktManager: Error processing message '".concat(message.methodName, "': ").concat(getErrorMessage(error)));
10015            if (reject) {
10016              reject(error);
10017            }
10018          };
10019          try {
10020            var result = _this[message.methodName](message.payload);
10021            Promise.resolve(result).then(function(resolvedResult) {
10022              if (resolve) {
10023                resolve(resolvedResult);
10024              }
10025            })["catch"](handleError);
10026          } catch (error) {
10027            handleError(error);
10028          }
10029        });
10030      };
10031      RoktManager2.prototype.queueMessage = function(message) {
10032        this.messageQueue.set(message.messageId, message);
10033      };
10034      RoktManager2.prototype.deferredCall = function(methodName, payload) {
10035        var _this = this;
10036        return new Promise(function(resolve, reject) {
10037          var messageId = "".concat(methodName, "_").concat(generateUniqueId());
10038          _this.queueMessage({
10039            messageId,
10040            methodName,
10041            payload,
10042            resolve,
10043            reject
10044          });
10045        });
10046      };
10047      RoktManager2.prototype.sha256Hex = function(input) {
10048        return __awaiter(this, void 0, void 0, function() {
10049          var encoder, encodedInput, digest;
10050          return __generator(this, function(_a2) {
10051            switch (_a2.label) {
10052              case 0:
10053            
10053    encoder = new TextEncoder();
10054                encodedInput = encoder.encode(input);
10055                return [4, crypto.subtle.digest("SHA-256", encodedInput)];
10056              case 1:
10057                digest = _a2.sent();
10058                return [2, this.arrayBufferToHex(digest)];
10059            }
10060          });
10061        });
10062      };
10063      RoktManager2.prototype.arrayBufferToHex = function(buffer) {
10064        var bytes = new Uint8Array(buffer);
10065        var hexString = "";
10066        for (var i = 0; i < bytes.length; i++) {
10067          var hexByte = bytes[i].toString(16).padStart(2, "0");
10068          hexString += hexByte;
10069        }
10070        return hexString;
10071      };
10072      RoktManager2.prototype.hasIdentityChanged = function(currentValue, newValue) {
10073        if (!newValue) {
10074          return false;
10075        }
10076        if (!currentValue) {
10077          return true;
10078        }
10079        if (currentValue !== newValue) {
10080          return true;
10081        }
10082        return false;
10083      };
10084      return RoktManager2;
10085    })()
10086  );
10087  var CookieConsentManager = (
10088    /** @class */
10089    (function() {
10090      function CookieConsentManager2(flags) {
10091        this.flags = flags;
10092        this.flags = {
10093          noFunctional: flags.noFunctional === true,
10094          noTargeting: flags.noTargeting === true
10095        };
10096      }
10097      CookieConsentManager2.prototype.getNoTargeting = function() {
10098        return this.flags.noTargeting;
10099      };
10100      CookieConsentManager2.prototype.getNoFunctional = function() {
10101        return this.flags.noFunctional;
10102      };
10103      CookieConsentManager2.prototype.syncNoTargetingAttribute = function(user) {
10104        if (!user) return;
10105        if (this.flags.noTargeting) {
10106          user.setUserAttribute(NO_TARGETING_ATTRIBUTE, true);
10107        } else if (user.getAllUserAttributes().hasOwnProperty(NO_TARGETING_ATTRIBUTE)) {
10108          user.removeUserAttribute(NO_TARGETING_ATTRIBUTE);
10109        }
10110      };
10111      return CookieConsentManager2;
10112    })()
10113  );
10114  var ErrorReportingDispatcher = (
10115    /** @class */
10116    (function() {
10117      function ErrorReportingDispatcher2() {
10118        this.services = [];
10119      }
10120      ErrorReportingDispatcher2.prototype.register = function(service) {
10121        this.services.push(service);
10122      };
10123      ErrorReportingDispatcher2.prototype.report = function(error) {
10124        var _this = this;
10125        this.services.forEach(function(s) {
10126          var _a2;
10127          try {
10128            s.report(error);
10129          } catch (e) {
10130            (_a2 = _this.logger) === null || _a2 === void 0 ? void 0 : _a2.error("Error in ErrorReportingService: " + e);
10131          }
10132        });
10133      };
10134      return ErrorReportingDispatcher2;
10135    })()
10136  );
10137  var LoggingDispatcher = (
10138    /** @class */
10139    (function() {
10140      function LoggingDispatcher2() {
10141        this.services = [];
10142      }
10143      LoggingDispatcher2.prototype.register = function(service) {
10144        this.services.push(service);
10145      };
10146      LoggingDispatcher2.prototype.log = function(entry) {
10147        var _this = this;
10148        this.services.forEach(function(s) {
10149          var _a2;
10150          try {
10151            s.log(entry);
10152          } catch (e) {
10153            (_a2 = _this.logger) === null || _a2 === void 0 ? void 0 : _a2.error("Error in LoggingService: " + e);
10154          }
10155        });
10156      };
10157      return LoggingDispatcher2;
10158    })()
10159  );
10160  var Messages = Constants.Messages, HTTPCodes = Constants.HTTPCodes, FeatureFlags = Constants.FeatureFlags, CaptureIntegrationSpecificIdsV2Modes = Constants.CaptureIntegrationSpecificIdsV2Modes;
10161  var ReportBatching = FeatureFlags.ReportBatching, CaptureIntegrationSpecificIds = FeatureFlags.CaptureIntegrationSpecificIds, CaptureIntegrationSpecificIdsV2 = FeatureFlags.CaptureIntegrationSpecificIdsV2;
10162  var StartingInitialization = Messages.InformationMessages.StartingInitialization;
10163  function mParticleInstance(instanceName) {
10164    var self = this;
10165    this._instanceName = instanceName;
10166    this._NativeSdkHelpers = new NativeSdkHelpers(this);
10167    this._SessionManager = new SessionManager(this);
10168    this._Persistence = new _Persistence(this);
10169    this._Helpers = new Helpers(this);
10170    this._Events = new Events(this);
10171    this._CookieSyncManager = new CookieSyncManager(this);
10172    this._ServerModel = new ServerModel(this);
10173    this._Ecommerce = new Ecommerce(this);
10174    this._ForwardingStatsUploader = new forwardingStatsUploader(this);
10175    this._Consent = new Consent(this);
10176    this._IdentityAPIClient = new IdentityAPIClient(this);
10177    this._preInit = {
10178      readyQueue: [],
10179      integrationDelays: {},
10180      forwarderConstructors: []
10181    };
10182    this._ErrorReportingDispatcher = new ErrorReportingDispatcher();
10183    this._LoggingDispatcher = new LoggingDispatcher();
10184    this._RoktManager = new RoktManager();
10185    this._RoktManager.setOnReadyCallback(function() {
10186      self.processQueueOnIdentityFailure();
10187    });
10188    this.processQueueOnIdentityFailure = function() {
10189      var _a2, _b2, _c;
10190      if ((_a2 = self._Store) === null || _a2 === void 0 ? void 0 : _a2.isInitialized) {
10191        return;
10192      }
10193      if (((_b2 = self._Store) === null || _b2 === void 0 ? void 0 : _b2.identityCallFailed) && ((_c = self._RoktManager) === null || _c === void 0 ? void 0 : _c.isReady())) {
10194        self._RoktManager.processMessageQueue();
10195        self._preInit.readyQueue = processReadyQueue(self._preInit.readyQueue, self.Logger);
10196      }
10197    };
10198    this.processQueueOnNoFunctional = function() {
10199      var _a2, _b2;
10200      if ((_a2 = self._Store) === null || _a2 === void 0 ? void 0 : _a2.isInitialized) {
10201        return;
10202      }
10203      var noFunctionalWithoutId = ((_b2 = self._CookieConsentManager) === null || _b2 === void 0 ? void 0 : _b2.getNoFunctional()) && !hasExplicitIdentifier(self._Store);
10204      if (noFunctionalWithoutId) {
10205        self._preInit.readyQueue = processReadyQueue(self._preInit.readyQueue, self.Logger);
10206      }
10207    };
10208    this.IdentityType = IdentityType;
10209    this.EventType = EventType;
10210    this.CommerceEventType = CommerceEventType;
10211    this.PromotionType = PromotionActionType;
10212    this.ProductActionType = ProductActionType;
10213    this.RoktEvents = RoktEvents;
10214    this._Identity = new Identity(this);
10215    this.Identity = this._Identity.IdentityAPI;
10216    this.generateHash = this._Helpers.generateHash;
10217    this.getDeviceId = this._Persistence.getDeviceId;
10218    if (typeof window !== "undefined") {
10219      if (window.mParticle && window.mParticle.config) {
10220        if (window.mParticle.config.hasOwnProperty("rq")) {
10221          this._preInit.readyQueue = window.mParticle.config.rq;
10222        }
10223      }
10224    }
10225    this.init = function(apiKey, config) {
10226      var _this = this;
10227      if (!config) {
10228        console.warn("You did not pass a config object to init(). mParticle will not initialize properly");
10229      }
10230      runPreConfigFetchInitialization(this, apiKey, config);
10231      if (config) {
10232        if (!config.hasOwnProperty("requestConfig") || config.requestConfig) {
10233          var configApiClient = new ConfigAPIClient(apiKey, config, this);
10234          configApiClient.getSDKConfiguration().then(function(result) {
10235            var mergedConfig = extend({}, config, result);
10236            completeSDKInitialization(apiKey, mergedConfig, _this);
10237          });
10238        } else {
10239          completeSDKInitialization(apiKey, config, this);
10240        }
10241      } else {
10242        console.error("No config available on the window, please pass a config object to mParticle.init()");
10243        return;
10244      }
10245    };
10246    this.setLogLevel = function(newLogLevel) {
10247      self.Logger.setLogLevel(newLogLevel);
10248    };
10249    this.reset = function(instance) {
10250      try {
10251        instance._Persistence.resetPersistence();
10252        if (instance._Store) {
10253          delete instance._Store;
10254        }
10255      } catch (error) {
10256        console.error("Cannot reset mParticle", error);
10257      }
10258    };
10259    this._resetForTests = function(config, keepPersistence, instance) {
10260      if (instance._Store) {
10261        delete instance._Store;
10262      }
10263      instance._ErrorReportingDispatcher = new ErrorReportingDispatcher();
10264      instance._LoggingDispatcher = new LoggingDispatcher();
10265      instance.Logger = new Logger(config);
10266      instance._ErrorReportingDispatcher.logger = instance.Logger;
10267      instance._LoggingDispatcher.logger = instance.Logger;
10268      instance._Store = new Store(config, instance);
10269      instance._Store.isLocalStorageAvailable = instance._Persistence.determineLocalStorageAvailability(window.localStorage);
10270      instance._Events.stopTracking();
10271      resetPageViewTracking();
10272      instance._PageViewTracker = void 0;
10273      if (!keepPersistence) {
10274        instance._Persistence.resetPersistence();
10275      }
10276      instance._Persistence.forwardingStatsBatches.uploadsTable = {};
10277      instance._Persistence.forwardingStatsBatches.forwardingStatsEventQueue = [];
10278      instance._preInit = {
10279        readyQueue: [],
10280        pixelConfigurations: [],
10281        integrationDelays: {},
10282        forwarderConstructors: [],
10283        isDevelopmentMode: false
10284      };
10285    };
10286    this.ready = function(f) {
10287      var _a2, _b2, _c;
10288      var noFunctionalWithoutId = ((_a2 = self._CookieConsentManager) === null || _a2 === void 0 ? void 0 : _a2.getNoFunctional()) && !hasExplicitIdentifier(self._Store);
10289      var shouldExecute = isFunction(f) && (((_b2 = self._Store) === null || _b2 === void 0 ? void 0 : _b2.isInitialized) || ((_c = self._Store) === null || _c === void 0 ? void 0 : _c.identityCallFailed) && self._RoktManager.isReady() || noFunctionalWithoutId);
10290      if (shouldExecute) {
10291        f();
10292      } else {
10293        self._preInit.readyQueue.push(f);
10294      }
10295    };
10296    this.getEnvironment = function() {
10297      return self._Store.SDKConfig.isDevelopmentMode ? Constants.Environment.Development : Constants.Environment.Production;
10298    };
10299    this.getVersion = function() {
10300      return Constants.sdkVersion;
10301    };
10302    this.setAppVersion = function(version2) {
10303      var queued = queueIfNotInitialized(function() {
10304        self.setAppVersion(version2);
10305      }, self);
10306      if (queued) return;
10307      self._Store.SDKConfig.appVersion = version2;
10308      self._Persistence.update();
10309    };
10310    this.setDeviceId = function(guid) {
10311      var queued = queueIfNotInitialized(function() {
10312        self.setDeviceId(guid);
10313      }, self);
10314      if (queued) return;
10315      this._Store.setDeviceId(guid);
10316    };
10317    this.isInitialized = function() {
10318      return self._Store ? self._Store.isInitialized : false;
10319    };
10320    this.getAppName = function() {
10321      return self._Store.SDKConfig.appName;
10322    };
10323    this.setAppName = function(name) {
10324      var queued = queueIfNotInitialized(function() {
10325        self.setAppName(name);
10326      }, self);
10327      if (queued) return;
10328      self._Store.SDKConfig.appName = name;
10329    };
10330    this.getAppVersion = function() {
10331      return self._Store.SDKConfig.appVersion;
10332    };
10333    this.stopTrackingLocation = function() {
10334      self._SessionManager.resetSessionTimer();
10335      self._Events.stopTracking();
10336    };
10337    this.startTrackingLocation = function(callback) {
10338      if (!isFunction(callback)) {
10339        self.Logger.warning("Warning: Location tracking is triggered, but not including a callback into the `startTrackingLocation` may result in events logged too quickly and not being associated with a location.");
10340      }
10341      self._SessionManager.resetSessionTimer();
10342      self._Events.startTracking(callback);
10343    };
10344    this.setPosition = function(lat, lng) {
10345      var queued = queueIfNotInitialized(function() {
10346        self.setPosition(lat, lng);
10347      }, self);
10348      if (queued) return;
10349      self._SessionManager.resetSessionTimer();
10350      if (typeof lat === "number" && typeof lng === "number") {
10351        self._Store.currentPosition = {
10352          lat,
10353          lng
10354        };
10355      } else {
10356        self.Logger.error("Position latitude and/or longitude must both be of type number");
10357      }
10358    };
10359    this.startNewSession = function() {
10360      self._SessionManager.startNewSession();
10361    };
10362    this.endSession = function() {
10363      self._SessionManager.endSession(true);
10364    };
10365    this.logBaseEvent = function(event, eventOptions) {
10366      var queued = queueIfNotInitialized(function() {
10367        self.logBaseEvent(event, eventOptions);
10368      }, self);
10369      if (queued) return;
10370      self._SessionManager.resetSessionTimer();
10371      if (typeof event.name !== "string") {
10372        self.Logger.error(Messages.ErrorMessages.EventNameInvalidType);
10373        return;
10374      }
10375      if (!event.eventType) {
10376        event.eventType = EventType.Unknown;
10377      }
10378      if (!self._Helpers.canLog()) {
10379        self.Logger.error(Messages.ErrorMessages.LoggingDisabled);
10380        return;
10381      }
10382      self._Events.logEvent(event, eventOptions);
10383    };
10384    this.logEvent = function(eventName, eventType, eventInfo, customFlags, eventOptions) {
10385      var queued = queueIfNotInitialized(function() {
10386        self.logEvent(eventName, eventType, eventInfo, customFlags, eventOptions);
10387      }, self);
10388      if (queued) return;
10389      self._SessionManager.resetSessionTimer();
10390      if (typeof eventName !== "string") {
10391        self.Logger.error(Messages.ErrorMessages.EventNameInvalidType);
10392        return;
10393      }
10394      if (!eventType) {
10395        eventType = EventType.Unknown;
10396      }
10397      if (!self._Helpers.isEventType(eventType)) {
10398        self.Logger.error("Invalid event type: " + eventType + ", must be one of: \n" + JSON.stringify(EventType));
10399        return;
10400      }
10401      if (!self._Helpers.canLog()) {
10402        self.Logger.error(Messages.ErrorMessages.LoggingDisabled);
10403        return;
10404      }
10405      self._Events.logEvent({
10406        messageType: MessageType$1.PageEvent,
10407        name: eventName,
10408        data: eventInfo,
10409        eventType,
10410        customFlags
10411      }, eventOptions);
10412    };
10413    this.logError = function(error, attrs) {
10414      var queued = queueIfNotInitialized(function() {
10415        self.logError(error, attrs);
10416      }, self);
10417      if (queued) return;
10418      self._SessionManager.resetSessionTimer();
10419      if (!error) {
10420        return;
10421      }
10422      if (typeof error === "string") {
10423        error = {
10424          message: error
10425        };
10426      }
10427      var data = {
10428        m: error.message ? error.message : error,
10429        s: "Error",
10430        t: error.stack || null
10431      };
10432      if (attrs) {
10433        var sanitized = self._Helpers.sanitizeAttributes(attrs, data.m);
10434        for (var prop in sanitized) {
10435          data[prop] = sanitized[prop];
10436        }
10437      }
10438      self._Events.logEvent({
10439        messageType: MessageType$1.CrashReport,
10440        name: error.name ? error.name : "Error",
10441        eventType: EventType.Other,
10442        data
10443      });
10444    };
10445    this.logLink = function(selector, eventName, eventType, eventInfo) {
10446      self._Events.addEventHandler("click", selector, eventName, eventInfo, eventType);
10447    };
10448    this.logForm = function(selector, eventName, eventType, eventInfo) {
10449      self._Events.addEventHandler("submit", selector, eventName, eventInfo, eventType);
10450    };
10451    this.logPageView = function(eventName, attrs, customFlags, eventOptions) {
10452      var queued = queueIfNotInitialized(function() {
10453        self.logPageView(eventName, attrs, customFlags, eventOptions);
10454      }, self);
10455      if (queued) return;
10456      self._SessionManager.resetSessionTimer();
10457      if (self._Helpers.canLog()) {
10458        if (!self._Helpers.Validators.isStringOrNumber(eventName)) {
10459          eventName = "PageView";
10460        }
10461        if (!attrs) {
10462          attrs = {
10463            hostname: window.location.hostname,
10464            title: window.document.title
10465          };
10466        } else if (!self._Helpers.isObject(attrs)) {
10467          self.Logger.error("The attributes argument must be an object. A " + _typeof(attrs) + " was entered. Please correct and retry.");
10468          return;
10469        }
10470        if (customFlags && !self._Helpers.isObject(customFlags)) {
10471          self.Logger.error("The customFlags argument must be an object. A " + _typeof(customFlags) + " was entered. Please correct and retry.");
10472          return;
10473        }
10474      }
10475      self._Events.logEvent({
10476        messageType: MessageType$1.PageView,
10477        name: eventName,
10478        data: attrs,
10479        eventType: EventType.Unknown,
10480        customFlags
10481      }, eventOptions);
10482    };
10483    this.upload = function() {
10484      var _a2, _b2;
10485      if (self._Helpers.canLog()) {
10486        if (self._Store.webviewBridgeEnabled) {
10487          self._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.Upload);
10488        } else {
10489          (_b2 = (_a2 = self._APIClient) === null || _a2 === void 0 ? void 0 : _a2.uploader) === null || _b2 === void 0 ? void 0 : _b2.prepareAndUpload(false, false);
10490        }
10491      }
10492    };
10493    this.Consent = {
10494      /**
10495       * Creates a CCPA Opt Out Consent State.
10496       *
10497       * @method createCCPAConsent
10498       * @param {Boolean} optOut true represents a "data sale opt-out", false represents the user declining a "data sale opt-out"
10499       * @param {Number} timestamp Unix time (likely to be Date.now())
10500       * @param {String} consentDocument document version or experience that the user may have consented to
10501       * @param {String} location location where the user gave consent
10502       * @param {String} hardwareId hardware ID for the device or browser used to give consent. This property exists only to provide additional context and is not used to identify users
10503       * @return {Object} CCPA Consent State
10504       */
10505      createCCPAConsent: self._Consent.createPrivacyConsent,
10506      /**
10507       * Creates a GDPR Consent State.
10508       *
10509       * @method createGDPRConsent
10510       * @param {Boolean} consent true represents a "data sale opt-out", false represents the user declining a "data sale opt-out"
10511       * @param {Number} timestamp Unix time (likely to be Date.now())
10512       * @param {String} consentDocument document version or experience that the user may have consented to
10513       * @param {String} location location where the user gave consent
10514       * @param {String} hardwareId hardware ID for the device or browser used to give consent. This property exists only to provide additional context and is not used to identify users
10515       * @return {Object} GDPR Consent State
10516       */
10517      createGDPRConsent: self._Consent.createPrivacyConsent,
10518      /**
10519       * Creates a Consent State Object, which can then be used to set CCPA states, add multiple GDPR states, as well as get and remove these privacy states.
10520       *
10521       * @method createConsentState
10522       * @return {Object} ConsentState object
10523       */
10524      createConsentState: self._Consent.createConsentState
10525    };
10526    this.eCommerce = {
10527      /**
10528       * Invoke these methods on the mParticle.eCommerce.Cart object.
10529       * Example: mParticle.eCommerce.Cart.add(...)
10530       * @class mParticle.eCommerce.Cart
10531       * @deprecated
10532       */
10533      Cart: {
10534        /**
10535         * Adds a product to the cart
10536         * @method add
10537         * @param {Object} product The product you want to add to the cart
10538         * @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs.
10539         * @deprecated
10540         */
10541        add: function add(product, logEventBoolean) {
10542          logDeprecatedMethodUsage({
10543            methodName: "mPInstance.eCommerce.Cart.add()",
10544            warningMessage: generateDeprecationMessage("eCommerce.Cart.add()", true, "eCommerce.logProductAction()", "https://docs.mparticle.com/developers/sdk/web/commerce-tracking")
10545          }, self.Logger, self._ErrorReportingDispatcher);
10546        },
10547        /**
10548         * Removes a product from the cart
10549         * @method remove
10550         * @param {Object} product The product you want to add to the cart
10551         * @param {Boolean} [logEventBoolean] Option to log the event to mParticle's servers. If blank, no logging occurs.
10552         * @deprecated
10553         */
10554        remove: function remove(product, logEventBoolean) {
10555          logDeprecatedMethodUsage({
10556            methodName: "mPInstance.eCommerce.Cart.remove()",
10557            warningMessage: generateDeprecationMessage("eCommerce.Cart.remove()", true, "eCommerce.logProductAction()", "https://docs.mparticle.com/developers/sdk/web/commerce-tracking")
10558          }, self.Logger, self._ErrorReportingDispatcher);
10559        },
10560        /**
10561         * Clears the cart
10562         * @method clear
10563         * @deprecated
10564         */
10565        clear: function clear() {
10566          logDeprecatedMethodUsage({
10567            methodName: "mPInstance.eCommerce.Cart.clear()",
10568            warningMessage: generateDeprecationMessage("eCommerce.Cart.clear()", true, "", "https://docs.mparticle.com/developers/sdk/web/commerce-tracking")
10569          }, self.Logger, self._ErrorReportingDispatcher);
10570        }
10571      },
10572      /**
10573       * Sets the currency code
10574       * @for mParticle.eCommerce
10575       * @method setCurrencyCode
10576       * @param {String} code The currency code
10577       */
10578      setCurrencyCode: function setCurrencyCode(code) {
10579        var queued = queueIfNotInitialized(function() {
10580          self.eCommerce.setCurrencyCode(code);
10581        }, self);
10582        if (queued) return;
10583        if (typeof code !== "string") {
10584          self.Logger.error("Code must be a string");
10585          return;
10586        }
10587        self._SessionManager.resetSessionTimer();
10588        self._Store.currencyCode = code;
10589      },
10590      /**
10591       * Creates a product
10592       * @for mParticle.eCommerce
10593       * @method createProduct
10594       * @param {String} name product name
10595       * @param {String} sku product sku
10596       * @param {Number} price product price
10597       * @param {Number} [quantity] product quantity. If blank, defaults to 1.
10598       * @param {String} [variant] product variant
10599       * @param {String} [category] product category
10600       * @param {String} [brand] product brand
10601       * @param {Number} [position] product position
10602       * @param {String} [coupon] product coupon
10603       * @param {Object} [attributes] product attributes
10604       */
10605      createProduct: function createProduct(name, sku, price, quantity, variant, category, brand, position, coupon, attributes) {
10606        return self._Ecommerce.createProduct(name, sku, price, quantity, variant, category, brand, position, coupon, attributes);
10607      },
10608      /**
10609       * Creates a promotion
10610       * @for mParticle.eCommerce
10611       * @method createPromotion
10612       * @param {String} id a unique promotion id
10613       * @param {String} [creative] promotion creative
10614       * @param {String} [name] promotion name
10615       * @param {Number} [position] promotion position
10616       */
10617      createPromotion: function createPromotion(id, creative, name, position) {
10618        return self._Ecommerce.createPromotion(id, creative, name, position);
10619      },
10620      /**
10621       * Creates a product impression
10622       * @for mParticle.eCommerce
10623       * @method createImpression
10624       * @param {String} name impression name
10625       * @param {Object} product the product for which an impression is being created
10626       */
10627      createImpression: function createImpression(name, product) {
10628        return self._Ecommerce.createImpression(name, product);
10629      },
10630      /**
10631       * Creates a transaction attributes object to be used with a checkout
10632       * @for mParticle.eCommerce
10633       * @method createTransactionAttributes
10634       * @param {String or Number} id a unique transaction id
10635       * @param {String} [affiliation] affilliation
10636       * @param {String} [couponCode] the coupon code for which you are creating transaction attributes
10637       * @param {Number} [revenue] total revenue for the product being purchased
10638       * @param {String} [shipping] the shipping method
10639       * @param {Number} [tax] the tax amount
10640       */
10641      createTransactionAttributes: function createTransactionAttributes(id, affiliation, couponCode, revenue, shipping, tax) {
10642        return self._Ecommerce.createTransactionAttributes(id, affiliation, couponCode, revenue, shipping, tax);
10643      },
10644      /**
10645       * Logs a checkout action
10646       * @for mParticle.eCommerce
10647       * @method logCheckout
10648       * @param {Number} step checkout step number
10649       * @param {String} checkout option string
10650       * @param {Object} attrs
10651       * @param {Object} [customFlags] Custom flags for the event
10652       * @deprecated
10653       */
10654      logCheckout: function logCheckout(step, option, attrs, customFlags) {
10655        logDeprecatedMethodUsage({
10656          methodName: "mParticle.logCheckout",
10657          warningMessage: "mParticle.logCheckout is deprecated, please use mParticle.logProductAction instead"
10658        }, self.Logger, self._ErrorReportingDispatcher);
10659        if (!self._Store.isInitialized) {
10660          self.ready(function() {
10661            self.eCommerce.logCheckout(step, option, attrs, customFlags);
10662          });
10663          return;
10664        }
10665        self._SessionManager.resetSessionTimer();
10666        self._Events.logCheckoutEvent(step, option, attrs, customFlags);
10667      },
10668      /**
10669       * Logs a product action
10670       * @for mParticle.eCommerce
10671       * @method logProductAction
10672       * @param {Number} productActionType product action type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L206-L218)
10673       * @param {Object} product the product for which you are creating the product action
10674       * @param {Object} [attrs] attributes related to the product action
10675       * @param {Object} [customFlags] Custom flags for the event
10676       * @param {Object} [transactionAttributes] Transaction Attributes for the event
10677       * @param {Object} [eventOptions] For Event-level Configuration Options
10678       */
10679      logProductAction: function logProductAction(productActionType, product, attrs, customFlags, transactionAttributes, eventOptions) {
10680        var queued = queueIfNotInitialized(function() {
10681          self.eCommerce.logProductAction(productActionType, product, attrs, customFlags, transactionAttributes, eventOptions);
10682        }, self);
10683        if (queued) return;
10684        self._SessionManager.resetSessionTimer();
10685        self._Events.logProductActionEvent(productActionType, product, attrs, customFlags, transactionAttributes, eventOptions);
10686      },
10687      /**
10688       * Logs a product purchase
10689       * @for mParticle.eCommerce
10690       * @method logPurchase
10691       * @param {Object} transactionAttributes transactionAttributes object
10692       * @param {Object} product the product being purchased
10693       * @param {Boolean} [clearCart] boolean to clear the cart after logging or not. Defaults to false
10694       * @param {Object} [attrs] other attributes related to the product purchase
10695       * @param {Object} [customFlags] Custom flags for the event
10696       * @deprecated
10697       */
10698      logPurchase: function logPurchase(transactionAttributes, product, clearCart, attrs, customFlags) {
10699        logDeprecatedMethodUsage({
10700          methodName: "mParticle.logPurchase",
10701          warningMessage: "mParticle.logPurchase is deprecated, please use mParticle.logProductAction instead"
10702        }, self.Logger, self._ErrorReportingDispatcher);
10703        if (!self._Store.isInitialized) {
10704          self.ready(function() {
10705            self.eCommerce.logPurchase(transactionAttributes, product, clearCart, attrs, customFlags);
10706          });
10707          return;
10708        }
10709        if (!transactionAttributes || !product) {
10710          self.Logger.error(Messages.ErrorMessages.BadLogPurchase);
10711          return;
10712        }
10713        self._SessionManager.resetSessionTimer();
10714        self._Events.logPurchaseEvent(transactionAttributes, product, attrs, customFlags);
10715      },
10716      /**
10717       * Logs a product promotion
10718       * @for mParticle.eCommerce
10719       * @method logPromotion
10720       * @param {Number} type the promotion type as found [here](https://github.com/mParticle/mparticle-sdk-javascript/blob/master-v2/src/types.js#L275-L279)
10721       * @param {Object} promotion promotion object
10722       * @param {Object} [attrs] boolean to clear the cart after logging or not
10723       * @param {Object} [customFlags] Custom flags for the event
10724       * @param {Object} [eventOptions] For Event-level Configuration Options
10725       */
10726      logPromotion: function logPromotion(type, promotion, attrs, customFlags, eventOptions) {
10727        var queued = queueIfNotInitialized(function() {
10728          self.eCommerce.logPromotion(type, promotion, attrs, customFlags, eventOptions);
10729        }, self);
10730        if (queued) return;
10731        self._SessionManager.resetSessionTimer();
10732        self._Events.logPromotionEvent(type, promotion, attrs, customFlags, eventOptions);
10733      },
10734      /**
10735       * Logs a product impression
10736       * @for mParticle.eCommerce
10737       * @method logImpression
10738       * @param {Object} impression product impression object
10739       * @param {Object} attrs attributes related to the impression log
10740       * @param {Object} [customFlags] Custom flags for the event
10741       * @param {Object} [eventOptions] For Event-level Configuration Options
10742       */
10743      logImpression: function logImpression(impression, attrs, customFlags, eventOptions) {
10744        var queued = queueIfNotInitialized(function() {
10745          self.eCommerce.logImpression(impression, attrs, customFlags, eventOptions);
10746        }, self);
10747        if (queued) return;
10748        self._SessionManager.resetSessionTimer();
10749        self._Events.logImpressionEvent(impression, attrs, customFlags, eventOptions);
10750      },
10751      /**
10752       * Logs a refund
10753       * @for mParticle.eCommerce
10754       * @method logRefund
10755       * @param {Object} transactionAttributes transaction attributes related to the refund
10756       * @param {Object} product product being refunded
10757       * @param {Boolean} [clearCart] boolean to clear the cart after refund is logged. Defaults to false.
10758       * @param {Object} [attrs] attributes related to the refund
10759       * @param {Object} [customFlags] Custom flags for the event
10760       * @deprecated
10761       */
10762      logRefund: function logRefund(transactionAttributes, product, clearCart, attrs, customFlags) {
10763        logDeprecatedMethodUsage({
10764          methodName: "mParticle.logRefund",
10765          warningMessage: "mParticle.logRefund is deprecated, please use mParticle.logProductAction instead"
10766        }, self.Logger, self._ErrorReportingDispatcher);
10767        if (!self._Store.isInitialized) {
10768          self.ready(function() {
10769            self.eCommerce.logRefund(transactionAttributes, product, clearCart, attrs, customFlags);
10770          });
10771          return;
10772        }
10773        self._SessionManager.resetSessionTimer();
10774        self._Events.logRefundEvent(transactionAttributes, product, attrs, customFlags);
10775      },
10776      expandCommerceEvent: function expandCommerceEvent(event) {
10777        return self._Ecommerce.expandCommerceEvent(event);
10778      }
10779    };
10780    this.setSessionAttribute = function(key, value) {
10781      var _a2;
10782      var skipQueue = ((_a2 = self._CookieConsentManager) === null || _a2 === void 0 ? void 0 : _a2.getNoFunctional()) && !hasExplicitIdentifier(self._Store);
10783      if (!skipQueue) {
10784        var queued = queueIfNotInitialized(function() {
10785          self.setSessionAttribute(key, value);
10786        }, self);
10787        if (queued) return;
10788      }
10789      if (self._Helpers.canLog()) {
10790        if (!self._Helpers.Validators.isValidAttributeValue(value)) {
10791          self.Logger.error(Messages.ErrorMessages.BadAttribute);
10792          return;
10793        }
10794        if (!self._Helpers.Validators.isValidKeyValue(key)) {
10795          self.Logger.error(Messages.ErrorMessages.BadKey);
10796          return;
10797        }
10798        if (self._Store.webviewBridgeEnabled) {
10799          self._NativeSdkHelpers.sendToNative(Constants.NativeSdkPaths.SetSessionAttribute, JSON.stringify({
10800            key,
10801            value
10802          }));
10803        } else {
10804          var existingProp = self._Helpers.findKeyInObject(self._Store.sessionAttributes, key);
10805          if (existingProp) {
10806            key = existingProp;
10807          }
10808          self._Store.sessionAttributes[key] = value;
10809          self._Persistence.update();
10810          self._Forwarders.applyToForwarders("setSessionAttribute", [key, value]);
10811        }
10812      }
10813    };
10814    this.setOptOut = function(isOptingOut) {
10815      var queued = queueIfNotInitialized(function() {
10816        self.setOptOut(isOptingOut);
10817      }, self);
10818      if (queued) return;
10819      self._SessionManager.resetSessionTimer();
10820      self._Store.isEnabled = !isOptingOut;
10821      self._Events.logOptOut();
10822      self._Persistence.update();
10823      if (self._Store.activeForwarders.length) {
10824        self._Store.activeForwarders.forEach(function(forwarder) {
10825          if (forwarder.setOptOut) {
10826            var result = forwarder.setOptOut(isOptingOut);
10827            if (result) {
10828              self.Logger.verbose(result);
10829            }
10830          }
10831        });
10832      }
10833    };
10834    this.setIntegrationAttribute = function(integrationId, attrs) {
10835      var queued = queueIfNotInitialized(function() {
10836        self.setIntegrationAttribute(integrationId, attrs);
10837      }, self);
10838      if (queued) return;
10839      if (typeof integrationId !== "number") {
10840        self.Logger.error("integrationId must be a number");
10841        return;
10842      }
10843      if (attrs === null) {
10844        self._Store.integrationAttributes[integrationId] = {};
10845      } else if (self._Helpers.isObject(attrs)) {
10846        if (Object.keys(attrs).length === 0) {
10847          self._Store.integrationAttributes[integrationId] = {};
10848        } else {
10849          for (var key in attrs) {
10850            if (typeof key === "string") {
10851              if (typeof attrs[key] === "string") {
10852                if (self._Helpers.isObject(self._Store.integrationAttributes[integrationId])) {
10853                  self._Store.integrationAttributes[integrationId][key] = attrs[key];
10854                } else {
10855                  self._Store.integrationAttributes[integrationId] = {};
10856                  self._Store.integrationAttributes[integrationId][key] = attrs[key];
10857                }
10858              } else {
10859                self.Logger.error("Values for integration attributes must be strings. You entered a " + _typeof(attrs[key]));
10860                continue;
10861              }
10862            } else {
10863              self.Logger.error("Keys must be strings, you entered a " + _typeof(key));
10864              continue;
10865            }
10866          }
10867        }
10868      } else {
10869        self.Logger.error("Attrs must be an object with keys and values. You entered a " + _typeof(attrs));
10870        return;
10871      }
10872      self._Persistence.update();
10873    };
10874    this.getIntegrationAttributes = function(integrationId) {
10875      if (self._Store.integrationAttributes[integrationId]) {
10876        return self._Store.integrationAttributes[integrationId];
10877      } else {
10878        return {};
10879      }
10880    };
10881    this.addForwarder = function(forwarder) {
10882      self._preInit.forwarderConstructors.push(forwarder);
10883    };
10884    this.configurePixel = function(settings) {
10885      self._Forwarders.configurePixel(settings);
10886    };
10887    this._getActiveForwarders = function() {
10888      return self._Store.activeForwarders;
10889    };
10890    this._getIntegrationDelays = function() {
10891      return self._preInit.integrationDelays;
10892    };
10893    this._setIntegrationDelay = function(module, shouldDelayIntegration) {
10894      self._preInit.integrationDelays[module] = shouldDelayIntegration;
10895      if (shouldDelayIntegration === true) {
10896        return;
10897      }
10898      var integrationDelaysKeys = Object.keys(self._preInit.integrationDelays);
10899      if (integrationDelaysKeys.length === 0) {
10900        return;
10901      }
10902      var hasIntegrationDelays = integrationDelaysKeys.some(function(integration) {
10903        return self._preInit.integrationDelays[integration] === true;
10904      });
10905      if (!hasIntegrationDelays) {
10906        self._APIClient.processQueuedEvents();
10907      }
10908    };
10909    this._setWrapperSDKInfo = function(name, version2) {
10910      var queued = queueIfNotInitialized(function() {
10911        self._setWrapperSDKInfo(name, version2);
10912      }, self);
10913      if (queued) return;
10914      if (self._Store.wrapperSDKInfo === void 0 || !self._Store.wrapperSDKInfo.isInfoSet) {
10915        self._Store.wrapperSDKInfo = {
10916          name,
10917          version: version2,
10918          isInfoSet: true
10919        };
10920      }
10921    };
10922    this._registerErrorReportingService = function(service) {
10923      self._ErrorReportingDispatcher.register(service);
10924    };
10925    this._registerLoggingService = function(service) {
10926      self._LoggingDispatcher.register(service);
10927    };
10928    var launcherInstanceGuidKey = Constants.Rokt.LauncherInstanceGuidKey;
10929    this.setLauncherInstanceGuid = function() {
10930      if (!window[launcherInstanceGuidKey] || typeof window[launcherInstanceGuidKey] !== "string") {
10931        window[launcherInstanceGuidKey] = self._Helpers.generateUniqueId();
10932      }
10933    };
10934    this.getLauncherInstanceGuid = function() {
10935      return window[launcherInstanceGuidKey];
10936    };
10937    this.captureTiming = function(metricsName) {
10938      var _a2;
10939      if (typeof window !== "undefined" && ((_a2 = window.performance) === null || _a2 === void 0 ? void 0 : _a2.mark)) {
10940        window.performance.mark(metricsName);
10941      }
10942    };
10943  }
10944  function completeSDKInitialization(apiKey, config, mpInstance) {
10945    var _a2, _b2, _c, _d;
10946    var kitBlocker = createKitBlocker(config, mpInstance);
10947    var getFeatureFlag = mpInstance._Helpers.getFeatureFlag;
10948    var AutoLogPageView = Constants.FeatureFlags.AutoLogPageView;
10949    if ((_a2 = mpInstance._APIClient) === null || _a2 === void 0 ? void 0 : _a2.uploader) {
10950      mpInstance._APIClient.uploader.destroy();
10951    }
10952    mpInstance._APIClient = new APIClient(mpInstance, kitBlocker);
10953    mpInstance._Forwarders = new Forwarders(mpInstance, kitBlocker);
10954    mpInstance._Store.processConfig(config);
10955    mpInstance._Identity.idCache = createIdentityCache(mpInstance);
10956    removeExpiredIdentityCacheDates(mpInstance._Identity.idCache);
10957    if (mpInstance._Store.webviewBridgeEnabled) {
10958      mpInstance._NativeSdkHelpers.initializeSessionAttributes(apiKey);
10959    } else {
10960      mpInstance._Persistence.initializeStorage();
10961      mpInstance._Store.syncPersistenceData();
10962      var currentUser = mpInstance.Identity.getCurrentUser();
10963      var currentUserMPID = currentUser ? currentUser.getMPID() : null;
10964      var currentUserIdentities = currentUser ? currentUser.getUserIdentities().userIdentities : {};
10965      mpInstance._Store.SDKConfig.identifyRequest = mpInstance._Store.hasInvalidIdentifyRequest() ? {
10966        userIdentities: currentUserIdentities
10967      } : mpInstance._Store.SDKConfig.identifyRequest;
10968      if (getFeatureFlag(ReportBatching)) {
10969        mpInstance._ForwardingStatsUploader.startForwardingStatsTimer();
10970      }
10971      var integrationSpecificIds = getFeatureFlag(CaptureIntegrationSpecificIds);
10972      var integrationSpecificIdsV2 = getFeatureFlag(CaptureIntegrationSpecificIdsV2);
10973      var isIntegrationCaptureEnabled = integrationSpecificIdsV2 && integrationSpecificIdsV2 !== CaptureIntegrationSpecificIdsV2Modes.None || integrationSpecificIds === true;
10974      if (isIntegrationCaptureEnabled) {
10975        var captureMode = void 0;
10976        if (integrationSpecificIds || integrationSpecificIdsV2 === CaptureIntegrationSpecificIdsV2Modes.All) {
10977          captureMode = "all";
10978        } else if (integrationSpecificIdsV2 === CaptureIntegrationSpecificIdsV2Modes.RoktOnly) {
10979          captureMode = "roktonly";
10980        }
10981        mpInstance._IntegrationCapture = new IntegrationCapture(captureMode);
10982        mpInstance._IntegrationCapture.capture();
10983      }
10984      var roktConfig = parseConfig(config, "Rokt", 181);
10985      if (roktConfig) {
10986        var accountId = (_b2 = roktConfig.settings) === null || _b2 === void 0 ? void 0 : _b2.accountId;
10987        mpInstance._Store.setRoktAccountId(accountId);
10988        var userAttributeFilters = roktConfig.userAttributeFilters;
10989        var roktFilteredUser = filteredMparticleUser(currentUserMPID, {
10990          userAttributeFilters
10991        }, mpInstance);
10992        var roktOptions = {
10993          sandbox: config === null || config === void 0 ? void 0 : config.isDevelopmentMode,
10994          launcherOptions: config === null || config === void 0 ? void 0 : config.launcherOptions,
10995          domain: config === null || config === void 0 ? void 0 : config.domain
10996        };
10997        mpInstance._RoktManager.init(roktConfig, roktFilteredUser, mpInstance.Identity, mpInstance._Store, mpInstance.Logger, roktOptions, mpInstance.captureTiming, mpInstance._ErrorReportingDispatcher, mpInstance._LoggingDispatcher, mpInstance._IntegrationCapture);
10998      }
10999      mpInstance._Forwarders.processForwarders(config, mpInstance._APIClient.prepareForwardingStats);
11000      mpInstance._Forwarders.processPixelConfigs(config);
11001      mpInstance._SessionManager.initialize();
11002      mpInstance._Events.logAST();
11003      if (getFeatureFlag(AutoLogPageView)) {
11004        if (!mpInstance._PageViewTracker) {
11005          mpInstance.Logger.verbose("mParticle APV: [sdk-init] creating new PageViewTracker for this instance");
11006          mpInstance._PageViewTracker = new PageViewTracker(mpInstance);
11007        }
11008        if (hasInitialPageViewFired()) {
11009          mpInstance.Logger.verbose("mParticle APV: [sdk-init] initial page view already logged this page load, skipping");
11010        } else {
11011          markInitialPageViewFired();
11012          mpInstance._Events.logPageView();
11013        }
11014        mpInstance._PageViewTracker.init();
11015      } else if (mpInstance._PageViewTracker) {
11016        mpInstance._PageViewTracker.teardown();
11017      }
11018      processIdentityCallback(mpInstance, currentUser, currentUserMPID, currentUserIdentities);
11019    }
11020    if (mpInstance._Store.mpid && !mpInstance._Store.identifyCalled || mpInstance._Store.webviewBridgeEnabled) {
11021      mpInstance._Store.isInitialized = true;
11022      (_c = mpInstance._CookieConsentManager) === null || _c === void 0 ? void 0 : _c.syncNoTargetingAttribute(mpInstance.Identity.getCurrentUser());
11023      mpInstance._preInit.readyQueue = processReadyQueue(mpInstance._preInit.readyQueue, mpInstance.Logger);
11024    }
11025    (_d = mpInstance.processQueueOnNoFunctional) === null || _d === void 0 ? void 0 : _d.call(mpInstance);
11026    if (mpInstance._Store.isFirstRun) {
11027      mpInstance._Store.isFirstRun = false;
11028    }
11029  }
11030  function createKitBlocker(config, mpInstance) {
11031    var kitBlocker;
11032    var dataPlanForKitBlocker;
11033    var kitBlockError;
11034    var kitBlockOptions;
11035    if (config.dataPlanOptions) {
11036      mpInstance.Logger.verbose("Customer provided data plan found");
11037      kitBlockOptions = config.dataPlanOptions;
11038      dataPlanForKitBlocker = {
11039        document: {
11040          dtpn: {
11041            vers: kitBlockOptions.dataPlanVersion,
11042            blok: {
11043              ev: kitBlockOptions.blockEvents,
11044              ea: kitBlockOptions.blockEventAttributes,
11045              ua: kitBlockOptions.blockUserAttributes,
11046              id: kitBlockOptions.blockUserIdentities
11047            }
11048          }
11049        }
11050      };
11051    }
11052    if (!dataPlanForKitBlocker) {
11053      if (config.dataPlan && config.dataPlan.document) {
11054        if (config.dataPlan.document.error_message) {
11055          kitBlockError = config.dataPlan.document.error_message;
11056        } else {
11057          mpInstance.Logger.verbose("Data plan found from mParticle.js");
11058          dataPlanForKitBlocker = config.dataPlan;
11059        }
11060      } else if (config.dataPlanResult) {
11061        if (config.dataPlanResult.error_message) {
11062          kitBlockError = config.dataPlanResult.error_message;
11063        } else {
11064          mpInstance.Logger.verbose("Data plan found from /config");
11065          dataPlanForKitBlocker = {
11066            document: config.dataPlanResult
11067          };
11068        }
11069      }
11070    }
11071    if (kitBlockError) {
11072      mpInstance.Logger.error(kitBlockError);
11073    }
11074    if (dataPlanForKitBlocker) {
11075      kitBlocker = new KitBlocker(dataPlanForKitBlocker, mpInstance);
11076    }
11077    return kitBlocker;
11078  }
11079  function createIdentityCache(mpInstance) {
11080    var _a2;
11081    if ((_a2 = mpInstance._CookieConsentManager) === null || _a2 === void 0 ? void 0 : _a2.getNoFunctional()) {
11082      return new DisabledVault("".concat(mpInstance._Store.storageName, "-id-cache"));
11083    }
11084    return new LocalStorageVault("".concat(mpInstance._Store.storageName, "-id-cache"));
11085  }
11086  function runPreConfigFetchInitialization(mpInstance, apiKey, config) {
11087    mpInstance.Logger = new Logger(config);
11088    mpInstance._ErrorReportingDispatcher.logger = mpInstance.Logger;
11089    mpInstance._LoggingDispatcher.logger = mpInstance.Logger;
11090    mpInstance._Store = new Store(config, mpInstance, apiKey);
11091    window.mParticle.Store = mpInstance._Store;
11092    mpInstance.Logger.verbose(StartingInitialization);
11093    var _a2 = normalizeRoktLauncherOptions(config === null || config === void 0 ? void 0 : config.launcherOptions), noFunctional = _a2.noFunctional, noTargeting = _a2.noTargeting;
11094    mpInstance._CookieConsentManager = new CookieConsentManager({
11095      noFunctional,
11096      noTargeting
11097    });
11098    try {
11099      mpInstance._Store.isLocalStorageAvailable = mpInstance._Persistence.determineLocalStorageAvailability(window.localStorage);
11100    } catch (e) {
11101      mpInstance.Logger.warning("localStorage is not available, using cookies if available");
11102      mpInstance._Store.isLocalStorageAvailable = false;
11103    }
11104  }
11105  function processIdentityCallback(mpInstance, currentUser, currentUserMPID, currentUserIdentities) {
11106    if (!mpInstance._Store.identifyCalled && mpInstance._Store.SDKConfig.identityCallback && currentUser && currentUserMPID) {
11107      mpInstance._Store.SDKConfig.identityCallback({
11108        httpCode: HTTPCodes.activeSession,
11109        getUser: function getUser() {
11110          return mpInstance._Identity.mParticleUser(currentUserMPID);
11111        },
11112        getPreviousUser: function getPreviousUser() {
11113          var users = mpInstance.Identity.getUsers();
11114          var mostRecentUser = users.shift();
11115          var mostRecentUserMPID = mostRecentUser.getMPID();
11116          if (mostRecentUser && mostRecentUserMPID === currentUserMPID) {
11117            mostRecentUser = users.shift();
11118          }
11119          return mostRecentUser || null;
11120        },
11121        body: {
11122          mpid: currentUserMPID,
11123          is_logged_in: mpInstance._Store.isLoggedIn,
11124          matched_identities: currentUserIdentities,
11125          context: null,
11126          is_ephemeral: false
11127        }
11128      });
11129    }
11130  }
11131  function queueIfNotInitialized(func, self) {
11132    var _a2, _b2;
11133    var noFunctionalWithoutId = ((_a2 = self._CookieConsentManager) === null || _a2 === void 0 ? void 0 : _a2.getNoFunctional()) && !hasExplicitIdentifier(self._Store);
11134    if (((_b2 = self._Store) === null || _b2 === void 0 ? void 0 : _b2.isInitialized) || noFunctionalWithoutId) {
11135      return false;
11136    }
11137    self._preInit.readyQueue.push(function() {
11138      var _a3;
11139      if ((_a3 = self._Store) === null || _a3 === void 0 ? void 0 : _a3.isInitialized) {
11140        func();
11141      }
11142    });
11143    return true;
11144  }
11145  var mockFunction = function mockFunction2() {
11146    return null;
11147  };
11148  var _BatchValidator = (
11149    /** @class */
11150    (function() {
11151      function _BatchValidator2() {
11152      }
11153      _BatchValidator2.prototype.getMPInstance = function() {
11154        return {
11155          // Certain Helper, Store, and Identity properties need to be mocked to be used in the `returnBatch` method
11156          _Helpers: {
11157            sanitizeAttributes: window.mParticle.getInstance()._Helpers.sanitizeAttributes,
11158            generateHash: function generateHash2() {
11159              return "mockHash";
11160            },
11161            generateUniqueId: function generateUniqueId2() {
11162              return "mockId";
11163            },
11164            extend,
11165            createServiceUrl: mockFunction,
11166            parseNumber: mockFunction,
11167            isObject: mockFunction,
11168            Validators: null
11169          },
11170          _resetForTests: mockFunction,
11171          _APIClient: null,
11172          _timeOnSiteTimer: {
11173            getTimeInForeground: mockFunction
11174          },
11175          MPSideloadedKit: null,
11176          _Consent: null,
11177          _Events: null,
11178          _Forwarders: null,
11179          _NativeSdkHelpers: null,
11180          _Persistence: null,
11181          _preInit: null,
11182          Consent: null,
11183          _ServerModel: null,
11184          _SessionManager: null,
11185          _Store: {
11186            sessionId: "mockSessionId",
11187            sideloadedKits: [],
11188            devToken: "test_dev_token",
11189            isFirstRun: true,
11190            isEnabled: true,
11191            sessionAttributes: {},
11192            currentSessionMPIDs: [],
11193            consentState: null,
11194            clientId: null,
11195            deviceId: null,
11196            serverSettings: {},
11197            dateLastEventSent: null,
11198            sessionStartDate: null,
11199            currentPosition: null,
11200            isTracking: false,
11201            watchPositionId: null,
11202            cartProducts: [],
11203            eventQueue: [],
11204            currencyCode: null,
11205            globalTimer: null,
11206            context: null,
11207            configurationLoaded: false,
11208            identityCallInFlight: false,
11209            nonCurrentUserMPIDs: {},
11210            identifyCalled: false,
11211            isLoggedIn: false,
11212            cookieSyncDates: {},
11213            integrationAttributes: {},
11214            requireDelay: true,
11215            isLocalStorageAvailable: null,
11216            integrationDelayTimeoutStart: null,
11217            storageName: null,
11218            prodStorageName: null,
11219            activeForwarders: [],
11220            kits: {},
11221            configuredForwarders: [],
11222            pixelConfigurations: [],
11223            wrapperSDKInfo: {
11224              name: "none",
11225              version: null,
11226              isInfoSet: false
11227            },
11228            SDKConfig: {
11229              isDevelopmentMode: false,
11230              onCreateBatch: mockFunction
11231            },
11232            getTotalTimeOnSite: mockFunction
11233          },
11234          config: null,
11235          eCommerce: null,
11236          Identity: {
11237            getCurrentUser: mockFunction,
11238            IdentityAPI: {},
11239            identify: mockFunction,
11240            login: mockFunction,
11241            logout: mockFunction,
11242            modify: mockFunction
11243          },
11244          Logger: {
11245            verbose: mockFunction,
11246            error: mockFunction,
11247            warning: mockFunction
11248          },
11249          ProductActionType: null,
11250          ServerModel: null,
11251          addForwarder: mockFunction,
11252          generateHash: mockFunction,
11253          getAppVersion: mockFunction,
11254          getAppName: mockFunction,
11255          getInstance: mockFunction,
11256          getDeviceId: mockFunction,
11257          init: mockFunction,
11258          logBaseEvent: mockFunction,
11259          logEvent: mockFunction,
11260          logLevel: "none",
11261          setPosition: mockFunction,
11262          upload: mockFunction
11263        };
11264      };
11265      _BatchValidator2.prototype.createSDKEventFunction = function(event) {
11266        return new ServerModel(this.getMPInstance()).createEventObject(event);
11267      };
11268      _BatchValidator2.prototype.returnBatch = function(events) {
11269        var _this = this;
11270        var mpInstance = this.getMPInstance();
11271        var sdkEvents = Array.isArray(events) ? events.map(function(event) {
11272          return _this.createSDKEventFunction(event);
11273        }) : [this.createSDKEventFunction(events)];
11274        var batch = convertEvents("0", sdkEvents, mpInstance);
11275        return batch;
11276      };
11277      return _BatchValidator2;
11278    })()
11279  );
11280  var MPSideloadedKit = (
11281    /** @class */
11282    (function() {
11283      function MPSideloadedKit2(unregisteredKitInstance) {
11284        this.filterDictionary = {
11285          eventTypeFilters: [],
11286          eventNameFilters: [],
11287          screenNameFilters: [],
11288          screenAttributeFilters: [],
11289          userIdentityFilters: [],
11290          userAttributeFilters: [],
11291          attributeFilters: [],
11292          consentRegulationFilters: [],
11293          consentRegulationPurposeFilters: [],
11294          messageTypeFilters: [],
11295          messageTypeStateFilters: [],
11296          // The below filtering members are optional, but we instantiate them
11297          // to simplify public method assignment
11298          filteringEventAttributeValue: {},
11299          filteringUserAttributeValue: {},
11300          filteringConsentRuleValues: {}
11301        };
11302        this.kitInstance = unregisteredKitInstance;
11303      }
11304      MPSideloadedKit2.prototype.addEventTypeFilter = function(eventType) {
11305        var hashedEventType = KitFilterHelper.hashEventType(eventType);
11306        this.filterDictionary.eventTypeFilters.push(hashedEventType);
11307      };
11308      MPSideloadedKit2.prototype.addEventNameFilter = function(eventType, eventName) {
11309        var hashedEventName = KitFilterHelper.hashEventName(eventName, eventType);
11310        this.filterDictionary.eventNameFilters.push(hashedEventName);
11311      };
11312      MPSideloadedKit2.prototype.addEventAttributeFilter = function(eventType, eventName, customAttributeKey) {
11313        var hashedEventAttribute = KitFilterHelper.hashEventAttributeKey(eventType, eventName, customAttributeKey);
11314        this.filterDictionary.attributeFilters.push(hashedEventAttribute);
11315      };
11316      MPSideloadedKit2.prototype.addScreenNameFilter = function(screenName) {
11317        var hashedScreenName = KitFilterHelper.hashEventName(screenName, EventType.Unknown);
11318        this.filterDictionary.screenNameFilters.push(hashedScreenName);
11319      };
11320      MPSideloadedKit2.prototype.addScreenAttributeFilter = function(screenName, screenAttribute) {
11321        var hashedScreenAttribute = KitFilterHelper.hashEventAttributeKey(EventType.Unknown, screenName, screenAttribute);
11322        this.filterDictionary.screenAttributeFilters.push(hashedScreenAttribute);
11323      };
11324      MPSideloadedKit2.prototype.addUserIdentityFilter = function(userIdentity) {
11325        var hashedIdentityType = KitFilterHelper.hashUserIdentity(userIdentity);
11326        this.filterDictionary.userIdentityFilters.push(hashedIdentityType);
11327      };
11328      MPSideloadedKit2.prototype.addUserAttributeFilter = function(userAttributeKey) {
11329        var hashedUserAttributeKey = KitFilterHelper.hashUserAttribute(userAttributeKey);
11330        this.filterDictionary.userAttributeFilters.push(hashedUserAttributeKey);
11331      };
11332      return MPSideloadedKit2;
11333    })()
11334  );
11335  if (!Array.prototype.forEach) {
11336    Array.prototype.forEach = Polyfill.forEach;
11337  }
11338  if (!Array.prototype.map) {
11339    Array.prototype.map = Polyfill.map;
11340  }
11341  if (!Array.prototype.filter) {
11342    Array.prototype.filter = Polyfill.filter;
11343  }
11344  if (!Array.isArray) {
11345    Array.prototype.isArray = Polyfill.isArray;
11346  }
11347  function mParticleInstanceManager() {
11348    var self = this;
11349    this.Store = {};
11350    this._instances = {};
11351    this.IdentityType = IdentityType;
11352    this.EventType = EventType;
11353    this.CommerceEventType = CommerceEventType;
11354    this.PromotionType = PromotionActionType;
11355    this.ProductActionType = ProductActionType;
11356    this.RoktEvents = RoktEvents;
11357    this.MPSideloadedKit = MPSideloadedKit;
11358    if (typeof window !== "undefined") {
11359      this.isIOS = window.mParticle && window.mParticle.isIOS ? window.mParticle.isIOS : false;
11360      this.config = window.mParticle && window.mParticle.config ? window.mParticle.config : {};
11361    }
11362    this.init = function(apiKey, config, instanceName) {
11363      if (!config && window.mParticle && window.mParticle.config) {
11364        console.warn("You did not pass a config object to mParticle.init(). Attempting to use the window.mParticle.config if it exists. Please note that in a future release, this may not work and mParticle will not initialize properly");
11365        config = window.mParticle ? window.mParticle.config : {};
11366      }
11367      instanceName = (!instanceName || instanceName.length === 0 ? Constants.DefaultInstance : instanceName).toLowerCase();
11368      var client = self._instances[instanceName];
11369      if (client === void 0) {
11370        client = new mParticleInstance(instanceName);
11371        self._instances[instanceName] = client;
11372      }
11373      client.captureTiming(PerformanceMarkType.SdkStart);
11374      client.setLauncherInstanceGuid();
11375      client.init(apiKey, config, instanceName);
11376    };
11377    this.captureTiming = function(metricsName) {
11378      self.getInstance().captureTiming(metricsName);
11379    };
11380    this.getInstance = function getInstance(instanceName) {
11381      var client;
11382      if (!instanceName) {
11383        instanceName = Constants.DefaultInstance;
11384        client = self._instances[instanceName];
11385        if (!client) {
11386          client = new mParticleInstance(instanceName);
11387          self._instances[Constants.DefaultInstance] = client;
11388        }
11389        return client;
11390      } else {
11391        client = self._instances[instanceName.toLowerCase()];
11392        if (!client) {
11393          console.log("You tried to initialize an instance named " + instanceName + ". This instance does not exist. Check your instance name or initialize a new instance with this name before calling it.");
11394          return null;
11395        }
11396        return client;
11397      }
11398    };
11399    this.Rokt = self.getInstance()._RoktManager;
11400    this.getDeviceId = function() {
11401      return self.getInstance().getDeviceId();
11402    };
11403    this.setDeviceId = function(guid) {
11404      return self.getInstance().setDeviceId(guid);
11405    };
11406    this.isInitialized = function() {
11407      return self.getInstance().isInitialized();
11408    };
11409    this.startNewSession = function() {
11410      self.getInstance().startNewSession();
11411    };
11412    this.endSession = function() {
11413      self.getInstance().endSession();
11414    };
11415    this.setLogLevel = function(newLogLevel) {
11416      self.getInstance().setLogLevel(newLogLevel);
11417    };
11418    this.ready = function(argument) {
11419      self.getInstance().ready(argument);
11420    };
11421    this.setAppVersion = function(version2) {
11422      self.getInstance().setAppVersion(version2);
11423    };
11424    this.getAppName = function() {
11425      return self.getInstance().getAppName();
11426    };
11427    this.setAppName = function(name) {
11428      self.getInstance().setAppName(name);
11429    };
11430    this.getAppVersion = function() {
11431      return self.getInstance().getAppVersion();
11432    };
11433    this.getEnvironment = function() {
11434      return self.getInstance().getEnvironment();
11435    };
11436    this.stopTrackingLocation = function() {
11437      self.getInstance().stopTrackingLocation();
11438    };
11439    this.startTrackingLocation = function(callback) {
11440      self.getInstance().startTrackingLocation(callback);
11441    };
11442    this.setPosition = function(lat, lng) {
11443      self.getInstance().setPosition(lat, lng);
11444    };
11445    this.logBaseEvent = function(event, eventOptions) {
11446      self.getInstance().logBaseEvent(event, eventOptions);
11447    };
11448    this.logEvent = function(eventName, eventType, eventInfo, customFlags, eventOptions) {
11449      self.getInstance().logEvent(eventName, eventType, eventInfo, customFlags, eventOptions);
11450    };
11451    this.logError = function(error, attrs) {
11452      self.getInstance().logError(error, attrs);
11453    };
11454    this.logLink = function(selector, eventName, eventType, eventInfo) {
11455      self.getInstance().logLink(selector, eventName, eventType, eventInfo);
11456    };
11457    this.logForm = function(selector, eventName, eventType, eventInfo) {
11458      self.getInstance().logForm(selector, eventName, eventType, eventInfo);
11459    };
11460    this.logPageView = function(eventName, attrs, customFlags, eventOptions) {
11461      self.getInstance().logPageView(eventName, attrs, customFlags, eventOptions);
11462    };
11463    this.upload = function() {
11464      self.getInstance().upload();
11465    };
11466    this.eCommerce = {
11467      Cart: {
11468        add: function add(product, logEventBoolean) {
11469          self.getInstance().eCommerce.Cart.add(product, logEventBoolean);
11470        },
11471        remove: function remove(product, logEventBoolean) {
11472          self.getInstance().eCommerce.Cart.remove(product, logEventBoolean);
11473        },
11474        clear: function clear() {
11475          self.getInstance().eCommerce.Cart.clear();
11476        }
11477      },
11478      setCurrencyCode: function setCurrencyCode(code) {
11479        self.getInstance().eCommerce.setCurrencyCode(code);
11480      },
11481      createProduct: function createProduct(name, sku, price, quantity, variant, category, brand, position, coupon, attributes) {
11482        return self.getInstance().eCommerce.createProduct(name, sku, price, quantity, variant, category, brand, position, coupon, attributes);
11483      },
11484      createPromotion: function createPromotion(id, creative, name, position) {
11485        return self.getInstance().eCommerce.createPromotion(id, creative, name, position);
11486      },
11487      createImpression: function createImpression(name, product) {
11488        return self.getInstance().eCommerce.createImpression(name, product);
11489      },
11490      createTransactionAttributes: function createTransactionAttributes(id, affiliation, couponCode, revenue, shipping, tax) {
11491        return self.getInstance().eCommerce.createTransactionAttributes(id, affiliation, couponCode, revenue, shipping, tax);
11492      },
11493      logCheckout: function logCheckout(step, options, attrs, customFlags) {
11494        self.getInstance().eCommerce.logCheckout(step, options, attrs, customFlags);
11495      },
11496      logProductAction: function logProductAction(productActionType, product, attrs, customFlags, transactionAttributes, eventOptions) {
11497        self.getInstance().eCommerce.logProductAction(productActionType, product, attrs, customFlags, transactionAttributes, eventOptions);
11498      },
11499      logPurchase: function logPurchase(transactionAttributes, product, clearCart, attrs, customFlags) {
11500        self.getInstance().eCommerce.logPurchase(transactionAttributes, product, clearCart, attrs, customFlags);
11501      },
11502      logPromotion: function logPromotion(type, promotion, attrs, customFlags, eventOptions) {
11503        self.getInstance().eCommerce.logPromotion(type, promotion, attrs, customFlags, eventOptions);
11504      },
11505      logImpression: function logImpression(impression, attrs, customFlags, eventOptions) {
11506        self.getInstance().eCommerce.logImpression(impression, attrs, customFlags, eventOptions);
11507      },
11508      logRefund: function logRefund(transactionAttributes, product, clearCart, attrs, customFlags) {
11509        self.getInstance().eCommerce.logRefund(transactionAttributes, product, clearCart, attrs, customFlags);
11510      },
11511      expandCommerceEvent: function expandCommerceEvent(event) {
11512        return self.getInstance().eCommerce.expandCommerceEvent(event);
11513      }
11514    };
11515    this.setSessionAttribute = function(key, value) {
11516      self.getInstance().setSessionAttribute(key, value);
11517    };
11518    this.setOptOut = function(isOptingOut) {
11519      self.getInstance().setOptOut(isOptingOut);
11520    };
11521    this.setIntegrationAttribute = function(integrationId, attrs) {
11522      self.getInstance().setIntegrationAttribute(integrationId, attrs);
11523    };
11524    this.getIntegrationAttributes = function(moduleId) {
11525      return self.getInstance().getIntegrationAttributes(moduleId);
11526    };
11527    this.Identity = {
11528      HTTPCodes: Constants.HTTPCodes,
11529      aliasUsers: function aliasUsers(aliasRequest, callback) {
11530        self.getInstance().Identity.aliasUsers(aliasRequest, callback);
11531      },
11532      createAliasRequest: function createAliasRequest(sourceUser, destinationUser, scope) {
11533        return self.getInstance().Identity.createAliasRequest(sourceUser, destinationUser, scope);
11534      },
11535      getCurrentUser: function getCurrentUser() {
11536        return self.getInstance().Identity.getCurrentUser();
11537      },
11538      getUser: function getUser(mpid) {
11539        return self.getInstance().Identity.getUser(mpid);
11540      },
11541      getUsers: function getUsers() {
11542        return self.getInstance().Identity.getUsers();
11543      },
11544      identify: function identify(identityApiData, callback) {
11545        self.getInstance().Identity.identify(identityApiData, callback);
11546      },
11547      login: function login(identityApiData, callback) {
11548        self.getInstance().Identity.login(identityApiData, callback);
11549      },
11550      logout: function logout(identityApiData, callback) {
11551        self.getInstance().Identity.logout(identityApiData, callback);
11552      },
11553      modify: function modify(identityApiData, callback) {
11554        self.getInstance().Identity.modify(identityApiData, callback);
11555      },
11556      search: function search(workspaceApiKey, knownIdentities, callback) {
11557        self.getInstance().Identity.search(workspaceApiKey, knownIdentities, callback);
11558      }
11559    };
11560    this.sessionManager = {
11561      getSession: function getSession() {
11562        return self.getInstance()._SessionManager.getSessionId();
11563      }
11564    };
11565    this.Consent = {
11566      createConsentState: function createConsentState() {
11567        return self.getInstance().Consent.createConsentState();
11568      },
11569      createGDPRConsent: function createGDPRConsent(consented, timestamp, consentDocument, location2, hardwareId) {
11570        return self.getInstance().Consent.createGDPRConsent(consented, timestamp, consentDocument, location2, hardwareId);
11571      },
11572      createCCPAConsent: function createCCPAConsent(consented, timestamp, consentDocument, location2, hardwareId) {
11573        return self.getInstance().Consent.createGDPRConsent(consented, timestamp, consentDocument, location2, hardwareId);
11574      }
11575    };
11576    this.reset = function() {
11577      self.getInstance().reset(self.getInstance());
11578    };
11579    this._resetForTests = function(MPConfig, keepPersistence) {
11580      if (typeof keepPersistence === "boolean") {
11581        self.getInstance()._resetForTests(MPConfig, keepPersistence, self.getInstance());
11582      } else {
11583        self.getInstance()._resetForTests(MPConfig, false, self.getInstance());
11584      }
11585    };
11586    this.configurePixel = function(settings) {
11587      self.getInstance().configurePixel(settings);
11588    };
11589    this._setIntegrationDelay = function(moduleId, _boolean) {
11590      self.getInstance()._setIntegrationDelay(moduleId, _boolean);
11591    };
11592    this._getIntegrationDelays = function() {
11593      return self.getInstance()._getIntegrationDelays();
11594    };
11595    this.getVersion = function() {
11596      return self.getInstance().getVersion();
11597    };
11598    this.generateHash = function(string) {
11599      return self.getInstance().generateHash(string);
11600    };
11601    this.addForwarder = function(forwarder) {
11602      self.getInstance().addForwarder(forwarder);
11603    };
11604    this._getActiveForwarders = function() {
11605      return self.getInstance()._getActiveForwarders();
11606    };
11607    this._setWrapperSDKInfo = function(name, version2) {
11608      self.getInstance()._setWrapperSDKInfo(name, version2);
11609    };
11610    this._registerErrorReportingService = function(service) {
11611      self.getInstance()._registerErrorReportingService(service);
11612    };
11613    this._registerLoggingService = function(service) {
11614      self.getInstance()._registerLoggingService(service);
11615    };
11616  }
11617  var mParticleManager = new mParticleInstanceManager();
11618  if (typeof window !== "undefined") {
11619    window.mParticle = mParticleManager;
11620    window.mParticle._BatchValidator = new _BatchValidator();
11621  }
11622  return mParticleManager;
11623})();

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.