@rudderstack/analytics-js 3.6.1 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3947 @@
1
+ 'use strict';
2
+
3
+ function _arrayLikeToArray(r, a) {
4
+ (null == a || a > r.length) && (a = r.length);
5
+ for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
6
+ return n;
7
+ }
8
+ function _arrayWithHoles(r) {
9
+ if (Array.isArray(r)) return r;
10
+ }
11
+ function _arrayWithoutHoles(r) {
12
+ if (Array.isArray(r)) return _arrayLikeToArray(r);
13
+ }
14
+ function _assertThisInitialized(e) {
15
+ if (void 0 === e) throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
16
+ return e;
17
+ }
18
+ function asyncGeneratorStep(n, t, e, r, o, a, c) {
19
+ try {
20
+ var i = n[a](c),
21
+ u = i.value;
22
+ } catch (n) {
23
+ return void e(n);
24
+ }
25
+ i.done ? t(u) : Promise.resolve(u).then(r, o);
26
+ }
27
+ function _asyncToGenerator(n) {
28
+ return function () {
29
+ var t = this,
30
+ e = arguments;
31
+ return new Promise(function (r, o) {
32
+ var a = n.apply(t, e);
33
+ function _next(n) {
34
+ asyncGeneratorStep(a, r, o, _next, _throw, "next", n);
35
+ }
36
+ function _throw(n) {
37
+ asyncGeneratorStep(a, r, o, _next, _throw, "throw", n);
38
+ }
39
+ _next(void 0);
40
+ });
41
+ };
42
+ }
43
+ function _callSuper(t, o, e) {
44
+ return o = _getPrototypeOf(o), _possibleConstructorReturn(t, _isNativeReflectConstruct() ? Reflect.construct(o, e || [], _getPrototypeOf(t).constructor) : o.apply(t, e));
45
+ }
46
+ function _classCallCheck(a, n) {
47
+ if (!(a instanceof n)) throw new TypeError("Cannot call a class as a function");
48
+ }
49
+ function _construct(t, e, r) {
50
+ if (_isNativeReflectConstruct()) return Reflect.construct.apply(null, arguments);
51
+ var o = [null];
52
+ o.push.apply(o, e);
53
+ var p = new (t.bind.apply(t, o))();
54
+ return p;
55
+ }
56
+ function _defineProperties(e, r) {
57
+ for (var t = 0; t < r.length; t++) {
58
+ var o = r[t];
59
+ o.enumerable = o.enumerable || !1, o.configurable = !0, "value" in o && (o.writable = !0), Object.defineProperty(e, _toPropertyKey(o.key), o);
60
+ }
61
+ }
62
+ function _createClass(e, r, t) {
63
+ return r && _defineProperties(e.prototype, r), t && _defineProperties(e, t), Object.defineProperty(e, "prototype", {
64
+ writable: !1
65
+ }), e;
66
+ }
67
+ function _createForOfIteratorHelper(r, e) {
68
+ var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
69
+ if (!t) {
70
+ if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e ) {
71
+ t && (r = t);
72
+ var n = 0,
73
+ F = function () {};
74
+ return {
75
+ s: F,
76
+ n: function () {
77
+ return n >= r.length ? {
78
+ done: !0
79
+ } : {
80
+ done: !1,
81
+ value: r[n++]
82
+ };
83
+ },
84
+ e: function (r) {
85
+ throw r;
86
+ },
87
+ f: F
88
+ };
89
+ }
90
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
91
+ }
92
+ var o,
93
+ a = !0,
94
+ u = !1;
95
+ return {
96
+ s: function () {
97
+ t = t.call(r);
98
+ },
99
+ n: function () {
100
+ var r = t.next();
101
+ return a = r.done, r;
102
+ },
103
+ e: function (r) {
104
+ u = !0, o = r;
105
+ },
106
+ f: function () {
107
+ try {
108
+ a || null == t.return || t.return();
109
+ } finally {
110
+ if (u) throw o;
111
+ }
112
+ }
113
+ };
114
+ }
115
+ function _defineProperty(e, r, t) {
116
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
117
+ value: t,
118
+ enumerable: !0,
119
+ configurable: !0,
120
+ writable: !0
121
+ }) : e[r] = t, e;
122
+ }
123
+ function _get() {
124
+ return _get = "undefined" != typeof Reflect && Reflect.get ? Reflect.get.bind() : function (e, t, r) {
125
+ var p = _superPropBase(e, t);
126
+ if (p) {
127
+ var n = Object.getOwnPropertyDescriptor(p, t);
128
+ return n.get ? n.get.call(arguments.length < 3 ? e : r) : n.value;
129
+ }
130
+ }, _get.apply(null, arguments);
131
+ }
132
+ function _getPrototypeOf(t) {
133
+ return _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function (t) {
134
+ return t.__proto__ || Object.getPrototypeOf(t);
135
+ }, _getPrototypeOf(t);
136
+ }
137
+ function _inherits(t, e) {
138
+ if ("function" != typeof e && null !== e) throw new TypeError("Super expression must either be null or a function");
139
+ t.prototype = Object.create(e && e.prototype, {
140
+ constructor: {
141
+ value: t,
142
+ writable: !0,
143
+ configurable: !0
144
+ }
145
+ }), Object.defineProperty(t, "prototype", {
146
+ writable: !1
147
+ }), e && _setPrototypeOf(t, e);
148
+ }
149
+ function _isNativeReflectConstruct() {
150
+ try {
151
+ var t = !Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {}));
152
+ } catch (t) {}
153
+ return (_isNativeReflectConstruct = function () {
154
+ return !!t;
155
+ })();
156
+ }
157
+ function _iterableToArray(r) {
158
+ if ("undefined" != typeof Symbol && null != r[Symbol.iterator] || null != r["@@iterator"]) return Array.from(r);
159
+ }
160
+ function _iterableToArrayLimit(r, l) {
161
+ var t = null == r ? null : "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
162
+ if (null != t) {
163
+ var e,
164
+ n,
165
+ i,
166
+ u,
167
+ a = [],
168
+ f = !0,
169
+ o = !1;
170
+ try {
171
+ if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);
172
+ } catch (r) {
173
+ o = !0, n = r;
174
+ } finally {
175
+ try {
176
+ if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;
177
+ } finally {
178
+ if (o) throw n;
179
+ }
180
+ }
181
+ return a;
182
+ }
183
+ }
184
+ function _nonIterableRest() {
185
+ throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
186
+ }
187
+ function _nonIterableSpread() {
188
+ throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
189
+ }
190
+ function ownKeys(e, r) {
191
+ var t = Object.keys(e);
192
+ if (Object.getOwnPropertySymbols) {
193
+ var o = Object.getOwnPropertySymbols(e);
194
+ r && (o = o.filter(function (r) {
195
+ return Object.getOwnPropertyDescriptor(e, r).enumerable;
196
+ })), t.push.apply(t, o);
197
+ }
198
+ return t;
199
+ }
200
+ function _objectSpread2(e) {
201
+ for (var r = 1; r < arguments.length; r++) {
202
+ var t = null != arguments[r] ? arguments[r] : {};
203
+ r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
204
+ _defineProperty(e, r, t[r]);
205
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
206
+ Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
207
+ });
208
+ }
209
+ return e;
210
+ }
211
+ function _possibleConstructorReturn(t, e) {
212
+ if (e && ("object" == typeof e || "function" == typeof e)) return e;
213
+ if (void 0 !== e) throw new TypeError("Derived constructors may only return object or undefined");
214
+ return _assertThisInitialized(t);
215
+ }
216
+ function _regeneratorRuntime() {
217
+ _regeneratorRuntime = function () {
218
+ return e;
219
+ };
220
+ var t,
221
+ e = {},
222
+ r = Object.prototype,
223
+ n = r.hasOwnProperty,
224
+ o = Object.defineProperty || function (t, e, r) {
225
+ t[e] = r.value;
226
+ },
227
+ i = "function" == typeof Symbol ? Symbol : {},
228
+ a = i.iterator || "@@iterator",
229
+ c = i.asyncIterator || "@@asyncIterator",
230
+ u = i.toStringTag || "@@toStringTag";
231
+ function define(t, e, r) {
232
+ return Object.defineProperty(t, e, {
233
+ value: r,
234
+ enumerable: !0,
235
+ configurable: !0,
236
+ writable: !0
237
+ }), t[e];
238
+ }
239
+ try {
240
+ define({}, "");
241
+ } catch (t) {
242
+ define = function (t, e, r) {
243
+ return t[e] = r;
244
+ };
245
+ }
246
+ function wrap(t, e, r, n) {
247
+ var i = e && e.prototype instanceof Generator ? e : Generator,
248
+ a = Object.create(i.prototype),
249
+ c = new Context(n || []);
250
+ return o(a, "_invoke", {
251
+ value: makeInvokeMethod(t, r, c)
252
+ }), a;
253
+ }
254
+ function tryCatch(t, e, r) {
255
+ try {
256
+ return {
257
+ type: "normal",
258
+ arg: t.call(e, r)
259
+ };
260
+ } catch (t) {
261
+ return {
262
+ type: "throw",
263
+ arg: t
264
+ };
265
+ }
266
+ }
267
+ e.wrap = wrap;
268
+ var h = "suspendedStart",
269
+ l = "suspendedYield",
270
+ f = "executing",
271
+ s = "completed",
272
+ y = {};
273
+ function Generator() {}
274
+ function GeneratorFunction() {}
275
+ function GeneratorFunctionPrototype() {}
276
+ var p = {};
277
+ define(p, a, function () {
278
+ return this;
279
+ });
280
+ var d = Object.getPrototypeOf,
281
+ v = d && d(d(values([])));
282
+ v && v !== r && n.call(v, a) && (p = v);
283
+ var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
284
+ function defineIteratorMethods(t) {
285
+ ["next", "throw", "return"].forEach(function (e) {
286
+ define(t, e, function (t) {
287
+ return this._invoke(e, t);
288
+ });
289
+ });
290
+ }
291
+ function AsyncIterator(t, e) {
292
+ function invoke(r, o, i, a) {
293
+ var c = tryCatch(t[r], t, o);
294
+ if ("throw" !== c.type) {
295
+ var u = c.arg,
296
+ h = u.value;
297
+ return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
298
+ invoke("next", t, i, a);
299
+ }, function (t) {
300
+ invoke("throw", t, i, a);
301
+ }) : e.resolve(h).then(function (t) {
302
+ u.value = t, i(u);
303
+ }, function (t) {
304
+ return invoke("throw", t, i, a);
305
+ });
306
+ }
307
+ a(c.arg);
308
+ }
309
+ var r;
310
+ o(this, "_invoke", {
311
+ value: function (t, n) {
312
+ function callInvokeWithMethodAndArg() {
313
+ return new e(function (e, r) {
314
+ invoke(t, n, e, r);
315
+ });
316
+ }
317
+ return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
318
+ }
319
+ });
320
+ }
321
+ function makeInvokeMethod(e, r, n) {
322
+ var o = h;
323
+ return function (i, a) {
324
+ if (o === f) throw Error("Generator is already running");
325
+ if (o === s) {
326
+ if ("throw" === i) throw a;
327
+ return {
328
+ value: t,
329
+ done: !0
330
+ };
331
+ }
332
+ for (n.method = i, n.arg = a;;) {
333
+ var c = n.delegate;
334
+ if (c) {
335
+ var u = maybeInvokeDelegate(c, n);
336
+ if (u) {
337
+ if (u === y) continue;
338
+ return u;
339
+ }
340
+ }
341
+ if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
342
+ if (o === h) throw o = s, n.arg;
343
+ n.dispatchException(n.arg);
344
+ } else "return" === n.method && n.abrupt("return", n.arg);
345
+ o = f;
346
+ var p = tryCatch(e, r, n);
347
+ if ("normal" === p.type) {
348
+ if (o = n.done ? s : l, p.arg === y) continue;
349
+ return {
350
+ value: p.arg,
351
+ done: n.done
352
+ };
353
+ }
354
+ "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
355
+ }
356
+ };
357
+ }
358
+ function maybeInvokeDelegate(e, r) {
359
+ var n = r.method,
360
+ o = e.iterator[n];
361
+ if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y;
362
+ var i = tryCatch(o, e.iterator, r.arg);
363
+ if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
364
+ var a = i.arg;
365
+ return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y);
366
+ }
367
+ function pushTryEntry(t) {
368
+ var e = {
369
+ tryLoc: t[0]
370
+ };
371
+ 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
372
+ }
373
+ function resetTryEntry(t) {
374
+ var e = t.completion || {};
375
+ e.type = "normal", delete e.arg, t.completion = e;
376
+ }
377
+ function Context(t) {
378
+ this.tryEntries = [{
379
+ tryLoc: "root"
380
+ }], t.forEach(pushTryEntry, this), this.reset(!0);
381
+ }
382
+ function values(e) {
383
+ if (e || "" === e) {
384
+ var r = e[a];
385
+ if (r) return r.call(e);
386
+ if ("function" == typeof e.next) return e;
387
+ if (!isNaN(e.length)) {
388
+ var o = -1,
389
+ i = function next() {
390
+ for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
391
+ return next.value = t, next.done = !0, next;
392
+ };
393
+ return i.next = i;
394
+ }
395
+ }
396
+ throw new TypeError(typeof e + " is not iterable");
397
+ }
398
+ return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
399
+ value: GeneratorFunctionPrototype,
400
+ configurable: !0
401
+ }), o(GeneratorFunctionPrototype, "constructor", {
402
+ value: GeneratorFunction,
403
+ configurable: !0
404
+ }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
405
+ var e = "function" == typeof t && t.constructor;
406
+ return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
407
+ }, e.mark = function (t) {
408
+ return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
409
+ }, e.awrap = function (t) {
410
+ return {
411
+ __await: t
412
+ };
413
+ }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
414
+ return this;
415
+ }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
416
+ void 0 === i && (i = Promise);
417
+ var a = new AsyncIterator(wrap(t, r, n, o), i);
418
+ return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
419
+ return t.done ? t.value : a.next();
420
+ });
421
+ }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
422
+ return this;
423
+ }), define(g, "toString", function () {
424
+ return "[object Generator]";
425
+ }), e.keys = function (t) {
426
+ var e = Object(t),
427
+ r = [];
428
+ for (var n in e) r.push(n);
429
+ return r.reverse(), function next() {
430
+ for (; r.length;) {
431
+ var t = r.pop();
432
+ if (t in e) return next.value = t, next.done = !1, next;
433
+ }
434
+ return next.done = !0, next;
435
+ };
436
+ }, e.values = values, Context.prototype = {
437
+ constructor: Context,
438
+ reset: function (e) {
439
+ if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t);
440
+ },
441
+ stop: function () {
442
+ this.done = !0;
443
+ var t = this.tryEntries[0].completion;
444
+ if ("throw" === t.type) throw t.arg;
445
+ return this.rval;
446
+ },
447
+ dispatchException: function (e) {
448
+ if (this.done) throw e;
449
+ var r = this;
450
+ function handle(n, o) {
451
+ return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
452
+ }
453
+ for (var o = this.tryEntries.length - 1; o >= 0; --o) {
454
+ var i = this.tryEntries[o],
455
+ a = i.completion;
456
+ if ("root" === i.tryLoc) return handle("end");
457
+ if (i.tryLoc <= this.prev) {
458
+ var c = n.call(i, "catchLoc"),
459
+ u = n.call(i, "finallyLoc");
460
+ if (c && u) {
461
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
462
+ if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
463
+ } else if (c) {
464
+ if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
465
+ } else {
466
+ if (!u) throw Error("try statement without catch or finally");
467
+ if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
468
+ }
469
+ }
470
+ }
471
+ },
472
+ abrupt: function (t, e) {
473
+ for (var r = this.tryEntries.length - 1; r >= 0; --r) {
474
+ var o = this.tryEntries[r];
475
+ if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
476
+ var i = o;
477
+ break;
478
+ }
479
+ }
480
+ i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
481
+ var a = i ? i.completion : {};
482
+ return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
483
+ },
484
+ complete: function (t, e) {
485
+ if ("throw" === t.type) throw t.arg;
486
+ return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y;
487
+ },
488
+ finish: function (t) {
489
+ for (var e = this.tryEntries.length - 1; e >= 0; --e) {
490
+ var r = this.tryEntries[e];
491
+ if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
492
+ }
493
+ },
494
+ catch: function (t) {
495
+ for (var e = this.tryEntries.length - 1; e >= 0; --e) {
496
+ var r = this.tryEntries[e];
497
+ if (r.tryLoc === t) {
498
+ var n = r.completion;
499
+ if ("throw" === n.type) {
500
+ var o = n.arg;
501
+ resetTryEntry(r);
502
+ }
503
+ return o;
504
+ }
505
+ }
506
+ throw Error("illegal catch attempt");
507
+ },
508
+ delegateYield: function (e, r, n) {
509
+ return this.delegate = {
510
+ iterator: values(e),
511
+ resultName: r,
512
+ nextLoc: n
513
+ }, "next" === this.method && (this.arg = t), y;
514
+ }
515
+ }, e;
516
+ }
517
+ function _setPrototypeOf(t, e) {
518
+ return _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function (t, e) {
519
+ return t.__proto__ = e, t;
520
+ }, _setPrototypeOf(t, e);
521
+ }
522
+ function _slicedToArray(r, e) {
523
+ return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();
524
+ }
525
+ function _superPropBase(t, o) {
526
+ for (; !{}.hasOwnProperty.call(t, o) && null !== (t = _getPrototypeOf(t)););
527
+ return t;
528
+ }
529
+ function _toConsumableArray(r) {
530
+ return _arrayWithoutHoles(r) || _iterableToArray(r) || _unsupportedIterableToArray(r) || _nonIterableSpread();
531
+ }
532
+ function _toPrimitive(t, r) {
533
+ if ("object" != typeof t || !t) return t;
534
+ var e = t[Symbol.toPrimitive];
535
+ if (void 0 !== e) {
536
+ var i = e.call(t, r || "default");
537
+ if ("object" != typeof i) return i;
538
+ throw new TypeError("@@toPrimitive must return a primitive value.");
539
+ }
540
+ return ("string" === r ? String : Number)(t);
541
+ }
542
+ function _toPropertyKey(t) {
543
+ var i = _toPrimitive(t, "string");
544
+ return "symbol" == typeof i ? i : i + "";
545
+ }
546
+ function _typeof(o) {
547
+ "@babel/helpers - typeof";
548
+
549
+ return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
550
+ return typeof o;
551
+ } : function (o) {
552
+ return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
553
+ }, _typeof(o);
554
+ }
555
+ function _unsupportedIterableToArray(r, a) {
556
+ if (r) {
557
+ if ("string" == typeof r) return _arrayLikeToArray(r, a);
558
+ var t = {}.toString.call(r).slice(8, -1);
559
+ return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
560
+ }
561
+ }
562
+
563
+ function _isPlaceholder(a){return a!=null&&_typeof(a)==='object'&&a['@@functional/placeholder']===true;}
564
+
565
+ /**
566
+ * Optimized internal one-arity curry function.
567
+ *
568
+ * @private
569
+ * @category Function
570
+ * @param {Function} fn The function to curry.
571
+ * @return {Function} The curried function.
572
+ */function _curry1(fn){return function f1(a){if(arguments.length===0||_isPlaceholder(a)){return f1;}else {return fn.apply(this,arguments);}};}
573
+
574
+ /**
575
+ * Optimized internal two-arity curry function.
576
+ *
577
+ * @private
578
+ * @category Function
579
+ * @param {Function} fn The function to curry.
580
+ * @return {Function} The curried function.
581
+ */function _curry2(fn){return function f2(a,b){switch(arguments.length){case 0:return f2;case 1:return _isPlaceholder(a)?f2:_curry1(function(_b){return fn(a,_b);});default:return _isPlaceholder(a)&&_isPlaceholder(b)?f2:_isPlaceholder(a)?_curry1(function(_a){return fn(_a,b);}):_isPlaceholder(b)?_curry1(function(_b){return fn(a,_b);}):fn(a,b);}};}
582
+
583
+ /**
584
+ * Optimized internal three-arity curry function.
585
+ *
586
+ * @private
587
+ * @category Function
588
+ * @param {Function} fn The function to curry.
589
+ * @return {Function} The curried function.
590
+ */function _curry3(fn){return function f3(a,b,c){switch(arguments.length){case 0:return f3;case 1:return _isPlaceholder(a)?f3:_curry2(function(_b,_c){return fn(a,_b,_c);});case 2:return _isPlaceholder(a)&&_isPlaceholder(b)?f3:_isPlaceholder(a)?_curry2(function(_a,_c){return fn(_a,b,_c);}):_isPlaceholder(b)?_curry2(function(_b,_c){return fn(a,_b,_c);}):_curry1(function(_c){return fn(a,b,_c);});default:return _isPlaceholder(a)&&_isPlaceholder(b)&&_isPlaceholder(c)?f3:_isPlaceholder(a)&&_isPlaceholder(b)?_curry2(function(_a,_b){return fn(_a,_b,c);}):_isPlaceholder(a)&&_isPlaceholder(c)?_curry2(function(_a,_c){return fn(_a,b,_c);}):_isPlaceholder(b)&&_isPlaceholder(c)?_curry2(function(_b,_c){return fn(a,_b,_c);}):_isPlaceholder(a)?_curry1(function(_a){return fn(_a,b,c);}):_isPlaceholder(b)?_curry1(function(_b){return fn(a,_b,c);}):_isPlaceholder(c)?_curry1(function(_c){return fn(a,b,_c);}):fn(a,b,c);}};}
591
+
592
+ function _has(prop,obj){return Object.prototype.hasOwnProperty.call(obj,prop);}
593
+
594
+ /**
595
+ * Gives a single-word string description of the (native) type of a value,
596
+ * returning such answers as 'Object', 'Number', 'Array', or 'Null'. Does not
597
+ * attempt to distinguish user Object types any further, reporting them all as
598
+ * 'Object'.
599
+ *
600
+ * @func
601
+ * @memberOf R
602
+ * @since v0.8.0
603
+ * @category Type
604
+ * @sig * -> String
605
+ * @param {*} val The value to test
606
+ * @return {String}
607
+ * @example
608
+ *
609
+ * R.type({}); //=> "Object"
610
+ * R.type(1); //=> "Number"
611
+ * R.type(false); //=> "Boolean"
612
+ * R.type('s'); //=> "String"
613
+ * R.type(null); //=> "Null"
614
+ * R.type([]); //=> "Array"
615
+ * R.type(/[A-z]/); //=> "RegExp"
616
+ * R.type(() => {}); //=> "Function"
617
+ * R.type(async () => {}); //=> "AsyncFunction"
618
+ * R.type(undefined); //=> "Undefined"
619
+ * R.type(BigInt(123)); //=> "BigInt"
620
+ */var type=/*#__PURE__*/_curry1(function type(val){return val===null?'Null':val===undefined?'Undefined':Object.prototype.toString.call(val).slice(8,-1);});
621
+
622
+ function _isObject(x){return Object.prototype.toString.call(x)==='[object Object]';}
623
+
624
+ /**
625
+ * Determine if the passed argument is an integer.
626
+ *
627
+ * @private
628
+ * @param {*} n
629
+ * @category Type
630
+ * @return {Boolean}
631
+ */var _isInteger = Number.isInteger||function _isInteger(n){return n<<0===n;};
632
+
633
+ function _isString(x){return Object.prototype.toString.call(x)==='[object String]';}
634
+
635
+ function _nth(offset,list){var idx=offset<0?list.length+offset:offset;return _isString(list)?list.charAt(idx):list[idx];}
636
+
637
+ function _cloneRegExp(pattern){return new RegExp(pattern.source,pattern.flags?pattern.flags:(pattern.global?'g':'')+(pattern.ignoreCase?'i':'')+(pattern.multiline?'m':'')+(pattern.sticky?'y':'')+(pattern.unicode?'u':'')+(pattern.dotAll?'s':''));}
638
+
639
+ /**
640
+ * Copies an object.
641
+ *
642
+ * @private
643
+ * @param {*} value The value to be copied
644
+ * @param {Boolean} deep Whether or not to perform deep cloning.
645
+ * @return {*} The copied value.
646
+ */function _clone(value,deep,map){map||(map=new _ObjectMap());// this avoids the slower switch with a quick if decision removing some milliseconds in each run.
647
+ if(_isPrimitive(value)){return value;}var copy=function copy(copiedValue){// Check for circular and same references on the object graph and return its corresponding clone.
648
+ var cachedCopy=map.get(value);if(cachedCopy){return cachedCopy;}map.set(value,copiedValue);for(var key in value){if(Object.prototype.hasOwnProperty.call(value,key)){copiedValue[key]=_clone(value[key],true,map);}}return copiedValue;};switch(type(value)){case'Object':return copy(Object.create(Object.getPrototypeOf(value)));case'Array':return copy(Array(value.length));case'Date':return new Date(value.valueOf());case'RegExp':return _cloneRegExp(value);case'Int8Array':case'Uint8Array':case'Uint8ClampedArray':case'Int16Array':case'Uint16Array':case'Int32Array':case'Uint32Array':case'Float32Array':case'Float64Array':case'BigInt64Array':case'BigUint64Array':return value.slice();default:return value;}}function _isPrimitive(param){var type=_typeof(param);return param==null||type!='object'&&type!='function';}var _ObjectMap=/*#__PURE__*/function(){function _ObjectMap(){this.map={};this.length=0;}_ObjectMap.prototype.set=function(key,value){var hashedKey=this.hash(key);var bucket=this.map[hashedKey];if(!bucket){this.map[hashedKey]=bucket=[];}bucket.push([key,value]);this.length+=1;};_ObjectMap.prototype.hash=function(key){var hashedKey=[];for(var value in key){hashedKey.push(Object.prototype.toString.call(key[value]));}return hashedKey.join();};_ObjectMap.prototype.get=function(key){/**
649
+ * depending on the number of objects to be cloned is faster to just iterate over the items in the map just because the hash function is so costly,
650
+ * on my tests this number is 180, anything above that using the hash function is faster.
651
+ */if(this.length<=180){for(var p in this.map){var bucket=this.map[p];for(var i=0;i<bucket.length;i+=1){var element=bucket[i];if(element[0]===key){return element[1];}}}return;}var hashedKey=this.hash(key);var bucket=this.map[hashedKey];if(!bucket){return;}for(var i=0;i<bucket.length;i+=1){var element=bucket[i];if(element[0]===key){return element[1];}}};return _ObjectMap;}();
652
+
653
+ /**
654
+ * Creates a deep copy of the source that can be used in place of the source
655
+ * object without retaining any references to it.
656
+ * The source object may contain (nested) `Array`s and `Object`s,
657
+ * `Number`s, `String`s, `Boolean`s and `Date`s.
658
+ * `Function`s are assigned by reference rather than copied.
659
+ *
660
+ * Dispatches to a `clone` method if present.
661
+ *
662
+ * Note that if the source object has multiple nodes that share a reference,
663
+ * the returned object will have the same structure, but the references will
664
+ * be pointed to the location within the cloned value.
665
+ *
666
+ * @func
667
+ * @memberOf R
668
+ * @since v0.1.0
669
+ * @category Object
670
+ * @sig {*} -> {*}
671
+ * @param {*} value The object or array to clone
672
+ * @return {*} A deeply cloned copy of `val`
673
+ * @example
674
+ *
675
+ * const objects = [{}, {}, {}];
676
+ * const objectsClone = R.clone(objects);
677
+ * objects === objectsClone; //=> false
678
+ * objects[0] === objectsClone[0]; //=> false
679
+ */var clone=/*#__PURE__*/_curry1(function clone(value){return value!=null&&typeof value.clone==='function'?value.clone():_clone(value);});
680
+
681
+ function _path(pathAr,obj){var val=obj;for(var i=0;i<pathAr.length;i+=1){if(val==null){return undefined;}var p=pathAr[i];if(_isInteger(p)){val=_nth(p,val);}else {val=val[p];}}return val;}
682
+
683
+ /**
684
+ * Creates a new object with the own properties of the two provided objects. If
685
+ * a key exists in both objects, the provided function is applied to the key
686
+ * and the values associated with the key in each object, with the result being
687
+ * used as the value associated with the key in the returned object.
688
+ *
689
+ * @func
690
+ * @memberOf R
691
+ * @since v0.19.0
692
+ * @category Object
693
+ * @sig ((String, a, a) -> a) -> {a} -> {a} -> {a}
694
+ * @param {Function} fn
695
+ * @param {Object} l
696
+ * @param {Object} r
697
+ * @return {Object}
698
+ * @see R.mergeDeepWithKey, R.merge, R.mergeWith
699
+ * @example
700
+ *
701
+ * let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r
702
+ * R.mergeWithKey(concatValues,
703
+ * { a: true, thing: 'foo', values: [10, 20] },
704
+ * { b: true, thing: 'bar', values: [15, 35] });
705
+ * //=> { a: true, b: true, thing: 'bar', values: [10, 20, 15, 35] }
706
+ * @symb R.mergeWithKey(f, { x: 1, y: 2 }, { y: 5, z: 3 }) = { x: 1, y: f('y', 2, 5), z: 3 }
707
+ */var mergeWithKey=/*#__PURE__*/_curry3(function mergeWithKey(fn,l,r){var result={};var k;l=l||{};r=r||{};for(k in l){if(_has(k,l)){result[k]=_has(k,r)?fn(k,l[k],r[k]):l[k];}}for(k in r){if(_has(k,r)&&!_has(k,result)){result[k]=r[k];}}return result;});
708
+
709
+ /**
710
+ * Creates a new object with the own properties of the two provided objects.
711
+ * If a key exists in both objects:
712
+ * - and both associated values are also objects then the values will be
713
+ * recursively merged.
714
+ * - otherwise the provided function is applied to the key and associated values
715
+ * using the resulting value as the new value associated with the key.
716
+ * If a key only exists in one object, the value will be associated with the key
717
+ * of the resulting object.
718
+ *
719
+ * @func
720
+ * @memberOf R
721
+ * @since v0.24.0
722
+ * @category Object
723
+ * @sig ((String, a, a) -> a) -> {a} -> {a} -> {a}
724
+ * @param {Function} fn
725
+ * @param {Object} lObj
726
+ * @param {Object} rObj
727
+ * @return {Object}
728
+ * @see R.mergeWithKey, R.mergeDeepWith
729
+ * @example
730
+ *
731
+ * let concatValues = (k, l, r) => k == 'values' ? R.concat(l, r) : r
732
+ * R.mergeDeepWithKey(concatValues,
733
+ * { a: true, c: { thing: 'foo', values: [10, 20] }},
734
+ * { b: true, c: { thing: 'bar', values: [15, 35] }});
735
+ * //=> { a: true, b: true, c: { thing: 'bar', values: [10, 20, 15, 35] }}
736
+ */var mergeDeepWithKey=/*#__PURE__*/_curry3(function mergeDeepWithKey(fn,lObj,rObj){return mergeWithKey(function(k,lVal,rVal){if(_isObject(lVal)&&_isObject(rVal)){return mergeDeepWithKey(fn,lVal,rVal);}else {return fn(k,lVal,rVal);}},lObj,rObj);});
737
+
738
+ /**
739
+ * Creates a new object with the own properties of the two provided objects.
740
+ * If a key exists in both objects:
741
+ * - and both associated values are also objects then the values will be
742
+ * recursively merged.
743
+ * - otherwise the provided function is applied to associated values using the
744
+ * resulting value as the new value associated with the key.
745
+ * If a key only exists in one object, the value will be associated with the key
746
+ * of the resulting object.
747
+ *
748
+ * @func
749
+ * @memberOf R
750
+ * @since v0.24.0
751
+ * @category Object
752
+ * @sig ((a, a) -> a) -> {a} -> {a} -> {a}
753
+ * @param {Function} fn
754
+ * @param {Object} lObj
755
+ * @param {Object} rObj
756
+ * @return {Object}
757
+ * @see R.mergeWith, R.mergeDeepWithKey
758
+ * @example
759
+ *
760
+ * R.mergeDeepWith(R.concat,
761
+ * { a: true, c: { values: [10, 20] }},
762
+ * { b: true, c: { values: [15, 35] }});
763
+ * //=> { a: true, b: true, c: { values: [10, 20, 15, 35] }}
764
+ */var mergeDeepWith=/*#__PURE__*/_curry3(function mergeDeepWith(fn,lObj,rObj){return mergeDeepWithKey(function(k,lVal,rVal){return fn(lVal,rVal);},lObj,rObj);});
765
+
766
+ /**
767
+ * Retrieves the value at a given path. The nodes of the path can be arbitrary strings or non-negative integers.
768
+ * For anything else, the value is unspecified. Integer paths are meant to index arrays, strings are meant for objects.
769
+ *
770
+ * @func
771
+ * @memberOf R
772
+ * @since v0.2.0
773
+ * @category Object
774
+ * @typedefn Idx = String | Int | Symbol
775
+ * @sig [Idx] -> {a} -> a | Undefined
776
+ * @sig Idx = String | NonNegativeInt
777
+ * @param {Array} path The path to use.
778
+ * @param {Object} obj The object or array to retrieve the nested property from.
779
+ * @return {*} The data at `path`.
780
+ * @see R.prop, R.nth, R.assocPath, R.dissocPath
781
+ * @example
782
+ *
783
+ * R.path(['a', 'b'], {a: {b: 2}}); //=> 2
784
+ * R.path(['a', 'b'], {c: {b: 2}}); //=> undefined
785
+ * R.path(['a', 'b', 0], {a: {b: [1, 2, 3]}}); //=> 1
786
+ * R.path(['a', 'b', -2], {a: {b: [1, 2, 3]}}); //=> 2
787
+ * R.path([2], {'2': 2}); //=> 2
788
+ * R.path([-2], {'-2': 'a'}); //=> undefined
789
+ */var path=/*#__PURE__*/_curry2(_path);
790
+
791
+ /**
792
+ * Returns a partial copy of an object containing only the keys that satisfy
793
+ * the supplied predicate.
794
+ *
795
+ * @func
796
+ * @memberOf R
797
+ * @since v0.8.0
798
+ * @category Object
799
+ * @sig ((v, k) -> Boolean) -> {k: v} -> {k: v}
800
+ * @param {Function} pred A predicate to determine whether or not a key
801
+ * should be included on the output object.
802
+ * @param {Object} obj The object to copy from
803
+ * @return {Object} A new object with only properties that satisfy `pred`
804
+ * on it.
805
+ * @see R.pick, R.filter
806
+ * @example
807
+ *
808
+ * const isUpperCase = (val, key) => key.toUpperCase() === key;
809
+ * R.pickBy(isUpperCase, {a: 1, b: 2, A: 3, B: 4}); //=> {A: 3, B: 4}
810
+ */var pickBy=/*#__PURE__*/_curry2(function pickBy(test,obj){var result={};for(var prop in obj){if(test(obj[prop],prop,obj)){result[prop]=obj[prop];}}return result;});
811
+
812
+ /**
813
+ * A function to check given value is a function
814
+ * @param value input value
815
+ * @returns boolean
816
+ */ // eslint-disable-next-line @typescript-eslint/ban-types
817
+ var isFunction=function isFunction(value){return typeof value==='function'&&Boolean(value.constructor&&value.call&&value.apply);};/**
818
+ * A function to check given value is a string
819
+ * @param value input value
820
+ * @returns boolean
821
+ */var isString=function isString(value){return typeof value==='string';};/**
822
+ * A function to check given value is null or not
823
+ * @param value input value
824
+ * @returns boolean
825
+ */var isNull=function isNull(value){return value===null;};/**
826
+ * A function to check given value is undefined
827
+ * @param value input value
828
+ * @returns boolean
829
+ */var isUndefined=function isUndefined(value){return typeof value==='undefined';};/**
830
+ * A function to check given value is null or undefined
831
+ * @param value input value
832
+ * @returns boolean
833
+ */var isNullOrUndefined=function isNullOrUndefined(value){return isNull(value)||isUndefined(value);};/**
834
+ * A function to check given value is defined
835
+ * @param value input value
836
+ * @returns boolean
837
+ */var isDefined=function isDefined(value){return !isUndefined(value);};/**
838
+ * A function to check given value is defined and not null
839
+ * @param value input value
840
+ * @returns boolean
841
+ */var isDefinedAndNotNull=function isDefinedAndNotNull(value){return !isNullOrUndefined(value);};/**
842
+ * A function to check given value is defined and not null
843
+ * @param value input value
844
+ * @returns boolean
845
+ */var isDefinedNotNullAndNotEmptyString=function isDefinedNotNullAndNotEmptyString(value){return isDefinedAndNotNull(value)&&value!=='';};/**
846
+ * Determines if the input is an instance of Error
847
+ * @param obj input value
848
+ * @returns true if the input is an instance of Error and false otherwise
849
+ */var isTypeOfError=function isTypeOfError(obj){return obj instanceof Error;};
850
+
851
+ var getValueByPath=function getValueByPath(obj,keyPath){var pathParts=keyPath.split('.');return path(pathParts,obj);};var hasValueByPath=function hasValueByPath(obj,path){return Boolean(getValueByPath(obj,path));};/**
852
+ * Checks if the input is an object literal or built-in object type and not null
853
+ * @param value Input value
854
+ * @returns true if the input is an object and not null
855
+ */var isObjectAndNotNull=function isObjectAndNotNull(value){return !isNull(value)&&_typeof(value)==='object'&&!Array.isArray(value);};/**
856
+ * Checks if the input is an object literal and not null
857
+ * @param value Input value
858
+ * @returns true if the input is an object and not null
859
+ */var isObjectLiteralAndNotNull=function isObjectLiteralAndNotNull(value){return !isNull(value)&&Object.prototype.toString.call(value)==='[object Object]';};var mergeDeepRightObjectArrays=function mergeDeepRightObjectArrays(leftValue,rightValue){if(!Array.isArray(leftValue)||!Array.isArray(rightValue)){return clone(rightValue);}var mergedArray=clone(leftValue);rightValue.forEach(function(value,index){mergedArray[index]=Array.isArray(value)||isObjectAndNotNull(value)?// eslint-disable-next-line @typescript-eslint/no-use-before-define
860
+ mergeDeepRight(mergedArray[index],value):value;});return mergedArray;};var mergeDeepRight=function mergeDeepRight(leftObject,rightObject){return mergeDeepWith(mergeDeepRightObjectArrays,leftObject,rightObject);};/**
861
+ Checks if the input is a non-empty object literal type and not undefined or null
862
+ * @param value input any
863
+ * @returns boolean
864
+ */var isNonEmptyObject=function isNonEmptyObject(value){return isObjectLiteralAndNotNull(value)&&Object.keys(value).length>0;};/**
865
+ * A utility to recursively remove undefined values from an object
866
+ * @param obj input object
867
+ * @returns a new object
868
+ */var removeUndefinedValues=function removeUndefinedValues(obj){var result=pickBy(isDefined,obj);Object.keys(result).forEach(function(key){var value=result[key];if(isObjectLiteralAndNotNull(value)){result[key]=removeUndefinedValues(value);}});return result;};/**
869
+ * A utility to recursively remove undefined and null values from an object
870
+ * @param obj input object
871
+ * @returns a new object
872
+ */var removeUndefinedAndNullValues=function removeUndefinedAndNullValues(obj){var result=pickBy(isDefinedAndNotNull,obj);Object.keys(result).forEach(function(key){var value=result[key];if(isObjectLiteralAndNotNull(value)){result[key]=removeUndefinedAndNullValues(value);}});return result;};
873
+
874
+ var trim=function trim(value){return value.replace(/^\s+|\s+$/gm,'');};var removeDoubleSpaces=function removeDoubleSpaces(value){return value.replace(/ {2,}/g,' ');};var removeLeadingPeriod=function removeLeadingPeriod(value){return value.replace(/^\.+/,'');};/**
875
+ * A function to convert values to string
876
+ * @param val input value
877
+ * @returns stringified value
878
+ */var tryStringify=function tryStringify(val){var retVal=val;if(!isString(val)&&!isNullOrUndefined(val)){try{retVal=JSON.stringify(val);}catch(e){retVal=null;}}return retVal;};// The following text encoding and decoding is done before base64 encoding to prevent
879
+ // https://developer.mozilla.org/en-US/docs/Glossary/Base64#the_unicode_problem
880
+ /**
881
+ * Converts a base64 encoded string to bytes array
882
+ * @param base64Str base64 encoded string
883
+ * @returns bytes array
884
+ */var base64ToBytes=function base64ToBytes(base64Str){var binString=globalThis.atob(base64Str);var bytes=binString.split('').map(function(char){return char.charCodeAt(0);});return new Uint8Array(bytes);};/**
885
+ * Converts a bytes array to base64 encoded string
886
+ * @param bytes bytes array to be converted to base64
887
+ * @returns base64 encoded string
888
+ */var bytesToBase64=function bytesToBase64(bytes){var binString=Array.from(bytes,function(x){return String.fromCodePoint(x);}).join('');return globalThis.btoa(binString);};/**
889
+ * Encodes a string to base64 even with unicode characters
890
+ * @param value input string
891
+ * @returns base64 encoded string
892
+ */var toBase64=function toBase64(value){return bytesToBase64(new TextEncoder().encode(value));};/**
893
+ * Decodes a base64 encoded string
894
+ * @param value base64 encoded string
895
+ * @returns decoded string
896
+ */var fromBase64=function fromBase64(value){return new TextDecoder().decode(base64ToBytes(value));};
897
+
898
+ // if yes make them null instead of omitting in overloaded cases
899
+ /*
900
+ * Normalise the overloaded arguments of the page call facade
901
+ */var pageArgumentsToCallOptions=function pageArgumentsToCallOptions(category,name,properties,options,callback){var payload={category:category,name:name,properties:properties,options:options,callback:undefined};if(isFunction(callback)){payload.callback=callback;}if(isFunction(options)){payload.category=category;payload.name=name;payload.properties=properties;payload.options=undefined;payload.callback=options;}if(isFunction(properties)){payload.category=category;payload.name=name;payload.properties=undefined;payload.options=undefined;payload.callback=properties;}if(isFunction(name)){payload.category=category;payload.name=undefined;payload.properties=undefined;payload.options=undefined;payload.callback=name;}if(isFunction(category)){payload.category=undefined;payload.name=undefined;payload.properties=undefined;payload.options=undefined;payload.callback=category;}if(isObjectLiteralAndNotNull(category)){payload.name=undefined;payload.category=undefined;payload.properties=category;if(!isFunction(name)){payload.options=name;}else {payload.options=undefined;}}else if(isObjectLiteralAndNotNull(name)){payload.name=undefined;payload.properties=name;if(!isFunction(properties)){payload.options=properties;}else {payload.options=undefined;}}// if the category argument alone is provided b/w category and name,
902
+ // use it as name and set category to undefined
903
+ if(isString(category)&&!isString(name)){payload.category=undefined;payload.name=category;}// Rest of the code is just to clean up undefined values
904
+ // and set some proper defaults
905
+ // Also, to clone the incoming object type arguments
906
+ if(!isDefined(payload.category)){payload.category=undefined;}if(!isDefined(payload.name)){payload.name=undefined;}payload.properties=payload.properties?clone(payload.properties):{};if(isDefined(payload.options)){payload.options=clone(payload.options);}else {payload.options=undefined;}var nameForProperties=isString(payload.name)?payload.name:payload.properties.name;var categoryForProperties=isString(payload.category)?payload.category:payload.properties.category;// add name and category to properties
907
+ payload.properties=mergeDeepRight(isObjectLiteralAndNotNull(payload.properties)?payload.properties:{},_objectSpread2(_objectSpread2({},nameForProperties&&{name:nameForProperties}),categoryForProperties&&{category:categoryForProperties}));return payload;};/*
908
+ * Normalise the overloaded arguments of the track call facade
909
+ */var trackArgumentsToCallOptions=function trackArgumentsToCallOptions(event,properties,options,callback){var payload={name:event,properties:properties,options:options,callback:undefined};if(isFunction(callback)){payload.callback=callback;}if(isFunction(options)){payload.properties=properties;payload.options=undefined;payload.callback=options;}if(isFunction(properties)){payload.properties=undefined;payload.options=undefined;payload.callback=properties;}// Rest of the code is just to clean up undefined values
910
+ // and set some proper defaults
911
+ // Also, to clone the incoming object type arguments
912
+ payload.properties=isDefinedAndNotNull(payload.properties)?clone(payload.properties):{};if(isDefined(payload.options)){payload.options=clone(payload.options);}else {payload.options=undefined;}return payload;};/*
913
+ * Normalise the overloaded arguments of the identify call facade
914
+ */var identifyArgumentsToCallOptions=function identifyArgumentsToCallOptions(userId,traits,options,callback){var payload={userId:userId,traits:traits,options:options,callback:undefined};if(isFunction(callback)){payload.callback=callback;}if(isFunction(options)){payload.userId=userId;payload.traits=traits;payload.options=undefined;payload.callback=options;}if(isFunction(traits)){payload.userId=userId;payload.traits=undefined;payload.options=undefined;payload.callback=traits;}if(isObjectLiteralAndNotNull(userId)||isNull(userId)){// Explicitly set null to prevent resetting the existing value
915
+ // in the Analytics class
916
+ payload.userId=null;payload.traits=userId;if(!isFunction(traits)){payload.options=traits;}else {payload.options=undefined;}}// Rest of the code is just to clean up undefined values
917
+ // and set some proper defaults
918
+ // Also, to clone the incoming object type arguments
919
+ payload.userId=tryStringify(payload.userId);if(isObjectLiteralAndNotNull(payload.traits)){payload.traits=clone(payload.traits);}else {payload.traits=undefined;}if(isDefined(payload.options)){payload.options=clone(payload.options);}else {payload.options=undefined;}return payload;};/*
920
+ * Normalise the overloaded arguments of the alias call facade
921
+ */var aliasArgumentsToCallOptions=function aliasArgumentsToCallOptions(to,from,options,callback){var payload={to:to,from:from,options:options,callback:undefined};if(isFunction(callback)){payload.callback=callback;}if(isFunction(options)){payload.to=to;payload.from=from;payload.options=undefined;payload.callback=options;}if(isFunction(from)){payload.to=to;payload.from=undefined;payload.options=undefined;payload.callback=from;}else if(isObjectLiteralAndNotNull(from)||isNull(from)){payload.to=to;payload.from=undefined;payload.options=from;}// Rest of the code is just to clean up undefined values
922
+ // and set some proper defaults
923
+ // Also, to clone the incoming object type arguments
924
+ if(isDefined(payload.to)){payload.to=tryStringify(payload.to);}if(isDefined(payload.from)){payload.from=tryStringify(payload.from);}else {payload.from=undefined;}if(isDefined(payload.options)){payload.options=clone(payload.options);}else {payload.options=undefined;}return payload;};/*
925
+ * Normalise the overloaded arguments of the group call facade
926
+ */var groupArgumentsToCallOptions=function groupArgumentsToCallOptions(groupId,traits,options,callback){var payload={groupId:groupId,traits:traits,options:options,callback:undefined};if(isFunction(callback)){payload.callback=callback;}if(isFunction(options)){payload.groupId=groupId;payload.traits=traits;payload.options=undefined;payload.callback=options;}if(isFunction(traits)){payload.groupId=groupId;payload.traits=undefined;payload.options=undefined;payload.callback=traits;}if(isObjectLiteralAndNotNull(groupId)||isNull(groupId)){// Explicitly set null to prevent resetting the existing value
927
+ // in the Analytics class
928
+ payload.groupId=null;payload.traits=groupId;if(!isFunction(traits)){payload.options=traits;}else {payload.options=undefined;}}// Rest of the code is just to clean up undefined values
929
+ // and set some proper defaults
930
+ // Also, to clone the incoming object type arguments
931
+ payload.groupId=tryStringify(payload.groupId);if(isObjectLiteralAndNotNull(payload.traits)){payload.traits=clone(payload.traits);}else {payload.traits=undefined;}if(isDefined(payload.options)){payload.options=clone(payload.options);}else {payload.options=undefined;}return payload;};
932
+
933
+ var CAPABILITIES_MANAGER='CapabilitiesManager';var CONFIG_MANAGER='ConfigManager';var EVENT_MANAGER='EventManager';var PLUGINS_MANAGER='PluginsManager';var USER_SESSION_MANAGER='UserSessionManager';var ERROR_HANDLER='ErrorHandler';var PLUGIN_ENGINE='PluginEngine';var STORE_MANAGER='StoreManager';var READY_API='readyApi';var EVENT_REPOSITORY='EventRepository';var EXTERNAL_SRC_LOADER='ExternalSrcLoader';var HTTP_CLIENT='HttpClient';var RS_APP='RudderStackApplication';var ANALYTICS_CORE='AnalyticsCore';
934
+
935
+ var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.7.0';var APP_NAMESPACE='com.rudderlabs.javascript';var MODULE_TYPE='npm';var ADBLOCK_PAGE_CATEGORY='RudderJS-Initiated';var ADBLOCK_PAGE_NAME='ad-block page request';var ADBLOCK_PAGE_PATH='/ad-blocked';var GLOBAL_PRELOAD_BUFFER='preloadedEventsBuffer';var CONSENT_TRACK_EVENT_NAME='Consent Management Interaction';
936
+
937
+ var QUERY_PARAM_TRAIT_PREFIX='ajs_trait_';var QUERY_PARAM_PROPERTY_PREFIX='ajs_prop_';var QUERY_PARAM_ANONYMOUS_ID_KEY='ajs_aid';var QUERY_PARAM_USER_ID_KEY='ajs_uid';var QUERY_PARAM_TRACK_EVENT_NAME_KEY='ajs_event';
938
+
939
+ var DEFAULT_XHR_TIMEOUT_MS=10*1000;// 10 seconds
940
+ var DEFAULT_COOKIE_MAX_AGE_MS=31536000*1000;// 1 year
941
+ var DEFAULT_SESSION_TIMEOUT_MS=30*60*1000;// 30 minutes
942
+ var MIN_SESSION_TIMEOUT_MS=10*1000;// 10 seconds
943
+ var DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS=10*1000;// 10 seconds
944
+ var DEBOUNCED_TIMEOUT_MS=250;// 250 milliseconds
945
+
946
+ /**
947
+ * Create globally accessible RudderStackGlobals object
948
+ */var createExposedGlobals=function createExposedGlobals(){var analyticsInstanceId=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'app';if(!globalThis.RudderStackGlobals){globalThis.RudderStackGlobals={};}if(!globalThis.RudderStackGlobals[analyticsInstanceId]){globalThis.RudderStackGlobals[analyticsInstanceId]={};}};/**
949
+ * Add move values to globally accessible RudderStackGlobals object per analytics instance
950
+ */var setExposedGlobal=function setExposedGlobal(keyName,value){var analyticsInstanceId=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'app';createExposedGlobals(analyticsInstanceId);globalThis.RudderStackGlobals[analyticsInstanceId][keyName]=value;};/**
951
+ * Get values from globally accessible RudderStackGlobals object by analytics instance
952
+ */var getExposedGlobal=function getExposedGlobal(keyName){var analyticsInstanceId=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'app';createExposedGlobals(analyticsInstanceId);return globalThis.RudderStackGlobals[analyticsInstanceId][keyName];};function debounce(func,thisArg){var delay=arguments.length>2&&arguments[2]!==undefined?arguments[2]:DEBOUNCED_TIMEOUT_MS;var timeoutId;return function(){for(var _len=arguments.length,args=new Array(_len),_key=0;_key<_len;_key++){args[_key]=arguments[_key];}globalThis.clearTimeout(timeoutId);timeoutId=globalThis.setTimeout(function(){func.apply(thisArg,args);},delay);};}
953
+
954
+ /**
955
+ * Parse query string params into object values for keys that start with a defined prefix
956
+ */var getEventDataFromQueryString=function getEventDataFromQueryString(params,dataTypeNamePrefix){var data={};params.forEach(function(value,key){if(key.startsWith(dataTypeNamePrefix)){// remove prefix from key name
957
+ var dataKey=key.substring(dataTypeNamePrefix.length);// add new key value pair in generated object
958
+ data[dataKey]=params.get(key);}});return data;};/**
959
+ * Parse query string into preload buffer events & push into existing array before any other events
960
+ */var retrieveEventsFromQueryString=function retrieveEventsFromQueryString(){var argumentsArray=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];// Mapping for trait and properties values based on key prefix
961
+ var eventArgumentToQueryParamMap={trait:QUERY_PARAM_TRAIT_PREFIX,properties:QUERY_PARAM_PROPERTY_PREFIX};var queryObject=new URLSearchParams(globalThis.location.search);// Add track events with name and properties
962
+ if(queryObject.get(QUERY_PARAM_TRACK_EVENT_NAME_KEY)){argumentsArray.unshift(['track',queryObject.get(QUERY_PARAM_TRACK_EVENT_NAME_KEY),getEventDataFromQueryString(queryObject,eventArgumentToQueryParamMap.properties)]);}// Set userId and user traits
963
+ if(queryObject.get(QUERY_PARAM_USER_ID_KEY)){argumentsArray.unshift(['identify',queryObject.get(QUERY_PARAM_USER_ID_KEY),getEventDataFromQueryString(queryObject,eventArgumentToQueryParamMap.trait)]);}// Set anonymousID
964
+ if(queryObject.get(QUERY_PARAM_ANONYMOUS_ID_KEY)){argumentsArray.unshift(['setAnonymousId',queryObject.get(QUERY_PARAM_ANONYMOUS_ID_KEY)]);}};/**
965
+ * Retrieve an existing buffered load method call and remove from the existing array
966
+ */var getPreloadedLoadEvent=function getPreloadedLoadEvent(preloadedEventsArray){var loadMethodName='load';var loadEvent=[];/**
967
+ * Iterate the buffered API calls until we find load call and process it separately
968
+ */var i=0;while(i<preloadedEventsArray.length){if(preloadedEventsArray[i]&&preloadedEventsArray[i][0]===loadMethodName){loadEvent=clone(preloadedEventsArray[i]);preloadedEventsArray.splice(i,1);break;}i+=1;}return loadEvent;};/**
969
+ * Promote consent events to the top of the preloaded events array
970
+ * @param preloadedEventsArray Preloaded events array
971
+ * @returns None
972
+ */var promotePreloadedConsentEventsToTop=function promotePreloadedConsentEventsToTop(preloadedEventsArray){var consentMethodName='consent';var consentEvents=preloadedEventsArray.filter(function(bufferedEvent){return bufferedEvent[0]===consentMethodName;});var nonConsentEvents=preloadedEventsArray.filter(function(bufferedEvent){return bufferedEvent[0]!==consentMethodName;});// Remove all elements and add consent events first followed by non consent events
973
+ // eslint-disable-next-line unicorn/no-useless-spread
974
+ preloadedEventsArray.splice.apply(preloadedEventsArray,[0,preloadedEventsArray.length].concat(_toConsumableArray(consentEvents),_toConsumableArray(nonConsentEvents)));};/**
975
+ * Retrieve any existing events that were triggered before SDK load and enqueue in buffer
976
+ */var retrievePreloadBufferEvents=function retrievePreloadBufferEvents(instance){var preloadedEventsArray=getExposedGlobal(GLOBAL_PRELOAD_BUFFER)||[];// Get events that are pre-populated via query string params
977
+ retrieveEventsFromQueryString(preloadedEventsArray);// Enqueue the non load events in the buffer of the global rudder analytics singleton
978
+ if(preloadedEventsArray.length>0){instance.enqueuePreloadBufferEvents(preloadedEventsArray);setExposedGlobal(GLOBAL_PRELOAD_BUFFER,[]);}};var consumePreloadBufferedEvent=function consumePreloadBufferedEvent(event,analyticsInstance){var _ref;var methodName=event.shift();var callOptions;if(isFunction(analyticsInstance[methodName])){switch(methodName){case'page':callOptions=pageArgumentsToCallOptions.apply(void 0,_toConsumableArray(event));break;case'track':callOptions=trackArgumentsToCallOptions.apply(void 0,_toConsumableArray(event));break;case'identify':callOptions=identifyArgumentsToCallOptions.apply(void 0,_toConsumableArray(event));break;case'alias':callOptions=aliasArgumentsToCallOptions.apply(void 0,_toConsumableArray(event));break;case'group':callOptions=groupArgumentsToCallOptions.apply(void 0,_toConsumableArray(event));break;default:(_ref=analyticsInstance)[methodName].apply(_ref,_toConsumableArray(event));break;}if(callOptions){analyticsInstance[methodName](callOptions);}}};
979
+
980
+ var DEFAULT_EXT_SRC_LOAD_TIMEOUT_MS=10*1000;// 10 seconds
981
+
982
+ var LOG_CONTEXT_SEPARATOR=':: ';var SCRIPT_ALREADY_EXISTS_ERROR=function SCRIPT_ALREADY_EXISTS_ERROR(id){return "A script with the id \"".concat(id,"\" is already loaded. Skipping the loading of this script to prevent conflicts.");};var SCRIPT_LOAD_ERROR=function SCRIPT_LOAD_ERROR(id,url){return "Failed to load the script with the id \"".concat(id,"\" from URL \"").concat(url,"\".");};var SCRIPT_LOAD_TIMEOUT_ERROR=function SCRIPT_LOAD_TIMEOUT_ERROR(id,url,timeout){return "A timeout of ".concat(timeout," ms occurred while trying to load the script with id \"").concat(id,"\" from URL \"").concat(url,"\".");};var CIRCULAR_REFERENCE_WARNING=function CIRCULAR_REFERENCE_WARNING(context,key){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"A circular reference has been detected in the object and the property \"").concat(key,"\" has been dropped from the output.");};var JSON_STRINGIFY_WARNING="Failed to convert the value to a JSON string.";
983
+
984
+ var JSON_STRINGIFY='JSONStringify';var getCircularReplacer=function getCircularReplacer(excludeNull,excludeKeys,logger){var ancestors=[];// Here we do not want to use arrow function to use "this" in function context
985
+ // eslint-disable-next-line func-names
986
+ return function(key,value){if(excludeKeys!==null&&excludeKeys!==void 0&&excludeKeys.includes(key)){return undefined;}if(excludeNull&&isNullOrUndefined(value)){return undefined;}if(_typeof(value)!=='object'||isNull(value)){return value;}// `this` is the object that value is contained in, i.e., its direct parent.
987
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment
988
+ // @ts-ignore-next-line
989
+ while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop();}if(ancestors.includes(value)){logger===null||logger===void 0||logger.warn(CIRCULAR_REFERENCE_WARNING(JSON_STRINGIFY,key));return '[Circular Reference]';}ancestors.push(value);return value;};};/**
990
+ * Utility method for JSON stringify object excluding null values & circular references
991
+ *
992
+ * @param {*} value input
993
+ * @param {boolean} excludeNull if it should exclude nul or not
994
+ * @param {function} logger optional logger methods for warning
995
+ * @returns string
996
+ */var stringifyWithoutCircular=function stringifyWithoutCircular(value,excludeNull,excludeKeys,logger){try{return JSON.stringify(value,getCircularReplacer(excludeNull,excludeKeys,logger));}catch(err){logger===null||logger===void 0||logger.warn(JSON_STRINGIFY_WARNING,err);return null;}};
997
+
998
+ /**
999
+ * Get mutated error with issue prepended to error message
1000
+ * @param err Original error
1001
+ * @param issue Issue to prepend to error message
1002
+ * @returns Instance of Error with message prepended with issue
1003
+ */var getMutatedError=function getMutatedError(err,issue){var finalError=err;if(!isTypeOfError(err)){finalError=new Error("".concat(issue,": ").concat(stringifyWithoutCircular(err)));}else {finalError.message="".concat(issue,": ").concat(err.message);}return finalError;};
1004
+
1005
+ var EXTERNAL_SOURCE_LOAD_ORIGIN='RS_JS_SDK';
1006
+
1007
+ /**
1008
+ * Create the DOM element to load a script marked as RS SDK originated
1009
+ *
1010
+ * @param {*} url The URL of the script to be loaded
1011
+ * @param {*} id ID for the script tag
1012
+ * @param {*} async Whether to load the script in async mode. Defaults to `true` [optional]
1013
+ * @param {*} onload callback to invoke onload [optional]
1014
+ * @param {*} onerror callback to invoke onerror [optional]
1015
+ * @param {*} extraAttributes key/value pair with html attributes to add in html tag [optional]
1016
+ *
1017
+ * @returns HTMLScriptElement
1018
+ */var createScriptElement=function createScriptElement(url,id){var async=arguments.length>2&&arguments[2]!==undefined?arguments[2]:true;var onload=arguments.length>3&&arguments[3]!==undefined?arguments[3]:null;var onerror=arguments.length>4&&arguments[4]!==undefined?arguments[4]:null;var extraAttributes=arguments.length>5&&arguments[5]!==undefined?arguments[5]:{};var scriptElement=document.createElement('script');scriptElement.type='text/javascript';scriptElement.onload=onload;scriptElement.onerror=onerror;scriptElement.src=url;scriptElement.id=id;scriptElement.async=async;Object.keys(extraAttributes).forEach(function(attributeName){scriptElement.setAttribute(attributeName,extraAttributes[attributeName]);});scriptElement.setAttribute('data-loader',EXTERNAL_SOURCE_LOAD_ORIGIN);return scriptElement;};/**
1019
+ * Add script DOM element to DOM
1020
+ *
1021
+ * @param {*} newScriptElement the script element to add
1022
+ *
1023
+ * @returns
1024
+ */var insertScript=function insertScript(newScriptElement){var _scriptElements$;// First try to add it to the head
1025
+ var headElements=document.getElementsByTagName('head');if(headElements.length>0){var _headElements$,_headElements$2;(_headElements$=headElements[0])===null||_headElements$===void 0||_headElements$.insertBefore(newScriptElement,(_headElements$2=headElements[0])===null||_headElements$2===void 0?void 0:_headElements$2.firstChild);return;}// Else wise add it before the first script tag
1026
+ var scriptElements=document.getElementsByTagName('script');if(scriptElements.length>0&&(_scriptElements$=scriptElements[0])!==null&&_scriptElements$!==void 0&&_scriptElements$.parentNode){var _scriptElements$2;(_scriptElements$2=scriptElements[0])===null||_scriptElements$2===void 0||_scriptElements$2.parentNode.insertBefore(newScriptElement,scriptElements[0]);return;}// Create a new head element and add the script as fallback
1027
+ var headElement=document.createElement('head');headElement.appendChild(newScriptElement);var htmlElement=document.getElementsByTagName('html')[0];htmlElement===null||htmlElement===void 0||htmlElement.insertBefore(headElement,htmlElement.firstChild);};/**
1028
+ * Loads external js file as a script html tag
1029
+ *
1030
+ * @param {*} url The URL of the script to be loaded
1031
+ * @param {*} id ID for the script tag
1032
+ * @param {*} timeout loading timeout
1033
+ * @param {*} async Whether to load the script in async mode. Defaults to `true` [optional]
1034
+ * @param {*} extraAttributes key/value pair with html attributes to add in html tag [optional]
1035
+ *
1036
+ * @returns
1037
+ */var jsFileLoader=function jsFileLoader(url,id,timeout){var async=arguments.length>3&&arguments[3]!==undefined?arguments[3]:true;var extraAttributes=arguments.length>4?arguments[4]:undefined;return new Promise(function(resolve,reject){var scriptExists=document.getElementById(id);if(scriptExists){reject(new Error(SCRIPT_ALREADY_EXISTS_ERROR(id)));}try{var timeoutID;var onload=function onload(){globalThis.clearTimeout(timeoutID);resolve(id);};var onerror=function onerror(){globalThis.clearTimeout(timeoutID);reject(new Error(SCRIPT_LOAD_ERROR(id,url)));};// Create the DOM element to load the script and add it to the DOM
1038
+ insertScript(createScriptElement(url,id,async,onload,onerror,extraAttributes));// Reject on timeout
1039
+ timeoutID=globalThis.setTimeout(function(){reject(new Error(SCRIPT_LOAD_TIMEOUT_ERROR(id,url,timeout)));},timeout);}catch(err){reject(getMutatedError(err,SCRIPT_LOAD_ERROR(id,url)));}});};
1040
+
1041
+ /**
1042
+ * Service to load external resources/files
1043
+ */var ExternalSrcLoader=/*#__PURE__*/function(){function ExternalSrcLoader(errorHandler,logger){var timeout=arguments.length>2&&arguments[2]!==undefined?arguments[2]:DEFAULT_EXT_SRC_LOAD_TIMEOUT_MS;_classCallCheck(this,ExternalSrcLoader);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.timeout=timeout;this.hasErrorHandler=Boolean(this.errorHandler);this.onError=this.onError.bind(this);}/**
1044
+ * Load external resource of type javascript
1045
+ */return _createClass(ExternalSrcLoader,[{key:"loadJSFile",value:function loadJSFile(config){var _this=this;var url=config.url,id=config.id,timeout=config.timeout,async=config.async,callback=config.callback,extraAttributes=config.extraAttributes;var isFireAndForget=!isFunction(callback);jsFileLoader(url,id,timeout||this.timeout,async,extraAttributes).then(function(id){if(!isFireAndForget){callback(id);}}).catch(function(err){_this.onError(err);if(!isFireAndForget){callback();}});}/**
1046
+ * Handle errors
1047
+ */},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError(error,EXTERNAL_SRC_LOADER);}else {throw error;}}}]);}();
1048
+
1049
+ var i$2=Symbol.for("preact-signals");function t$1(){if(!(s>1)){var i,t=!1;while(void 0!==h){var r=h;h=void 0;f++;while(void 0!==r){var o=r.o;r.o=void 0;r.f&=-3;if(!(8&r.f)&&c(r))try{r.c();}catch(r){if(!t){i=r;t=!0;}}r=o;}}f=0;s--;if(t)throw i;}else s--;}function r(i){if(s>0)return i();s++;try{return i();}finally{t$1();}}var o=void 0;var h=void 0,s=0,f=0,v=0;function e(i){if(void 0!==o){var t=i.n;if(void 0===t||t.t!==o){t={i:0,S:i,p:o.s,n:void 0,t:o,e:void 0,x:void 0,r:t};if(void 0!==o.s)o.s.n=t;o.s=t;i.n=t;if(32&o.f)i.S(t);return t;}else if(-1===t.i){t.i=0;if(void 0!==t.n){t.n.p=t.p;if(void 0!==t.p)t.p.n=t.n;t.p=o.s;t.n=void 0;o.s.n=t;o.s=t;}return t;}}}function u(i){this.v=i;this.i=0;this.n=void 0;this.t=void 0;}u.prototype.brand=i$2;u.prototype.h=function(){return !0;};u.prototype.S=function(i){if(this.t!==i&&void 0===i.e){i.x=this.t;if(void 0!==this.t)this.t.e=i;this.t=i;}};u.prototype.U=function(i){if(void 0!==this.t){var t=i.e,r=i.x;if(void 0!==t){t.x=r;i.e=void 0;}if(void 0!==r){r.e=t;i.x=void 0;}if(i===this.t)this.t=r;}};u.prototype.subscribe=function(i){var t=this;return E(function(){var r=t.value,n=o;o=void 0;try{i(r);}finally{o=n;}});};u.prototype.valueOf=function(){return this.value;};u.prototype.toString=function(){return this.value+"";};u.prototype.toJSON=function(){return this.value;};u.prototype.peek=function(){var i=o;o=void 0;try{return this.value;}finally{o=i;}};Object.defineProperty(u.prototype,"value",{get:function get(){var i=e(this);if(void 0!==i)i.i=this.i;return this.v;},set:function set(i){if(i!==this.v){if(f>100)throw new Error("Cycle detected");this.v=i;this.i++;v++;s++;try{for(var r=this.t;void 0!==r;r=r.x)r.t.N();}finally{t$1();}}}});function d$1(i){return new u(i);}function c(i){for(var t=i.s;void 0!==t;t=t.n)if(t.S.i!==t.i||!t.S.h()||t.S.i!==t.i)return !0;return !1;}function a(i){for(var t=i.s;void 0!==t;t=t.n){var r=t.S.n;if(void 0!==r)t.r=r;t.S.n=t;t.i=-1;if(void 0===t.n){i.s=t;break;}}}function l(i){var t=i.s,r=void 0;while(void 0!==t){var o=t.p;if(-1===t.i){t.S.U(t);if(void 0!==o)o.n=t.n;if(void 0!==t.n)t.n.p=o;}else r=t;t.S.n=t.r;if(void 0!==t.r)t.r=void 0;t=o;}i.s=r;}function y(i){u.call(this,void 0);this.x=i;this.s=void 0;this.g=v-1;this.f=4;}(y.prototype=new u()).h=function(){this.f&=-3;if(1&this.f)return !1;if(32==(36&this.f))return !0;this.f&=-5;if(this.g===v)return !0;this.g=v;this.f|=1;if(this.i>0&&!c(this)){this.f&=-2;return !0;}var i=o;try{a(this);o=this;var t=this.x();if(16&this.f||this.v!==t||0===this.i){this.v=t;this.f&=-17;this.i++;}}catch(i){this.v=i;this.f|=16;this.i++;}o=i;l(this);this.f&=-2;return !0;};y.prototype.S=function(i){if(void 0===this.t){this.f|=36;for(var t=this.s;void 0!==t;t=t.n)t.S.S(t);}u.prototype.S.call(this,i);};y.prototype.U=function(i){if(void 0!==this.t){u.prototype.U.call(this,i);if(void 0===this.t){this.f&=-33;for(var t=this.s;void 0!==t;t=t.n)t.S.U(t);}}};y.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var i=this.t;void 0!==i;i=i.x)i.t.N();}};Object.defineProperty(y.prototype,"value",{get:function get(){if(1&this.f)throw new Error("Cycle detected");var i=e(this);this.h();if(void 0!==i)i.i=this.i;if(16&this.f)throw this.v;return this.v;}});function _(i){var r=i.u;i.u=void 0;if("function"==typeof r){s++;var n=o;o=void 0;try{r();}catch(t){i.f&=-2;i.f|=8;g(i);throw t;}finally{o=n;t$1();}}}function g(i){for(var t=i.s;void 0!==t;t=t.n)t.S.U(t);i.x=void 0;i.s=void 0;_(i);}function p(i){if(o!==this)throw new Error("Out-of-order effect");l(this);o=i;this.f&=-2;if(8&this.f)g(this);t$1();}function b(i){this.x=i;this.u=void 0;this.s=void 0;this.o=void 0;this.f=32;}b.prototype.c=function(){var i=this.S();try{if(8&this.f)return;if(void 0===this.x)return;var t=this.x();if("function"==typeof t)this.u=t;}finally{i();}};b.prototype.S=function(){if(1&this.f)throw new Error("Cycle detected");this.f|=1;this.f&=-9;_(this);a(this);s++;var i=o;o=this;return p.bind(this,i);};b.prototype.N=function(){if(!(2&this.f)){this.f|=2;this.o=h;h=this;}};b.prototype.d=function(){this.f|=8;if(!(1&this.f))g(this);};function E(i){var t=new b(i);try{t.c();}catch(i){t.d();throw i;}return t.d.bind(t);}
1050
+
1051
+ /**
1052
+ * A buffer queue to serve as a store for any type of data
1053
+ */var BufferQueue=/*#__PURE__*/function(){function BufferQueue(){_classCallCheck(this,BufferQueue);this.items=[];}return _createClass(BufferQueue,[{key:"enqueue",value:function enqueue(item){this.items.push(item);}},{key:"dequeue",value:function dequeue(){if(this.items.length===0){return null;}return this.items.shift();}},{key:"isEmpty",value:function isEmpty(){return this.items.length===0;}},{key:"size",value:function size(){return this.items.length;}},{key:"clear",value:function clear(){this.items=[];}}]);}();
1054
+
1055
+ var LOG_LEVEL_MAP={LOG:0,INFO:1,DEBUG:2,WARN:3,ERROR:4,NONE:5};var DEFAULT_LOG_LEVEL='ERROR';var LOG_MSG_PREFIX='RS SDK';var LOG_MSG_PREFIX_STYLE='font-weight: bold; background: black; color: white;';var LOG_MSG_STYLE='font-weight: normal;';/**
1056
+ * Service to log messages/data to output provider, default is console
1057
+ */var Logger=/*#__PURE__*/function(){function Logger(){var minLogLevel=arguments.length>0&&arguments[0]!==undefined?arguments[0]:DEFAULT_LOG_LEVEL;var scope=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var logProvider=arguments.length>2&&arguments[2]!==undefined?arguments[2]:console;_classCallCheck(this,Logger);this.minLogLevel=LOG_LEVEL_MAP[minLogLevel];this.scope=scope;this.logProvider=logProvider;}return _createClass(Logger,[{key:"log",value:function log(){for(var _len=arguments.length,data=new Array(_len),_key=0;_key<_len;_key++){data[_key]=arguments[_key];}this.outputLog('LOG',data);}},{key:"info",value:function info(){for(var _len2=arguments.length,data=new Array(_len2),_key2=0;_key2<_len2;_key2++){data[_key2]=arguments[_key2];}this.outputLog('INFO',data);}},{key:"debug",value:function debug(){for(var _len3=arguments.length,data=new Array(_len3),_key3=0;_key3<_len3;_key3++){data[_key3]=arguments[_key3];}this.outputLog('DEBUG',data);}},{key:"warn",value:function warn(){for(var _len4=arguments.length,data=new Array(_len4),_key4=0;_key4<_len4;_key4++){data[_key4]=arguments[_key4];}this.outputLog('WARN',data);}},{key:"error",value:function error(){for(var _len5=arguments.length,data=new Array(_len5),_key5=0;_key5<_len5;_key5++){data[_key5]=arguments[_key5];}this.outputLog('ERROR',data);}},{key:"outputLog",value:function outputLog(logMethod,data){if(this.minLogLevel<=LOG_LEVEL_MAP[logMethod]){var _this$logProvider,_this$logProvider2;(_this$logProvider=(_this$logProvider2=this.logProvider)[logMethod.toLowerCase()])===null||_this$logProvider===void 0||_this$logProvider.call.apply(_this$logProvider,[_this$logProvider2].concat(_toConsumableArray(this.formatLogData(data))));}}},{key:"setScope",value:function setScope(scopeVal){this.scope=scopeVal||this.scope;}// TODO: should we allow to change the level via global variable on run time
1058
+ // to assist on the fly debugging?
1059
+ },{key:"setMinLogLevel",value:function setMinLogLevel(logLevel){this.minLogLevel=LOG_LEVEL_MAP[logLevel];if(isUndefined(this.minLogLevel)){this.minLogLevel=LOG_LEVEL_MAP[DEFAULT_LOG_LEVEL];}}/**
1060
+ * Formats the console message using `scope` and styles
1061
+ */},{key:"formatLogData",value:function formatLogData(data){if(Array.isArray(data)&&data.length>0){// prefix SDK identifier
1062
+ var msg="%c ".concat(LOG_MSG_PREFIX);// format the log message using `scope`
1063
+ if(this.scope){msg="".concat(msg," - ").concat(this.scope);}// trim whitespaces for original message
1064
+ var originalMsg=isString(data[0])?data[0].trim():'';// prepare the final message
1065
+ msg="".concat(msg," %c ").concat(originalMsg);var styledLogArgs=[msg,LOG_MSG_PREFIX_STYLE,// add style for the prefix
1066
+ LOG_MSG_STYLE// reset the style for the actual message
1067
+ ];// add first it if it was not a string msg
1068
+ if(!isString(data[0])){styledLogArgs.push(data[0]);}// append rest of the original arguments
1069
+ styledLogArgs.push.apply(styledLogArgs,_toConsumableArray(data.slice(1)));return styledLogArgs;}return data;}}]);}();var defaultLogger=new Logger();
1070
+
1071
+ var ErrorType=/*#__PURE__*/function(ErrorType){ErrorType["HANDLEDEXCEPTION"]="handledException";ErrorType["UNHANDLEDEXCEPTION"]="unhandledException";ErrorType["UNHANDLEDREJECTION"]="unhandledPromiseRejection";return ErrorType;}({});
1072
+
1073
+ // default is v3
1074
+ var SUPPORTED_STORAGE_TYPES=['localStorage','memoryStorage','cookieStorage','sessionStorage','none'];var DEFAULT_STORAGE_TYPE='cookieStorage';
1075
+
1076
+ var SOURCE_CONFIG_OPTION_ERROR="\"getSourceConfig\" must be a function. Please make sure that it is defined and returns a valid source configuration object.";var SOURCE_CONFIG_RESOLUTION_ERROR="Unable to process/parse source configuration response.";var SOURCE_DISABLED_ERROR="The source is disabled. Please enable the source in the dashboard to send events.";var XHR_PAYLOAD_PREP_ERROR="Failed to prepare data for the request.";var EVENT_OBJECT_GENERATION_ERROR="Failed to generate the event object.";var PLUGIN_EXT_POINT_MISSING_ERROR="Failed to invoke plugin because the extension point name is missing.";var PLUGIN_EXT_POINT_INVALID_ERROR="Failed to invoke plugin because the extension point name is invalid.";var COMPONENT_BASE_URL_ERROR=function COMPONENT_BASE_URL_ERROR(component){return "Failed to load the SDK as the base URL for ".concat(component," is not valid.");};// ERROR
1077
+ var UNSUPPORTED_CONSENT_MANAGER_ERROR=function UNSUPPORTED_CONSENT_MANAGER_ERROR(context,selectedConsentManager,consentManagersToPluginNameMap){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The consent manager \"").concat(selectedConsentManager,"\" is not supported. Please choose one of the following supported consent managers: \"").concat(Object.keys(consentManagersToPluginNameMap),"\".");};var REPORTING_PLUGIN_INIT_FAILURE_ERROR=function REPORTING_PLUGIN_INIT_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to initialize the error reporting plugin.");};var NOTIFY_FAILURE_ERROR=function NOTIFY_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to notify the error.");};var PLUGIN_NAME_MISSING_ERROR=function PLUGIN_NAME_MISSING_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin name is missing.");};var PLUGIN_ALREADY_EXISTS_ERROR=function PLUGIN_ALREADY_EXISTS_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" already exists.");};var PLUGIN_NOT_FOUND_ERROR=function PLUGIN_NOT_FOUND_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found.");};var PLUGIN_ENGINE_BUG_ERROR=function PLUGIN_ENGINE_BUG_ERROR(context,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" not found in plugins but found in byName. This indicates a bug in the plugin engine. Please report this issue to the development team.");};var PLUGIN_DEPS_ERROR=function PLUGIN_DEPS_ERROR(context,pluginName,notExistDeps){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Plugin \"").concat(pluginName,"\" could not be loaded because some of its dependencies \"").concat(notExistDeps,"\" do not exist.");};var PLUGIN_INVOCATION_ERROR=function PLUGIN_INVOCATION_ERROR(context,extPoint,pluginName){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to invoke the \"").concat(extPoint,"\" extension point of plugin \"").concat(pluginName,"\".");};var STORAGE_UNAVAILABILITY_ERROR_PREFIX=function STORAGE_UNAVAILABILITY_ERROR_PREFIX(context,storageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(storageType,"\" storage type is ");};var SOURCE_CONFIG_FETCH_ERROR=function SOURCE_CONFIG_FETCH_ERROR(reason){return "Failed to fetch the source config. Reason: ".concat(reason);};var WRITE_KEY_VALIDATION_ERROR=function WRITE_KEY_VALIDATION_ERROR(writeKey){return "The write key \"".concat(writeKey,"\" is invalid. It must be a non-empty string. Please check that the write key is correct and try again.");};var DATA_PLANE_URL_VALIDATION_ERROR=function DATA_PLANE_URL_VALIDATION_ERROR(dataPlaneUrl){return "The data plane URL \"".concat(dataPlaneUrl,"\" is invalid. It must be a valid URL string. Please check that the data plane URL is correct and try again.");};var READY_API_CALLBACK_ERROR=function READY_API_CALLBACK_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The callback is not a function.");};var XHR_DELIVERY_ERROR=function XHR_DELIVERY_ERROR(prefix,status,statusText,url){return "".concat(prefix," with status: ").concat(status,", ").concat(statusText," for URL: ").concat(url,".");};var XHR_REQUEST_ERROR=function XHR_REQUEST_ERROR(prefix,e,url){return "".concat(prefix," due to timeout or no connection (").concat(e?e.type:'',") for URL: ").concat(url,".");};var XHR_SEND_ERROR=function XHR_SEND_ERROR(prefix,url){return "".concat(prefix," for URL: ").concat(url);};var STORE_DATA_SAVE_ERROR=function STORE_DATA_SAVE_ERROR(key){return "Failed to save the value for \"".concat(key,"\" to storage");};var STORE_DATA_FETCH_ERROR=function STORE_DATA_FETCH_ERROR(key){return "Failed to retrieve or parse data for \"".concat(key,"\" from storage");};var DATA_SERVER_REQUEST_FAIL_ERROR=function DATA_SERVER_REQUEST_FAIL_ERROR(status){return "The server responded with status ".concat(status," while setting the cookies. As a fallback, the cookies will be set client side.");};var FAILED_SETTING_COOKIE_FROM_SERVER_ERROR=function FAILED_SETTING_COOKIE_FROM_SERVER_ERROR(key){return "The server failed to set the ".concat(key," cookie. As a fallback, the cookies will be set client side.");};var FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR="Failed to set/remove cookies via server. As a fallback, the cookies will be managed client side.";// WARNING
1078
+ var STORAGE_TYPE_VALIDATION_WARNING=function STORAGE_TYPE_VALIDATION_WARNING(context,storageType,defaultStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(storageType,"\" is not supported. Please choose one of the following supported types: \"").concat(SUPPORTED_STORAGE_TYPES,"\". The default type \"").concat(defaultStorageType,"\" will be used instead.");};var UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING=function UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(context,selectedStorageEncryptionVersion,storageEncryptionVersionsToPluginNameMap,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage encryption version \"").concat(selectedStorageEncryptionVersion,"\" is not supported. Please choose one of the following supported versions: \"").concat(Object.keys(storageEncryptionVersionsToPluginNameMap),"\". The default version \"").concat(defaultVersion,"\" will be used instead.");};var STORAGE_DATA_MIGRATION_OVERRIDE_WARNING=function STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(context,storageEncryptionVersion,defaultVersion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage data migration has been disabled because the configured storage encryption version (").concat(storageEncryptionVersion,") is not the latest (").concat(defaultVersion,"). To enable storage data migration, please update the storage encryption version to the latest version.");};var SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING=function SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING(context,providedCookieDomain,currentCookieDomain){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided cookie domain (").concat(providedCookieDomain,") does not match the current webpage's domain (").concat(currentCookieDomain,"). Hence, the cookies will be set client-side.");};var RESERVED_KEYWORD_WARNING=function RESERVED_KEYWORD_WARNING(context,property,parentKeyPath,reservedElements){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(property,"\" property defined under \"").concat(parentKeyPath,"\" is a reserved keyword. Please choose a different property name to avoid conflicts with reserved keywords (").concat(reservedElements,").");};var UNSUPPORTED_BEACON_API_WARNING=function UNSUPPORTED_BEACON_API_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The Beacon API is not supported by your browser. The events will be sent using XHR instead.");};var TIMEOUT_NOT_NUMBER_WARNING=function TIMEOUT_NOT_NUMBER_WARNING(context,timeout,defaultValue){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value \"").concat(timeout,"\" is not a number. The default timeout of ").concat(defaultValue," ms will be used instead.");};var TIMEOUT_ZERO_WARNING=function TIMEOUT_ZERO_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value is 0, which disables the automatic session tracking feature. If you want to enable session tracking, please provide a positive integer value for the timeout.");};var TIMEOUT_NOT_RECOMMENDED_WARNING=function TIMEOUT_NOT_RECOMMENDED_WARNING(context,timeout,minTimeout){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The session timeout value ").concat(timeout," ms is less than the recommended minimum of ").concat(minTimeout," ms. Please consider increasing the timeout value to ensure optimal performance and reliability.");};var INVALID_SESSION_ID_WARNING=function INVALID_SESSION_ID_WARNING(context,sessionId,minSessionIdLength){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided session ID (").concat(sessionId,") is either invalid, not a positive integer, or not at least \"").concat(minSessionIdLength,"\" digits long. A new session ID will be auto-generated instead.");};var STORAGE_QUOTA_EXCEEDED_WARNING=function STORAGE_QUOTA_EXCEEDED_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage is either full or unavailable, so the data will not be persisted. Switching to in-memory storage.");};var STORAGE_UNAVAILABLE_WARNING=function STORAGE_UNAVAILABLE_WARNING(context,entry,selectedStorageType,finalStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(selectedStorageType,"\" is not available for entry \"").concat(entry,"\". The SDK will initialize the entry with \"").concat(finalStorageType,"\" storage type instead.");};var WRITE_KEY_NOT_A_STRING_ERROR=function WRITE_KEY_NOT_A_STRING_ERROR(context,writeKey){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The write key \"").concat(writeKey,"\" is not a string. Please check that the write key is correct and try again.");};var EMPTY_GROUP_CALL_ERROR=function EMPTY_GROUP_CALL_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The group() method must be called with at least one argument.");};var READY_CALLBACK_INVOKE_ERROR="Failed to invoke the ready callback";var API_CALLBACK_INVOKE_ERROR="API Callback Invocation Failed";var NATIVE_DEST_PLUGIN_INITIALIZE_ERROR="NativeDestinationQueuePlugin initialization failed";var DATAPLANE_PLUGIN_INITIALIZE_ERROR="XhrQueuePlugin initialization failed";var DMT_PLUGIN_INITIALIZE_ERROR="DeviceModeTransformationPlugin initialization failed";var NATIVE_DEST_PLUGIN_ENQUEUE_ERROR="NativeDestinationQueuePlugin event enqueue failed";var DATAPLANE_PLUGIN_ENQUEUE_ERROR="XhrQueuePlugin event enqueue failed";var INVALID_CONFIG_URL_WARNING=function INVALID_CONFIG_URL_WARNING(context,configUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided source config URL \"").concat(configUrl,"\" is invalid. Using the default source config URL instead.");};var POLYFILL_SCRIPT_LOAD_ERROR=function POLYFILL_SCRIPT_LOAD_ERROR(scriptId,url){return "Failed to load the polyfill script with ID \"".concat(scriptId,"\" from URL ").concat(url,".");};var UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY=function UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY(context,selectedStrategy,defaultStrategy){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The pre-consent storage strategy \"").concat(selectedStrategy,"\" is not supported. Please choose one of the following supported strategies: \"none, session, anonymousId\". The default strategy \"").concat(defaultStrategy,"\" will be used instead.");};var UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE=function UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE(context,selectedDeliveryType,defaultDeliveryType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The pre-consent events delivery type \"").concat(selectedDeliveryType,"\" is not supported. Please choose one of the following supported types: \"immediate, buffer\". The default type \"").concat(defaultDeliveryType,"\" will be used instead.");};var generateMisconfiguredPluginsWarning=function generateMisconfiguredPluginsWarning(context,configurationStatus,missingPlugins,shouldAddMissingPlugins){var isSinglePlugin=missingPlugins.length===1;var pluginsString=isSinglePlugin?" '".concat(missingPlugins[0],"' plugin was"):" ['".concat(missingPlugins.join("', '"),"'] plugins were");var baseWarning="".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(configurationStatus,", but").concat(pluginsString," not configured to load.");if(shouldAddMissingPlugins){return "".concat(baseWarning," So, ").concat(isSinglePlugin?'the plugin':'those plugins'," will be loaded automatically.");}return "".concat(baseWarning," Ignore if this was intentional. Otherwise, consider adding ").concat(isSinglePlugin?'it':'them'," to the 'plugins' load API option.");};var INVALID_POLYFILL_URL_WARNING=function INVALID_POLYFILL_URL_WARNING(context,customPolyfillUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided polyfill URL \"").concat(customPolyfillUrl,"\" is invalid. The default polyfill URL will be used instead.");};// DEBUG
1079
+
1080
+ var CDN_INT_DIR='js-integrations';var CDN_PLUGINS_DIR='plugins';var URL_PATTERN=new RegExp('^(https?:\\/\\/)'+// protocol
1081
+ '('+'((([a-zA-Z\\d]([a-zA-Z\\d-]*[a-zA-Z\\d])*)\\.)+[a-zA-Z]{2,}|'+// domain name
1082
+ 'localhost|'+// localhost
1083
+ '((25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9]?)\\.){3}'+// OR IP (v4) address first 3 octets
1084
+ '(25[0-5]|2[0-4][0-9]|[0-1]?[0-9]?[0-9]?))'+// last octet of IP address
1085
+ ')'+'(\\:\\d+)?'+// port
1086
+ '(\\/[-a-zA-Z\\d%_.~+]*)*'+// path
1087
+ '(\\?[;&a-zA-Z\\d%_.~+=-]*)?'+// query string
1088
+ '(\\#[-a-zA-Z\\d_]*)?$')// fragment locator
1089
+ ;
1090
+
1091
+ var BUILD_TYPE='legacy';var SDK_CDN_BASE_URL='https://cdn.rudderlabs.com';var CDN_ARCH_VERSION_DIR='v3';var DEST_SDK_BASE_URL="".concat(SDK_CDN_BASE_URL,"/").concat(CDN_ARCH_VERSION_DIR,"/").concat(BUILD_TYPE,"/").concat(CDN_INT_DIR);var PLUGINS_BASE_URL="".concat(SDK_CDN_BASE_URL,"/").concat(CDN_ARCH_VERSION_DIR,"/").concat(BUILD_TYPE,"/").concat(CDN_PLUGINS_DIR);var DEFAULT_CONFIG_BE_URL='https://api.rudderstack.com';
1092
+
1093
+ var DEFAULT_STORAGE_ENCRYPTION_VERSION='v3';var DEFAULT_DATA_PLANE_EVENTS_TRANSPORT='xhr';var ConsentManagersToPluginNameMap={oneTrust:'OneTrustConsentManager',ketch:'KetchConsentManager',custom:'CustomConsentManager'};var StorageEncryptionVersionsToPluginNameMap=_defineProperty(_defineProperty({},DEFAULT_STORAGE_ENCRYPTION_VERSION,'StorageEncryption'),"legacy",'StorageEncryptionLegacy');var DataPlaneEventsTransportToPluginNameMap=_defineProperty(_defineProperty({},DEFAULT_DATA_PLANE_EVENTS_TRANSPORT,'XhrQueue'),"beacon",'BeaconQueue');var DEFAULT_DATA_SERVICE_ENDPOINT='rsaRequest';var METRICS_SERVICE_ENDPOINT='rsaMetrics';
1094
+
1095
+ var defaultLoadOptions={logLevel:'ERROR',configUrl:DEFAULT_CONFIG_BE_URL,loadIntegration:true,sessions:{autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS},sameSiteCookie:'Lax',polyfillIfRequired:true,integrations:{All:true},useBeacon:false,beaconQueueOptions:{},destinationsQueueOptions:{},queueOptions:{},lockIntegrationsVersion:false,lockPluginsVersion:false,uaChTrackLevel:'none',plugins:[],useGlobalIntegrationsConfigInEvents:false,bufferDataPlaneEventsUntilReady:false,dataPlaneEventsBufferTimeout:DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS,storage:{encryption:{version:DEFAULT_STORAGE_ENCRYPTION_VERSION},migrate:true},sendAdblockPageOptions:{},useServerSideCookies:false};var loadOptionsState=d$1(clone(defaultLoadOptions));
1096
+
1097
+ var DEFAULT_USER_SESSION_VALUES={userId:'',userTraits:{},anonymousId:'',groupId:'',groupTraits:{},initialReferrer:'',initialReferringDomain:'',sessionInfo:{},authToken:null};var SERVER_SIDE_COOKIES_DEBOUNCE_TIME=10;// milliseconds
1098
+
1099
+ var defaultSessionConfiguration={autoTrack:true,timeout:DEFAULT_SESSION_TIMEOUT_MS};var sessionState={userId:d$1(DEFAULT_USER_SESSION_VALUES.userId),userTraits:d$1(DEFAULT_USER_SESSION_VALUES.userTraits),anonymousId:d$1(DEFAULT_USER_SESSION_VALUES.anonymousId),groupId:d$1(DEFAULT_USER_SESSION_VALUES.groupId),groupTraits:d$1(DEFAULT_USER_SESSION_VALUES.groupTraits),initialReferrer:d$1(DEFAULT_USER_SESSION_VALUES.initialReferrer),initialReferringDomain:d$1(DEFAULT_USER_SESSION_VALUES.initialReferringDomain),sessionInfo:d$1(DEFAULT_USER_SESSION_VALUES.sessionInfo),authToken:d$1(DEFAULT_USER_SESSION_VALUES.authToken)};
1100
+
1101
+ var capabilitiesState={isOnline:d$1(true),storage:{isLocalStorageAvailable:d$1(false),isCookieStorageAvailable:d$1(false),isSessionStorageAvailable:d$1(false)},isBeaconAvailable:d$1(false),isLegacyDOM:d$1(false),isUaCHAvailable:d$1(false),isCryptoAvailable:d$1(false),isIE11:d$1(false),isAdBlocked:d$1(false)};
1102
+
1103
+ var reportingState={isErrorReportingEnabled:d$1(false),isMetricsReportingEnabled:d$1(false),isErrorReportingPluginLoaded:d$1(false),breadcrumbs:d$1([])};
1104
+
1105
+ var sourceConfigState=d$1(undefined);
1106
+
1107
+ var lifecycleState={activeDataplaneUrl:d$1(undefined),integrationsCDNPath:d$1(DEST_SDK_BASE_URL),pluginsCDNPath:d$1(PLUGINS_BASE_URL),sourceConfigUrl:d$1(undefined),status:d$1(undefined),initialized:d$1(false),logLevel:d$1('ERROR'),loaded:d$1(false),readyCallbacks:d$1([]),writeKey:d$1(undefined),dataPlaneUrl:d$1(undefined)};
1108
+
1109
+ var consentsState={enabled:d$1(false),initialized:d$1(false),data:d$1({}),activeConsentManagerPluginName:d$1(undefined),preConsent:d$1({enabled:false}),postConsent:d$1({}),resolutionStrategy:d$1('and'),provider:d$1(undefined),metadata:d$1(undefined)};
1110
+
1111
+ var metricsState={retries:d$1(0),dropped:d$1(0),sent:d$1(0),queued:d$1(0),triggered:d$1(0),metricsServiceUrl:d$1(undefined)};
1112
+
1113
+ var contextState={app:d$1({name:APP_NAME,namespace:APP_NAMESPACE,version:APP_VERSION,installType:MODULE_TYPE}),traits:d$1(null),library:d$1({name:APP_NAME,version:APP_VERSION,snippetVersion:globalThis.RudderSnippetVersion}),userAgent:d$1(''),device:d$1(null),network:d$1(null),os:d$1({name:'',version:''}),locale:d$1(null),screen:d$1({density:0,width:0,height:0,innerWidth:0,innerHeight:0}),'ua-ch':d$1(undefined),timezone:d$1(undefined)};
1114
+
1115
+ var nativeDestinationsState={configuredDestinations:d$1([]),activeDestinations:d$1([]),loadOnlyIntegrations:d$1({}),failedDestinations:d$1([]),loadIntegration:d$1(true),initializedDestinations:d$1([]),clientDestinationsReady:d$1(false),integrationsConfig:d$1({})};
1116
+
1117
+ var eventBufferState={toBeProcessedArray:d$1([]),readyCallbacksArray:d$1([])};
1118
+
1119
+ var pluginsState={ready:d$1(false),loadedPlugins:d$1([]),failedPlugins:d$1([]),pluginsToLoadFromConfig:d$1([]),activePlugins:d$1([]),totalPluginsToLoad:d$1(0)};
1120
+
1121
+ var storageState={encryptionPluginName:d$1(undefined),migrate:d$1(false),type:d$1(undefined),cookie:d$1(undefined),entries:d$1({}),trulyAnonymousTracking:d$1(false)};
1122
+
1123
+ var serverSideCookiesState={isEnabledServerSideCookies:d$1(false),dataServiceUrl:d$1(undefined)};
1124
+
1125
+ var dataPlaneEventsState={eventsQueuePluginName:d$1(undefined),deliveryEnabled:d$1(true)// Delivery should always happen
1126
+ };
1127
+
1128
+ var defaultStateValues={capabilities:capabilitiesState,consents:consentsState,context:contextState,eventBuffer:eventBufferState,lifecycle:lifecycleState,loadOptions:loadOptionsState,metrics:metricsState,nativeDestinations:nativeDestinationsState,plugins:pluginsState,reporting:reportingState,session:sessionState,source:sourceConfigState,storage:storageState,serverCookies:serverSideCookiesState,dataPlaneEvents:dataPlaneEventsState};var state=_objectSpread2({},clone(defaultStateValues));
1129
+
1130
+ // to next or return the value if it is the last one instead of an array per
1131
+ // plugin that is the normal invoke
1132
+ // TODO: add invoke method for extension point that we know only one plugin can be used. add invokeMultiple and invokeSingle methods
1133
+ var PluginEngine=/*#__PURE__*/function(){function PluginEngine(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var logger=arguments.length>1?arguments[1]:undefined;_classCallCheck(this,PluginEngine);_defineProperty(this,"plugins",[]);_defineProperty(this,"byName",{});_defineProperty(this,"cache",{});_defineProperty(this,"config",{throws:true});this.config=_objectSpread2({throws:true},options);this.logger=logger;}return _createClass(PluginEngine,[{key:"register",value:function register(plugin,state){if(!plugin.name){var errorMessage=PLUGIN_NAME_MISSING_ERROR(PLUGIN_ENGINE);if(this.config.throws){throw new Error(errorMessage);}else {var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.error(errorMessage,plugin);}}if(this.byName[plugin.name]){var _errorMessage=PLUGIN_ALREADY_EXISTS_ERROR(PLUGIN_ENGINE,plugin.name);if(this.config.throws){throw new Error(_errorMessage);}else {var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(_errorMessage);}}this.cache={};this.plugins=this.plugins.slice();var pos=this.plugins.length;this.plugins.forEach(function(pluginItem,index){var _pluginItem$deps;if((_pluginItem$deps=pluginItem.deps)!==null&&_pluginItem$deps!==void 0&&_pluginItem$deps.includes(plugin.name)){pos=Math.min(pos,index);}});this.plugins.splice(pos,0,plugin);this.byName[plugin.name]=plugin;if(isFunction(plugin.initialize)){plugin.initialize(state);}}},{key:"unregister",value:function unregister(name){var plugin=this.byName[name];if(!plugin){var errorMessage=PLUGIN_NOT_FOUND_ERROR(PLUGIN_ENGINE,name);if(this.config.throws){throw new Error(errorMessage);}else {var _this$logger3;(_this$logger3=this.logger)===null||_this$logger3===void 0||_this$logger3.error(errorMessage);}}var index=this.plugins.indexOf(plugin);if(index===-1){var _errorMessage2=PLUGIN_ENGINE_BUG_ERROR(PLUGIN_ENGINE,name);if(this.config.throws){throw new Error(_errorMessage2);}else {var _this$logger4;(_this$logger4=this.logger)===null||_this$logger4===void 0||_this$logger4.error(_errorMessage2);}}this.cache={};delete this.byName[name];this.plugins=this.plugins.slice();this.plugins.splice(index,1);}},{key:"getPlugin",value:function getPlugin(name){return this.byName[name];}},{key:"getPlugins",value:function getPlugins(extPoint){var _this=this;var lifeCycleName=extPoint!==null&&extPoint!==void 0?extPoint:'.';if(!this.cache[lifeCycleName]){this.cache[lifeCycleName]=this.plugins.filter(function(plugin){var _plugin$deps;if((_plugin$deps=plugin.deps)!==null&&_plugin$deps!==void 0&&_plugin$deps.some(function(dependency){return !_this.byName[dependency];})){var _this$logger5;// If deps not exist, then not load it.
1134
+ var notExistDeps=plugin.deps.filter(function(dependency){return !_this.byName[dependency];});(_this$logger5=_this.logger)===null||_this$logger5===void 0||_this$logger5.error(PLUGIN_DEPS_ERROR(PLUGIN_ENGINE,plugin.name,notExistDeps));return false;}return lifeCycleName==='.'?true:hasValueByPath(plugin,lifeCycleName);});}return this.cache[lifeCycleName];}// This method allows to process this.plugins so that it could
1135
+ // do some unified pre-process before application starts.
1136
+ },{key:"processRawPlugins",value:function processRawPlugins(callback){callback(this.plugins);this.cache={};}},{key:"invoke",value:function invoke(extPoint){var _this$config$throws,_this2=this;var allowMultiple=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;for(var _len=arguments.length,args=new Array(_len>2?_len-2:0),_key=2;_key<_len;_key++){args[_key-2]=arguments[_key];}var extensionPointName=extPoint;if(!extensionPointName){throw new Error(PLUGIN_EXT_POINT_MISSING_ERROR);}var noCall=extensionPointName.startsWith('!');var throws=(_this$config$throws=this.config.throws)!==null&&_this$config$throws!==void 0?_this$config$throws:extensionPointName.endsWith('!');// eslint-disable-next-line unicorn/better-regex
1137
+ extensionPointName=extensionPointName.replace(/(^!|!$)/g,'');if(!extensionPointName){throw new Error(PLUGIN_EXT_POINT_INVALID_ERROR);}var extensionPointNameParts=extensionPointName.split('.');extensionPointNameParts.pop();var pluginMethodPath=extensionPointNameParts.join('.');var pluginsToInvoke=allowMultiple?this.getPlugins(extensionPointName):[this.getPlugins(extensionPointName)[0]];return pluginsToInvoke.map(function(plugin){var method=getValueByPath(plugin,extensionPointName);if(!isFunction(method)||noCall){return method;}try{return method.apply(getValueByPath(plugin,pluginMethodPath),args);}catch(err){// When a plugin failed, doesn't break the app
1138
+ if(throws){throw err;}else {var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===void 0||_this2$logger.error(PLUGIN_INVOCATION_ERROR(PLUGIN_ENGINE,extensionPointName,plugin.name),err);}}return null;});}},{key:"invokeSingle",value:function invokeSingle(extPoint){for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){args[_key2-1]=arguments[_key2];}return this.invoke.apply(this,[extPoint,false].concat(args))[0];}},{key:"invokeMultiple",value:function invokeMultiple(extPoint){for(var _len3=arguments.length,args=new Array(_len3>1?_len3-1:0),_key3=1;_key3<_len3;_key3++){args[_key3-1]=arguments[_key3];}return this.invoke.apply(this,[extPoint,true].concat(args));}}]);}();var defaultPluginEngine=new PluginEngine({throws:true},defaultLogger);
1139
+
1140
+ var FAILED_REQUEST_ERR_MSG_PREFIX='The request failed';var ERROR_MESSAGES_TO_BE_FILTERED=[FAILED_REQUEST_ERR_MSG_PREFIX];
1141
+
1142
+ var LOAD_ORIGIN='RS_JS_SDK';
1143
+
1144
+ /**
1145
+ * Utility method to normalise errors
1146
+ */var processError=function processError(error){var errorMessage;try{if(isString(error)){errorMessage=error;}else if(error instanceof Error){errorMessage=error.message;}else if(error instanceof ErrorEvent){errorMessage=error.message;}else {errorMessage=error.message?error.message:stringifyWithoutCircular(error);}}catch(e){errorMessage="Unknown error: ".concat(e.message);}return errorMessage;};var getNormalizedErrorForUnhandledError=function getNormalizedErrorForUnhandledError(error){try{if(error instanceof Error||error instanceof ErrorEvent||error instanceof PromiseRejectionEvent&&error.reason){return error;}// TODO: remove this block once all device mode integrations start using the v3 script loader module (TS)
1147
+ if(error instanceof Event){var eventTarget=error.target;// Discard all the non-script loading errors
1148
+ if(eventTarget&&eventTarget.localName!=='script'){return undefined;}// Discard script errors that are not originated at SDK or from native SDKs
1149
+ if(eventTarget!==null&&eventTarget!==void 0&&eventTarget.dataset&&(eventTarget.dataset.loader!==LOAD_ORIGIN||eventTarget.dataset.isnonnativesdk!=='true')){return undefined;}var errorMessage="Error in loading a third-party script from URL ".concat(eventTarget===null||eventTarget===void 0?void 0:eventTarget.src," with ID ").concat(eventTarget===null||eventTarget===void 0?void 0:eventTarget.id,".");return Object.create(error,{message:{value:errorMessage}});}return error;}catch(e){return e;}};/**
1150
+ * A function to determine whether the error should be promoted to notify or not
1151
+ * @param {Error} error
1152
+ * @returns
1153
+ */var isAllowedToBeNotified=function isAllowedToBeNotified(error){if((error instanceof Error||error instanceof ErrorEvent)&&error.message){return !ERROR_MESSAGES_TO_BE_FILTERED.some(function(e){return error.message.includes(e);});}if(error instanceof PromiseRejectionEvent&&typeof error.reason==='string'){return !ERROR_MESSAGES_TO_BE_FILTERED.some(function(e){return error.reason.includes(e);});}return true;};
1154
+
1155
+ /**
1156
+ * A service to handle errors
1157
+ */var ErrorHandler=/*#__PURE__*/function(){// If no logger is passed errors will be thrown as unhandled error
1158
+ function ErrorHandler(logger,pluginEngine){_classCallCheck(this,ErrorHandler);this.logger=logger;this.pluginEngine=pluginEngine;this.errorBuffer=new BufferQueue();this.attachEffect();}return _createClass(ErrorHandler,[{key:"attachEffect",value:function attachEffect(){if(state.reporting.isErrorReportingPluginLoaded.value===true){while(this.errorBuffer.size()>0){var errorToProcess=this.errorBuffer.dequeue();if(errorToProcess){// send it to the plugin
1159
+ this.notifyError(errorToProcess.error,errorToProcess.errorState);}}}}},{key:"attachErrorListeners",value:function attachErrorListeners(){var _this=this;if('addEventListener'in globalThis){globalThis.addEventListener('error',function(event){_this.onError(event,undefined,undefined,undefined,ErrorType.UNHANDLEDEXCEPTION);});globalThis.addEventListener('unhandledrejection',function(event){_this.onError(event,undefined,undefined,undefined,ErrorType.UNHANDLEDREJECTION);});}else {var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.debug("Failed to attach global error listeners.");}}},{key:"init",value:function init(httpClient,externalSrcLoader){var _this2=this;this.httpClient=httpClient;// Below lines are only kept for backward compatibility
1160
+ // TODO: Remove this in the next major release
1161
+ if(!this.pluginEngine){return;}try{var extPoint='errorReporting.init';var errReportingInitVal=this.pluginEngine.invokeSingle(extPoint,state,this.pluginEngine,externalSrcLoader,this.logger,true);if(errReportingInitVal instanceof Promise){errReportingInitVal.then(function(client){_this2.errReportingClient=client;}).catch(function(err){var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===void 0||_this2$logger.error(REPORTING_PLUGIN_INIT_FAILURE_ERROR(ERROR_HANDLER),err);});}}catch(err){this.onError(err,ERROR_HANDLER);}}},{key:"onError",value:function onError(error){var context=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'';var customMessage=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'';var shouldAlwaysThrow=arguments.length>3&&arguments[3]!==undefined?arguments[3]:false;var errorType=arguments.length>4&&arguments[4]!==undefined?arguments[4]:ErrorType.HANDLEDEXCEPTION;var normalizedError;var errorMessage;if(errorType===ErrorType.HANDLEDEXCEPTION){errorMessage=processError(error);// If no error message after we normalize, then we swallow/ignore the errors
1162
+ if(!errorMessage){return;}errorMessage=removeDoubleSpaces("".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(customMessage," ").concat(errorMessage));normalizedError=new Error(errorMessage);if(isTypeOfError(error)){normalizedError=Object.create(error,{message:{value:errorMessage}});}}else {normalizedError=getNormalizedErrorForUnhandledError(error);}var isErrorReportingEnabled=state.reporting.isErrorReportingEnabled.value;var isErrorReportingPluginLoaded=state.reporting.isErrorReportingPluginLoaded.value;try{if(isErrorReportingEnabled){var errorState={severity:'error',unhandled:errorType!==ErrorType.HANDLEDEXCEPTION,severityReason:{type:errorType}};if(!isErrorReportingPluginLoaded){// buffer the error
1163
+ this.errorBuffer.enqueue({error:normalizedError,errorState:errorState});}else {this.notifyError(normalizedError,errorState);}}}catch(e){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),e);}if(errorType===ErrorType.HANDLEDEXCEPTION){if(this.logger){this.logger.error(errorMessage);if(shouldAlwaysThrow){throw normalizedError;}}else {throw normalizedError;}}}/**
1164
+ * Add breadcrumbs to add insight of a user's journey before an error
1165
+ * occurred and send to external error monitoring service via a plugin
1166
+ *
1167
+ * @param {string} breadcrumb breadcrumbs message
1168
+ */},{key:"leaveBreadcrumb",value:function leaveBreadcrumb(breadcrumb){if(this.pluginEngine){try{this.pluginEngine.invokeSingle('errorReporting.breadcrumb',this.pluginEngine,// deprecated parameter
1169
+ this.errReportingClient,// deprecated parameter
1170
+ breadcrumb,this.logger,state);}catch(err){this.onError(err,ERROR_HANDLER,'errorReporting.breadcrumb');}}}/**
1171
+ * Send handled errors to external error monitoring service via a plugin
1172
+ *
1173
+ * @param {Error} error Error instance from handled error
1174
+ */},{key:"notifyError",value:function notifyError(error,errorState){if(this.pluginEngine&&this.httpClient&&isAllowedToBeNotified(error)){try{this.pluginEngine.invokeSingle('errorReporting.notify',this.pluginEngine,// deprecated parameter
1175
+ this.errReportingClient,// deprecated parameter
1176
+ error,state,this.logger,this.httpClient,errorState);}catch(err){var _this$logger3;// Not calling onError here as we don't want to go into infinite loop
1177
+ (_this$logger3=this.logger)===null||_this$logger3===void 0||_this$logger3.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),err);}}}}]);}();var defaultErrorHandler=new ErrorHandler(defaultLogger,defaultPluginEngine);
1178
+
1179
+ /**
1180
+ * A function to filter and return non cloud mode destinations
1181
+ * @param destination
1182
+ *
1183
+ * @returns boolean
1184
+ */var isNonCloudDestination=function isNonCloudDestination(destination){return Boolean(destination.config.connectionMode!=='cloud'||destination.config.useNativeSDKToSend===true||// this is the older flag for hybrid mode destinations
1185
+ destination.config.useNativeSDK===true);};var isHybridModeDestination=function isHybridModeDestination(destination){return Boolean(destination.config.connectionMode==='hybrid'||destination.config.useNativeSDKToSend===true);};/**
1186
+ * A function to filter and return non cloud mode destinations
1187
+ * @param destinations
1188
+ *
1189
+ * @returns destinations
1190
+ */var getNonCloudDestinations=function getNonCloudDestinations(destinations){return destinations.filter(isNonCloudDestination);};
1191
+
1192
+ /**
1193
+ * List of plugin names that are loaded as dynamic imports in modern builds
1194
+ */var pluginNamesList=['BeaconQueue','Bugsnag',// deprecated
1195
+ 'CustomConsentManager','DeviceModeDestinations','DeviceModeTransformation','ErrorReporting','ExternalAnonymousId','GoogleLinker','KetchConsentManager','NativeDestinationQueue','OneTrustConsentManager','StorageEncryption','StorageEncryptionLegacy','StorageMigrator','XhrQueue'];
1196
+
1197
+ /**
1198
+ * To get the current timestamp in ISO string format
1199
+ * @returns ISO formatted timestamp string
1200
+ */var getCurrentTimeFormatted=function getCurrentTimeFormatted(){var curDateTime=new Date().toISOString();return curDateTime;};
1201
+
1202
+ var COOKIE_STORAGE='cookieStorage';var LOCAL_STORAGE='localStorage';var SESSION_STORAGE='sessionStorage';var MEMORY_STORAGE='memoryStorage';var NO_STORAGE='none';
1203
+
1204
+ var removeDuplicateSlashes=function removeDuplicateSlashes(str){return str.replace(/\/{2,}/g,'/');};/**
1205
+ * Checks if provided url is valid or not
1206
+ * @param url
1207
+ * @returns true if `url` is valid and false otherwise
1208
+ */var isValidURL=function isValidURL(url){if(!isString(url)){return false;}try{// If URL is supported by the browser, we can use it to validate the URL
1209
+ // Otherwise, we can at least check if the URL matches the pattern
1210
+ if(isFunction(globalThis.URL)){// eslint-disable-next-line no-new
1211
+ new URL(url);}return URL_PATTERN.test(url);}catch(e){return false;}};
1212
+
1213
+ function random(len){return crypto.getRandomValues(new Uint8Array(len));}
1214
+
1215
+ var SIZE=4096,HEX$1=[],IDX$1=0,BUFFER$1;for(;IDX$1<256;IDX$1++){HEX$1[IDX$1]=(IDX$1+256).toString(16).substring(1);}function v4$1(){if(!BUFFER$1||IDX$1+16>SIZE){BUFFER$1=random(SIZE);IDX$1=0;}var i=0,tmp,out='';for(;i<16;i++){tmp=BUFFER$1[IDX$1+i];if(i==6)out+=HEX$1[tmp&15|64];else if(i==8)out+=HEX$1[tmp&63|128];else out+=HEX$1[tmp];if(i&1&&i>1&&i<11)out+='-';}IDX$1+=16;return out;}
1216
+
1217
+ var IDX=256,HEX=[],BUFFER;while(IDX--)HEX[IDX]=(IDX+256).toString(16).substring(1);function v4(){var i=0,num,out='';if(!BUFFER||IDX+16>256){BUFFER=Array(i=256);while(i--)BUFFER[i]=256*Math.random()|0;i=IDX=0;}for(;i<16;i++){num=BUFFER[IDX+i];if(i==6)out+=HEX[num&15|64];else if(i==8)out+=HEX[num&63|128];else out+=HEX[num];if(i&1&&i>1&&i<11)out+='-';}IDX++;return out;}
1218
+
1219
+ var hasCrypto$1=function hasCrypto(){return !isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);};
1220
+
1221
+ var generateUUID=function generateUUID(){if(hasCrypto$1()){return v4$1();}return v4();};
1222
+
1223
+ var isErrRetryable=function isErrRetryable(details){var isRetryableNWFailure=false;if(details!==null&&details!==void 0&&details.error&&details!==null&&details!==void 0&&details.xhr){var xhrStatus=details.xhr.status;// same as in v1.1
1224
+ isRetryableNWFailure=xhrStatus===429||xhrStatus>=500&&xhrStatus<600;}return isRetryableNWFailure;};
1225
+
1226
+ var userIdKey='rl_user_id';var userTraitsKey='rl_trait';var anonymousUserIdKey='rl_anonymous_id';var groupIdKey='rl_group_id';var groupTraitsKey='rl_group_trait';var pageInitialReferrerKey='rl_page_init_referrer';var pageInitialReferringDomainKey='rl_page_init_referring_domain';var sessionInfoKey='rl_session';var authTokenKey='rl_auth_token';var COOKIE_KEYS={userId:userIdKey,userTraits:userTraitsKey,anonymousId:anonymousUserIdKey,groupId:groupIdKey,groupTraits:groupTraitsKey,initialReferrer:pageInitialReferrerKey,initialReferringDomain:pageInitialReferringDomainKey,sessionInfo:sessionInfoKey,authToken:authTokenKey};var ENCRYPTION_PREFIX_V3='RS_ENC_v3_';
1227
+
1228
+ var COOKIE_DATA_ENCODING_ERROR="Failed to encode the cookie data.";
1229
+
1230
+ /**
1231
+ * Encode.
1232
+ */var encode=function encode(value,logger){try{return encodeURIComponent(value);}catch(err){logger===null||logger===void 0||logger.error(COOKIE_DATA_ENCODING_ERROR,err);return undefined;}};/**
1233
+ * Decode
1234
+ */var decode$1=function decode(value){try{return decodeURIComponent(value);}catch(err){// Do nothing as non-RS SDK cookies may not be URI encoded
1235
+ return undefined;}};/**
1236
+ * Parse cookie `str`
1237
+ */var parse=function parse(str){var obj={};var pairs=str.split(/\s*;\s*/);var pair;if(!pairs[0]){return obj;}// TODO: Decode only the cookies that are needed by the SDK
1238
+ pairs.forEach(function(pairItem){pair=pairItem.split('=');var keyName=pair[0]?decode$1(pair[0]):undefined;if(keyName){obj[keyName]=pair[1]?decode$1(pair[1]):undefined;}});return obj;};/**
1239
+ * Set cookie `name` to `value`
1240
+ */var set=function set(name,value,optionsConfig,logger){var options=_objectSpread2({},optionsConfig||{});var cookieString="".concat(encode(name,logger),"=").concat(encode(value,logger));if(isNull(value)){options.maxage=-1;}if(options.maxage){options.expires=new Date(+new Date()+options.maxage);}if(options.path){cookieString+="; path=".concat(options.path);}if(options.domain){cookieString+="; domain=".concat(options.domain);}if(options.expires){cookieString+="; expires=".concat(options.expires.toUTCString());}if(options.samesite){cookieString+="; samesite=".concat(options.samesite);}if(options.secure){cookieString+="; secure";}globalThis.document.cookie=cookieString;};/**
1241
+ * Return all cookies
1242
+ */var all=function all(){var cookieStringValue=globalThis.document.cookie;return parse(cookieStringValue);};/**
1243
+ * Get cookie `name`
1244
+ */var get=function get(name){return all()[name];};/**
1245
+ * Set or get cookie `name` with `value` and `options` object
1246
+ */ // eslint-disable-next-line func-names
1247
+ var cookie=function cookie(name,value,options,logger){switch(arguments.length){case 4:case 3:case 2:return set(name,value,options,logger);case 1:if(name){return get(name);}return all();default:return all();}};
1248
+
1249
+ var encryptBrowser=function encryptBrowser(value){return "".concat(ENCRYPTION_PREFIX_V3).concat(toBase64(value));};var decryptBrowser=function decryptBrowser(value){if(value!==null&&value!==void 0&&value.startsWith(ENCRYPTION_PREFIX_V3)){return fromBase64(value.substring(ENCRYPTION_PREFIX_V3.length));}return value;};
1250
+
1251
+ var EVENT_PAYLOAD_SIZE_BYTES_LIMIT=32*1024;// 32 KB
1252
+
1253
+ var EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING=function EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING(context,payloadSize,sizeLimit){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The size of the event payload (").concat(payloadSize," bytes) exceeds the maximum limit of ").concat(sizeLimit," bytes. Events with large payloads may be dropped in the future. Please review your instrumentation to ensure that event payloads are within the size limit.");};var EVENT_PAYLOAD_SIZE_VALIDATION_WARNING=function EVENT_PAYLOAD_SIZE_VALIDATION_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to validate event payload size. Please make sure that the event payload is within the size limit and is a valid JSON object.");};var QUEUE_UTILITIES='QueueUtilities';/**
1254
+ * Utility to get the stringified event payload
1255
+ * @param event RudderEvent object
1256
+ * @param logger Logger instance
1257
+ * @returns stringified event payload. Empty string if error occurs.
1258
+ */var getDeliveryPayload=function getDeliveryPayload(event,logger){return stringifyWithoutCircular(event,true,undefined,logger);};var getDMTDeliveryPayload=function getDMTDeliveryPayload(dmtRequestPayload,logger){return stringifyWithoutCircular(dmtRequestPayload,true,undefined,logger);};/**
1259
+ * Utility to validate final payload size before sending to server
1260
+ * @param event RudderEvent object
1261
+ * @param logger Logger instance
1262
+ */var validateEventPayloadSize=function validateEventPayloadSize(event,logger){var payloadStr=getDeliveryPayload(event,logger);if(payloadStr){var payloadSize=payloadStr.length;if(payloadSize>EVENT_PAYLOAD_SIZE_BYTES_LIMIT){logger===null||logger===void 0||logger.warn(EVENT_PAYLOAD_SIZE_CHECK_FAIL_WARNING(QUEUE_UTILITIES,payloadSize,EVENT_PAYLOAD_SIZE_BYTES_LIMIT));}}else {logger===null||logger===void 0||logger.warn(EVENT_PAYLOAD_SIZE_VALIDATION_WARNING(QUEUE_UTILITIES));}};/**
1263
+ * Mutates the event and return final event for delivery
1264
+ * Updates certain parameters like sentAt timestamp, integrations config etc.
1265
+ * @param event RudderEvent object
1266
+ * @returns Final event ready to be delivered
1267
+ */var getFinalEventForDeliveryMutator=function getFinalEventForDeliveryMutator(event,currentTime){var finalEvent=clone(event);// Update sentAt timestamp to the latest timestamp
1268
+ finalEvent.sentAt=currentTime;return finalEvent;};
1269
+
1270
+ var BEACON_PLUGIN_EVENTS_QUEUE_DEBUG=function BEACON_PLUGIN_EVENTS_QUEUE_DEBUG(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Sending events to data plane.");};var BEACON_QUEUE_STRING_CONVERSION_FAILURE_ERROR=function BEACON_QUEUE_STRING_CONVERSION_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to convert events batch object to string.");};var BEACON_QUEUE_BLOB_CONVERSION_FAILURE_ERROR=function BEACON_QUEUE_BLOB_CONVERSION_FAILURE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to convert events batch object to Blob.");};var BEACON_QUEUE_SEND_ERROR=function BEACON_QUEUE_SEND_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to send events batch data to the browser's beacon queue. The events will be dropped.");};var BEACON_QUEUE_DELIVERY_ERROR=function BEACON_QUEUE_DELIVERY_ERROR(url){return "Failed to send events batch data to the browser's beacon queue for URL ".concat(url,".");};
1271
+
1272
+ var DEFAULT_BEACON_QUEUE_MAX_SIZE=10;var DEFAULT_BEACON_QUEUE_FLUSH_INTERVAL_MS=10*60*1000;// 10 minutes
1273
+ // Limit of the Beacon transfer mechanism on the browsers
1274
+ var MAX_BATCH_PAYLOAD_SIZE_BYTES=64*1024;// 64 KB
1275
+ var DEFAULT_BEACON_QUEUE_OPTIONS={maxItems:DEFAULT_BEACON_QUEUE_MAX_SIZE,flushQueueInterval:DEFAULT_BEACON_QUEUE_FLUSH_INTERVAL_MS};var DATA_PLANE_API_VERSION$1='v1';var QUEUE_NAME$3='rudder_beacon';var BEACON_QUEUE_PLUGIN='BeaconQueuePlugin';
1276
+
1277
+ /**
1278
+ * Utility to get the stringified event payload as Blob
1279
+ * @param events RudderEvent object array
1280
+ * @param logger Logger instance
1281
+ * @returns stringified events payload as Blob, undefined if error occurs.
1282
+ */var getBatchDeliveryPayload$1=function getBatchDeliveryPayload(events,currentTime,logger){var data={batch:events,sentAt:currentTime};try{var blobPayload=stringifyWithoutCircular(data,true);var blobOptions={type:'text/plain'};if(blobPayload){return new Blob([blobPayload],blobOptions);}logger===null||logger===void 0||logger.error(BEACON_QUEUE_STRING_CONVERSION_FAILURE_ERROR(BEACON_QUEUE_PLUGIN));}catch(err){logger===null||logger===void 0||logger.error(BEACON_QUEUE_BLOB_CONVERSION_FAILURE_ERROR(BEACON_QUEUE_PLUGIN),err);}return undefined;};var getNormalizedBeaconQueueOptions=function getNormalizedBeaconQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_BEACON_QUEUE_OPTIONS,queueOpts);};var getDeliveryUrl$1=function getDeliveryUrl(dataplaneUrl,writeKey){var dpUrl=new URL(dataplaneUrl);return new URL(removeDuplicateSlashes([dpUrl.pathname,'/','beacon','/',DATA_PLANE_API_VERSION$1,'/',"batch?writeKey=".concat(writeKey)].join('')),dpUrl).href;};
1283
+
1284
+ var QueueStatuses={IN_PROGRESS:'inProgress',QUEUE:'queue',RECLAIM_START:'reclaimStart',RECLAIM_END:'reclaimEnd',ACK:'ack',BATCH_QUEUE:'batchQueue'};
1285
+
1286
+ var onPageLeave=function onPageLeave(callback){// To ensure the callback is only called once even if more than one events
1287
+ // are fired at once.
1288
+ var pageLeft=false;function handleOnLeave(){if(pageLeft){return;}pageLeft=true;callback();}// Catches the unloading of the page (e.g., closing the tab or navigating away).
1289
+ // Includes user actions like clicking a link, entering a new URL,
1290
+ // refreshing the page, or closing the browser tab
1291
+ // Note that 'pagehide' is not supported in IE.
1292
+ // So, this is a fallback.
1293
+ globalThis.addEventListener('beforeunload',handleOnLeave);// Catches the page being hidden, including scenarios like closing the tab.
1294
+ document.addEventListener('pagehide',handleOnLeave);// Catches visibility changes, such as switching tabs or minimizing the browser.
1295
+ document.addEventListener('visibilitychange',function(){if(document.visibilityState==='hidden'){handleOnLeave();}else {pageLeft=false;}});};
1296
+
1297
+ var ScheduleModes=/*#__PURE__*/function(ScheduleModes){ScheduleModes[ScheduleModes["ASAP"]=1]="ASAP";ScheduleModes[ScheduleModes["RESCHEDULE"]=2]="RESCHEDULE";ScheduleModes[ScheduleModes["ABANDON"]=3]="ABANDON";return ScheduleModes;}({});var DEFAULT_CLOCK_LATE_FACTOR=2;var DEFAULT_CLOCK={setTimeout:function setTimeout(fn,ms){return globalThis.setTimeout(fn,ms);},clearTimeout:function clearTimeout(id){return globalThis.clearTimeout(id);},Date:globalThis.Date,clockLateFactor:DEFAULT_CLOCK_LATE_FACTOR};var Schedule=/*#__PURE__*/function(){function Schedule(){_classCallCheck(this,Schedule);this.tasks={};this.nextId=1;this.clock=DEFAULT_CLOCK;}return _createClass(Schedule,[{key:"now",value:function now(){return +new this.clock.Date();}},{key:"run",value:function run(task,timeout,mode){var id=(this.nextId+1).toString();this.tasks[id]=this.clock.setTimeout(this.handle(id,task,timeout,mode||ScheduleModes.ASAP),timeout);return id;}},{key:"handle",value:function handle(id,callback,timeout,mode){var _this=this;var start=this.now();return function(){delete _this.tasks[id];var elapsedTimeoutTime=start+timeout*(_this.clock.clockLateFactor||DEFAULT_CLOCK_LATE_FACTOR);var currentTime=_this.now();var notCompletedOrTimedOut=mode>=ScheduleModes.RESCHEDULE&&elapsedTimeoutTime<currentTime;if(notCompletedOrTimedOut){if(mode===ScheduleModes.RESCHEDULE){_this.run(callback,timeout,mode);}return undefined;}return callback();};}},{key:"cancel",value:function cancel(id){if(this.tasks[id]){this.clock.clearTimeout(this.tasks[id]);delete this.tasks[id];}}},{key:"cancelAll",value:function cancelAll(){Object.values(this.tasks).forEach(this.clock.clearTimeout);this.tasks={};}}]);}();
1298
+
1299
+ var RETRY_QUEUE_PROCESS_ERROR=function RETRY_QUEUE_PROCESS_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Process function threw an error.");};var RETRY_QUEUE_ENTRY_REMOVE_ERROR=function RETRY_QUEUE_ENTRY_REMOVE_ERROR(context,entry,attempt){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to remove local storage entry \"").concat(entry,"\" (attempt: ").concat(attempt,".");};
1300
+
1301
+ var DEFAULT_MIN_RETRY_DELAY_MS=1000;var DEFAULT_MAX_RETRY_DELAY_MS=30000;var DEFAULT_BACKOFF_FACTOR=2;var DEFAULT_BACKOFF_JITTER=0;var DEFAULT_MAX_RETRY_ATTEMPTS=Infinity;var DEFAULT_MAX_ITEMS=Infinity;var DEFAULT_ACK_TIMER_MS=1000;var DEFAULT_RECLAIM_TIMER_MS=3000;var DEFAULT_RECLAIM_TIMEOUT_MS=10000;var DEFAULT_RECLAIM_WAIT_MS=500;var MIN_TIMER_SCALE_FACTOR=1;var MAX_TIMER_SCALE_FACTOR=10;var DEFAULT_MAX_BATCH_SIZE_BYTES=512*1024;// 512 KB; this is also the max size of a batch
1302
+ var DEFAULT_MAX_BATCH_ITEMS=100;var DEFAULT_BATCH_FLUSH_INTERVAL_MS=60*1000;// 1 minutes
1303
+
1304
+ var sortByTime=function sortByTime(a,b){return a.time-b.time;};var RETRY_QUEUE='RetryQueue';/**
1305
+ * Constructs a RetryQueue backed by localStorage
1306
+ *
1307
+ * @constructor
1308
+ * @param {String} name The name of the queue. Will be used to find abandoned queues and retry their items
1309
+ * @param {Object} [opts] Optional argument to override `maxItems`, `maxAttempts`, `minRetryDelay, `maxRetryDelay`, `backoffFactor` and `backoffJitter`.
1310
+ * @param {QueueProcessCallback} fn The function to call in order to process an item added to the queue
1311
+ */var RetryQueue=/*#__PURE__*/function(){function RetryQueue(name,options,queueProcessCb,storeManager){var _options$timerScaleFa;var storageType=arguments.length>4&&arguments[4]!==undefined?arguments[4]:LOCAL_STORAGE;var logger=arguments.length>5?arguments[5]:undefined;var queueBatchItemsSizeCalculatorCb=arguments.length>6?arguments[6]:undefined;_classCallCheck(this,RetryQueue);this.storeManager=storeManager;this.logger=logger;this.name=name;this.id=generateUUID();this.processQueueCb=queueProcessCb;this.batchSizeCalcCb=queueBatchItemsSizeCalculatorCb;this.maxItems=options.maxItems||DEFAULT_MAX_ITEMS;this.maxAttempts=options.maxAttempts||DEFAULT_MAX_RETRY_ATTEMPTS;this.batch={enabled:false};this.configureBatchMode(options);this.backoff={minRetryDelay:options.minRetryDelay||DEFAULT_MIN_RETRY_DELAY_MS,maxRetryDelay:options.maxRetryDelay||DEFAULT_MAX_RETRY_DELAY_MS,factor:options.backoffFactor||DEFAULT_BACKOFF_FACTOR,jitter:options.backoffJitter||DEFAULT_BACKOFF_JITTER};// Limit the timer scale factor to the minimum value
1312
+ var timerScaleFactor=Math.max((_options$timerScaleFa=options.timerScaleFactor)!==null&&_options$timerScaleFa!==void 0?_options$timerScaleFa:MIN_TIMER_SCALE_FACTOR,MIN_TIMER_SCALE_FACTOR);// Limit the timer scale factor to the maximum value
1313
+ timerScaleFactor=Math.min(timerScaleFactor,MAX_TIMER_SCALE_FACTOR);// painstakingly tuned. that's why they're not "easily" configurable
1314
+ this.timeouts={ackTimer:Math.round(timerScaleFactor*DEFAULT_ACK_TIMER_MS),reclaimTimer:Math.round(timerScaleFactor*DEFAULT_RECLAIM_TIMER_MS),reclaimTimeout:Math.round(timerScaleFactor*DEFAULT_RECLAIM_TIMEOUT_MS),reclaimWait:Math.round(timerScaleFactor*DEFAULT_RECLAIM_WAIT_MS)};this.schedule=new Schedule();this.processId='0';// Set up our empty queues
1315
+ this.store=this.storeManager.setStore({id:this.id,name:this.name,validKeys:QueueStatuses,type:storageType});this.setDefaultQueueEntries();// bind recurring tasks for ease of use
1316
+ this.ack=this.ack.bind(this);this.checkReclaim=this.checkReclaim.bind(this);this.processHead=this.processHead.bind(this);this.flushBatch=this.flushBatch.bind(this);// Flush the queue on page leave
1317
+ this.flushBatchOnPageLeave();this.scheduleTimeoutActive=false;}return _createClass(RetryQueue,[{key:"setDefaultQueueEntries",value:function setDefaultQueueEntries(){this.setStorageEntry(QueueStatuses.IN_PROGRESS,{});this.setStorageEntry(QueueStatuses.QUEUE,[]);this.setStorageEntry(QueueStatuses.BATCH_QUEUE,[]);}},{key:"configureBatchMode",value:function configureBatchMode(options){this.batchingInProgress=false;if(!isObjectLiteralAndNotNull(options.batch)){return;}var batchOptions=options.batch;this.batch.enabled=batchOptions.enabled===true;if(this.batch.enabled){var _batchOptions$maxSize,_batchOptions$maxItem,_batchOptions$flushIn;// Set upper cap on the batch payload size
1318
+ this.batch.maxSize=Math.min((_batchOptions$maxSize=batchOptions.maxSize)!==null&&_batchOptions$maxSize!==void 0?_batchOptions$maxSize:DEFAULT_MAX_BATCH_SIZE_BYTES,DEFAULT_MAX_BATCH_SIZE_BYTES);this.batch.maxItems=(_batchOptions$maxItem=batchOptions.maxItems)!==null&&_batchOptions$maxItem!==void 0?_batchOptions$maxItem:DEFAULT_MAX_BATCH_ITEMS;this.batch.flushInterval=(_batchOptions$flushIn=batchOptions.flushInterval)!==null&&_batchOptions$flushIn!==void 0?_batchOptions$flushIn:DEFAULT_BATCH_FLUSH_INTERVAL_MS;}}},{key:"flushBatchOnPageLeave",value:function flushBatchOnPageLeave(){if(this.batch.enabled){onPageLeave(this.flushBatch);}}},{key:"getStorageEntry",value:function getStorageEntry(name){return this.store.get(name);}// TODO: fix the type of different queues to be the same if possible
1319
+ },{key:"setStorageEntry",value:function setStorageEntry(name,value){if(isNullOrUndefined(value)){this.store.remove(name);}else {this.store.set(name,value);}}/**
1320
+ * Stops processing the queue
1321
+ */},{key:"stop",value:function stop(){this.schedule.cancelAll();this.scheduleTimeoutActive=false;}/**
1322
+ * Starts processing the queue
1323
+ */},{key:"start",value:function start(){if(this.scheduleTimeoutActive){this.stop();}this.scheduleTimeoutActive=true;this.scheduleFlushBatch();this.ack();this.checkReclaim();this.processHead();}/**
1324
+ * Configures the timeout handler for flushing the batch queue
1325
+ */},{key:"scheduleFlushBatch",value:function scheduleFlushBatch(){var _this$batch;if(this.batch.enabled&&(_this$batch=this.batch)!==null&&_this$batch!==void 0&&_this$batch.flushInterval){if(this.flushBatchTaskId){this.schedule.cancel(this.flushBatchTaskId);}this.flushBatchTaskId=this.schedule.run(this.flushBatch,this.batch.flushInterval,ScheduleModes.ASAP);}}/**
1326
+ * Flushes the batch queue
1327
+ */},{key:"flushBatch",value:function flushBatch(){if(!this.batchingInProgress){var _ref;this.batchingInProgress=true;var batchQueue=(_ref=this.getStorageEntry(QueueStatuses.BATCH_QUEUE))!==null&&_ref!==void 0?_ref:[];if(batchQueue.length>0){batchQueue=batchQueue.slice(-batchQueue.length);var batchEntry=this.genQueueItem(batchQueue.map(function(queueItem){return queueItem.item;}));this.setStorageEntry(QueueStatuses.BATCH_QUEUE,[]);this.pushToMainQueue(batchEntry);}this.batchingInProgress=false;// Re-schedule the flush task
1328
+ this.scheduleFlushBatch();}}/**
1329
+ * Decides whether to retry. Overridable.
1330
+ *
1331
+ * @param {Object} item The item being processed
1332
+ * @param {Number} attemptNumber The attemptNumber (1 for first retry)
1333
+ * @return {Boolean} Whether to requeue the message
1334
+ */},{key:"shouldRetry",value:function shouldRetry(item,attemptNumber){return attemptNumber<=this.maxAttempts;}/**
1335
+ * Calculates the delay (in ms) for a retry attempt
1336
+ *
1337
+ * @param {Number} attemptNumber The attemptNumber (1 for first retry)
1338
+ * @return {Number} The delay in milliseconds to wait before attempting a retry
1339
+ */},{key:"getDelay",value:function getDelay(attemptNumber){var ms=this.backoff.minRetryDelay*Math.pow(this.backoff.factor,attemptNumber);if(this.backoff.jitter){var rand=Math.random();var deviation=Math.floor(rand*this.backoff.jitter*ms);if(Math.floor(rand*10)<5){ms-=deviation;}else {ms+=deviation;}}return Number(Math.min(ms,this.backoff.maxRetryDelay).toPrecision(1));}},{key:"enqueue",value:function enqueue(entry){var curEntry;if(this.batch.enabled){curEntry=this.handleNewItemForBatch(entry);}else {curEntry=entry;}// when batching is enabled, `curEntry` could be `undefined` if the batch criteria is not met
1340
+ if(curEntry){this.pushToMainQueue(curEntry);}}/**
1341
+ * Handles a new item added to the retry queue when batching is enabled
1342
+ * @param entry New item added to the retry queue
1343
+ * @returns Undefined or batch entry object
1344
+ */},{key:"handleNewItemForBatch",value:function handleNewItemForBatch(entry){var _ref2;var curEntry;var batchQueue=(_ref2=this.getStorageEntry(QueueStatuses.BATCH_QUEUE))!==null&&_ref2!==void 0?_ref2:[];if(!this.batchingInProgress){this.batchingInProgress=true;batchQueue=batchQueue.slice(-batchQueue.length);batchQueue.push(entry);var batchDispatchInfo=this.getBatchDispatchInfo(batchQueue);// if batch criteria is met, queue the batch events to the main queue and clear batch queue
1345
+ if(batchDispatchInfo.criteriaMet||batchDispatchInfo.criteriaExceeded){var batchItems;if(batchDispatchInfo.criteriaExceeded){batchItems=batchQueue.slice(0,batchQueue.length-1).map(function(queueItem){return queueItem.item;});batchQueue=[entry];}else {batchItems=batchQueue.map(function(queueItem){return queueItem.item;});batchQueue=[];}// Don't make any batch request if there are no items
1346
+ if(batchItems.length>0){curEntry=this.genQueueItem(batchItems);}// re-attach the timeout handler
1347
+ this.scheduleFlushBatch();}this.batchingInProgress=false;}else {batchQueue.push(entry);}// update the batch queue
1348
+ this.setStorageEntry(QueueStatuses.BATCH_QUEUE,batchQueue);return curEntry;}},{key:"pushToMainQueue",value:function pushToMainQueue(curEntry){var _ref3;var queue=(_ref3=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_ref3!==void 0?_ref3:[];queue=queue.slice(-(this.maxItems-1));queue.push(curEntry);queue=queue.sort(sortByTime);this.setStorageEntry(QueueStatuses.QUEUE,queue);if(this.scheduleTimeoutActive){this.processHead();}}/**
1349
+ * Adds an item to the queue
1350
+ *
1351
+ * @param {Object} itemData The item to process
1352
+ */},{key:"addItem",value:function addItem(itemData){this.enqueue(this.genQueueItem(itemData));}/**
1353
+ * Generates a queue item
1354
+ * @param itemData Queue item data
1355
+ * @returns Queue item
1356
+ */},{key:"genQueueItem",value:function genQueueItem(itemData){return {item:itemData,attemptNumber:0,time:this.schedule.now(),id:generateUUID()};}/**
1357
+ * Adds an item to the retry queue
1358
+ *
1359
+ * @param {Object} itemData The item to retry
1360
+ * @param {Number} attemptNumber The attempt number (1 for first retry)
1361
+ * @param {Error} [error] The error from previous attempt, if there was one
1362
+ * @param {String} [id] The id of the queued message used for tracking duplicate entries
1363
+ */},{key:"requeue",value:function requeue(itemData,attemptNumber,error,id){if(this.shouldRetry(itemData,attemptNumber)){this.enqueue({item:itemData,attemptNumber:attemptNumber,time:this.schedule.now()+this.getDelay(attemptNumber),id:id!==null&&id!==void 0?id:generateUUID()});}}/**
1364
+ * Returns the information about whether the batch criteria is met or exceeded
1365
+ * @param batchItems Prospective batch items
1366
+ * @returns Batch dispatch info
1367
+ */},{key:"getBatchDispatchInfo",value:function getBatchDispatchInfo(batchItems){var _this$batch2,_this$batch3;var lengthCriteriaMet=false;var lengthCriteriaExceeded=false;var configuredBatchMaxItems=(_this$batch2=this.batch)===null||_this$batch2===void 0?void 0:_this$batch2.maxItems;if(isDefined(configuredBatchMaxItems)){lengthCriteriaMet=batchItems.length===configuredBatchMaxItems;lengthCriteriaExceeded=batchItems.length>configuredBatchMaxItems;}if(lengthCriteriaMet||lengthCriteriaExceeded){return {criteriaMet:lengthCriteriaMet,criteriaExceeded:lengthCriteriaExceeded};}var sizeCriteriaMet=false;var sizeCriteriaExceeded=false;var configuredBatchMaxSize=(_this$batch3=this.batch)===null||_this$batch3===void 0?void 0:_this$batch3.maxSize;if(isDefined(configuredBatchMaxSize)&&isDefined(this.batchSizeCalcCb)){var curBatchSize=this.batchSizeCalcCb(batchItems.map(function(queueItem){return queueItem.item;}));sizeCriteriaMet=curBatchSize===configuredBatchMaxSize;sizeCriteriaExceeded=curBatchSize>configuredBatchMaxSize;}return {criteriaMet:sizeCriteriaMet,criteriaExceeded:sizeCriteriaExceeded};}},{key:"processHead",value:function processHead(){var _ref4,_ref5,_this=this,_ref7;// cancel the scheduled task if it exists
1368
+ this.schedule.cancel(this.processId);// Pop the head off the queue
1369
+ var queue=(_ref4=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_ref4!==void 0?_ref4:[];var inProgress=(_ref5=this.getStorageEntry(QueueStatuses.IN_PROGRESS))!==null&&_ref5!==void 0?_ref5:{};var now=this.schedule.now();var toRun=[];// eslint-disable-next-line @typescript-eslint/no-unused-vars
1370
+ var processItemCallback=function processItemCallback(el,id){return function(err,res){var _ref6;var inProgress=(_ref6=_this.getStorageEntry(QueueStatuses.IN_PROGRESS))!==null&&_ref6!==void 0?_ref6:{};delete inProgress[id];_this.setStorageEntry(QueueStatuses.IN_PROGRESS,inProgress);if(err){_this.requeue(el.item,el.attemptNumber+1,err,el.id);}};};var enqueueItem=function enqueueItem(el,id){toRun.push({item:el.item,done:processItemCallback(el,id),attemptNumber:el.attemptNumber});};var inProgressSize=Object.keys(inProgress).length;// eslint-disable-next-line no-plusplus
1371
+ while(queue.length>0&&queue[0].time<=now&&inProgressSize++<this.maxItems){var el=queue.shift();if(el){var id=generateUUID();// Save this to the in progress map
1372
+ inProgress[id]={item:el.item,attemptNumber:el.attemptNumber,time:this.schedule.now()};enqueueItem(el,id);}}this.setStorageEntry(QueueStatuses.QUEUE,queue);this.setStorageEntry(QueueStatuses.IN_PROGRESS,inProgress);toRun.forEach(function(el){// TODO: handle processQueueCb timeout
1373
+ try{var willBeRetried=_this.shouldRetry(el.item,el.attemptNumber+1);_this.processQueueCb(el.item,el.done,el.attemptNumber,_this.maxAttempts,willBeRetried);}catch(err){var _this$logger;(_this$logger=_this.logger)===null||_this$logger===void 0||_this$logger.error(RETRY_QUEUE_PROCESS_ERROR(RETRY_QUEUE),err);}});// re-read the queue in case the process function finished immediately or added another item
1374
+ queue=(_ref7=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_ref7!==void 0?_ref7:[];this.schedule.cancel(this.processId);if(queue.length>0){var nextProcessExecutionTime=queue[0].time-now;this.processId=this.schedule.run(this.processHead,nextProcessExecutionTime,ScheduleModes.ASAP);}}// Ack continuously to prevent other tabs from claiming our queue
1375
+ },{key:"ack",value:function ack(){this.setStorageEntry(QueueStatuses.ACK,this.schedule.now());if(this.reclaimStartVal!=null){this.reclaimStartVal=null;this.setStorageEntry(QueueStatuses.RECLAIM_START,null);}if(this.reclaimEndVal!=null){this.reclaimEndVal=null;this.setStorageEntry(QueueStatuses.RECLAIM_END,null);}this.schedule.run(this.ack,this.timeouts.ackTimer,ScheduleModes.ASAP);}},{key:"reclaim",value:function reclaim(id){var _this$getStorageEntry,_other$get,_other$get2,_other$get3,_this2=this;var other=this.storeManager.setStore({id:id,name:this.name,validKeys:QueueStatuses,type:LOCAL_STORAGE});var our={queue:(_this$getStorageEntry=this.getStorageEntry(QueueStatuses.QUEUE))!==null&&_this$getStorageEntry!==void 0?_this$getStorageEntry:[]};var their={inProgress:(_other$get=other.get(QueueStatuses.IN_PROGRESS))!==null&&_other$get!==void 0?_other$get:{},batchQueue:(_other$get2=other.get(QueueStatuses.BATCH_QUEUE))!==null&&_other$get2!==void 0?_other$get2:[],queue:(_other$get3=other.get(QueueStatuses.QUEUE))!==null&&_other$get3!==void 0?_other$get3:[]};var trackMessageIds=[];var addConcatQueue=function addConcatQueue(queue,incrementAttemptNumberBy){var concatIterator=function concatIterator(el){var _el$id;var id=(_el$id=el.id)!==null&&_el$id!==void 0?_el$id:generateUUID();if(trackMessageIds.includes(id));else {our.queue.push({item:el.item,attemptNumber:el.attemptNumber+incrementAttemptNumberBy,time:_this2.schedule.now(),id:id});trackMessageIds.push(id);}};if(Array.isArray(queue)){queue.forEach(concatIterator);}else if(queue){Object.values(queue).forEach(concatIterator);}};// add their queue to ours, resetting run-time to immediate and copying the attempt#
1376
+ addConcatQueue(their.queue,0);// Process batch queue items
1377
+ if(this.batch.enabled){their.batchQueue.forEach(function(el){var _el$id2;var id=(_el$id2=el.id)!==null&&_el$id2!==void 0?_el$id2:generateUUID();if(trackMessageIds.includes(id));else {_this2.enqueue(el);trackMessageIds.push(id);}});}else {// if batching is not enabled in the current instance, add those items to the main queue directly
1378
+ addConcatQueue(their.batchQueue,0);}// if the queue is abandoned, all the in-progress are failed. retry them immediately and increment the attempt#
1379
+ addConcatQueue(their.inProgress,1);our.queue=our.queue.sort(sortByTime);this.setStorageEntry(QueueStatuses.QUEUE,our.queue);// remove all keys one by on next tick to avoid NS_ERROR_STORAGE_BUSY error
1380
+ this.clearQueueEntries(other,1);// process the new items we claimed
1381
+ this.processHead();}// eslint-disable-next-line class-methods-use-this
1382
+ },{key:"clearQueueEntries",value:function clearQueueEntries(other,localStorageBackoff){this.removeStorageEntry(other,0,localStorageBackoff);}},{key:"removeStorageEntry",value:function removeStorageEntry(store,entryIdx,backoff){var _this3=this;var attempt=arguments.length>3&&arguments[3]!==undefined?arguments[3]:1;var maxAttempts=2;var queueEntryKeys=Object.keys(QueueStatuses);var entry=QueueStatuses[queueEntryKeys[entryIdx]];globalThis.setTimeout(function(){try{store.remove(entry);// clear the next entry
1383
+ if(entryIdx+1<queueEntryKeys.length){_this3.removeStorageEntry(store,entryIdx+1,backoff);}}catch(err){var storageBusyErr='NS_ERROR_STORAGE_BUSY';var isLocalStorageBusy=err.name===storageBusyErr||err.code===storageBusyErr||err.code===0x80630001;if(isLocalStorageBusy&&attempt<maxAttempts){// Try clearing the same entry again with some extra delay
1384
+ _this3.removeStorageEntry(store,entryIdx,backoff+40,attempt+1);}else {var _this3$logger;(_this3$logger=_this3.logger)===null||_this3$logger===void 0||_this3$logger.error(RETRY_QUEUE_ENTRY_REMOVE_ERROR(RETRY_QUEUE,entry,attempt),err);}// clear the next entry after we've exhausted our attempts
1385
+ if(attempt===maxAttempts&&entryIdx+1<queueEntryKeys.length){_this3.removeStorageEntry(store,entryIdx+1,backoff);}}},backoff);}},{key:"checkReclaim",value:function checkReclaim(){var _this4=this;var createReclaimStartTask=function createReclaimStartTask(store){return function(){if(store.get(QueueStatuses.RECLAIM_END)!==_this4.id){return;}if(store.get(QueueStatuses.RECLAIM_START)!==_this4.id){return;}_this4.reclaim(store.id);};};var createReclaimEndTask=function createReclaimEndTask(store){return function(){if(store.get(QueueStatuses.RECLAIM_START)!==_this4.id){return;}store.set(QueueStatuses.RECLAIM_END,_this4.id);_this4.schedule.run(createReclaimStartTask(store),_this4.timeouts.reclaimWait,ScheduleModes.ABANDON);};};var tryReclaim=function tryReclaim(store){store.set(QueueStatuses.RECLAIM_START,_this4.id);store.set(QueueStatuses.ACK,_this4.schedule.now());_this4.schedule.run(createReclaimEndTask(store),_this4.timeouts.reclaimWait,ScheduleModes.ABANDON);};var findOtherQueues=function findOtherQueues(name){var res=[];var storageEngine=_this4.store.getOriginalEngine();var storageKeys=[];// 'keys' API is not supported by all the core SDK versions
1386
+ // Hence, we need this backward compatibility check
1387
+ if(isFunction(storageEngine.keys)){storageKeys=storageEngine.keys();}else {for(var i=0;i<storageEngine.length;i++){var key=storageEngine.key(i);if(key){storageKeys.push(key);}}}storageKeys.forEach(function(k){var keyParts=k?k.split('.'):[];if(keyParts.length>=3&&keyParts[0]===name&&keyParts[1]!==_this4.id&&keyParts[2]===QueueStatuses.ACK){res.push(_this4.storeManager.setStore({id:keyParts[1],name:name,validKeys:QueueStatuses,type:LOCAL_STORAGE}));}});return res;};findOtherQueues(this.name).forEach(function(store){if(_this4.schedule.now()-store.get(QueueStatuses.ACK)<_this4.timeouts.reclaimTimeout){return;}tryReclaim(store);});this.schedule.run(this.checkReclaim,this.timeouts.reclaimTimer,ScheduleModes.RESCHEDULE);}},{key:"clear",value:function clear(){this.schedule.cancelAll();this.setDefaultQueueEntries();}}]);}();
1388
+
1389
+ var pluginName$e='BeaconQueue';var BeaconQueue=function BeaconQueue(){return {name:pluginName$e,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$e]);},dataplaneEventsQueue:{/**
1390
+ * Initialize the queue for delivery
1391
+ * @param state Application state
1392
+ * @param httpClient http client instance
1393
+ * @param storeManager Store Manager instance
1394
+ * @param errorHandler Error handler instance
1395
+ * @param logger Logger instance
1396
+ * @returns BeaconItemsQueue instance
1397
+ */init:function init(state,httpClient,storeManager,errorHandler,logger){var _state$loadOptions$va;var writeKey=state.lifecycle.writeKey.value;var dataplaneUrl=state.lifecycle.activeDataplaneUrl.value;var url=getDeliveryUrl$1(dataplaneUrl,writeKey);var finalQOpts=getNormalizedBeaconQueueOptions((_state$loadOptions$va=state.loadOptions.value.beaconQueueOptions)!==null&&_state$loadOptions$va!==void 0?_state$loadOptions$va:{});var queueProcessCallback=function queueProcessCallback(itemData,done){logger===null||logger===void 0||logger.debug(BEACON_PLUGIN_EVENTS_QUEUE_DEBUG(BEACON_QUEUE_PLUGIN));var currentTime=getCurrentTimeFormatted();var finalEvents=itemData.map(function(queueItemData){return getFinalEventForDeliveryMutator(queueItemData.event,currentTime);});var data=getBatchDeliveryPayload$1(finalEvents,currentTime,logger);if(data){try{var isEnqueuedInBeacon=navigator.sendBeacon(url,data);if(!isEnqueuedInBeacon){logger===null||logger===void 0||logger.error(BEACON_QUEUE_SEND_ERROR(BEACON_QUEUE_PLUGIN));}done(null,isEnqueuedInBeacon);}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,BEACON_QUEUE_PLUGIN,BEACON_QUEUE_DELIVERY_ERROR(url));// Remove the item from queue
1398
+ done(null);}}else {// Mark the item as done so that it can be removed from the queue
1399
+ done(null);}};var eventsQueue=new RetryQueue("".concat(QUEUE_NAME$3,"_").concat(writeKey),{batch:{enabled:true,flushInterval:finalQOpts.flushQueueInterval,maxSize:MAX_BATCH_PAYLOAD_SIZE_BYTES,// set the hard limit
1400
+ maxItems:finalQOpts.maxItems}},queueProcessCallback,storeManager,LOCAL_STORAGE,logger,function(itemData){var currentTime=getCurrentTimeFormatted();var events=itemData.map(function(queueItemData){return queueItemData.event;});// type casting to Blob as we know that the event has already been validated prior to enqueue
1401
+ return getBatchDeliveryPayload$1(events,currentTime,logger).size;});return eventsQueue;},/**
1402
+ * Add event to the queue for delivery
1403
+ * @param state Application state
1404
+ * @param eventsQueue IQueue instance
1405
+ * @param event RudderEvent object
1406
+ * @param errorHandler Error handler instance
1407
+ * @param logger Logger instance
1408
+ * @returns none
1409
+ */enqueue:function enqueue(state,eventsQueue,event,errorHandler,logger){// sentAt is only added here for the validation step
1410
+ // It'll be updated to the latest timestamp during actual delivery
1411
+ event.sentAt=getCurrentTimeFormatted();validateEventPayloadSize(event,logger);eventsQueue.addItem({event:event});}}};};
1412
+
1413
+ var BUGSNAG_API_KEY_VALIDATION_ERROR=function BUGSNAG_API_KEY_VALIDATION_ERROR(apiKey){return "The Bugsnag API key (".concat(apiKey,") is invalid or not provided.");};var BUGSNAG_SDK_LOAD_TIMEOUT_ERROR=function BUGSNAG_SDK_LOAD_TIMEOUT_ERROR(timeout){return "A timeout ".concat(timeout," ms occurred while trying to load the Bugsnag SDK.");};var BUGSNAG_SDK_LOAD_ERROR=function BUGSNAG_SDK_LOAD_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to load the Bugsnag SDK.");};var FAILED_TO_FILTER_ERROR=function FAILED_TO_FILTER_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to filter the error.");};
1414
+
1415
+ var BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME='bugsnag';// For version 6 and below
1416
+ var BUGSNAG_LIB_V7_INSTANCE_GLOBAL_KEY_NAME='Bugsnag';var GLOBAL_LIBRARY_OBJECT_NAMES=[BUGSNAG_LIB_V7_INSTANCE_GLOBAL_KEY_NAME,BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME];var BUGSNAG_CDN_URL='https://d2wy8f7a9ursnm.cloudfront.net/v6/bugsnag.min.js';var ERROR_REPORT_PROVIDER_NAME_BUGSNAG='rs-bugsnag';// This API key token is parsed in the CI pipeline
1417
+ var API_KEY='0d96a60df267f4a13f808bbaa54e535c';var BUGSNAG_VALID_MAJOR_VERSION='6';var SDK_LOAD_POLL_INTERVAL_MS=100;// ms
1418
+ var MAX_WAIT_FOR_SDK_LOAD_MS=100*SDK_LOAD_POLL_INTERVAL_MS;// ms
1419
+ // Errors from the below scripts are NOT allowed to reach Bugsnag
1420
+ var SDK_FILE_NAME_PREFIXES$1=function SDK_FILE_NAME_PREFIXES(){return ['rsa'// Prefix for all the SDK scripts including plugins and module federated chunks
1421
+ ];};var DEV_HOSTS$1=['www.test-host.com','localhost','127.0.0.1','[::1]'];// List of keys to exclude from the metadata
1422
+ // Potential PII or sensitive data
1423
+ var APP_STATE_EXCLUDE_KEYS$1=['userId','userTraits','groupId','groupTraits','anonymousId','config','instance',// destination instance objects
1424
+ 'eventBuffer',// pre-load event buffer (may contain PII)
1425
+ 'traits'];var BUGSNAG_PLUGIN='BugsnagPlugin';
1426
+
1427
+ var isValidVersion=function isValidVersion(globalLibInstance){var _globalLibInstance$_c;// For version 7
1428
+ // eslint-disable-next-line no-underscore-dangle
1429
+ var version=globalLibInstance===null||globalLibInstance===void 0||(_globalLibInstance$_c=globalLibInstance._client)===null||_globalLibInstance$_c===void 0||(_globalLibInstance$_c=_globalLibInstance$_c._notifier)===null||_globalLibInstance$_c===void 0?void 0:_globalLibInstance$_c.version;// For versions older than 7
1430
+ if(!version){var _tempInstance$notifie;var tempInstance=globalLibInstance({apiKey:API_KEY,releaseStage:'version-test',// eslint-disable-next-line func-names, object-shorthand
1431
+ beforeSend:function beforeSend(){return false;}});version=(_tempInstance$notifie=tempInstance.notifier)===null||_tempInstance$notifie===void 0?void 0:_tempInstance$notifie.version;}return version&&version.charAt(0)===BUGSNAG_VALID_MAJOR_VERSION;};var isRudderSDKError$1=function isRudderSDKError(event){var _event$stacktrace;var errorOrigin=(_event$stacktrace=event.stacktrace)===null||_event$stacktrace===void 0||(_event$stacktrace=_event$stacktrace[0])===null||_event$stacktrace===void 0?void 0:_event$stacktrace.file;if(!errorOrigin||typeof errorOrigin!=='string'){return false;}// Prefix folder for all the destination SDK scripts
1432
+ var isDestinationIntegrationBundle=errorOrigin.includes(CDN_INT_DIR);var srcFileName=errorOrigin.substring(errorOrigin.lastIndexOf('/')+1);return isDestinationIntegrationBundle||SDK_FILE_NAME_PREFIXES$1().some(function(prefix){return srcFileName.startsWith(prefix)&&srcFileName.endsWith('.js');});};var getAppStateForMetadata$1=function getAppStateForMetadata(state){var stateStr=stringifyWithoutCircular(state,false,APP_STATE_EXCLUDE_KEYS$1);return stateStr!==null?JSON.parse(stateStr):undefined;};var enhanceErrorEventMutator=function enhanceErrorEventMutator(state,event){var _getAppStateForMetada;event.updateMetaData('source',{snippetVersion:globalThis.RudderSnippetVersion});event.updateMetaData('state',(_getAppStateForMetada=getAppStateForMetadata$1(state))!==null&&_getAppStateForMetada!==void 0?_getAppStateForMetada:{});var errorMessage=event.errorMessage;// eslint-disable-next-line no-param-reassign
1433
+ event.context=errorMessage;// Hack for easily grouping the script load errors
1434
+ // on the dashboard
1435
+ if(errorMessage.includes('error in script loading')){// eslint-disable-next-line no-param-reassign
1436
+ event.context='Script load failures';}// eslint-disable-next-line no-param-reassign
1437
+ event.severity='error';};var onError=function onError(state,logger){return function(event){try{// Discard the event if it's not originated at the SDK
1438
+ if(!isRudderSDKError$1(event)){return false;}enhanceErrorEventMutator(state,event);return true;}catch(_unused){logger===null||logger===void 0||logger.error(FAILED_TO_FILTER_ERROR(BUGSNAG_PLUGIN));// Drop the error event if it couldn't be filtered as
1439
+ // it is most likely a non-SDK error
1440
+ return false;}};};var getReleaseStage$1=function getReleaseStage(){var host=globalThis.location.hostname;return host&&DEV_HOSTS$1.includes(host)?'development':'production';};var getGlobalBugsnagLibInstance=function getGlobalBugsnagLibInstance(){return globalThis[BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME];};var getNewClient=function getNewClient(state,logger){var _state$source$value;var globalBugsnagLibInstance=getGlobalBugsnagLibInstance();var clientConfig={apiKey:API_KEY,appVersion:state.context.app.value.version,metaData:{SDK:{name:'JS',installType:state.context.app.value.installType}},beforeSend:onError(state,logger),autoCaptureSessions:false,// auto capture sessions is disabled
1441
+ collectUserIp:false,// collecting user's IP is disabled
1442
+ // enabledBreadcrumbTypes: ['error', 'log', 'user'], // for v7 and above
1443
+ maxEvents:100,maxBreadcrumbs:40,releaseStage:getReleaseStage$1(),user:{id:((_state$source$value=state.source.value)===null||_state$source$value===void 0?void 0:_state$source$value.id)||state.lifecycle.writeKey.value},logger:logger,networkBreadcrumbsEnabled:false};var client=globalBugsnagLibInstance(clientConfig);return client;};var isApiKeyValid=function isApiKeyValid(apiKey){var isAPIKeyValid=!(apiKey.startsWith('{{')||apiKey.endsWith('}}')||apiKey.length===0);return isAPIKeyValid;};var loadBugsnagSDK=function loadBugsnagSDK(externalSrcLoader,logger){var isNotLoaded=GLOBAL_LIBRARY_OBJECT_NAMES.every(function(globalKeyName){return !globalThis[globalKeyName];});if(!isNotLoaded){return;}externalSrcLoader.loadJSFile({url:BUGSNAG_CDN_URL,id:ERROR_REPORT_PROVIDER_NAME_BUGSNAG,callback:function callback(id){if(!id){logger===null||logger===void 0||logger.error(BUGSNAG_SDK_LOAD_ERROR(BUGSNAG_PLUGIN));}}});};var initBugsnagClient=function initBugsnagClient(state,promiseResolve,promiseReject,logger){var time=arguments.length>4&&arguments[4]!==undefined?arguments[4]:0;var globalBugsnagLibInstance=getGlobalBugsnagLibInstance();if(typeof globalBugsnagLibInstance==='function'){if(isValidVersion(globalBugsnagLibInstance)){var client=getNewClient(state,logger);promiseResolve(client);}}else if(time>=MAX_WAIT_FOR_SDK_LOAD_MS){promiseReject(new Error(BUGSNAG_SDK_LOAD_TIMEOUT_ERROR(MAX_WAIT_FOR_SDK_LOAD_MS)));}else {// Try to initialize the client after a delay
1444
+ globalThis.setTimeout(initBugsnagClient,SDK_LOAD_POLL_INTERVAL_MS,state,promiseResolve,promiseReject,logger,time+SDK_LOAD_POLL_INTERVAL_MS);}};
1445
+
1446
+ var pluginName$d='Bugsnag';var Bugsnag=function Bugsnag(){return {name:pluginName$d,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$d]);},errorReportingProvider:{init:function init(state,externalSrcLoader,logger){return new Promise(function(resolve,reject){// If API key token is not parsed or invalid, don't proceed to initialize the client
1447
+ if(!isApiKeyValid(API_KEY)){reject(new Error(BUGSNAG_API_KEY_VALIDATION_ERROR(API_KEY)));return;}// If SDK URL is empty, don't proceed to initialize the client
1448
+ loadBugsnagSDK(externalSrcLoader,logger);initBugsnagClient(state,resolve,reject,logger);});},notify:function notify(client,error,state,logger){client.notify(error);},breadcrumb:function breadcrumb(client,message,logger){client===null||client===void 0||client.leaveBreadcrumb(message);}}};};
1449
+
1450
+ var CUSTOM_CONSENT_MANAGER_PLUGIN='CustomConsentManagerPlugin';
1451
+
1452
+ var DESTINATION_CONSENT_STATUS_ERROR$2="Failed to determine the consent status for the destination. Please check the destination configuration and try again.";
1453
+
1454
+ var pluginName$c='CustomConsentManager';var CustomConsentManager=function CustomConsentManager(){return {name:pluginName$c,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$c]);},consentManager:{init:function init(state,logger){// Nothing to initialize
1455
+ },updateConsentsInfo:function updateConsentsInfo(state,storeManager,logger){// Nothing to update. Already provided by the user
1456
+ },isDestinationConsented:function isDestinationConsented(state,destConfig,errorHandler,logger){if(!state.consents.initialized.value){return true;}var allowedConsentIds=state.consents.data.value.allowedConsentIds;try{var _cmpConfig$resolution;var consentManagement=destConfig.consentManagement;// If the destination does not have consent management config, events should be sent.
1457
+ if(!consentManagement){return true;}// Get the corresponding consents for the destination
1458
+ var cmpConfig=consentManagement.find(function(c){return c.provider===state.consents.provider.value;});// If there are no consents configured for the destination for the current provider, events should be sent.
1459
+ if(!(cmpConfig!==null&&cmpConfig!==void 0&&cmpConfig.consents)){return true;}var configuredConsents=cmpConfig.consents.map(function(c){return c.consent.trim();}).filter(function(n){return n;});var resolutionStrategy=(_cmpConfig$resolution=cmpConfig.resolutionStrategy)!==null&&_cmpConfig$resolution!==void 0?_cmpConfig$resolution:state.consents.resolutionStrategy.value;// match the configured consents with user provided consents as per
1460
+ // the configured resolution strategy
1461
+ var matchPredicate=function matchPredicate(consent){return allowedConsentIds.includes(consent);};switch(resolutionStrategy){case'or':return configuredConsents.some(matchPredicate)||configuredConsents.length===0;case'and':default:return configuredConsents.every(matchPredicate);}}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,CUSTOM_CONSENT_MANAGER_PLUGIN,DESTINATION_CONSENT_STATUS_ERROR$2);return true;}}}};};
1462
+
1463
+ var DIR_NAME$1d='AdobeAnalytics';var NAME$1d='ADOBE_ANALYTICS';var DISPLAY_NAME$1d='Adobe Analytics';_defineProperty({},DISPLAY_NAME$1d,DIR_NAME$1d);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({'Adobe Analytics':NAME$1d,ADOBEANALYTICS:NAME$1d,'ADOBE ANALYTICS':NAME$1d},NAME$1d,NAME$1d),"AdobeAnalytics",NAME$1d),"adobeanalytics",NAME$1d),'adobe analytics',NAME$1d),'Adobe analytics',NAME$1d),'adobe Analytics',NAME$1d);
1464
+
1465
+ var DIR_NAME$1c='Amplitude';var NAME$1c='AM';var DISPLAY_NAME$1c='Amplitude';_defineProperty({},DISPLAY_NAME$1c,DIR_NAME$1c);_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$1c,NAME$1c),"AMPLITUDE",NAME$1c),"Amplitude",NAME$1c),"am",NAME$1c);
1466
+
1467
+ var DIR_NAME$1b='Appcues';var NAME$1b='APPCUES';var DISPLAY_NAME$1b='Appcues';_defineProperty({},DISPLAY_NAME$1b,DIR_NAME$1b);_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$1b,NAME$1b),"Appcues",NAME$1b),'App Cues',NAME$1b),"appcues",NAME$1b);
1468
+
1469
+ var DIR_NAME$1a='BingAds';var NAME$1a='BINGADS';var DISPLAY_NAME$1a='Bing Ads';_defineProperty({},DISPLAY_NAME$1a,DIR_NAME$1a);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$1a,NAME$1a),"BingAds",NAME$1a),"bingads",NAME$1a),'Bing Ads',NAME$1a),'Bing ads',NAME$1a),'bing Ads',NAME$1a),'bing ads',NAME$1a);
1470
+
1471
+ var DIR_NAME$19='Braze';var NAME$19='BRAZE';var DISPLAY_NAME$19='Braze';_defineProperty({},DISPLAY_NAME$19,DIR_NAME$19);_defineProperty(_defineProperty(_defineProperty({},NAME$19,NAME$19),"Braze",NAME$19),"braze",NAME$19);
1472
+
1473
+ var DIR_NAME$18='Bugsnag';var NAME$18='BUGSNAG';var DISPLAY_NAME$18='Bugsnag';_defineProperty({},DISPLAY_NAME$18,DIR_NAME$18);_defineProperty(_defineProperty(_defineProperty({},NAME$18,NAME$18),"bugsnag",NAME$18),"Bugsnag",NAME$18);
1474
+
1475
+ var DIR_NAME$17='Chartbeat';var NAME$17='CHARTBEAT';var DISPLAY_NAME$17='Chartbeat';_defineProperty({},DISPLAY_NAME$17,DIR_NAME$17);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$17,NAME$17),"Chartbeat",NAME$17),"chartbeat",NAME$17),'Chart Beat',NAME$17),'chart beat',NAME$17);
1476
+
1477
+ var DIR_NAME$16='Clevertap';var NAME$16='CLEVERTAP';var DISPLAY_NAME$16='CleverTap';_defineProperty({},DISPLAY_NAME$16,DIR_NAME$16);_defineProperty(_defineProperty(_defineProperty({},NAME$16,NAME$16),"Clevertap",NAME$16),"clevertap",NAME$16);
1478
+
1479
+ var DIR_NAME$15='Comscore';var NAME$15='COMSCORE';var DISPLAY_NAME$15='Comscore';_defineProperty({},DISPLAY_NAME$15,DIR_NAME$15);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$15,NAME$15),"Comscore",NAME$15),'Com Score',NAME$15),'com Score',NAME$15),'com score',NAME$15),'Com score',NAME$15);
1480
+
1481
+ var DIR_NAME$14='Criteo';var NAME$14='CRITEO';var DISPLAY_NAME$14='Criteo';_defineProperty({},DISPLAY_NAME$14,DIR_NAME$14);_defineProperty(_defineProperty(_defineProperty({},NAME$14,NAME$14),"Criteo",NAME$14),"criteo",NAME$14);
1482
+
1483
+ var DIR_NAME$13='CustomerIO';var NAME$13='CUSTOMERIO';var DISPLAY_NAME$13='Customer IO';_defineProperty({},DISPLAY_NAME$13,DIR_NAME$13);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$13,NAME$13),"Customerio",NAME$13),'Customer.io',NAME$13),'CUSTOMER.IO',NAME$13),'customer.io',NAME$13);
1484
+
1485
+ var DIR_NAME$12='Drip';var NAME$12='DRIP';var DISPLAY_NAME$12='Drip';_defineProperty({},DISPLAY_NAME$12,DIR_NAME$12);_defineProperty(_defineProperty(_defineProperty({},NAME$12,NAME$12),"Drip",NAME$12),"drip",NAME$12);
1486
+
1487
+ var DIR_NAME$11='FacebookPixel';var NAME$11='FACEBOOK_PIXEL';var DISPLAY_NAME$11='Facebook Pixel';_defineProperty({},DISPLAY_NAME$11,DIR_NAME$11);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$11,NAME$11),'FB Pixel',NAME$11),'Facebook Pixel',NAME$11),'facebook pixel',NAME$11),"fbpixel",NAME$11),"FBPIXEL",NAME$11),"FB_PIXEL",NAME$11);
1488
+
1489
+ var DIR_NAME$10='Fullstory';var NAME$10='FULLSTORY';var DISPLAY_NAME$10='Fullstory';_defineProperty({},DISPLAY_NAME$10,DIR_NAME$10);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$10,NAME$10),"Fullstory",NAME$10),"FullStory",NAME$10),'full Story',NAME$10),'Full Story',NAME$10),'Full story',NAME$10),'full story',NAME$10),"fullstory",NAME$10);
1490
+
1491
+ var DIR_NAME$$='GA';var NAME$$='GA';var DISPLAY_NAME$$='Google Analytics';_defineProperty({},DISPLAY_NAME$$,DIR_NAME$$);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$$,NAME$$),'Google Analytics',NAME$$),"GoogleAnalytics",NAME$$),'GOOGLE ANALYTICS',NAME$$),'google analytics',NAME$$);
1492
+
1493
+ var DIR_NAME$_='GA4';var NAME$_='GA4';var DISPLAY_NAME$_='Google Analytics 4 (GA4)';_defineProperty({},DISPLAY_NAME$_,DIR_NAME$_);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$_,NAME$_),'Google Analytics 4',NAME$_),'Google analytics 4',NAME$_),'google analytics 4',NAME$_),'Google Analytics4',NAME$_),'Google analytics4',NAME$_),'google analytics4',NAME$_),'Google Analytics 4 (GA4)',NAME$_),'google analytics 4 (ga4)',NAME$_),"GoogleAnalytics4",NAME$_);
1494
+
1495
+ var DIR_NAME$Z='GoogleAds';var NAME$Z='GOOGLEADS';var DISPLAY_NAME$Z='Google Ads';_defineProperty({},DISPLAY_NAME$Z,DIR_NAME$Z);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$Z,NAME$Z),'Google Ads',NAME$Z),"GoogleAds",NAME$Z),'GOOGLE ADS',NAME$Z),'google ads',NAME$Z),"googleads",NAME$Z);
1496
+
1497
+ var DIR_NAME$Y='GoogleOptimize';var NAME$Y='GOOGLE_OPTIMIZE';var DISPLAY_NAME$Y='Google Optimize';_defineProperty({},DISPLAY_NAME$Y,DIR_NAME$Y);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$Y,NAME$Y),'Google Optimize',NAME$Y),"GoogleOptimize",NAME$Y),"Googleoptimize",NAME$Y),"GOOGLEOPTIMIZE",NAME$Y),'google optimize',NAME$Y),'Google optimize',NAME$Y),'GOOGLE OPTIMIZE',NAME$Y);
1498
+
1499
+ var DIR_NAME$X='GoogleTagManager';var NAME$X='GTM';var DISPLAY_NAME$X='Google Tag Manager';_defineProperty({},DISPLAY_NAME$X,DIR_NAME$X);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$X,NAME$X),'Google Tag Manager',NAME$X),'google tag manager',NAME$X),'googletag manager',NAME$X),"googletagmanager",NAME$X);
1500
+
1501
+ var DIR_NAME$W='Heap';var NAME$W='HEAP';var DISPLAY_NAME$W='Heap.io';_defineProperty({},DISPLAY_NAME$W,DIR_NAME$W);_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$W,NAME$W),"Heap",NAME$W),"heap",NAME$W),'Heap.io',NAME$W);
1502
+
1503
+ var DIR_NAME$V='Hotjar';var NAME$V='HOTJAR';var DISPLAY_NAME$V='Hotjar';_defineProperty({},DISPLAY_NAME$V,DIR_NAME$V);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$V,NAME$V),"Hotjar",NAME$V),"hotjar",NAME$V),'Hot Jar',NAME$V),'hot jar',NAME$V);
1504
+
1505
+ var DIR_NAME$U='HubSpot';var NAME$U='HS';var DISPLAY_NAME$U='HubSpot';_defineProperty({},DISPLAY_NAME$U,DIR_NAME$U);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$U,NAME$U),"Hubspot",NAME$U),"HUBSPOT",NAME$U),'hub spot',NAME$U),'Hub Spot',NAME$U),'Hub spot',NAME$U);
1506
+
1507
+ var DIR_NAME$T='INTERCOM';var NAME$T='INTERCOM';var DISPLAY_NAME$T='Intercom';_defineProperty({},DISPLAY_NAME$T,DIR_NAME$T);_defineProperty(_defineProperty(_defineProperty({},NAME$T,NAME$T),"Intercom",NAME$T),"intercom",NAME$T);
1508
+
1509
+ var DIR_NAME$S='Keen';var NAME$S='KEEN';var DISPLAY_NAME$S='Keen';_defineProperty({},DISPLAY_NAME$S,DIR_NAME$S);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$S,NAME$S),"Keen",NAME$S),'Keen.io',NAME$S),"keen",NAME$S),'keen.io',NAME$S);
1510
+
1511
+ var DIR_NAME$R='Kissmetrics';var NAME$R='KISSMETRICS';var DISPLAY_NAME$R='Kiss Metrics';_defineProperty({},DISPLAY_NAME$R,DIR_NAME$R);_defineProperty(_defineProperty(_defineProperty({},NAME$R,NAME$R),"Kissmetrics",NAME$R),"kissmetrics",NAME$R);
1512
+
1513
+ var DIR_NAME$Q='Klaviyo';var NAME$Q='KLAVIYO';var DISPLAY_NAME$Q='Klaviyo';_defineProperty({},DISPLAY_NAME$Q,DIR_NAME$Q);_defineProperty(_defineProperty(_defineProperty({},NAME$Q,NAME$Q),"Klaviyo",NAME$Q),"klaviyo",NAME$Q);
1514
+
1515
+ var DIR_NAME$P='LaunchDarkly';var NAME$P='LAUNCHDARKLY';var DISPLAY_NAME$P='LaunchDarkly';_defineProperty({},DISPLAY_NAME$P,DIR_NAME$P);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$P,NAME$P),"LaunchDarkly",NAME$P),"Launch_Darkly",NAME$P),'Launch Darkly',NAME$P),"launchDarkly",NAME$P),'launch darkly',NAME$P);
1516
+
1517
+ var _CNameMapping$1;var DIR_NAME$O='LinkedInInsightTag';var NAME$O='LINKEDIN_INSIGHT_TAG';var DISPLAY_NAME$O='Linkedin Insight Tag';_defineProperty({},DISPLAY_NAME$O,DIR_NAME$O);(_CNameMapping$1={},_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_CNameMapping$1,NAME$O,NAME$O),'LinkedIn Insight Tag',NAME$O),'LinkedIn insight tag',NAME$O),'linkedIn insight tag',NAME$O),"Linkedin_insight_tag",NAME$O),"LinkedinInsighttag",NAME$O),"LinkedinInsightTag",NAME$O),"LinkedInInsightTag",NAME$O),"Linkedininsighttag",NAME$O),"LINKEDININSIGHTTAG",NAME$O),_defineProperty(_CNameMapping$1,"linkedininsighttag",NAME$O));
1518
+
1519
+ var DIR_NAME$N='Lotame';var NAME$N='LOTAME';var DISPLAY_NAME$N='Lotame';_defineProperty({},DISPLAY_NAME$N,DIR_NAME$N);_defineProperty(_defineProperty(_defineProperty({},NAME$N,NAME$N),"Lotame",NAME$N),"lotame",NAME$N);
1520
+
1521
+ var DIR_NAME$M='Lytics';var NAME$M='LYTICS';var DISPLAY_NAME$M='Lytics';_defineProperty({},DISPLAY_NAME$M,DIR_NAME$M);_defineProperty(_defineProperty(_defineProperty({},NAME$M,NAME$M),"Lytics",NAME$M),"lytics",NAME$M);
1522
+
1523
+ var DIR_NAME$L='Mixpanel';var NAME$L='MP';var DISPLAY_NAME$L='Mixpanel';_defineProperty({},DISPLAY_NAME$L,DIR_NAME$L);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$L,NAME$L),"MIXPANEL",NAME$L),"Mixpanel",NAME$L),'MIX PANEL',NAME$L),'Mix panel',NAME$L),'Mix Panel',NAME$L);
1524
+
1525
+ var DIR_NAME$K='MoEngage';var NAME$K='MOENGAGE';var DISPLAY_NAME$K='MoEngage';_defineProperty({},DISPLAY_NAME$K,DIR_NAME$K);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$K,NAME$K),"MoEngage",NAME$K),"moengage",NAME$K),"Moengage",NAME$K),'Mo Engage',NAME$K),'mo engage',NAME$K),'Mo engage',NAME$K);
1526
+
1527
+ var DIR_NAME$J='Optimizely';var NAME$J='OPTIMIZELY';var DISPLAY_NAME$J='Optimizely Web';_defineProperty({},DISPLAY_NAME$J,DIR_NAME$J);_defineProperty(_defineProperty(_defineProperty({},NAME$J,NAME$J),"Optimizely",NAME$J),"optimizely",NAME$J);
1528
+
1529
+ var DIR_NAME$I='Pendo';var NAME$I='PENDO';var DISPLAY_NAME$I='Pendo';_defineProperty({},DISPLAY_NAME$I,DIR_NAME$I);_defineProperty(_defineProperty(_defineProperty({},NAME$I,NAME$I),"Pendo",NAME$I),"pendo",NAME$I);
1530
+
1531
+ var _CNameMapping;var DIR_NAME$H='PinterestTag';var NAME$H='PINTEREST_TAG';var DISPLAY_NAME$H='Pinterest Tag';_defineProperty({},DISPLAY_NAME$H,DIR_NAME$H);(_CNameMapping={},_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_CNameMapping,NAME$H,NAME$H),"PinterestTag",NAME$H),"Pinterest_Tag",NAME$H),"PINTERESTTAG",NAME$H),"pinterest",NAME$H),"PinterestAds",NAME$H),"Pinterest_Ads",NAME$H),"Pinterest",NAME$H),'Pinterest Tag',NAME$H),'Pinterest tag',NAME$H),_defineProperty(_defineProperty(_defineProperty(_defineProperty(_CNameMapping,'PINTEREST TAG',NAME$H),'pinterest tag',NAME$H),'Pinterest Ads',NAME$H),'Pinterest ads',NAME$H));
1532
+
1533
+ var DIR_NAME$G='PostAffiliatePro';var NAME$G='POST_AFFILIATE_PRO';var DISPLAY_NAME$G='Post Affiliate Pro';_defineProperty({},DISPLAY_NAME$G,DIR_NAME$G);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$G,NAME$G),"PostAffiliatePro",NAME$G),"Post_affiliate_pro",NAME$G),'Post Affiliate Pro',NAME$G),'Post affiliate pro',NAME$G),'post affiliate pro',NAME$G),"postaffiliatepro",NAME$G),"POSTAFFILIATEPRO",NAME$G);
1534
+
1535
+ var DIR_NAME$F='Posthog';var NAME$F='POSTHOG';var DISPLAY_NAME$F='PostHog';_defineProperty({},DISPLAY_NAME$F,DIR_NAME$F);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$F,NAME$F),"PostHog",NAME$F),"Posthog",NAME$F),"posthog",NAME$F),'Post Hog',NAME$F),'Post hog',NAME$F),'post hog',NAME$F);
1536
+
1537
+ var DIR_NAME$E='ProfitWell';var NAME$E='PROFITWELL';var DISPLAY_NAME$E='ProfitWell';_defineProperty({},DISPLAY_NAME$E,DIR_NAME$E);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$E,NAME$E),"ProfitWell",NAME$E),"profitwell",NAME$E),"Profitwell",NAME$E),'Profit Well',NAME$E),'profit well',NAME$E),'Profit well',NAME$E);
1538
+
1539
+ var DIR_NAME$D='Qualtrics';var NAME$D='QUALTRICS';var DISPLAY_NAME$D='Qualtrics';_defineProperty({},DISPLAY_NAME$D,DIR_NAME$D);_defineProperty(_defineProperty(_defineProperty({},NAME$D,NAME$D),"Qualtrics",NAME$D),"qualtrics",NAME$D);
1540
+
1541
+ var DIR_NAME$C='QuantumMetric';var NAME$C='QUANTUMMETRIC';var DISPLAY_NAME$C='Quantum Metric';_defineProperty({},DISPLAY_NAME$C,DIR_NAME$C);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$C,NAME$C),'Quantum Metric',NAME$C),'quantum Metric',NAME$C),'quantum metric',NAME$C),"QuantumMetric",NAME$C),"quantumMetric",NAME$C),"quantummetric",NAME$C),"Quantum_Metric",NAME$C);
1542
+
1543
+ var DIR_NAME$B='RedditPixel';var NAME$B='REDDIT_PIXEL';var DISPLAY_NAME$B='Reddit Pixel';_defineProperty({},DISPLAY_NAME$B,DIR_NAME$B);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$B,NAME$B),"Reddit_Pixel",NAME$B),"RedditPixel",NAME$B),"REDDITPIXEL",NAME$B),"redditpixel",NAME$B),'Reddit Pixel',NAME$B),'REDDIT PIXEL',NAME$B),'reddit pixel',NAME$B);
1544
+
1545
+ var DIR_NAME$A='Sentry';var NAME$A='SENTRY';var DISPLAY_NAME$A='Sentry';_defineProperty({},DISPLAY_NAME$A,DIR_NAME$A);_defineProperty(_defineProperty(_defineProperty({},NAME$A,NAME$A),"sentry",NAME$A),"Sentry",NAME$A);
1546
+
1547
+ var DIR_NAME$z='SnapPixel';var NAME$z='SNAP_PIXEL';var DISPLAY_NAME$z='Snap Pixel';_defineProperty({},DISPLAY_NAME$z,DIR_NAME$z);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$z,NAME$z),"Snap_Pixel",NAME$z),"SnapPixel",NAME$z),"SNAPPIXEL",NAME$z),"snappixel",NAME$z),'Snap Pixel',NAME$z),'SNAP PIXEL',NAME$z),'snap pixel',NAME$z);
1548
+
1549
+ var DIR_NAME$y='TVSquared';var NAME$y='TVSQUARED';var DISPLAY_NAME$y='TVSquared';_defineProperty({},DISPLAY_NAME$y,DIR_NAME$y);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$y,NAME$y),"TVSquared",NAME$y),"tvsquared",NAME$y),"tvSquared",NAME$y),"TvSquared",NAME$y),"Tvsquared",NAME$y),'TV Squared',NAME$y),'tv squared',NAME$y),'tv Squared',NAME$y);
1550
+
1551
+ var DIR_NAME$x='VWO';var NAME$x='VWO';var DISPLAY_NAME$x='VWO';_defineProperty({},DISPLAY_NAME$x,DIR_NAME$x);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$x,NAME$x),"VisualWebsiteOptimizer",NAME$x),"Visualwebsiteoptimizer",NAME$x),"visualwebsiteoptimizer",NAME$x),"vwo",NAME$x),'Visual Website Optimizer',NAME$x),'Visual website optimizer',NAME$x),'visual website optimizer',NAME$x);
1552
+
1553
+ var DIR_NAME$w='GA360';var NAME$w='GA360';var DISPLAY_NAME$w='Google Analytics 360';_defineProperty({},DISPLAY_NAME$w,DIR_NAME$w);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$w,NAME$w),'Google Analytics 360',NAME$w),'Google analytics 360',NAME$w),'google analytics 360',NAME$w),'Google Analytics360',NAME$w),'Google analytics360',NAME$w),'google analytics360',NAME$w),"GoogleAnalytics360",NAME$w),'GA 360',NAME$w);
1554
+
1555
+ var DIR_NAME$v='Adroll';var NAME$v='ADROLL';var DISPLAY_NAME$v='Adroll';_defineProperty({},DISPLAY_NAME$v,DIR_NAME$v);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$v,NAME$v),"Adroll",NAME$v),'Ad roll',NAME$v),'ad roll',NAME$v),"adroll",NAME$v);
1556
+
1557
+ var DIR_NAME$u='DCMFloodlight';var NAME$u='DCM_FLOODLIGHT';var DISPLAY_NAME$u='DCM Floodlight';_defineProperty({},DISPLAY_NAME$u,DIR_NAME$u);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$u,NAME$u),'DCM Floodlight',NAME$u),'dcm floodlight',NAME$u),'Dcm Floodlight',NAME$u),"DCMFloodlight",NAME$u),"dcmfloodlight",NAME$u),"DcmFloodlight",NAME$u),"dcm_floodlight",NAME$u),"DCM_Floodlight",NAME$u);
1558
+
1559
+ var DIR_NAME$t='Matomo';var NAME$t='MATOMO';var DISPLAY_NAME$t='Matomo';_defineProperty({},DISPLAY_NAME$t,DIR_NAME$t);_defineProperty(_defineProperty(_defineProperty({},NAME$t,NAME$t),"Matomo",NAME$t),"matomo",NAME$t);
1560
+
1561
+ var DIR_NAME$s='Vero';var NAME$s='VERO';var DISPLAY_NAME$s='Vero';_defineProperty({},DISPLAY_NAME$s,DIR_NAME$s);_defineProperty(_defineProperty(_defineProperty({},NAME$s,NAME$s),"Vero",NAME$s),"vero",NAME$s);
1562
+
1563
+ var DIR_NAME$r='Mouseflow';var NAME$r='MOUSEFLOW';var DISPLAY_NAME$r='Mouseflow';_defineProperty({},DISPLAY_NAME$r,DIR_NAME$r);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$r,NAME$r),"Mouseflow",NAME$r),"mouseflow",NAME$r),"mouseFlow",NAME$r),"MouseFlow",NAME$r),'Mouse flow',NAME$r),'mouse flow',NAME$r),'mouse Flow',NAME$r),'Mouse Flow',NAME$r);
1564
+
1565
+ var DIR_NAME$q='Rockerbox';var NAME$q='ROCKERBOX';var DISPLAY_NAME$q='Rockerbox';_defineProperty({},DISPLAY_NAME$q,DIR_NAME$q);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$q,NAME$q),"Rockerbox",NAME$q),"rockerbox",NAME$q),"RockerBox",NAME$q),'Rocker box',NAME$q),'rocker box',NAME$q),'Rocker Box',NAME$q);
1566
+
1567
+ var DIR_NAME$p='ConvertFlow';var NAME$p='CONVERTFLOW';var DISPLAY_NAME$p='ConvertFlow';_defineProperty({},DISPLAY_NAME$p,DIR_NAME$p);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$p,NAME$p),"Convertflow",NAME$p),"convertflow",NAME$p),"convertFlow",NAME$p),"ConvertFlow",NAME$p),'Convert flow',NAME$p),'convert flow',NAME$p),'convert Flow',NAME$p),'Convert Flow',NAME$p),'CONVERT FLOW',NAME$p);
1568
+
1569
+ var DIR_NAME$o='SnapEngage';var NAME$o='SNAPENGAGE';var DISPLAY_NAME$o='SnapEngage';_defineProperty({},DISPLAY_NAME$o,DIR_NAME$o);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$o,NAME$o),"SnapEngage",NAME$o),"Snap_Engage",NAME$o),"snapengage",NAME$o),'SNAP ENGAGE',NAME$o),'Snap Engage',NAME$o),'snap engage',NAME$o);
1570
+
1571
+ var DIR_NAME$n='LiveChat';var NAME$n='LIVECHAT';var DISPLAY_NAME$n='LiveChat';_defineProperty({},DISPLAY_NAME$n,DIR_NAME$n);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$n,NAME$n),"LiveChat",NAME$n),"Live_Chat",NAME$n),"livechat",NAME$n),'LIVE CHAT',NAME$n),'Live Chat',NAME$n),'live chat',NAME$n);
1572
+
1573
+ var DIR_NAME$m='Shynet';var NAME$m='SHYNET';var DISPLAY_NAME$m='Shynet';_defineProperty({},DISPLAY_NAME$m,DIR_NAME$m);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$m,NAME$m),"shynet",NAME$m),"ShyNet",NAME$m),"shyNet",NAME$m),"Shynet",NAME$m),'shy net',NAME$m),'Shy Net',NAME$m),'shy Net',NAME$m),'Shy net',NAME$m);
1574
+
1575
+ var DIR_NAME$l='Woopra';var NAME$l='WOOPRA';var DISPLAY_NAME$l='Woopra';_defineProperty({},DISPLAY_NAME$l,DIR_NAME$l);_defineProperty(_defineProperty(_defineProperty({},NAME$l,NAME$l),"Woopra",NAME$l),"woopra",NAME$l);
1576
+
1577
+ var DIR_NAME$k='RollBar';var NAME$k='ROLLBAR';var DISPLAY_NAME$k='RollBar';_defineProperty({},DISPLAY_NAME$k,DIR_NAME$k);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$k,NAME$k),"RollBar",NAME$k),"Roll_Bar",NAME$k),"rollbar",NAME$k),"Rollbar",NAME$k),'ROLL BAR',NAME$k),'Roll Bar',NAME$k),'roll bar',NAME$k);
1578
+
1579
+ var DIR_NAME$j='QuoraPixel';var NAME$j='QUORA_PIXEL';var DISPLAY_NAME$j='Quora Pixel';_defineProperty({},DISPLAY_NAME$j,DIR_NAME$j);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$j,NAME$j),'Quora Pixel',NAME$j),'Quora pixel',NAME$j),'QUORA PIXEL',NAME$j),"QuoraPixel",NAME$j),"Quorapixel",NAME$j),"QUORAPIXEL",NAME$j),"Quora_Pixel",NAME$j),"quora_pixel",NAME$j),"Quora",NAME$j);
1580
+
1581
+ var DIR_NAME$i='June';var NAME$i='JUNE';var DISPLAY_NAME$i='June';_defineProperty({},DISPLAY_NAME$i,DIR_NAME$i);_defineProperty(_defineProperty(_defineProperty({},NAME$i,NAME$i),"June",NAME$i),"june",NAME$i);
1582
+
1583
+ var DIR_NAME$h='Engage';var NAME$h='ENGAGE';var DISPLAY_NAME$h='Engage';_defineProperty({},DISPLAY_NAME$h,DIR_NAME$h);_defineProperty(_defineProperty(_defineProperty({},NAME$h,NAME$h),"Engage",NAME$h),"engage",NAME$h);
1584
+
1585
+ var DIR_NAME$g='Iterable';var NAME$g='ITERABLE';var DISPLAY_NAME$g='Iterable';_defineProperty({},DISPLAY_NAME$g,DIR_NAME$g);_defineProperty(_defineProperty(_defineProperty({},NAME$g,NAME$g),"Iterable",NAME$g),"iterable",NAME$g);
1586
+
1587
+ var DIR_NAME$f='YandexMetrica';var NAME$f='YANDEX_METRICA';var DISPLAY_NAME$f='Yandex.Metrica';_defineProperty({},DISPLAY_NAME$f,DIR_NAME$f);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$f,NAME$f),"Yandexmetrica",NAME$f),"yandexmetrica",NAME$f),"yandexMetrica",NAME$f),"YandexMetrica",NAME$f);
1588
+
1589
+ var DIR_NAME$e='Refiner';var NAME$e='REFINER';var DISPLAY_NAME$e='Refiner';_defineProperty({},DISPLAY_NAME$e,DIR_NAME$e);_defineProperty(_defineProperty(_defineProperty({},NAME$e,NAME$e),"Refiner",NAME$e),"refiner",NAME$e);
1590
+
1591
+ var DIR_NAME$d='Qualaroo';var NAME$d='QUALAROO';var DISPLAY_NAME$d='Qualaroo';_defineProperty({},DISPLAY_NAME$d,DIR_NAME$d);_defineProperty(_defineProperty(_defineProperty({},NAME$d,NAME$d),"Qualaroo",NAME$d),"qualaroo",NAME$d);
1592
+
1593
+ var DIR_NAME$c='Podsights';var NAME$c='PODSIGHTS';var DISPLAY_NAME$c='Podsights';_defineProperty({},DISPLAY_NAME$c,DIR_NAME$c);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$c,NAME$c),"Podsights",NAME$c),"PodSights",NAME$c),'pod Sights',NAME$c),'Pod Sights',NAME$c),'pod sights',NAME$c),'POD SIGHTS',NAME$c),'Pod sights',NAME$c);
1594
+
1595
+ var DIR_NAME$b='Axeptio';var NAME$b='AXEPTIO';var DISPLAY_NAME$b='Axeptio';_defineProperty({},DISPLAY_NAME$b,DIR_NAME$b);_defineProperty(_defineProperty(_defineProperty({},NAME$b,NAME$b),"Axeptio",NAME$b),"axeptio",NAME$b);
1596
+
1597
+ var DIR_NAME$a='Satismeter';var NAME$a='SATISMETER';var DISPLAY_NAME$a='Satismeter';_defineProperty({},DISPLAY_NAME$a,DIR_NAME$a);_defineProperty(_defineProperty(_defineProperty({},NAME$a,NAME$a),"Satismeter",NAME$a),"SatisMeter",NAME$a);
1598
+
1599
+ var DIR_NAME$9='MicrosoftClarity';var NAME$9='MICROSOFT_CLARITY';var DISPLAY_NAME$9='Microsoft Clarity';_defineProperty({},DISPLAY_NAME$9,DIR_NAME$9);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$9,NAME$9),'Microsoft Clarity',NAME$9),'Microsoft clarity',NAME$9),'microsoft clarity',NAME$9),"Microsoft_clarity",NAME$9),"MicrosoftClarity",NAME$9),"MICROSOFTCLARITY",NAME$9),"microsoftclarity",NAME$9),"microsoftClarity",NAME$9);
1600
+
1601
+ var DIR_NAME$8='Sendinblue';var NAME$8='SENDINBLUE';var DISPLAY_NAME$8='Sendinblue';_defineProperty({},DISPLAY_NAME$8,DIR_NAME$8);_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$8,NAME$8),"Sendinblue",NAME$8),"sendinblue",NAME$8),"SendinBlue",NAME$8);
1602
+
1603
+ var DIR_NAME$7='Olark';var NAME$7='OLARK';var DISPLAY_NAME$7='Olark';_defineProperty({},DISPLAY_NAME$7,DIR_NAME$7);_defineProperty(_defineProperty(_defineProperty({},NAME$7,NAME$7),"Olark",NAME$7),"olark",NAME$7);
1604
+
1605
+ var DIR_NAME$6='Lemnisk';var NAME$6='LEMNISK';var DISPLAY_NAME$6='Lemnisk';_defineProperty({},DISPLAY_NAME$6,DIR_NAME$6);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$6,NAME$6),"LEMNISK_MARKETING_AUTOMATION",NAME$6),'Lemnisk Marketing Automation',NAME$6),"LemniskMarketingAutomation",NAME$6),"lemniskmarketingautomation",NAME$6),"lemniskMarketingAutomation",NAME$6),"lemnisk",NAME$6),"Lemnisk",NAME$6);
1606
+
1607
+ var DIR_NAME$5='TiktokAds';var NAME$5='TIKTOK_ADS';var DISPLAY_NAME$5='TikTok Ads';_defineProperty({},DISPLAY_NAME$5,DIR_NAME$5);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$5,NAME$5),"TiktokAds",NAME$5),'Tiktok ads',NAME$5),'Tiktok Ads',NAME$5),'Tik Tok Ads',NAME$5),'tik tok ads',NAME$5),"tiktokads",NAME$5);
1608
+
1609
+ var DIR_NAME$4='ActiveCampaign';var NAME$4='ACTIVE_CAMPAIGN';var DISPLAY_NAME$4='Active Campaign';_defineProperty({},DISPLAY_NAME$4,DIR_NAME$4);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({ActiveCampaign:NAME$4,'Active Campaign':NAME$4,'ACTIVE CAMPAIGN':NAME$4},NAME$4,NAME$4),"activecampaign",NAME$4),'active campaign',NAME$4),'Active campaign',NAME$4),'active Campaign',NAME$4),"active_campaign",NAME$4);
1610
+
1611
+ var DIR_NAME$3='Sprig';var NAME$3='SPRIG';var DISPLAY_NAME$3='Sprig';_defineProperty({},DISPLAY_NAME$3,DIR_NAME$3);_defineProperty(_defineProperty(_defineProperty({},NAME$3,NAME$3),"Sprig",NAME$3),"sprig",NAME$3);
1612
+
1613
+ var DIR_NAME$2='SpotifyPixel';var NAME$2='SPOTIFYPIXEL';var DISPLAY_NAME$2='Spotify Pixel';_defineProperty({},DISPLAY_NAME$2,DIR_NAME$2);_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$2,NAME$2),'Spotify Pixel',NAME$2),'spotify pixel',NAME$2),"SPOTIFY_PIXEL",NAME$2);
1614
+
1615
+ var DIR_NAME$1='CommandBar';var NAME$1='COMMANDBAR';var DISPLAY_NAME$1='CommandBar';_defineProperty({},DISPLAY_NAME$1,DIR_NAME$1);_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME$1,NAME$1),'Command Bar',NAME$1),'Commandbar',NAME$1),"COMMAND_BAR",NAME$1),"commandbar",NAME$1);
1616
+
1617
+ var DIR_NAME='Ninetailed';var NAME='NINETAILED';var DISPLAY_NAME='Ninetailed';_defineProperty({},DISPLAY_NAME,DIR_NAME);_defineProperty(_defineProperty(_defineProperty(_defineProperty({},NAME,NAME),"Ninetailed",NAME),"ninetailed",NAME),"NineTailed",NAME);
1618
+
1619
+ var _destDisplayNamesToFi;// map of the destination display names to the destination directory names
1620
+ var destDisplayNamesToFileNamesMap=(_destDisplayNamesToFi={},_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$U,DIR_NAME$U),DISPLAY_NAME$$,DIR_NAME$$),DISPLAY_NAME$V,DIR_NAME$V),DISPLAY_NAME$Z,DIR_NAME$Z),DISPLAY_NAME$x,DIR_NAME$x),DISPLAY_NAME$X,DIR_NAME$X),DISPLAY_NAME$19,DIR_NAME$19),DISPLAY_NAME$T,DIR_NAME$T),DISPLAY_NAME$S,DIR_NAME$S),DISPLAY_NAME$R,DIR_NAME$R),_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$13,DIR_NAME$13),DISPLAY_NAME$17,DIR_NAME$17),DISPLAY_NAME$15,DIR_NAME$15),DISPLAY_NAME$11,DIR_NAME$11),DISPLAY_NAME$N,DIR_NAME$N),DISPLAY_NAME$J,DIR_NAME$J),DISPLAY_NAME$18,DIR_NAME$18),DISPLAY_NAME$10,DIR_NAME$10),DISPLAY_NAME$y,DIR_NAME$y),DISPLAY_NAME$_,DIR_NAME$_),_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$K,DIR_NAME$K),DISPLAY_NAME$1c,DIR_NAME$1c),DISPLAY_NAME$I,DIR_NAME$I),DISPLAY_NAME$M,DIR_NAME$M),DISPLAY_NAME$1b,DIR_NAME$1b),DISPLAY_NAME$F,DIR_NAME$F),DISPLAY_NAME$Q,DIR_NAME$Q),DISPLAY_NAME$16,DIR_NAME$16),DISPLAY_NAME$1a,DIR_NAME$1a),DISPLAY_NAME$H,DIR_NAME$H),_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$1d,DIR_NAME$1d),DISPLAY_NAME$O,DIR_NAME$O),DISPLAY_NAME$B,DIR_NAME$B),DISPLAY_NAME$12,DIR_NAME$12),DISPLAY_NAME$W,DIR_NAME$W),DISPLAY_NAME$14,DIR_NAME$14),DISPLAY_NAME$L,DIR_NAME$L),DISPLAY_NAME$D,DIR_NAME$D),DISPLAY_NAME$E,DIR_NAME$E),DISPLAY_NAME$A,DIR_NAME$A),_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$C,DIR_NAME$C),DISPLAY_NAME$z,DIR_NAME$z),DISPLAY_NAME$G,DIR_NAME$G),DISPLAY_NAME$Y,DIR_NAME$Y),DISPLAY_NAME$P,DIR_NAME$P),DISPLAY_NAME$w,DIR_NAME$w),DISPLAY_NAME$v,DIR_NAME$v),DISPLAY_NAME$u,DIR_NAME$u),DISPLAY_NAME$t,DIR_NAME$t),DISPLAY_NAME$s,DIR_NAME$s),_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$r,DIR_NAME$r),DISPLAY_NAME$q,DIR_NAME$q),DISPLAY_NAME$p,DIR_NAME$p),DISPLAY_NAME$o,DIR_NAME$o),DISPLAY_NAME$n,DIR_NAME$n),DISPLAY_NAME$m,DIR_NAME$m),DISPLAY_NAME$l,DIR_NAME$l),DISPLAY_NAME$k,DIR_NAME$k),DISPLAY_NAME$j,DIR_NAME$j),DISPLAY_NAME$i,DIR_NAME$i),_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$h,DIR_NAME$h),DISPLAY_NAME$g,DIR_NAME$g),DISPLAY_NAME$f,DIR_NAME$f),DISPLAY_NAME$e,DIR_NAME$e),DISPLAY_NAME$d,DIR_NAME$d),DISPLAY_NAME$c,DIR_NAME$c),DISPLAY_NAME$b,DIR_NAME$b),DISPLAY_NAME$a,DIR_NAME$a),DISPLAY_NAME$9,DIR_NAME$9),DISPLAY_NAME$8,DIR_NAME$8),_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_defineProperty(_destDisplayNamesToFi,DISPLAY_NAME$7,DIR_NAME$7),DISPLAY_NAME$6,DIR_NAME$6),DISPLAY_NAME$5,DIR_NAME$5),DISPLAY_NAME$4,DIR_NAME$4),DISPLAY_NAME$3,DIR_NAME$3),DISPLAY_NAME$2,DIR_NAME$2),DISPLAY_NAME$1,DIR_NAME$1),DISPLAY_NAME,DIR_NAME));
1621
+
1622
+ var DEFAULT_INTEGRATIONS_CONFIG={All:true};
1623
+
1624
+ var isDestIntgConfigTruthy=function isDestIntgConfigTruthy(destIntgConfig){return !isUndefined(destIntgConfig)&&Boolean(destIntgConfig)===true;};var isDestIntgConfigFalsy=function isDestIntgConfigFalsy(destIntgConfig){return !isUndefined(destIntgConfig)&&Boolean(destIntgConfig)===false;};/**
1625
+ * Filters the destinations that should not be loaded or forwarded events to based on the integration options (load or events API)
1626
+ * @param intgOpts Integration options object
1627
+ * @param destinations Destinations array
1628
+ * @returns Destinations array filtered based on the integration options
1629
+ */var filterDestinations=function filterDestinations(intgOpts,destinations){var _intgOpts$All;var allOptVal=(_intgOpts$All=intgOpts.All)!==null&&_intgOpts$All!==void 0?_intgOpts$All:true;return destinations.filter(function(dest){var destDisplayName=dest.displayName;var isDestEnabled;if(allOptVal){isDestEnabled=true;if(isDestIntgConfigFalsy(intgOpts[destDisplayName])){isDestEnabled=false;}}else {isDestEnabled=false;if(isDestIntgConfigTruthy(intgOpts[destDisplayName])){isDestEnabled=true;}}return isDestEnabled;});};
1630
+
1631
+ var READY_CHECK_TIMEOUT_MS=11*1000;// 11 seconds
1632
+ var SCRIPT_LOAD_TIMEOUT_MS=10*1000;// 10 seconds
1633
+ var DEVICE_MODE_DESTINATIONS_PLUGIN='DeviceModeDestinationsPlugin';
1634
+
1635
+ var DESTINATION_NOT_SUPPORTED_ERROR=function DESTINATION_NOT_SUPPORTED_ERROR(destUserFriendlyId){return "Destination ".concat(destUserFriendlyId," is not supported.");};var DESTINATION_SDK_LOAD_ERROR=function DESTINATION_SDK_LOAD_ERROR(context,destUserFriendlyId){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to load script for destination ").concat(destUserFriendlyId,".");};var DESTINATION_INIT_ERROR=function DESTINATION_INIT_ERROR(destUserFriendlyId){return "Failed to initialize destination ".concat(destUserFriendlyId,".");};var DESTINATION_INTEGRATIONS_DATA_ERROR=function DESTINATION_INTEGRATIONS_DATA_ERROR(destUserFriendlyId){return "Failed to get integrations data for destination ".concat(destUserFriendlyId,".");};var DESTINATION_READY_TIMEOUT_ERROR=function DESTINATION_READY_TIMEOUT_ERROR(timeout,destUserFriendlyId){return "A timeout of ".concat(timeout," ms occurred while trying to check the ready status for \"").concat(destUserFriendlyId,"\" destination.");};
1636
+
1637
+ /**
1638
+ * Determines if the destination SDK code is evaluated
1639
+ * @param destSDKIdentifier The name of the global globalThis object that contains the destination SDK
1640
+ * @param sdkTypeName The name of the destination SDK type
1641
+ * @param logger Logger instance
1642
+ * @returns true if the destination SDK code is evaluated, false otherwise
1643
+ */var isDestinationSDKMounted=function isDestinationSDKMounted(destSDKIdentifier,sdkTypeName,logger){return Boolean(globalThis[destSDKIdentifier]&&globalThis[destSDKIdentifier][sdkTypeName]&&globalThis[destSDKIdentifier][sdkTypeName].prototype&&typeof globalThis[destSDKIdentifier][sdkTypeName].prototype.constructor!=='undefined');};var createDestinationInstance=function createDestinationInstance(destSDKIdentifier,sdkTypeName,dest,state){var _state$consents$postC,_state$consents$postC2;var rAnalytics=globalThis.rudderanalytics;var analytics=rAnalytics.getAnalyticsInstance(state.lifecycle.writeKey.value);var analyticsInstance={loadIntegration:state.nativeDestinations.loadIntegration.value,logLevel:state.lifecycle.logLevel.value,loadOnlyIntegrations:(_state$consents$postC=(_state$consents$postC2=state.consents.postConsent.value)===null||_state$consents$postC2===void 0?void 0:_state$consents$postC2.integrations)!==null&&_state$consents$postC!==void 0?_state$consents$postC:state.nativeDestinations.loadOnlyIntegrations.value,page:function page(category,name,properties,options,callback){return analytics.page(pageArgumentsToCallOptions(category,name,properties,options,callback));},track:function track(event,properties,options,callback){return analytics.track(trackArgumentsToCallOptions(event,properties,options,callback));},identify:function identify(userId,traits,options,callback){return analytics.identify(identifyArgumentsToCallOptions(userId,traits,options,callback));},alias:function alias(to,from,options,callback){return analytics.alias(aliasArgumentsToCallOptions(to,from,options,callback));},group:function group(groupId,traits,options,callback){return analytics.group(groupArgumentsToCallOptions(groupId,traits,options,callback));},getAnonymousId:function getAnonymousId(options){return analytics.getAnonymousId(options);},getUserId:function getUserId(){return analytics.getUserId();},getUserTraits:function getUserTraits(){return analytics.getUserTraits();},getGroupId:function getGroupId(){return analytics.getGroupId();},getGroupTraits:function getGroupTraits(){return analytics.getGroupTraits();},getSessionId:function getSessionId(){return analytics.getSessionId();}};var deviceModeDestination=new globalThis[destSDKIdentifier][sdkTypeName](clone(dest.config),analyticsInstance,{shouldApplyDeviceModeTransformation:dest.shouldApplyDeviceModeTransformation,propagateEventsUntransformedOnError:dest.propagateEventsUntransformedOnError,destinationId:dest.id});return deviceModeDestination;};var isDestinationReady=function isDestinationReady(dest){return new Promise(function(resolve,reject){var instance=dest.instance;var handleNumber;var checkReady=function checkReady(){if(instance.isLoaded()&&(!instance.isReady||instance.isReady())){resolve(true);}else {handleNumber=globalThis.requestAnimationFrame(checkReady);}};checkReady();setTimeout(function(){globalThis.cancelAnimationFrame(handleNumber);reject(new Error(DESTINATION_READY_TIMEOUT_ERROR(READY_CHECK_TIMEOUT_MS,dest.userFriendlyId)));},READY_CHECK_TIMEOUT_MS);});};/**
1644
+ * Extracts the integration config, if any, from the given destination
1645
+ * and merges it with the current integrations config
1646
+ * @param dest Destination object
1647
+ * @param curDestIntgConfig Current destinations integration config
1648
+ * @param logger Logger object
1649
+ * @returns Combined destinations integrations config
1650
+ */var getCumulativeIntegrationsConfig=function getCumulativeIntegrationsConfig(dest,curDestIntgConfig,errorHandler){var _dest$instance;var integrationsConfig=curDestIntgConfig;if(isFunction((_dest$instance=dest.instance)===null||_dest$instance===void 0?void 0:_dest$instance.getDataForIntegrationsObject)){try{var _dest$instance2;integrationsConfig=mergeDeepRight(curDestIntgConfig,(_dest$instance2=dest.instance)===null||_dest$instance2===void 0?void 0:_dest$instance2.getDataForIntegrationsObject());}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,DEVICE_MODE_DESTINATIONS_PLUGIN,DESTINATION_INTEGRATIONS_DATA_ERROR(dest.userFriendlyId));}}return integrationsConfig;};var initializeDestination=function initializeDestination(dest,state,destSDKIdentifier,sdkTypeName,errorHandler,logger){try{var initializedDestination=clone(dest);var destInstance=createDestinationInstance(destSDKIdentifier,sdkTypeName,dest,state);initializedDestination.instance=destInstance;destInstance.init();isDestinationReady(initializedDestination).then(function(){// Collect the integrations data for the hybrid mode destinations
1651
+ if(isHybridModeDestination(initializedDestination)){state.nativeDestinations.integrationsConfig.value=getCumulativeIntegrationsConfig(initializedDestination,state.nativeDestinations.integrationsConfig.value,errorHandler);}state.nativeDestinations.initializedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.initializedDestinations.value),[initializedDestination]);}).catch(function(err){state.nativeDestinations.failedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.failedDestinations.value),[dest]);// The error message is already formatted in the isDestinationReady function
1652
+ logger===null||logger===void 0||logger.error(err);});}catch(err){state.nativeDestinations.failedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.failedDestinations.value),[dest]);errorHandler===null||errorHandler===void 0||errorHandler.onError(err,DEVICE_MODE_DESTINATIONS_PLUGIN,DESTINATION_INIT_ERROR(dest.userFriendlyId));}};
1653
+
1654
+ var pluginName$b='DeviceModeDestinations';var DeviceModeDestinations=function DeviceModeDestinations(){return {name:pluginName$b,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$b]);},nativeDestinations:{setActiveDestinations:function setActiveDestinations(state,pluginsManager,errorHandler,logger){var _clone,_state$consents$postC,_state$consents$postC2;// Normalize the integration options from the load API call
1655
+ state.nativeDestinations.loadOnlyIntegrations.value=(_clone=clone(state.loadOptions.value.integrations))!==null&&_clone!==void 0?_clone:DEFAULT_INTEGRATIONS_CONFIG;state.nativeDestinations.loadIntegration.value=state.loadOptions.value.loadIntegration;// Filter destination that doesn't have mapping config-->Integration names
1656
+ var configSupportedDestinations=state.nativeDestinations.configuredDestinations.value.filter(function(configDest){if(destDisplayNamesToFileNamesMap[configDest.displayName]){return true;}errorHandler===null||errorHandler===void 0||errorHandler.onError(new Error(DESTINATION_NOT_SUPPORTED_ERROR(configDest.userFriendlyId)),DEVICE_MODE_DESTINATIONS_PLUGIN);return false;});// Filter destinations that are disabled through load or consent API options
1657
+ var destinationsToLoad=filterDestinations((_state$consents$postC=(_state$consents$postC2=state.consents.postConsent.value)===null||_state$consents$postC2===void 0?void 0:_state$consents$postC2.integrations)!==null&&_state$consents$postC!==void 0?_state$consents$postC:state.nativeDestinations.loadOnlyIntegrations.value,configSupportedDestinations);var consentedDestinations=destinationsToLoad.filter(function(dest){var _pluginsManager$invok;return(// if consent manager is not configured, then default to load the destination
1658
+ (_pluginsManager$invok=pluginsManager.invokeSingle("consentManager.isDestinationConsented",state,dest.config,errorHandler,logger))!==null&&_pluginsManager$invok!==void 0?_pluginsManager$invok:true);});state.nativeDestinations.activeDestinations.value=consentedDestinations;},load:function load(state,externalSrcLoader,errorHandler,logger,externalScriptOnLoad){var integrationsCDNPath=state.lifecycle.integrationsCDNPath.value;var activeDestinations=state.nativeDestinations.activeDestinations.value;activeDestinations.forEach(function(dest){var sdkName=destDisplayNamesToFileNamesMap[dest.displayName];var destSDKIdentifier="".concat(sdkName,"_RS");// this is the name of the object loaded on the window
1659
+ var sdkTypeName=sdkName;if(sdkTypeName&&!isDestinationSDKMounted(destSDKIdentifier,sdkTypeName)){var destSdkURL="".concat(integrationsCDNPath,"/").concat(sdkName,".min.js");externalSrcLoader.loadJSFile({url:destSdkURL,id:dest.userFriendlyId,callback:externalScriptOnLoad!==null&&externalScriptOnLoad!==void 0?externalScriptOnLoad:function(id){if(!id){logger===null||logger===void 0||logger.error(DESTINATION_SDK_LOAD_ERROR(DEVICE_MODE_DESTINATIONS_PLUGIN,dest.userFriendlyId));state.nativeDestinations.failedDestinations.value=[].concat(_toConsumableArray(state.nativeDestinations.failedDestinations.value),[dest]);}else {initializeDestination(dest,state,destSDKIdentifier,sdkTypeName,errorHandler,logger);}},timeout:SCRIPT_LOAD_TIMEOUT_MS});}else if(sdkTypeName){initializeDestination(dest,state,destSDKIdentifier,sdkTypeName,errorHandler,logger);}else {logger===null||logger===void 0||logger.error(DESTINATION_SDK_LOAD_ERROR(DEVICE_MODE_DESTINATIONS_PLUGIN,dest.displayName));}});}}};};
1660
+
1661
+ var DEFAULT_TRANSFORMATION_QUEUE_OPTIONS={minRetryDelay:500,backoffFactor:2,maxAttempts:3};var REQUEST_TIMEOUT_MS$2=10*1000;// 10 seconds
1662
+ var QUEUE_NAME$2='rudder';var DMT_PLUGIN='DeviceModeTransformationPlugin';
1663
+
1664
+ var DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR=function DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR(context,displayName,reason,action){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Event transformation unsuccessful for destination \"").concat(displayName,"\". Reason: ").concat(reason,". ").concat(action,".");};var DMT_REQUEST_FAILED_ERROR=function DMT_REQUEST_FAILED_ERROR(context,displayName,status,action){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"[Destination: ").concat(displayName,"].Transformation request failed with status: ").concat(status,". Retries exhausted. ").concat(action,".");};var DMT_EXCEPTION=function DMT_EXCEPTION(displayName){return "[Destination:".concat(displayName,"].");};var DMT_SERVER_ACCESS_DENIED_WARNING=function DMT_SERVER_ACCESS_DENIED_WARNING(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Transformation server access is denied. The configuration data seems to be out of sync. Sending untransformed event to the destination.");};
1665
+
1666
+ /**
1667
+ * A helper function that will take rudderEvent and generate
1668
+ * a batch payload that will be sent to transformation server
1669
+ *
1670
+ */var createPayload=function createPayload(event,destinationIds,token){var orderNo=Date.now();var payload={metadata:{'Custom-Authorization':token},batch:[{orderNo:orderNo,destinationIds:destinationIds,event:event}]};return payload;};var sendTransformedEventToDestinations=function sendTransformedEventToDestinations(state,pluginsManager,destinationIds,result,status,event,errorHandler,logger){var NATIVE_DEST_EXT_POINT='destinationsEventsQueue.enqueueEventToDestination';var ACTION_TO_SEND_UNTRANSFORMED_EVENT='Sending untransformed event';var ACTION_TO_DROP_EVENT='Dropping the event';var destinations=state.nativeDestinations.initializedDestinations.value.filter(function(d){return d&&destinationIds.includes(d.id);});destinations.forEach(function(dest){try{var eventsToSend=[];switch(status){case 200:{var response=JSON.parse(result);var destTransformedResult=response.transformedBatch.find(function(e){return e.id===dest.id;});destTransformedResult===null||destTransformedResult===void 0||destTransformedResult.payload.forEach(function(tEvent){if(tEvent.status==='200'){eventsToSend.push(tEvent.event);}else {var reason='Unknown';if(tEvent.status==='410'){reason='Transformation is not available';}var action=ACTION_TO_DROP_EVENT;if(dest.propagateEventsUntransformedOnError===true){action=ACTION_TO_SEND_UNTRANSFORMED_EVENT;eventsToSend.push(event);logger===null||logger===void 0||logger.warn(DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR(DMT_PLUGIN,dest.displayName,reason,action));}else {logger===null||logger===void 0||logger.error(DMT_TRANSFORMATION_UNSUCCESSFUL_ERROR(DMT_PLUGIN,dest.displayName,reason,action));}}});break;}// Transformation server access denied
1671
+ case 404:{logger===null||logger===void 0||logger.warn(DMT_SERVER_ACCESS_DENIED_WARNING(DMT_PLUGIN));eventsToSend.push(event);break;}default:{if(dest.propagateEventsUntransformedOnError===true){logger===null||logger===void 0||logger.warn(DMT_REQUEST_FAILED_ERROR(DMT_PLUGIN,dest.displayName,status,ACTION_TO_SEND_UNTRANSFORMED_EVENT));eventsToSend.push(event);}else {logger===null||logger===void 0||logger.error(DMT_REQUEST_FAILED_ERROR(DMT_PLUGIN,dest.displayName,status,ACTION_TO_DROP_EVENT));}break;}}eventsToSend===null||eventsToSend===void 0||eventsToSend.forEach(function(tEvent){if(isNonEmptyObject(tEvent)){pluginsManager.invokeSingle(NATIVE_DEST_EXT_POINT,state,tEvent,dest,errorHandler,logger);}});}catch(e){errorHandler===null||errorHandler===void 0||errorHandler.onError(e,DMT_PLUGIN,DMT_EXCEPTION(dest.displayName));}});};
1672
+
1673
+ var pluginName$a='DeviceModeTransformation';var DeviceModeTransformation=function DeviceModeTransformation(){return {name:pluginName$a,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$a]);},transformEvent:{init:function init(state,pluginsManager,httpClient,storeManager,errorHandler,logger){var writeKey=state.lifecycle.writeKey.value;httpClient.setAuthHeader(writeKey);var eventsQueue=new RetryQueue(// adding write key to the queue name to avoid conflicts
1674
+ "".concat(QUEUE_NAME$2,"_").concat(writeKey),DEFAULT_TRANSFORMATION_QUEUE_OPTIONS,function(item,done,attemptNumber,maxRetryAttempts){var payload=createPayload(item.event,item.destinationIds,item.token);httpClient.getAsyncData({url:"".concat(state.lifecycle.activeDataplaneUrl.value,"/transform"),options:{method:'POST',data:getDMTDeliveryPayload(payload),sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS$2,callback:function callback(result,details){// null means item will not be requeued
1675
+ var queueErrResp=isErrRetryable(details)?details:null;if(!queueErrResp||attemptNumber===maxRetryAttempts){var _details$xhr;sendTransformedEventToDestinations(state,pluginsManager,item.destinationIds,result,details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.status,item.event,errorHandler,logger);}done(queueErrResp,result);}});},storeManager,MEMORY_STORAGE);return eventsQueue;},enqueue:function enqueue(state,eventsQueue,event,destinations){var destinationIds=destinations.map(function(d){return d.id;});eventsQueue.addItem({event:event,destinationIds:destinationIds,token:state.session.authToken.value});}}};};
1676
+
1677
+ var METRICS_PAYLOAD_VERSION='1';
1678
+
1679
+ // Errors from the below scripts are NOT allowed to reach Bugsnag
1680
+ var SDK_FILE_NAME_PREFIXES=function SDK_FILE_NAME_PREFIXES(){return ['rsa'// Prefix for all the SDK scripts including plugins and module federated chunks
1681
+ ];};var DEV_HOSTS=['www.test-host.com','localhost','127.0.0.1','[::1]'];// List of keys to exclude from the metadata
1682
+ // Potential PII or sensitive data
1683
+ var APP_STATE_EXCLUDE_KEYS=['userId','userTraits','groupId','groupTraits','anonymousId','config','instance',// destination instance objects
1684
+ 'eventBuffer',// pre-load event buffer (may contain PII)
1685
+ 'traits'];var REQUEST_TIMEOUT_MS$1=10*1000;// 10 seconds
1686
+ var NOTIFIER_NAME='RudderStack JavaScript SDK Error Notifier';var SDK_GITHUB_URL='https://github.com/rudderlabs/rudder-sdk-js';var SOURCE_NAME='js';
1687
+
1688
+ var getConfigForPayloadCreation=function getConfigForPayloadCreation(err,errorType){switch(errorType){case ErrorType.UNHANDLEDEXCEPTION:{var _ref=err,error=_ref.error;return {component:'unhandledException handler',tolerateNonErrors:true,errorFramesToSkip:1,normalizedError:error||err};}case ErrorType.UNHANDLEDREJECTION:{var _error=err;return {component:'unhandledrejection handler',tolerateNonErrors:false,errorFramesToSkip:1,normalizedError:_error.reason};}case ErrorType.HANDLEDEXCEPTION:default:return {component:'notify()',tolerateNonErrors:true,errorFramesToSkip:2,normalizedError:err};}};var createNewBreadcrumb=function createNewBreadcrumb(message,metaData){return {type:'manual',name:message,timestamp:new Date(),metaData:metaData!==null&&metaData!==void 0?metaData:{}};};var getReleaseStage=function getReleaseStage(){var host=globalThis.location.hostname;return host&&DEV_HOSTS.includes(host)?'development':'production';};var getAppStateForMetadata=function getAppStateForMetadata(state){var stateStr=stringifyWithoutCircular(state,false,APP_STATE_EXCLUDE_KEYS);return stateStr!==null?JSON.parse(stateStr):{};};var getURLWithoutQueryString=function getURLWithoutQueryString(){var url=globalThis.location.href.split('?');return url[0];};var getErrorContext=function getErrorContext(event){var message=event.message;var context=message;// Hack for easily grouping the script load errors
1689
+ // on the dashboard
1690
+ if(message.includes('Error in loading a third-party script')){context='Script load failures';}return context;};var getBugsnagErrorEvent=function getBugsnagErrorEvent(payload,errorState,state){var _state$context$locale,_state$context$userAg,_getAppStateForMetada,_state$source$value$i,_state$source$value;return {notifier:{name:NOTIFIER_NAME,version:state.context.app.value.version,url:SDK_GITHUB_URL},events:[{payloadVersion:'5',exceptions:clone(payload.errors),severity:errorState.severity,unhandled:errorState.unhandled,severityReason:errorState.severityReason,app:{version:state.context.app.value.version,releaseStage:getReleaseStage()},device:{locale:(_state$context$locale=state.context.locale.value)!==null&&_state$context$locale!==void 0?_state$context$locale:undefined,userAgent:(_state$context$userAg=state.context.userAgent.value)!==null&&_state$context$userAg!==void 0?_state$context$userAg:undefined,time:new Date()},request:{url:getURLWithoutQueryString(),clientIp:'[NOT COLLECTED]'},breadcrumbs:clone(state.reporting.breadcrumbs.value),context:getErrorContext(payload.errors[0]),metaData:{sdk:{name:'JS',installType:state.context.app.value.installType},state:(_getAppStateForMetada=getAppStateForMetadata(state))!==null&&_getAppStateForMetada!==void 0?_getAppStateForMetada:{},source:{snippetVersion:globalThis.RudderSnippetVersion}},user:{id:(_state$source$value$i=(_state$source$value=state.source.value)===null||_state$source$value===void 0?void 0:_state$source$value.id)!==null&&_state$source$value$i!==void 0?_state$source$value$i:state.lifecycle.writeKey.value}}]};};var isRudderSDKError=function isRudderSDKError(event){var _event$stacktrace;var errorOrigin=(_event$stacktrace=event.stacktrace)===null||_event$stacktrace===void 0||(_event$stacktrace=_event$stacktrace[0])===null||_event$stacktrace===void 0?void 0:_event$stacktrace.file;if(!errorOrigin||typeof errorOrigin!=='string'){return false;}var srcFileName=errorOrigin.substring(errorOrigin.lastIndexOf('/')+1);var paths=errorOrigin.split('/');// extract the parent folder name from the error origin file path
1691
+ // Ex: parentFolderName will be 'sample' for url: https://example.com/sample/file.min.js
1692
+ var parentFolderName=paths[paths.length-2];return parentFolderName===CDN_INT_DIR||SDK_FILE_NAME_PREFIXES().some(function(prefix){return srcFileName.startsWith(prefix)&&srcFileName.endsWith('.js');});};var getErrorDeliveryPayload=function getErrorDeliveryPayload(payload,state){var data={version:METRICS_PAYLOAD_VERSION,message_id:generateUUID(),source:{name:SOURCE_NAME,sdk_version:state.context.app.value.version,write_key:state.lifecycle.writeKey.value,install_type:state.context.app.value.installType},errors:payload};return stringifyWithoutCircular(data);};
1693
+
1694
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
1695
+
1696
+ function getDefaultExportFromCjs (x) {
1697
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
1698
+ }
1699
+
1700
+ var errorStackParser = {exports: {}};
1701
+
1702
+ var stackframe = {exports: {}};
1703
+
1704
+ var hasRequiredStackframe;function requireStackframe(){if(hasRequiredStackframe)return stackframe.exports;hasRequiredStackframe=1;(function(module,exports){(function(root,factory){/* istanbul ignore next */{module.exports=factory();}})(commonjsGlobal,function(){function _isNumber(n){return !isNaN(parseFloat(n))&&isFinite(n);}function _capitalize(str){return str.charAt(0).toUpperCase()+str.substring(1);}function _getter(p){return function(){return this[p];};}var booleanProps=['isConstructor','isEval','isNative','isToplevel'];var numericProps=['columnNumber','lineNumber'];var stringProps=['fileName','functionName','source'];var arrayProps=['args'];var objectProps=['evalOrigin'];var props=booleanProps.concat(numericProps,stringProps,arrayProps,objectProps);function StackFrame(obj){if(!obj)return;for(var i=0;i<props.length;i++){if(obj[props[i]]!==undefined){this['set'+_capitalize(props[i])](obj[props[i]]);}}}StackFrame.prototype={getArgs:function getArgs(){return this.args;},setArgs:function setArgs(v){if(Object.prototype.toString.call(v)!=='[object Array]'){throw new TypeError('Args must be an Array');}this.args=v;},getEvalOrigin:function getEvalOrigin(){return this.evalOrigin;},setEvalOrigin:function setEvalOrigin(v){if(v instanceof StackFrame){this.evalOrigin=v;}else if(v instanceof Object){this.evalOrigin=new StackFrame(v);}else {throw new TypeError('Eval Origin must be an Object or StackFrame');}},toString:function toString(){var fileName=this.getFileName()||'';var lineNumber=this.getLineNumber()||'';var columnNumber=this.getColumnNumber()||'';var functionName=this.getFunctionName()||'';if(this.getIsEval()){if(fileName){return '[eval] ('+fileName+':'+lineNumber+':'+columnNumber+')';}return '[eval]:'+lineNumber+':'+columnNumber;}if(functionName){return functionName+' ('+fileName+':'+lineNumber+':'+columnNumber+')';}return fileName+':'+lineNumber+':'+columnNumber;}};StackFrame.fromString=function StackFrame$$fromString(str){var argsStartIndex=str.indexOf('(');var argsEndIndex=str.lastIndexOf(')');var functionName=str.substring(0,argsStartIndex);var args=str.substring(argsStartIndex+1,argsEndIndex).split(',');var locationString=str.substring(argsEndIndex+1);if(locationString.indexOf('@')===0){var parts=/@(.+?)(?::(\d+))?(?::(\d+))?$/.exec(locationString,'');var fileName=parts[1];var lineNumber=parts[2];var columnNumber=parts[3];}return new StackFrame({functionName:functionName,args:args||undefined,fileName:fileName,lineNumber:lineNumber||undefined,columnNumber:columnNumber||undefined});};for(var i=0;i<booleanProps.length;i++){StackFrame.prototype['get'+_capitalize(booleanProps[i])]=_getter(booleanProps[i]);StackFrame.prototype['set'+_capitalize(booleanProps[i])]=function(p){return function(v){this[p]=Boolean(v);};}(booleanProps[i]);}for(var j=0;j<numericProps.length;j++){StackFrame.prototype['get'+_capitalize(numericProps[j])]=_getter(numericProps[j]);StackFrame.prototype['set'+_capitalize(numericProps[j])]=function(p){return function(v){if(!_isNumber(v)){throw new TypeError(p+' must be a Number');}this[p]=Number(v);};}(numericProps[j]);}for(var k=0;k<stringProps.length;k++){StackFrame.prototype['get'+_capitalize(stringProps[k])]=_getter(stringProps[k]);StackFrame.prototype['set'+_capitalize(stringProps[k])]=function(p){return function(v){this[p]=String(v);};}(stringProps[k]);}return StackFrame;});})(stackframe);return stackframe.exports;}
1705
+
1706
+ (function(module,exports){(function(root,factory){/* istanbul ignore next */{module.exports=factory(requireStackframe());}})(commonjsGlobal,function ErrorStackParser(StackFrame){var FIREFOX_SAFARI_STACK_REGEXP=/(^|@)\S+:\d+/;var CHROME_IE_STACK_REGEXP=/^\s*at .*(\S+:\d+|\(native\))/m;var SAFARI_NATIVE_CODE_REGEXP=/^(eval@)?(\[native code])?$/;return {/**
1707
+ * Given an Error object, extract the most information from it.
1708
+ *
1709
+ * @param {Error} error object
1710
+ * @return {Array} of StackFrames
1711
+ */parse:function ErrorStackParser$$parse(error){if(typeof error.stacktrace!=='undefined'||typeof error['opera#sourceloc']!=='undefined'){return this.parseOpera(error);}else if(error.stack&&error.stack.match(CHROME_IE_STACK_REGEXP)){return this.parseV8OrIE(error);}else if(error.stack){return this.parseFFOrSafari(error);}else {throw new Error('Cannot parse given Error object');}},// Separate line and column numbers from a string of the form: (URI:Line:Column)
1712
+ extractLocation:function ErrorStackParser$$extractLocation(urlLike){// Fail-fast but return locations like "(native)"
1713
+ if(urlLike.indexOf(':')===-1){return [urlLike];}var regExp=/(.+?)(?::(\d+))?(?::(\d+))?$/;var parts=regExp.exec(urlLike.replace(/[()]/g,''));return [parts[1],parts[2]||undefined,parts[3]||undefined];},parseV8OrIE:function ErrorStackParser$$parseV8OrIE(error){var filtered=error.stack.split('\n').filter(function(line){return !!line.match(CHROME_IE_STACK_REGEXP);},this);return filtered.map(function(line){if(line.indexOf('(eval ')>-1){// Throw away eval information until we implement stacktrace.js/stackframe#8
1714
+ line=line.replace(/eval code/g,'eval').replace(/(\(eval at [^()]*)|(,.*$)/g,'');}var sanitizedLine=line.replace(/^\s+/,'').replace(/\(eval code/g,'(').replace(/^.*?\s+/,'');// capture and preseve the parenthesized location "(/foo/my bar.js:12:87)" in
1715
+ // case it has spaces in it, as the string is split on \s+ later on
1716
+ var location=sanitizedLine.match(/ (\(.+\)$)/);// remove the parenthesized location from the line, if it was matched
1717
+ sanitizedLine=location?sanitizedLine.replace(location[0],''):sanitizedLine;// if a location was matched, pass it to extractLocation() otherwise pass all sanitizedLine
1718
+ // because this line doesn't have function name
1719
+ var locationParts=this.extractLocation(location?location[1]:sanitizedLine);var functionName=location&&sanitizedLine||undefined;var fileName=['eval','<anonymous>'].indexOf(locationParts[0])>-1?undefined:locationParts[0];return new StackFrame({functionName:functionName,fileName:fileName,lineNumber:locationParts[1],columnNumber:locationParts[2],source:line});},this);},parseFFOrSafari:function ErrorStackParser$$parseFFOrSafari(error){var filtered=error.stack.split('\n').filter(function(line){return !line.match(SAFARI_NATIVE_CODE_REGEXP);},this);return filtered.map(function(line){// Throw away eval information until we implement stacktrace.js/stackframe#8
1720
+ if(line.indexOf(' > eval')>-1){line=line.replace(/ line (\d+)(?: > eval line \d+)* > eval:\d+:\d+/g,':$1');}if(line.indexOf('@')===-1&&line.indexOf(':')===-1){// Safari eval frames only have function names and nothing else
1721
+ return new StackFrame({functionName:line});}else {var functionNameRegex=/((.*".+"[^@]*)?[^@]*)(?:@)/;var matches=line.match(functionNameRegex);var functionName=matches&&matches[1]?matches[1]:undefined;var locationParts=this.extractLocation(line.replace(functionNameRegex,''));return new StackFrame({functionName:functionName,fileName:locationParts[0],lineNumber:locationParts[1],columnNumber:locationParts[2],source:line});}},this);},parseOpera:function ErrorStackParser$$parseOpera(e){if(!e.stacktrace||e.message.indexOf('\n')>-1&&e.message.split('\n').length>e.stacktrace.split('\n').length){return this.parseOpera9(e);}else if(!e.stack){return this.parseOpera10(e);}else {return this.parseOpera11(e);}},parseOpera9:function ErrorStackParser$$parseOpera9(e){var lineRE=/Line (\d+).*script (?:in )?(\S+)/i;var lines=e.message.split('\n');var result=[];for(var i=2,len=lines.length;i<len;i+=2){var match=lineRE.exec(lines[i]);if(match){result.push(new StackFrame({fileName:match[2],lineNumber:match[1],source:lines[i]}));}}return result;},parseOpera10:function ErrorStackParser$$parseOpera10(e){var lineRE=/Line (\d+).*script (?:in )?(\S+)(?:: In function (\S+))?$/i;var lines=e.stacktrace.split('\n');var result=[];for(var i=0,len=lines.length;i<len;i+=2){var match=lineRE.exec(lines[i]);if(match){result.push(new StackFrame({functionName:match[3]||undefined,fileName:match[2],lineNumber:match[1],source:lines[i]}));}}return result;},// Opera 10.65+ Error.stack very similar to FF/Safari
1722
+ parseOpera11:function ErrorStackParser$$parseOpera11(error){var filtered=error.stack.split('\n').filter(function(line){return !!line.match(FIREFOX_SAFARI_STACK_REGEXP)&&!line.match(/^Error created at/);},this);return filtered.map(function(line){var tokens=line.split('@');var locationParts=this.extractLocation(tokens.pop());var functionCall=tokens.shift()||'';var functionName=functionCall.replace(/<anonymous function(: (\w+))?>/,'$2').replace(/\([^)]*\)/g,'')||undefined;var argsRaw;if(functionCall.match(/\(([^)]*)\)/)){argsRaw=functionCall.replace(/^[^(]+\(([^)]*)\)$/,'$1');}var args=argsRaw===undefined||argsRaw==='[arguments not available]'?undefined:argsRaw.split(',');return new StackFrame({functionName:functionName,args:args,fileName:locationParts[0],lineNumber:locationParts[1],columnNumber:locationParts[2],source:line});},this);}};});})(errorStackParser);var errorStackParserExports=errorStackParser.exports;var ErrorStackParser = /*@__PURE__*/getDefaultExportFromCjs(errorStackParserExports);
1723
+
1724
+ var hasStack=function hasStack(err){return !!err&&(!!err.stack||!!err.stacktrace||!!err['opera#sourceloc'])&&typeof(err.stack||err.stacktrace||err['opera#sourceloc'])==='string'&&err.stack!=="".concat(err.name,": ").concat(err.message);};var isError=function isError(value){switch(Object.prototype.toString.call(value)){case'[object Error]':case'[object Exception]':case'[object DOMException]':return true;default:return value instanceof Error;}};
1725
+
1726
+ var normaliseFunctionName=function normaliseFunctionName(name){return /^global code$/i.test(name)?'global code':name;};// takes a stacktrace.js style stackframe (https://github.com/stacktracejs/stackframe)
1727
+ // and returns a Bugsnag compatible stackframe (https://docs.bugsnag.com/api/error-reporting/#json-payload)
1728
+ var formatStackframe=function formatStackframe(frame){var f={file:frame.fileName,method:normaliseFunctionName(frame.functionName),lineNumber:frame.lineNumber,columnNumber:frame.columnNumber,code:undefined,inProject:undefined};// Some instances result in no file:
1729
+ // - calling notify() from chrome's terminal results in no file/method.
1730
+ // - non-error exception thrown from global code in FF
1731
+ // This adds one.
1732
+ if(f.lineNumber>-1&&!f.file&&!f.method){f.file='global code';}return f;};var ensureString=function ensureString(str){return typeof str==='string'?str:'';};function createBugsnagError(errorClass,errorMessage,stacktrace){return {errorClass:ensureString(errorClass),message:ensureString(errorMessage),type:'browserjs',stacktrace:stacktrace.reduce(function(accum,frame){var f=formatStackframe(frame);// don't include a stackframe if none of its properties are defined
1733
+ try{if(JSON.stringify(f)==='{}')return accum;return accum.concat(f);}catch(e){return accum;}},[])};}// Helpers
1734
+ var getStacktrace=function getStacktrace(error,errorFramesToSkip){if(hasStack(error))return ErrorStackParser.parse(error).slice(errorFramesToSkip);return [];};var hasNecessaryFields=function hasNecessaryFields(error){return (typeof error.name==='string'||typeof error.errorClass==='string')&&(typeof error.message==='string'||typeof error.errorMessage==='string');};var normaliseError=function normaliseError(maybeError,tolerateNonErrors,component,logger){var error;var internalFrames=0;var createAndLogInputError=function createAndLogInputError(reason){var verb=component==='error cause'?'was':'received';if(logger)logger.warn("".concat(component," ").concat(verb," a non-error: \"").concat(reason,"\""));var err=new Error("".concat(component," ").concat(verb," a non-error. See \"").concat(component,"\" tab for more detail."));err.name='InvalidError';return err;};// In some cases:
1735
+ //
1736
+ // - the promise rejection handler (both in the browser and node)
1737
+ // - the node uncaughtException handler
1738
+ //
1739
+ // We are really limited in what we can do to get a stacktrace. So we use the
1740
+ // tolerateNonErrors option to ensure that the resulting error communicates as
1741
+ // such.
1742
+ if(!tolerateNonErrors){if(isError(maybeError)){error=maybeError;}else {error=createAndLogInputError(_typeof(maybeError));internalFrames+=2;}}else {switch(_typeof(maybeError)){case'string':case'number':case'boolean':error=new Error(String(maybeError));internalFrames+=1;break;case'function':error=createAndLogInputError('function');internalFrames+=2;break;case'object':if(maybeError!==null&&isError(maybeError)){error=maybeError;}else if(maybeError!==null&&hasNecessaryFields(maybeError)){error=new Error(maybeError.message||maybeError.errorMessage);error.name=maybeError.name||maybeError.errorClass;internalFrames+=1;}else {error=createAndLogInputError(maybeError===null?'null':'unsupported object');internalFrames+=2;}break;default:error=createAndLogInputError('nothing');internalFrames+=2;}}if(!hasStack(error)){// in IE10/11 a new Error() doesn't have a stacktrace until you throw it, so try that here
1743
+ try{throw error;}catch(e){if(hasStack(e)){error=e;// if the error only got a stacktrace after we threw it here, we know it
1744
+ // will only have one extra internal frame from this function, regardless
1745
+ // of whether it went through createAndLogInputError() or not
1746
+ internalFrames=1;}}}return [error,internalFrames];};var ErrorFormat=/*#__PURE__*/function(){function ErrorFormat(errorClass,errorMessage,stacktrace){_classCallCheck(this,ErrorFormat);this.errors=[createBugsnagError(errorClass,errorMessage,stacktrace)];}return _createClass(ErrorFormat,null,[{key:"create",value:function create(maybeError,tolerateNonErrors,handledState,component){var errorFramesToSkip=arguments.length>4&&arguments[4]!==undefined?arguments[4]:0;var logger=arguments.length>5?arguments[5]:undefined;var _normaliseError=normaliseError(maybeError,tolerateNonErrors,component,logger),_normaliseError2=_slicedToArray(_normaliseError,2),error=_normaliseError2[0],internalFrames=_normaliseError2[1];var event;try{var stacktrace=getStacktrace(error,// if an error was created/throw in the normaliseError() function, we need to
1747
+ // tell the getStacktrace() function to skip the number of frames we know will
1748
+ // be from our own functions. This is added to the number of frames deep we
1749
+ // were told about
1750
+ internalFrames>0?1+internalFrames+errorFramesToSkip:0);event=new ErrorFormat(error.name,error.message,stacktrace);}catch(e){event=new ErrorFormat(error.name,error.message,[]);}return event;}}]);}();
1751
+
1752
+ var INVALID_SOURCE_CONFIG_ERROR="Invalid source configuration or source id.";
1753
+
1754
+ var pluginName$9='ErrorReporting';var ErrorReporting=function ErrorReporting(){return {name:pluginName$9,deps:[],initialize:function initialize(state){var _state$reporting$brea;state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$9]);state.reporting.isErrorReportingPluginLoaded.value=true;if((_state$reporting$brea=state.reporting.breadcrumbs)!==null&&_state$reporting$brea!==void 0&&_state$reporting$brea.value){state.reporting.breadcrumbs.value=[createNewBreadcrumb('Error Reporting Plugin Loaded')];}},errorReporting:{// This extension point is deprecated
1755
+ // TODO: Remove this in the next major release
1756
+ init:function init(state,pluginEngine,externalSrcLoader,logger,isInvokedFromLatestCore){var _state$source$value,_state$source$value2;if(isInvokedFromLatestCore){return undefined;}if(!((_state$source$value=state.source.value)!==null&&_state$source$value!==void 0&&_state$source$value.config)||!((_state$source$value2=state.source.value)!==null&&_state$source$value2!==void 0&&_state$source$value2.id)){return Promise.reject(new Error(INVALID_SOURCE_CONFIG_ERROR));}return pluginEngine.invokeSingle('errorReportingProvider.init',state,externalSrcLoader,logger);},notify:function notify(pluginEngine,client,error,state,logger,httpClient,errorState){if(httpClient){var _getConfigForPayloadC=getConfigForPayloadCreation(error,errorState===null||errorState===void 0?void 0:errorState.severityReason.type),component=_getConfigForPayloadC.component,tolerateNonErrors=_getConfigForPayloadC.tolerateNonErrors,errorFramesToSkip=_getConfigForPayloadC.errorFramesToSkip,normalizedError=_getConfigForPayloadC.normalizedError;// Generate the error payload
1757
+ var errorPayload=ErrorFormat.create(normalizedError,tolerateNonErrors,errorState,component,errorFramesToSkip,logger);// filter errors
1758
+ if(!isRudderSDKError(errorPayload.errors[0])){return;}// enrich error payload
1759
+ var bugsnagPayload=getBugsnagErrorEvent(errorPayload,errorState,state);// send it to metrics service
1760
+ httpClient===null||httpClient===void 0||httpClient.getAsyncData({url:state.metrics.metricsServiceUrl.value,options:{method:'POST',data:getErrorDeliveryPayload(bugsnagPayload,state),sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS$1,callback:function callback(result,details){// do nothing
1761
+ }});}else {pluginEngine.invokeSingle('errorReportingProvider.notify',client,error,state,logger);}},breadcrumb:function breadcrumb(pluginEngine,client,message,logger,state,metaData){if(state){state.reporting.breadcrumbs.value=[].concat(_toConsumableArray(state.reporting.breadcrumbs.value),[createNewBreadcrumb(message,metaData)]);}else {pluginEngine.invokeSingle('errorReportingProvider.breadcrumb',client,message,logger);}}}};};
1762
+
1763
+ var externallyLoadedSessionStorageKeys={segment:'ajs_anonymous_id'};
1764
+
1765
+ var getSegmentAnonymousId=function getSegmentAnonymousId(getStorageEngine){var anonymousId;/**
1766
+ * First check the local storage for anonymousId
1767
+ * Ref: https://segment.com/docs/connections/sources/catalog/libraries/website/javascript/#identify
1768
+ */var lsEngine=getStorageEngine(LOCAL_STORAGE);if(lsEngine!==null&&lsEngine!==void 0&&lsEngine.isEnabled){anonymousId=lsEngine.getItem(externallyLoadedSessionStorageKeys.segment);}// If anonymousId is not present in local storage and find it in cookies
1769
+ var csEngine=getStorageEngine(COOKIE_STORAGE);if(!anonymousId&&csEngine!==null&&csEngine!==void 0&&csEngine.isEnabled){anonymousId=csEngine.getItem(externallyLoadedSessionStorageKeys.segment);}return anonymousId;};
1770
+
1771
+ var pluginName$8='ExternalAnonymousId';var ExternalAnonymousId=function ExternalAnonymousId(){return {name:pluginName$8,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$8]);},storage:{getAnonymousId:function getAnonymousId(getStorageEngine,options){var _options$autoCapture;var anonymousId;if(options!==null&&options!==void 0&&(_options$autoCapture=options.autoCapture)!==null&&_options$autoCapture!==void 0&&_options$autoCapture.enabled&&options.autoCapture.source){var source=options.autoCapture.source.toLowerCase();if(!Object.keys(externallyLoadedSessionStorageKeys).includes(source)){return anonymousId;}// eslint-disable-next-line sonarjs/no-small-switch
1772
+ switch(source){case'segment':anonymousId=getSegmentAnonymousId(getStorageEngine);break;}}return anonymousId;}}};};
1773
+
1774
+ var AMP_LINKER_ANONYMOUS_ID_KEY='rs_amp_id';
1775
+
1776
+ /* eslint-disable no-bitwise */ /**
1777
+ * generate crc table
1778
+ *
1779
+ * @params none
1780
+ * @returns array of CRC table
1781
+ */var makeCRCTable=function makeCRCTable(){var crcTable=[];var c;for(var n=0;n<256;n++){c=n;for(var k=0;k<8;k++){c=c&1?0xedb88320^c>>>1:c>>>1;}crcTable[n]=c;}return crcTable;};/**
1782
+ * This is utility function for crc32 algorithm
1783
+ *
1784
+ * @param {string} str
1785
+ * @returns {number} crc32
1786
+ */var crc32=function crc32(str){var crcTable=makeCRCTable();var crc=0^-1;for(var i=0;i<str.length;i++){// eslint-disable-next-line @typescript-eslint/ban-ts-comment
1787
+ // @ts-ignore
1788
+ crc=crc>>>8^crcTable[(crc^str.charCodeAt(i))&0xff];}return (crc^-1)>>>0;};
1789
+
1790
+ /**
1791
+ * An interface to fetch user device details.
1792
+ */var USER_INTERFACE={/**
1793
+ * @returns {string} user language
1794
+ */getUserLanguage:function getUserLanguage(){var _navigator;return (_navigator=navigator)===null||_navigator===void 0?void 0:_navigator.language;},/**
1795
+ * @returns {string} userAgent
1796
+ */getUserAgent:function getUserAgent(){var _navigator2;return (_navigator2=navigator)===null||_navigator2===void 0?void 0:_navigator2.userAgent;}};
1797
+
1798
+ /**
1799
+ * This is utility function for decoding from base 64 to utf8
1800
+ *
1801
+ * @param {string} str base64
1802
+ *
1803
+ * @returns {string} utf8
1804
+ */var b64DecodeUnicode=function b64DecodeUnicode(str){return(// Going backwards: from bytestream, to percent-encoding, to original string.
1805
+ decodeURIComponent(globalThis.atob(str).split('').map(function(c){var percentEncodingChar="00".concat(c.charCodeAt(0).toString(16));return "%".concat(percentEncodingChar.slice(-2));}).join('')));};/**
1806
+ * This is utility function for decoding from base 64 to utf8
1807
+ *
1808
+ * @param {string} data
1809
+ *
1810
+ * @return {string}
1811
+ */var decode=function decode(){var data=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'';var decodedData=data.endsWith('..')?data.substring(0,data.length-2):data;return b64DecodeUnicode(decodedData);};
1812
+
1813
+ var KEY_VALIDATOR=/^[\w.-]+$/;var CHECKSUM_OFFSET_MAX_MIN=1;var VALID_VERSION=1;var DELIMITER='*';/**
1814
+ * Parse the linker param value to version checksum and serializedParams
1815
+ *
1816
+ * @param {string} value
1817
+ *
1818
+ * @return {?Object}
1819
+ */var parseLinkerParamValue=function parseLinkerParamValue(value){var parts=value.split(DELIMITER);var isEven=parts.length%2===0;if(parts.length<4||!isEven){// Format <version>*<checksum>*<key1>*<value1>
1820
+ // Note: linker makes sure there's at least one pair of non empty key value
1821
+ // Make sure there is at least three delimiters.
1822
+ return null;}var version=Number(parts.shift());if(version!==VALID_VERSION){return null;}var checksum=parts.shift();var serializedIds=parts.join(DELIMITER);return {checksum:checksum!==null&&checksum!==void 0?checksum:'',serializedIds:serializedIds};};/**
1823
+ * Deserialize the serializedIds and return keyValue pairs.
1824
+ *
1825
+ * @param {string} serializedIds
1826
+ *
1827
+ * @return {!Object<string, string>}
1828
+ */var deserialize=function deserialize(serializedIds){if(!serializedIds){return {};}var keyValuePairs={};var params=serializedIds.split(DELIMITER);for(var i=0;i<params.length;i+=2){var key=params[i];var valid=KEY_VALIDATOR.test(key);if(valid){keyValuePairs[key]=decode(params[i+1]);}}return keyValuePairs;};/**
1829
+ * Generates a semi-unique value for page visitor.
1830
+ *
1831
+ * @return {string}
1832
+ */var getFingerprint=function getFingerprint(userAgent,language){var date=new Date();var timezone=date.getTimezoneOffset();return [userAgent,timezone,language].join(DELIMITER);};/**
1833
+ * Rounded time used to check if t2 - t1 is within our time tolerance.
1834
+ * Timestamp in minutes, floored.
1835
+ *
1836
+ * @return {number}
1837
+ */var getMinSinceEpoch=function getMinSinceEpoch(){return Math.floor(Date.now()/60000);};/**
1838
+ * Create a unique checksum hashing the fingerprint and a few other values.
1839
+ *
1840
+ * @param {string} serializedIds
1841
+ * @param {number=} optOffsetMin
1842
+ * @param {string} userAgent
1843
+ * @param {string} language
1844
+ *
1845
+ * @return {string}
1846
+ */var getCheckSum=function getCheckSum(serializedIds,optOffsetMin,userAgent,language){var fingerprint=getFingerprint(userAgent,language);var offset=optOffsetMin||0;var timestamp=getMinSinceEpoch()-offset;var crc=crc32([fingerprint,timestamp,serializedIds].join(DELIMITER));// Encoded to base36 for fewer bytes.
1847
+ return crc.toString(36);};/**
1848
+ * Check if the checksum is valid with time offset tolerance.
1849
+ *
1850
+ * @param {string} serializedIds
1851
+ * @param {string} checksum
1852
+ *
1853
+ * @return {boolean}
1854
+ */var isCheckSumValid=function isCheckSumValid(serializedIds,checksum){var userAgent=USER_INTERFACE.getUserAgent();var language=USER_INTERFACE.getUserLanguage();for(var i=0;i<=CHECKSUM_OFFSET_MAX_MIN;i+=1){var calculateCheckSum=getCheckSum(serializedIds,i,userAgent,language);if(calculateCheckSum===checksum){return true;}}return false;};/**
1855
+ * AMP Linker Parser (works for Rudder, GA or any other linker created by following Google's linker standard.)
1856
+ *
1857
+ * @param {string} value
1858
+ *
1859
+ * @return {?Object<string, string>}
1860
+ */var parseLinker=function parseLinker(value){var linkerObj=parseLinkerParamValue(value);if(!linkerObj){return null;}var checksum=linkerObj.checksum,serializedIds=linkerObj.serializedIds;if(!serializedIds||!checksum||!isCheckSumValid(serializedIds,checksum)){return null;}return deserialize(serializedIds);};
1861
+
1862
+ var pluginName$7='GoogleLinker';var GoogleLinker=function GoogleLinker(){return {name:pluginName$7,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$7]);},userSession:{anonymousIdGoogleLinker:function anonymousIdGoogleLinker(rudderAmpLinkerParam){if(!rudderAmpLinkerParam){return null;}var parsedAnonymousIdObj=rudderAmpLinkerParam?parseLinker(rudderAmpLinkerParam):null;return parsedAnonymousIdObj?parsedAnonymousIdObj[AMP_LINKER_ANONYMOUS_ID_KEY]:null;}}};};
1863
+
1864
+ var KETCH_CONSENT_COOKIE_READ_ERROR=function KETCH_CONSENT_COOKIE_READ_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to read the consent cookie.");};var KETCH_CONSENT_COOKIE_PARSE_ERROR=function KETCH_CONSENT_COOKIE_PARSE_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to parse the consent cookie.");};var DESTINATION_CONSENT_STATUS_ERROR$1="Failed to determine the consent status for the destination. Please check the destination configuration and try again.";
1865
+
1866
+ var KETCH_CONSENT_MANAGER_PLUGIN='KetchConsentManagerPlugin';var KETCH_CONSENT_COOKIE_NAME_V1='_ketch_consent_v1_';
1867
+
1868
+ /**
1869
+ * Gets the consent data from the Ketch's consent cookie
1870
+ * @param storeManager Store manager instance
1871
+ * @param logger Logger instance
1872
+ * @returns Consent data from the consent cookie
1873
+ */var getKetchConsentData=function getKetchConsentData(storeManager,logger){var rawConsentCookieData=null;try{// Create a data store instance to read the consent cookie
1874
+ var dataStore=storeManager===null||storeManager===void 0?void 0:storeManager.setStore({id:KETCH_CONSENT_MANAGER_PLUGIN,name:KETCH_CONSENT_MANAGER_PLUGIN,type:COOKIE_STORAGE});rawConsentCookieData=dataStore===null||dataStore===void 0?void 0:dataStore.engine.getItem(KETCH_CONSENT_COOKIE_NAME_V1);}catch(err){logger===null||logger===void 0||logger.error(KETCH_CONSENT_COOKIE_READ_ERROR(KETCH_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(isNullOrUndefined(rawConsentCookieData)){return undefined;}// Decode and parse the cookie data to JSON
1875
+ var consentCookieData;try{consentCookieData=JSON.parse(fromBase64(rawConsentCookieData));}catch(err){logger===null||logger===void 0||logger.error(KETCH_CONSENT_COOKIE_PARSE_ERROR(KETCH_CONSENT_MANAGER_PLUGIN),err);return undefined;}if(!consentCookieData){return undefined;}// Convert the cookie data to consent data
1876
+ var consentPurposes={};Object.entries(consentCookieData).forEach(function(pEntry){var purposeCode=pEntry[0];var purposeValue=pEntry[1];consentPurposes[purposeCode]=(purposeValue===null||purposeValue===void 0?void 0:purposeValue.status)==='granted';});return consentPurposes;};/**
1877
+ * Gets the consent data in the format expected by the application state
1878
+ * @param ketchConsentData Consent data derived from the consent cookie
1879
+ * @returns Consent data
1880
+ */var getConsentData=function getConsentData(ketchConsentData){var allowedConsentIds=[];var deniedConsentIds=[];if(ketchConsentData){Object.entries(ketchConsentData).forEach(function(e){var purposeCode=e[0];var isConsented=e[1];if(isConsented){allowedConsentIds.push(purposeCode);}else {deniedConsentIds.push(purposeCode);}});}return {allowedConsentIds:allowedConsentIds,deniedConsentIds:deniedConsentIds};};var updateConsentStateFromData=function updateConsentStateFromData(state,ketchConsentData){var consentData=getConsentData(ketchConsentData);state.consents.initialized.value=isDefined(ketchConsentData);state.consents.data.value=consentData;};
1881
+
1882
+ var pluginName$6='KetchConsentManager';var KetchConsentManager=function KetchConsentManager(){return {name:pluginName$6,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$6]);},consentManager:{init:function init(state,logger){// getKetchUserConsentedPurposes returns current ketch opted-in purposes
1883
+ // This will be helpful for debugging
1884
+ globalThis.getKetchUserConsentedPurposes=function(){var _state$consents$data$;return (_state$consents$data$=state.consents.data.value.allowedConsentIds)===null||_state$consents$data$===void 0?void 0:_state$consents$data$.slice();};// getKetchUserDeniedPurposes returns current ketch opted-out purposes
1885
+ // This will be helpful for debugging
1886
+ globalThis.getKetchUserDeniedPurposes=function(){var _state$consents$data$2;return (_state$consents$data$2=state.consents.data.value.deniedConsentIds)===null||_state$consents$data$2===void 0?void 0:_state$consents$data$2.slice();};// updateKetchConsent callback function to update current consent purpose state
1887
+ // this will be called from ketch rudderstack plugin
1888
+ globalThis.updateKetchConsent=function(ketchConsentData){updateConsentStateFromData(state,ketchConsentData);};},updateConsentsInfo:function updateConsentsInfo(state,storeManager,logger){// retrieve consent data and update the state
1889
+ var ketchConsentData;if(!isUndefined(globalThis.ketchConsent)){ketchConsentData=globalThis.ketchConsent;}else {ketchConsentData=getKetchConsentData(storeManager,logger);}updateConsentStateFromData(state,ketchConsentData);},isDestinationConsented:function isDestinationConsented(state,destConfig,errorHandler,logger){if(!state.consents.initialized.value){return true;}var allowedConsentIds=state.consents.data.value.allowedConsentIds;try{var ketchConsentPurposes=destConfig.ketchConsentPurposes,consentManagement=destConfig.consentManagement;var matchPredicate=function matchPredicate(consent){return allowedConsentIds.includes(consent);};// Generic consent management
1890
+ if(consentManagement){var _consentManagement$fi;// Get the corresponding consents for the destination
1891
+ var cmpConsents=(_consentManagement$fi=consentManagement.find(function(c){return c.provider===state.consents.provider.value;}))===null||_consentManagement$fi===void 0?void 0:_consentManagement$fi.consents;// If there are no consents configured for the destination for the current provider, events should be sent.
1892
+ if(!cmpConsents){return true;}var configuredConsents=cmpConsents.map(function(c){return c.consent.trim();}).filter(function(n){return n;});// match the configured consents with user provided consents as per
1893
+ // the configured resolution strategy
1894
+ switch(state.consents.resolutionStrategy.value){case'or':return configuredConsents.some(matchPredicate)||configuredConsents.length===0;case'and':default:return configuredConsents.every(matchPredicate);}// Legacy cookie consent management
1895
+ // TODO: To be removed once the source config API is updated to support generic consent management
1896
+ }else if(ketchConsentPurposes){var _configuredConsents=ketchConsentPurposes.map(function(p){return p.purpose.trim();}).filter(function(n){return n;});// Check if any of the destination's mapped ketch purposes are consented by the user in the browser.
1897
+ return _configuredConsents.some(matchPredicate)||_configuredConsents.length===0;}// If there are no consents configured for the destination for the current provider, events should be sent.
1898
+ return true;}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,KETCH_CONSENT_MANAGER_PLUGIN,DESTINATION_CONSENT_STATUS_ERROR$1);return true;}}}};};
1899
+
1900
+ var DEFAULT_QUEUE_OPTIONS={maxItems:100};var QUEUE_NAME$1='rudder_destinations_events';var NATIVE_DESTINATION_QUEUE_PLUGIN='NativeDestinationQueuePlugin';
1901
+
1902
+ var DESTINATION_EVENT_FILTERING_WARNING=function DESTINATION_EVENT_FILTERING_WARNING(context,eventName,destUserFriendlyId){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The \"").concat(eventName,"\" track event has been filtered for the \"").concat(destUserFriendlyId,"\" destination.");};var DESTINATION_EVENT_FORWARDING_ERROR=function DESTINATION_EVENT_FORWARDING_ERROR(destUserFriendlyId){return "Failed to forward event to destination \"".concat(destUserFriendlyId,"\".");};
1903
+
1904
+ var getNormalizedQueueOptions$1=function getNormalizedQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_QUEUE_OPTIONS,queueOpts);};var isValidEventName=function isValidEventName(eventName){return eventName&&typeof eventName==='string';};var isEventDenyListed=function isEventDenyListed(eventType,eventName,dest){if(eventType!=='track'){return false;}var _dest$config=dest.config,blacklistedEvents=_dest$config.blacklistedEvents,whitelistedEvents=_dest$config.whitelistedEvents,eventFilteringOption=_dest$config.eventFilteringOption;switch(eventFilteringOption){// Blacklist is chosen for filtering events
1905
+ case'blacklistedEvents':{if(!isValidEventName(eventName)){return false;}var trimmedEventName=eventName.trim();if(Array.isArray(blacklistedEvents)){return blacklistedEvents.some(function(eventObj){return eventObj.eventName.trim()===trimmedEventName;});}return false;}// Whitelist is chosen for filtering events
1906
+ case'whitelistedEvents':{if(!isValidEventName(eventName)){return true;}var _trimmedEventName=eventName.trim();if(Array.isArray(whitelistedEvents)){return !whitelistedEvents.some(function(eventObj){return eventObj.eventName.trim()===_trimmedEventName;});}return true;}case'disable':default:return false;}};var sendEventToDestination=function sendEventToDestination(item,dest,errorHandler,logger){var methodName=item.type.toString();try{var _dest$instance,_dest$instance$method;// Destinations expect the event to be wrapped under the `message` key
1907
+ // This will remain until we update the destinations to accept the event directly
1908
+ (_dest$instance=dest.instance)===null||_dest$instance===void 0||(_dest$instance$method=_dest$instance[methodName])===null||_dest$instance$method===void 0||_dest$instance$method.call(_dest$instance,{message:item});}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,NATIVE_DESTINATION_QUEUE_PLUGIN,DESTINATION_EVENT_FORWARDING_ERROR(dest.userFriendlyId));}};
1909
+
1910
+ var pluginName$5='NativeDestinationQueue';var NativeDestinationQueue=function NativeDestinationQueue(){return {name:pluginName$5,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$5]);},destinationsEventsQueue:{/**
1911
+ * Initialize the queue for delivery to destinations
1912
+ * @param state Application state
1913
+ * @param pluginsManager PluginsManager instance
1914
+ * @param storeManager StoreManager instance
1915
+ * @param errorHandler Error handler instance
1916
+ * @param logger Logger instance
1917
+ * @returns IQueue instance
1918
+ */init:function init(state,pluginsManager,storeManager,dmtQueue,errorHandler,logger){var finalQOpts=getNormalizedQueueOptions$1(state.loadOptions.value.destinationsQueueOptions);var writeKey=state.lifecycle.writeKey.value;var eventsQueue=new RetryQueue(// adding write key to the queue name to avoid conflicts
1919
+ "".concat(QUEUE_NAME$1,"_").concat(writeKey),finalQOpts,function(rudderEvent,done){var destinationsToSend=filterDestinations(rudderEvent.integrations,state.nativeDestinations.initializedDestinations.value);// list of destinations which are enable for DMT
1920
+ var destWithTransformationEnabled=[];var clonedRudderEvent=clone(rudderEvent);destinationsToSend.forEach(function(dest){try{var sendEvent=!isEventDenyListed(clonedRudderEvent.type,clonedRudderEvent.event,dest);if(!sendEvent){logger===null||logger===void 0||logger.warn(DESTINATION_EVENT_FILTERING_WARNING(NATIVE_DESTINATION_QUEUE_PLUGIN,clonedRudderEvent.event,dest.userFriendlyId));return;}if(dest.shouldApplyDeviceModeTransformation){destWithTransformationEnabled.push(dest);}else {sendEventToDestination(clonedRudderEvent,dest,errorHandler,logger);}}catch(e){errorHandler===null||errorHandler===void 0||errorHandler.onError(e,NATIVE_DESTINATION_QUEUE_PLUGIN);}});if(destWithTransformationEnabled.length>0){pluginsManager.invokeSingle('transformEvent.enqueue',state,dmtQueue,clonedRudderEvent,destWithTransformationEnabled,errorHandler,logger);}// Mark success always
1921
+ done(null);},storeManager,MEMORY_STORAGE);// TODO: This seems to not work as expected. Need to investigate
1922
+ // effect(() => {
1923
+ // if (state.nativeDestinations.clientDestinationsReady.value === true) {
1924
+ // eventsQueue.start();
1925
+ // }
1926
+ // });
1927
+ return eventsQueue;},/**
1928
+ * Add event to the queue for delivery to destinations
1929
+ * @param state Application state
1930
+ * @param eventsQueue IQueue instance
1931
+ * @param event RudderEvent object
1932
+ * @param errorHandler Error handler instance
1933
+ * @param logger Logger instance
1934
+ * @returns none
1935
+ */enqueue:function enqueue(state,eventsQueue,event,errorHandler,logger){eventsQueue.addItem(event);},/**
1936
+ * This extension point is used to directly send the transformed event to the destination
1937
+ * @param state Application state
1938
+ * @param event RudderEvent Object
1939
+ * @param destination Destination Object
1940
+ * @param errorHandler Error handler instance
1941
+ * @param logger Logger instance
1942
+ */enqueueEventToDestination:function enqueueEventToDestination(state,event,destination,errorHandler,logger){sendEventToDestination(event,destination,errorHandler);}}};};
1943
+
1944
+ var ONETRUST_ACCESS_ERROR=function ONETRUST_ACCESS_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to access OneTrust SDK resources. Please ensure that the OneTrust SDK is loaded successfully before RudderStack SDK.");};var DESTINATION_CONSENT_STATUS_ERROR="Failed to determine the consent status for the destination. Please check the destination configuration and try again.";
1945
+
1946
+ var ONETRUST_CONSENT_MANAGER_PLUGIN='OneTrustConsentManagerPlugin';
1947
+
1948
+ var pluginName$4='OneTrustConsentManager';var OneTrustConsentManager=function OneTrustConsentManager(){return {name:pluginName$4,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$4]);},consentManager:{init:function init(state,logger){// Nothing to initialize
1949
+ },updateConsentsInfo:function updateConsentsInfo(state,storeManager,logger){if(!globalThis.OneTrust||!globalThis.OnetrustActiveGroups){logger===null||logger===void 0||logger.error(ONETRUST_ACCESS_ERROR(ONETRUST_CONSENT_MANAGER_PLUGIN));state.consents.initialized.value=false;return;}// Get the groups (cookie categorization), user has created in OneTrust account.
1950
+ var oneTrustAllGroupsInfo=globalThis.OneTrust.GetDomainData().Groups;// OneTrustConsentManager SDK populates a data layer object OnetrustActiveGroups with
1951
+ // the cookie categories Ids that the user has consented to.
1952
+ // Eg: ',C0001,C0003,'
1953
+ // We split it and save it as an array.
1954
+ var allowedConsentIds=globalThis.OnetrustActiveGroups.split(',').filter(function(n){return n;});var deniedConsentIds=[];oneTrustAllGroupsInfo.forEach(function(_ref){var CustomGroupId=_ref.CustomGroupId;if(!allowedConsentIds.includes(CustomGroupId)){deniedConsentIds.push(CustomGroupId);}});state.consents.initialized.value=true;state.consents.data.value={allowedConsentIds:allowedConsentIds,deniedConsentIds:deniedConsentIds};},isDestinationConsented:function isDestinationConsented(state,destConfig,errorHandler,logger){if(!state.consents.initialized.value){return true;}var allowedConsentIds=state.consents.data.value.allowedConsentIds;try{// mapping of the destination with the consent group name
1955
+ var oneTrustCookieCategories=destConfig.oneTrustCookieCategories,consentManagement=destConfig.consentManagement;var matchPredicate=function matchPredicate(consent){return allowedConsentIds.includes(consent);};// Generic consent management
1956
+ if(consentManagement){var _consentManagement$fi;// Get the corresponding consents for the destination
1957
+ var cmpConsents=(_consentManagement$fi=consentManagement.find(function(c){return c.provider===state.consents.provider.value;}))===null||_consentManagement$fi===void 0?void 0:_consentManagement$fi.consents;// If there are no consents configured for the destination for the current provider, events should be sent.
1958
+ if(!cmpConsents){return true;}var configuredConsents=cmpConsents.map(function(c){return c.consent.trim();}).filter(function(n){return n;});// match the configured consents with user provided consents as per
1959
+ // the configured resolution strategy
1960
+ switch(state.consents.resolutionStrategy.value){case'or':return configuredConsents.some(matchPredicate)||configuredConsents.length===0;case'and':default:return configuredConsents.every(matchPredicate);}// Legacy cookie consent management
1961
+ // TODO: To be removed once the source config API is updated to support generic consent management
1962
+ }else if(oneTrustCookieCategories){// Change the structure of oneTrustConsentGroup as an array and filter values if empty string
1963
+ // Eg:
1964
+ // ["Performance Cookies", "Functional Cookies"]
1965
+ var _configuredConsents=oneTrustCookieCategories.map(function(c){return c.oneTrustCookieCategory.trim();}).filter(function(n){return n;});// Check if all the destination's mapped cookie categories are consented by the user in the browser.
1966
+ return _configuredConsents.every(matchPredicate);}// If there are no consents configured for the destination for the current provider, events should be sent.
1967
+ return true;}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,ONETRUST_CONSENT_MANAGER_PLUGIN,DESTINATION_CONSENT_STATUS_ERROR);return true;}}}};};
1968
+
1969
+ var pluginName$3='StorageEncryption';var StorageEncryption=function StorageEncryption(){return {name:pluginName$3,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$3]);},storage:{encrypt:function encrypt(value){return encryptBrowser(value);},decrypt:function decrypt(value){return decryptBrowser(value);}}};};
1970
+
1971
+ var _ref,_ref2,_ref3,_ref4,_ref5;/* eslint-disable no-use-before-define */var crypto$1=((_ref=typeof globalThis!='undefined'?globalThis:void 0)===null||_ref===void 0?void 0:_ref.crypto)||((_ref2=typeof global!='undefined'?global:void 0)===null||_ref2===void 0?void 0:_ref2.crypto)||((_ref3=typeof window!='undefined'?window:void 0)===null||_ref3===void 0?void 0:_ref3.crypto)||((_ref4=typeof self!='undefined'?self:void 0)===null||_ref4===void 0?void 0:_ref4.crypto)||((_ref5=typeof frames!='undefined'?frames:void 0)===null||_ref5===void 0||(_ref5=_ref5[0])===null||_ref5===void 0?void 0:_ref5.crypto);var randomWordArray;if(crypto$1){randomWordArray=function randomWordArray(nBytes){var words=[];for(var i=0,rcache;i<nBytes;i+=4){words.push(crypto$1.getRandomValues(new Uint32Array(1))[0]);}return new WordArray(words,nBytes);};}else {// Because there is no global crypto property in this context, cryptographically unsafe Math.random() is used.
1972
+ randomWordArray=function randomWordArray(nBytes){var words=[];var r=function r(m_w){var _m_w=m_w;var _m_z=0x3ade68b1;var mask=0xffffffff;return function(){_m_z=0x9069*(_m_z&0xFFFF)+(_m_z>>0x10)&mask;_m_w=0x4650*(_m_w&0xFFFF)+(_m_w>>0x10)&mask;var result=(_m_z<<0x10)+_m_w&mask;result/=0x100000000;result+=0.5;return result*(Math.random()>0.5?1:-1);};};for(var i=0,rcache;i<nBytes;i+=4){var _r=r((rcache||Math.random())*0x100000000);rcache=_r()*0x3ade67b7;words.push(_r()*0x100000000|0);}return new WordArray(words,nBytes);};}/**
1973
+ * Base class for inheritance.
1974
+ */var Base=/*#__PURE__*/function(){function Base(){_classCallCheck(this,Base);}return _createClass(Base,[{key:"mixIn",value:/**
1975
+ * Copies properties into this object.
1976
+ *
1977
+ * @param {Object} properties The properties to mix in.
1978
+ *
1979
+ * @example
1980
+ *
1981
+ * MyType.mixIn({
1982
+ * field: 'value'
1983
+ * });
1984
+ */function mixIn(properties){return Object.assign(this,properties);}/**
1985
+ * Creates a copy of this object.
1986
+ *
1987
+ * @return {Object} The clone.
1988
+ *
1989
+ * @example
1990
+ *
1991
+ * var clone = instance.clone();
1992
+ */},{key:"clone",value:function clone(){var clone=new this.constructor();Object.assign(clone,this);return clone;}}],[{key:"create",value:/**
1993
+ * Extends this object and runs the init method.
1994
+ * Arguments to create() will be passed to init().
1995
+ *
1996
+ * @return {Object} The new object.
1997
+ *
1998
+ * @static
1999
+ *
2000
+ * @example
2001
+ *
2002
+ * var instance = MyType.create();
2003
+ */function create(){for(var _len=arguments.length,args=new Array(_len),_key2=0;_key2<_len;_key2++){args[_key2]=arguments[_key2];}return _construct(this,args);}}]);}();/**
2004
+ * An array of 32-bit words.
2005
+ *
2006
+ * @property {Array} words The array of 32-bit words.
2007
+ * @property {number} sigBytes The number of significant bytes in this word array.
2008
+ */var WordArray=/*#__PURE__*/function(_Base){/**
2009
+ * Initializes a newly created word array.
2010
+ *
2011
+ * @param {Array} words (Optional) An array of 32-bit words.
2012
+ * @param {number} sigBytes (Optional) The number of significant bytes in the words.
2013
+ *
2014
+ * @example
2015
+ *
2016
+ * var wordArray = CryptoJS.lib.WordArray.create();
2017
+ * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
2018
+ * var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
2019
+ */function WordArray(){var _this;var words=arguments.length>0&&arguments[0]!==undefined?arguments[0]:[];var sigBytes=arguments.length>1&&arguments[1]!==undefined?arguments[1]:words.length*4;_classCallCheck(this,WordArray);_this=_callSuper(this,WordArray);var typedArray=words;// Convert buffers to uint8
2020
+ if(typedArray instanceof ArrayBuffer){typedArray=new Uint8Array(typedArray);}// Convert other array views to uint8
2021
+ if(typedArray instanceof Int8Array||typedArray instanceof Uint8ClampedArray||typedArray instanceof Int16Array||typedArray instanceof Uint16Array||typedArray instanceof Int32Array||typedArray instanceof Uint32Array||typedArray instanceof Float32Array||typedArray instanceof Float64Array){typedArray=new Uint8Array(typedArray.buffer,typedArray.byteOffset,typedArray.byteLength);}// Handle Uint8Array
2022
+ if(typedArray instanceof Uint8Array){// Shortcut
2023
+ var typedArrayByteLength=typedArray.byteLength;// Extract bytes
2024
+ var _words=[];for(var i=0;i<typedArrayByteLength;i+=1){_words[i>>>2]|=typedArray[i]<<24-i%4*8;}// Initialize this word array
2025
+ _this.words=_words;_this.sigBytes=typedArrayByteLength;}else {// Else call normal init
2026
+ _this.words=words;_this.sigBytes=sigBytes;}return _this;}/**
2027
+ * Creates a word array filled with random bytes.
2028
+ *
2029
+ * @param {number} nBytes The number of random bytes to generate.
2030
+ *
2031
+ * @return {WordArray} The random word array.
2032
+ *
2033
+ * @static
2034
+ *
2035
+ * @example
2036
+ *
2037
+ * var wordArray = CryptoJS.lib.WordArray.random(16);
2038
+ */_inherits(WordArray,_Base);return _createClass(WordArray,[{key:"toString",value:/**
2039
+ * Converts this word array to a string.
2040
+ *
2041
+ * @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
2042
+ *
2043
+ * @return {string} The stringified word array.
2044
+ *
2045
+ * @example
2046
+ *
2047
+ * var string = wordArray + '';
2048
+ * var string = wordArray.toString();
2049
+ * var string = wordArray.toString(CryptoJS.enc.Utf8);
2050
+ */function toString(){var encoder=arguments.length>0&&arguments[0]!==undefined?arguments[0]:Hex;return encoder.stringify(this);}/**
2051
+ * Concatenates a word array to this word array.
2052
+ *
2053
+ * @param {WordArray} wordArray The word array to append.
2054
+ *
2055
+ * @return {WordArray} This word array.
2056
+ *
2057
+ * @example
2058
+ *
2059
+ * wordArray1.concat(wordArray2);
2060
+ */},{key:"concat",value:function concat(wordArray){// Shortcuts
2061
+ var thisWords=this.words;var thatWords=wordArray.words;var thisSigBytes=this.sigBytes;var thatSigBytes=wordArray.sigBytes;// Clamp excess bits
2062
+ this.clamp();// Concat
2063
+ if(thisSigBytes%4){// Copy one byte at a time
2064
+ for(var i=0;i<thatSigBytes;i+=1){var thatByte=thatWords[i>>>2]>>>24-i%4*8&0xff;thisWords[thisSigBytes+i>>>2]|=thatByte<<24-(thisSigBytes+i)%4*8;}}else {// Copy one word at a time
2065
+ for(var _i=0;_i<thatSigBytes;_i+=4){thisWords[thisSigBytes+_i>>>2]=thatWords[_i>>>2];}}this.sigBytes+=thatSigBytes;// Chainable
2066
+ return this;}/**
2067
+ * Removes insignificant bits.
2068
+ *
2069
+ * @example
2070
+ *
2071
+ * wordArray.clamp();
2072
+ */},{key:"clamp",value:function clamp(){// Shortcuts
2073
+ var words=this.words,sigBytes=this.sigBytes;// Clamp
2074
+ words[sigBytes>>>2]&=0xffffffff<<32-sigBytes%4*8;words.length=Math.ceil(sigBytes/4);}/**
2075
+ * Creates a copy of this word array.
2076
+ *
2077
+ * @return {WordArray} The clone.
2078
+ *
2079
+ * @example
2080
+ *
2081
+ * var clone = wordArray.clone();
2082
+ */},{key:"clone",value:function clone(){var clone=_get(_getPrototypeOf(WordArray.prototype),"clone",this).call(this);clone.words=this.words.slice(0);return clone;}}]);}(Base);/**
2083
+ * Hex encoding strategy.
2084
+ */_defineProperty(WordArray,"random",randomWordArray);var Hex={/**
2085
+ * Converts a word array to a hex string.
2086
+ *
2087
+ * @param {WordArray} wordArray The word array.
2088
+ *
2089
+ * @return {string} The hex string.
2090
+ *
2091
+ * @static
2092
+ *
2093
+ * @example
2094
+ *
2095
+ * var hexString = CryptoJS.enc.Hex.stringify(wordArray);
2096
+ */stringify:function stringify(wordArray){// Shortcuts
2097
+ var words=wordArray.words,sigBytes=wordArray.sigBytes;// Convert
2098
+ var hexChars=[];for(var i=0;i<sigBytes;i+=1){var bite=words[i>>>2]>>>24-i%4*8&0xff;hexChars.push((bite>>>4).toString(16));hexChars.push((bite&0x0f).toString(16));}return hexChars.join('');},/**
2099
+ * Converts a hex string to a word array.
2100
+ *
2101
+ * @param {string} hexStr The hex string.
2102
+ *
2103
+ * @return {WordArray} The word array.
2104
+ *
2105
+ * @static
2106
+ *
2107
+ * @example
2108
+ *
2109
+ * var wordArray = CryptoJS.enc.Hex.parse(hexString);
2110
+ */parse:function parse(hexStr){// Shortcut
2111
+ var hexStrLength=hexStr.length;// Convert
2112
+ var words=[];for(var i=0;i<hexStrLength;i+=2){words[i>>>3]|=parseInt(hexStr.substr(i,2),16)<<24-i%8*4;}return new WordArray(words,hexStrLength/2);}};/**
2113
+ * Latin1 encoding strategy.
2114
+ */var Latin1={/**
2115
+ * Converts a word array to a Latin1 string.
2116
+ *
2117
+ * @param {WordArray} wordArray The word array.
2118
+ *
2119
+ * @return {string} The Latin1 string.
2120
+ *
2121
+ * @static
2122
+ *
2123
+ * @example
2124
+ *
2125
+ * var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
2126
+ */stringify:function stringify(wordArray){// Shortcuts
2127
+ var words=wordArray.words,sigBytes=wordArray.sigBytes;// Convert
2128
+ var latin1Chars=[];for(var i=0;i<sigBytes;i+=1){var bite=words[i>>>2]>>>24-i%4*8&0xff;latin1Chars.push(String.fromCharCode(bite));}return latin1Chars.join('');},/**
2129
+ * Converts a Latin1 string to a word array.
2130
+ *
2131
+ * @param {string} latin1Str The Latin1 string.
2132
+ *
2133
+ * @return {WordArray} The word array.
2134
+ *
2135
+ * @static
2136
+ *
2137
+ * @example
2138
+ *
2139
+ * var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
2140
+ */parse:function parse(latin1Str){// Shortcut
2141
+ var latin1StrLength=latin1Str.length;// Convert
2142
+ var words=[];for(var i=0;i<latin1StrLength;i+=1){words[i>>>2]|=(latin1Str.charCodeAt(i)&0xff)<<24-i%4*8;}return new WordArray(words,latin1StrLength);}};/**
2143
+ * UTF-8 encoding strategy.
2144
+ */var Utf8={/**
2145
+ * Converts a word array to a UTF-8 string.
2146
+ *
2147
+ * @param {WordArray} wordArray The word array.
2148
+ *
2149
+ * @return {string} The UTF-8 string.
2150
+ *
2151
+ * @static
2152
+ *
2153
+ * @example
2154
+ *
2155
+ * var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
2156
+ */stringify:function stringify(wordArray){try{return decodeURIComponent(escape(Latin1.stringify(wordArray)));}catch(e){throw new Error('Malformed UTF-8 data');}},/**
2157
+ * Converts a UTF-8 string to a word array.
2158
+ *
2159
+ * @param {string} utf8Str The UTF-8 string.
2160
+ *
2161
+ * @return {WordArray} The word array.
2162
+ *
2163
+ * @static
2164
+ *
2165
+ * @example
2166
+ *
2167
+ * var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
2168
+ */parse:function parse(utf8Str){return Latin1.parse(unescape(encodeURIComponent(utf8Str)));}};/**
2169
+ * Abstract buffered block algorithm template.
2170
+ *
2171
+ * The property blockSize must be implemented in a concrete subtype.
2172
+ *
2173
+ * @property {number} _minBufferSize
2174
+ *
2175
+ * The number of blocks that should be kept unprocessed in the buffer. Default: 0
2176
+ */var BufferedBlockAlgorithm=/*#__PURE__*/function(_Base2){function BufferedBlockAlgorithm(){var _this2;_classCallCheck(this,BufferedBlockAlgorithm);_this2=_callSuper(this,BufferedBlockAlgorithm);_this2._minBufferSize=0;return _this2;}/**
2177
+ * Resets this block algorithm's data buffer to its initial state.
2178
+ *
2179
+ * @example
2180
+ *
2181
+ * bufferedBlockAlgorithm.reset();
2182
+ */_inherits(BufferedBlockAlgorithm,_Base2);return _createClass(BufferedBlockAlgorithm,[{key:"reset",value:function reset(){// Initial values
2183
+ this._data=new WordArray();this._nDataBytes=0;}/**
2184
+ * Adds new data to this block algorithm's buffer.
2185
+ *
2186
+ * @param {WordArray|string} data
2187
+ *
2188
+ * The data to append. Strings are converted to a WordArray using UTF-8.
2189
+ *
2190
+ * @example
2191
+ *
2192
+ * bufferedBlockAlgorithm._append('data');
2193
+ * bufferedBlockAlgorithm._append(wordArray);
2194
+ */},{key:"_append",value:function _append(data){var m_data=data;// Convert string to WordArray, else assume WordArray already
2195
+ if(typeof m_data==='string'){m_data=Utf8.parse(m_data);}// Append
2196
+ this._data.concat(m_data);this._nDataBytes+=m_data.sigBytes;}/**
2197
+ * Processes available data blocks.
2198
+ *
2199
+ * This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
2200
+ *
2201
+ * @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
2202
+ *
2203
+ * @return {WordArray} The processed data.
2204
+ *
2205
+ * @example
2206
+ *
2207
+ * var processedData = bufferedBlockAlgorithm._process();
2208
+ * var processedData = bufferedBlockAlgorithm._process(!!'flush');
2209
+ */},{key:"_process",value:function _process(doFlush){var processedWords;// Shortcuts
2210
+ var data=this._data,blockSize=this.blockSize;var dataWords=data.words;var dataSigBytes=data.sigBytes;var blockSizeBytes=blockSize*4;// Count blocks ready
2211
+ var nBlocksReady=dataSigBytes/blockSizeBytes;if(doFlush){// Round up to include partial blocks
2212
+ nBlocksReady=Math.ceil(nBlocksReady);}else {// Round down to include only full blocks,
2213
+ // less the number of blocks that must remain in the buffer
2214
+ nBlocksReady=Math.max((nBlocksReady|0)-this._minBufferSize,0);}// Count words ready
2215
+ var nWordsReady=nBlocksReady*blockSize;// Count bytes ready
2216
+ var nBytesReady=Math.min(nWordsReady*4,dataSigBytes);// Process blocks
2217
+ if(nWordsReady){for(var offset=0;offset<nWordsReady;offset+=blockSize){// Perform concrete-algorithm logic
2218
+ this._doProcessBlock(dataWords,offset);}// Remove processed words
2219
+ processedWords=dataWords.splice(0,nWordsReady);data.sigBytes-=nBytesReady;}// Return processed words
2220
+ return new WordArray(processedWords,nBytesReady);}/**
2221
+ * Creates a copy of this object.
2222
+ *
2223
+ * @return {Object} The clone.
2224
+ *
2225
+ * @example
2226
+ *
2227
+ * var clone = bufferedBlockAlgorithm.clone();
2228
+ */},{key:"clone",value:function clone(){var clone=_get(_getPrototypeOf(BufferedBlockAlgorithm.prototype),"clone",this).call(this);clone._data=this._data.clone();return clone;}}]);}(Base);/**
2229
+ * Abstract hasher template.
2230
+ *
2231
+ * @property {number} blockSize
2232
+ *
2233
+ * The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
2234
+ */var Hasher=/*#__PURE__*/function(_BufferedBlockAlgorit){function Hasher(cfg){var _this3;_classCallCheck(this,Hasher);_this3=_callSuper(this,Hasher);_this3.blockSize=512/32;/**
2235
+ * Configuration options.
2236
+ */_this3.cfg=Object.assign(new Base(),cfg);// Set initial values
2237
+ _this3.reset();return _this3;}/**
2238
+ * Creates a shortcut function to a hasher's object interface.
2239
+ *
2240
+ * @param {Hasher} SubHasher The hasher to create a helper for.
2241
+ *
2242
+ * @return {Function} The shortcut function.
2243
+ *
2244
+ * @static
2245
+ *
2246
+ * @example
2247
+ *
2248
+ * var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
2249
+ */_inherits(Hasher,_BufferedBlockAlgorit);return _createClass(Hasher,[{key:"reset",value:/**
2250
+ * Resets this hasher to its initial state.
2251
+ *
2252
+ * @example
2253
+ *
2254
+ * hasher.reset();
2255
+ */function reset(){// Reset data buffer
2256
+ _get(_getPrototypeOf(Hasher.prototype),"reset",this).call(this);// Perform concrete-hasher logic
2257
+ this._doReset();}/**
2258
+ * Updates this hasher with a message.
2259
+ *
2260
+ * @param {WordArray|string} messageUpdate The message to append.
2261
+ *
2262
+ * @return {Hasher} This hasher.
2263
+ *
2264
+ * @example
2265
+ *
2266
+ * hasher.update('message');
2267
+ * hasher.update(wordArray);
2268
+ */},{key:"update",value:function update(messageUpdate){// Append
2269
+ this._append(messageUpdate);// Update the hash
2270
+ this._process();// Chainable
2271
+ return this;}/**
2272
+ * Finalizes the hash computation.
2273
+ * Note that the finalize operation is effectively a destructive, read-once operation.
2274
+ *
2275
+ * @param {WordArray|string} messageUpdate (Optional) A final message update.
2276
+ *
2277
+ * @return {WordArray} The hash.
2278
+ *
2279
+ * @example
2280
+ *
2281
+ * var hash = hasher.finalize();
2282
+ * var hash = hasher.finalize('message');
2283
+ * var hash = hasher.finalize(wordArray);
2284
+ */},{key:"finalize",value:function finalize(messageUpdate){// Final message update
2285
+ if(messageUpdate){this._append(messageUpdate);}// Perform concrete-hasher logic
2286
+ var hash=this._doFinalize();return hash;}}],[{key:"_createHelper",value:function _createHelper(SubHasher){return function(message,cfg){return new SubHasher(cfg).finalize(message);};}/**
2287
+ * Creates a shortcut function to the HMAC's object interface.
2288
+ *
2289
+ * @param {Hasher} SubHasher The hasher to use in this HMAC helper.
2290
+ *
2291
+ * @return {Function} The shortcut function.
2292
+ *
2293
+ * @static
2294
+ *
2295
+ * @example
2296
+ *
2297
+ * var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
2298
+ */},{key:"_createHmacHelper",value:function _createHmacHelper(SubHasher){return function(message,key){return new HMAC(SubHasher,key).finalize(message);};}}]);}(BufferedBlockAlgorithm);/**
2299
+ * HMAC algorithm.
2300
+ */var HMAC=/*#__PURE__*/function(_Base3){/**
2301
+ * Initializes a newly created HMAC.
2302
+ *
2303
+ * @param {Hasher} SubHasher The hash algorithm to use.
2304
+ * @param {WordArray|string} key The secret key.
2305
+ *
2306
+ * @example
2307
+ *
2308
+ * var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
2309
+ */function HMAC(SubHasher,key){var _this4;_classCallCheck(this,HMAC);_this4=_callSuper(this,HMAC);var hasher=new SubHasher();_this4._hasher=hasher;// Convert string to WordArray, else assume WordArray already
2310
+ var _key=key;if(typeof _key==='string'){_key=Utf8.parse(_key);}// Shortcuts
2311
+ var hasherBlockSize=hasher.blockSize;var hasherBlockSizeBytes=hasherBlockSize*4;// Allow arbitrary length keys
2312
+ if(_key.sigBytes>hasherBlockSizeBytes){_key=hasher.finalize(key);}// Clamp excess bits
2313
+ _key.clamp();// Clone key for inner and outer pads
2314
+ var oKey=_key.clone();_this4._oKey=oKey;var iKey=_key.clone();_this4._iKey=iKey;// Shortcuts
2315
+ var oKeyWords=oKey.words;var iKeyWords=iKey.words;// XOR keys with pad constants
2316
+ for(var i=0;i<hasherBlockSize;i+=1){oKeyWords[i]^=0x5c5c5c5c;iKeyWords[i]^=0x36363636;}oKey.sigBytes=hasherBlockSizeBytes;iKey.sigBytes=hasherBlockSizeBytes;// Set initial values
2317
+ _this4.reset();return _this4;}/**
2318
+ * Resets this HMAC to its initial state.
2319
+ *
2320
+ * @example
2321
+ *
2322
+ * hmacHasher.reset();
2323
+ */_inherits(HMAC,_Base3);return _createClass(HMAC,[{key:"reset",value:function reset(){// Shortcut
2324
+ var hasher=this._hasher;// Reset
2325
+ hasher.reset();hasher.update(this._iKey);}/**
2326
+ * Updates this HMAC with a message.
2327
+ *
2328
+ * @param {WordArray|string} messageUpdate The message to append.
2329
+ *
2330
+ * @return {HMAC} This HMAC instance.
2331
+ *
2332
+ * @example
2333
+ *
2334
+ * hmacHasher.update('message');
2335
+ * hmacHasher.update(wordArray);
2336
+ */},{key:"update",value:function update(messageUpdate){this._hasher.update(messageUpdate);// Chainable
2337
+ return this;}/**
2338
+ * Finalizes the HMAC computation.
2339
+ * Note that the finalize operation is effectively a destructive, read-once operation.
2340
+ *
2341
+ * @param {WordArray|string} messageUpdate (Optional) A final message update.
2342
+ *
2343
+ * @return {WordArray} The HMAC.
2344
+ *
2345
+ * @example
2346
+ *
2347
+ * var hmac = hmacHasher.finalize();
2348
+ * var hmac = hmacHasher.finalize('message');
2349
+ * var hmac = hmacHasher.finalize(wordArray);
2350
+ */},{key:"finalize",value:function finalize(messageUpdate){// Shortcut
2351
+ var hasher=this._hasher;// Compute HMAC
2352
+ var innerHash=hasher.finalize(messageUpdate);hasher.reset();var hmac=hasher.finalize(this._oKey.clone().concat(innerHash));return hmac;}}]);}(Base);
2353
+
2354
+ var parseLoop=function parseLoop(base64Str,base64StrLength,reverseMap){var words=[];var nBytes=0;for(var i=0;i<base64StrLength;i+=1){if(i%4){var bits1=reverseMap[base64Str.charCodeAt(i-1)]<<i%4*2;var bits2=reverseMap[base64Str.charCodeAt(i)]>>>6-i%4*2;var bitsCombined=bits1|bits2;words[nBytes>>>2]|=bitsCombined<<24-nBytes%4*8;nBytes+=1;}}return WordArray.create(words,nBytes);};/**
2355
+ * Base64 encoding strategy.
2356
+ */var Base64={/**
2357
+ * Converts a word array to a Base64 string.
2358
+ *
2359
+ * @param {WordArray} wordArray The word array.
2360
+ *
2361
+ * @return {string} The Base64 string.
2362
+ *
2363
+ * @static
2364
+ *
2365
+ * @example
2366
+ *
2367
+ * const base64String = CryptoJS.enc.Base64.stringify(wordArray);
2368
+ */stringify:function stringify(wordArray){// Shortcuts
2369
+ var words=wordArray.words,sigBytes=wordArray.sigBytes;var map=this._map;// Clamp excess bits
2370
+ wordArray.clamp();// Convert
2371
+ var base64Chars=[];for(var i=0;i<sigBytes;i+=3){var byte1=words[i>>>2]>>>24-i%4*8&0xff;var byte2=words[i+1>>>2]>>>24-(i+1)%4*8&0xff;var byte3=words[i+2>>>2]>>>24-(i+2)%4*8&0xff;var triplet=byte1<<16|byte2<<8|byte3;for(var j=0;j<4&&i+j*0.75<sigBytes;j+=1){base64Chars.push(map.charAt(triplet>>>6*(3-j)&0x3f));}}// Add padding
2372
+ var paddingChar=map.charAt(64);if(paddingChar){while(base64Chars.length%4){base64Chars.push(paddingChar);}}return base64Chars.join('');},/**
2373
+ * Converts a Base64 string to a word array.
2374
+ *
2375
+ * @param {string} base64Str The Base64 string.
2376
+ *
2377
+ * @return {WordArray} The word array.
2378
+ *
2379
+ * @static
2380
+ *
2381
+ * @example
2382
+ *
2383
+ * const wordArray = CryptoJS.enc.Base64.parse(base64String);
2384
+ */parse:function parse(base64Str){// Shortcuts
2385
+ var base64StrLength=base64Str.length;var map=this._map;var reverseMap=this._reverseMap;if(!reverseMap){this._reverseMap=[];reverseMap=this._reverseMap;for(var j=0;j<map.length;j+=1){reverseMap[map.charCodeAt(j)]=j;}}// Ignore padding
2386
+ var paddingChar=map.charAt(64);if(paddingChar){var paddingIndex=base64Str.indexOf(paddingChar);if(paddingIndex!==-1){base64StrLength=paddingIndex;}}// Convert
2387
+ return parseLoop(base64Str,base64StrLength,reverseMap);},_map:'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='};
2388
+
2389
+ var T=[];// Compute constants
2390
+ for(var i$1=0;i$1<64;i$1+=1){T[i$1]=Math.abs(Math.sin(i$1+1))*0x100000000|0;}var FF=function FF(a,b,c,d,x,s,t){var n=a+(b&c|~b&d)+x+t;return (n<<s|n>>>32-s)+b;};var GG=function GG(a,b,c,d,x,s,t){var n=a+(b&d|c&~d)+x+t;return (n<<s|n>>>32-s)+b;};var HH=function HH(a,b,c,d,x,s,t){var n=a+(b^c^d)+x+t;return (n<<s|n>>>32-s)+b;};var II=function II(a,b,c,d,x,s,t){var n=a+(c^(b|~d))+x+t;return (n<<s|n>>>32-s)+b;};/**
2391
+ * MD5 hash algorithm.
2392
+ */var MD5Algo=/*#__PURE__*/function(_Hasher){function MD5Algo(){_classCallCheck(this,MD5Algo);return _callSuper(this,MD5Algo,arguments);}_inherits(MD5Algo,_Hasher);return _createClass(MD5Algo,[{key:"_doReset",value:function _doReset(){this._hash=new WordArray([0x67452301,0xefcdab89,0x98badcfe,0x10325476]);}},{key:"_doProcessBlock",value:function _doProcessBlock(M,offset){var _M=M;// Swap endian
2393
+ for(var _i=0;_i<16;_i+=1){// Shortcuts
2394
+ var offset_i=offset+_i;var M_offset_i=M[offset_i];_M[offset_i]=(M_offset_i<<8|M_offset_i>>>24)&0x00ff00ff|(M_offset_i<<24|M_offset_i>>>8)&0xff00ff00;}// Shortcuts
2395
+ var H=this._hash.words;var M_offset_0=_M[offset+0];var M_offset_1=_M[offset+1];var M_offset_2=_M[offset+2];var M_offset_3=_M[offset+3];var M_offset_4=_M[offset+4];var M_offset_5=_M[offset+5];var M_offset_6=_M[offset+6];var M_offset_7=_M[offset+7];var M_offset_8=_M[offset+8];var M_offset_9=_M[offset+9];var M_offset_10=_M[offset+10];var M_offset_11=_M[offset+11];var M_offset_12=_M[offset+12];var M_offset_13=_M[offset+13];var M_offset_14=_M[offset+14];var M_offset_15=_M[offset+15];// Working varialbes
2396
+ var a=H[0];var b=H[1];var c=H[2];var d=H[3];// Computation
2397
+ a=FF(a,b,c,d,M_offset_0,7,T[0]);d=FF(d,a,b,c,M_offset_1,12,T[1]);c=FF(c,d,a,b,M_offset_2,17,T[2]);b=FF(b,c,d,a,M_offset_3,22,T[3]);a=FF(a,b,c,d,M_offset_4,7,T[4]);d=FF(d,a,b,c,M_offset_5,12,T[5]);c=FF(c,d,a,b,M_offset_6,17,T[6]);b=FF(b,c,d,a,M_offset_7,22,T[7]);a=FF(a,b,c,d,M_offset_8,7,T[8]);d=FF(d,a,b,c,M_offset_9,12,T[9]);c=FF(c,d,a,b,M_offset_10,17,T[10]);b=FF(b,c,d,a,M_offset_11,22,T[11]);a=FF(a,b,c,d,M_offset_12,7,T[12]);d=FF(d,a,b,c,M_offset_13,12,T[13]);c=FF(c,d,a,b,M_offset_14,17,T[14]);b=FF(b,c,d,a,M_offset_15,22,T[15]);a=GG(a,b,c,d,M_offset_1,5,T[16]);d=GG(d,a,b,c,M_offset_6,9,T[17]);c=GG(c,d,a,b,M_offset_11,14,T[18]);b=GG(b,c,d,a,M_offset_0,20,T[19]);a=GG(a,b,c,d,M_offset_5,5,T[20]);d=GG(d,a,b,c,M_offset_10,9,T[21]);c=GG(c,d,a,b,M_offset_15,14,T[22]);b=GG(b,c,d,a,M_offset_4,20,T[23]);a=GG(a,b,c,d,M_offset_9,5,T[24]);d=GG(d,a,b,c,M_offset_14,9,T[25]);c=GG(c,d,a,b,M_offset_3,14,T[26]);b=GG(b,c,d,a,M_offset_8,20,T[27]);a=GG(a,b,c,d,M_offset_13,5,T[28]);d=GG(d,a,b,c,M_offset_2,9,T[29]);c=GG(c,d,a,b,M_offset_7,14,T[30]);b=GG(b,c,d,a,M_offset_12,20,T[31]);a=HH(a,b,c,d,M_offset_5,4,T[32]);d=HH(d,a,b,c,M_offset_8,11,T[33]);c=HH(c,d,a,b,M_offset_11,16,T[34]);b=HH(b,c,d,a,M_offset_14,23,T[35]);a=HH(a,b,c,d,M_offset_1,4,T[36]);d=HH(d,a,b,c,M_offset_4,11,T[37]);c=HH(c,d,a,b,M_offset_7,16,T[38]);b=HH(b,c,d,a,M_offset_10,23,T[39]);a=HH(a,b,c,d,M_offset_13,4,T[40]);d=HH(d,a,b,c,M_offset_0,11,T[41]);c=HH(c,d,a,b,M_offset_3,16,T[42]);b=HH(b,c,d,a,M_offset_6,23,T[43]);a=HH(a,b,c,d,M_offset_9,4,T[44]);d=HH(d,a,b,c,M_offset_12,11,T[45]);c=HH(c,d,a,b,M_offset_15,16,T[46]);b=HH(b,c,d,a,M_offset_2,23,T[47]);a=II(a,b,c,d,M_offset_0,6,T[48]);d=II(d,a,b,c,M_offset_7,10,T[49]);c=II(c,d,a,b,M_offset_14,15,T[50]);b=II(b,c,d,a,M_offset_5,21,T[51]);a=II(a,b,c,d,M_offset_12,6,T[52]);d=II(d,a,b,c,M_offset_3,10,T[53]);c=II(c,d,a,b,M_offset_10,15,T[54]);b=II(b,c,d,a,M_offset_1,21,T[55]);a=II(a,b,c,d,M_offset_8,6,T[56]);d=II(d,a,b,c,M_offset_15,10,T[57]);c=II(c,d,a,b,M_offset_6,15,T[58]);b=II(b,c,d,a,M_offset_13,21,T[59]);a=II(a,b,c,d,M_offset_4,6,T[60]);d=II(d,a,b,c,M_offset_11,10,T[61]);c=II(c,d,a,b,M_offset_2,15,T[62]);b=II(b,c,d,a,M_offset_9,21,T[63]);// Intermediate hash value
2398
+ H[0]=H[0]+a|0;H[1]=H[1]+b|0;H[2]=H[2]+c|0;H[3]=H[3]+d|0;}/* eslint-ensable no-param-reassign */},{key:"_doFinalize",value:function _doFinalize(){// Shortcuts
2399
+ var data=this._data;var dataWords=data.words;var nBitsTotal=this._nDataBytes*8;var nBitsLeft=data.sigBytes*8;// Add padding
2400
+ dataWords[nBitsLeft>>>5]|=0x80<<24-nBitsLeft%32;var nBitsTotalH=Math.floor(nBitsTotal/0x100000000);var nBitsTotalL=nBitsTotal;dataWords[(nBitsLeft+64>>>9<<4)+15]=(nBitsTotalH<<8|nBitsTotalH>>>24)&0x00ff00ff|(nBitsTotalH<<24|nBitsTotalH>>>8)&0xff00ff00;dataWords[(nBitsLeft+64>>>9<<4)+14]=(nBitsTotalL<<8|nBitsTotalL>>>24)&0x00ff00ff|(nBitsTotalL<<24|nBitsTotalL>>>8)&0xff00ff00;data.sigBytes=(dataWords.length+1)*4;// Hash final blocks
2401
+ this._process();// Shortcuts
2402
+ var hash=this._hash;var H=hash.words;// Swap endian
2403
+ for(var _i2=0;_i2<4;_i2+=1){// Shortcut
2404
+ var H_i=H[_i2];H[_i2]=(H_i<<8|H_i>>>24)&0x00ff00ff|(H_i<<24|H_i>>>8)&0xff00ff00;}// Return final computed hash
2405
+ return hash;}},{key:"clone",value:function clone(){var clone=_get(_getPrototypeOf(MD5Algo.prototype),"clone",this).call(this);clone._hash=this._hash.clone();return clone;}}]);}(Hasher);/**
2406
+ * Shortcut function to the hasher's object interface.
2407
+ *
2408
+ * @param {WordArray|string} message The message to hash.
2409
+ *
2410
+ * @return {WordArray} The hash.
2411
+ *
2412
+ * @static
2413
+ *
2414
+ * @example
2415
+ *
2416
+ * var hash = CryptoJS.MD5('message');
2417
+ * var hash = CryptoJS.MD5(wordArray);
2418
+ */Hasher._createHelper(MD5Algo);/**
2419
+ * Shortcut function to the HMAC's object interface.
2420
+ *
2421
+ * @param {WordArray|string} message The message to hash.
2422
+ * @param {WordArray|string} key The secret key.
2423
+ *
2424
+ * @return {WordArray} The HMAC.
2425
+ *
2426
+ * @static
2427
+ *
2428
+ * @example
2429
+ *
2430
+ * var hmac = CryptoJS.HmacMD5(message, key);
2431
+ */Hasher._createHmacHelper(MD5Algo);
2432
+
2433
+ /**
2434
+ * This key derivation function is meant to conform with EVP_BytesToKey.
2435
+ * www.openssl.org/docs/crypto/EVP_BytesToKey.html
2436
+ */var EvpKDFAlgo=/*#__PURE__*/function(_Base){/**
2437
+ * Initializes a newly created key derivation function.
2438
+ *
2439
+ * @param {Object} cfg (Optional) The configuration options to use for the derivation.
2440
+ *
2441
+ * @example
2442
+ *
2443
+ * const kdf = CryptoJS.algo.EvpKDF.create();
2444
+ * const kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
2445
+ * const kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
2446
+ */function EvpKDFAlgo(cfg){var _this;_classCallCheck(this,EvpKDFAlgo);_this=_callSuper(this,EvpKDFAlgo);/**
2447
+ * Configuration options.
2448
+ *
2449
+ * @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
2450
+ * @property {Hasher} hasher The hash algorithm to use. Default: MD5
2451
+ * @property {number} iterations The number of iterations to perform. Default: 1
2452
+ */_this.cfg=Object.assign(new Base(),{keySize:128/32,hasher:MD5Algo,iterations:1},cfg);return _this;}/**
2453
+ * Derives a key from a password.
2454
+ *
2455
+ * @param {WordArray|string} password The password.
2456
+ * @param {WordArray|string} salt A salt.
2457
+ *
2458
+ * @return {WordArray} The derived key.
2459
+ *
2460
+ * @example
2461
+ *
2462
+ * const key = kdf.compute(password, salt);
2463
+ */_inherits(EvpKDFAlgo,_Base);return _createClass(EvpKDFAlgo,[{key:"compute",value:function compute(password,salt){var block;// Shortcut
2464
+ var cfg=this.cfg;// Init hasher
2465
+ var hasher=cfg.hasher.create();// Initial values
2466
+ var derivedKey=WordArray.create();// Shortcuts
2467
+ var derivedKeyWords=derivedKey.words;var keySize=cfg.keySize,iterations=cfg.iterations;// Generate key
2468
+ while(derivedKeyWords.length<keySize){if(block){hasher.update(block);}block=hasher.update(password).finalize(salt);hasher.reset();// Iterations
2469
+ for(var i=1;i<iterations;i+=1){block=hasher.finalize(block);hasher.reset();}derivedKey.concat(block);}derivedKey.sigBytes=keySize*4;return derivedKey;}}]);}(Base);
2470
+
2471
+ var ObjectAssign=typeof Object.assign!=="function"?function(target){if(target==null){throw new TypeError('Cannot convert undefined or null to object');}target=Object(target);for(var index=1;index<arguments.length;index++){var source=arguments[index];if(source!=null){for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}}return target;}:Object.assign;/**
2472
+ * Abstract base cipher template.
2473
+ *
2474
+ * @property {number} keySize This cipher's key size. Default: 4 (128 bits)
2475
+ * @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
2476
+ * @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
2477
+ * @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
2478
+ */var Cipher=/*#__PURE__*/function(_BufferedBlockAlgorit){/**
2479
+ * Initializes a newly created cipher.
2480
+ *
2481
+ * @param {number} xformMode Either the encryption or decryption transormation mode constant.
2482
+ * @param {WordArray} key The key.
2483
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2484
+ *
2485
+ * @example
2486
+ *
2487
+ * const cipher = CryptoJS.algo.AES.create(
2488
+ * CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray }
2489
+ * );
2490
+ */function Cipher(xformMode,key,cfg){var _this;_classCallCheck(this,Cipher);_this=_callSuper(this,Cipher);/**
2491
+ * Configuration options.
2492
+ *
2493
+ * @property {WordArray} iv The IV to use for this operation.
2494
+ */_this.cfg=ObjectAssign(new Base(),cfg);// Store transform mode and key
2495
+ _this._xformMode=xformMode;_this._key=key;// Set initial values
2496
+ _this.reset();return _this;}/**
2497
+ * Creates this cipher in encryption mode.
2498
+ *
2499
+ * @param {WordArray} key The key.
2500
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2501
+ *
2502
+ * @return {Cipher} A cipher instance.
2503
+ *
2504
+ * @static
2505
+ *
2506
+ * @example
2507
+ *
2508
+ * const cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
2509
+ */_inherits(Cipher,_BufferedBlockAlgorit);return _createClass(Cipher,[{key:"reset",value:/**
2510
+ * Resets this cipher to its initial state.
2511
+ *
2512
+ * @example
2513
+ *
2514
+ * cipher.reset();
2515
+ */function reset(){// Reset data buffer
2516
+ _get(_getPrototypeOf(Cipher.prototype),"reset",this).call(this);// Perform concrete-cipher logic
2517
+ this._doReset();}/**
2518
+ * Adds data to be encrypted or decrypted.
2519
+ *
2520
+ * @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
2521
+ *
2522
+ * @return {WordArray} The data after processing.
2523
+ *
2524
+ * @example
2525
+ *
2526
+ * const encrypted = cipher.process('data');
2527
+ * const encrypted = cipher.process(wordArray);
2528
+ */},{key:"process",value:function process(dataUpdate){// Append
2529
+ this._append(dataUpdate);// Process available blocks
2530
+ return this._process();}/**
2531
+ * Finalizes the encryption or decryption process.
2532
+ * Note that the finalize operation is effectively a destructive, read-once operation.
2533
+ *
2534
+ * @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
2535
+ *
2536
+ * @return {WordArray} The data after final processing.
2537
+ *
2538
+ * @example
2539
+ *
2540
+ * const encrypted = cipher.finalize();
2541
+ * const encrypted = cipher.finalize('data');
2542
+ * const encrypted = cipher.finalize(wordArray);
2543
+ */},{key:"finalize",value:function finalize(dataUpdate){// Final data update
2544
+ if(dataUpdate){this._append(dataUpdate);}// Perform concrete-cipher logic
2545
+ var finalProcessedData=this._doFinalize();return finalProcessedData;}}],[{key:"createEncryptor",value:function createEncryptor(key,cfg){return this.create(this._ENC_XFORM_MODE,key,cfg);}/**
2546
+ * Creates this cipher in decryption mode.
2547
+ *
2548
+ * @param {WordArray} key The key.
2549
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2550
+ *
2551
+ * @return {Cipher} A cipher instance.
2552
+ *
2553
+ * @static
2554
+ *
2555
+ * @example
2556
+ *
2557
+ * const cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
2558
+ */},{key:"createDecryptor",value:function createDecryptor(key,cfg){return this.create(this._DEC_XFORM_MODE,key,cfg);}/**
2559
+ * Creates shortcut functions to a cipher's object interface.
2560
+ *
2561
+ * @param {Cipher} cipher The cipher to create a helper for.
2562
+ *
2563
+ * @return {Object} An object with encrypt and decrypt shortcut functions.
2564
+ *
2565
+ * @static
2566
+ *
2567
+ * @example
2568
+ *
2569
+ * const AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
2570
+ */},{key:"_createHelper",value:function _createHelper(SubCipher){var selectCipherStrategy=function selectCipherStrategy(key){if(typeof key==='string'){return PasswordBasedCipher;}return SerializableCipher;};return {encrypt:function encrypt(message,key,cfg){return selectCipherStrategy(key).encrypt(SubCipher,message,key,cfg);},decrypt:function decrypt(ciphertext,key,cfg){return selectCipherStrategy(key).decrypt(SubCipher,ciphertext,key,cfg);}};}}]);}(BufferedBlockAlgorithm);Cipher._ENC_XFORM_MODE=1;Cipher._DEC_XFORM_MODE=2;Cipher.keySize=128/32;Cipher.ivSize=128/32;/**
2571
+ * Abstract base block cipher mode template.
2572
+ */var BlockCipherMode=/*#__PURE__*/function(_Base){/**
2573
+ * Initializes a newly created mode.
2574
+ *
2575
+ * @param {Cipher} cipher A block cipher instance.
2576
+ * @param {Array} iv The IV words.
2577
+ *
2578
+ * @example
2579
+ *
2580
+ * const mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
2581
+ */function BlockCipherMode(cipher,iv){var _this3;_classCallCheck(this,BlockCipherMode);_this3=_callSuper(this,BlockCipherMode);_this3._cipher=cipher;_this3._iv=iv;return _this3;}/**
2582
+ * Creates this mode for encryption.
2583
+ *
2584
+ * @param {Cipher} cipher A block cipher instance.
2585
+ * @param {Array} iv The IV words.
2586
+ *
2587
+ * @static
2588
+ *
2589
+ * @example
2590
+ *
2591
+ * const mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
2592
+ */_inherits(BlockCipherMode,_Base);return _createClass(BlockCipherMode,null,[{key:"createEncryptor",value:function createEncryptor(cipher,iv){return this.Encryptor.create(cipher,iv);}/**
2593
+ * Creates this mode for decryption.
2594
+ *
2595
+ * @param {Cipher} cipher A block cipher instance.
2596
+ * @param {Array} iv The IV words.
2597
+ *
2598
+ * @static
2599
+ *
2600
+ * @example
2601
+ *
2602
+ * const mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
2603
+ */},{key:"createDecryptor",value:function createDecryptor(cipher,iv){return this.Decryptor.create(cipher,iv);}}]);}(Base);function xorBlock(words,offset,blockSize){var _words=words;var block;// Shortcut
2604
+ var iv=this._iv;// Choose mixing block
2605
+ if(iv){block=iv;// Remove IV for subsequent blocks
2606
+ this._iv=undefined;}else {block=this._prevBlock;}// XOR blocks
2607
+ for(var i=0;i<blockSize;i+=1){_words[offset+i]^=block[i];}}/**
2608
+ * Cipher Block Chaining mode.
2609
+ */ /**
2610
+ * Abstract base CBC mode.
2611
+ */var CBC=/*#__PURE__*/function(_BlockCipherMode){function CBC(){_classCallCheck(this,CBC);return _callSuper(this,CBC,arguments);}_inherits(CBC,_BlockCipherMode);return _createClass(CBC);}(BlockCipherMode);/**
2612
+ * CBC encryptor.
2613
+ */CBC.Encryptor=/*#__PURE__*/function(_CBC){function _class(){_classCallCheck(this,_class);return _callSuper(this,_class,arguments);}_inherits(_class,_CBC);return _createClass(_class,[{key:"processBlock",value:/**
2614
+ * Processes the data block at offset.
2615
+ *
2616
+ * @param {Array} words The data words to operate on.
2617
+ * @param {number} offset The offset where the block starts.
2618
+ *
2619
+ * @example
2620
+ *
2621
+ * mode.processBlock(data.words, offset);
2622
+ */function processBlock(words,offset){// Shortcuts
2623
+ var cipher=this._cipher;var blockSize=cipher.blockSize;// XOR and encrypt
2624
+ xorBlock.call(this,words,offset,blockSize);cipher.encryptBlock(words,offset);// Remember this block to use with next block
2625
+ this._prevBlock=words.slice(offset,offset+blockSize);}}]);}(CBC);/**
2626
+ * CBC decryptor.
2627
+ */CBC.Decryptor=/*#__PURE__*/function(_CBC2){function _class2(){_classCallCheck(this,_class2);return _callSuper(this,_class2,arguments);}_inherits(_class2,_CBC2);return _createClass(_class2,[{key:"processBlock",value:/**
2628
+ * Processes the data block at offset.
2629
+ *
2630
+ * @param {Array} words The data words to operate on.
2631
+ * @param {number} offset The offset where the block starts.
2632
+ *
2633
+ * @example
2634
+ *
2635
+ * mode.processBlock(data.words, offset);
2636
+ */function processBlock(words,offset){// Shortcuts
2637
+ var cipher=this._cipher;var blockSize=cipher.blockSize;// Remember this block to use with next block
2638
+ var thisBlock=words.slice(offset,offset+blockSize);// Decrypt and XOR
2639
+ cipher.decryptBlock(words,offset);xorBlock.call(this,words,offset,blockSize);// This block becomes the previous block
2640
+ this._prevBlock=thisBlock;}}]);}(CBC);/**
2641
+ * PKCS #5/7 padding strategy.
2642
+ */var Pkcs7={/**
2643
+ * Pads data using the algorithm defined in PKCS #5/7.
2644
+ *
2645
+ * @param {WordArray} data The data to pad.
2646
+ * @param {number} blockSize The multiple that the data should be padded to.
2647
+ *
2648
+ * @static
2649
+ *
2650
+ * @example
2651
+ *
2652
+ * CryptoJS.pad.Pkcs7.pad(wordArray, 4);
2653
+ */pad:function pad(data,blockSize){// Shortcut
2654
+ var blockSizeBytes=blockSize*4;// Count padding bytes
2655
+ var nPaddingBytes=blockSizeBytes-data.sigBytes%blockSizeBytes;// Create padding word
2656
+ var paddingWord=nPaddingBytes<<24|nPaddingBytes<<16|nPaddingBytes<<8|nPaddingBytes;// Create padding
2657
+ var paddingWords=[];for(var i=0;i<nPaddingBytes;i+=4){paddingWords.push(paddingWord);}var padding=WordArray.create(paddingWords,nPaddingBytes);// Add padding
2658
+ data.concat(padding);},/**
2659
+ * Unpads data that had been padded using the algorithm defined in PKCS #5/7.
2660
+ *
2661
+ * @param {WordArray} data The data to unpad.
2662
+ *
2663
+ * @static
2664
+ *
2665
+ * @example
2666
+ *
2667
+ * CryptoJS.pad.Pkcs7.unpad(wordArray);
2668
+ */unpad:function unpad(data){var _data=data;// Get number of padding bytes from last byte
2669
+ var nPaddingBytes=_data.words[_data.sigBytes-1>>>2]&0xff;// Remove padding
2670
+ _data.sigBytes-=nPaddingBytes;}};/**
2671
+ * Abstract base block cipher template.
2672
+ *
2673
+ * @property {number} blockSize
2674
+ *
2675
+ * The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
2676
+ */var BlockCipher=/*#__PURE__*/function(_Cipher2){function BlockCipher(xformMode,key,cfg){var _this4;_classCallCheck(this,BlockCipher);/**
2677
+ * Configuration options.
2678
+ *
2679
+ * @property {Mode} mode The block mode to use. Default: CBC
2680
+ * @property {Padding} padding The padding strategy to use. Default: Pkcs7
2681
+ */_this4=_callSuper(this,BlockCipher,[xformMode,key,ObjectAssign({mode:CBC,padding:Pkcs7},cfg)]);_this4.blockSize=128/32;return _this4;}_inherits(BlockCipher,_Cipher2);return _createClass(BlockCipher,[{key:"reset",value:function reset(){var modeCreator;// Reset cipher
2682
+ _get(_getPrototypeOf(BlockCipher.prototype),"reset",this).call(this);// Shortcuts
2683
+ var cfg=this.cfg;var iv=cfg.iv,mode=cfg.mode;// Reset block mode
2684
+ if(this._xformMode===this.constructor._ENC_XFORM_MODE){modeCreator=mode.createEncryptor;}else/* if (this._xformMode == this._DEC_XFORM_MODE) */{modeCreator=mode.createDecryptor;// Keep at least one block in the buffer for unpadding
2685
+ this._minBufferSize=1;}this._mode=modeCreator.call(mode,this,iv&&iv.words);this._mode.__creator=modeCreator;}},{key:"_doProcessBlock",value:function _doProcessBlock(words,offset){this._mode.processBlock(words,offset);}},{key:"_doFinalize",value:function _doFinalize(){var finalProcessedBlocks;// Shortcut
2686
+ var padding=this.cfg.padding;// Finalize
2687
+ if(this._xformMode===this.constructor._ENC_XFORM_MODE){// Pad data
2688
+ padding.pad(this._data,this.blockSize);// Process final blocks
2689
+ finalProcessedBlocks=this._process(!!'flush');}else/* if (this._xformMode == this._DEC_XFORM_MODE) */{// Process final blocks
2690
+ finalProcessedBlocks=this._process(!!'flush');// Unpad data
2691
+ padding.unpad(finalProcessedBlocks);}return finalProcessedBlocks;}}]);}(Cipher);/**
2692
+ * A collection of cipher parameters.
2693
+ *
2694
+ * @property {WordArray} ciphertext The raw ciphertext.
2695
+ * @property {WordArray} key The key to this ciphertext.
2696
+ * @property {WordArray} iv The IV used in the ciphering operation.
2697
+ * @property {WordArray} salt The salt used with a key derivation function.
2698
+ * @property {Cipher} algorithm The cipher algorithm.
2699
+ * @property {Mode} mode The block mode used in the ciphering operation.
2700
+ * @property {Padding} padding The padding scheme used in the ciphering operation.
2701
+ * @property {number} blockSize The block size of the cipher.
2702
+ * @property {Format} formatter
2703
+ * The default formatting strategy to convert this cipher params object to a string.
2704
+ */var CipherParams=/*#__PURE__*/function(_Base2){/**
2705
+ * Initializes a newly created cipher params object.
2706
+ *
2707
+ * @param {Object} cipherParams An object with any of the possible cipher parameters.
2708
+ *
2709
+ * @example
2710
+ *
2711
+ * var cipherParams = CryptoJS.lib.CipherParams.create({
2712
+ * ciphertext: ciphertextWordArray,
2713
+ * key: keyWordArray,
2714
+ * iv: ivWordArray,
2715
+ * salt: saltWordArray,
2716
+ * algorithm: CryptoJS.algo.AES,
2717
+ * mode: CryptoJS.mode.CBC,
2718
+ * padding: CryptoJS.pad.PKCS7,
2719
+ * blockSize: 4,
2720
+ * formatter: CryptoJS.format.OpenSSL
2721
+ * });
2722
+ */function CipherParams(cipherParams){var _this5;_classCallCheck(this,CipherParams);_this5=_callSuper(this,CipherParams);_this5.mixIn(cipherParams);return _this5;}/**
2723
+ * Converts this cipher params object to a string.
2724
+ *
2725
+ * @param {Format} formatter (Optional) The formatting strategy to use.
2726
+ *
2727
+ * @return {string} The stringified cipher params.
2728
+ *
2729
+ * @throws Error If neither the formatter nor the default formatter is set.
2730
+ *
2731
+ * @example
2732
+ *
2733
+ * var string = cipherParams + '';
2734
+ * var string = cipherParams.toString();
2735
+ * var string = cipherParams.toString(CryptoJS.format.OpenSSL);
2736
+ */_inherits(CipherParams,_Base2);return _createClass(CipherParams,[{key:"toString",value:function toString(formatter){return (formatter||this.formatter).stringify(this);}}]);}(Base);/**
2737
+ * OpenSSL formatting strategy.
2738
+ */var OpenSSLFormatter={/**
2739
+ * Converts a cipher params object to an OpenSSL-compatible string.
2740
+ *
2741
+ * @param {CipherParams} cipherParams The cipher params object.
2742
+ *
2743
+ * @return {string} The OpenSSL-compatible string.
2744
+ *
2745
+ * @static
2746
+ *
2747
+ * @example
2748
+ *
2749
+ * var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
2750
+ */stringify:function stringify(cipherParams){var wordArray;// Shortcuts
2751
+ var ciphertext=cipherParams.ciphertext,salt=cipherParams.salt;// Format
2752
+ if(salt){wordArray=WordArray.create([0x53616c74,0x65645f5f]).concat(salt).concat(ciphertext);}else {wordArray=ciphertext;}return wordArray.toString(Base64);},/**
2753
+ * Converts an OpenSSL-compatible string to a cipher params object.
2754
+ *
2755
+ * @param {string} openSSLStr The OpenSSL-compatible string.
2756
+ *
2757
+ * @return {CipherParams} The cipher params object.
2758
+ *
2759
+ * @static
2760
+ *
2761
+ * @example
2762
+ *
2763
+ * var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
2764
+ */parse:function parse(openSSLStr){var salt;// Parse base64
2765
+ var ciphertext=Base64.parse(openSSLStr);// Shortcut
2766
+ var ciphertextWords=ciphertext.words;// Test for salt
2767
+ if(ciphertextWords[0]===0x53616c74&&ciphertextWords[1]===0x65645f5f){// Extract salt
2768
+ salt=WordArray.create(ciphertextWords.slice(2,4));// Remove salt from ciphertext
2769
+ ciphertextWords.splice(0,4);ciphertext.sigBytes-=16;}return CipherParams.create({ciphertext:ciphertext,salt:salt});}};/**
2770
+ * A cipher wrapper that returns ciphertext as a serializable cipher params object.
2771
+ */var SerializableCipher=/*#__PURE__*/function(_Base3){function SerializableCipher(){_classCallCheck(this,SerializableCipher);return _callSuper(this,SerializableCipher,arguments);}_inherits(SerializableCipher,_Base3);return _createClass(SerializableCipher,null,[{key:"encrypt",value:/**
2772
+ * Encrypts a message.
2773
+ *
2774
+ * @param {Cipher} cipher The cipher algorithm to use.
2775
+ * @param {WordArray|string} message The message to encrypt.
2776
+ * @param {WordArray} key The key.
2777
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2778
+ *
2779
+ * @return {CipherParams} A cipher params object.
2780
+ *
2781
+ * @static
2782
+ *
2783
+ * @example
2784
+ *
2785
+ * var ciphertextParams = CryptoJS.lib.SerializableCipher
2786
+ * .encrypt(CryptoJS.algo.AES, message, key);
2787
+ * var ciphertextParams = CryptoJS.lib.SerializableCipher
2788
+ * .encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
2789
+ * var ciphertextParams = CryptoJS.lib.SerializableCipher
2790
+ * .encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
2791
+ */function encrypt(cipher,message,key,cfg){// Apply config defaults
2792
+ var _cfg=ObjectAssign(new Base(),this.cfg,cfg);// Encrypt
2793
+ var encryptor=cipher.createEncryptor(key,_cfg);var ciphertext=encryptor.finalize(message);// Shortcut
2794
+ var cipherCfg=encryptor.cfg;// Create and return serializable cipher params
2795
+ return CipherParams.create({ciphertext:ciphertext,key:key,iv:cipherCfg.iv,algorithm:cipher,mode:cipherCfg.mode,padding:cipherCfg.padding,blockSize:encryptor.blockSize,formatter:_cfg.format});}/**
2796
+ * Decrypts serialized ciphertext.
2797
+ *
2798
+ * @param {Cipher} cipher The cipher algorithm to use.
2799
+ * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
2800
+ * @param {WordArray} key The key.
2801
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2802
+ *
2803
+ * @return {WordArray} The plaintext.
2804
+ *
2805
+ * @static
2806
+ *
2807
+ * @example
2808
+ *
2809
+ * var plaintext = CryptoJS.lib.SerializableCipher
2810
+ * .decrypt(CryptoJS.algo.AES, formattedCiphertext, key,
2811
+ * { iv: iv, format: CryptoJS.format.OpenSSL });
2812
+ * var plaintext = CryptoJS.lib.SerializableCipher
2813
+ * .decrypt(CryptoJS.algo.AES, ciphertextParams, key,
2814
+ * { iv: iv, format: CryptoJS.format.OpenSSL });
2815
+ */},{key:"decrypt",value:function decrypt(cipher,ciphertext,key,cfg){var _ciphertext=ciphertext;// Apply config defaults
2816
+ var _cfg=ObjectAssign(new Base(),this.cfg,cfg);// Convert string to CipherParams
2817
+ _ciphertext=this._parse(_ciphertext,_cfg.format);// Decrypt
2818
+ var plaintext=cipher.createDecryptor(key,_cfg).finalize(_ciphertext.ciphertext);return plaintext;}/**
2819
+ * Converts serialized ciphertext to CipherParams,
2820
+ * else assumed CipherParams already and returns ciphertext unchanged.
2821
+ *
2822
+ * @param {CipherParams|string} ciphertext The ciphertext.
2823
+ * @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
2824
+ *
2825
+ * @return {CipherParams} The unserialized ciphertext.
2826
+ *
2827
+ * @static
2828
+ *
2829
+ * @example
2830
+ *
2831
+ * var ciphertextParams = CryptoJS.lib.SerializableCipher
2832
+ * ._parse(ciphertextStringOrParams, format);
2833
+ */},{key:"_parse",value:function _parse(ciphertext,format){if(typeof ciphertext==='string'){return format.parse(ciphertext,this);}return ciphertext;}}]);}(Base);/**
2834
+ * Configuration options.
2835
+ *
2836
+ * @property {Formatter} format
2837
+ *
2838
+ * The formatting strategy to convert cipher param objects to and from a string.
2839
+ * Default: OpenSSL
2840
+ */SerializableCipher.cfg=ObjectAssign(new Base(),{format:OpenSSLFormatter});/**
2841
+ * OpenSSL key derivation function.
2842
+ */var OpenSSLKdf={/**
2843
+ * Derives a key and IV from a password.
2844
+ *
2845
+ * @param {string} password The password to derive from.
2846
+ * @param {number} keySize The size in words of the key to generate.
2847
+ * @param {number} ivSize The size in words of the IV to generate.
2848
+ * @param {WordArray|string} salt
2849
+ * (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
2850
+ *
2851
+ * @return {CipherParams} A cipher params object with the key, IV, and salt.
2852
+ *
2853
+ * @static
2854
+ *
2855
+ * @example
2856
+ *
2857
+ * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
2858
+ * var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
2859
+ */execute:function execute(password,keySize,ivSize,salt,hasher){var _salt=salt;// Generate random salt
2860
+ if(!_salt){_salt=WordArray.random(64/8);}// Derive key and IV
2861
+ var key;if(!hasher){key=EvpKDFAlgo.create({keySize:keySize+ivSize}).compute(password,_salt);}else {key=EvpKDFAlgo.create({keySize:keySize+ivSize,hasher:hasher}).compute(password,_salt);}// Separate key and IV
2862
+ var iv=WordArray.create(key.words.slice(keySize),ivSize*4);key.sigBytes=keySize*4;// Return params
2863
+ return CipherParams.create({key:key,iv:iv,salt:_salt});}};/**
2864
+ * A serializable cipher wrapper that derives the key from a password,
2865
+ * and returns ciphertext as a serializable cipher params object.
2866
+ */var PasswordBasedCipher=/*#__PURE__*/function(_SerializableCipher){function PasswordBasedCipher(){_classCallCheck(this,PasswordBasedCipher);return _callSuper(this,PasswordBasedCipher,arguments);}_inherits(PasswordBasedCipher,_SerializableCipher);return _createClass(PasswordBasedCipher,null,[{key:"encrypt",value:/**
2867
+ * Encrypts a message using a password.
2868
+ *
2869
+ * @param {Cipher} cipher The cipher algorithm to use.
2870
+ * @param {WordArray|string} message The message to encrypt.
2871
+ * @param {string} password The password.
2872
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2873
+ *
2874
+ * @return {CipherParams} A cipher params object.
2875
+ *
2876
+ * @static
2877
+ *
2878
+ * @example
2879
+ *
2880
+ * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher
2881
+ * .encrypt(CryptoJS.algo.AES, message, 'password');
2882
+ * var ciphertextParams = CryptoJS.lib.PasswordBasedCipher
2883
+ * .encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
2884
+ */function encrypt(cipher,message,password,cfg){// Apply config defaults
2885
+ var _cfg=ObjectAssign(new Base(),this.cfg,cfg);// Derive key and other params
2886
+ var derivedParams=_cfg.kdf.execute(password,cipher.keySize,cipher.ivSize,_cfg.salt,_cfg.hasher);// Add IV to config
2887
+ _cfg.iv=derivedParams.iv;// Encrypt
2888
+ var ciphertext=SerializableCipher.encrypt.call(this,cipher,message,derivedParams.key,_cfg);// Mix in derived params
2889
+ ciphertext.mixIn(derivedParams);return ciphertext;}/**
2890
+ * Decrypts serialized ciphertext using a password.
2891
+ *
2892
+ * @param {Cipher} cipher The cipher algorithm to use.
2893
+ * @param {CipherParams|string} ciphertext The ciphertext to decrypt.
2894
+ * @param {string} password The password.
2895
+ * @param {Object} cfg (Optional) The configuration options to use for this operation.
2896
+ *
2897
+ * @return {WordArray} The plaintext.
2898
+ *
2899
+ * @static
2900
+ *
2901
+ * @example
2902
+ *
2903
+ * var plaintext = CryptoJS.lib.PasswordBasedCipher
2904
+ * .decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password',
2905
+ * { format: CryptoJS.format.OpenSSL });
2906
+ * var plaintext = CryptoJS.lib.PasswordBasedCipher
2907
+ * .decrypt(CryptoJS.algo.AES, ciphertextParams, 'password',
2908
+ * { format: CryptoJS.format.OpenSSL });
2909
+ */},{key:"decrypt",value:function decrypt(cipher,ciphertext,password,cfg){var _ciphertext=ciphertext;// Apply config defaults
2910
+ var _cfg=ObjectAssign(new Base(),this.cfg,cfg);// Convert string to CipherParams
2911
+ _ciphertext=this._parse(_ciphertext,_cfg.format);// Derive key and other params
2912
+ var derivedParams=_cfg.kdf.execute(password,cipher.keySize,cipher.ivSize,_ciphertext.salt,_cfg.hasher);// Add IV to config
2913
+ _cfg.iv=derivedParams.iv;// Decrypt
2914
+ var plaintext=SerializableCipher.decrypt.call(this,cipher,_ciphertext,derivedParams.key,_cfg);return plaintext;}}]);}(SerializableCipher);/**
2915
+ * Configuration options.
2916
+ *
2917
+ * @property {KDF} kdf
2918
+ * The key derivation function to use to generate a key and IV from a password.
2919
+ * Default: OpenSSL
2920
+ */PasswordBasedCipher.cfg=ObjectAssign(SerializableCipher.cfg,{kdf:OpenSSLKdf});
2921
+
2922
+ var _SBOX=[];var INV_SBOX=[];var _SUB_MIX_0=[];var _SUB_MIX_1=[];var _SUB_MIX_2=[];var _SUB_MIX_3=[];var INV_SUB_MIX_0=[];var INV_SUB_MIX_1=[];var INV_SUB_MIX_2=[];var INV_SUB_MIX_3=[];// Compute lookup tables
2923
+ // Compute double table
2924
+ var d=[];for(var i=0;i<256;i+=1){if(i<128){d[i]=i<<1;}else {d[i]=i<<1^0x11b;}}// Walk GF(2^8)
2925
+ var x=0;var xi=0;for(var _i=0;_i<256;_i+=1){// Compute sbox
2926
+ var sx=xi^xi<<1^xi<<2^xi<<3^xi<<4;sx=sx>>>8^sx&0xff^0x63;_SBOX[x]=sx;INV_SBOX[sx]=x;// Compute multiplication
2927
+ var x2=d[x];var x4=d[x2];var x8=d[x4];// Compute sub bytes, mix columns tables
2928
+ var t=d[sx]*0x101^sx*0x1010100;_SUB_MIX_0[x]=t<<24|t>>>8;_SUB_MIX_1[x]=t<<16|t>>>16;_SUB_MIX_2[x]=t<<8|t>>>24;_SUB_MIX_3[x]=t;// Compute inv sub bytes, inv mix columns tables
2929
+ t=x8*0x1010101^x4*0x10001^x2*0x101^x*0x1010100;INV_SUB_MIX_0[sx]=t<<24|t>>>8;INV_SUB_MIX_1[sx]=t<<16|t>>>16;INV_SUB_MIX_2[sx]=t<<8|t>>>24;INV_SUB_MIX_3[sx]=t;// Compute next counter
2930
+ if(!x){xi=1;x=xi;}else {x=x2^d[d[d[x8^x2]]];xi^=d[d[xi]];}}// Precomputed Rcon lookup
2931
+ var RCON=[0x00,0x01,0x02,0x04,0x08,0x10,0x20,0x40,0x80,0x1b,0x36];/**
2932
+ * AES block cipher algorithm.
2933
+ */var AESAlgo=/*#__PURE__*/function(_BlockCipher){function AESAlgo(){_classCallCheck(this,AESAlgo);return _callSuper(this,AESAlgo,arguments);}_inherits(AESAlgo,_BlockCipher);return _createClass(AESAlgo,[{key:"_doReset",value:function _doReset(){var t;// Skip reset of nRounds has been set before and key did not change
2934
+ if(this._nRounds&&this._keyPriorReset===this._key){return;}// Shortcuts
2935
+ this._keyPriorReset=this._key;var key=this._keyPriorReset;var keyWords=key.words;var keySize=key.sigBytes/4;// Compute number of rounds
2936
+ this._nRounds=keySize+6;var nRounds=this._nRounds;// Compute number of key schedule rows
2937
+ var ksRows=(nRounds+1)*4;// Compute key schedule
2938
+ this._keySchedule=[];var keySchedule=this._keySchedule;for(var ksRow=0;ksRow<ksRows;ksRow+=1){if(ksRow<keySize){keySchedule[ksRow]=keyWords[ksRow];}else {t=keySchedule[ksRow-1];if(!(ksRow%keySize)){// Rot word
2939
+ t=t<<8|t>>>24;// Sub word
2940
+ t=_SBOX[t>>>24]<<24|_SBOX[t>>>16&0xff]<<16|_SBOX[t>>>8&0xff]<<8|_SBOX[t&0xff];// Mix Rcon
2941
+ t^=RCON[ksRow/keySize|0]<<24;}else if(keySize>6&&ksRow%keySize===4){// Sub word
2942
+ t=_SBOX[t>>>24]<<24|_SBOX[t>>>16&0xff]<<16|_SBOX[t>>>8&0xff]<<8|_SBOX[t&0xff];}keySchedule[ksRow]=keySchedule[ksRow-keySize]^t;}}// Compute inv key schedule
2943
+ this._invKeySchedule=[];var invKeySchedule=this._invKeySchedule;for(var invKsRow=0;invKsRow<ksRows;invKsRow+=1){var _ksRow=ksRows-invKsRow;if(invKsRow%4){t=keySchedule[_ksRow];}else {t=keySchedule[_ksRow-4];}if(invKsRow<4||_ksRow<=4){invKeySchedule[invKsRow]=t;}else {invKeySchedule[invKsRow]=INV_SUB_MIX_0[_SBOX[t>>>24]]^INV_SUB_MIX_1[_SBOX[t>>>16&0xff]]^INV_SUB_MIX_2[_SBOX[t>>>8&0xff]]^INV_SUB_MIX_3[_SBOX[t&0xff]];}}}},{key:"encryptBlock",value:function encryptBlock(M,offset){this._doCryptBlock(M,offset,this._keySchedule,_SUB_MIX_0,_SUB_MIX_1,_SUB_MIX_2,_SUB_MIX_3,_SBOX);}},{key:"decryptBlock",value:function decryptBlock(M,offset){var _M=M;// Swap 2nd and 4th rows
2944
+ var t=_M[offset+1];_M[offset+1]=_M[offset+3];_M[offset+3]=t;this._doCryptBlock(_M,offset,this._invKeySchedule,INV_SUB_MIX_0,INV_SUB_MIX_1,INV_SUB_MIX_2,INV_SUB_MIX_3,INV_SBOX);// Inv swap 2nd and 4th rows
2945
+ t=_M[offset+1];_M[offset+1]=_M[offset+3];_M[offset+3]=t;}},{key:"_doCryptBlock",value:function _doCryptBlock(M,offset,keySchedule,SUB_MIX_0,SUB_MIX_1,SUB_MIX_2,SUB_MIX_3,SBOX){var _M=M;// Shortcut
2946
+ var nRounds=this._nRounds;// Get input, add round key
2947
+ var s0=_M[offset]^keySchedule[0];var s1=_M[offset+1]^keySchedule[1];var s2=_M[offset+2]^keySchedule[2];var s3=_M[offset+3]^keySchedule[3];// Key schedule row counter
2948
+ var ksRow=4;// Rounds
2949
+ for(var round=1;round<nRounds;round+=1){// Shift rows, sub bytes, mix columns, add round key
2950
+ var _t=SUB_MIX_0[s0>>>24]^SUB_MIX_1[s1>>>16&0xff]^SUB_MIX_2[s2>>>8&0xff]^SUB_MIX_3[s3&0xff]^keySchedule[ksRow];ksRow+=1;var _t2=SUB_MIX_0[s1>>>24]^SUB_MIX_1[s2>>>16&0xff]^SUB_MIX_2[s3>>>8&0xff]^SUB_MIX_3[s0&0xff]^keySchedule[ksRow];ksRow+=1;var _t3=SUB_MIX_0[s2>>>24]^SUB_MIX_1[s3>>>16&0xff]^SUB_MIX_2[s0>>>8&0xff]^SUB_MIX_3[s1&0xff]^keySchedule[ksRow];ksRow+=1;var _t4=SUB_MIX_0[s3>>>24]^SUB_MIX_1[s0>>>16&0xff]^SUB_MIX_2[s1>>>8&0xff]^SUB_MIX_3[s2&0xff]^keySchedule[ksRow];ksRow+=1;// Update state
2951
+ s0=_t;s1=_t2;s2=_t3;s3=_t4;}// Shift rows, sub bytes, add round key
2952
+ var t0=(SBOX[s0>>>24]<<24|SBOX[s1>>>16&0xff]<<16|SBOX[s2>>>8&0xff]<<8|SBOX[s3&0xff])^keySchedule[ksRow];ksRow+=1;var t1=(SBOX[s1>>>24]<<24|SBOX[s2>>>16&0xff]<<16|SBOX[s3>>>8&0xff]<<8|SBOX[s0&0xff])^keySchedule[ksRow];ksRow+=1;var t2=(SBOX[s2>>>24]<<24|SBOX[s3>>>16&0xff]<<16|SBOX[s0>>>8&0xff]<<8|SBOX[s1&0xff])^keySchedule[ksRow];ksRow+=1;var t3=(SBOX[s3>>>24]<<24|SBOX[s0>>>16&0xff]<<16|SBOX[s1>>>8&0xff]<<8|SBOX[s2&0xff])^keySchedule[ksRow];ksRow+=1;// Set output
2953
+ _M[offset]=t0;_M[offset+1]=t1;_M[offset+2]=t2;_M[offset+3]=t3;}}]);}(BlockCipher);AESAlgo.keySize=256/32;/**
2954
+ * Shortcut functions to the cipher's object interface.
2955
+ *
2956
+ * @example
2957
+ *
2958
+ * var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
2959
+ * var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
2960
+ */var AES=BlockCipher._createHelper(AESAlgo);
2961
+
2962
+ var ENCRYPTION_PREFIX_V1='RudderEncrypt:';var ENCRYPTION_KEY_V1='Rudder';
2963
+
2964
+ var encrypt=function encrypt(value){return "".concat(ENCRYPTION_PREFIX_V1).concat(AES.encrypt(value,ENCRYPTION_KEY_V1).toString());};var decrypt=function decrypt(value){if(value.startsWith(ENCRYPTION_PREFIX_V1)){return AES.decrypt(value.substring(ENCRYPTION_PREFIX_V1.length),ENCRYPTION_KEY_V1).toString(Utf8);}return value;};
2965
+
2966
+ var pluginName$2='StorageEncryptionLegacy';var StorageEncryptionLegacy=function StorageEncryptionLegacy(){return {name:pluginName$2,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$2]);},storage:{encrypt:function encrypt$1(value){return encrypt(value);},decrypt:function decrypt$1(value){return decrypt(value);}}};};
2967
+
2968
+ var STORAGE_MIGRATION_ERROR=function STORAGE_MIGRATION_ERROR(key){return "Failed to retrieve or parse data for ".concat(key," from storage.");};
2969
+
2970
+ var STORAGE_MIGRATOR_PLUGIN='StorageMigratorPlugin';
2971
+
2972
+ var pluginName$1='StorageMigrator';var StorageMigrator=function StorageMigrator(){return {name:pluginName$1,initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$1]);},storage:{migrate:function migrate(key,storageEngine,errorHandler,logger){try{var storedVal=storageEngine.getItem(key);if(isNullOrUndefined(storedVal)){return null;}var decryptedVal=decrypt(storedVal);// The value is not encrypted using legacy encryption
2973
+ // Try latest
2974
+ if(decryptedVal===storedVal){decryptedVal=decryptBrowser(storedVal);}if(isNullOrUndefined(decryptedVal)){return null;}// storejs that is used in localstorage engine already deserializes json strings but swallows errors
2975
+ return JSON.parse(decryptedVal);}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,STORAGE_MIGRATOR_PLUGIN,STORAGE_MIGRATION_ERROR(key));return null;}}}};};
2976
+
2977
+ var DEFAULT_RETRY_QUEUE_OPTIONS={maxRetryDelay:360000,minRetryDelay:1000,backoffFactor:2,maxAttempts:10,maxItems:100};var REQUEST_TIMEOUT_MS=30*1000;// 30 seconds
2978
+ var DATA_PLANE_API_VERSION='v1';var QUEUE_NAME='rudder';var XHR_QUEUE_PLUGIN='XhrQueuePlugin';
2979
+
2980
+ var EVENT_DELIVERY_FAILURE_ERROR_PREFIX=function EVENT_DELIVERY_FAILURE_ERROR_PREFIX(context,url){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to deliver event(s) to ").concat(url,".");};
2981
+
2982
+ var getBatchDeliveryPayload=function getBatchDeliveryPayload(events,currentTime,logger){var batchPayload={batch:events,sentAt:currentTime};return stringifyWithoutCircular(batchPayload,true,undefined,logger);};var getNormalizedQueueOptions=function getNormalizedQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_RETRY_QUEUE_OPTIONS,queueOpts);};var getDeliveryUrl=function getDeliveryUrl(dataplaneUrl,endpoint){var dpUrl=new URL(dataplaneUrl);return new URL(removeDuplicateSlashes([dpUrl.pathname,'/',DATA_PLANE_API_VERSION,'/',endpoint].join('')),dpUrl).href;};var getBatchDeliveryUrl=function getBatchDeliveryUrl(dataplaneUrl){return getDeliveryUrl(dataplaneUrl,'batch');};var logErrorOnFailure=function logErrorOnFailure(details,url,willBeRetried,attemptNumber,maxRetryAttempts,logger){if(isUndefined(details===null||details===void 0?void 0:details.error)||isUndefined(logger)){return;}var isRetryableFailure=isErrRetryable(details);var errMsg=EVENT_DELIVERY_FAILURE_ERROR_PREFIX(XHR_QUEUE_PLUGIN,url);var dropMsg="The event(s) will be dropped.";if(isRetryableFailure){if(willBeRetried){errMsg="".concat(errMsg," It/they will be retried.");if(attemptNumber>0){errMsg="".concat(errMsg," Retry attempt ").concat(attemptNumber," of ").concat(maxRetryAttempts,".");}}else {errMsg="".concat(errMsg," Retries exhausted (").concat(maxRetryAttempts,"). ").concat(dropMsg);}}else {errMsg="".concat(errMsg," ").concat(dropMsg);}logger===null||logger===void 0||logger.error(errMsg);};var getRequestInfo=function getRequestInfo(itemData,state,logger){var data;var headers;var url;var currentTime=getCurrentTimeFormatted();if(Array.isArray(itemData)){var finalEvents=itemData.map(function(queueItemData){return getFinalEventForDeliveryMutator(queueItemData.event,currentTime);});data=getBatchDeliveryPayload(finalEvents,currentTime,logger);headers=itemData[0]?clone(itemData[0].headers):{};url=getBatchDeliveryUrl(state.lifecycle.activeDataplaneUrl.value);}else {var eventUrl=itemData.url,event=itemData.event,eventHeaders=itemData.headers;var finalEvent=getFinalEventForDeliveryMutator(event,currentTime);data=getDeliveryPayload(finalEvent,logger);headers=clone(eventHeaders);url=eventUrl;}return {data:data,headers:headers,url:url};};
2983
+
2984
+ var pluginName='XhrQueue';var XhrQueue=function XhrQueue(){return {name:pluginName,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName]);},dataplaneEventsQueue:{/**
2985
+ * Initialize the queue for delivery
2986
+ * @param state Application state
2987
+ * @param httpClient http client instance
2988
+ * @param storeManager Store Manager instance
2989
+ * @param errorHandler Error handler instance
2990
+ * @param logger Logger instance
2991
+ * @returns RetryQueue instance
2992
+ */init:function init(state,httpClient,storeManager,errorHandler,logger){var writeKey=state.lifecycle.writeKey.value;httpClient.setAuthHeader(writeKey);var finalQOpts=getNormalizedQueueOptions(state.loadOptions.value.queueOptions);var eventsQueue=new RetryQueue(// adding write key to the queue name to avoid conflicts
2993
+ "".concat(QUEUE_NAME,"_").concat(writeKey),finalQOpts,function(itemData,done,attemptNumber,maxRetryAttempts,willBeRetried){var _getRequestInfo=getRequestInfo(itemData,state,logger),data=_getRequestInfo.data,url=_getRequestInfo.url,headers=_getRequestInfo.headers;httpClient.getAsyncData({url:url,options:{method:'POST',headers:headers,data:data,sendRawData:true},isRawResponse:true,timeout:REQUEST_TIMEOUT_MS,callback:function callback(result,details){// null means item will not be requeued
2994
+ var queueErrResp=isErrRetryable(details)?details:null;logErrorOnFailure(details,url,willBeRetried,attemptNumber,maxRetryAttempts,logger);done(queueErrResp,result);}});},storeManager,LOCAL_STORAGE,logger,function(itemData){var _getBatchDeliveryPayl;var currentTime=getCurrentTimeFormatted();var events=itemData.map(function(queueItemData){return queueItemData.event;});// type casting to string as we know that the event has already been validated prior to enqueue
2995
+ return (_getBatchDeliveryPayl=getBatchDeliveryPayload(events,currentTime,logger))===null||_getBatchDeliveryPayl===void 0?void 0:_getBatchDeliveryPayl.length;});return eventsQueue;},/**
2996
+ * Add event to the queue for delivery
2997
+ * @param state Application state
2998
+ * @param eventsQueue RetryQueue instance
2999
+ * @param event RudderEvent object
3000
+ * @param errorHandler Error handler instance
3001
+ * @param logger Logger instance
3002
+ * @returns none
3003
+ */enqueue:function enqueue(state,eventsQueue,event,errorHandler,logger){// sentAt is only added here for the validation step
3004
+ // It'll be updated to the latest timestamp during actual delivery
3005
+ event.sentAt=getCurrentTimeFormatted();validateEventPayloadSize(event,logger);var dataplaneUrl=state.lifecycle.activeDataplaneUrl.value;var url=getDeliveryUrl(dataplaneUrl,event.type);// Other default headers are added by the HttpClient
3006
+ // Auth header is added during initialization
3007
+ var headers={// To maintain event ordering while using the HTTP API as per is documentation,
3008
+ // make sure to include anonymousId as a header
3009
+ AnonymousId:toBase64(event.anonymousId)};eventsQueue.addItem({url:url,headers:headers,event:event});}}};};
3010
+
3011
+ /**
3012
+ * Map plugin names to direct code imports from plugins package
3013
+ */var getBundledBuildPluginImports=function getBundledBuildPluginImports(){return {BeaconQueue:BeaconQueue,Bugsnag:Bugsnag,CustomConsentManager:CustomConsentManager,DeviceModeDestinations:DeviceModeDestinations,DeviceModeTransformation:DeviceModeTransformation,ErrorReporting:ErrorReporting,ExternalAnonymousId:ExternalAnonymousId,GoogleLinker:GoogleLinker,KetchConsentManager:KetchConsentManager,NativeDestinationQueue:NativeDestinationQueue,OneTrustConsentManager:OneTrustConsentManager,StorageEncryption:StorageEncryption,StorageEncryptionLegacy:StorageEncryptionLegacy,StorageMigrator:StorageMigrator,XhrQueue:XhrQueue};};
3014
+
3015
+ /**
3016
+ * Map of mandatory plugin names and direct imports
3017
+ */var getMandatoryPluginsMap=function getMandatoryPluginsMap(){return {};};/**
3018
+ * Map of optional plugin names and direct imports for legacy builds
3019
+ */var getOptionalPluginsMap=function getOptionalPluginsMap(){return getBundledBuildPluginImports();};/**
3020
+ * Map of optional plugin names and dynamic imports for modern builds
3021
+ */var getRemotePluginsMap=function getRemotePluginsMap(activePluginNames){{return {};}};var pluginsInventory=_objectSpread2(_objectSpread2({},getMandatoryPluginsMap()),getOptionalPluginsMap());var remotePluginsInventory=function remotePluginsInventory(activePluginNames){return _objectSpread2({},getRemotePluginsMap());};
3022
+
3023
+ // TODO: add retry mechanism for getting remote plugins
3024
+ // TODO: add timeout error mechanism for marking remote plugins that failed to load as failed in state
3025
+ var PluginsManager=/*#__PURE__*/function(){function PluginsManager(engine,errorHandler,logger){_classCallCheck(this,PluginsManager);this.engine=engine;this.errorHandler=errorHandler;this.logger=logger;this.onError=this.onError.bind(this);}/**
3026
+ * Orchestrate the plugin loading and registering
3027
+ */return _createClass(PluginsManager,[{key:"init",value:function init(){state.lifecycle.status.value='pluginsLoading';// Expose pluginsCDNPath to global object, so it can be used in the promise that determines
3028
+ this.setActivePlugins();this.registerLocalPlugins();this.registerRemotePlugins();this.attachEffects();}/**
3029
+ * Update state based on plugin loaded status
3030
+ */ // eslint-disable-next-line class-methods-use-this
3031
+ },{key:"attachEffects",value:function attachEffects(){E(function(){var isAllPluginsReady=state.plugins.activePlugins.value.length===0||state.plugins.loadedPlugins.value.length+state.plugins.failedPlugins.value.length===state.plugins.totalPluginsToLoad.value;if(isAllPluginsReady){r(function(){state.plugins.ready.value=true;// TODO: decide what to do if a plugin fails to load for any reason.
3032
+ // Should we stop here or should we progress?
3033
+ state.lifecycle.status.value='pluginsReady';});}});}/**
3034
+ * Determine the list of plugins that should be loaded based on sourceConfig & load options
3035
+ */ // eslint-disable-next-line class-methods-use-this
3036
+ },{key:"getPluginsToLoadBasedOnConfig",value:function getPluginsToLoadBasedOnConfig(){var _this=this;// This contains the default plugins if load option has been omitted by user
3037
+ var pluginsToLoadFromConfig=state.plugins.pluginsToLoadFromConfig.value;if(!pluginsToLoadFromConfig){return [];}// TODO: Uncomment below lines after removing deprecated plugin
3038
+ // Filter deprecated plugins
3039
+ // pluginsToLoadFromConfig = pluginsToLoadFromConfig.filter(pluginName => {
3040
+ // if (deprecatedPluginsList.includes(pluginName)) {
3041
+ // this.logger?.warn(DEPRECATED_PLUGIN_WARNING(PLUGINS_MANAGER, pluginName));
3042
+ // return false;
3043
+ // }
3044
+ // return true;
3045
+ // });
3046
+ var pluginGroupsToProcess=[{configurationStatus:function configurationStatus(){return isDefined(state.dataPlaneEvents.eventsQueuePluginName.value);},configurationStatusStr:'Data plane events delivery is enabled',activePluginName:state.dataPlaneEvents.eventsQueuePluginName.value,supportedPlugins:Object.values(DataPlaneEventsTransportToPluginNameMap),shouldAddMissingPlugins:true},{configurationStatus:function configurationStatus(){return state.reporting.isErrorReportingEnabled.value;},configurationStatusStr:'Error reporting is enabled',supportedPlugins:['ErrorReporting','Bugsnag']// TODO: Remove deprecated plugin- Bugsnag
3047
+ },{configurationStatus:function configurationStatus(){return getNonCloudDestinations(state.nativeDestinations.configuredDestinations.value).length>0;},configurationStatusStr:'Device mode destinations are connected to the source',supportedPlugins:['DeviceModeDestinations','NativeDestinationQueue']},{configurationStatus:function configurationStatus(){return getNonCloudDestinations(state.nativeDestinations.configuredDestinations.value).some(function(destination){return destination.shouldApplyDeviceModeTransformation;});},configurationStatusStr:'Device mode transformations are enabled for at least one destination',supportedPlugins:['DeviceModeTransformation']},{configurationStatus:function configurationStatus(){return isDefined(state.consents.activeConsentManagerPluginName.value);},configurationStatusStr:'Consent management is enabled',activePluginName:state.consents.activeConsentManagerPluginName.value,supportedPlugins:Object.values(ConsentManagersToPluginNameMap)},{configurationStatus:function configurationStatus(){return isDefined(state.storage.encryptionPluginName.value);},configurationStatusStr:'Storage encryption is enabled',activePluginName:state.storage.encryptionPluginName.value,supportedPlugins:Object.values(StorageEncryptionVersionsToPluginNameMap)},{configurationStatus:function configurationStatus(){return state.storage.migrate.value;},configurationStatusStr:'Storage migration is enabled',supportedPlugins:['StorageMigrator']}];var addMissingPlugins=false;pluginGroupsToProcess.forEach(function(group){if(group.configurationStatus()){pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(group.activePluginName?function(pluginName){return !(pluginName!==group.activePluginName&&group.supportedPlugins.includes(pluginName));}:function(pluginName){return isDefined(pluginName);}// pass through
3048
+ );_this.addMissingPlugins(group,addMissingPlugins,pluginsToLoadFromConfig);}else {pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(group.basePlugins!==undefined?function(pluginName){return !(group.basePlugins.includes(pluginName)||group.supportedPlugins.includes(pluginName));}:function(pluginName){return !group.supportedPlugins.includes(pluginName);});}});return [].concat(_toConsumableArray(Object.keys(getMandatoryPluginsMap())),_toConsumableArray(pluginsToLoadFromConfig));}},{key:"addMissingPlugins",value:function addMissingPlugins(group,_addMissingPlugins,pluginsToLoadFromConfig){var shouldAddMissingPlugins=group.shouldAddMissingPlugins||_addMissingPlugins;var pluginsToConfigure;if(group.activePluginName){pluginsToConfigure=[].concat(_toConsumableArray(group.basePlugins||[]),[group.activePluginName]);}else {pluginsToConfigure=_toConsumableArray(group.supportedPlugins);}var missingPlugins=pluginsToConfigure.filter(function(pluginName){return !pluginsToLoadFromConfig.includes(pluginName);});if(missingPlugins.length>0){var _this$logger;if(shouldAddMissingPlugins){pluginsToLoadFromConfig.push.apply(pluginsToLoadFromConfig,_toConsumableArray(missingPlugins));}(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.warn(generateMisconfiguredPluginsWarning(PLUGINS_MANAGER,group.configurationStatusStr,missingPlugins,shouldAddMissingPlugins));}}/**
3049
+ * Determine the list of plugins that should be activated
3050
+ */},{key:"setActivePlugins",value:function setActivePlugins(){var pluginsToLoad=this.getPluginsToLoadBasedOnConfig();// Merging available mandatory and optional plugin name list
3051
+ var availablePlugins=[].concat(_toConsumableArray(Object.keys(pluginsInventory)),_toConsumableArray(pluginNamesList));var activePlugins=[];var failedPlugins=[];pluginsToLoad.forEach(function(pluginName){if(availablePlugins.includes(pluginName)){activePlugins.push(pluginName);}else {failedPlugins.push(pluginName);}});if(failedPlugins.length>0){this.onError(new Error("Ignoring loading of unknown plugins: ".concat(failedPlugins.join(','),". Mandatory plugins: ").concat(Object.keys(getMandatoryPluginsMap()).join(','),". Load option plugins: ").concat(state.plugins.pluginsToLoadFromConfig.value.join(','))));}r(function(){state.plugins.totalPluginsToLoad.value=pluginsToLoad.length;state.plugins.activePlugins.value=activePlugins;state.plugins.failedPlugins.value=failedPlugins;});}/**
3052
+ * Register plugins that are direct imports to PluginEngine
3053
+ */},{key:"registerLocalPlugins",value:function registerLocalPlugins(){var _this2=this;Object.values(pluginsInventory).forEach(function(localPlugin){if(isFunction(localPlugin)&&state.plugins.activePlugins.value.includes(localPlugin().name)){_this2.register([localPlugin()]);}});}/**
3054
+ * Register plugins that are dynamic imports to PluginEngine
3055
+ */},{key:"registerRemotePlugins",value:function registerRemotePlugins(){var _this3=this;var remotePluginsList=remotePluginsInventory(state.plugins.activePlugins.value);Promise.all(Object.keys(remotePluginsList).map(/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(remotePluginKey){return _regeneratorRuntime().wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:_context.next=2;return remotePluginsList[remotePluginKey]().then(function(remotePluginModule){return _this3.register([remotePluginModule.default()]);}).catch(function(err){// TODO: add retry here if dynamic import fails
3056
+ state.plugins.failedPlugins.value=[].concat(_toConsumableArray(state.plugins.failedPlugins.value),[remotePluginKey]);_this3.onError(err,remotePluginKey);});case 2:case"end":return _context.stop();}},_callee);}));return function(_x){return _ref.apply(this,arguments);};}())).catch(function(err){_this3.onError(err);});}/**
3057
+ * Extension point invoke that allows multiple plugins to be registered to it with error handling
3058
+ */},{key:"invokeMultiple",value:function invokeMultiple(extPoint){try{var _this$engine;for(var _len=arguments.length,args=new Array(_len>1?_len-1:0),_key=1;_key<_len;_key++){args[_key-1]=arguments[_key];}return (_this$engine=this.engine).invokeMultiple.apply(_this$engine,[extPoint].concat(args));}catch(e){this.onError(e,extPoint);return [];}}/**
3059
+ * Extension point invoke that allows a single plugin to be registered to it with error handling
3060
+ */},{key:"invokeSingle",value:function invokeSingle(extPoint){try{var _this$engine2;for(var _len2=arguments.length,args=new Array(_len2>1?_len2-1:0),_key2=1;_key2<_len2;_key2++){args[_key2-1]=arguments[_key2];}return (_this$engine2=this.engine).invokeSingle.apply(_this$engine2,[extPoint].concat(args));}catch(e){this.onError(e,extPoint);return null;}}/**
3061
+ * Plugin engine register with error handling
3062
+ */},{key:"register",value:function register(plugins){var _this4=this;plugins.forEach(function(plugin){try{_this4.engine.register(plugin,state);}catch(e){state.plugins.failedPlugins.value=[].concat(_toConsumableArray(state.plugins.failedPlugins.value),[plugin.name]);_this4.onError(e);}});}// TODO: Implement reset API instead
3063
+ },{key:"unregisterLocalPlugins",value:function unregisterLocalPlugins(){var _this5=this;Object.values(pluginsInventory).forEach(function(localPlugin){try{_this5.engine.unregister(localPlugin().name);}catch(e){_this5.onError(e);}});}/**
3064
+ * Handle errors
3065
+ */},{key:"onError",value:function onError(error,customMessage){if(this.errorHandler){this.errorHandler.onError(error,PLUGINS_MANAGER,customMessage);}else {throw error;}}}]);}();
3066
+
3067
+ /**
3068
+ * Utility to parse XHR JSON response
3069
+ */var responseTextToJson=function responseTextToJson(responseText,onError){try{return JSON.parse(responseText||'');}catch(err){var error=getMutatedError(err,'Failed to parse response data');if(isFunction(onError)){onError(error);}else {throw error;}}return undefined;};
3070
+
3071
+ var DEFAULT_XHR_REQUEST_OPTIONS={headers:{Accept:'application/json','Content-Type':'application/json;charset=UTF-8'},method:'GET'};/**
3072
+ * Utility to create request configuration based on default options
3073
+ */var createXhrRequestOptions=function createXhrRequestOptions(url,options,basicAuthHeader){var requestOptions=mergeDeepRight(DEFAULT_XHR_REQUEST_OPTIONS,options||{});if(basicAuthHeader){requestOptions.headers=mergeDeepRight(requestOptions.headers,{Authorization:basicAuthHeader});}requestOptions.url=url;return requestOptions;};/**
3074
+ * Utility implementation of XHR, fetch cannot be used as it requires explicit
3075
+ * origin allowed values and not wildcard for CORS requests with credentials and
3076
+ * this is not supported by our sourceConfig API
3077
+ */var xhrRequest=function xhrRequest(options){var timeout=arguments.length>1&&arguments[1]!==undefined?arguments[1]:DEFAULT_XHR_TIMEOUT_MS;var logger=arguments.length>2?arguments[2]:undefined;return new Promise(function(resolve,reject){var payload;if(options.sendRawData===true){payload=options.data;}else {payload=stringifyWithoutCircular(options.data,false,[],logger);if(isNull(payload)){reject({error:new Error(XHR_PAYLOAD_PREP_ERROR),undefined:undefined,options:options});// return and don't process further if the payload could not be stringified
3078
+ return;}}var xhr=new XMLHttpRequest();// eslint-disable-next-line @typescript-eslint/no-unused-vars
3079
+ var xhrReject=function xhrReject(e){reject({error:new Error(XHR_DELIVERY_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,xhr.status,xhr.statusText,options.url)),xhr:xhr,options:options});};var xhrError=function xhrError(e){reject({error:new Error(XHR_REQUEST_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,e,options.url)),xhr:xhr,options:options});};xhr.ontimeout=xhrError;xhr.onerror=xhrError;xhr.onload=function(){if(xhr.status>=200&&xhr.status<400){resolve({response:xhr.responseText,xhr:xhr,options:options});}else {xhrReject();}};xhr.open(options.method,options.url);if(options.withCredentials===true){xhr.withCredentials=true;}// The timeout property may be set only in the time interval between a call to the open method
3080
+ // and the first call to the send method in legacy browsers
3081
+ xhr.timeout=timeout;Object.keys(options.headers).forEach(function(headerName){if(options.headers[headerName]){xhr.setRequestHeader(headerName,options.headers[headerName]);}});try{xhr.send(payload);}catch(err){reject({error:getMutatedError(err,XHR_SEND_ERROR(FAILED_REQUEST_ERR_MSG_PREFIX,options.url)),xhr:xhr,options:options});}});};
3082
+
3083
+ /**
3084
+ * Service to handle data communication with APIs
3085
+ */var HttpClient=/*#__PURE__*/function(){function HttpClient(errorHandler,logger){_classCallCheck(this,HttpClient);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.hasErrorHandler=Boolean(this.errorHandler);this.onError=this.onError.bind(this);}/**
3086
+ * Implement requests in a blocking way
3087
+ */return _createClass(HttpClient,[{key:"getData",value:(function(){var _getData=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(config){var url,options,timeout,isRawResponse,data,_error;return _regeneratorRuntime().wrap(function _callee$(_context){while(1)switch(_context.prev=_context.next){case 0:url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse;_context.prev=1;_context.next=4;return xhrRequest(createXhrRequestOptions(url,options,this.basicAuthHeader),timeout,this.logger);case 4:data=_context.sent;return _context.abrupt("return",{data:isRawResponse?data.response:responseTextToJson(data.response,this.onError),details:data});case 8:_context.prev=8;_context.t0=_context["catch"](1);this.onError((_error=_context.t0.error)!==null&&_error!==void 0?_error:_context.t0);return _context.abrupt("return",{data:undefined,details:_context.t0});case 12:case"end":return _context.stop();}},_callee,this,[[1,8]]);}));function getData(_x){return _getData.apply(this,arguments);}return getData;}()/**
3088
+ * Implement requests in a non-blocking way
3089
+ */)},{key:"getAsyncData",value:function getAsyncData(config){var _this=this;var callback=config.callback,url=config.url,options=config.options,timeout=config.timeout,isRawResponse=config.isRawResponse;var isFireAndForget=!isFunction(callback);xhrRequest(createXhrRequestOptions(url,options,this.basicAuthHeader),timeout,this.logger).then(function(data){if(!isFireAndForget){callback(isRawResponse?data.response:responseTextToJson(data.response,_this.onError),data);}}).catch(function(data){var _data$error;_this.onError((_data$error=data.error)!==null&&_data$error!==void 0?_data$error:data);if(!isFireAndForget){callback(undefined,data);}});}/**
3090
+ * Handle errors
3091
+ */},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError(error,HTTP_CLIENT);}else {throw error;}}/**
3092
+ * Set basic authentication header (eg writekey)
3093
+ */},{key:"setAuthHeader",value:function setAuthHeader(value){var noBtoa=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var authVal=noBtoa?value:toBase64("".concat(value,":"));this.basicAuthHeader="Basic ".concat(authVal);}/**
3094
+ * Clear basic authentication header
3095
+ */},{key:"resetAuthHeader",value:function resetAuthHeader(){this.basicAuthHeader=undefined;}}]);}();var defaultHttpClient=new HttpClient(defaultErrorHandler,defaultLogger);
3096
+
3097
+ var STORAGE_TEST_COOKIE='test_rudder_cookie';var STORAGE_TEST_LOCAL_STORAGE='test_rudder_ls';var STORAGE_TEST_SESSION_STORAGE='test_rudder_ss';var STORAGE_TEST_TOP_LEVEL_DOMAIN='__tld__';var CLIENT_DATA_STORE_COOKIE='clientDataInCookie';var CLIENT_DATA_STORE_LS='clientDataInLocalStorage';var CLIENT_DATA_STORE_MEMORY='clientDataInMemory';var CLIENT_DATA_STORE_SESSION='clientDataInSessionStorage';var USER_SESSION_KEYS=['userId','userTraits','anonymousId','groupId','groupTraits','initialReferrer','initialReferringDomain','sessionInfo','authToken'];
3098
+
3099
+ var storageClientDataStoreNameMap=_defineProperty(_defineProperty(_defineProperty(_defineProperty({},COOKIE_STORAGE,CLIENT_DATA_STORE_COOKIE),LOCAL_STORAGE,CLIENT_DATA_STORE_LS),MEMORY_STORAGE,CLIENT_DATA_STORE_MEMORY),SESSION_STORAGE,CLIENT_DATA_STORE_SESSION);
3100
+
3101
+ var detectAdBlockers=function detectAdBlockers(errorHandler,logger){// Apparently, '?view=ad' is a query param that is blocked by majority of adblockers
3102
+ // Use source config URL here as it is very unlikely to be blocked by adblockers
3103
+ // Only the extra query param should make it vulnerable to adblockers
3104
+ // This will work even if the users proxies it.
3105
+ // The edge case where this doesn't work is when HEAD method is not allowed by the server (user's)
3106
+ var baseUrl=new URL(state.lifecycle.sourceConfigUrl.value);var url="".concat(baseUrl.origin).concat(baseUrl.pathname,"?view=ad");var httpClient=new HttpClient(errorHandler,logger);httpClient.setAuthHeader(state.lifecycle.writeKey.value);httpClient.getAsyncData({url:url,options:{// We actually don't need the response from the request, so we are using HEAD
3107
+ method:'HEAD',headers:{'Content-Type':undefined}},isRawResponse:true,callback:function callback(result,details){var _details$xhr;// not ad blocked if the request is successful or it is not internally redirected on the client side
3108
+ // Often adblockers instead of blocking the request, they redirect it to an internal URL
3109
+ state.capabilities.isAdBlocked.value=(details===null||details===void 0?void 0:details.error)!==undefined||(details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.responseURL)!==url;}});};
3110
+
3111
+ var hasCrypto=function hasCrypto(){return !isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);};// eslint-disable-next-line compat/compat -- We are checking for the existence of navigator.userAgentData
3112
+ var hasUAClientHints=function hasUAClientHints(){return !isNullOrUndefined(globalThis.navigator.userAgentData);};var hasBeacon=function hasBeacon(){return !isNullOrUndefined(globalThis.navigator.sendBeacon)&&isFunction(globalThis.navigator.sendBeacon);};var isIE11=function isIE11(){return Boolean(globalThis.navigator.userAgent.match(/Trident.*rv:11\./));};
3113
+
3114
+ var getUserAgentClientHint=function getUserAgentClientHint(callback){var level=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'none';if(level==='none'){callback(undefined);}if(level==='default'){callback(navigator.userAgentData);}if(level==='full'){var _navigator$userAgentD;(_navigator$userAgentD=navigator.userAgentData)===null||_navigator$userAgentD===void 0||_navigator$userAgentD.getHighEntropyValues(['architecture','bitness','brands','mobile','model','platform','platformVersion','uaFullVersion','fullVersionList','wow64']).then(function(ua){callback(ua);}).catch(function(){callback();});}};
3115
+
3116
+ var isDatasetAvailable=function isDatasetAvailable(){var testElement=globalThis.document.createElement('div');testElement.setAttribute('data-a-b','c');return testElement.dataset?testElement.dataset.aB==='c':false;};var legacyJSEngineRequiredPolyfills={// Ideally, we should separate the checks for URL and URLSearchParams but
3117
+ // the polyfill service serves them under the same feature name, "URL".
3118
+ URL:function URL(){return !isFunction(globalThis.URL)||!isFunction(globalThis.URLSearchParams);},Promise:function Promise(){return !isFunction(globalThis.Promise);},'Number.isNaN':function NumberIsNaN(){return !isFunction(globalThis.Number.isNaN);},'Number.isInteger':function NumberIsInteger(){return !isFunction(globalThis.Number.isInteger);},'Array.from':function ArrayFrom(){return !isFunction(globalThis.Array.from);},'Array.prototype.find':function ArrayPrototypeFind(){return !isFunction(globalThis.Array.prototype.find);},'Array.prototype.includes':function ArrayPrototypeIncludes(){return !isFunction(globalThis.Array.prototype.includes);},'String.prototype.endsWith':function StringPrototypeEndsWith(){return !isFunction(globalThis.String.prototype.endsWith);},'String.prototype.startsWith':function StringPrototypeStartsWith(){return !isFunction(globalThis.String.prototype.startsWith);},'String.prototype.includes':function StringPrototypeIncludes(){return !isFunction(globalThis.String.prototype.includes);},'String.prototype.replaceAll':function StringPrototypeReplaceAll(){return !isFunction(globalThis.String.prototype.replaceAll);},'String.fromCodePoint':function StringFromCodePoint(){return !isFunction(globalThis.String.fromCodePoint);},'Object.entries':function ObjectEntries(){return !isFunction(globalThis.Object.entries);},'Object.values':function ObjectValues(){return !isFunction(globalThis.Object.values);},'Object.assign':function ObjectAssign(){return !isFunction(globalThis.Object.assign);},'Object.fromEntries':function ObjectFromEntries(){return !isFunction(globalThis.Object.fromEntries);},'Element.prototype.dataset':function ElementPrototypeDataset(){return !isDatasetAvailable();},// Ideally, we should separate the checks for TextEncoder and TextDecoder but
3119
+ // the polyfill service serves them under the same feature name, "TextEncoder".
3120
+ TextEncoder:function TextEncoder(){return !isFunction(globalThis.TextEncoder)||!isFunction(globalThis.TextDecoder);},requestAnimationFrame:function requestAnimationFrame(){return !isFunction(globalThis.requestAnimationFrame)||!isFunction(globalThis.cancelAnimationFrame);},CustomEvent:function CustomEvent(){return !isFunction(globalThis.CustomEvent);},'navigator.sendBeacon':function navigatorSendBeacon(){return !isFunction(globalThis.navigator.sendBeacon);},// Note, the polyfill service serves both ArrayBuffer and Uint8Array under the same feature name, "ArrayBuffer".
3121
+ ArrayBuffer:function ArrayBuffer(){return !isFunction(globalThis.Uint8Array);},Set:function Set(){return !isFunction(globalThis.Set);},atob:function atob(){return !isFunction(globalThis.atob);}};var isLegacyJSEngine=function isLegacyJSEngine(){var requiredCapabilitiesList=Object.keys(legacyJSEngineRequiredPolyfills);var needsPolyfill=false;/* eslint-disable-next-line unicorn/no-for-loop */for(var i=0;i<requiredCapabilitiesList.length;i++){var isCapabilityMissing=legacyJSEngineRequiredPolyfills[requiredCapabilitiesList[i]];if(isFunction(isCapabilityMissing)&&isCapabilityMissing()){needsPolyfill=true;break;}}return needsPolyfill;};
3122
+
3123
+ var getScreenDetails=function getScreenDetails(){var screenDetails={density:0,width:0,height:0,innerWidth:0,innerHeight:0};screenDetails={width:globalThis.screen.width,height:globalThis.screen.height,density:globalThis.devicePixelRatio,innerWidth:globalThis.innerWidth,innerHeight:globalThis.innerHeight};return screenDetails;};
3124
+
3125
+ var isStorageQuotaExceeded=function isStorageQuotaExceeded(e){var matchingNames=['QuotaExceededError','NS_ERROR_DOM_QUOTA_REACHED'];// [everything except Firefox, Firefox]
3126
+ var matchingCodes=[22,1014];// [everything except Firefox, Firefox]
3127
+ var isQuotaExceededError=matchingNames.includes(e.name)||matchingCodes.includes(e.code);return e instanceof DOMException&&isQuotaExceededError;};// TODO: also check for SecurityErrors
3128
+ // https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage#exceptions
3129
+ var isStorageAvailable=function isStorageAvailable(){var type=arguments.length>0&&arguments[0]!==undefined?arguments[0]:LOCAL_STORAGE;var storageInstance=arguments.length>1?arguments[1]:undefined;var logger=arguments.length>2?arguments[2]:undefined;var storage;var testData;try{switch(type){case MEMORY_STORAGE:return true;case COOKIE_STORAGE:storage=storageInstance;testData=STORAGE_TEST_COOKIE;break;case LOCAL_STORAGE:storage=storageInstance!==null&&storageInstance!==void 0?storageInstance:globalThis.localStorage;testData=STORAGE_TEST_LOCAL_STORAGE;// was STORAGE_TEST_LOCAL_STORAGE in ours and generateUUID() in segment retry one
3130
+ break;case SESSION_STORAGE:storage=storageInstance!==null&&storageInstance!==void 0?storageInstance:globalThis.sessionStorage;testData=STORAGE_TEST_SESSION_STORAGE;break;default:return false;}if(!storage){return false;}storage.setItem(testData,'true');if(storage.getItem(testData)){storage.removeItem(testData);return true;}return false;}catch(err){var msgPrefix=STORAGE_UNAVAILABILITY_ERROR_PREFIX(CAPABILITIES_MANAGER,type);var reason='unavailable';if(isStorageQuotaExceeded(err)){reason='full';}logger===null||logger===void 0||logger.warn("".concat(msgPrefix).concat(reason,"."),err);return false;}};
3131
+
3132
+ var legacyGetHostname=function legacyGetHostname(href){var l=document.createElement('a');l.href=href;return l.hostname;};/**
3133
+ * Levels returns all levels of the given url
3134
+ *
3135
+ * The method returns an empty array when the hostname is an ip.
3136
+ */var levelsFunc=function levelsFunc(url){var _host$split;// This is called before the polyfills load thus new URL cannot be used
3137
+ var host=typeof globalThis.URL!=='function'?legacyGetHostname(url):new URL(url).hostname;var parts=(_host$split=host===null||host===void 0?void 0:host.split('.'))!==null&&_host$split!==void 0?_host$split:[];var last=parts[parts.length-1];var levels=[];// Ip address.
3138
+ if(parts.length===4&&last&&last===parseInt(last,10).toString()){return levels;}// Localhost.
3139
+ if(parts.length<=1){// Fix to support localhost
3140
+ if(parts[0]&&parts[0].indexOf('localhost')!==-1){return ['localhost'];}return levels;}// Create levels.
3141
+ for(var i=parts.length-2;i>=0;i-=1){levels.push(parts.slice(i).join('.'));}return levels;};/**
3142
+ * Get the top domain.
3143
+ *
3144
+ * The function constructs the levels of domain and attempts to set a global
3145
+ * cookie on each one when it succeeds it returns the top level domain.
3146
+ *
3147
+ * The method returns an empty string when the hostname is an ip.
3148
+ */var domain=function domain(url){var levels=levelsFunc(url);// Lookup the real top level one.
3149
+ // eslint-disable-next-line unicorn/no-for-loop
3150
+ for(var i=0;i<levels.length;i+=1){var _domain=levels[i];var cname=STORAGE_TEST_TOP_LEVEL_DOMAIN;var opts={domain:"".concat(_domain.indexOf('localhost')!==-1?'':'.').concat(_domain)};// Set cookie on domain
3151
+ cookie(cname,1,opts);// If successful
3152
+ if(cookie(cname)){// Remove cookie from domain
3153
+ cookie(cname,null,opts);return _domain;}}return '';};
3154
+
3155
+ var getDefaultCookieOptions=function getDefaultCookieOptions(){var topDomain=".".concat(domain(globalThis.location.href));return {maxage:DEFAULT_COOKIE_MAX_AGE_MS,path:'/',domain:!topDomain||topDomain==='.'?undefined:topDomain,samesite:'Lax',enabled:true};};var getDefaultLocalStorageOptions=function getDefaultLocalStorageOptions(){return {enabled:true};};var getDefaultSessionStorageOptions=function getDefaultSessionStorageOptions(){return {enabled:true};};var getDefaultInMemoryStorageOptions=function getDefaultInMemoryStorageOptions(){return {enabled:true};};
3156
+
3157
+ /**
3158
+ * A storage utility to persist values in cookies via Storage interface
3159
+ */var CookieStorage=/*#__PURE__*/function(){function CookieStorage(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var logger=arguments.length>1?arguments[1]:undefined;_classCallCheck(this,CookieStorage);_defineProperty(this,"isSupportAvailable",true);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);if(CookieStorage.globalSingleton){// eslint-disable-next-line no-constructor-return
3160
+ return CookieStorage.globalSingleton;}this.options=getDefaultCookieOptions();this.logger=logger;this.configure(options);CookieStorage.globalSingleton=this;}return _createClass(CookieStorage,[{key:"configure",value:function configure(options){var _this$options;this.options=mergeDeepRight((_this$options=this.options)!==null&&_this$options!==void 0?_this$options:{},options);if(options.sameDomainCookiesOnly){delete this.options.domain;}this.isSupportAvailable=isStorageAvailable(COOKIE_STORAGE,this,this.logger);this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}},{key:"setItem",value:function setItem(key,value){cookie(key,value,this.options,this.logger);this.length=Object.keys(cookie()).length;return true;}// eslint-disable-next-line class-methods-use-this
3161
+ },{key:"getItem",value:function getItem(key){var value=cookie(key);return isUndefined(value)?null:value;}},{key:"removeItem",value:function removeItem(key){var result=this.setItem(key,null);this.length=Object.keys(cookie()).length;return result;}// eslint-disable-next-line class-methods-use-this
3162
+ },{key:"clear",value:function clear(){// Not implemented
3163
+ // getting a list of all cookie storage keys and remove all values
3164
+ // sounds risky to do as it will take on all top domain cookies
3165
+ // better to explicitly clear specific ones if needed
3166
+ }},{key:"key",value:function key(index){var _curKeys$index;var curKeys=this.keys();return (_curKeys$index=curKeys[index])!==null&&_curKeys$index!==void 0?_curKeys$index:null;}// eslint-disable-next-line class-methods-use-this
3167
+ },{key:"keys",value:function keys(){return Object.keys(cookie());}}]);}();_defineProperty(CookieStorage,"globalSingleton",null);
3168
+
3169
+ /**
3170
+ * A storage utility to retain values in memory via Storage interface
3171
+ */var InMemoryStorage=/*#__PURE__*/function(){function InMemoryStorage(options,logger){_classCallCheck(this,InMemoryStorage);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);_defineProperty(this,"data",{});this.options=getDefaultInMemoryStorageOptions();this.logger=logger;this.configure(options!==null&&options!==void 0?options:{});}return _createClass(InMemoryStorage,[{key:"configure",value:function configure(options){this.options=mergeDeepRight(this.options,options);this.isEnabled=Boolean(this.options.enabled);return this.options;}},{key:"setItem",value:function setItem(key,value){this.data[key]=value;this.length=Object.keys(this.data).length;return value;}},{key:"getItem",value:function getItem(key){if(key in this.data){return this.data[key];}return null;}},{key:"removeItem",value:function removeItem(key){if(key in this.data){delete this.data[key];}this.length=Object.keys(this.data).length;return null;}},{key:"clear",value:function clear(){this.data={};this.length=0;}},{key:"key",value:function key(index){var _curKeys$index;var curKeys=this.keys();return (_curKeys$index=curKeys[index])!==null&&_curKeys$index!==void 0?_curKeys$index:null;}},{key:"keys",value:function keys(){return Object.keys(this.data);}}]);}();var defaultInMemoryStorage=new InMemoryStorage({},defaultLogger);
3172
+
3173
+ var store$1 = {exports: {}};
3174
+
3175
+ (function(module,exports){(function(global,factory){module.exports=factory();})(commonjsGlobal,function(){function isJSON(obj){obj=JSON.stringify(obj);if(!/^\{[\s\S]*\}$/.test(obj)){return false;}return true;}function stringify(val){return val===undefined||typeof val==="function"?val+'':JSON.stringify(val);}function deserialize(value){if(typeof value!=='string'){return undefined;}try{return JSON.parse(value);}catch(e){return value;}}function isFunction(value){return {}.toString.call(value)==="[object Function]";}function isArray(value){return Object.prototype.toString.call(value)==="[object Array]";}// https://github.com/jaywcjlove/store.js/pull/8
3176
+ // Error: QuotaExceededError
3177
+ function dealIncognito(storage){var _KEY='_Is_Incognit',_VALUE='yes';try{// NOTE: set default storage when not passed in
3178
+ if(!storage){storage=window.localStorage;}storage.setItem(_KEY,_VALUE);storage.removeItem(_KEY);}catch(e){var inMemoryStorage={};inMemoryStorage._data={};inMemoryStorage.setItem=function(id,val){return inMemoryStorage._data[id]=String(val);};inMemoryStorage.getItem=function(id){return inMemoryStorage._data.hasOwnProperty(id)?inMemoryStorage._data[id]:undefined;};inMemoryStorage.removeItem=function(id){return delete inMemoryStorage._data[id];};inMemoryStorage.clear=function(){return inMemoryStorage._data={};};storage=inMemoryStorage;}finally{if(storage.getItem(_KEY)===_VALUE)storage.removeItem(_KEY);}return storage;}// deal QuotaExceededError if user use incognito mode in browser
3179
+ var storage=dealIncognito();function Store(){if(!(this instanceof Store)){return new Store();}}Store.prototype={set:function set(key,val){if(key&&!isJSON(key)){storage.setItem(key,stringify(val));}else if(isJSON(key)){for(var a in key)this.set(a,key[a]);}return this;},get:function get(key){// Return all entries if no key
3180
+ if(key===undefined){var ret={};this.forEach(function(key,val){return ret[key]=val;});return ret;}if(key.charAt(0)==='?'){return this.has(key.substr(1));}var args=arguments;if(args.length>1){var dt={};for(var i=0,len=args.length;i<len;i++){var value=deserialize(storage.getItem(args[i]));if(this.has(args[i])){dt[args[i]]=value;}}return dt;}return deserialize(storage.getItem(key));},clear:function clear(){storage.clear();return this;},remove:function remove(key){var val=this.get(key);storage.removeItem(key);return val;},has:function has(key){return {}.hasOwnProperty.call(this.get(),key);},keys:function keys(){var d=[];this.forEach(function(k){d.push(k);});return d;},forEach:function forEach(callback){for(var i=0,len=storage.length;i<len;i++){var key=storage.key(i);callback(key,this.get(key));}return this;},search:function search(str){var arr=this.keys(),dt={};for(var i=0,len=arr.length;i<len;i++){if(arr[i].indexOf(str)>-1)dt[arr[i]]=this.get(arr[i]);}return dt;},len:function len(){return storage.length;}};var _Store=null;function store(key,data){var argm=arguments;var dt=null;if(!_Store)_Store=Store();if(argm.length===0)return _Store.get();if(argm.length===1){if(typeof key==="string")return _Store.get(key);if(isJSON(key))return _Store.set(key);}if(argm.length===2&&typeof key==="string"){if(!data)return _Store.remove(key);if(data&&typeof data==="string")return _Store.set(key,data);if(data&&isFunction(data)){dt=null;dt=data(key,_Store.get(key));store.set(key,dt);}}if(argm.length===2&&isArray(key)&&isFunction(data)){for(var i=0,len=key.length;i<len;i++){dt=data(key[i],_Store.get(key[i]));store.set(key[i],dt);}}return store;}for(var a in Store.prototype)store[a]=Store.prototype[a];return store;});})(store$1);var storeExports=store$1.exports;var store = /*@__PURE__*/getDefaultExportFromCjs(storeExports);
3181
+
3182
+ // check if the get, set overloads and search methods are used at all
3183
+ // if we do, ensure we provide types to support overloads as per storejs docs
3184
+ // https://www.npmjs.com/package/storejs
3185
+ /**
3186
+ * A storage utility to persist values in localstorage via Storage interface
3187
+ */var LocalStorage=/*#__PURE__*/function(){function LocalStorage(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var logger=arguments.length>1?arguments[1]:undefined;_classCallCheck(this,LocalStorage);_defineProperty(this,"isSupportAvailable",true);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);this.options=getDefaultLocalStorageOptions();this.logger=logger;this.configure(options);}return _createClass(LocalStorage,[{key:"configure",value:function configure(options){this.options=mergeDeepRight(this.options,options);this.isSupportAvailable=isStorageAvailable(LOCAL_STORAGE,this,this.logger);this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}},{key:"setItem",value:function setItem(key,value){store.set(key,value);this.length=store.len();}// eslint-disable-next-line class-methods-use-this
3188
+ },{key:"getItem",value:function getItem(key){var value=store.get(key);return isUndefined(value)?null:value;}},{key:"removeItem",value:function removeItem(key){store.remove(key);this.length=store.len();}},{key:"clear",value:function clear(){store.clear();this.length=0;}},{key:"key",value:function key(index){var _curKeys$index;var curKeys=this.keys();return (_curKeys$index=curKeys[index])!==null&&_curKeys$index!==void 0?_curKeys$index:null;}// eslint-disable-next-line class-methods-use-this
3189
+ },{key:"keys",value:function keys(){return store.keys();}}]);}();var defaultLocalStorage=new LocalStorage({},defaultLogger);
3190
+
3191
+ /**
3192
+ * A storage utility to persist values in SessionStorage via Storage interface
3193
+ */var SessionStorage=/*#__PURE__*/function(){function SessionStorage(){var options=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var logger=arguments.length>1?arguments[1]:undefined;_classCallCheck(this,SessionStorage);_defineProperty(this,"isSupportAvailable",true);_defineProperty(this,"isEnabled",true);_defineProperty(this,"length",0);_defineProperty(this,"store",globalThis.sessionStorage);this.options=getDefaultSessionStorageOptions();this.logger=logger;this.configure(options);}return _createClass(SessionStorage,[{key:"configure",value:function configure(options){this.options=mergeDeepRight(this.options,options);this.isSupportAvailable=isStorageAvailable(SESSION_STORAGE,this,this.logger);this.isEnabled=Boolean(this.options.enabled&&this.isSupportAvailable);return this.options;}},{key:"setItem",value:function setItem(key,value){this.store.setItem(key,value);this.length=this.store.length;}},{key:"getItem",value:function getItem(key){var value=this.store.getItem(key);return isUndefined(value)?null:value;}},{key:"removeItem",value:function removeItem(key){this.store.removeItem(key);this.length=this.store.length;}},{key:"clear",value:function clear(){this.store.clear();this.length=0;}},{key:"key",value:function key(index){return this.store.key(index);}},{key:"keys",value:function keys(){var keys=[];for(var i=0;i<this.store.length;i+=1){var key=this.store.key(i);if(key!==null){keys.push(key);}}return keys;}}]);}();var defaultSessionStorage=new SessionStorage({},defaultLogger);
3194
+
3195
+ /**
3196
+ * A utility to retrieve the storage singleton instance by type
3197
+ */var getStorageEngine=function getStorageEngine(type){switch(type){case LOCAL_STORAGE:return defaultLocalStorage;case SESSION_STORAGE:return defaultSessionStorage;case MEMORY_STORAGE:return defaultInMemoryStorage;case COOKIE_STORAGE:return new CookieStorage({},defaultLogger);default:return defaultInMemoryStorage;}};/**
3198
+ * Configure cookie storage singleton
3199
+ */var configureCookieStorageEngine=function configureCookieStorageEngine(options){var cookieStorageOptions=new CookieStorage({},defaultLogger).configure(options);state.storage.cookie.value={maxage:cookieStorageOptions.maxage,path:cookieStorageOptions.path,domain:cookieStorageOptions.domain,samesite:cookieStorageOptions.samesite,expires:cookieStorageOptions.expires,secure:cookieStorageOptions.secure};};/**
3200
+ * Configure local storage singleton
3201
+ */var configureLocalStorageEngine=function configureLocalStorageEngine(options){defaultLocalStorage.configure(options);};/**
3202
+ * Configure in memory storage singleton
3203
+ */var configureInMemoryStorageEngine=function configureInMemoryStorageEngine(options){defaultInMemoryStorage.configure(options);};/**
3204
+ * Configure session storage singleton
3205
+ */var configureSessionStorageEngine=function configureSessionStorageEngine(options){defaultSessionStorage.configure(options);};/**
3206
+ * Configure all storage singleton instances
3207
+ */var configureStorageEngines=function configureStorageEngines(){var cookieStorageOptions=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};var localStorageOptions=arguments.length>1&&arguments[1]!==undefined?arguments[1]:{};var inMemoryStorageOptions=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};var sessionStorageOptions=arguments.length>3&&arguments[3]!==undefined?arguments[3]:{};configureCookieStorageEngine(cookieStorageOptions);configureLocalStorageEngine(localStorageOptions);configureInMemoryStorageEngine(inMemoryStorageOptions);configureSessionStorageEngine(sessionStorageOptions);};
3208
+
3209
+ /**
3210
+ * Store Implementation with dedicated storage
3211
+ */var Store=/*#__PURE__*/function(){function Store(config,engine,pluginsManager){var _config$isEncrypted,_config$validKeys,_config$errorHandler,_config$logger;_classCallCheck(this,Store);_defineProperty(this,"hasErrorHandler",false);this.id=config.id;this.name=config.name;this.isEncrypted=(_config$isEncrypted=config.isEncrypted)!==null&&_config$isEncrypted!==void 0?_config$isEncrypted:false;this.validKeys=(_config$validKeys=config.validKeys)!==null&&_config$validKeys!==void 0?_config$validKeys:{};this.engine=engine!==null&&engine!==void 0?engine:getStorageEngine(LOCAL_STORAGE);this.noKeyValidation=Object.keys(this.validKeys).length===0;this.noCompoundKey=config.noCompoundKey;this.originalEngine=this.engine;this.errorHandler=(_config$errorHandler=config.errorHandler)!==null&&_config$errorHandler!==void 0?_config$errorHandler:defaultErrorHandler;this.hasErrorHandler=Boolean(this.errorHandler);this.logger=(_config$logger=config.logger)!==null&&_config$logger!==void 0?_config$logger:defaultLogger;this.pluginsManager=pluginsManager;}/**
3212
+ * Ensure the key is valid and with correct format
3213
+ */return _createClass(Store,[{key:"createValidKey",value:function createValidKey(key){var name=this.name,id=this.id,validKeys=this.validKeys,noKeyValidation=this.noKeyValidation,noCompoundKey=this.noCompoundKey;if(noKeyValidation){return noCompoundKey?key:[name,id,key].join('.');}// validate and return undefined if invalid key
3214
+ var compoundKey;Object.values(validKeys).forEach(function(validKeyName){if(validKeyName===key){compoundKey=noCompoundKey?key:[name,id,key].join('.');}});return compoundKey;}/**
3215
+ * Switch to inMemoryEngine, bringing any existing data with.
3216
+ */},{key:"swapQueueStoreToInMemoryEngine",value:function swapQueueStoreToInMemoryEngine(){var _this=this;var name=this.name,id=this.id,validKeys=this.validKeys,noCompoundKey=this.noCompoundKey;var inMemoryStorage=getStorageEngine(MEMORY_STORAGE);// grab existing data, but only for this page's queue instance, not all
3217
+ // better to keep other queues in localstorage to be flushed later
3218
+ // than to pull them into memory and remove them from durable storage
3219
+ Object.keys(validKeys).forEach(function(key){var value=_this.get(validKeys[key]);var validKey=noCompoundKey?key:[name,id,key].join('.');inMemoryStorage.setItem(validKey,value);// TODO: are we sure we want to drop clientData
3220
+ // if cookies are not available and localstorage is full?
3221
+ _this.remove(key);});this.engine=inMemoryStorage;}/**
3222
+ * Set value by key.
3223
+ */},{key:"set",value:function set(key,value){var validKey=this.createValidKey(key);if(!validKey){return;}try{// storejs that is used in localstorage engine already stringifies json
3224
+ this.engine.setItem(validKey,this.encrypt(stringifyWithoutCircular(value,false,[],this.logger)));}catch(err){if(isStorageQuotaExceeded(err)){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.warn(STORAGE_QUOTA_EXCEEDED_WARNING("Store ".concat(this.id)));// switch to inMemory engine
3225
+ this.swapQueueStoreToInMemoryEngine();// and save it there
3226
+ this.set(key,value);}else {this.onError(getMutatedError(err,STORE_DATA_SAVE_ERROR(key)));}}}/**
3227
+ * Get by Key.
3228
+ */},{key:"get",value:function get(key){var validKey=this.createValidKey(key);try{if(!validKey){return null;}var str=this.decrypt(this.engine.getItem(validKey));if(isNullOrUndefined(str)){return null;}// storejs that is used in localstorage engine already deserializes json strings but swallows errors
3229
+ return JSON.parse(str);}catch(err){this.onError(new Error("".concat(STORE_DATA_FETCH_ERROR(key),": ").concat(err.message)));return null;}}/**
3230
+ * Remove by Key.
3231
+ */},{key:"remove",value:function remove(key){var validKey=this.createValidKey(key);if(validKey){this.engine.removeItem(validKey);}}/**
3232
+ * Get original engine
3233
+ */},{key:"getOriginalEngine",value:function getOriginalEngine(){return this.originalEngine;}/**
3234
+ * Decrypt values
3235
+ */},{key:"decrypt",value:function decrypt(value){if(isNullOrUndefined(value)){return null;}return this.crypto(value,'decrypt');}/**
3236
+ * Encrypt value
3237
+ */},{key:"encrypt",value:function encrypt(value){return this.crypto(value,'encrypt');}/**
3238
+ * Extension point to use with encryption plugins
3239
+ */},{key:"crypto",value:function crypto(value,mode){var noEncryption=!this.isEncrypted||!value||typeof value!=='string'||trim(value)==='';if(noEncryption){return value;}var extensionPointName="storage.".concat(mode);var formattedValue=this.pluginsManager?this.pluginsManager.invokeSingle(extensionPointName,value):value;return typeof formattedValue==='undefined'?value:formattedValue!==null&&formattedValue!==void 0?formattedValue:'';}/**
3240
+ * Handle errors
3241
+ */},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError(error,"Store ".concat(this.id));}else {throw error;}}}]);}();
3242
+
3243
+ var getStorageTypeFromPreConsentIfApplicable=function getStorageTypeFromPreConsentIfApplicable(state,sessionKey){var overriddenStorageType;if(state.consents.preConsent.value.enabled){var _state$consents$preCo;switch((_state$consents$preCo=state.consents.preConsent.value.storage)===null||_state$consents$preCo===void 0?void 0:_state$consents$preCo.strategy){case'none':overriddenStorageType=NO_STORAGE;break;case'session':if(sessionKey!=='sessionInfo'){overriddenStorageType=NO_STORAGE;}break;case'anonymousId':if(sessionKey!=='anonymousId'){overriddenStorageType=NO_STORAGE;}break;}}return overriddenStorageType;};
3244
+
3245
+ /**
3246
+ * A service to manage stores & available storage client configurations
3247
+ */var StoreManager=/*#__PURE__*/function(){function StoreManager(pluginsManager,errorHandler,logger){_classCallCheck(this,StoreManager);_defineProperty(this,"stores",{});_defineProperty(this,"isInitialized",false);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.hasErrorHandler=Boolean(this.errorHandler);this.pluginsManager=pluginsManager;this.onError=this.onError.bind(this);}/**
3248
+ * Configure available storage client instances
3249
+ */return _createClass(StoreManager,[{key:"init",value:function init(){var _config$cookieStorage,_state$storage$cookie,_state$storage$cookie2;if(this.isInitialized){return;}var loadOptions=state.loadOptions.value;var config={cookieStorageOptions:{samesite:loadOptions.sameSiteCookie,secure:loadOptions.secureCookie,domain:loadOptions.setCookieDomain,sameDomainCookiesOnly:loadOptions.sameDomainCookiesOnly,enabled:true},localStorageOptions:{enabled:true},inMemoryStorageOptions:{enabled:true},sessionStorageOptions:{enabled:true}};configureStorageEngines(removeUndefinedValues(mergeDeepRight((_config$cookieStorage=config.cookieStorageOptions)!==null&&_config$cookieStorage!==void 0?_config$cookieStorage:{},(_state$storage$cookie=(_state$storage$cookie2=state.storage.cookie)===null||_state$storage$cookie2===void 0?void 0:_state$storage$cookie2.value)!==null&&_state$storage$cookie!==void 0?_state$storage$cookie:{})),removeUndefinedValues(config.localStorageOptions),removeUndefinedValues(config.inMemoryStorageOptions),removeUndefinedValues(config.sessionStorageOptions));this.initClientDataStores();this.isInitialized=true;}/**
3250
+ * Create store to persist data used by the SDK like session, used details etc
3251
+ */},{key:"initClientDataStores",value:function initClientDataStores(){var _this=this;this.initializeStorageState();// TODO: fill in extra config values and bring them in from StoreManagerOptions if needed
3252
+ // TODO: should we pass the keys for all in order to validate or leave free as v1.1?
3253
+ // Initializing all the enabled store because previous user data might be in different storage
3254
+ // that needs auto migration
3255
+ var storageTypes=[MEMORY_STORAGE,LOCAL_STORAGE,COOKIE_STORAGE,SESSION_STORAGE];storageTypes.forEach(function(storageType){var _getStorageEngine;if((_getStorageEngine=getStorageEngine(storageType))!==null&&_getStorageEngine!==void 0&&_getStorageEngine.isEnabled){_this.setStore({id:storageClientDataStoreNameMap[storageType],name:storageClientDataStoreNameMap[storageType],isEncrypted:true,noCompoundKey:true,type:storageType});}});}},{key:"initializeStorageState",value:function initializeStorageState(){var _state$loadOptions$va,_this2=this;var globalStorageType=state.storage.type.value;var entriesOptions=(_state$loadOptions$va=state.loadOptions.value.storage)===null||_state$loadOptions$va===void 0?void 0:_state$loadOptions$va.entries;// Use the storage options from post consent if anything is defined
3256
+ var postConsentStorageOpts=state.consents.postConsent.value.storage;if(isDefined(postConsentStorageOpts===null||postConsentStorageOpts===void 0?void 0:postConsentStorageOpts.type)||isDefined(postConsentStorageOpts===null||postConsentStorageOpts===void 0?void 0:postConsentStorageOpts.entries)){globalStorageType=postConsentStorageOpts===null||postConsentStorageOpts===void 0?void 0:postConsentStorageOpts.type;entriesOptions=postConsentStorageOpts===null||postConsentStorageOpts===void 0?void 0:postConsentStorageOpts.entries;}var trulyAnonymousTracking=true;var storageEntries={};USER_SESSION_KEYS.forEach(function(sessionKey){var _entriesOptions,_ref,_ref2;var key=sessionKey;var storageKey=sessionKey;var configuredStorageType=(_entriesOptions=entriesOptions)===null||_entriesOptions===void 0||(_entriesOptions=_entriesOptions[key])===null||_entriesOptions===void 0?void 0:_entriesOptions.type;var preConsentStorageType=getStorageTypeFromPreConsentIfApplicable(state,sessionKey);// Storage type precedence order: pre-consent strategy > entry type > global type > default
3257
+ var storageType=(_ref=(_ref2=preConsentStorageType!==null&&preConsentStorageType!==void 0?preConsentStorageType:configuredStorageType)!==null&&_ref2!==void 0?_ref2:globalStorageType)!==null&&_ref!==void 0?_ref:DEFAULT_STORAGE_TYPE;var finalStorageType=_this2.getResolvedStorageTypeForEntry(storageType,sessionKey);if(finalStorageType!==NO_STORAGE){trulyAnonymousTracking=false;}storageEntries=_objectSpread2(_objectSpread2({},storageEntries),{},_defineProperty({},sessionKey,{type:finalStorageType,key:COOKIE_KEYS[storageKey]}));});r(function(){state.storage.type.value=globalStorageType;state.storage.entries.value=storageEntries;state.storage.trulyAnonymousTracking.value=trulyAnonymousTracking;});}},{key:"getResolvedStorageTypeForEntry",value:function getResolvedStorageTypeForEntry(storageType,sessionKey){var _getStorageEngine2,_getStorageEngine3,_getStorageEngine4,_getStorageEngine5,_getStorageEngine6;var finalStorageType=storageType;switch(storageType){case LOCAL_STORAGE:if(!((_getStorageEngine2=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine2!==void 0&&_getStorageEngine2.isEnabled)){finalStorageType=MEMORY_STORAGE;}break;case SESSION_STORAGE:if(!((_getStorageEngine3=getStorageEngine(SESSION_STORAGE))!==null&&_getStorageEngine3!==void 0&&_getStorageEngine3.isEnabled)){finalStorageType=MEMORY_STORAGE;}break;case MEMORY_STORAGE:case NO_STORAGE:break;case COOKIE_STORAGE:default:// First try setting the storage to cookie else to local storage
3258
+ if((_getStorageEngine4=getStorageEngine(COOKIE_STORAGE))!==null&&_getStorageEngine4!==void 0&&_getStorageEngine4.isEnabled){finalStorageType=COOKIE_STORAGE;}else if((_getStorageEngine5=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine5!==void 0&&_getStorageEngine5.isEnabled){finalStorageType=LOCAL_STORAGE;}else if((_getStorageEngine6=getStorageEngine(SESSION_STORAGE))!==null&&_getStorageEngine6!==void 0&&_getStorageEngine6.isEnabled){finalStorageType=SESSION_STORAGE;}else {finalStorageType=MEMORY_STORAGE;}break;}if(finalStorageType!==storageType){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.warn(STORAGE_UNAVAILABLE_WARNING(STORE_MANAGER,sessionKey,storageType,finalStorageType));}return finalStorageType;}/**
3259
+ * Create a new store
3260
+ */},{key:"setStore",value:function setStore(storeConfig){var storageEngine=getStorageEngine(storeConfig.type);this.stores[storeConfig.id]=new Store(storeConfig,storageEngine,this.pluginsManager);return this.stores[storeConfig.id];}/**
3261
+ * Retrieve a store
3262
+ */},{key:"getStore",value:function getStore(id){return this.stores[id];}/**
3263
+ * Handle errors
3264
+ */},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError(error,STORE_MANAGER);}else {throw error;}}}]);}();
3265
+
3266
+ var validateWriteKey=function validateWriteKey(writeKey){if(!isString(writeKey)||writeKey.trim().length===0){throw new Error(WRITE_KEY_VALIDATION_ERROR(writeKey));}};var validateDataPlaneUrl=function validateDataPlaneUrl(dataPlaneUrl){if(!isValidURL(dataPlaneUrl)){throw new Error(DATA_PLANE_URL_VALIDATION_ERROR(dataPlaneUrl));}};var validateLoadArgs=function validateLoadArgs(writeKey,dataPlaneUrl){validateWriteKey(writeKey);validateDataPlaneUrl(dataPlaneUrl);};var isValidSourceConfig=function isValidSourceConfig(res){return isObjectLiteralAndNotNull(res)&&isObjectLiteralAndNotNull(res.source)&&!isNullOrUndefined(res.source.id)&&isObjectLiteralAndNotNull(res.source.config)&&Array.isArray(res.source.destinations);};var isValidStorageType=function isValidStorageType(storageType){return typeof storageType==='string'&&SUPPORTED_STORAGE_TYPES.includes(storageType);};var getTopDomain=function getTopDomain(url){// Create a URL object
3267
+ var urlObj=new URL(url);// Extract the host and protocol
3268
+ var host=urlObj.host,protocol=urlObj.protocol;// Split the host into parts
3269
+ var parts=host.split('.');var topDomain;// Handle different cases, especially for co.uk or similar TLDs
3270
+ if(parts.length>2){// Join the last two parts for the top-level domain
3271
+ topDomain="".concat(parts[parts.length-2],".").concat(parts[parts.length-1]);}else {// If only two parts or less, return as it is
3272
+ topDomain=host;}return {topDomain:topDomain,protocol:protocol};};var getTopDomainUrl=function getTopDomainUrl(url){var _getTopDomain=getTopDomain(url),topDomain=_getTopDomain.topDomain,protocol=_getTopDomain.protocol;return "".concat(protocol,"//").concat(topDomain);};var getDataServiceUrl=function getDataServiceUrl(endpoint,useExactDomain){var url=useExactDomain?window.location.origin:getTopDomainUrl(window.location.href);var formattedEndpoint=endpoint.startsWith('/')?endpoint.substring(1):endpoint;return "".concat(url,"/").concat(formattedEndpoint);};var isWebpageTopLevelDomain=function isWebpageTopLevelDomain(providedDomain){var _getTopDomain2=getTopDomain(window.location.href),topDomain=_getTopDomain2.topDomain;return topDomain===providedDomain;};
3273
+
3274
+ /**
3275
+ * A function to filter enabled destinations and map to required properties only
3276
+ * @param destinations
3277
+ *
3278
+ * @returns Destination[]
3279
+ */var filterEnabledDestination=function filterEnabledDestination(destinations){var nativeDestinations=[];destinations.forEach(function(destination){if(destination.enabled&&!destination.deleted){nativeDestinations.push({id:destination.id,displayName:destination.destinationDefinition.displayName,config:destination.config,shouldApplyDeviceModeTransformation:destination.shouldApplyDeviceModeTransformation||false,propagateEventsUntransformedOnError:destination.propagateEventsUntransformedOnError||false,userFriendlyId:"".concat(destination.destinationDefinition.displayName.replaceAll(' ','-'),"___").concat(destination.id)});}});return nativeDestinations;};
3280
+
3281
+ /**
3282
+ * Removes trailing slash from url
3283
+ * @param url
3284
+ * @returns url
3285
+ */var removeTrailingSlashes=function removeTrailingSlashes(url){return url!==null&&url!==void 0&&url.endsWith('/')?removeTrailingSlashes(url.substring(0,url.length-1)):url;};var getDomain=function getDomain(url){try{var urlObj=new URL(url);return urlObj.host;}catch(error){return null;}};/**
3286
+ * Get the referring domain from the referrer URL
3287
+ * @param referrer Page referrer
3288
+ * @returns Page referring domain
3289
+ */var getReferringDomain=function getReferringDomain(referrer){var _getDomain;return (_getDomain=getDomain(referrer))!==null&&_getDomain!==void 0?_getDomain:'';};/**
3290
+ * Extracts UTM parameters from the URL
3291
+ * @param url Page URL
3292
+ * @returns UTM parameters
3293
+ */var extractUTMParameters=function extractUTMParameters(url){var result={};try{var urlObj=new URL(url);var UTM_PREFIX='utm_';urlObj.searchParams.forEach(function(value,sParam){if(sParam.startsWith(UTM_PREFIX)){var utmParam=sParam.substring(UTM_PREFIX.length);// Not sure why we're doing this
3294
+ if(utmParam==='campaign'){utmParam='name';}result[utmParam]=value;}});}catch(error){// Do nothing
3295
+ }return result;};/**
3296
+ * To get the URL until the hash
3297
+ * @param url The input URL
3298
+ * @returns URL until the hash
3299
+ */var getUrlWithoutHash=function getUrlWithoutHash(url){var urlWithoutHash=url;try{var urlObj=new URL(url);urlWithoutHash=urlObj.origin+urlObj.pathname+urlObj.search;}catch(error){// Do nothing
3300
+ }return urlWithoutHash;};
3301
+
3302
+ /**
3303
+ * Determines if the SDK is running inside a chrome extension
3304
+ * @returns boolean
3305
+ */var isSDKRunningInChromeExtension=function isSDKRunningInChromeExtension(){return !!(window.chrome&&window.chrome.runtime&&window.chrome.runtime.id);};
3306
+
3307
+ var DEFAULT_PRE_CONSENT_STORAGE_STRATEGY='none';var DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE='immediate';
3308
+
3309
+ var isErrorReportingEnabled=function isErrorReportingEnabled(sourceConfig){var _sourceConfig$statsCo;return (sourceConfig===null||sourceConfig===void 0||(_sourceConfig$statsCo=sourceConfig.statsCollection)===null||_sourceConfig$statsCo===void 0||(_sourceConfig$statsCo=_sourceConfig$statsCo.errors)===null||_sourceConfig$statsCo===void 0?void 0:_sourceConfig$statsCo.enabled)===true;};var isMetricsReportingEnabled=function isMetricsReportingEnabled(sourceConfig){var _sourceConfig$statsCo2;return (sourceConfig===null||sourceConfig===void 0||(_sourceConfig$statsCo2=sourceConfig.statsCollection)===null||_sourceConfig$statsCo2===void 0||(_sourceConfig$statsCo2=_sourceConfig$statsCo2.metrics)===null||_sourceConfig$statsCo2===void 0?void 0:_sourceConfig$statsCo2.enabled)===true;};
3310
+
3311
+ /**
3312
+ * Validates and normalizes the consent options provided by the user
3313
+ * @param options Consent options provided by the user
3314
+ * @returns Validated and normalized consent options
3315
+ */var getValidPostConsentOptions=function getValidPostConsentOptions(options){var validOptions={sendPageEvent:false,trackConsent:false,discardPreConsentEvents:false};if(isObjectLiteralAndNotNull(options)){var clonedOptions=clone(options);validOptions.storage=clonedOptions.storage;if(isDefined(clonedOptions.integrations)){validOptions.integrations=isObjectLiteralAndNotNull(clonedOptions.integrations)?clonedOptions.integrations:DEFAULT_INTEGRATIONS_CONFIG;}validOptions.discardPreConsentEvents=clonedOptions.discardPreConsentEvents===true;validOptions.sendPageEvent=clonedOptions.sendPageEvent===true;validOptions.trackConsent=clonedOptions.trackConsent===true;if(isNonEmptyObject(clonedOptions.consentManagement)){// Override enabled value with the current state value
3316
+ validOptions.consentManagement=mergeDeepRight(clonedOptions.consentManagement,{enabled:state.consents.enabled.value});}}return validOptions;};/**
3317
+ * Validates if the input is a valid consents data
3318
+ * @param value Input consents data
3319
+ * @returns true if the input is a valid consents data else false
3320
+ */var isValidConsentsData=function isValidConsentsData(value){return isNonEmptyObject(value)||Array.isArray(value);};/**
3321
+ * Retrieves the corresponding provider and plugin name of the selected consent manager from the supported consent managers
3322
+ * @param consentManagementOpts consent management options
3323
+ * @param logger logger instance
3324
+ * @returns Corresponding provider and plugin name of the selected consent manager from the supported consent managers
3325
+ */var getConsentManagerInfo=function getConsentManagerInfo(consentManagementOpts,logger){var provider=consentManagementOpts.provider;var consentManagerPluginName=provider?ConsentManagersToPluginNameMap[provider]:undefined;if(provider&&!consentManagerPluginName){logger===null||logger===void 0||logger.error(UNSUPPORTED_CONSENT_MANAGER_ERROR(CONFIG_MANAGER,provider,ConsentManagersToPluginNameMap));// Reset the provider value
3326
+ provider=undefined;}return {provider:provider,consentManagerPluginName:consentManagerPluginName};};/**
3327
+ * Validates and converts the consent management options into a normalized format
3328
+ * @param consentManagementOpts Consent management options provided by the user
3329
+ * @param logger logger instance
3330
+ * @returns An object containing the consent manager plugin name, initialized, enabled and consents data
3331
+ */var getConsentManagementData=function getConsentManagementData(consentManagementOpts,logger){var consentManagerPluginName;var allowedConsentIds=[];var deniedConsentIds=[];var initialized=false;var provider;var enabled=(consentManagementOpts===null||consentManagementOpts===void 0?void 0:consentManagementOpts.enabled)===true;if(isNonEmptyObject(consentManagementOpts)&&enabled){// Get the corresponding plugin name of the selected consent manager from the supported consent managers
3332
+ var _getConsentManagerInf=getConsentManagerInfo(consentManagementOpts,logger);provider=_getConsentManagerInf.provider;consentManagerPluginName=_getConsentManagerInf.consentManagerPluginName;if(isValidConsentsData(consentManagementOpts.allowedConsentIds)){allowedConsentIds=consentManagementOpts.allowedConsentIds;initialized=true;}if(isValidConsentsData(consentManagementOpts.deniedConsentIds)){deniedConsentIds=consentManagementOpts.deniedConsentIds;initialized=true;}}var consentsData={allowedConsentIds:allowedConsentIds,deniedConsentIds:deniedConsentIds};// Enable consent management only if consent manager is supported
3333
+ enabled=enabled&&Boolean(consentManagerPluginName);return {provider:provider,consentManagerPluginName:consentManagerPluginName,initialized:initialized,enabled:enabled,consentsData:consentsData};};
3334
+
3335
+ /**
3336
+ * Determines the SDK URL
3337
+ * @returns sdkURL
3338
+ */var getSDKUrl=function getSDKUrl(){var scripts=document.getElementsByTagName('script');var sdkFileNameRegex=/(?:^|\/)rsa(\.min)?\.js$/;// eslint-disable-next-line no-restricted-syntax
3339
+ var _iterator=_createForOfIteratorHelper(scripts),_step;try{for(_iterator.s();!(_step=_iterator.n()).done;){var script=_step.value;var src=script.getAttribute('src');if(src&&sdkFileNameRegex.test(src)){return src;}}}catch(err){_iterator.e(err);}finally{_iterator.f();}return undefined;};/**
3340
+ * Updates the reporting state variables from the source config data
3341
+ * @param res Source config
3342
+ * @param logger Logger instance
3343
+ */var updateReportingState=function updateReportingState(res){state.reporting.isErrorReportingEnabled.value=isErrorReportingEnabled(res.source.config)&&!isSDKRunningInChromeExtension();state.reporting.isMetricsReportingEnabled.value=isMetricsReportingEnabled(res.source.config);};var updateStorageStateFromLoadOptions=function updateStorageStateFromLoadOptions(logger){var _storageOptsFromLoad$;var _state$loadOptions$va=state.loadOptions.value,useServerSideCookies=_state$loadOptions$va.useServerSideCookies,dataServiceEndpoint=_state$loadOptions$va.dataServiceEndpoint,storageOptsFromLoad=_state$loadOptions$va.storage,setCookieDomain=_state$loadOptions$va.setCookieDomain,sameDomainCookiesOnly=_state$loadOptions$va.sameDomainCookiesOnly;var storageType=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.type;if(isDefined(storageType)&&!isValidStorageType(storageType)){logger===null||logger===void 0||logger.warn(STORAGE_TYPE_VALIDATION_WARNING(CONFIG_MANAGER,storageType,DEFAULT_STORAGE_TYPE));storageType=DEFAULT_STORAGE_TYPE;}var storageEncryptionVersion=storageOptsFromLoad===null||storageOptsFromLoad===void 0||(_storageOptsFromLoad$=storageOptsFromLoad.encryption)===null||_storageOptsFromLoad$===void 0?void 0:_storageOptsFromLoad$.version;var encryptionPluginName=storageEncryptionVersion&&StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];if(!isUndefined(storageEncryptionVersion)&&isUndefined(encryptionPluginName)){// set the default encryption plugin
3344
+ logger===null||logger===void 0||logger.warn(UNSUPPORTED_STORAGE_ENCRYPTION_VERSION_WARNING(CONFIG_MANAGER,storageEncryptionVersion,StorageEncryptionVersionsToPluginNameMap,DEFAULT_STORAGE_ENCRYPTION_VERSION));storageEncryptionVersion=DEFAULT_STORAGE_ENCRYPTION_VERSION;}else if(isUndefined(storageEncryptionVersion)){storageEncryptionVersion=DEFAULT_STORAGE_ENCRYPTION_VERSION;}// Allow migration only if the configured encryption version is the default encryption version
3345
+ var configuredMigrationValue=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.migrate;var finalMigrationVal=configuredMigrationValue&&storageEncryptionVersion===DEFAULT_STORAGE_ENCRYPTION_VERSION;if(configuredMigrationValue===true&&finalMigrationVal!==configuredMigrationValue){logger===null||logger===void 0||logger.warn(STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(CONFIG_MANAGER,storageEncryptionVersion,DEFAULT_STORAGE_ENCRYPTION_VERSION));}r(function(){var _storageOptsFromLoad$2;state.storage.type.value=storageType;var cookieOptions=(_storageOptsFromLoad$2=storageOptsFromLoad===null||storageOptsFromLoad===void 0?void 0:storageOptsFromLoad.cookie)!==null&&_storageOptsFromLoad$2!==void 0?_storageOptsFromLoad$2:{};if(useServerSideCookies){var _cookieOptions$domain;state.serverCookies.isEnabledServerSideCookies.value=useServerSideCookies;var providedCookieDomain=(_cookieOptions$domain=cookieOptions.domain)!==null&&_cookieOptions$domain!==void 0?_cookieOptions$domain:setCookieDomain;/**
3346
+ * Based on the following conditions, we decide whether to use the exact domain or not to determine the data service URL:
3347
+ * 1. If the cookie domain is provided and it is not a top-level domain, then use the exact domain
3348
+ * 2. If the sameDomainCookiesOnly flag is set to true, then use the exact domain
3349
+ */var useExactDomain=isDefined(providedCookieDomain)&&!isWebpageTopLevelDomain(removeLeadingPeriod(providedCookieDomain))||sameDomainCookiesOnly;var dataServiceUrl=getDataServiceUrl(dataServiceEndpoint!==null&&dataServiceEndpoint!==void 0?dataServiceEndpoint:DEFAULT_DATA_SERVICE_ENDPOINT,useExactDomain!==null&&useExactDomain!==void 0?useExactDomain:false);if(isValidURL(dataServiceUrl)){state.serverCookies.dataServiceUrl.value=removeTrailingSlashes(dataServiceUrl);var curHost=getDomain(window.location.href);var dataServiceHost=getDomain(dataServiceUrl);// If the current host is different from the data service host, then it is a cross-site request
3350
+ // For server-side cookies to work, we need to set the SameSite=None and Secure attributes
3351
+ // One round of cookie options manipulation is taking place here
3352
+ // Based on these(setCookieDomain/storage.cookie or sameDomainCookiesOnly) two load-options, final cookie options are set in the storage module
3353
+ // TODO: Refactor the cookie options manipulation logic in one place
3354
+ if(curHost!==dataServiceHost){cookieOptions=_objectSpread2(_objectSpread2({},cookieOptions),{},{samesite:'None',secure:true});}/**
3355
+ * If the sameDomainCookiesOnly flag is not set and the cookie domain is provided(not top level domain),
3356
+ * and the data service host is different from the provided cookie domain, then we disable server-side cookies
3357
+ * ex: provided cookie domain: 'random.com', data service host: 'sub.example.com'
3358
+ */if(!sameDomainCookiesOnly&&useExactDomain&&dataServiceHost!==removeLeadingPeriod(providedCookieDomain)){state.serverCookies.isEnabledServerSideCookies.value=false;logger===null||logger===void 0||logger.warn(SERVER_SIDE_COOKIE_FEATURE_OVERRIDE_WARNING(CONFIG_MANAGER,providedCookieDomain,dataServiceHost));}}else {state.serverCookies.isEnabledServerSideCookies.value=false;}}state.storage.cookie.value=cookieOptions;state.storage.encryptionPluginName.value=StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];state.storage.migrate.value=finalMigrationVal;});};var updateConsentsStateFromLoadOptions=function updateConsentsStateFromLoadOptions(logger){var _preConsentOpts$stora,_preConsentOpts$stora2,_preConsentOpts$event,_preConsentOpts$event2;var _getConsentManagement=getConsentManagementData(state.loadOptions.value.consentManagement,logger),provider=_getConsentManagement.provider,consentManagerPluginName=_getConsentManagement.consentManagerPluginName,initialized=_getConsentManagement.initialized,enabled=_getConsentManagement.enabled,consentsData=_getConsentManagement.consentsData;// Pre-consent
3359
+ var preConsentOpts=state.loadOptions.value.preConsent;var storageStrategy=(_preConsentOpts$stora=preConsentOpts===null||preConsentOpts===void 0||(_preConsentOpts$stora2=preConsentOpts.storage)===null||_preConsentOpts$stora2===void 0?void 0:_preConsentOpts$stora2.strategy)!==null&&_preConsentOpts$stora!==void 0?_preConsentOpts$stora:DEFAULT_PRE_CONSENT_STORAGE_STRATEGY;var StorageStrategies=['none','session','anonymousId'];if(isDefined(storageStrategy)&&!StorageStrategies.includes(storageStrategy)){var _preConsentOpts$stora3;storageStrategy=DEFAULT_PRE_CONSENT_STORAGE_STRATEGY;logger===null||logger===void 0||logger.warn(UNSUPPORTED_PRE_CONSENT_STORAGE_STRATEGY(CONFIG_MANAGER,preConsentOpts===null||preConsentOpts===void 0||(_preConsentOpts$stora3=preConsentOpts.storage)===null||_preConsentOpts$stora3===void 0?void 0:_preConsentOpts$stora3.strategy,DEFAULT_PRE_CONSENT_STORAGE_STRATEGY));}var eventsDeliveryType=(_preConsentOpts$event=preConsentOpts===null||preConsentOpts===void 0||(_preConsentOpts$event2=preConsentOpts.events)===null||_preConsentOpts$event2===void 0?void 0:_preConsentOpts$event2.delivery)!==null&&_preConsentOpts$event!==void 0?_preConsentOpts$event:DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE;var deliveryTypes=['immediate','buffer'];if(isDefined(eventsDeliveryType)&&!deliveryTypes.includes(eventsDeliveryType)){var _preConsentOpts$event3;eventsDeliveryType=DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE;logger===null||logger===void 0||logger.warn(UNSUPPORTED_PRE_CONSENT_EVENTS_DELIVERY_TYPE(CONFIG_MANAGER,preConsentOpts===null||preConsentOpts===void 0||(_preConsentOpts$event3=preConsentOpts.events)===null||_preConsentOpts$event3===void 0?void 0:_preConsentOpts$event3.delivery,DEFAULT_PRE_CONSENT_EVENTS_DELIVERY_TYPE));}r(function(){var _state$loadOptions$va2;state.consents.activeConsentManagerPluginName.value=consentManagerPluginName;state.consents.initialized.value=initialized;state.consents.enabled.value=enabled;state.consents.data.value=consentsData;state.consents.provider.value=provider;state.consents.preConsent.value={// Only enable pre-consent if it is explicitly enabled and
3360
+ // if it is not already initialized and
3361
+ // if consent management is enabled
3362
+ enabled:((_state$loadOptions$va2=state.loadOptions.value.preConsent)===null||_state$loadOptions$va2===void 0?void 0:_state$loadOptions$va2.enabled)===true&&initialized===false&&enabled===true,storage:{strategy:storageStrategy},events:{delivery:eventsDeliveryType}};});};/**
3363
+ * Determines the consent management state variables from the source config data
3364
+ * @param resp Source config response
3365
+ * @param logger Logger instance
3366
+ */var updateConsentsState=function updateConsentsState(resp){var resolutionStrategy=state.consents.resolutionStrategy.value;var cmpMetadata;if(isObjectLiteralAndNotNull(resp.consentManagementMetadata)){if(state.consents.provider.value){var _resp$consentManageme,_resp$consentManageme2;resolutionStrategy=(_resp$consentManageme=(_resp$consentManageme2=resp.consentManagementMetadata.providers.find(function(p){return p.provider===state.consents.provider.value;}))===null||_resp$consentManageme2===void 0?void 0:_resp$consentManageme2.resolutionStrategy)!==null&&_resp$consentManageme!==void 0?_resp$consentManageme:state.consents.resolutionStrategy.value;}cmpMetadata=resp.consentManagementMetadata;}// If the provider is custom, then the resolution strategy is not applicable
3367
+ if(state.consents.provider.value==='custom'){resolutionStrategy=undefined;}r(function(){state.consents.metadata.value=clone(cmpMetadata);state.consents.resolutionStrategy.value=resolutionStrategy;});};var updateDataPlaneEventsStateFromLoadOptions=function updateDataPlaneEventsStateFromLoadOptions(logger){if(state.dataPlaneEvents.deliveryEnabled.value){var defaultEventsQueuePluginName='XhrQueue';var eventsQueuePluginName=defaultEventsQueuePluginName;if(state.loadOptions.value.useBeacon){if(state.capabilities.isBeaconAvailable.value){eventsQueuePluginName='BeaconQueue';}else {eventsQueuePluginName=defaultEventsQueuePluginName;logger===null||logger===void 0||logger.warn(UNSUPPORTED_BEACON_API_WARNING(CONFIG_MANAGER));}}r(function(){state.dataPlaneEvents.eventsQueuePluginName.value=eventsQueuePluginName;});}};var getSourceConfigURL=function getSourceConfigURL(configUrl,writeKey,lockIntegrationsVersion,lockPluginsVersion,logger){var defSearchParams=new URLSearchParams({p:MODULE_TYPE,v:APP_VERSION,build:BUILD_TYPE,writeKey:writeKey,lockIntegrationsVersion:lockIntegrationsVersion.toString(),lockPluginsVersion:lockPluginsVersion.toString()});var origin=DEFAULT_CONFIG_BE_URL;var searchParams=defSearchParams;var pathname='/sourceConfig/';var hash='';if(isValidURL(configUrl)){var configUrlInstance=new URL(configUrl);if(!removeTrailingSlashes(configUrlInstance.pathname).endsWith('/sourceConfig')){configUrlInstance.pathname="".concat(removeTrailingSlashes(configUrlInstance.pathname),"/sourceConfig/");}configUrlInstance.pathname=removeDuplicateSlashes(configUrlInstance.pathname);defSearchParams.forEach(function(value,key){if(configUrlInstance.searchParams.get(key)===null){configUrlInstance.searchParams.set(key,value);}});origin=configUrlInstance.origin;pathname=configUrlInstance.pathname;searchParams=configUrlInstance.searchParams;hash=configUrlInstance.hash;}else {logger===null||logger===void 0||logger.warn(INVALID_CONFIG_URL_WARNING(CONFIG_MANAGER,configUrl));}return "".concat(origin).concat(pathname,"?").concat(searchParams).concat(hash);};
3368
+
3369
+ var getSDKComponentBaseURL=function getSDKComponentBaseURL(componentType,pathSuffix,baseURL,currentVersion,lockVersion,customURL){var sdkComponentURL='';if(customURL){if(!isValidURL(customURL)){throw new Error(COMPONENT_BASE_URL_ERROR(componentType));}return removeTrailingSlashes(customURL);}var sdkURL=getSDKUrl();sdkComponentURL=sdkURL?sdkURL.split('/').slice(0,-1).concat(pathSuffix).join('/'):baseURL;if(lockVersion){sdkComponentURL=sdkComponentURL.replace("/".concat(CDN_ARCH_VERSION_DIR,"/").concat(BUILD_TYPE,"/").concat(pathSuffix),"/".concat(currentVersion,"/").concat(BUILD_TYPE,"/").concat(pathSuffix));}return sdkComponentURL;};/**
3370
+ * A function that determines integration SDK loading path
3371
+ * @param currentVersion
3372
+ * @param lockIntegrationsVersion
3373
+ * @param customIntegrationsCDNPath
3374
+ * @returns
3375
+ */var getIntegrationsCDNPath=function getIntegrationsCDNPath(currentVersion,lockIntegrationsVersion,customIntegrationsCDNPath){return getSDKComponentBaseURL('integrations',CDN_INT_DIR,DEST_SDK_BASE_URL,currentVersion,lockIntegrationsVersion,customIntegrationsCDNPath);};/**
3376
+ * A function that determines plugins SDK loading path
3377
+ * @param currentVersion Current SDK version
3378
+ * @param lockPluginsVersion Flag to lock the plugins version
3379
+ * @param customPluginsCDNPath URL to load the plugins from
3380
+ * @returns Final plugins CDN path
3381
+ */var getPluginsCDNPath=function getPluginsCDNPath(currentVersion,lockPluginsVersion,customPluginsCDNPath){return getSDKComponentBaseURL('plugins',CDN_PLUGINS_DIR,PLUGINS_BASE_URL,currentVersion,lockPluginsVersion,customPluginsCDNPath);};
3382
+
3383
+ var ConfigManager=/*#__PURE__*/function(){function ConfigManager(httpClient,errorHandler,logger){_classCallCheck(this,ConfigManager);_defineProperty(this,"hasErrorHandler",false);this.errorHandler=errorHandler;this.logger=logger;this.httpClient=httpClient;this.hasErrorHandler=Boolean(this.errorHandler);this.onError=this.onError.bind(this);this.processConfig=this.processConfig.bind(this);}return _createClass(ConfigManager,[{key:"attachEffects",value:function attachEffects(){var _this=this;E(function(){var _this$logger;(_this$logger=_this.logger)===null||_this$logger===void 0||_this$logger.setMinLogLevel(state.lifecycle.logLevel.value);});}/**
3384
+ * A function to validate, construct and store loadOption, lifecycle, source and destination
3385
+ * config related information in global state
3386
+ */},{key:"init",value:function init(){var _this2=this;this.attachEffects();validateLoadArgs(state.lifecycle.writeKey.value,state.lifecycle.dataPlaneUrl.value);var _state$loadOptions$va=state.loadOptions.value,logLevel=_state$loadOptions$va.logLevel,configUrl=_state$loadOptions$va.configUrl,lockIntegrationsVersion=_state$loadOptions$va.lockIntegrationsVersion,lockPluginsVersion=_state$loadOptions$va.lockPluginsVersion,destSDKBaseURL=_state$loadOptions$va.destSDKBaseURL,pluginsSDKBaseURL=_state$loadOptions$va.pluginsSDKBaseURL;state.lifecycle.activeDataplaneUrl.value=removeTrailingSlashes(state.lifecycle.dataPlaneUrl.value);// determine the path to fetch integration SDK from
3387
+ var intgCdnUrl=getIntegrationsCDNPath(APP_VERSION,lockIntegrationsVersion,destSDKBaseURL);// determine the path to fetch remote plugins from
3388
+ var pluginsCDNPath=getPluginsCDNPath(APP_VERSION,lockPluginsVersion,pluginsSDKBaseURL);updateStorageStateFromLoadOptions(this.logger);updateConsentsStateFromLoadOptions(this.logger);updateDataPlaneEventsStateFromLoadOptions(this.logger);// set application lifecycle state in global state
3389
+ r(function(){state.lifecycle.integrationsCDNPath.value=intgCdnUrl;state.lifecycle.pluginsCDNPath.value=pluginsCDNPath;if(logLevel){state.lifecycle.logLevel.value=logLevel;}state.lifecycle.sourceConfigUrl.value=getSourceConfigURL(configUrl,state.lifecycle.writeKey.value,lockIntegrationsVersion,lockPluginsVersion,_this2.logger);state.metrics.metricsServiceUrl.value="".concat(state.lifecycle.activeDataplaneUrl.value,"/").concat(METRICS_SERVICE_ENDPOINT);});this.getConfig();}/**
3390
+ * Handle errors
3391
+ */},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0||_this$errorHandler.onError(error,CONFIG_MANAGER,customMessage,shouldAlwaysThrow);}else {throw error;}}/**
3392
+ * A callback function that is executed once we fetch the source config response.
3393
+ * Use to construct and store information that are dependent on the sourceConfig.
3394
+ */},{key:"processConfig",value:function processConfig(response,details){// TODO: add retry logic with backoff based on rejectionDetails.xhr.status
3395
+ // We can use isErrRetryable utility method
3396
+ if(!response){this.onError(SOURCE_CONFIG_FETCH_ERROR(details===null||details===void 0?void 0:details.error));return;}var res;try{if(isString(response)){res=JSON.parse(response);}else {res=response;}}catch(err){this.onError(err,SOURCE_CONFIG_RESOLUTION_ERROR,true);return;}if(!isValidSourceConfig(res)){this.onError(new Error(SOURCE_CONFIG_RESOLUTION_ERROR),undefined,true);return;}// Log error and abort if source is disabled
3397
+ if(res.source.enabled===false){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(SOURCE_DISABLED_ERROR);return;}// set the values in state for reporting slice
3398
+ updateReportingState(res);var nativeDestinations=res.source.destinations.length>0?filterEnabledDestination(res.source.destinations):[];// set in the state --> source, destination, lifecycle, reporting
3399
+ r(function(){var _state$loadOptions$va2;// set source related information in state
3400
+ state.source.value={config:res.source.config,id:res.source.id,workspaceId:res.source.workspaceId};// set device mode destination related information in state
3401
+ state.nativeDestinations.configuredDestinations.value=nativeDestinations;// set the desired optional plugins
3402
+ state.plugins.pluginsToLoadFromConfig.value=(_state$loadOptions$va2=state.loadOptions.value.plugins)!==null&&_state$loadOptions$va2!==void 0?_state$loadOptions$va2:[];updateConsentsState(res);// set application lifecycle state
3403
+ state.lifecycle.status.value='configured';});}/**
3404
+ * A function to fetch source config either from /sourceConfig endpoint
3405
+ * or from getSourceConfig load option
3406
+ * @returns
3407
+ */},{key:"getConfig",value:function getConfig(){var _this3=this;var sourceConfigFunc=state.loadOptions.value.getSourceConfig;if(sourceConfigFunc){if(!isFunction(sourceConfigFunc)){throw new Error(SOURCE_CONFIG_OPTION_ERROR);}// Fetch source config from the function
3408
+ var res=sourceConfigFunc();if(res instanceof Promise){res.then(function(pRes){return _this3.processConfig(pRes);}).catch(function(err){_this3.onError(err,'SourceConfig');});}else {this.processConfig(res);}}else {// Fetch source configuration from the configured URL
3409
+ this.httpClient.getAsyncData({url:state.lifecycle.sourceConfigUrl.value,options:{headers:{'Content-Type':undefined}},callback:this.processConfig});}}}]);}();
3410
+
3411
+ /**
3412
+ * To get the timezone of the user
3413
+ *
3414
+ * @returns string
3415
+ */var getTimezone=function getTimezone(){var timezone=new Date().toString().match(/([A-Z]+[+-]\d+)/);return timezone&&timezone[1]?timezone[1]:'NA';};
3416
+
3417
+ /**
3418
+ * Get the referrer URL
3419
+ * @returns The referrer URL
3420
+ */var getReferrer=function getReferrer(){var _document;return ((_document=document)===null||_document===void 0?void 0:_document.referrer)||'$direct';};/**
3421
+ * To get the canonical URL of the page
3422
+ * @returns canonical URL
3423
+ */var getCanonicalUrl=function getCanonicalUrl(){var tags=document.getElementsByTagName('link');var canonicalUrl='';for(var i=0;tags[i];i+=1){var tag=tags[i];if(tag.getAttribute('rel')==='canonical'&&!canonicalUrl){var _tag$getAttribute;canonicalUrl=(_tag$getAttribute=tag.getAttribute('href'))!==null&&_tag$getAttribute!==void 0?_tag$getAttribute:'';break;}}return canonicalUrl;};var getUserAgent=function getUserAgent(){if(isUndefined(globalThis.navigator)){return null;}var userAgent=globalThis.navigator.userAgent;var _ref=globalThis.navigator,brave=_ref.brave;// For supporting Brave browser detection,
3424
+ // add "Brave/<version>" to the user agent with the version value from the Chrome component
3425
+ if(brave&&Object.getPrototypeOf(brave).isBrave){// Example:
3426
+ // Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.5060.114 Safari/537.36
3427
+ var matchedArr=userAgent.match(/(chrome)\/([\w.]+)/i);if(matchedArr){userAgent="".concat(userAgent," Brave/").concat(matchedArr[2]);}}return userAgent;};var getLanguage=function getLanguage(){var _globalThis$navigator;if(isUndefined(globalThis.navigator)){return null;}return (_globalThis$navigator=globalThis.navigator.language)!==null&&_globalThis$navigator!==void 0?_globalThis$navigator:globalThis.navigator.browserLanguage;};/**
3428
+ * Default page properties
3429
+ * @returns Default page properties
3430
+ */var getDefaultPageProperties=function getDefaultPageProperties(){var canonicalUrl=getCanonicalUrl();var path=globalThis.location.pathname;var tabUrl=globalThis.location.href;var pageUrl=tabUrl;var search=globalThis.location.search;// If valid canonical URL is provided use this as page URL.
3431
+ if(canonicalUrl){try{var urlObj=new URL(canonicalUrl);// If existing, query params of canonical URL will be used instead of the location.search ones
3432
+ if(urlObj.search===''){pageUrl=canonicalUrl+search;}else {pageUrl=canonicalUrl;}path=urlObj.pathname;}catch(err){// Do nothing
3433
+ }}var url=getUrlWithoutHash(pageUrl);var _document2=document,title=_document2.title;var referrer=getReferrer();return {path:path,referrer:referrer,referring_domain:getReferringDomain(referrer),search:search,title:title,url:url,tab_url:tabUrl};};
3434
+
3435
+ var POLYFILL_URL="https://polyfill-fastly.io/v3/polyfill.min.js?version=3.111.0&features=".concat(Object.keys(legacyJSEngineRequiredPolyfills).join('%2C'));var POLYFILL_LOAD_TIMEOUT=10*1000;// 10 seconds
3436
+ var POLYFILL_SCRIPT_ID='rudderstackPolyfill';
3437
+
3438
+ var CapabilitiesManager=/*#__PURE__*/function(){function CapabilitiesManager(errorHandler,logger){_classCallCheck(this,CapabilitiesManager);this.logger=logger;this.errorHandler=errorHandler;this.externalSrcLoader=new ExternalSrcLoader(this.errorHandler,this.logger);this.onError=this.onError.bind(this);this.onReady=this.onReady.bind(this);}return _createClass(CapabilitiesManager,[{key:"init",value:function init(){try{this.prepareBrowserCapabilities();this.attachWindowListeners();}catch(err){this.onError(err);}}/**
3439
+ * Detect supported capabilities and set values in state
3440
+ */ // eslint-disable-next-line class-methods-use-this
3441
+ },{key:"detectBrowserCapabilities",value:function detectBrowserCapabilities(){var _this=this;r(function(){// Storage related details
3442
+ state.capabilities.storage.isCookieStorageAvailable.value=isStorageAvailable(COOKIE_STORAGE,getStorageEngine(COOKIE_STORAGE),_this.logger);state.capabilities.storage.isLocalStorageAvailable.value=isStorageAvailable(LOCAL_STORAGE,undefined,_this.logger);state.capabilities.storage.isSessionStorageAvailable.value=isStorageAvailable(SESSION_STORAGE,undefined,_this.logger);// Browser feature detection details
3443
+ state.capabilities.isBeaconAvailable.value=hasBeacon();state.capabilities.isUaCHAvailable.value=hasUAClientHints();state.capabilities.isCryptoAvailable.value=hasCrypto();state.capabilities.isIE11.value=isIE11();state.capabilities.isOnline.value=globalThis.navigator.onLine;// Get page context details
3444
+ state.context.userAgent.value=getUserAgent();state.context.locale.value=getLanguage();state.context.screen.value=getScreenDetails();state.context.timezone.value=getTimezone();if(hasUAClientHints()){getUserAgentClientHint(function(uach){state.context['ua-ch'].value=uach;},state.loadOptions.value.uaChTrackLevel);}});// Ad blocker detection
3445
+ E(function(){if(state.loadOptions.value.sendAdblockPage===true&&state.lifecycle.sourceConfigUrl.value!==undefined){detectAdBlockers(_this.errorHandler,_this.logger);}});}/**
3446
+ * Detect if polyfills are required and then load script from polyfill URL
3447
+ */},{key:"prepareBrowserCapabilities",value:function prepareBrowserCapabilities(){var _this2=this;state.capabilities.isLegacyDOM.value=isLegacyJSEngine();var customPolyfillUrl=state.loadOptions.value.polyfillURL;var polyfillUrl=POLYFILL_URL;if(isDefinedAndNotNull(customPolyfillUrl)){if(isValidURL(customPolyfillUrl)){polyfillUrl=customPolyfillUrl;}else {var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.warn(INVALID_POLYFILL_URL_WARNING(CAPABILITIES_MANAGER,customPolyfillUrl));}}var shouldLoadPolyfill=state.loadOptions.value.polyfillIfRequired&&state.capabilities.isLegacyDOM.value&&isValidURL(polyfillUrl);if(shouldLoadPolyfill){var isDefaultPolyfillService=polyfillUrl!==state.loadOptions.value.polyfillURL;if(isDefaultPolyfillService){// write key specific callback
3448
+ // NOTE: we're not putting this into RudderStackGlobals as providing the property path to the callback function in the polyfill URL is not possible
3449
+ var polyfillCallbackName="RS_polyfillCallback_".concat(state.lifecycle.writeKey.value);var polyfillCallback=function polyfillCallback(){_this2.onReady();// Remove the entry from window so we don't leave room for calling it again
3450
+ delete globalThis[polyfillCallbackName];};globalThis[polyfillCallbackName]=polyfillCallback;polyfillUrl="".concat(polyfillUrl,"&callback=").concat(polyfillCallbackName);}this.externalSrcLoader.loadJSFile({url:polyfillUrl,id:POLYFILL_SCRIPT_ID,async:true,timeout:POLYFILL_LOAD_TIMEOUT,callback:function callback(scriptId){if(!scriptId){_this2.onError(new Error(POLYFILL_SCRIPT_LOAD_ERROR(POLYFILL_SCRIPT_ID,polyfillUrl)));}else if(!isDefaultPolyfillService){_this2.onReady();}}});}else {this.onReady();}}/**
3451
+ * Attach listeners to window to observe event that update capabilities state values
3452
+ */},{key:"attachWindowListeners",value:function attachWindowListeners(){globalThis.addEventListener('offline',function(){state.capabilities.isOnline.value=false;});globalThis.addEventListener('online',function(){state.capabilities.isOnline.value=true;});globalThis.addEventListener('resize',debounce(function(){state.context.screen.value=getScreenDetails();},this));}/**
3453
+ * Set the lifecycle status to next phase
3454
+ */ // eslint-disable-next-line class-methods-use-this
3455
+ },{key:"onReady",value:function onReady(){this.detectBrowserCapabilities();state.lifecycle.status.value='browserCapabilitiesReady';}/**
3456
+ * Handles error
3457
+ * @param error The error object
3458
+ */},{key:"onError",value:function onError(error){if(this.errorHandler){this.errorHandler.onError(error,CAPABILITIES_MANAGER);}else {throw error;}}}]);}();
3459
+
3460
+ var CHANNEL='web';// These are the top-level elements in the standard RudderStack event spec
3461
+ var TOP_LEVEL_ELEMENTS=['integrations','anonymousId','originalTimestamp'];// Reserved elements in the context of standard RudderStack event spec
3462
+ // Typically, these elements are not allowed to be overridden by the user
3463
+ var CONTEXT_RESERVED_ELEMENTS=['library','consentManagement','userAgent','ua-ch','screen'];// Reserved elements in the standard RudderStack event spec
3464
+ var RESERVED_ELEMENTS=['id','anonymous_id','user_id','sent_at','timestamp','received_at','original_timestamp','event','event_text','channel','context_ip','context_request_ip','context_passed_ip','group_id','previous_id'];
3465
+
3466
+ /**
3467
+ * A function to check given value is a number or not
3468
+ * @param num input value
3469
+ * @returns boolean
3470
+ */var isNumber=function isNumber(num){return typeof num==='number'&&!Number.isNaN(num);};/**
3471
+ * A function to check given number has minimum length or not
3472
+ * @param minimumLength minimum length
3473
+ * @param num input number
3474
+ * @returns boolean
3475
+ */var hasMinLength=function hasMinLength(minimumLength,num){return num.toString().length>=minimumLength;};/**
3476
+ * A function to check given value is a positive integer or not
3477
+ * @param num input value
3478
+ * @returns boolean
3479
+ */var isPositiveInteger=function isPositiveInteger(num){return isNumber(num)&&num>=0&&Number.isInteger(num);};
3480
+
3481
+ var MIN_SESSION_ID_LENGTH=10;/**
3482
+ * A function to validate current session and return true/false depending on that
3483
+ * @returns boolean
3484
+ */var hasSessionExpired=function hasSessionExpired(expiresAt){var timestamp=Date.now();return Boolean(!expiresAt||timestamp>expiresAt);};/**
3485
+ * A function to generate session id
3486
+ * @returns number
3487
+ */var generateSessionId=function generateSessionId(){return Date.now();};/**
3488
+ * Function to validate user provided sessionId
3489
+ * @param {number} sessionId
3490
+ * @param logger logger
3491
+ * @returns
3492
+ */var isManualSessionIdValid=function isManualSessionIdValid(sessionId,logger){if(!sessionId||!isPositiveInteger(sessionId)||!hasMinLength(MIN_SESSION_ID_LENGTH,sessionId)){logger===null||logger===void 0||logger.warn(INVALID_SESSION_ID_WARNING(USER_SESSION_MANAGER,sessionId,MIN_SESSION_ID_LENGTH));return false;}return true;};/**
3493
+ * A function to generate new auto tracking session
3494
+ * @param sessionTimeout current timestamp
3495
+ * @returns SessionInfo
3496
+ */var generateAutoTrackingSession=function generateAutoTrackingSession(sessionTimeout){var timestamp=Date.now();var timeout=sessionTimeout||DEFAULT_SESSION_TIMEOUT_MS;return {id:timestamp,// set the current timestamp
3497
+ expiresAt:timestamp+timeout,// set the expiry time of the session
3498
+ timeout:timeout,sessionStart:undefined,autoTrack:true};};/**
3499
+ * A function to generate new manual tracking session
3500
+ * @param id Provided sessionId
3501
+ * @param logger Logger module
3502
+ * @returns SessionInfo
3503
+ */var generateManualTrackingSession=function generateManualTrackingSession(id,logger){var sessionId=isManualSessionIdValid(id,logger)?id:generateSessionId();return {id:sessionId,sessionStart:undefined,manualTrack:true};};var isStorageTypeValidForStoringData=function isStorageTypeValidForStoringData(storageType){return Boolean(storageType===COOKIE_STORAGE||storageType===LOCAL_STORAGE||storageType===SESSION_STORAGE||storageType===MEMORY_STORAGE);};/**
3504
+ * Generate a new anonymousId
3505
+ * @returns string anonymousID
3506
+ */var generateAnonymousId=function generateAnonymousId(){return generateUUID();};
3507
+
3508
+ /**
3509
+ * To get the page properties for context object
3510
+ * @param pageProps Page properties
3511
+ * @returns page properties object for context
3512
+ */var getContextPageProperties=function getContextPageProperties(pageProps){// Need to get updated page details on each event as an event to notify on SPA URL changes does not seem to exist
3513
+ var curPageProps=getDefaultPageProperties();var ctxPageProps={};Object.keys(curPageProps).forEach(function(key){ctxPageProps[key]=(pageProps===null||pageProps===void 0?void 0:pageProps[key])||curPageProps[key];});ctxPageProps.initial_referrer=(pageProps===null||pageProps===void 0?void 0:pageProps.initial_referrer)||state.session.initialReferrer.value;ctxPageProps.initial_referring_domain=(pageProps===null||pageProps===void 0?void 0:pageProps.initial_referring_domain)||state.session.initialReferringDomain.value;return ctxPageProps;};/**
3514
+ * Add any missing default page properties using values from options and defaults
3515
+ * @param properties Input page properties
3516
+ * @param options API options
3517
+ */var getUpdatedPageProperties=function getUpdatedPageProperties(properties,options){var optionsPageProps=(options===null||options===void 0?void 0:options.page)||{};var pageProps=properties;// Need to get updated page details on each event as an event to notify on SPA URL changes does not seem to exist
3518
+ var curPageProps=getDefaultPageProperties();Object.keys(curPageProps).forEach(function(key){if(isUndefined(pageProps[key])){pageProps[key]=optionsPageProps[key]||curPageProps[key];}});if(isUndefined(pageProps.initial_referrer)){pageProps.initial_referrer=optionsPageProps.initial_referrer||state.session.initialReferrer.value;}if(isUndefined(pageProps.initial_referring_domain)){pageProps.initial_referring_domain=optionsPageProps.initial_referring_domain||state.session.initialReferringDomain.value;}return pageProps;};/**
3519
+ * Utility to check for reserved keys in the input object
3520
+ * @param obj Generic object
3521
+ * @param parentKeyPath Object's parent key path
3522
+ * @param logger Logger instance
3523
+ */var checkForReservedElementsInObject=function checkForReservedElementsInObject(obj,parentKeyPath,logger){if(isObjectLiteralAndNotNull(obj)){Object.keys(obj).forEach(function(property){if(RESERVED_ELEMENTS.includes(property)||RESERVED_ELEMENTS.includes(property.toLowerCase())){logger===null||logger===void 0||logger.warn(RESERVED_KEYWORD_WARNING(EVENT_MANAGER,property,parentKeyPath,RESERVED_ELEMENTS));}});}};/**
3524
+ * Checks for reserved keys in traits, properties, and contextual traits
3525
+ * @param rudderEvent Generated rudder event
3526
+ * @param logger Logger instance
3527
+ */var checkForReservedElements=function checkForReservedElements(rudderEvent,logger){// properties, traits, contextualTraits are either undefined or object
3528
+ var properties=rudderEvent.properties,traits=rudderEvent.traits,context=rudderEvent.context;var contextualTraits=context.traits;checkForReservedElementsInObject(properties,'properties',logger);checkForReservedElementsInObject(traits,'traits',logger);checkForReservedElementsInObject(contextualTraits,'context.traits',logger);};/**
3529
+ * Overrides the top-level event properties with data from API options
3530
+ * @param rudderEvent Generated rudder event
3531
+ * @param options API options
3532
+ */var updateTopLevelEventElements=function updateTopLevelEventElements(rudderEvent,options){if(options.anonymousId&&isString(options.anonymousId)){// eslint-disable-next-line no-param-reassign
3533
+ rudderEvent.anonymousId=options.anonymousId;}if(isObjectLiteralAndNotNull(options.integrations)){// eslint-disable-next-line no-param-reassign
3534
+ rudderEvent.integrations=options.integrations;}if(options.originalTimestamp&&isString(options.originalTimestamp)){// eslint-disable-next-line no-param-reassign
3535
+ rudderEvent.originalTimestamp=options.originalTimestamp;}};/**
3536
+ * To merge the contextual information in API options with existing data
3537
+ * @param rudderContext Generated rudder event
3538
+ * @param options API options
3539
+ * @param logger Logger instance
3540
+ */var getMergedContext=function getMergedContext(rudderContext,options,logger){var context=rudderContext;Object.keys(options).forEach(function(key){if(!TOP_LEVEL_ELEMENTS.includes(key)&&!CONTEXT_RESERVED_ELEMENTS.includes(key)){if(key!=='context'){context=mergeDeepRight(context,_defineProperty({},key,options[key]));}else if(!isUndefined(options[key])&&isObjectLiteralAndNotNull(options[key])){var tempContext={};Object.keys(options[key]).forEach(function(e){if(!CONTEXT_RESERVED_ELEMENTS.includes(e)){tempContext[e]=options[key][e];}});context=mergeDeepRight(context,_objectSpread2({},tempContext));}else;}});return context;};/**
3541
+ * A function to determine whether SDK should use the integration option provided in load call
3542
+ * @returns boolean
3543
+ */var shouldUseGlobalIntegrationsConfigInEvents=function shouldUseGlobalIntegrationsConfigInEvents(){var _state$consents$postC;return state.loadOptions.value.useGlobalIntegrationsConfigInEvents&&(isObjectLiteralAndNotNull((_state$consents$postC=state.consents.postConsent.value)===null||_state$consents$postC===void 0?void 0:_state$consents$postC.integrations)||isObjectLiteralAndNotNull(state.nativeDestinations.loadOnlyIntegrations.value));};/**
3544
+ * Updates rudder event object with data from the API options
3545
+ * @param rudderEvent Generated rudder event
3546
+ * @param options API options
3547
+ */var processOptions=function processOptions(rudderEvent,options){// Only allow object type for options
3548
+ if(isObjectLiteralAndNotNull(options)){updateTopLevelEventElements(rudderEvent,options);// eslint-disable-next-line no-param-reassign
3549
+ rudderEvent.context=getMergedContext(rudderEvent.context,options);}};/**
3550
+ * Returns the final integrations config for the event based on the global config and event's config
3551
+ * @param integrationsConfig Event's integrations config
3552
+ * @returns Final integrations config
3553
+ */var getEventIntegrationsConfig=function getEventIntegrationsConfig(integrationsConfig){var finalIntgConfig;if(shouldUseGlobalIntegrationsConfigInEvents()){var _state$consents$postC2,_state$consents$postC3;finalIntgConfig=clone((_state$consents$postC2=(_state$consents$postC3=state.consents.postConsent.value)===null||_state$consents$postC3===void 0?void 0:_state$consents$postC3.integrations)!==null&&_state$consents$postC2!==void 0?_state$consents$postC2:state.nativeDestinations.loadOnlyIntegrations.value);}else if(isObjectLiteralAndNotNull(integrationsConfig)){finalIntgConfig=integrationsConfig;}else {finalIntgConfig=DEFAULT_INTEGRATIONS_CONFIG;}return finalIntgConfig;};/**
3554
+ * Enrich the base event object with data from state and the API options
3555
+ * @param rudderEvent RudderEvent object
3556
+ * @param options API options
3557
+ * @param pageProps Page properties
3558
+ * @param logger logger
3559
+ * @returns Enriched RudderEvent object
3560
+ */var getEnrichedEvent=function getEnrichedEvent(rudderEvent,options,pageProps,logger){var _state$storage$entrie;var commonEventData={channel:CHANNEL,context:_objectSpread2(_objectSpread2({traits:clone(state.session.userTraits.value),sessionId:state.session.sessionInfo.value.id||undefined,sessionStart:state.session.sessionInfo.value.sessionStart||undefined},state.consents.enabled.value&&{consentManagement:{deniedConsentIds:clone(state.consents.data.value.deniedConsentIds),allowedConsentIds:clone(state.consents.data.value.allowedConsentIds),provider:state.consents.provider.value,resolutionStrategy:state.consents.resolutionStrategy.value}}),{},{'ua-ch':state.context['ua-ch'].value,app:state.context.app.value,library:state.context.library.value,userAgent:state.context.userAgent.value,os:state.context.os.value,locale:state.context.locale.value,screen:state.context.screen.value,campaign:extractUTMParameters(globalThis.location.href),page:getContextPageProperties(pageProps),timezone:state.context.timezone.value}),originalTimestamp:getCurrentTimeFormatted(),integrations:DEFAULT_INTEGRATIONS_CONFIG,messageId:generateUUID(),userId:rudderEvent.userId||state.session.userId.value};if(!isStorageTypeValidForStoringData((_state$storage$entrie=state.storage.entries.value.anonymousId)===null||_state$storage$entrie===void 0?void 0:_state$storage$entrie.type)){// Generate new anonymous id for each request
3561
+ commonEventData.anonymousId=generateAnonymousId();}else {// Type casting to string as the user session manager will take care of initializing the value
3562
+ commonEventData.anonymousId=state.session.anonymousId.value;}// set truly anonymous tracking flag
3563
+ if(state.storage.trulyAnonymousTracking.value){commonEventData.context.trulyAnonymousTracking=true;}if(rudderEvent.type==='identify'){var _state$storage$entrie2;commonEventData.context.traits=((_state$storage$entrie2=state.storage.entries.value.userTraits)===null||_state$storage$entrie2===void 0?void 0:_state$storage$entrie2.type)!==NO_STORAGE?clone(state.session.userTraits.value):rudderEvent.context.traits;}if(rudderEvent.type==='group'){if(rudderEvent.groupId||state.session.groupId.value){commonEventData.groupId=rudderEvent.groupId||state.session.groupId.value;}if(rudderEvent.traits||state.session.groupTraits.value){var _state$storage$entrie3;commonEventData.traits=((_state$storage$entrie3=state.storage.entries.value.groupTraits)===null||_state$storage$entrie3===void 0?void 0:_state$storage$entrie3.type)!==NO_STORAGE?clone(state.session.groupTraits.value):rudderEvent.traits;}}var processedEvent=mergeDeepRight(rudderEvent,commonEventData);// Set the default values for the event properties
3564
+ // matching with v1.1 payload
3565
+ if(processedEvent.event===undefined){processedEvent.event=null;}if(processedEvent.properties===undefined){processedEvent.properties=null;}processOptions(processedEvent,options);checkForReservedElements(processedEvent,logger);// Update the integrations config for the event
3566
+ processedEvent.integrations=getEventIntegrationsConfig(processedEvent.integrations);return processedEvent;};
3567
+
3568
+ var RudderEventFactory=/*#__PURE__*/function(){function RudderEventFactory(logger){_classCallCheck(this,RudderEventFactory);this.logger=logger;}/**
3569
+ * Generate a 'page' event based on the user-input fields
3570
+ * @param category Page's category
3571
+ * @param name Page name
3572
+ * @param properties Page properties
3573
+ * @param options API options
3574
+ */return _createClass(RudderEventFactory,[{key:"generatePageEvent",value:function generatePageEvent(category,name,properties,options){var props=properties!==null&&properties!==void 0?properties:{};props=getUpdatedPageProperties(props,options);var pageEvent={properties:props,name:name,category:category,type:'page'};return getEnrichedEvent(pageEvent,options,props,this.logger);}/**
3575
+ * Generate a 'track' event based on the user-input fields
3576
+ * @param event The event name
3577
+ * @param properties Event properties
3578
+ * @param options API options
3579
+ */},{key:"generateTrackEvent",value:function generateTrackEvent(event,properties,options){var trackEvent={properties:properties,event:event,type:'track'};return getEnrichedEvent(trackEvent,options,undefined,this.logger);}/**
3580
+ * Generate an 'identify' event based on the user-input fields
3581
+ * @param userId New user ID
3582
+ * @param traits new traits
3583
+ * @param options API options
3584
+ */},{key:"generateIdentifyEvent",value:function generateIdentifyEvent(userId,traits,options){var identifyEvent={userId:userId,type:'identify',context:{traits:traits}};return getEnrichedEvent(identifyEvent,options,undefined,this.logger);}/**
3585
+ * Generate an 'alias' event based on the user-input fields
3586
+ * @param to New user ID
3587
+ * @param from Old user ID
3588
+ * @param options API options
3589
+ */},{key:"generateAliasEvent",value:function generateAliasEvent(to,from,options){var aliasEvent={previousId:from,type:'alias'};var enrichedEvent=getEnrichedEvent(aliasEvent,options,undefined,this.logger);// override the User ID from the API inputs
3590
+ enrichedEvent.userId=to!==null&&to!==void 0?to:enrichedEvent.userId;return enrichedEvent;}/**
3591
+ * Generate a 'group' event based on the user-input fields
3592
+ * @param groupId New group ID
3593
+ * @param traits new group traits
3594
+ * @param options API options
3595
+ */},{key:"generateGroupEvent",value:function generateGroupEvent(groupId,traits,options){var groupEvent={type:'group'};if(groupId){groupEvent.groupId=groupId;}if(traits){groupEvent.traits=traits;}return getEnrichedEvent(groupEvent,options,undefined,this.logger);}/**
3596
+ * Generates a new RudderEvent object based on the user-input fields
3597
+ * @param event API event parameters object
3598
+ * @returns A RudderEvent object
3599
+ */},{key:"create",value:function create(event){var eventObj;switch(event.type){case'page':eventObj=this.generatePageEvent(event.category,event.name,event.properties,event.options);break;case'track':eventObj=this.generateTrackEvent(event.name,event.properties,event.options);break;case'identify':eventObj=this.generateIdentifyEvent(event.userId,event.traits,event.options);break;case'alias':eventObj=this.generateAliasEvent(event.to,event.from,event.options);break;case'group':eventObj=this.generateGroupEvent(event.groupId,event.traits,event.options);break;}return eventObj;}}]);}();
3600
+
3601
+ /**
3602
+ * A service to generate valid event payloads and queue them for processing
3603
+ */var EventManager=/*#__PURE__*/function(){/**
3604
+ *
3605
+ * @param eventRepository Event repository instance
3606
+ * @param userSessionManager UserSession Manager instance
3607
+ * @param errorHandler Error handler object
3608
+ * @param logger Logger object
3609
+ */function EventManager(eventRepository,userSessionManager,errorHandler,logger){_classCallCheck(this,EventManager);this.eventRepository=eventRepository;this.userSessionManager=userSessionManager;this.errorHandler=errorHandler;this.logger=logger;this.eventFactory=new RudderEventFactory(this.logger);this.onError=this.onError.bind(this);}/**
3610
+ * Initializes the event manager
3611
+ */return _createClass(EventManager,[{key:"init",value:function init(){this.eventRepository.init();}},{key:"resume",value:function resume(){this.eventRepository.resume();}/**
3612
+ * Consumes a new incoming event
3613
+ * @param event Incoming event data
3614
+ */},{key:"addEvent",value:function addEvent(event){this.userSessionManager.refreshSession();var rudderEvent=this.eventFactory.create(event);if(rudderEvent){this.eventRepository.enqueue(rudderEvent,event.callback);}else {this.onError(new Error(EVENT_OBJECT_GENERATION_ERROR));}}/**
3615
+ * Handles error
3616
+ * @param error The error object
3617
+ */},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.errorHandler){this.errorHandler.onError(error,EVENT_MANAGER,customMessage,shouldAlwaysThrow);}else {throw error;}}}]);}();
3618
+
3619
+ var UserSessionManager=/*#__PURE__*/function(){function UserSessionManager(errorHandler,logger,pluginsManager,storeManager,httpClient){_classCallCheck(this,UserSessionManager);this.storeManager=storeManager;this.pluginsManager=pluginsManager;this.logger=logger;this.errorHandler=errorHandler;this.httpClient=httpClient;this.onError=this.onError.bind(this);this.serverSideCookieDebounceFuncs={};}/**
3620
+ * Initialize User session with values from storage
3621
+ */return _createClass(UserSessionManager,[{key:"init",value:function init(){this.syncStorageDataToState();// Register the effect to sync with storage
3622
+ this.registerEffects();}},{key:"syncStorageDataToState",value:function syncStorageDataToState(){var _externalAnonymousId;this.migrateStorageIfNeeded();this.migrateDataFromPreviousStorage();// get the values from storage and set it again
3623
+ this.setUserId(this.getUserId());this.setUserTraits(this.getUserTraits());this.setGroupId(this.getGroupId());this.setGroupTraits(this.getGroupTraits());var _state$loadOptions$va=state.loadOptions.value,externalAnonymousIdCookieName=_state$loadOptions$va.externalAnonymousIdCookieName,anonymousIdOptions=_state$loadOptions$va.anonymousIdOptions;var externalAnonymousId;if(isDefinedAndNotNull(externalAnonymousIdCookieName)&&typeof externalAnonymousIdCookieName==='string'){externalAnonymousId=this.getExternalAnonymousIdByCookieName(externalAnonymousIdCookieName);}this.setAnonymousId((_externalAnonymousId=externalAnonymousId)!==null&&_externalAnonymousId!==void 0?_externalAnonymousId:this.getAnonymousId(anonymousIdOptions));this.setAuthToken(this.getAuthToken());this.setInitialReferrerInfo();this.configureSessionTracking();}},{key:"configureSessionTracking",value:function configureSessionTracking(){var sessionInfo=this.getSessionInfo();if(this.isPersistenceEnabledForStorageEntry('sessionInfo')){var _sessionInfo;var configuredSessionTrackingInfo=this.getConfiguredSessionTrackingInfo();var initialSessionInfo=(_sessionInfo=sessionInfo)!==null&&_sessionInfo!==void 0?_sessionInfo:defaultSessionConfiguration;sessionInfo=_objectSpread2(_objectSpread2(_objectSpread2({},initialSessionInfo),configuredSessionTrackingInfo),{},{autoTrack:configuredSessionTrackingInfo.autoTrack&&initialSessionInfo.manualTrack!==true});}state.session.sessionInfo.value=this.isPersistenceEnabledForStorageEntry('sessionInfo')?sessionInfo:DEFAULT_USER_SESSION_VALUES.sessionInfo;// If auto session tracking is enabled start the session tracking
3624
+ if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking(state.session.sessionInfo.value);}}},{key:"setInitialReferrerInfo",value:function setInitialReferrerInfo(){var persistedInitialReferrer=this.getInitialReferrer();var persistedInitialReferringDomain=this.getInitialReferringDomain();if(persistedInitialReferrer&&persistedInitialReferringDomain){this.setInitialReferrer(persistedInitialReferrer);this.setInitialReferringDomain(persistedInitialReferringDomain);}else {var initialReferrer=persistedInitialReferrer||getReferrer();this.setInitialReferrer(initialReferrer);this.setInitialReferringDomain(getReferringDomain(initialReferrer));}}},{key:"isPersistenceEnabledForStorageEntry",value:function isPersistenceEnabledForStorageEntry(entryName){var _state$storage$entrie;return isStorageTypeValidForStoringData((_state$storage$entrie=state.storage.entries.value[entryName])===null||_state$storage$entrie===void 0?void 0:_state$storage$entrie.type);}},{key:"migrateDataFromPreviousStorage",value:function migrateDataFromPreviousStorage(){var _this=this;var entries=state.storage.entries.value;var storageTypesForMigration=[COOKIE_STORAGE,LOCAL_STORAGE,SESSION_STORAGE];Object.keys(entries).forEach(function(entry){var _entries$key,_this$storeManager;var key=entry;var currentStorage=(_entries$key=entries[key])===null||_entries$key===void 0?void 0:_entries$key.type;var curStore=(_this$storeManager=_this.storeManager)===null||_this$storeManager===void 0?void 0:_this$storeManager.getStore(storageClientDataStoreNameMap[currentStorage]);if(curStore){storageTypesForMigration.forEach(function(storage){var _this$storeManager2;var store=(_this$storeManager2=_this.storeManager)===null||_this$storeManager2===void 0?void 0:_this$storeManager2.getStore(storageClientDataStoreNameMap[storage]);if(store&&storage!==currentStorage){var value=store.get(COOKIE_KEYS[key]);if(isDefinedNotNullAndNotEmptyString(value)){curStore.set(COOKIE_KEYS[key],value);}store.remove(COOKIE_KEYS[key]);}});}});}},{key:"migrateStorageIfNeeded",value:function migrateStorageIfNeeded(){var _this2=this;if(!state.storage.migrate.value){return;}var persistentStoreNames=[CLIENT_DATA_STORE_COOKIE,CLIENT_DATA_STORE_LS,CLIENT_DATA_STORE_SESSION];var stores=[];persistentStoreNames.forEach(function(storeName){var _this2$storeManager;var store=(_this2$storeManager=_this2.storeManager)===null||_this2$storeManager===void 0?void 0:_this2$storeManager.getStore(storeName);if(store){stores.push(store);}});Object.keys(COOKIE_KEYS).forEach(function(storageKey){var storageEntry=COOKIE_KEYS[storageKey];stores.forEach(function(store){var _this2$pluginsManager;var migratedVal=(_this2$pluginsManager=_this2.pluginsManager)===null||_this2$pluginsManager===void 0?void 0:_this2$pluginsManager.invokeSingle('storage.migrate',storageEntry,store.engine,_this2.errorHandler,_this2.logger);// Skip setting the value if it is null or undefined
3625
+ // as those values indicate there is no need for migration or
3626
+ // migration failed
3627
+ if(!isNullOrUndefined(migratedVal)){store.set(storageEntry,migratedVal);}});});}},{key:"getConfiguredSessionTrackingInfo",value:function getConfiguredSessionTrackingInfo(){var _state$loadOptions$va2,_state$loadOptions$va3;var autoTrack=((_state$loadOptions$va2=state.loadOptions.value.sessions)===null||_state$loadOptions$va2===void 0?void 0:_state$loadOptions$va2.autoTrack)!==false;// Do not validate any further if autoTrack is disabled
3628
+ if(!autoTrack){return {autoTrack:autoTrack};}var timeout;var configuredSessionTimeout=(_state$loadOptions$va3=state.loadOptions.value.sessions)===null||_state$loadOptions$va3===void 0?void 0:_state$loadOptions$va3.timeout;if(!isPositiveInteger(configuredSessionTimeout)){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.warn(TIMEOUT_NOT_NUMBER_WARNING(USER_SESSION_MANAGER,configuredSessionTimeout,DEFAULT_SESSION_TIMEOUT_MS));timeout=DEFAULT_SESSION_TIMEOUT_MS;}else {timeout=configuredSessionTimeout;}if(timeout===0){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.warn(TIMEOUT_ZERO_WARNING(USER_SESSION_MANAGER));autoTrack=false;}// In case user provides a timeout value greater than 0 but less than 10 seconds SDK will show a warning
3629
+ // and will proceed with it
3630
+ if(timeout>0&&timeout<MIN_SESSION_TIMEOUT_MS){var _this$logger3;(_this$logger3=this.logger)===null||_this$logger3===void 0||_this$logger3.warn(TIMEOUT_NOT_RECOMMENDED_WARNING(USER_SESSION_MANAGER,timeout,MIN_SESSION_TIMEOUT_MS));}return {timeout:timeout,autoTrack:autoTrack};}/**
3631
+ * Handles error
3632
+ * @param error The error object
3633
+ */},{key:"onError",value:function onError(error,customMessage){if(this.errorHandler){this.errorHandler.onError(error,USER_SESSION_MANAGER,customMessage);}else {throw error;}}/**
3634
+ * A function to encrypt the cookie value and return the encrypted data
3635
+ * @param cookiesData
3636
+ * @param store
3637
+ * @returns
3638
+ */},{key:"getEncryptedCookieData",value:function getEncryptedCookieData(cookiesData,store){var _this3=this;var encryptedCookieData=[];cookiesData.forEach(function(cData){var encryptedValue=store===null||store===void 0?void 0:store.encrypt(stringifyWithoutCircular(cData.value,false,[],_this3.logger));if(isDefinedAndNotNull(encryptedValue)){encryptedCookieData.push({name:cData.name,value:encryptedValue});}});return encryptedCookieData;}/**
3639
+ * A function that makes request to data service to set the cookie
3640
+ * @param encryptedCookieData
3641
+ * @param callback
3642
+ */},{key:"makeRequestToSetCookie",value:function makeRequestToSetCookie(encryptedCookieData,callback){var _this$httpClient,_state$source$value,_state$storage$cookie,_state$storage$cookie2,_state$storage$cookie3,_state$storage$cookie4,_state$storage$cookie5,_state$storage$cookie6;(_this$httpClient=this.httpClient)===null||_this$httpClient===void 0||_this$httpClient.getAsyncData({url:state.serverCookies.dataServiceUrl.value,options:{method:'POST',data:stringifyWithoutCircular({reqType:'setCookies',workspaceId:(_state$source$value=state.source.value)===null||_state$source$value===void 0?void 0:_state$source$value.workspaceId,data:{options:{maxAge:(_state$storage$cookie=state.storage.cookie.value)===null||_state$storage$cookie===void 0?void 0:_state$storage$cookie.maxage,path:(_state$storage$cookie2=state.storage.cookie.value)===null||_state$storage$cookie2===void 0?void 0:_state$storage$cookie2.path,domain:(_state$storage$cookie3=state.storage.cookie.value)===null||_state$storage$cookie3===void 0?void 0:_state$storage$cookie3.domain,sameSite:(_state$storage$cookie4=state.storage.cookie.value)===null||_state$storage$cookie4===void 0?void 0:_state$storage$cookie4.samesite,secure:(_state$storage$cookie5=state.storage.cookie.value)===null||_state$storage$cookie5===void 0?void 0:_state$storage$cookie5.secure,expires:(_state$storage$cookie6=state.storage.cookie.value)===null||_state$storage$cookie6===void 0?void 0:_state$storage$cookie6.expires},cookies:encryptedCookieData}}),sendRawData:true,withCredentials:true},isRawResponse:true,callback:callback});}/**
3643
+ * A function to make an external request to set the cookie from server side
3644
+ * @param key cookie name
3645
+ * @param value encrypted cookie value
3646
+ */},{key:"setServerSideCookies",value:function setServerSideCookies(cookiesData,cb,store){var _this4=this;try{// encrypt cookies values
3647
+ var encryptedCookieData=this.getEncryptedCookieData(cookiesData,store);if(encryptedCookieData.length>0){// make request to data service to set the cookie from server side
3648
+ this.makeRequestToSetCookie(encryptedCookieData,function(res,details){var _details$xhr;if((details===null||details===void 0||(_details$xhr=details.xhr)===null||_details$xhr===void 0?void 0:_details$xhr.status)===200){cookiesData.forEach(function(cData){var cookieValue=store===null||store===void 0?void 0:store.get(cData.name);var before=stringifyWithoutCircular(cData.value,false,[]);var after=stringifyWithoutCircular(cookieValue,false,[]);if(after!==before){var _this4$logger;(_this4$logger=_this4.logger)===null||_this4$logger===void 0||_this4$logger.error(FAILED_SETTING_COOKIE_FROM_SERVER_ERROR(cData.name));if(cb){cb(cData.name,cData.value);}}});}else {var _this4$logger2,_details$xhr2;(_this4$logger2=_this4.logger)===null||_this4$logger2===void 0||_this4$logger2.error(DATA_SERVER_REQUEST_FAIL_ERROR(details===null||details===void 0||(_details$xhr2=details.xhr)===null||_details$xhr2===void 0?void 0:_details$xhr2.status));cookiesData.forEach(function(each){if(cb){cb(each.name,each.value);}});}});}}catch(e){this.onError(e,FAILED_SETTING_COOKIE_FROM_SERVER_GLOBAL_ERROR);cookiesData.forEach(function(each){if(cb){cb(each.name,each.value);}});}}/**
3649
+ * A function to sync values in storage
3650
+ * @param sessionKey
3651
+ * @param value
3652
+ */},{key:"syncValueToStorage",value:function syncValueToStorage(sessionKey,value){var _entries$sessionKey,_this5=this;var entries=state.storage.entries.value;var storageType=(_entries$sessionKey=entries[sessionKey])===null||_entries$sessionKey===void 0?void 0:_entries$sessionKey.type;if(isStorageTypeValidForStoringData(storageType)){var _this$storeManager3,_entries$sessionKey2;var curStore=(_this$storeManager3=this.storeManager)===null||_this$storeManager3===void 0?void 0:_this$storeManager3.getStore(storageClientDataStoreNameMap[storageType]);var key=(_entries$sessionKey2=entries[sessionKey])===null||_entries$sessionKey2===void 0?void 0:_entries$sessionKey2.key;if(value&&(isString(value)||isNonEmptyObject(value))){// if useServerSideCookies load option is set to true
3653
+ // set the cookie from server side
3654
+ if(state.serverCookies.isEnabledServerSideCookies.value&&storageType===COOKIE_STORAGE){if(this.serverSideCookieDebounceFuncs[sessionKey]){globalThis.clearTimeout(this.serverSideCookieDebounceFuncs[sessionKey]);}this.serverSideCookieDebounceFuncs[sessionKey]=globalThis.setTimeout(function(){_this5.setServerSideCookies([{name:key,value:value}],function(cookieName,cookieValue){curStore===null||curStore===void 0||curStore.set(cookieName,cookieValue);},curStore);},SERVER_SIDE_COOKIES_DEBOUNCE_TIME);}else {curStore===null||curStore===void 0||curStore.set(key,value);}}else {curStore===null||curStore===void 0||curStore.remove(key);}}}/**
3655
+ * Function to update storage whenever state value changes
3656
+ */},{key:"registerEffects",value:function registerEffects(){var _this6=this;// This will work as long as the user session entry key names are same as the state keys
3657
+ USER_SESSION_KEYS.forEach(function(sessionKey){E(function(){_this6.syncValueToStorage(sessionKey,state.session[sessionKey].value);});});}/**
3658
+ * Sets anonymous id in the following precedence:
3659
+ *
3660
+ * 1. anonymousId: Id directly provided to the function.
3661
+ * 2. rudderAmpLinkerParam: value generated from linker query parm (rudderstack)
3662
+ * using parseLinker util.
3663
+ * 3. generateUUID: A new unique id is generated and assigned.
3664
+ */},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){var finalAnonymousId=anonymousId;if(this.isPersistenceEnabledForStorageEntry('anonymousId')){if(!finalAnonymousId&&rudderAmpLinkerParam){var _this$pluginsManager;var linkerPluginsResult=(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===void 0?void 0:_this$pluginsManager.invokeSingle('userSession.anonymousIdGoogleLinker',rudderAmpLinkerParam);finalAnonymousId=linkerPluginsResult;}finalAnonymousId=finalAnonymousId||generateAnonymousId();}else {finalAnonymousId=DEFAULT_USER_SESSION_VALUES.anonymousId;}state.session.anonymousId.value=finalAnonymousId;}/**
3665
+ * Fetches anonymousId
3666
+ * @param options option to fetch it from external source
3667
+ * @returns anonymousId
3668
+ */},{key:"getAnonymousId",value:function getAnonymousId(options){var _state$storage$entrie2;var storage=(_state$storage$entrie2=state.storage.entries.value.anonymousId)===null||_state$storage$entrie2===void 0?void 0:_state$storage$entrie2.type;// fetch the anonymousId from storage
3669
+ if(isStorageTypeValidForStoringData(storage)){var persistedAnonymousId=this.getEntryValue('anonymousId');if(!persistedAnonymousId&&options){var _this$pluginsManager2;// fetch anonymousId from external source
3670
+ var autoCapturedAnonymousId=(_this$pluginsManager2=this.pluginsManager)===null||_this$pluginsManager2===void 0?void 0:_this$pluginsManager2.invokeSingle('storage.getAnonymousId',getStorageEngine,options);persistedAnonymousId=autoCapturedAnonymousId;}state.session.anonymousId.value=persistedAnonymousId||generateAnonymousId();}return state.session.anonymousId.value;}},{key:"getEntryValue",value:function getEntryValue(sessionKey){var _entries$sessionKey3;var entries=state.storage.entries.value;var storageType=(_entries$sessionKey3=entries[sessionKey])===null||_entries$sessionKey3===void 0?void 0:_entries$sessionKey3.type;if(isStorageTypeValidForStoringData(storageType)){var _this$storeManager4,_entries$sessionKey4,_store$get;var store=(_this$storeManager4=this.storeManager)===null||_this$storeManager4===void 0?void 0:_this$storeManager4.getStore(storageClientDataStoreNameMap[storageType]);var storageKey=(_entries$sessionKey4=entries[sessionKey])===null||_entries$sessionKey4===void 0?void 0:_entries$sessionKey4.key;return (_store$get=store===null||store===void 0?void 0:store.get(storageKey))!==null&&_store$get!==void 0?_store$get:null;}return null;}},{key:"getExternalAnonymousIdByCookieName",value:function getExternalAnonymousIdByCookieName(key){var storageEngine=getStorageEngine(COOKIE_STORAGE);if(storageEngine!==null&&storageEngine!==void 0&&storageEngine.isEnabled){var _storageEngine$getIte;return (_storageEngine$getIte=storageEngine.getItem(key))!==null&&_storageEngine$getIte!==void 0?_storageEngine$getIte:null;}return null;}/**
3671
+ * Fetches User Id
3672
+ * @returns
3673
+ */},{key:"getUserId",value:function getUserId(){return this.getEntryValue('userId');}/**
3674
+ * Fetches User Traits
3675
+ * @returns
3676
+ */},{key:"getUserTraits",value:function getUserTraits(){return this.getEntryValue('userTraits');}/**
3677
+ * Fetches Group Id
3678
+ * @returns
3679
+ */},{key:"getGroupId",value:function getGroupId(){return this.getEntryValue('groupId');}/**
3680
+ * Fetches Group Traits
3681
+ * @returns
3682
+ */},{key:"getGroupTraits",value:function getGroupTraits(){return this.getEntryValue('groupTraits');}/**
3683
+ * Fetches Initial Referrer
3684
+ * @returns
3685
+ */},{key:"getInitialReferrer",value:function getInitialReferrer(){return this.getEntryValue('initialReferrer');}/**
3686
+ * Fetches Initial Referring domain
3687
+ * @returns
3688
+ */},{key:"getInitialReferringDomain",value:function getInitialReferringDomain(){return this.getEntryValue('initialReferringDomain');}/**
3689
+ * Fetches session tracking information from storage
3690
+ * @returns
3691
+ */},{key:"getSessionInfo",value:function getSessionInfo(){return this.getEntryValue('sessionInfo');}/**
3692
+ * Fetches auth token from storage
3693
+ * @returns
3694
+ */},{key:"getAuthToken",value:function getAuthToken(){return this.getEntryValue('authToken');}/**
3695
+ * If session is active it returns the sessionId
3696
+ * @returns
3697
+ */},{key:"getSessionId",value:function getSessionId(){var _this$getSessionInfo;var sessionInfo=(_this$getSessionInfo=this.getSessionInfo())!==null&&_this$getSessionInfo!==void 0?_this$getSessionInfo:DEFAULT_USER_SESSION_VALUES.sessionInfo;if(sessionInfo.autoTrack&&!hasSessionExpired(sessionInfo.expiresAt)||sessionInfo.manualTrack){var _sessionInfo$id;return (_sessionInfo$id=sessionInfo.id)!==null&&_sessionInfo$id!==void 0?_sessionInfo$id:null;}return null;}/**
3698
+ * A function to keep the session information up to date in the state
3699
+ * before using it for building event payloads.
3700
+ */},{key:"refreshSession",value:function refreshSession(){var _this$getSessionInfo2;var sessionInfo=(_this$getSessionInfo2=this.getSessionInfo())!==null&&_this$getSessionInfo2!==void 0?_this$getSessionInfo2:DEFAULT_USER_SESSION_VALUES.sessionInfo;if(sessionInfo.autoTrack||sessionInfo.manualTrack){if(sessionInfo.autoTrack){this.startOrRenewAutoTracking(sessionInfo);sessionInfo=state.session.sessionInfo.value;}// Note that if sessionStart is false, then it's an active session.
3701
+ // So, we needn't update the session info.
3702
+ //
3703
+ // For other scenarios,
3704
+ // 1. If sessionStart is undefined, then it's a new session.
3705
+ // Mark it as sessionStart.
3706
+ // 2. If sessionStart is true, then need to flip it for the future events.
3707
+ if(sessionInfo.sessionStart===undefined){sessionInfo=_objectSpread2(_objectSpread2({},sessionInfo),{},{sessionStart:true});}else if(sessionInfo.sessionStart){sessionInfo=_objectSpread2(_objectSpread2({},sessionInfo),{},{sessionStart:false});}}// Always write to state (in-turn to storage) to keep the session info up to date.
3708
+ state.session.sessionInfo.value=sessionInfo;if(state.lifecycle.status.value!=='readyExecuted'){// Force update the storage as the 'effect' blocks are not getting triggered
3709
+ // when processing preload buffered requests
3710
+ this.syncValueToStorage('sessionInfo',sessionInfo);}}/**
3711
+ * Reset state values
3712
+ * @param resetAnonymousId
3713
+ * @param noNewSessionStart
3714
+ * @returns
3715
+ */},{key:"reset",value:function reset(resetAnonymousId,noNewSessionStart){var _this7=this;var session=state.session;var _session$sessionInfo$=session.sessionInfo.value,manualTrack=_session$sessionInfo$.manualTrack,autoTrack=_session$sessionInfo$.autoTrack;r(function(){session.userId.value=DEFAULT_USER_SESSION_VALUES.userId;session.userTraits.value=DEFAULT_USER_SESSION_VALUES.userTraits;session.groupId.value=DEFAULT_USER_SESSION_VALUES.groupId;session.groupTraits.value=DEFAULT_USER_SESSION_VALUES.groupTraits;session.authToken.value=DEFAULT_USER_SESSION_VALUES.authToken;if(resetAnonymousId){// This will generate a new anonymous ID
3716
+ _this7.setAnonymousId();}if(noNewSessionStart){return;}if(autoTrack){session.sessionInfo.value=DEFAULT_USER_SESSION_VALUES.sessionInfo;_this7.startOrRenewAutoTracking(session.sessionInfo.value);}else if(manualTrack){_this7.startManualTrackingInternal();}});}/**
3717
+ * Set user Id
3718
+ * @param userId
3719
+ */},{key:"setUserId",value:function setUserId(userId){state.session.userId.value=this.isPersistenceEnabledForStorageEntry('userId')&&userId?userId:DEFAULT_USER_SESSION_VALUES.userId;}/**
3720
+ * Set user traits
3721
+ * @param traits
3722
+ */},{key:"setUserTraits",value:function setUserTraits(traits){var _state$session$userTr;state.session.userTraits.value=this.isPersistenceEnabledForStorageEntry('userTraits')&&traits?mergeDeepRight((_state$session$userTr=state.session.userTraits.value)!==null&&_state$session$userTr!==void 0?_state$session$userTr:DEFAULT_USER_SESSION_VALUES.userTraits,traits):DEFAULT_USER_SESSION_VALUES.userTraits;}/**
3723
+ * Set group Id
3724
+ * @param groupId
3725
+ */},{key:"setGroupId",value:function setGroupId(groupId){state.session.groupId.value=this.isPersistenceEnabledForStorageEntry('groupId')&&groupId?groupId:DEFAULT_USER_SESSION_VALUES.groupId;}/**
3726
+ * Set group traits
3727
+ * @param traits
3728
+ */},{key:"setGroupTraits",value:function setGroupTraits(traits){var _state$session$groupT;state.session.groupTraits.value=this.isPersistenceEnabledForStorageEntry('groupTraits')&&traits?mergeDeepRight((_state$session$groupT=state.session.groupTraits.value)!==null&&_state$session$groupT!==void 0?_state$session$groupT:DEFAULT_USER_SESSION_VALUES.groupTraits,traits):DEFAULT_USER_SESSION_VALUES.groupTraits;}/**
3729
+ * Set initial referrer
3730
+ * @param referrer
3731
+ */},{key:"setInitialReferrer",value:function setInitialReferrer(referrer){state.session.initialReferrer.value=this.isPersistenceEnabledForStorageEntry('initialReferrer')&&referrer?referrer:DEFAULT_USER_SESSION_VALUES.initialReferrer;}/**
3732
+ * Set initial referring domain
3733
+ * @param {String} referringDomain
3734
+ */},{key:"setInitialReferringDomain",value:function setInitialReferringDomain(referringDomain){state.session.initialReferringDomain.value=this.isPersistenceEnabledForStorageEntry('initialReferringDomain')&&referringDomain?referringDomain:DEFAULT_USER_SESSION_VALUES.initialReferringDomain;}/**
3735
+ * A function to check for existing session details and depending on that create a new session
3736
+ */},{key:"startOrRenewAutoTracking",value:function startOrRenewAutoTracking(sessionInfo){if(hasSessionExpired(sessionInfo.expiresAt)){state.session.sessionInfo.value=generateAutoTrackingSession(sessionInfo.timeout);}else {var timestamp=Date.now();var timeout=sessionInfo.timeout;state.session.sessionInfo.value=mergeDeepRight(sessionInfo,{expiresAt:timestamp+timeout// set the expiry time of the session
3737
+ });}}/**
3738
+ * A function method to start a manual session
3739
+ * @param {number} id session identifier
3740
+ * @returns
3741
+ */},{key:"start",value:function start(id){state.session.sessionInfo.value=generateManualTrackingSession(id,this.logger);}/**
3742
+ * An internal function to start manual session
3743
+ */},{key:"startManualTrackingInternal",value:function startManualTrackingInternal(){this.start(Date.now());}/**
3744
+ * A public method to end an ongoing session.
3745
+ */},{key:"end",value:function end(){state.session.sessionInfo.value=DEFAULT_USER_SESSION_VALUES.sessionInfo;}/**
3746
+ * Set auth token
3747
+ * @param userId
3748
+ */},{key:"setAuthToken",value:function setAuthToken(token){state.session.authToken.value=this.isPersistenceEnabledForStorageEntry('authToken')&&token?token:DEFAULT_USER_SESSION_VALUES.authToken;}}]);}();
3749
+
3750
+ /**
3751
+ * Plugins to be loaded in the plugins loadOption is not defined
3752
+ */var defaultOptionalPluginsList=['BeaconQueue','Bugsnag','CustomConsentManager','DeviceModeDestinations','DeviceModeTransformation','ErrorReporting','ExternalAnonymousId','GoogleLinker','KetchConsentManager','NativeDestinationQueue','OneTrustConsentManager','StorageEncryption','StorageEncryptionLegacy','StorageMigrator','XhrQueue'];
3753
+
3754
+ var normalizeLoadOptions=function normalizeLoadOptions(loadOptionsFromState,loadOptions){var _normalizedLoadOpts$p,_normalizedLoadOpts$s2;// TODO: Maybe add warnings for invalid values
3755
+ var normalizedLoadOpts=clone(loadOptions);if(!isString(normalizedLoadOpts.setCookieDomain)){delete normalizedLoadOpts.setCookieDomain;}var cookieSameSiteValues=['Strict','Lax','None'];if(!cookieSameSiteValues.includes(normalizedLoadOpts.sameSiteCookie)){delete normalizedLoadOpts.sameSiteCookie;}normalizedLoadOpts.secureCookie=normalizedLoadOpts.secureCookie===true;var uaChTrackLevels=['none','default','full'];if(!uaChTrackLevels.includes(normalizedLoadOpts.uaChTrackLevel)){delete normalizedLoadOpts.uaChTrackLevel;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.integrations)){delete normalizedLoadOpts.integrations;}normalizedLoadOpts.plugins=(_normalizedLoadOpts$p=normalizedLoadOpts.plugins)!==null&&_normalizedLoadOpts$p!==void 0?_normalizedLoadOpts$p:defaultOptionalPluginsList;normalizedLoadOpts.useGlobalIntegrationsConfigInEvents=normalizedLoadOpts.useGlobalIntegrationsConfigInEvents===true;normalizedLoadOpts.bufferDataPlaneEventsUntilReady=normalizedLoadOpts.bufferDataPlaneEventsUntilReady===true;normalizedLoadOpts.sendAdblockPage=normalizedLoadOpts.sendAdblockPage===true;normalizedLoadOpts.useServerSideCookies=normalizedLoadOpts.useServerSideCookies===true;if(normalizedLoadOpts.dataServiceEndpoint&&typeof normalizedLoadOpts.dataServiceEndpoint!=='string'){delete normalizedLoadOpts.dataServiceEndpoint;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.sendAdblockPageOptions)){delete normalizedLoadOpts.sendAdblockPageOptions;}if(!isDefined(normalizedLoadOpts.loadIntegration)){delete normalizedLoadOpts.loadIntegration;}else {normalizedLoadOpts.loadIntegration=normalizedLoadOpts.loadIntegration===true;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.storage)){delete normalizedLoadOpts.storage;}else {var _normalizedLoadOpts$s;normalizedLoadOpts.storage=removeUndefinedAndNullValues(normalizedLoadOpts.storage);normalizedLoadOpts.storage.migrate=((_normalizedLoadOpts$s=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s===void 0?void 0:_normalizedLoadOpts$s.migrate)===true;}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.beaconQueueOptions)){delete normalizedLoadOpts.beaconQueueOptions;}else {normalizedLoadOpts.beaconQueueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.beaconQueueOptions);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.destinationsQueueOptions)){delete normalizedLoadOpts.destinationsQueueOptions;}else {normalizedLoadOpts.destinationsQueueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.destinationsQueueOptions);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.queueOptions)){delete normalizedLoadOpts.queueOptions;}else {normalizedLoadOpts.queueOptions=removeUndefinedAndNullValues(normalizedLoadOpts.queueOptions);}normalizedLoadOpts.lockIntegrationsVersion=normalizedLoadOpts.lockIntegrationsVersion===true;normalizedLoadOpts.lockPluginsVersion=normalizedLoadOpts.lockPluginsVersion===true;if(!isNumber(normalizedLoadOpts.dataPlaneEventsBufferTimeout)){delete normalizedLoadOpts.dataPlaneEventsBufferTimeout;}if(!isObjectLiteralAndNotNull((_normalizedLoadOpts$s2=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s2===void 0?void 0:_normalizedLoadOpts$s2.cookie)){var _normalizedLoadOpts$s3;(_normalizedLoadOpts$s3=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s3===void 0||delete _normalizedLoadOpts$s3.cookie;}else {var _normalizedLoadOpts$s4;normalizedLoadOpts.storage.cookie=removeUndefinedAndNullValues((_normalizedLoadOpts$s4=normalizedLoadOpts.storage)===null||_normalizedLoadOpts$s4===void 0?void 0:_normalizedLoadOpts$s4.cookie);}if(!isObjectLiteralAndNotNull(normalizedLoadOpts.preConsent)){delete normalizedLoadOpts.preConsent;}else {normalizedLoadOpts.preConsent=removeUndefinedAndNullValues(normalizedLoadOpts.preConsent);}var mergedLoadOptions=mergeDeepRight(loadOptionsFromState,normalizedLoadOpts);return mergedLoadOptions;};
3756
+
3757
+ var DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';var DESTINATIONS_QUEUE_EXT_POINT_PREFIX='destinationsEventsQueue';var DMT_EXT_POINT_PREFIX='transformEvent';
3758
+
3759
+ /**
3760
+ * Filters and returns the user supplied integrations config that should take preference over the destination specific integrations config
3761
+ * @param eventIntgConfig User supplied integrations config at event level
3762
+ * @param destinationsIntgConfig Cumulative integrations config from all destinations
3763
+ * @returns Filtered user supplied integrations config
3764
+ */var getOverriddenIntegrationOptions=function getOverriddenIntegrationOptions(eventIntgConfig,destinationsIntgConfig){return Object.keys(eventIntgConfig).filter(function(intgName){return eventIntgConfig[intgName]!==true||!destinationsIntgConfig[intgName];}).reduce(function(obj,key){var retVal=clone(obj);retVal[key]=eventIntgConfig[key];return retVal;},{});};/**
3765
+ * Returns the event object with final integrations config
3766
+ * @param event RudderEvent object
3767
+ * @param state Application state
3768
+ * @returns Mutated event with final integrations config
3769
+ */var getFinalEvent=function getFinalEvent(event,state){var _event$integrations;var finalEvent=clone(event);// Merge the destination specific integrations config with the event's integrations config
3770
+ // In general, the preference is given to the event's integrations config
3771
+ var eventIntgConfig=(_event$integrations=event.integrations)!==null&&_event$integrations!==void 0?_event$integrations:DEFAULT_INTEGRATIONS_CONFIG;var destinationsIntgConfig=state.nativeDestinations.integrationsConfig.value;var overriddenIntgOpts=getOverriddenIntegrationOptions(eventIntgConfig,destinationsIntgConfig);finalEvent.integrations=mergeDeepRight(destinationsIntgConfig,overriddenIntgOpts);return finalEvent;};var shouldBufferEventsForPreConsent=function shouldBufferEventsForPreConsent(state){var _state$consents$preCo,_state$consents$preCo2,_state$consents$preCo3;return state.consents.preConsent.value.enabled&&((_state$consents$preCo=state.consents.preConsent.value.events)===null||_state$consents$preCo===void 0?void 0:_state$consents$preCo.delivery)==='buffer'&&(((_state$consents$preCo2=state.consents.preConsent.value.storage)===null||_state$consents$preCo2===void 0?void 0:_state$consents$preCo2.strategy)==='session'||((_state$consents$preCo3=state.consents.preConsent.value.storage)===null||_state$consents$preCo3===void 0?void 0:_state$consents$preCo3.strategy)==='none');};
3772
+
3773
+ /**
3774
+ * Event repository class responsible for queuing events for further processing and delivery
3775
+ */var EventRepository=/*#__PURE__*/function(){/**
3776
+ *
3777
+ * @param pluginsManager Plugins manager instance
3778
+ * @param storeManager Store Manager instance
3779
+ * @param errorHandler Error handler object
3780
+ * @param logger Logger object
3781
+ */function EventRepository(pluginsManager,storeManager,errorHandler,logger){_classCallCheck(this,EventRepository);this.pluginsManager=pluginsManager;this.errorHandler=errorHandler;this.logger=logger;this.httpClient=new HttpClient(errorHandler,logger);this.storeManager=storeManager;this.onError=this.onError.bind(this);}/**
3782
+ * Initializes the event repository
3783
+ */return _createClass(EventRepository,[{key:"init",value:function init(){var _this=this;try{this.dataplaneEventsQueue=this.pluginsManager.invokeSingle("".concat(DATA_PLANE_QUEUE_EXT_POINT_PREFIX,".init"),state,this.httpClient,this.storeManager,this.errorHandler,this.logger);}catch(e){this.onError(e,DATAPLANE_PLUGIN_INITIALIZE_ERROR);}try{this.dmtEventsQueue=this.pluginsManager.invokeSingle("".concat(DMT_EXT_POINT_PREFIX,".init"),state,this.pluginsManager,this.httpClient,this.storeManager,this.errorHandler,this.logger);}catch(e){this.onError(e,DMT_PLUGIN_INITIALIZE_ERROR);}try{this.destinationsEventsQueue=this.pluginsManager.invokeSingle("".concat(DESTINATIONS_QUEUE_EXT_POINT_PREFIX,".init"),state,this.pluginsManager,this.storeManager,this.dmtEventsQueue,this.errorHandler,this.logger);}catch(e){this.onError(e,NATIVE_DEST_PLUGIN_INITIALIZE_ERROR);}// Start the queue once the client destinations are ready
3784
+ E(function(){if(state.nativeDestinations.clientDestinationsReady.value===true){var _this$destinationsEve,_this$dmtEventsQueue;(_this$destinationsEve=_this.destinationsEventsQueue)===null||_this$destinationsEve===void 0||_this$destinationsEve.start();(_this$dmtEventsQueue=_this.dmtEventsQueue)===null||_this$dmtEventsQueue===void 0||_this$dmtEventsQueue.start();}});var bufferEventsBeforeConsent=shouldBufferEventsForPreConsent(state);// Start the queue processing only when the destinations are ready or hybrid mode destinations exist
3785
+ // However, events will be enqueued for now.
3786
+ // At the time of processing the events, the integrations config data from destinations
3787
+ // is merged into the event object
3788
+ var timeoutId;E(function(){var _this$dataplaneEvents;var shouldBufferDpEvents=state.loadOptions.value.bufferDataPlaneEventsUntilReady===true&&state.nativeDestinations.clientDestinationsReady.value===false;var hybridDestExist=state.nativeDestinations.activeDestinations.value.some(function(dest){return isHybridModeDestination(dest);});if((hybridDestExist===false||shouldBufferDpEvents===false)&&!bufferEventsBeforeConsent&&((_this$dataplaneEvents=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents===void 0?void 0:_this$dataplaneEvents.scheduleTimeoutActive)!==true){var _this$dataplaneEvents2;globalThis.clearTimeout(timeoutId);(_this$dataplaneEvents2=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents2===void 0||_this$dataplaneEvents2.start();}});// Force start the data plane events queue processing after a timeout
3789
+ if(state.loadOptions.value.bufferDataPlaneEventsUntilReady===true){timeoutId=globalThis.setTimeout(function(){var _this$dataplaneEvents3;if(((_this$dataplaneEvents3=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents3===void 0?void 0:_this$dataplaneEvents3.scheduleTimeoutActive)!==true){var _this$dataplaneEvents4;(_this$dataplaneEvents4=_this.dataplaneEventsQueue)===null||_this$dataplaneEvents4===void 0||_this$dataplaneEvents4.start();}},state.loadOptions.value.dataPlaneEventsBufferTimeout);}}},{key:"resume",value:function resume(){var _this$dataplaneEvents5;if(((_this$dataplaneEvents5=this.dataplaneEventsQueue)===null||_this$dataplaneEvents5===void 0?void 0:_this$dataplaneEvents5.scheduleTimeoutActive)!==true){var _this$dataplaneEvents7;if(state.consents.postConsent.value.discardPreConsentEvents){var _this$dataplaneEvents6,_this$destinationsEve2;(_this$dataplaneEvents6=this.dataplaneEventsQueue)===null||_this$dataplaneEvents6===void 0||_this$dataplaneEvents6.clear();(_this$destinationsEve2=this.destinationsEventsQueue)===null||_this$destinationsEve2===void 0||_this$destinationsEve2.clear();}(_this$dataplaneEvents7=this.dataplaneEventsQueue)===null||_this$dataplaneEvents7===void 0||_this$dataplaneEvents7.start();}}/**
3790
+ * Enqueues the event for processing
3791
+ * @param event RudderEvent object
3792
+ * @param callback API callback function
3793
+ */},{key:"enqueue",value:function enqueue(event,callback){var dpQEvent;try{dpQEvent=getFinalEvent(event,state);this.pluginsManager.invokeSingle("".concat(DATA_PLANE_QUEUE_EXT_POINT_PREFIX,".enqueue"),state,this.dataplaneEventsQueue,dpQEvent,this.errorHandler,this.logger);}catch(e){this.onError(e,DATAPLANE_PLUGIN_ENQUEUE_ERROR);}try{var dQEvent=clone(event);this.pluginsManager.invokeSingle("".concat(DESTINATIONS_QUEUE_EXT_POINT_PREFIX,".enqueue"),state,this.destinationsEventsQueue,dQEvent,this.errorHandler,this.logger);}catch(e){this.onError(e,NATIVE_DEST_PLUGIN_ENQUEUE_ERROR);}// Invoke the callback if it exists
3794
+ try{// Using the event sent to the data plane queue here
3795
+ // to ensure the mutated (if any) event is sent to the callback
3796
+ callback===null||callback===void 0||callback(dpQEvent);}catch(error){this.onError(error,API_CALLBACK_INVOKE_ERROR);}}/**
3797
+ * Handles error
3798
+ * @param error The error object
3799
+ * @param customMessage a message
3800
+ * @param shouldAlwaysThrow if it should throw or use logger
3801
+ */},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.errorHandler){this.errorHandler.onError(error,EVENT_REPOSITORY,customMessage,shouldAlwaysThrow);}else {throw error;}}}]);}();
3802
+
3803
+ var dispatchSDKEvent=function dispatchSDKEvent(event){var customEvent=new CustomEvent(event,{detail:{analyticsInstance:globalThis.rudderanalytics},bubbles:true,cancelable:true,composed:true});globalThis.document.dispatchEvent(customEvent);};
3804
+
3805
+ /*
3806
+ * Analytics class with lifecycle based on state ad user triggered events
3807
+ */var Analytics=/*#__PURE__*/function(){/**
3808
+ * Initialize services and components or use default ones if singletons
3809
+ */function Analytics(){_classCallCheck(this,Analytics);this.preloadBuffer=new BufferQueue();this.initialized=false;this.errorHandler=defaultErrorHandler;this.logger=defaultLogger;this.externalSrcLoader=new ExternalSrcLoader(this.errorHandler,this.logger);this.capabilitiesManager=new CapabilitiesManager(this.errorHandler,this.logger);this.httpClient=defaultHttpClient;}/**
3810
+ * Start application lifecycle if not already started
3811
+ */return _createClass(Analytics,[{key:"load",value:function load(writeKey,dataPlaneUrl){var loadOptions=arguments.length>2&&arguments[2]!==undefined?arguments[2]:{};if(state.lifecycle.status.value){return;}var clonedDataPlaneUrl=clone(dataPlaneUrl);var clonedLoadOptions=clone(loadOptions);// dataPlaneUrl is not provided
3812
+ if(isObjectAndNotNull(dataPlaneUrl)){clonedLoadOptions=dataPlaneUrl;clonedDataPlaneUrl=undefined;}// Set initial state values
3813
+ r(function(){state.lifecycle.writeKey.value=writeKey;state.lifecycle.dataPlaneUrl.value=clonedDataPlaneUrl;state.loadOptions.value=normalizeLoadOptions(state.loadOptions.value,clonedLoadOptions);state.lifecycle.status.value='mounted';});// set log level as early as possible
3814
+ if(state.loadOptions.value.logLevel){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.setMinLogLevel(state.loadOptions.value.logLevel);}// Expose state to global objects
3815
+ setExposedGlobal('state',state,writeKey);// Configure initial config of any services or components here
3816
+ // State application lifecycle
3817
+ this.startLifecycle();}// Start lifecycle methods
3818
+ /**
3819
+ * Orchestrate the lifecycle of the application phases/status
3820
+ */},{key:"startLifecycle",value:function startLifecycle(){var _this=this;E(function(){try{switch(state.lifecycle.status.value){case'mounted':_this.onMounted();break;case'browserCapabilitiesReady':_this.onBrowserCapabilitiesReady();break;case'configured':_this.onConfigured();break;case'pluginsLoading':break;case'pluginsReady':_this.onPluginsReady();break;case'initialized':_this.onInitialized();break;case'loaded':_this.onLoaded();break;case'destinationsLoading':break;case'destinationsReady':_this.onDestinationsReady();break;case'ready':_this.onReady();break;case'readyExecuted':default:break;}}catch(err){var issue='Failed to load the SDK';_this.errorHandler.onError(getMutatedError(err,issue),ANALYTICS_CORE);}});}},{key:"onBrowserCapabilitiesReady",value:function onBrowserCapabilitiesReady(){// initialize the preloaded events enqueuing
3821
+ retrievePreloadBufferEvents(this);this.prepareInternalServices();this.loadConfig();}},{key:"onLoaded",value:function onLoaded(){this.processBufferedEvents();// Short-circuit the life cycle and move to the ready state if pre-consent behavior is enabled
3822
+ if(state.consents.preConsent.value.enabled===true){state.lifecycle.status.value='ready';}else {this.loadDestinations();}}/**
3823
+ * Load browser polyfill if required
3824
+ */},{key:"onMounted",value:function onMounted(){this.capabilitiesManager.init();}/**
3825
+ * Enqueue in SDK preload buffer events, used from preloadBuffer component
3826
+ */},{key:"enqueuePreloadBufferEvents",value:function enqueuePreloadBufferEvents(bufferedEvents){var _this2=this;if(Array.isArray(bufferedEvents)){bufferedEvents.forEach(function(bufferedEvent){return _this2.preloadBuffer.enqueue(clone(bufferedEvent));});}}/**
3827
+ * Process the buffer preloaded events by passing their arguments to the respective facade methods
3828
+ */},{key:"processDataInPreloadBuffer",value:function processDataInPreloadBuffer(){while(this.preloadBuffer.size()>0){var eventToProcess=this.preloadBuffer.dequeue();if(eventToProcess){consumePreloadBufferedEvent(_toConsumableArray(eventToProcess),this);}}}},{key:"prepareInternalServices",value:function prepareInternalServices(){this.pluginsManager=new PluginsManager(defaultPluginEngine,this.errorHandler,this.logger);this.storeManager=new StoreManager(this.pluginsManager,this.errorHandler,this.logger);this.configManager=new ConfigManager(this.httpClient,this.errorHandler,this.logger);this.userSessionManager=new UserSessionManager(this.errorHandler,this.logger,this.pluginsManager,this.storeManager,this.httpClient);this.eventRepository=new EventRepository(this.pluginsManager,this.storeManager,this.errorHandler,this.logger);this.eventManager=new EventManager(this.eventRepository,this.userSessionManager,this.errorHandler,this.logger);}/**
3829
+ * Load configuration
3830
+ */},{key:"loadConfig",value:function loadConfig(){var _this$configManager;if(state.lifecycle.writeKey.value){this.httpClient.setAuthHeader(state.lifecycle.writeKey.value);}(_this$configManager=this.configManager)===null||_this$configManager===void 0||_this$configManager.init();}/**
3831
+ * Initialize the storage and event queue
3832
+ */},{key:"onPluginsReady",value:function onPluginsReady(){var _this$storeManager,_this$userSessionMana,_this$eventManager;this.errorHandler.init(this.httpClient,this.externalSrcLoader);// Initialize storage
3833
+ (_this$storeManager=this.storeManager)===null||_this$storeManager===void 0||_this$storeManager.init();(_this$userSessionMana=this.userSessionManager)===null||_this$userSessionMana===void 0||_this$userSessionMana.init();// Initialize the appropriate consent manager plugin
3834
+ if(state.consents.enabled.value&&!state.consents.initialized.value){var _this$pluginsManager;(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===void 0||_this$pluginsManager.invokeSingle("consentManager.init",state,this.logger);if(state.consents.preConsent.value.enabled===false){var _this$pluginsManager2;(_this$pluginsManager2=this.pluginsManager)===null||_this$pluginsManager2===void 0||_this$pluginsManager2.invokeSingle("consentManager.updateConsentsInfo",state,this.storeManager,this.logger);}}// Initialize event manager
3835
+ (_this$eventManager=this.eventManager)===null||_this$eventManager===void 0||_this$eventManager.init();// Mark the SDK as initialized
3836
+ state.lifecycle.status.value='initialized';}/**
3837
+ * Load plugins
3838
+ */},{key:"onConfigured",value:function onConfigured(){var _this$pluginsManager3;(_this$pluginsManager3=this.pluginsManager)===null||_this$pluginsManager3===void 0||_this$pluginsManager3.init();// TODO: are we going to enable custom plugins to be passed as load options?
3839
+ // registerCustomPlugins(state.loadOptions.value.customPlugins);
3840
+ }/**
3841
+ * Trigger onLoaded callback if any is provided in config & emit initialised event
3842
+ */},{key:"onInitialized",value:function onInitialized(){// Process any preloaded events
3843
+ this.processDataInPreloadBuffer();// TODO: we need to avoid passing the window object to the callback function
3844
+ // as this will prevent us from supporting multiple SDK instances in the same page
3845
+ // Execute onLoaded callback if provided in load options
3846
+ if(isFunction(state.loadOptions.value.onLoaded)){state.loadOptions.value.onLoaded(globalThis.rudderanalytics);}// Set lifecycle state
3847
+ r(function(){state.lifecycle.loaded.value=true;state.lifecycle.status.value='loaded';});this.initialized=true;// Emit an event to use as substitute to the onLoaded callback
3848
+ dispatchSDKEvent('RSA_Initialised');}/**
3849
+ * Emit ready event
3850
+ */ // eslint-disable-next-line class-methods-use-this
3851
+ },{key:"onReady",value:function onReady(){var _this3=this;state.lifecycle.status.value='readyExecuted';state.eventBuffer.readyCallbacksArray.value.forEach(function(callback){try{callback();}catch(err){_this3.errorHandler.onError(err,ANALYTICS_CORE,READY_CALLBACK_INVOKE_ERROR);}});// Emit an event to use as substitute to the ready callback
3852
+ dispatchSDKEvent('RSA_Ready');}/**
3853
+ * Consume preloaded events buffer
3854
+ */},{key:"processBufferedEvents",value:function processBufferedEvents(){// This logic has been intentionally implemented without a simple
3855
+ // for-loop as the individual events that are processed may
3856
+ // add more events to the buffer (this is needed for the consent API)
3857
+ var bufferedEvents=state.eventBuffer.toBeProcessedArray.value;while(bufferedEvents.length>0){var bufferedEvent=bufferedEvents.shift();state.eventBuffer.toBeProcessedArray.value=bufferedEvents;if(bufferedEvent){var methodName=bufferedEvent[0];if(isFunction(this[methodName])){var _ref;// Send additional arg 'true' to indicate that this is a buffered invocation
3858
+ (_ref=this)[methodName].apply(_ref,_toConsumableArray(bufferedEvent.slice(1)).concat([true]));}}bufferedEvents=state.eventBuffer.toBeProcessedArray.value;}}/**
3859
+ * Load device mode destinations
3860
+ */},{key:"loadDestinations",value:function loadDestinations(){var _this$pluginsManager4,_this$pluginsManager5;if(state.nativeDestinations.clientDestinationsReady.value){return;}// Set in state the desired activeDestinations to inject in DOM
3861
+ (_this$pluginsManager4=this.pluginsManager)===null||_this$pluginsManager4===void 0||_this$pluginsManager4.invokeSingle('nativeDestinations.setActiveDestinations',state,this.pluginsManager,this.errorHandler,this.logger);var totalDestinationsToLoad=state.nativeDestinations.activeDestinations.value.length;if(totalDestinationsToLoad===0){state.lifecycle.status.value='destinationsReady';return;}// Start loading native integration scripts and create instances
3862
+ state.lifecycle.status.value='destinationsLoading';(_this$pluginsManager5=this.pluginsManager)===null||_this$pluginsManager5===void 0||_this$pluginsManager5.invokeSingle('nativeDestinations.load',state,this.externalSrcLoader,this.errorHandler,this.logger);// Progress to next lifecycle phase if all native destinations are initialized or failed
3863
+ E(function(){var areAllDestinationsReady=totalDestinationsToLoad===0||state.nativeDestinations.initializedDestinations.value.length+state.nativeDestinations.failedDestinations.value.length===totalDestinationsToLoad;if(areAllDestinationsReady){r(function(){state.lifecycle.status.value='destinationsReady';state.nativeDestinations.clientDestinationsReady.value=true;});}});}/**
3864
+ * Move to the ready state
3865
+ */ // eslint-disable-next-line class-methods-use-this
3866
+ },{key:"onDestinationsReady",value:function onDestinationsReady(){// May be do any destination specific actions here
3867
+ // Mark the ready status if not already done
3868
+ if(state.lifecycle.status.value!=='ready'){state.lifecycle.status.value='ready';}}// End lifecycle methods
3869
+ // Start consumer exposed methods
3870
+ },{key:"ready",value:function ready(callback){var type='ready';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,callback]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));if(!isFunction(callback)){this.logger.error(READY_API_CALLBACK_ERROR(READY_API));return;}/**
3871
+ * If destinations are loaded or no integration is available for loading
3872
+ * execute the callback immediately else push the callbacks to a queue that
3873
+ * will be executed after loading completes
3874
+ */if(state.lifecycle.status.value==='readyExecuted'){try{callback();}catch(err){this.errorHandler.onError(err,ANALYTICS_CORE,READY_CALLBACK_INVOKE_ERROR);}}else {state.eventBuffer.readyCallbacksArray.value=[].concat(_toConsumableArray(state.eventBuffer.readyCallbacksArray.value),[callback]);}}},{key:"page",value:function page(payload){var _this$eventManager2;var type='page';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;(_this$eventManager2=this.eventManager)===null||_this$eventManager2===void 0||_this$eventManager2.addEvent({type:'page',category:payload.category,name:payload.name,properties:payload.properties,options:payload.options,callback:payload.callback});// TODO: Maybe we should alter the behavior to send the ad-block page event even if the SDK is still loaded. It'll be pushed into the to be processed queue.
3875
+ // Send automatic ad blocked page event if ad-blockers are detected on the page
3876
+ // Check page category to avoid infinite loop
3877
+ if(state.capabilities.isAdBlocked.value===true&&payload.category!==ADBLOCK_PAGE_CATEGORY){this.page(pageArgumentsToCallOptions(ADBLOCK_PAGE_CATEGORY,ADBLOCK_PAGE_NAME,{// 'title' is intentionally omitted as it does not make sense
3878
+ // in v3 implementation
3879
+ path:ADBLOCK_PAGE_PATH},state.loadOptions.value.sendAdblockPageOptions));}}},{key:"track",value:function track(payload){var _this$eventManager3;var type='track';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;(_this$eventManager3=this.eventManager)===null||_this$eventManager3===void 0||_this$eventManager3.addEvent({type:type,name:payload.name||undefined,properties:payload.properties,options:payload.options,callback:payload.callback});}},{key:"identify",value:function identify(payload){var _this$userSessionMana3,_this$eventManager4;var type='identify';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;var shouldResetSession=Boolean(payload.userId&&state.session.userId.value&&payload.userId!==state.session.userId.value);if(shouldResetSession){this.reset();}// `null` value indicates that previous user ID needs to be retained
3880
+ if(!isNull(payload.userId)){var _this$userSessionMana2;(_this$userSessionMana2=this.userSessionManager)===null||_this$userSessionMana2===void 0||_this$userSessionMana2.setUserId(payload.userId);}(_this$userSessionMana3=this.userSessionManager)===null||_this$userSessionMana3===void 0||_this$userSessionMana3.setUserTraits(payload.traits);(_this$eventManager4=this.eventManager)===null||_this$eventManager4===void 0||_this$eventManager4.addEvent({type:type,userId:payload.userId,traits:payload.traits,options:payload.options,callback:payload.callback});}},{key:"alias",value:function alias(payload){var _ref2,_payload$from,_this$userSessionMana4,_this$userSessionMana5,_this$eventManager5;var type='alias';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;var previousId=(_ref2=(_payload$from=payload.from)!==null&&_payload$from!==void 0?_payload$from:(_this$userSessionMana4=this.userSessionManager)===null||_this$userSessionMana4===void 0?void 0:_this$userSessionMana4.getUserId())!==null&&_ref2!==void 0?_ref2:(_this$userSessionMana5=this.userSessionManager)===null||_this$userSessionMana5===void 0?void 0:_this$userSessionMana5.getAnonymousId();(_this$eventManager5=this.eventManager)===null||_this$eventManager5===void 0||_this$eventManager5.addEvent({type:type,to:payload.to,from:previousId,options:payload.options,callback:payload.callback});}},{key:"group",value:function group(payload){var _this$userSessionMana7,_this$eventManager6;var type='group';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,payload]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;// `null` value indicates that previous group ID needs to be retained
3881
+ if(!isNull(payload.groupId)){var _this$userSessionMana6;(_this$userSessionMana6=this.userSessionManager)===null||_this$userSessionMana6===void 0||_this$userSessionMana6.setGroupId(payload.groupId);}(_this$userSessionMana7=this.userSessionManager)===null||_this$userSessionMana7===void 0||_this$userSessionMana7.setGroupTraits(payload.traits);(_this$eventManager6=this.eventManager)===null||_this$eventManager6===void 0||_this$eventManager6.addEvent({type:type,groupId:payload.groupId,traits:payload.traits,options:payload.options,callback:payload.callback});}},{key:"reset",value:function reset(resetAnonymousId){var _this$userSessionMana8;var type='reset';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,resetAnonymousId]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation, resetAnonymousId: ").concat(resetAnonymousId));(_this$userSessionMana8=this.userSessionManager)===null||_this$userSessionMana8===void 0||_this$userSessionMana8.reset(resetAnonymousId);}},{key:"getAnonymousId",value:function getAnonymousId(options){var _this$userSessionMana9;return (_this$userSessionMana9=this.userSessionManager)===null||_this$userSessionMana9===void 0?void 0:_this$userSessionMana9.getAnonymousId(options);}},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){var _this$userSessionMana10;var type='setAnonymousId';// Buffering is needed as setting the anonymous ID may require invoking the GoogleLinker plugin
3882
+ if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,anonymousId,rudderAmpLinkerParam]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));(_this$userSessionMana10=this.userSessionManager)===null||_this$userSessionMana10===void 0||_this$userSessionMana10.setAnonymousId(anonymousId,rudderAmpLinkerParam);}// eslint-disable-next-line class-methods-use-this
3883
+ },{key:"getUserId",value:function getUserId(){return state.session.userId.value;}// eslint-disable-next-line class-methods-use-this
3884
+ },{key:"getUserTraits",value:function getUserTraits(){return state.session.userTraits.value;}// eslint-disable-next-line class-methods-use-this
3885
+ },{key:"getGroupId",value:function getGroupId(){return state.session.groupId.value;}// eslint-disable-next-line class-methods-use-this
3886
+ },{key:"getGroupTraits",value:function getGroupTraits(){return state.session.groupTraits.value;}},{key:"startSession",value:function startSession(sessionId){var _this$userSessionMana11;var type='startSession';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,sessionId]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));(_this$userSessionMana11=this.userSessionManager)===null||_this$userSessionMana11===void 0||_this$userSessionMana11.start(sessionId);}},{key:"endSession",value:function endSession(){var _this$userSessionMana12;var type='endSession';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type]]);return;}this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));(_this$userSessionMana12=this.userSessionManager)===null||_this$userSessionMana12===void 0||_this$userSessionMana12.end();}// eslint-disable-next-line class-methods-use-this
3887
+ },{key:"getSessionId",value:function getSessionId(){var _this$userSessionMana13;var sessionId=(_this$userSessionMana13=this.userSessionManager)===null||_this$userSessionMana13===void 0?void 0:_this$userSessionMana13.getSessionId();return sessionId!==null&&sessionId!==void 0?sessionId:null;}},{key:"consent",value:function consent(options){var _this4=this,_this$storeManager2,_this$userSessionMana14,_this$eventManager7;var isBufferedInvocation=arguments.length>1&&arguments[1]!==undefined?arguments[1]:false;var type='consent';if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[[type,options]]);return;}this.errorHandler.leaveBreadcrumb("New consent invocation");r(function(){state.consents.preConsent.value=_objectSpread2(_objectSpread2({},state.consents.preConsent.value),{},{enabled:false});state.consents.postConsent.value=getValidPostConsentOptions(options);var _getConsentManagement=getConsentManagementData(state.consents.postConsent.value.consentManagement,_this4.logger),initialized=_getConsentManagement.initialized,consentsData=_getConsentManagement.consentsData;state.consents.initialized.value=initialized||state.consents.initialized.value;state.consents.data.value=consentsData;});// Update consents data in state
3888
+ if(state.consents.enabled.value&&!state.consents.initialized.value){var _this$pluginsManager6;(_this$pluginsManager6=this.pluginsManager)===null||_this$pluginsManager6===void 0||_this$pluginsManager6.invokeSingle("consentManager.updateConsentsInfo",state,this.storeManager,this.logger);}// Re-init store manager
3889
+ (_this$storeManager2=this.storeManager)===null||_this$storeManager2===void 0||_this$storeManager2.initializeStorageState();// Re-init user session manager
3890
+ (_this$userSessionMana14=this.userSessionManager)===null||_this$userSessionMana14===void 0||_this$userSessionMana14.syncStorageDataToState();// Resume event manager to process the events to destinations
3891
+ (_this$eventManager7=this.eventManager)===null||_this$eventManager7===void 0||_this$eventManager7.resume();this.loadDestinations();this.sendTrackingEvents(isBufferedInvocation);}},{key:"sendTrackingEvents",value:function sendTrackingEvents(isBufferedInvocation){// If isBufferedInvocation is true, then the tracking events will be added to the end of the
3892
+ // events buffer array so that any other preload events (mainly from query string API) will be processed first.
3893
+ if(state.consents.postConsent.value.trackConsent){var trackOptions=trackArgumentsToCallOptions(CONSENT_TRACK_EVENT_NAME);if(isBufferedInvocation){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[['track',trackOptions]]);}else {this.track(trackOptions);}}if(state.consents.postConsent.value.sendPageEvent){var pageOptions=pageArgumentsToCallOptions();if(isBufferedInvocation){state.eventBuffer.toBeProcessedArray.value=[].concat(_toConsumableArray(state.eventBuffer.toBeProcessedArray.value),[['page',pageOptions]]);}else {this.page(pageOptions);}}}},{key:"setAuthToken",value:function setAuthToken(token){var _this$userSessionMana15;(_this$userSessionMana15=this.userSessionManager)===null||_this$userSessionMana15===void 0||_this$userSessionMana15.setAuthToken(token);}// End consumer exposed methods
3894
+ }]);}();
3895
+
3896
+ /*
3897
+ * RudderAnalytics facade singleton that is exposed as global object and will:
3898
+ * expose overloaded methods
3899
+ * handle multiple Analytics instances
3900
+ * consume SDK preload event buffer
3901
+ */var RudderAnalytics=/*#__PURE__*/function(){// Singleton with constructor bind methods
3902
+ function RudderAnalytics(){_classCallCheck(this,RudderAnalytics);_defineProperty(this,"analyticsInstances",{});_defineProperty(this,"defaultAnalyticsKey",'');_defineProperty(this,"logger",defaultLogger);if(RudderAnalytics.globalSingleton){// START-NO-SONAR-SCAN
3903
+ // eslint-disable-next-line no-constructor-return
3904
+ return RudderAnalytics.globalSingleton;// END-NO-SONAR-SCAN
3905
+ }defaultErrorHandler.attachErrorListeners();this.setDefaultInstanceKey=this.setDefaultInstanceKey.bind(this);this.getAnalyticsInstance=this.getAnalyticsInstance.bind(this);this.load=this.load.bind(this);this.ready=this.ready.bind(this);this.triggerBufferedLoadEvent=this.triggerBufferedLoadEvent.bind(this);this.page=this.page.bind(this);this.track=this.track.bind(this);this.identify=this.identify.bind(this);this.alias=this.alias.bind(this);this.group=this.group.bind(this);this.reset=this.reset.bind(this);this.getAnonymousId=this.getAnonymousId.bind(this);this.setAnonymousId=this.setAnonymousId.bind(this);this.getUserId=this.getUserId.bind(this);this.getUserTraits=this.getUserTraits.bind(this);this.getGroupId=this.getGroupId.bind(this);this.getGroupTraits=this.getGroupTraits.bind(this);this.startSession=this.startSession.bind(this);this.endSession=this.endSession.bind(this);this.getSessionId=this.getSessionId.bind(this);this.setAuthToken=this.setAuthToken.bind(this);this.consent=this.consent.bind(this);RudderAnalytics.globalSingleton=this;// start loading if a load event was buffered or wait for explicit load call
3906
+ this.triggerBufferedLoadEvent();// Assign to global "rudderanalytics" object after processing the preload buffer (if any exists)
3907
+ // for CDN bundling IIFE exports covers this but for npm ESM and CJS bundling has to be done explicitly
3908
+ globalThis.rudderanalytics=this;}/**
3909
+ * Set instance to use if no specific writeKey is provided in methods
3910
+ * automatically for the first created instance
3911
+ * TODO: to support multiple analytics instances in the near future
3912
+ */return _createClass(RudderAnalytics,[{key:"setDefaultInstanceKey",value:function setDefaultInstanceKey(writeKey){if(writeKey){this.defaultAnalyticsKey=writeKey;}}/**
3913
+ * Retrieve an existing analytics instance
3914
+ */},{key:"getAnalyticsInstance",value:function getAnalyticsInstance(writeKey){var instanceId=writeKey!==null&&writeKey!==void 0?writeKey:this.defaultAnalyticsKey;var analyticsInstanceExists=Boolean(this.analyticsInstances[instanceId]);if(!analyticsInstanceExists){this.analyticsInstances[instanceId]=new Analytics();}return this.analyticsInstances[instanceId];}/**
3915
+ * Create new analytics instance and trigger application lifecycle start
3916
+ */},{key:"load",value:function load(writeKey,dataPlaneUrl,loadOptions){if(!isString(writeKey)){this.logger.error(WRITE_KEY_NOT_A_STRING_ERROR(RS_APP,writeKey));return;}if(this.analyticsInstances[writeKey]){return;}this.setDefaultInstanceKey(writeKey);this.analyticsInstances[writeKey]=new Analytics();this.getAnalyticsInstance(writeKey).load(writeKey,dataPlaneUrl,loadOptions);}/**
3917
+ * Trigger load event in buffer queue if exists and stores the
3918
+ * remaining preloaded events array in global object
3919
+ */},{key:"triggerBufferedLoadEvent",value:function triggerBufferedLoadEvent(){var preloadedEventsArray=Array.isArray(globalThis.rudderanalytics)?globalThis.rudderanalytics:[];// The array will be mutated in the below method
3920
+ promotePreloadedConsentEventsToTop(preloadedEventsArray);// Get any load method call that is buffered if any
3921
+ // BTW, load method is also removed from the array
3922
+ // So, the Analytics object can directly consume the remaining events
3923
+ var loadEvent=getPreloadedLoadEvent(preloadedEventsArray);// Set the final preloaded events array in global object
3924
+ setExposedGlobal(GLOBAL_PRELOAD_BUFFER,clone(preloadedEventsArray));// Process load method if present in the buffered requests
3925
+ if(loadEvent.length>0){// Remove the event name from the Buffered Event array and keep only arguments
3926
+ loadEvent.shift();// eslint-disable-next-line @typescript-eslint/ban-ts-comment
3927
+ // @ts-ignore
3928
+ this.load.apply(null,loadEvent);}}/**
3929
+ * Get ready callback arguments and forward to ready call
3930
+ */},{key:"ready",value:function ready(callback){this.getAnalyticsInstance().ready(callback);}/**
3931
+ * Process page arguments and forward to page call
3932
+ */ // These overloads should be same as AnalyticsPageMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
3933
+ },{key:"page",value:function page(category,name,properties,options,callback){this.getAnalyticsInstance().page(pageArgumentsToCallOptions(category,name,properties,options,callback));}/**
3934
+ * Process track arguments and forward to page call
3935
+ */ // These overloads should be same as AnalyticsTrackMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
3936
+ },{key:"track",value:function track(event,properties,options,callback){this.getAnalyticsInstance().track(trackArgumentsToCallOptions(event,properties,options,callback));}/**
3937
+ * Process identify arguments and forward to page call
3938
+ */ // These overloads should be same as AnalyticsIdentifyMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
3939
+ },{key:"identify",value:function identify(userId,traits,options,callback){this.getAnalyticsInstance().identify(identifyArgumentsToCallOptions(userId,traits,options,callback));}/**
3940
+ * Process alias arguments and forward to page call
3941
+ */ // These overloads should be same as AnalyticsAliasMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
3942
+ },{key:"alias",value:function alias(to,from,options,callback){this.getAnalyticsInstance().alias(aliasArgumentsToCallOptions(to,from,options,callback));}/**
3943
+ * Process group arguments and forward to page call
3944
+ */ // These overloads should be same as AnalyticsGroupMethod in @rudderstack/analytics-js-common/types/IRudderAnalytics
3945
+ },{key:"group",value:function group(groupId,traits,options,callback){if(arguments.length===0){this.logger.error(EMPTY_GROUP_CALL_ERROR(RS_APP));return;}this.getAnalyticsInstance().group(groupArgumentsToCallOptions(groupId,traits,options,callback));}},{key:"reset",value:function reset(resetAnonymousId){this.getAnalyticsInstance().reset(resetAnonymousId);}},{key:"getAnonymousId",value:function getAnonymousId(options){return this.getAnalyticsInstance().getAnonymousId(options);}},{key:"setAnonymousId",value:function setAnonymousId(anonymousId,rudderAmpLinkerParam){this.getAnalyticsInstance().setAnonymousId(anonymousId,rudderAmpLinkerParam);}},{key:"getUserId",value:function getUserId(){return this.getAnalyticsInstance().getUserId();}},{key:"getUserTraits",value:function getUserTraits(){return this.getAnalyticsInstance().getUserTraits();}},{key:"getGroupId",value:function getGroupId(){return this.getAnalyticsInstance().getGroupId();}},{key:"getGroupTraits",value:function getGroupTraits(){return this.getAnalyticsInstance().getGroupTraits();}},{key:"startSession",value:function startSession(sessionId){return this.getAnalyticsInstance().startSession(sessionId);}},{key:"endSession",value:function endSession(){return this.getAnalyticsInstance().endSession();}},{key:"getSessionId",value:function getSessionId(){return this.getAnalyticsInstance().getSessionId();}},{key:"setAuthToken",value:function setAuthToken(token){return this.getAnalyticsInstance().setAuthToken(token);}},{key:"consent",value:function consent(options){return this.getAnalyticsInstance().consent(options);}}]);}();_defineProperty(RudderAnalytics,"globalSingleton",null);
3946
+
3947
+ exports.RudderAnalytics = RudderAnalytics;