@rudderstack/analytics-js 3.0.0-beta.4 → 3.0.0-beta.6
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.
- package/CHANGELOG.md +30 -0
- package/index.d.ts +0 -1
- package/legacy/cjs/index.js +361 -348
- package/legacy/esm/index.js +361 -348
- package/legacy/umd/index.js +361 -348
- package/modern/cjs/index.js +44 -43
- package/modern/esm/index.js +44 -43
- package/modern/umd/index.js +44 -43
- package/package.json +5 -11
package/legacy/esm/index.js
CHANGED
@@ -18,331 +18,336 @@ var LogLevel=/*#__PURE__*/function(LogLevel){LogLevel["Log"]="LOG";LogLevel["Inf
|
|
18
18
|
|
19
19
|
var PluginName=/*#__PURE__*/function(PluginName){PluginName["BeaconQueue"]="BeaconQueue";PluginName["DeviceModeDestinations"]="DeviceModeDestinations";PluginName["DeviceModeTransformation"]="DeviceModeTransformation";PluginName["ErrorReporting"]="ErrorReporting";PluginName["ExternalAnonymousId"]="ExternalAnonymousId";PluginName["GoogleLinker"]="GoogleLinker";PluginName["NativeDestinationQueue"]="NativeDestinationQueue";PluginName["StorageEncryption"]="StorageEncryption";PluginName["StorageEncryptionLegacy"]="StorageEncryptionLegacy";PluginName["StorageMigrator"]="StorageMigrator";PluginName["XhrQueue"]="XhrQueue";PluginName["OneTrustConsentManager"]="OneTrustConsentManager";PluginName["KetchConsentManager"]="KetchConsentManager";PluginName["Bugsnag"]="Bugsnag";return PluginName;}({});
|
20
20
|
|
21
|
-
function ownKeys(
|
22
|
-
var
|
21
|
+
function ownKeys(e, r) {
|
22
|
+
var t = Object.keys(e);
|
23
23
|
if (Object.getOwnPropertySymbols) {
|
24
|
-
var
|
25
|
-
|
26
|
-
return Object.getOwnPropertyDescriptor(
|
27
|
-
})),
|
24
|
+
var o = Object.getOwnPropertySymbols(e);
|
25
|
+
r && (o = o.filter(function (r) {
|
26
|
+
return Object.getOwnPropertyDescriptor(e, r).enumerable;
|
27
|
+
})), t.push.apply(t, o);
|
28
28
|
}
|
29
|
-
return
|
29
|
+
return t;
|
30
30
|
}
|
31
|
-
function _objectSpread2(
|
32
|
-
for (var
|
33
|
-
var
|
34
|
-
|
35
|
-
_defineProperty(
|
36
|
-
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(
|
37
|
-
Object.defineProperty(
|
31
|
+
function _objectSpread2(e) {
|
32
|
+
for (var r = 1; r < arguments.length; r++) {
|
33
|
+
var t = null != arguments[r] ? arguments[r] : {};
|
34
|
+
r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
|
35
|
+
_defineProperty(e, r, t[r]);
|
36
|
+
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
|
37
|
+
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
|
38
38
|
});
|
39
39
|
}
|
40
|
-
return
|
40
|
+
return e;
|
41
41
|
}
|
42
42
|
function _regeneratorRuntime() {
|
43
43
|
_regeneratorRuntime = function () {
|
44
|
-
return
|
44
|
+
return e;
|
45
45
|
};
|
46
|
-
var
|
47
|
-
|
48
|
-
|
49
|
-
|
50
|
-
|
46
|
+
var t,
|
47
|
+
e = {},
|
48
|
+
r = Object.prototype,
|
49
|
+
n = r.hasOwnProperty,
|
50
|
+
o = Object.defineProperty || function (t, e, r) {
|
51
|
+
t[e] = r.value;
|
51
52
|
},
|
52
|
-
|
53
|
-
|
54
|
-
|
55
|
-
|
56
|
-
function define(
|
57
|
-
return Object.defineProperty(
|
58
|
-
value:
|
53
|
+
i = "function" == typeof Symbol ? Symbol : {},
|
54
|
+
a = i.iterator || "@@iterator",
|
55
|
+
c = i.asyncIterator || "@@asyncIterator",
|
56
|
+
u = i.toStringTag || "@@toStringTag";
|
57
|
+
function define(t, e, r) {
|
58
|
+
return Object.defineProperty(t, e, {
|
59
|
+
value: r,
|
59
60
|
enumerable: !0,
|
60
61
|
configurable: !0,
|
61
62
|
writable: !0
|
62
|
-
}),
|
63
|
+
}), t[e];
|
63
64
|
}
|
64
65
|
try {
|
65
66
|
define({}, "");
|
66
|
-
} catch (
|
67
|
-
define = function (
|
68
|
-
return
|
67
|
+
} catch (t) {
|
68
|
+
define = function (t, e, r) {
|
69
|
+
return t[e] = r;
|
69
70
|
};
|
70
71
|
}
|
71
|
-
function wrap(
|
72
|
-
var
|
73
|
-
|
74
|
-
|
75
|
-
return
|
76
|
-
value: makeInvokeMethod(
|
77
|
-
}),
|
72
|
+
function wrap(t, e, r, n) {
|
73
|
+
var i = e && e.prototype instanceof Generator ? e : Generator,
|
74
|
+
a = Object.create(i.prototype),
|
75
|
+
c = new Context(n || []);
|
76
|
+
return o(a, "_invoke", {
|
77
|
+
value: makeInvokeMethod(t, r, c)
|
78
|
+
}), a;
|
78
79
|
}
|
79
|
-
function tryCatch(
|
80
|
+
function tryCatch(t, e, r) {
|
80
81
|
try {
|
81
82
|
return {
|
82
83
|
type: "normal",
|
83
|
-
arg:
|
84
|
+
arg: t.call(e, r)
|
84
85
|
};
|
85
|
-
} catch (
|
86
|
+
} catch (t) {
|
86
87
|
return {
|
87
88
|
type: "throw",
|
88
|
-
arg:
|
89
|
+
arg: t
|
89
90
|
};
|
90
91
|
}
|
91
92
|
}
|
92
|
-
|
93
|
-
var
|
93
|
+
e.wrap = wrap;
|
94
|
+
var h = "suspendedStart",
|
95
|
+
l = "suspendedYield",
|
96
|
+
f = "executing",
|
97
|
+
s = "completed",
|
98
|
+
y = {};
|
94
99
|
function Generator() {}
|
95
100
|
function GeneratorFunction() {}
|
96
101
|
function GeneratorFunctionPrototype() {}
|
97
|
-
var
|
98
|
-
define(
|
102
|
+
var p = {};
|
103
|
+
define(p, a, function () {
|
99
104
|
return this;
|
100
105
|
});
|
101
|
-
var
|
102
|
-
|
103
|
-
|
104
|
-
var
|
105
|
-
function defineIteratorMethods(
|
106
|
-
["next", "throw", "return"].forEach(function (
|
107
|
-
define(
|
108
|
-
return this._invoke(
|
106
|
+
var d = Object.getPrototypeOf,
|
107
|
+
v = d && d(d(values([])));
|
108
|
+
v && v !== r && n.call(v, a) && (p = v);
|
109
|
+
var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
|
110
|
+
function defineIteratorMethods(t) {
|
111
|
+
["next", "throw", "return"].forEach(function (e) {
|
112
|
+
define(t, e, function (t) {
|
113
|
+
return this._invoke(e, t);
|
109
114
|
});
|
110
115
|
});
|
111
116
|
}
|
112
|
-
function AsyncIterator(
|
113
|
-
function invoke(
|
114
|
-
var
|
115
|
-
if ("throw" !==
|
116
|
-
var
|
117
|
-
|
118
|
-
return
|
119
|
-
invoke("next",
|
120
|
-
}, function (
|
121
|
-
invoke("throw",
|
122
|
-
}) :
|
123
|
-
|
124
|
-
}, function (
|
125
|
-
return invoke("throw",
|
117
|
+
function AsyncIterator(t, e) {
|
118
|
+
function invoke(r, o, i, a) {
|
119
|
+
var c = tryCatch(t[r], t, o);
|
120
|
+
if ("throw" !== c.type) {
|
121
|
+
var u = c.arg,
|
122
|
+
h = u.value;
|
123
|
+
return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
|
124
|
+
invoke("next", t, i, a);
|
125
|
+
}, function (t) {
|
126
|
+
invoke("throw", t, i, a);
|
127
|
+
}) : e.resolve(h).then(function (t) {
|
128
|
+
u.value = t, i(u);
|
129
|
+
}, function (t) {
|
130
|
+
return invoke("throw", t, i, a);
|
126
131
|
});
|
127
132
|
}
|
128
|
-
|
133
|
+
a(c.arg);
|
129
134
|
}
|
130
|
-
var
|
131
|
-
|
132
|
-
value: function (
|
135
|
+
var r;
|
136
|
+
o(this, "_invoke", {
|
137
|
+
value: function (t, n) {
|
133
138
|
function callInvokeWithMethodAndArg() {
|
134
|
-
return new
|
135
|
-
invoke(
|
139
|
+
return new e(function (e, r) {
|
140
|
+
invoke(t, n, e, r);
|
136
141
|
});
|
137
142
|
}
|
138
|
-
return
|
143
|
+
return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
|
139
144
|
}
|
140
145
|
});
|
141
146
|
}
|
142
|
-
function makeInvokeMethod(
|
143
|
-
var
|
144
|
-
return function (
|
145
|
-
if (
|
146
|
-
if (
|
147
|
-
if ("throw" ===
|
147
|
+
function makeInvokeMethod(e, r, n) {
|
148
|
+
var o = h;
|
149
|
+
return function (i, a) {
|
150
|
+
if (o === f) throw new Error("Generator is already running");
|
151
|
+
if (o === s) {
|
152
|
+
if ("throw" === i) throw a;
|
148
153
|
return {
|
149
|
-
value:
|
154
|
+
value: t,
|
150
155
|
done: !0
|
151
156
|
};
|
152
157
|
}
|
153
|
-
for (
|
154
|
-
var
|
155
|
-
if (
|
156
|
-
var
|
157
|
-
if (
|
158
|
-
if (
|
159
|
-
return
|
158
|
+
for (n.method = i, n.arg = a;;) {
|
159
|
+
var c = n.delegate;
|
160
|
+
if (c) {
|
161
|
+
var u = maybeInvokeDelegate(c, n);
|
162
|
+
if (u) {
|
163
|
+
if (u === y) continue;
|
164
|
+
return u;
|
160
165
|
}
|
161
166
|
}
|
162
|
-
if ("next" ===
|
163
|
-
if (
|
164
|
-
|
165
|
-
} else "return" ===
|
166
|
-
|
167
|
-
var
|
168
|
-
if ("normal" ===
|
169
|
-
if (
|
167
|
+
if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
|
168
|
+
if (o === h) throw o = s, n.arg;
|
169
|
+
n.dispatchException(n.arg);
|
170
|
+
} else "return" === n.method && n.abrupt("return", n.arg);
|
171
|
+
o = f;
|
172
|
+
var p = tryCatch(e, r, n);
|
173
|
+
if ("normal" === p.type) {
|
174
|
+
if (o = n.done ? s : l, p.arg === y) continue;
|
170
175
|
return {
|
171
|
-
value:
|
172
|
-
done:
|
176
|
+
value: p.arg,
|
177
|
+
done: n.done
|
173
178
|
};
|
174
179
|
}
|
175
|
-
"throw" ===
|
180
|
+
"throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
|
176
181
|
}
|
177
182
|
};
|
178
183
|
}
|
179
|
-
function maybeInvokeDelegate(
|
180
|
-
var
|
181
|
-
|
182
|
-
if (
|
183
|
-
var
|
184
|
-
if ("throw" ===
|
185
|
-
var
|
186
|
-
return
|
184
|
+
function maybeInvokeDelegate(e, r) {
|
185
|
+
var n = r.method,
|
186
|
+
o = e.iterator[n];
|
187
|
+
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;
|
188
|
+
var i = tryCatch(o, e.iterator, r.arg);
|
189
|
+
if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
|
190
|
+
var a = i.arg;
|
191
|
+
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);
|
187
192
|
}
|
188
|
-
function pushTryEntry(
|
189
|
-
var
|
190
|
-
tryLoc:
|
193
|
+
function pushTryEntry(t) {
|
194
|
+
var e = {
|
195
|
+
tryLoc: t[0]
|
191
196
|
};
|
192
|
-
1 in
|
197
|
+
1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
|
193
198
|
}
|
194
|
-
function resetTryEntry(
|
195
|
-
var
|
196
|
-
|
199
|
+
function resetTryEntry(t) {
|
200
|
+
var e = t.completion || {};
|
201
|
+
e.type = "normal", delete e.arg, t.completion = e;
|
197
202
|
}
|
198
|
-
function Context(
|
203
|
+
function Context(t) {
|
199
204
|
this.tryEntries = [{
|
200
205
|
tryLoc: "root"
|
201
|
-
}],
|
206
|
+
}], t.forEach(pushTryEntry, this), this.reset(!0);
|
202
207
|
}
|
203
|
-
function values(
|
204
|
-
if (
|
205
|
-
var
|
206
|
-
if (
|
207
|
-
if ("function" == typeof
|
208
|
-
if (!isNaN(
|
209
|
-
var
|
210
|
-
|
211
|
-
for (; ++
|
212
|
-
return next.value =
|
208
|
+
function values(e) {
|
209
|
+
if (e || "" === e) {
|
210
|
+
var r = e[a];
|
211
|
+
if (r) return r.call(e);
|
212
|
+
if ("function" == typeof e.next) return e;
|
213
|
+
if (!isNaN(e.length)) {
|
214
|
+
var o = -1,
|
215
|
+
i = function next() {
|
216
|
+
for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
|
217
|
+
return next.value = t, next.done = !0, next;
|
213
218
|
};
|
214
|
-
return
|
219
|
+
return i.next = i;
|
215
220
|
}
|
216
221
|
}
|
217
|
-
throw new TypeError(typeof
|
222
|
+
throw new TypeError(typeof e + " is not iterable");
|
218
223
|
}
|
219
|
-
return GeneratorFunction.prototype = GeneratorFunctionPrototype,
|
224
|
+
return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
|
220
225
|
value: GeneratorFunctionPrototype,
|
221
226
|
configurable: !0
|
222
|
-
}),
|
227
|
+
}), o(GeneratorFunctionPrototype, "constructor", {
|
223
228
|
value: GeneratorFunction,
|
224
229
|
configurable: !0
|
225
|
-
}), GeneratorFunction.displayName = define(GeneratorFunctionPrototype,
|
226
|
-
var
|
227
|
-
return !!
|
228
|
-
},
|
229
|
-
return Object.setPrototypeOf ? Object.setPrototypeOf(
|
230
|
-
},
|
230
|
+
}), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
|
231
|
+
var e = "function" == typeof t && t.constructor;
|
232
|
+
return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
|
233
|
+
}, e.mark = function (t) {
|
234
|
+
return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
|
235
|
+
}, e.awrap = function (t) {
|
231
236
|
return {
|
232
|
-
__await:
|
237
|
+
__await: t
|
233
238
|
};
|
234
|
-
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype,
|
239
|
+
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
|
235
240
|
return this;
|
236
|
-
}),
|
237
|
-
void 0 ===
|
238
|
-
var
|
239
|
-
return
|
240
|
-
return
|
241
|
+
}), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
|
242
|
+
void 0 === i && (i = Promise);
|
243
|
+
var a = new AsyncIterator(wrap(t, r, n, o), i);
|
244
|
+
return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
|
245
|
+
return t.done ? t.value : a.next();
|
241
246
|
});
|
242
|
-
}, defineIteratorMethods(
|
247
|
+
}, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
|
243
248
|
return this;
|
244
|
-
}), define(
|
249
|
+
}), define(g, "toString", function () {
|
245
250
|
return "[object Generator]";
|
246
|
-
}),
|
247
|
-
var
|
248
|
-
|
249
|
-
for (var
|
250
|
-
return
|
251
|
-
for (;
|
252
|
-
var
|
253
|
-
if (
|
251
|
+
}), e.keys = function (t) {
|
252
|
+
var e = Object(t),
|
253
|
+
r = [];
|
254
|
+
for (var n in e) r.push(n);
|
255
|
+
return r.reverse(), function next() {
|
256
|
+
for (; r.length;) {
|
257
|
+
var t = r.pop();
|
258
|
+
if (t in e) return next.value = t, next.done = !1, next;
|
254
259
|
}
|
255
260
|
return next.done = !0, next;
|
256
261
|
};
|
257
|
-
},
|
262
|
+
}, e.values = values, Context.prototype = {
|
258
263
|
constructor: Context,
|
259
|
-
reset: function (
|
260
|
-
if (this.prev = 0, this.next = 0, this.sent = this._sent =
|
264
|
+
reset: function (e) {
|
265
|
+
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);
|
261
266
|
},
|
262
267
|
stop: function () {
|
263
268
|
this.done = !0;
|
264
|
-
var
|
265
|
-
if ("throw" ===
|
269
|
+
var t = this.tryEntries[0].completion;
|
270
|
+
if ("throw" === t.type) throw t.arg;
|
266
271
|
return this.rval;
|
267
272
|
},
|
268
|
-
dispatchException: function (
|
269
|
-
if (this.done) throw
|
270
|
-
var
|
271
|
-
function handle(
|
272
|
-
return
|
273
|
+
dispatchException: function (e) {
|
274
|
+
if (this.done) throw e;
|
275
|
+
var r = this;
|
276
|
+
function handle(n, o) {
|
277
|
+
return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
|
273
278
|
}
|
274
|
-
for (var
|
275
|
-
var
|
276
|
-
|
277
|
-
if ("root" ===
|
278
|
-
if (
|
279
|
-
var
|
280
|
-
|
281
|
-
if (
|
282
|
-
if (this.prev <
|
283
|
-
if (this.prev <
|
284
|
-
} else if (
|
285
|
-
if (this.prev <
|
279
|
+
for (var o = this.tryEntries.length - 1; o >= 0; --o) {
|
280
|
+
var i = this.tryEntries[o],
|
281
|
+
a = i.completion;
|
282
|
+
if ("root" === i.tryLoc) return handle("end");
|
283
|
+
if (i.tryLoc <= this.prev) {
|
284
|
+
var c = n.call(i, "catchLoc"),
|
285
|
+
u = n.call(i, "finallyLoc");
|
286
|
+
if (c && u) {
|
287
|
+
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
|
288
|
+
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
|
289
|
+
} else if (c) {
|
290
|
+
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
|
286
291
|
} else {
|
287
|
-
if (!
|
288
|
-
if (this.prev <
|
292
|
+
if (!u) throw new Error("try statement without catch or finally");
|
293
|
+
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
|
289
294
|
}
|
290
295
|
}
|
291
296
|
}
|
292
297
|
},
|
293
|
-
abrupt: function (
|
294
|
-
for (var
|
295
|
-
var
|
296
|
-
if (
|
297
|
-
var
|
298
|
+
abrupt: function (t, e) {
|
299
|
+
for (var r = this.tryEntries.length - 1; r >= 0; --r) {
|
300
|
+
var o = this.tryEntries[r];
|
301
|
+
if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
|
302
|
+
var i = o;
|
298
303
|
break;
|
299
304
|
}
|
300
305
|
}
|
301
|
-
|
302
|
-
var
|
303
|
-
return
|
306
|
+
i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
|
307
|
+
var a = i ? i.completion : {};
|
308
|
+
return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
|
304
309
|
},
|
305
|
-
complete: function (
|
306
|
-
if ("throw" ===
|
307
|
-
return "break" ===
|
310
|
+
complete: function (t, e) {
|
311
|
+
if ("throw" === t.type) throw t.arg;
|
312
|
+
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;
|
308
313
|
},
|
309
|
-
finish: function (
|
310
|
-
for (var
|
311
|
-
var
|
312
|
-
if (
|
314
|
+
finish: function (t) {
|
315
|
+
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
|
316
|
+
var r = this.tryEntries[e];
|
317
|
+
if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
|
313
318
|
}
|
314
319
|
},
|
315
|
-
catch: function (
|
316
|
-
for (var
|
317
|
-
var
|
318
|
-
if (
|
319
|
-
var
|
320
|
-
if ("throw" ===
|
321
|
-
var
|
322
|
-
resetTryEntry(
|
320
|
+
catch: function (t) {
|
321
|
+
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
|
322
|
+
var r = this.tryEntries[e];
|
323
|
+
if (r.tryLoc === t) {
|
324
|
+
var n = r.completion;
|
325
|
+
if ("throw" === n.type) {
|
326
|
+
var o = n.arg;
|
327
|
+
resetTryEntry(r);
|
323
328
|
}
|
324
|
-
return
|
329
|
+
return o;
|
325
330
|
}
|
326
331
|
}
|
327
332
|
throw new Error("illegal catch attempt");
|
328
333
|
},
|
329
|
-
delegateYield: function (
|
334
|
+
delegateYield: function (e, r, n) {
|
330
335
|
return this.delegate = {
|
331
|
-
iterator: values(
|
332
|
-
resultName:
|
333
|
-
nextLoc:
|
334
|
-
}, "next" === this.method && (this.arg =
|
336
|
+
iterator: values(e),
|
337
|
+
resultName: r,
|
338
|
+
nextLoc: n
|
339
|
+
}, "next" === this.method && (this.arg = t), y;
|
335
340
|
}
|
336
|
-
},
|
341
|
+
}, e;
|
337
342
|
}
|
338
|
-
function _typeof(
|
343
|
+
function _typeof(o) {
|
339
344
|
"@babel/helpers - typeof";
|
340
345
|
|
341
|
-
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (
|
342
|
-
return typeof
|
343
|
-
} : function (
|
344
|
-
return
|
345
|
-
}, _typeof(
|
346
|
+
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
|
347
|
+
return typeof o;
|
348
|
+
} : function (o) {
|
349
|
+
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
|
350
|
+
}, _typeof(o);
|
346
351
|
}
|
347
352
|
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
348
353
|
try {
|
@@ -1016,17 +1021,24 @@ if(isDefined(payload.groupId)){payload.groupId=tryStringify(payload.groupId);}el
|
|
1016
1021
|
|
1017
1022
|
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 LOAD_CONFIGURATION='LoadConfiguration';var EVENT_REPOSITORY='EventRepository';var EXTERNAL_SRC_LOADER='ExternalSrcLoader';var HTTP_CLIENT='HttpClient';var RS_APP='RudderStackApplication';var ANALYTICS_CORE='AnalyticsCore';
|
1018
1023
|
|
1019
|
-
var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.0.0-beta.
|
1024
|
+
var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.0.0-beta.6';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';
|
1020
1025
|
|
1021
1026
|
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';
|
1022
1027
|
|
1028
|
+
var DEFAULT_XHR_TIMEOUT_MS=10*1000;// 10 seconds
|
1029
|
+
var DEFAULT_COOKIE_MAX_AGE_MS=31536000*1000;// 1 year
|
1030
|
+
var DEFAULT_SESSION_TIMEOUT_MS=30*60*1000;// 30 minutes
|
1031
|
+
var MIN_SESSION_TIMEOUT_MS=10*1000;// 10 seconds
|
1032
|
+
var DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS=10*1000;// 10 seconds
|
1033
|
+
var DEBOUNCED_TIMEOUT_MS=250;// 250 milliseconds
|
1034
|
+
|
1023
1035
|
/**
|
1024
1036
|
* Create globally accessible RudderStackGlobals object
|
1025
1037
|
*/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]={};}};/**
|
1026
1038
|
* Add move values to globally accessible RudderStackGlobals object per analytics instance
|
1027
1039
|
*/var setExposedGlobal=function setExposedGlobal(keyName,value){var analyticsInstanceId=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'app';createExposedGlobals(analyticsInstanceId);globalThis.RudderStackGlobals[analyticsInstanceId][keyName]=value;};/**
|
1028
1040
|
* Get values from globally accessible RudderStackGlobals object by analytics instance
|
1029
|
-
*/var getExposedGlobal=function getExposedGlobal(keyName){var analyticsInstanceId=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'app';createExposedGlobals(analyticsInstanceId);return globalThis.RudderStackGlobals[analyticsInstanceId][keyName];};
|
1041
|
+
*/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);};}
|
1030
1042
|
|
1031
1043
|
/**
|
1032
1044
|
* Parse query string params into object values for keys that start with a defined prefix
|
@@ -1057,14 +1069,14 @@ var JSON_STRINGIFY='JSONStringify';var getCircularReplacer=function getCircularR
|
|
1057
1069
|
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.
|
1058
1070
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
1059
1071
|
// @ts-ignore-next-line
|
1060
|
-
while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop();}if(ancestors.includes(value)){logger===null||logger===void 0
|
1072
|
+
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;};};/**
|
1061
1073
|
* Utility method for JSON stringify object excluding null values & circular references
|
1062
1074
|
*
|
1063
1075
|
* @param {*} value input
|
1064
1076
|
* @param {boolean} excludeNull if it should exclude nul or not
|
1065
1077
|
* @param {function} logger optional logger methods for warning
|
1066
1078
|
* @returns string
|
1067
|
-
*/var stringifyWithoutCircular=function stringifyWithoutCircular(value,excludeNull,excludeKeys,logger){try{return JSON.stringify(value,getCircularReplacer(excludeNull,excludeKeys,logger));}catch(err){logger===null||logger===void 0
|
1079
|
+
*/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;}};
|
1068
1080
|
|
1069
1081
|
/**
|
1070
1082
|
* Get mutated error with issue prepended to error message
|
@@ -1115,7 +1127,7 @@ timeoutID=globalThis.setTimeout(function(){reject(new Error(SCRIPT_LOAD_TIMEOUT_
|
|
1115
1127
|
* Load external resource of type javascript
|
1116
1128
|
*/_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=!(callback&&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();}});}/**
|
1117
1129
|
* Handle errors
|
1118
|
-
*/},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0
|
1130
|
+
*/},{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;}}}]);return ExternalSrcLoader;}();
|
1119
1131
|
|
1120
1132
|
function i(){throw new Error("Cycle detected");}function t(){if(!(h>1)){var i,t=!1;while(void 0!==n){var o=n;n=void 0;s++;while(void 0!==o){var r=o.o;o.o=void 0;o.f&=-3;if(!(8&o.f)&&c(o))try{o.c();}catch(o){if(!t){i=o;t=!0;}}o=r;}}s=0;h--;if(t)throw i;}else h--;}function o(i){if(h>0)return i();h++;try{return i();}finally{t();}}var r=void 0,n=void 0,h=0,s=0,f=0;function v(i){if(void 0!==r){var t=i.n;if(void 0===t||t.t!==r){t={i:0,S:i,p:r.s,n:void 0,t:r,e:void 0,x:void 0,r:t};if(void 0!==r.s)r.s.n=t;r.s=t;i.n=t;if(32&r.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=r.s;t.n=void 0;r.s.n=t;r.s=t;}return t;}}}function e(i){this.v=i;this.i=0;this.n=void 0;this.t=void 0;}e.prototype.h=function(){return !0;};e.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;}};e.prototype.U=function(i){if(void 0!==this.t){var t=i.e,o=i.x;if(void 0!==t){t.x=o;i.e=void 0;}if(void 0!==o){o.e=t;i.x=void 0;}if(i===this.t)this.t=o;}};e.prototype.subscribe=function(i){var t=this;return b(function(){var o=t.value,r=32&this.f;this.f&=-33;try{i(o);}finally{this.f|=r;}});};e.prototype.valueOf=function(){return this.value;};e.prototype.toString=function(){return this.value+"";};e.prototype.toJSON=function(){return this.value;};e.prototype.peek=function(){return this.v;};Object.defineProperty(e.prototype,"value",{get:function get(){var i=v(this);if(void 0!==i)i.i=this.i;return this.v;},set:function set(o){if(r instanceof l)!function(){throw new Error("Computed cannot have side-effects");}();if(o!==this.v){if(s>100)i();this.v=o;this.i++;f++;h++;try{for(var n=this.t;void 0!==n;n=n.x)n.t.N();}finally{t();}}}});function u(i){return new e(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 d(i){for(var t=i.s;void 0!==t;t=t.n){var o=t.S.n;if(void 0!==o)t.r=o;t.S.n=t;t.i=-1;if(void 0===t.n){i.s=t;break;}}}function a(i){var t=i.s,o=void 0;while(void 0!==t){var r=t.p;if(-1===t.i){t.S.U(t);if(void 0!==r)r.n=t.n;if(void 0!==t.n)t.n.p=r;}else o=t;t.S.n=t.r;if(void 0!==t.r)t.r=void 0;t=r;}i.s=o;}function l(i){e.call(this,void 0);this.x=i;this.s=void 0;this.g=f-1;this.f=4;}(l.prototype=new e()).h=function(){this.f&=-3;if(1&this.f)return !1;if(32==(36&this.f))return !0;this.f&=-5;if(this.g===f)return !0;this.g=f;this.f|=1;if(this.i>0&&!c(this)){this.f&=-2;return !0;}var i=r;try{d(this);r=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++;}r=i;a(this);this.f&=-2;return !0;};l.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);}e.prototype.S.call(this,i);};l.prototype.U=function(i){if(void 0!==this.t){e.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);}}};l.prototype.N=function(){if(!(2&this.f)){this.f|=6;for(var i=this.t;void 0!==i;i=i.x)i.t.N();}};l.prototype.peek=function(){if(!this.h())i();if(16&this.f)throw this.v;return this.v;};Object.defineProperty(l.prototype,"value",{get:function get(){if(1&this.f)i();var t=v(this);this.h();if(void 0!==t)t.i=this.i;if(16&this.f)throw this.v;return this.v;}});function y(i){var o=i.u;i.u=void 0;if("function"==typeof o){h++;var n=r;r=void 0;try{o();}catch(t){i.f&=-2;i.f|=8;_(i);throw t;}finally{r=n;t();}}}function _(i){for(var t=i.s;void 0!==t;t=t.n)t.S.U(t);i.x=void 0;i.s=void 0;y(i);}function p(i){if(r!==this)throw new Error("Out-of-order effect");a(this);r=i;this.f&=-2;if(8&this.f)_(this);t();}function g(i){this.x=i;this.u=void 0;this.s=void 0;this.o=void 0;this.f=32;}g.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();}};g.prototype.S=function(){if(1&this.f)i();this.f|=1;this.f&=-9;y(this);d(this);h++;var t=r;r=this;return p.bind(this,t);};g.prototype.N=function(){if(!(2&this.f)){this.f|=2;this.o=n;n=this;}};g.prototype.d=function(){this.f|=8;if(!(1&this.f))_(this);};function b(i){var t=new g(i);try{t.c();}catch(i){t.d();throw i;}return t.d.bind(t);}
|
1121
1133
|
|
@@ -1129,7 +1141,7 @@ var LifecycleStatus=/*#__PURE__*/function(LifecycleStatus){LifecycleStatus["Moun
|
|
1129
1141
|
|
1130
1142
|
var _LOG_LEVEL_MAP;var LOG_LEVEL_MAP=(_LOG_LEVEL_MAP={},_defineProperty(_LOG_LEVEL_MAP,LogLevel.Log,0),_defineProperty(_LOG_LEVEL_MAP,LogLevel.Info,1),_defineProperty(_LOG_LEVEL_MAP,LogLevel.Debug,2),_defineProperty(_LOG_LEVEL_MAP,LogLevel.Warn,3),_defineProperty(_LOG_LEVEL_MAP,LogLevel.Error,4),_defineProperty(_LOG_LEVEL_MAP,LogLevel.None,5),_LOG_LEVEL_MAP);var DEFAULT_LOG_LEVEL=LogLevel.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;';/**
|
1131
1143
|
* Service to log messages/data to output provider, default is console
|
1132
|
-
*/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;}_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(LogLevel.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(LogLevel.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(LogLevel.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(LogLevel.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(LogLevel.Error,data);}},{key:"outputLog",value:function outputLog(logMethod,data){if(this.minLogLevel<=LOG_LEVEL_MAP[logMethod]){var _this$logProvider;(_this$logProvider=this.logProvider)[logMethod.toLowerCase()].apply(_this$logProvider,_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
|
1144
|
+
*/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;}_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(LogLevel.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(LogLevel.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(LogLevel.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(LogLevel.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(LogLevel.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
|
1133
1145
|
// to assist on the fly debugging?
|
1134
1146
|
},{key:"setMinLogLevel",value:function setMinLogLevel(logLevel){this.minLogLevel=LOG_LEVEL_MAP[logLevel];if(isUndefined(this.minLogLevel)){this.minLogLevel=LOG_LEVEL_MAP[DEFAULT_LOG_LEVEL];}}/**
|
1135
1147
|
* Formats the console message using `scope` and styles
|
@@ -1148,13 +1160,7 @@ var SUPPORTED_STORAGE_TYPES=['localStorage','memoryStorage','cookieStorage','ses
|
|
1148
1160
|
|
1149
1161
|
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 INTG_CDN_BASE_URL_ERROR="Failed to load the SDK as the CDN base URL for integrations is not valid.";var PLUGINS_CDN_BASE_URL_ERROR="Failed to load the SDK as the CDN base URL for plugins is not valid.";var DATA_PLANE_URL_ERROR="Failed to load the SDK as the data plane URL could not be determined. Please check that the data plane URL is set correctly and try again.";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.";// ERROR
|
1150
1162
|
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");};// WARNING
|
1151
|
-
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 storage types: \"").concat(SUPPORTED_STORAGE_TYPES,"\". The default storage \"").concat(defaultStorageType,"\" will be used instead.");};var UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING=function UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING(context,selectedErrorReportingProvider,errorReportingProvidersToPluginNameMap,defaultProvider){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The error reporting provider \"").concat(selectedErrorReportingProvider,"\" is not supported. Please choose one of the following supported providers: \"").concat(Object.keys(errorReportingProvidersToPluginNameMap),"\". The default provider \"").concat(defaultProvider,"\" 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 UNSUPPORTED_RESIDENCY_SERVER_REGION_WARNING=function UNSUPPORTED_RESIDENCY_SERVER_REGION_WARNING(context,selectedResidencyServerRegion,defaultRegion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The residency server region \"").concat(selectedResidencyServerRegion,"\" is not supported. Please choose one of the following supported regions: \"").concat(Object.values(ResidencyServerRegion),"\". The default region \"").concat(defaultRegion,"\" will be used instead.");};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 INVALID_CONTEXT_OBJECT_WARNING=function INVALID_CONTEXT_OBJECT_WARNING(logContext){return "".concat(logContext).concat(LOG_CONTEXT_SEPARATOR,"Please make sure that the \"context\" property in the event API's \"options\" argument is a valid object literal with key-value pairs.");};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,selectedStorageType,finalStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(selectedStorageType,"\" is not available. The SDK will be initialized with \"").concat(finalStorageType,"\" 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 INVALID_CONFIG_URL_WARNING=function INVALID_CONFIG_URL_WARNING(context,configUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided config URL \"").concat(configUrl,"\" is invalid. Using the default value instead.");};// DEBUG
|
1152
|
-
|
1153
|
-
var DEFAULT_XHR_TIMEOUT_MS=10*1000;// 10 seconds
|
1154
|
-
var DEFAULT_COOKIE_MAX_AGE_MS=31536000*1000;// 1 year
|
1155
|
-
var DEFAULT_SESSION_TIMEOUT_MS=30*60*1000;// 30 minutes
|
1156
|
-
var MIN_SESSION_TIMEOUT_MS=10*1000;// 10 seconds
|
1157
|
-
var DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS=10*1000;// 10 seconds
|
1163
|
+
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 storage types: \"").concat(SUPPORTED_STORAGE_TYPES,"\". The default storage \"").concat(defaultStorageType,"\" will be used instead.");};var UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING=function UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING(context,selectedErrorReportingProvider,errorReportingProvidersToPluginNameMap,defaultProvider){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The error reporting provider \"").concat(selectedErrorReportingProvider,"\" is not supported. Please choose one of the following supported providers: \"").concat(Object.keys(errorReportingProvidersToPluginNameMap),"\". The default provider \"").concat(defaultProvider,"\" 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 UNSUPPORTED_RESIDENCY_SERVER_REGION_WARNING=function UNSUPPORTED_RESIDENCY_SERVER_REGION_WARNING(context,selectedResidencyServerRegion,defaultRegion){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The residency server region \"").concat(selectedResidencyServerRegion,"\" is not supported. Please choose one of the following supported regions: \"").concat(Object.values(ResidencyServerRegion),"\". The default region \"").concat(defaultRegion,"\" will be used instead.");};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 INVALID_CONTEXT_OBJECT_WARNING=function INVALID_CONTEXT_OBJECT_WARNING(logContext){return "".concat(logContext).concat(LOG_CONTEXT_SEPARATOR,"Please make sure that the \"context\" property in the event API's \"options\" argument is a valid object literal with key-value pairs.");};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,selectedStorageType,finalStorageType){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The storage type \"").concat(selectedStorageType,"\" is not available. The SDK will be initialized with \"").concat(finalStorageType,"\" 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 INVALID_CONFIG_URL_WARNING=function INVALID_CONFIG_URL_WARNING(context,configUrl){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"The provided config URL \"").concat(configUrl,"\" is invalid. Using the default value 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 COOKIE_DATA_ENCODING_ERROR="Failed to encode the cookie data.";// DEBUG
|
1158
1164
|
|
1159
1165
|
var BUILD_TYPE='legacy';var SDK_CDN_BASE_URL='https://cdn.rudderlabs.com';var CDN_ARCH_VERSION_DIR='v3';var CDN_INT_DIR='js-integrations';var CDN_PLUGINS_DIR='plugins';var DEST_SDK_BASE_URL="".concat(SDK_CDN_BASE_URL,"/beta/3.0.0-beta/").concat(BUILD_TYPE,"/").concat(CDN_INT_DIR);var PLUGINS_BASE_URL="".concat(SDK_CDN_BASE_URL,"/beta/3.0.0-beta/").concat(BUILD_TYPE,"/").concat(CDN_PLUGINS_DIR);// TODO: change the above to production URLs when beta phase is done
|
1160
1166
|
// const DEST_SDK_BASE_URL = `${SDK_CDN_BASE_URL}/latest/${CDN_ARCH_VERSION_DIR}/${BUILD_TYPE}/${CDN_INT_DIR}`;
|
@@ -1179,7 +1185,7 @@ var consentsState={data:u({initialized:false}),activeConsentManagerPluginName:u(
|
|
1179
1185
|
|
1180
1186
|
var metricsState={retries:u(0),dropped:u(0),sent:u(0),queued:u(0),triggered:u(0)};
|
1181
1187
|
|
1182
|
-
var contextState={app:u({name:APP_NAME,namespace:APP_NAMESPACE,version:APP_VERSION}),traits:u(null),library:u({name:APP_NAME,version:APP_VERSION}),userAgent:u(''),device:u(null),network:u(null),os:u({name:'',version:''}),locale:u(null),screen:u({density:0,width:0,height:0,innerWidth:0,innerHeight:0}),'ua-ch':u(undefined)
|
1188
|
+
var contextState={app:u({name:APP_NAME,namespace:APP_NAMESPACE,version:APP_VERSION}),traits:u(null),library:u({name:APP_NAME,version:APP_VERSION}),userAgent:u(''),device:u(null),network:u(null),os:u({name:'',version:''}),locale:u(null),screen:u({density:0,width:0,height:0,innerWidth:0,innerHeight:0}),'ua-ch':u(undefined)};
|
1183
1189
|
|
1184
1190
|
var nativeDestinationsState={configuredDestinations:u([]),activeDestinations:u([]),loadOnlyIntegrations:u({}),failedDestinations:u([]),loadIntegration:u(true),initializedDestinations:u([]),clientDestinationsReady:u(false),integrationsConfig:u({})};
|
1185
1191
|
|
@@ -1187,21 +1193,19 @@ var eventBufferState={toBeProcessedArray:u([]),readyCallbacksArray:u([])};
|
|
1187
1193
|
|
1188
1194
|
var pluginsState={ready:u(false),loadedPlugins:u([]),failedPlugins:u([]),pluginsToLoadFromConfig:u([]),activePlugins:u([]),totalPluginsToLoad:u(0)};
|
1189
1195
|
|
1190
|
-
var pagePropertiesState={path:u(''),referrer:u(''),referring_domain:u(''),search:u(''),title:u(''),url:u(''),tab_url:u('')};
|
1191
|
-
|
1192
1196
|
var storageState={encryptionPluginName:u(undefined),migrate:u(false),type:u(undefined)};
|
1193
1197
|
|
1194
|
-
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,
|
1198
|
+
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};var state=_objectSpread2({},clone$1(defaultStateValues));
|
1195
1199
|
|
1196
1200
|
// to next or return the value if it is the last one instead of an array per
|
1197
1201
|
// plugin that is the normal invoke
|
1198
1202
|
// TODO: add invoke method for extension point that we know only one plugin can be used. add invokeMultiple and invokeSingle methods
|
1199
|
-
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;}_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
|
1200
|
-
var notExistDeps=plugin.deps.filter(function(dependency){return !_this.byName[dependency];});(_this$logger5=_this.logger)===null||_this$logger5===void 0
|
1203
|
+
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;}_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(plugin.initialize&&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.
|
1204
|
+
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
|
1201
1205
|
// do some unified pre-process before application starts.
|
1202
1206
|
},{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
|
1203
1207
|
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
|
1204
|
-
if(throws){throw err;}else {var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===void 0
|
1208
|
+
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));}}]);return PluginEngine;}();var defaultPluginEngine=new PluginEngine({throws:true},defaultLogger);
|
1205
1209
|
|
1206
1210
|
var FAILED_REQUEST_ERR_MSG_PREFIX='The request failed';var ERROR_MESSAGES_TO_BE_FILTERED=[FAILED_REQUEST_ERR_MSG_PREFIX];
|
1207
1211
|
|
@@ -1216,7 +1220,7 @@ var FAILED_REQUEST_ERR_MSG_PREFIX='The request failed';var ERROR_MESSAGES_TO_BE_
|
|
1216
1220
|
/**
|
1217
1221
|
* A service to handle errors
|
1218
1222
|
*/var ErrorHandler=/*#__PURE__*/function(){// If no logger is passed errors will be thrown as unhandled error
|
1219
|
-
function ErrorHandler(logger,pluginEngine){_classCallCheck(this,ErrorHandler);this.logger=logger;this.pluginEngine=pluginEngine;}_createClass(ErrorHandler,[{key:"init",value:function init(externalSrcLoader){var _this=this;if(!this.pluginEngine){return;}try{var extPoint='errorReporting.init';var errReportingInitVal=this.pluginEngine.invokeSingle(extPoint,state,this.pluginEngine,externalSrcLoader,this.logger);if(errReportingInitVal instanceof Promise){errReportingInitVal.then(function(client){_this.errReportingClient=client;}).catch(function(err){var _this$logger;(_this$logger=_this.logger)===null||_this$logger===void 0
|
1223
|
+
function ErrorHandler(logger,pluginEngine){_classCallCheck(this,ErrorHandler);this.logger=logger;this.pluginEngine=pluginEngine;}_createClass(ErrorHandler,[{key:"init",value:function init(externalSrcLoader){var _this=this;if(!this.pluginEngine){return;}try{var extPoint='errorReporting.init';var errReportingInitVal=this.pluginEngine.invokeSingle(extPoint,state,this.pluginEngine,externalSrcLoader,this.logger);if(errReportingInitVal instanceof Promise){errReportingInitVal.then(function(client){_this.errReportingClient=client;}).catch(function(err){var _this$logger;(_this$logger=_this.logger)===null||_this$logger===void 0||_this$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;// Error handling is already implemented in processError method
|
1220
1224
|
var errorMessage=processError(error);// If no error message after we normalize, then we swallow/ignore the errors
|
1221
1225
|
if(!errorMessage){return;}errorMessage=removeDoubleSpaces("".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(customMessage," ").concat(errorMessage));var normalizedError=error;// Enhance error message
|
1222
1226
|
if(isTypeOfError(error)){normalizedError.message=errorMessage;}else {normalizedError=new Error(errorMessage);}this.notifyError(normalizedError);if(this.logger){this.logger.error(errorMessage);if(shouldAlwaysThrow){throw normalizedError;}}else {throw normalizedError;}}/**
|
@@ -1229,7 +1233,7 @@ if(isTypeOfError(error)){normalizedError.message=errorMessage;}else {normalizedE
|
|
1229
1233
|
*
|
1230
1234
|
* @param {Error} error Error instance from handled error
|
1231
1235
|
*/},{key:"notifyError",value:function notifyError(error){if(this.pluginEngine&&isAllowedToBeNotified(error)){try{this.pluginEngine.invokeSingle('errorReporting.notify',this.pluginEngine,this.errReportingClient,error,state,this.logger);}catch(err){var _this$logger2;// Not calling onError here as we don't want to go into infinite loop
|
1232
|
-
(_this$logger2=this.logger)===null||_this$logger2===void 0
|
1236
|
+
(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(NOTIFY_FAILURE_ERROR(ERROR_HANDLER),err);}}}}]);return ErrorHandler;}();var defaultErrorHandler=new ErrorHandler(defaultLogger,defaultPluginEngine);
|
1233
1237
|
|
1234
1238
|
var DestinationConnectionMode=/*#__PURE__*/function(DestinationConnectionMode){DestinationConnectionMode["Hybrid"]="hybrid";DestinationConnectionMode["Cloud"]="cloud";DestinationConnectionMode["Device"]="device";return DestinationConnectionMode;}({});
|
1235
1239
|
|
@@ -1265,7 +1269,7 @@ var hasCrypto$1=function hasCrypto(){return !isNullOrUndefined(globalThis.crypto
|
|
1265
1269
|
|
1266
1270
|
var generateUUID=function generateUUID(){if(hasCrypto$1()){return v4$1();}return v4();};
|
1267
1271
|
|
1268
|
-
var QueueStatuses={IN_PROGRESS:'inProgress',QUEUE:'queue',RECLAIM_START:'reclaimStart',RECLAIM_END:'reclaimEnd',ACK:'ack'};
|
1272
|
+
var QueueStatuses={IN_PROGRESS:'inProgress',QUEUE:'queue',RECLAIM_START:'reclaimStart',RECLAIM_END:'reclaimEnd',ACK:'ack',BATCH_QUEUE:'batchQueue'};
|
1269
1273
|
|
1270
1274
|
var _CNameMapping$18;var DIR_NAME$18='AdobeAnalytics';var NAME$18='ADOBE_ANALYTICS';var DISPLAY_NAME$18='Adobe Analytics';var DISPLAY_NAME_TO_DIR_NAME_MAP$18=_defineProperty({},DISPLAY_NAME$18,DIR_NAME$18);var CNameMapping$18=(_CNameMapping$18={'Adobe Analytics':NAME$18,ADOBEANALYTICS:NAME$18,'ADOBE ANALYTICS':NAME$18},_defineProperty(_CNameMapping$18,NAME$18,NAME$18),_defineProperty(_CNameMapping$18,"AdobeAnalytics",NAME$18),_defineProperty(_CNameMapping$18,"adobeanalytics",NAME$18),_defineProperty(_CNameMapping$18,'adobe analytics',NAME$18),_defineProperty(_CNameMapping$18,'Adobe analytics',NAME$18),_defineProperty(_CNameMapping$18,'adobe Analytics',NAME$18),_CNameMapping$18);
|
1271
1275
|
|
@@ -1425,7 +1429,7 @@ var destCNamesToDisplayNamesMap=_objectSpread2(_objectSpread2(_objectSpread2(_ob
|
|
1425
1429
|
var EVENT_PAYLOAD_SIZE_BYTES_LIMIT=32*1024;// 32 KB
|
1426
1430
|
|
1427
1431
|
var INVALID_SOURCE_CONFIG_ERROR="Invalid source configuration or source id.";// ERROR
|
1428
|
-
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,".");};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 BUGSNAG_SDK_LOAD_ERROR=function BUGSNAG_SDK_LOAD_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to load the Bugsnag SDK.");};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_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 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 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="Failed to determine the consent status for the destination. Please check the destination configuration and try again.";var STORAGE_MIGRATION_ERROR=function STORAGE_MIGRATION_ERROR(key){return "Failed to retrieve or parse data for ".concat(key," from storage.");};var
|
1432
|
+
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,".");};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 BUGSNAG_SDK_LOAD_ERROR=function BUGSNAG_SDK_LOAD_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Failed to load the Bugsnag SDK.");};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_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 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 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="Failed to determine the consent status for the destination. Please check the destination configuration and try again.";var STORAGE_MIGRATION_ERROR=function STORAGE_MIGRATION_ERROR(key){return "Failed to retrieve or parse data for ".concat(key," from storage.");};var RETRY_QUEUE_PROCESS_ERROR=function RETRY_QUEUE_PROCESS_ERROR(context){return "".concat(context).concat(LOG_CONTEXT_SEPARATOR,"Process function threw an error.");};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,".");};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 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.");};var DESTINATION_EVENT_FORWARDING_ERROR=function DESTINATION_EVENT_FORWARDING_ERROR(destUserFriendlyId){return "Failed to forward event to destination \"".concat(destUserFriendlyId,"\".");};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.");};// WARN
|
1429
1433
|
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.");};// DEBUG
|
1430
1434
|
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.");};
|
1431
1435
|
|
@@ -1434,11 +1438,11 @@ var QUEUE_UTILITIES='QueueUtilities';/**
|
|
1434
1438
|
* @param event RudderEvent object
|
1435
1439
|
* @param logger Logger instance
|
1436
1440
|
* @returns stringified event payload. Empty string if error occurs.
|
1437
|
-
*/var getDeliveryPayload$1=function getDeliveryPayload(event,logger){
|
1441
|
+
*/var getDeliveryPayload$1=function getDeliveryPayload(event,logger){return stringifyWithoutCircular(event,true,undefined,logger);};var getBatchDeliveryPayload=function getBatchDeliveryPayload(events,logger){return stringifyWithoutCircular({batch:events},true,undefined,logger);};/**
|
1438
1442
|
* Utility to validate final payload size before sending to server
|
1439
1443
|
* @param event RudderEvent object
|
1440
1444
|
* @param logger Logger instance
|
1441
|
-
*/var validateEventPayloadSize=function validateEventPayloadSize(event,logger){var payloadStr=getDeliveryPayload$1(event,logger);if(payloadStr){var payloadSize=payloadStr.length;if(payloadSize>EVENT_PAYLOAD_SIZE_BYTES_LIMIT){logger===null||logger===void 0
|
1445
|
+
*/var validateEventPayloadSize=function validateEventPayloadSize(event,logger){var payloadStr=getDeliveryPayload$1(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));}};/**
|
1442
1446
|
* Filters and returns the user supplied integrations config that should take preference over the destination specific integrations config
|
1443
1447
|
* @param eventIntgConfig User supplied integrations config at event level
|
1444
1448
|
* @param destinationsIntgConfig Cumulative integrations config from all destinations
|
@@ -1466,7 +1470,7 @@ var DEFAULT_BEACON_QUEUE_OPTIONS={maxItems:DEFAULT_BEACON_QUEUE_MAX_SIZE,flushQu
|
|
1466
1470
|
* @param events RudderEvent object array
|
1467
1471
|
* @param logger Logger instance
|
1468
1472
|
* @returns stringified events payload as Blob, undefined if error occurs.
|
1469
|
-
*/var getDeliveryPayload=function getDeliveryPayload(events,logger){var data={batch:events};try{var blobPayload=stringifyWithoutCircular(data,true);var blobOptions={type:'text/plain'};if(blobPayload){return new Blob([blobPayload],blobOptions);}logger===null||logger===void 0
|
1473
|
+
*/var getDeliveryPayload=function getDeliveryPayload(events,logger){var data={batch:events};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;};
|
1470
1474
|
|
1471
1475
|
var COOKIE_STORAGE='cookieStorage';var LOCAL_STORAGE='localStorage';var SESSION_STORAGE='sessionStorage';var MEMORY_STORAGE='memoryStorage';var NO_STORAGE='none';
|
1472
1476
|
|
@@ -1477,7 +1481,7 @@ var eventsToSend=queue.slice(0);var batchData=getDeliveryPayload(eventsToSend.ma
|
|
1477
1481
|
var isExceededMaxPayloadSize=Boolean(batchData&&batchData.length>MAX_BATCH_PAYLOAD_SIZE_BYTES);if(isExceededMaxPayloadSize){// Flush all previous items
|
1478
1482
|
eventsToSend=queue.slice(0,queue.length-1);this.flushQueue(eventsToSend);// Add only latest item in the remaining queue that is cleared appropriately in flushQueue
|
1479
1483
|
queue=this.getQueue();queue.push(entry);}this.setQueue(this.name,queue);// If queue has total of max items then flush
|
1480
|
-
if(queue.length===this.maxItems){this.flushQueue();}this.start();}},{key:"addItem",value:function addItem(
|
1484
|
+
if(queue.length===this.maxItems){this.flushQueue();}this.start();}},{key:"addItem",value:function addItem(itemData){this.enqueue({item:itemData,attemptNumber:0,time:Date.now(),id:generateUUID()});}},{key:"flushQueue",value:function flushQueue(queueItems){var _this2=this;if(!this.flushInProgress){this.flushInProgress=true;var batchItems=queueItems!==null&&queueItems!==void 0?queueItems:this.getQueue();var batchData=batchItems&&batchItems.length>0?batchItems.slice(0,batchItems.length):[];// TODO: add retry mechanism here
|
1481
1485
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
1482
1486
|
var beaconSendCallback=function beaconSendCallback(error,response){_this2.setQueue(_this2.name,[]);_this2.stop();_this2.flushInProgress=false;if(_this2.nextFlushPending){_this2.nextFlushPending=false;_this2.flushQueue();}};if(batchData.length>0){this.processQueueCb(batchData,beaconSendCallback);return;}// If no items to send just clear timer
|
1483
1487
|
beaconSendCallback(null);}else {this.nextFlushPending=true;}}}]);return BeaconItemsQueue;}();
|
@@ -1490,7 +1494,7 @@ var pluginName$d='BeaconQueue';var BeaconQueue=function BeaconQueue(){return {na
|
|
1490
1494
|
* @param errorHandler Error handler instance
|
1491
1495
|
* @param logger Logger instance
|
1492
1496
|
* @returns BeaconItemsQueue instance
|
1493
|
-
*/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(queueItems,done){logger===null||logger===void 0
|
1497
|
+
*/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(queueItems,done){logger===null||logger===void 0||logger.debug(BEACON_PLUGIN_EVENTS_QUEUE_DEBUG(BEACON_QUEUE_PLUGIN));var finalEvents=queueItems.map(function(queueItem){return getFinalEventForDeliveryMutator(queueItem.item.event,state);});var data=getDeliveryPayload(finalEvents);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));done(err);}}else {// Mark the item as done so that it can be removed from the queue
|
1494
1498
|
done(null);}};var eventsQueue=new BeaconItemsQueue("".concat(QUEUE_NAME$2,"_").concat(writeKey,"}"),finalQOpts,queueProcessCallback,storeManager);return eventsQueue;},/**
|
1495
1499
|
* Add event to the queue for delivery
|
1496
1500
|
* @param state Application state
|
@@ -1528,15 +1532,15 @@ event.context='Script load failures';}// eslint-disable-next-line no-param-reass
|
|
1528
1532
|
event.severity='error';};var onError=function onError(state){var _state$source$value;var metadataSource=(_state$source$value=state.source.value)===null||_state$source$value===void 0?void 0:_state$source$value.id;return function(event){try{// Discard the event if it's not originated at the SDK
|
1529
1533
|
if(!isRudderSDKError(event)){return false;}enhanceErrorEventMutator(event,metadataSource);return true;}catch(_unused){// Drop the error event if it couldn't be filtered as
|
1530
1534
|
// it is most likely a non-SDK error
|
1531
|
-
return false;}};};var getReleaseStage=function getReleaseStage(){var host=globalThis.location.hostname;return host&&DEV_HOSTS.includes(host)?'development':'production';};var getGlobalBugsnagLibInstance=function getGlobalBugsnagLibInstance(){return globalThis[BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME];};var getNewClient=function getNewClient(state,logger){var globalBugsnagLibInstance=getGlobalBugsnagLibInstance();var clientConfig={apiKey:API_KEY,appVersion:'3.0.0-beta.
|
1535
|
+
return false;}};};var getReleaseStage=function getReleaseStage(){var host=globalThis.location.hostname;return host&&DEV_HOSTS.includes(host)?'development':'production';};var getGlobalBugsnagLibInstance=function getGlobalBugsnagLibInstance(){return globalThis[BUGSNAG_LIB_INSTANCE_GLOBAL_KEY_NAME];};var getNewClient=function getNewClient(state,logger){var globalBugsnagLibInstance=getGlobalBugsnagLibInstance();var clientConfig={apiKey:API_KEY,appVersion:'3.0.0-beta.6',// Set SDK version as the app version from build config
|
1532
1536
|
metaData:{SDK:{name:'JS',installType:'npm'}},beforeSend:onError(state),autoCaptureSessions:false,// auto capture sessions is disabled
|
1533
1537
|
collectUserIp:false,// collecting user's IP is disabled
|
1534
1538
|
// enabledBreadcrumbTypes: ['error', 'log', 'user'], // for v7 and above
|
1535
|
-
maxEvents:100,maxBreadcrumbs:40,releaseStage:getReleaseStage(),user:{id:state.lifecycle.writeKey.value},logger:logger};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
|
1539
|
+
maxEvents:100,maxBreadcrumbs:40,releaseStage:getReleaseStage(),user:{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
|
1536
1540
|
globalThis.setTimeout(initBugsnagClient,SDK_LOAD_POLL_INTERVAL_MS,state,promiseResolve,promiseReject,logger,time+SDK_LOAD_POLL_INTERVAL_MS);}};var getAppStateForMetadata=function getAppStateForMetadata(state){var stateStr=stringifyWithoutCircular(state,false,APP_STATE_EXCLUDE_KEYS);return stateStr!==null?JSON.parse(stateStr):undefined;};
|
1537
1541
|
|
1538
1542
|
var pluginName$c='Bugsnag';var Bugsnag=function Bugsnag(){return {name:pluginName$c,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$c]);},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
|
1539
|
-
if(!isApiKeyValid(API_KEY)){reject(new Error(BUGSNAG_API_KEY_VALIDATION_ERROR(API_KEY)));return;}loadBugsnagSDK(externalSrcLoader,logger);initBugsnagClient(state,resolve,reject,logger);});},notify:function notify(client,error,state,logger){client===null||client===void 0
|
1543
|
+
if(!isApiKeyValid(API_KEY)){reject(new Error(BUGSNAG_API_KEY_VALIDATION_ERROR(API_KEY)));return;}loadBugsnagSDK(externalSrcLoader,logger);initBugsnagClient(state,resolve,reject,logger);});},notify:function notify(client,error,state,logger){client===null||client===void 0||client.notify(error,{metaData:{state:getAppStateForMetadata(state)}});},breadcrumb:function breadcrumb(client,message,logger){client===null||client===void 0||client.leaveBreadcrumb(message);}}};};
|
1540
1544
|
|
1541
1545
|
var READY_CHECK_TIMEOUT_MS=11*1000;// 11 seconds
|
1542
1546
|
var SCRIPT_LOAD_TIMEOUT_MS=10*1000;// 10 seconds
|
@@ -1562,16 +1566,16 @@ var isDestIntgConfigTruthy=function isDestIntgConfigTruthy(destIntgConfig){retur
|
|
1562
1566
|
* @param curDestIntgConfig Current destinations integration config
|
1563
1567
|
* @param logger Logger object
|
1564
1568
|
* @returns Combined destinations integrations config
|
1565
|
-
*/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,normalizeIntegrationOptions((_dest$instance2=dest.instance)===null||_dest$instance2===void 0?void 0:_dest$instance2.getDataForIntegrationsObject()));}catch(err){errorHandler===null||errorHandler===void 0
|
1566
|
-
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){
|
1567
|
-
logger===null||logger===void 0
|
1569
|
+
*/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,normalizeIntegrationOptions((_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$1(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
|
1570
|
+
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
|
1571
|
+
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));}};
|
1568
1572
|
|
1569
1573
|
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){// Normalize the integration options from the load API call
|
1570
1574
|
state.nativeDestinations.loadOnlyIntegrations.value=normalizeIntegrationOptions(state.loadOptions.value.integrations);state.nativeDestinations.loadIntegration.value=state.loadOptions.value.loadIntegration;// Filter destination that doesn't have mapping config-->Integration names
|
1571
|
-
var configSupportedDestinations=state.nativeDestinations.configuredDestinations.value.filter(function(configDest){if(destDisplayNamesToFileNamesMap[configDest.displayName]){return true;}errorHandler===null||errorHandler===void 0
|
1575
|
+
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 options
|
1572
1576
|
var destinationsToLoad=filterDestinations(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
|
1573
1577
|
(_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
|
1574
|
-
var sdkTypeName=sdkName;if(!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
|
1578
|
+
var sdkTypeName=sdkName;if(!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 {initializeDestination(dest,state,destSDKIdentifier,sdkTypeName,errorHandler,logger);}});}}};};
|
1575
1579
|
|
1576
1580
|
/* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable no-param-reassign */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:{enqueue:function enqueue(state,pluginsManager,event,destination,errorHandler,logger){// TODO: Implement DMT logic here
|
1577
1581
|
// TODO: for now this is a pass through
|
@@ -1681,6 +1685,9 @@ var GoogleLinker=function GoogleLinker(){return {name:pluginName$7,initialize:fu
|
|
1681
1685
|
|
1682
1686
|
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);_defineProperty(this,"tasks",{});_defineProperty(this,"nextId",1);_defineProperty(this,"clock",DEFAULT_CLOCK);}_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={};}},{key:"setClock",value:function setClock(newClock){this.clock=newClock;}},{key:"resetClock",value:function resetClock(){this.clock=DEFAULT_CLOCK;}}]);return Schedule;}();
|
1683
1687
|
|
1688
|
+
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 DEFAULT_MAX_BATCH_SIZE_BYTES=1024*1024;// 1MB
|
1689
|
+
var DEFAULT_MAX_BATCH_ITEMS=100;
|
1690
|
+
|
1684
1691
|
var sortByTime=function sortByTime(a,b){return a.time-b.time;};var RETRY_QUEUE='RetryQueue';/**
|
1685
1692
|
* Constructs a RetryQueue backed by localStorage
|
1686
1693
|
*
|
@@ -1688,10 +1695,11 @@ var sortByTime=function sortByTime(a,b){return a.time-b.time;};var RETRY_QUEUE='
|
|
1688
1695
|
* @param {String} name The name of the queue. Will be used to find abandoned queues and retry their items
|
1689
1696
|
* @param {Object} [opts] Optional argument to override `maxItems`, `maxAttempts`, `minRetryDelay, `maxRetryDelay`, `backoffFactor` and `backoffJitter`.
|
1690
1697
|
* @param {QueueProcessCallback} fn The function to call in order to process an item added to the queue
|
1691
|
-
*/var RetryQueue=/*#__PURE__*/function(){function RetryQueue(name,options,queueProcessCb,storeManager){var storageType=arguments.length>4&&arguments[4]!==undefined?arguments[4]:LOCAL_STORAGE;var logger=arguments.length>5?arguments[5]:undefined;_classCallCheck(this,RetryQueue);this.storeManager=storeManager;this.name=name;this.id=generateUUID();this.processQueueCb=queueProcessCb;this.maxItems=options.maxItems||
|
1692
|
-
this.timeouts={
|
1693
|
-
this.store=this.storeManager.setStore({id:this.id,name:this.name,validKeys:QueueStatuses,type:storageType});this.setQueue(QueueStatuses.IN_PROGRESS,{});this.setQueue(QueueStatuses.QUEUE,[]);// bind recurring tasks for ease of use
|
1694
|
-
this.ack=this.ack.bind(this);this.checkReclaim=this.checkReclaim.bind(this);this.processHead=this.processHead.bind(this);this.scheduleTimeoutActive=false;}_createClass(RetryQueue,[{key:"
|
1698
|
+
*/var RetryQueue=/*#__PURE__*/function(){function RetryQueue(name,options,queueProcessCb,storeManager){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.name=name;this.id=generateUUID();this.processQueueCb=queueProcessCb;this.maxItems=options.maxItems||DEFAULT_MAX_ITEMS;this.maxAttempts=options.maxAttempts||DEFAULT_MAX_RETRY_ATTEMPTS;this.enableBatching=isObjectLiteralAndNotNull(options.batch);this.queueBatchItemsSizeCalculatorCb=queueBatchItemsSizeCalculatorCb;this.configureBatchingOptions(options);this.logger=logger;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};// painstakingly tuned. that's why they're not "easily" configurable
|
1699
|
+
this.timeouts={ackTimer:DEFAULT_ACK_TIMER_MS,reclaimTimer:DEFAULT_RECLAIM_TIMER_MS,reclaimTimeout:DEFAULT_RECLAIM_TIMEOUT_MS,reclaimWait:DEFAULT_RECLAIM_WAIT_MS};this.schedule=new Schedule();this.processId='0';// Set up our empty queues
|
1700
|
+
this.store=this.storeManager.setStore({id:this.id,name:this.name,validKeys:QueueStatuses,type:storageType});this.setQueue(QueueStatuses.IN_PROGRESS,{});this.setQueue(QueueStatuses.QUEUE,[]);this.setQueue(QueueStatuses.BATCH_QUEUE,[]);// bind recurring tasks for ease of use
|
1701
|
+
this.ack=this.ack.bind(this);this.checkReclaim=this.checkReclaim.bind(this);this.processHead=this.processHead.bind(this);this.scheduleTimeoutActive=false;}_createClass(RetryQueue,[{key:"configureBatchingOptions",value:function configureBatchingOptions(options){if(this.enableBatching){this.batch=options.batch;if(isDefined(this.batch.maxSize)){this.batch.maxSize=+this.batch.maxSize||DEFAULT_MAX_BATCH_SIZE_BYTES;}if(isDefined(this.batch.maxItems)){this.batch.maxItems=+this.batch.maxItems||DEFAULT_MAX_BATCH_ITEMS;}// if both maxSize and maxItems are undefined, disable batching
|
1702
|
+
if(isUndefined(this.batch.maxSize)&&isUndefined(this.batch.maxItems)){this.enableBatching=false;}}}},{key:"getQueue",value:function getQueue(name){return this.store.get(name!==null&&name!==void 0?name:this.name);}// TODO: fix the type of different queues to be the same if possible
|
1695
1703
|
},{key:"setQueue",value:function setQueue(name,value){this.store.set(name!==null&&name!==void 0?name:this.name,value!==null&&value!==void 0?value:[]);}/**
|
1696
1704
|
* Stops processing the queue
|
1697
1705
|
*/},{key:"stop",value:function stop(){this.schedule.cancelAll();this.scheduleTimeoutActive=false;}/**
|
@@ -1707,34 +1715,38 @@ this.ack=this.ack.bind(this);this.checkReclaim=this.checkReclaim.bind(this);this
|
|
1707
1715
|
*
|
1708
1716
|
* @param {Number} attemptNumber The attemptNumber (1 for first retry)
|
1709
1717
|
* @return {Number} The delay in milliseconds to wait before attempting a retry
|
1710
|
-
*/},{key:"getDelay",value:function getDelay(attemptNumber){var ms=this.backoff.
|
1718
|
+
*/},{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.enableBatching){var _ref;var batchQueue=(_ref=this.getQueue(QueueStatuses.BATCH_QUEUE))!==null&&_ref!==void 0?_ref:[];batchQueue=batchQueue.slice(-batchQueue.length);batchQueue.push(entry);// if batch criteria is met, queue the batch events to the main queue and clear batch queue
|
1719
|
+
if(this.isBatchReadyToDispatch(batchQueue)){var batchItems=batchQueue.map(function(queueItem){return queueItem.item;});curEntry=this.generateQueueItem(batchItems);batchQueue=[];}this.setQueue(QueueStatuses.BATCH_QUEUE,batchQueue);}else {curEntry=entry;}// when batching is enabled, `curEntry` could be `undefined` if the batch criteria is not met
|
1720
|
+
if(curEntry){var _ref2;var queue=(_ref2=this.getQueue(QueueStatuses.QUEUE))!==null&&_ref2!==void 0?_ref2:[];queue=queue.slice(-(this.maxItems-1));queue.push(curEntry);queue=queue.sort(sortByTime);this.setQueue(QueueStatuses.QUEUE,queue);if(this.scheduleTimeoutActive){this.processHead();}}}/**
|
1711
1721
|
* Adds an item to the queue
|
1712
1722
|
*
|
1713
|
-
* @param {Object}
|
1714
|
-
*/},{key:"addItem",value:function addItem(
|
1723
|
+
* @param {Object} itemData The item to process
|
1724
|
+
*/},{key:"addItem",value:function addItem(itemData){this.enqueue(this.generateQueueItem(itemData));}},{key:"generateQueueItem",value:function generateQueueItem(itemData){return {item:itemData,attemptNumber:0,time:this.schedule.now(),id:generateUUID()};}/**
|
1715
1725
|
* Adds an item to the retry queue
|
1716
1726
|
*
|
1717
|
-
* @param {Object}
|
1727
|
+
* @param {Object} itemData The item to retry
|
1718
1728
|
* @param {Number} attemptNumber The attempt number (1 for first retry)
|
1719
1729
|
* @param {Error} [error] The error from previous attempt, if there was one
|
1720
1730
|
* @param {String} [id] The id of the queued message used for tracking duplicate entries
|
1721
|
-
*/},{key:"requeue",value:function requeue(
|
1731
|
+
*/},{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||generateUUID()});}}},{key:"isBatchReadyToDispatch",value:function isBatchReadyToDispatch(batchItems){var _this$batch,_this$batch3;var lengthCriteriaMet=false;if(isDefined((_this$batch=this.batch)===null||_this$batch===void 0?void 0:_this$batch.maxItems)){var _this$batch2;lengthCriteriaMet=batchItems.length>=((_this$batch2=this.batch)===null||_this$batch2===void 0?void 0:_this$batch2.maxItems);}if(lengthCriteriaMet){return true;}var sizeCriteriaMet=false;if(isDefined((_this$batch3=this.batch)===null||_this$batch3===void 0?void 0:_this$batch3.maxSize)&&isDefined(this.queueBatchItemsSizeCalculatorCb)){var _this$batch4;var curBatchSize=this.queueBatchItemsSizeCalculatorCb(batchItems.map(function(queueItem){return queueItem.item;}));sizeCriteriaMet=curBatchSize>=((_this$batch4=this.batch)===null||_this$batch4===void 0?void 0:_this$batch4.maxSize);}return sizeCriteriaMet;}},{key:"processHead",value:function processHead(){var _ref3,_ref4,_this=this,_ref6;// cancel the scheduled task if it exists
|
1722
1732
|
this.schedule.cancel(this.processId);// Pop the head off the queue
|
1723
|
-
var queue=(
|
1724
|
-
var processItemCallback=function processItemCallback(el,id){return function(err,res){var
|
1733
|
+
var queue=(_ref3=this.getQueue(QueueStatuses.QUEUE))!==null&&_ref3!==void 0?_ref3:[];var inProgress=(_ref4=this.getQueue(QueueStatuses.IN_PROGRESS))!==null&&_ref4!==void 0?_ref4:{};var now=this.schedule.now();var toRun=[];// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
1734
|
+
var processItemCallback=function processItemCallback(el,id){return function(err,res){var _ref5;var inProgress=(_ref5=_this.getQueue(QueueStatuses.IN_PROGRESS))!==null&&_ref5!==void 0?_ref5:{};delete inProgress[id];_this.setQueue(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
|
1725
1735
|
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
|
1726
1736
|
inProgress[id]={item:el.item,attemptNumber:el.attemptNumber,time:this.schedule.now()};enqueueItem(el,id);}}this.setQueue(QueueStatuses.QUEUE,queue);this.setQueue(QueueStatuses.IN_PROGRESS,inProgress);toRun.forEach(function(el){// TODO: handle processQueueCb timeout
|
1727
|
-
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
|
1728
|
-
queue=(
|
1729
|
-
},{key:"ack",value:function ack(){this.setQueue(QueueStatuses.ACK,this.schedule.now());this.setQueue(QueueStatuses.RECLAIM_START,null);this.setQueue(QueueStatuses.RECLAIM_END,null);this.schedule.run(this.ack,this.timeouts.
|
1730
|
-
addConcatQueue(their.queue,0);//
|
1737
|
+
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
|
1738
|
+
queue=(_ref6=this.getQueue(QueueStatuses.QUEUE))!==null&&_ref6!==void 0?_ref6:[];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
|
1739
|
+
},{key:"ack",value:function ack(){this.setQueue(QueueStatuses.ACK,this.schedule.now());this.setQueue(QueueStatuses.RECLAIM_START,null);this.setQueue(QueueStatuses.RECLAIM_END,null);this.schedule.run(this.ack,this.timeouts.ackTimer,ScheduleModes.ASAP);}},{key:"reclaim",value:function reclaim(id){var _this$getQueue,_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$getQueue=this.getQueue(QueueStatuses.QUEUE))!==null&&_this$getQueue!==void 0?_this$getQueue:[]};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 id=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#
|
1740
|
+
addConcatQueue(their.queue,0);// Process batch queue items
|
1741
|
+
if(this.enableBatching){their.batchQueue.forEach(function(el){var id=el.id||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
|
1742
|
+
addConcatQueue(their.batchQueue,0);}// if the queue is abandoned, all the in-progress are failed. retry them immediately and increment the attempt#
|
1731
1743
|
addConcatQueue(their.inProgress,1);our.queue=our.queue.sort(sortByTime);this.setQueue(QueueStatuses.QUEUE,our.queue);// remove all keys one by on next tick to avoid NS_ERROR_STORAGE_BUSY error
|
1732
|
-
try{this.clearOtherQueue(other,1);}catch(e){var isLocalStorageBusy=e.name==='NS_ERROR_STORAGE_BUSY'||e.code==='NS_ERROR_STORAGE_BUSY'||e.code===0x80630001;if(isLocalStorageBusy){try{this.clearOtherQueue(other,40);}catch(retryError){
|
1744
|
+
try{this.clearOtherQueue(other,1);}catch(e){var isLocalStorageBusy=e.name==='NS_ERROR_STORAGE_BUSY'||e.code==='NS_ERROR_STORAGE_BUSY'||e.code===0x80630001;if(isLocalStorageBusy){try{this.clearOtherQueue(other,40);}catch(retryError){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(retryError);}}else {var _this$logger3;(_this$logger3=this.logger)===null||_this$logger3===void 0||_this$logger3.error(e);}}// process the new items we claimed
|
1733
1745
|
this.processHead();}// eslint-disable-next-line class-methods-use-this
|
1734
|
-
},{key:"clearOtherQueue",value:function clearOtherQueue(other,localStorageBackoff){globalThis.setTimeout(function(){other.remove(QueueStatuses.IN_PROGRESS);globalThis.setTimeout(function(){other.remove(QueueStatuses.QUEUE);globalThis.setTimeout(function(){other.remove(QueueStatuses.RECLAIM_START);globalThis.setTimeout(function(){other.remove(QueueStatuses.RECLAIM_END);globalThis.setTimeout(function(){other.remove(QueueStatuses.ACK);},localStorageBackoff);},localStorageBackoff);},localStorageBackoff);},localStorageBackoff);},localStorageBackoff);}},{key:"checkReclaim",value:function checkReclaim(){var _this3=this;var createReclaimStartTask=function createReclaimStartTask(store){return function(){if(store.get(QueueStatuses.RECLAIM_END)!==_this3.id){return;}if(store.get(QueueStatuses.RECLAIM_START)!==_this3.id){return;}_this3.reclaim(store.id);};};var createReclaimEndTask=function createReclaimEndTask(store){return function(){if(store.get(QueueStatuses.RECLAIM_START)!==_this3.id){return;}store.set(QueueStatuses.RECLAIM_END,_this3.id);_this3.schedule.run(createReclaimStartTask(store),_this3.timeouts.
|
1746
|
+
},{key:"clearOtherQueue",value:function clearOtherQueue(other,localStorageBackoff){globalThis.setTimeout(function(){other.remove(QueueStatuses.BATCH_QUEUE);globalThis.setTimeout(function(){other.remove(QueueStatuses.IN_PROGRESS);globalThis.setTimeout(function(){other.remove(QueueStatuses.QUEUE);globalThis.setTimeout(function(){other.remove(QueueStatuses.RECLAIM_START);globalThis.setTimeout(function(){other.remove(QueueStatuses.RECLAIM_END);globalThis.setTimeout(function(){other.remove(QueueStatuses.ACK);},localStorageBackoff);},localStorageBackoff);},localStorageBackoff);},localStorageBackoff);},localStorageBackoff);},localStorageBackoff);}},{key:"checkReclaim",value:function checkReclaim(){var _this3=this;var createReclaimStartTask=function createReclaimStartTask(store){return function(){if(store.get(QueueStatuses.RECLAIM_END)!==_this3.id){return;}if(store.get(QueueStatuses.RECLAIM_START)!==_this3.id){return;}_this3.reclaim(store.id);};};var createReclaimEndTask=function createReclaimEndTask(store){return function(){if(store.get(QueueStatuses.RECLAIM_START)!==_this3.id){return;}store.set(QueueStatuses.RECLAIM_END,_this3.id);_this3.schedule.run(createReclaimStartTask(store),_this3.timeouts.reclaimWait,ScheduleModes.ABANDON);};};var tryReclaim=function tryReclaim(store){store.set(QueueStatuses.RECLAIM_START,_this3.id);store.set(QueueStatuses.ACK,_this3.schedule.now());_this3.schedule.run(createReclaimEndTask(store),_this3.timeouts.reclaimWait,ScheduleModes.ABANDON);};var findOtherQueues=function findOtherQueues(name){var res=[];var storage=_this3.store.getOriginalEngine();for(var i=0;i<storage.length;i++){var k=storage.key(i);var parts=k?k.split('.'):[];if(parts.length!==3){// eslint-disable-next-line no-continue
|
1735
1747
|
continue;}if(parts[0]!==name){// eslint-disable-next-line no-continue
|
1736
1748
|
continue;}if(parts[2]!==QueueStatuses.ACK){// eslint-disable-next-line no-continue
|
1737
|
-
continue;}res.push(_this3.storeManager.setStore({id:parts[1],name:name,validKeys:QueueStatuses,type:LOCAL_STORAGE}));}return res;};findOtherQueues(this.name).forEach(function(store){if(store.id===_this3.id){return;}if(_this3.schedule.now()-store.get(QueueStatuses.ACK)<_this3.timeouts.
|
1749
|
+
continue;}res.push(_this3.storeManager.setStore({id:parts[1],name:name,validKeys:QueueStatuses,type:LOCAL_STORAGE}));}return res;};findOtherQueues(this.name).forEach(function(store){if(store.id===_this3.id){return;}if(_this3.schedule.now()-store.get(QueueStatuses.ACK)<_this3.timeouts.reclaimTimeout){return;}tryReclaim(store);});this.schedule.run(this.checkReclaim,this.timeouts.reclaimTimer,ScheduleModes.RESCHEDULE);}}]);return RetryQueue;}();
|
1738
1750
|
|
1739
1751
|
var DEFAULT_QUEUE_OPTIONS={maxItems:100};var QUEUE_NAME$1='rudder_destinations_events';var NATIVE_DESTINATION_QUEUE_PLUGIN='NativeDestinationQueuePlugin';
|
1740
1752
|
|
@@ -1742,7 +1754,7 @@ var getNormalizedQueueOptions$1=function getNormalizedQueueOptions(queueOpts){re
|
|
1742
1754
|
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
|
1743
1755
|
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
|
1744
1756
|
// This will remain until we update the destinations to accept the event directly
|
1745
|
-
(_dest$instance=dest.instance)===null||_dest$instance===void 0||(_dest$instance$method=_dest$instance[methodName])===null||_dest$instance$method===void 0
|
1757
|
+
(_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));}};
|
1746
1758
|
|
1747
1759
|
var pluginName$6='NativeDestinationQueue';var NativeDestinationQueue=function NativeDestinationQueue(){return {name:pluginName$6,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$6]);},destinationsEventsQueue:{/**
|
1748
1760
|
* Initialize the queue for delivery to destinations
|
@@ -1753,7 +1765,7 @@ var pluginName$6='NativeDestinationQueue';var NativeDestinationQueue=function Na
|
|
1753
1765
|
* @param logger Logger instance
|
1754
1766
|
* @returns IQueue instance
|
1755
1767
|
*/init:function init(state,pluginsManager,storeManager,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
|
1756
|
-
"".concat(QUEUE_NAME$1,"_").concat(writeKey),finalQOpts,function(rudderEvent,done){var destinationsToSend=filterDestinations(rudderEvent.integrations,state.nativeDestinations.initializedDestinations.value);destinationsToSend.forEach(function(dest){var clonedRudderEvent=clone$1(rudderEvent);var sendEvent=!isEventDenyListed(clonedRudderEvent.type,clonedRudderEvent.event,dest);if(!sendEvent){logger===null||logger===void 0
|
1768
|
+
"".concat(QUEUE_NAME$1,"_").concat(writeKey),finalQOpts,function(rudderEvent,done){var destinationsToSend=filterDestinations(rudderEvent.integrations,state.nativeDestinations.initializedDestinations.value);destinationsToSend.forEach(function(dest){var clonedRudderEvent=clone$1(rudderEvent);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){pluginsManager.invokeSingle('transformEvent.enqueue',state,clonedRudderEvent,dest,logger);}else {sendEventToDestination(clonedRudderEvent,dest,errorHandler);}});// Mark success always
|
1757
1769
|
done(null);},storeManager,MEMORY_STORAGE);// TODO: This seems to not work as expected. Need to investigate
|
1758
1770
|
// effect(() => {
|
1759
1771
|
// if (state.nativeDestinations.clientDestinationsReady.value === true) {
|
@@ -1779,7 +1791,7 @@ return eventsQueue;},/**
|
|
1779
1791
|
|
1780
1792
|
var ONETRUST_CONSENT_MANAGER_PLUGIN='OneTrustConsentManagerPlugin';
|
1781
1793
|
|
1782
|
-
var pluginName$5='OneTrustConsentManager';var OneTrustConsentManager=function OneTrustConsentManager(){return {name:pluginName$5,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$5]);},consentManager:{init:function init(state,storeManager,logger){if(!globalThis.OneTrust||!globalThis.OnetrustActiveGroups){logger===null||logger===void 0
|
1794
|
+
var pluginName$5='OneTrustConsentManager';var OneTrustConsentManager=function OneTrustConsentManager(){return {name:pluginName$5,deps:[],initialize:function initialize(state){state.plugins.loadedPlugins.value=[].concat(_toConsumableArray(state.plugins.loadedPlugins.value),[pluginName$5]);},consentManager:{init:function init(state,storeManager,logger){if(!globalThis.OneTrust||!globalThis.OnetrustActiveGroups){logger===null||logger===void 0||logger.error(ONETRUST_ACCESS_ERROR(ONETRUST_CONSENT_MANAGER_PLUGIN));state.consents.data.value={initialized:false};return;}// OneTrustConsentManager SDK populates a data layer object OnetrustActiveGroups with
|
1783
1795
|
// the cookie categories Ids that the user has consented to.
|
1784
1796
|
// Eg: ',C0001,C0003,'
|
1785
1797
|
// We split it and save it as an array.
|
@@ -1790,7 +1802,7 @@ if(!oneTrustCookieCategories){return true;}// Change the structure of oneTrustCo
|
|
1790
1802
|
// Eg:
|
1791
1803
|
// ["Performance Cookies", "Functional Cookies"]
|
1792
1804
|
var validOneTrustCookieCategories=oneTrustCookieCategories.map(function(c){return c.oneTrustCookieCategory;}).filter(function(n){return n;});var containsAllConsent=true;// Check if all the destination's mapped cookie categories are consented by the user in the browser.
|
1793
|
-
containsAllConsent=validOneTrustCookieCategories.every(function(element){return Object.keys(allowedConsents).includes(element.trim())||Object.values(allowedConsents).includes(element.trim());});return containsAllConsent;}catch(err){errorHandler===null||errorHandler===void 0
|
1805
|
+
containsAllConsent=validOneTrustCookieCategories.every(function(element){return Object.keys(allowedConsents).includes(element.trim())||Object.values(allowedConsents).includes(element.trim());});return containsAllConsent;}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,ONETRUST_CONSENT_MANAGER_PLUGIN,DESTINATION_CONSENT_STATUS_ERROR);return true;}}}};};
|
1794
1806
|
|
1795
1807
|
var KETCH_CONSENT_MANAGER_PLUGIN='KetchConsentManagerPlugin';var KETCH_CONSENT_COOKIE_NAME_V1='_ketch_consent_v1_';
|
1796
1808
|
|
@@ -1800,8 +1812,8 @@ var KETCH_CONSENT_MANAGER_PLUGIN='KetchConsentManagerPlugin';var KETCH_CONSENT_C
|
|
1800
1812
|
* @param logger Logger instance
|
1801
1813
|
* @returns Consent data from the consent cookie
|
1802
1814
|
*/var getKetchConsentData=function getKetchConsentData(storeManager,logger){var rawConsentCookieData=null;try{// Create a data store instance to read the consent cookie
|
1803
|
-
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
|
1804
|
-
var consentCookieData;try{consentCookieData=JSON.parse(fromBase64(rawConsentCookieData));}catch(err){logger===null||logger===void 0
|
1815
|
+
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
|
1816
|
+
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
|
1805
1817
|
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;};/**
|
1806
1818
|
* Gets the consent data in the format expected by the application state
|
1807
1819
|
* @param ketchConsentData Consent data derived from the consent cookie
|
@@ -1817,7 +1829,7 @@ globalThis.getKetchUserDeniedPurposes=function(){var _state$consents$data$2;retu
|
|
1817
1829
|
globalThis.updateKetchConsent=function(ketchConsentData){updateConsentStateFromData(state,ketchConsentData);};// retrieve consent data and update the state
|
1818
1830
|
var ketchConsentData;if(!isUndefined(globalThis.ketchConsent)){ketchConsentData=globalThis.ketchConsent;}else {ketchConsentData=getKetchConsentData(storeManager,logger);}updateConsentStateFromData(state,ketchConsentData);},isDestinationConsented:function isDestinationConsented(state,destConfig,errorHandler,logger){var consentData=state.consents.data.value;if(!consentData.initialized){return true;}var allowedConsents=consentData.allowedConsents;try{var ketchConsentPurposes=destConfig.ketchConsentPurposes;// If the destination do not have this mapping events will be sent.
|
1819
1831
|
if(!ketchConsentPurposes||ketchConsentPurposes.length===0){return true;}var purposes=ketchConsentPurposes.map(function(p){return p.purpose;}).filter(function(n){return n;});// Check if any of the destination's mapped ketch purposes are consented by the user in the browser.
|
1820
|
-
var containsAnyOfConsent=purposes.some(function(element){return allowedConsents.includes(element.trim());});return containsAnyOfConsent;}catch(err){errorHandler===null||errorHandler===void 0
|
1832
|
+
var containsAnyOfConsent=purposes.some(function(element){return allowedConsents.includes(element.trim());});return containsAnyOfConsent;}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,KETCH_CONSENT_MANAGER_PLUGIN,DESTINATION_CONSENT_STATUS_ERROR);return true;}}}};};
|
1821
1833
|
|
1822
1834
|
var ENCRYPTION_PREFIX_V3='RS_ENC_v3_';
|
1823
1835
|
|
@@ -2991,7 +3003,7 @@ var STORAGE_MIGRATOR_PLUGIN='StorageMigratorPlugin';
|
|
2991
3003
|
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
|
2992
3004
|
// Try latest
|
2993
3005
|
if(decryptedVal===storedVal){decryptedVal=decrypt$1(storedVal);}if(isNullOrUndefined(decryptedVal)){return null;}// storejs that is used in localstorage engine already deserializes json strings but swallows errors
|
2994
|
-
return JSON.parse(decryptedVal);}catch(err){errorHandler===null||errorHandler===void 0
|
3006
|
+
return JSON.parse(decryptedVal);}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,STORAGE_MIGRATOR_PLUGIN,STORAGE_MIGRATION_ERROR(key));return null;}}}};};
|
2995
3007
|
|
2996
3008
|
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
|
2997
3009
|
isRetryableNWFailure=xhrStatus===429||xhrStatus>=500&&xhrStatus<600;}return isRetryableNWFailure;};
|
@@ -2999,7 +3011,7 @@ isRetryableNWFailure=xhrStatus===429||xhrStatus>=500&&xhrStatus<600;}return isRe
|
|
2999
3011
|
var DEFAULT_RETRY_QUEUE_OPTIONS={maxRetryDelay:360000,minRetryDelay:1000,backoffFactor:2,maxAttempts:10,maxItems:100};var REQUEST_TIMEOUT_MS=10*1000;// 10 seconds
|
3000
3012
|
var DATA_PLANE_API_VERSION='v1';var QUEUE_NAME='rudder';var XHR_QUEUE_PLUGIN='XhrQueuePlugin';
|
3001
3013
|
|
3002
|
-
var getNormalizedQueueOptions=function getNormalizedQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_RETRY_QUEUE_OPTIONS,queueOpts);};var getDeliveryUrl=function getDeliveryUrl(dataplaneUrl,
|
3014
|
+
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;if(Array.isArray(itemData)){var finalEvents=itemData.map(function(queueItemData){return getFinalEventForDeliveryMutator(queueItemData.event,state);});data=getBatchDeliveryPayload(finalEvents,logger);headers=_objectSpread2({},itemData[0].headers);url=getBatchDeliveryUrl(state.lifecycle.activeDataplaneUrl.value);}else {var eventUrl=itemData.url,event=itemData.event,eventHeaders=itemData.headers;var finalEvent=getFinalEventForDeliveryMutator(event,state);data=getDeliveryPayload$1(finalEvent,logger);headers=_objectSpread2({},eventHeaders);url=eventUrl;}return {data:data,headers:headers,url:url};};
|
3003
3015
|
|
3004
3016
|
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:{/**
|
3005
3017
|
* Initialize the queue for delivery
|
@@ -3010,9 +3022,8 @@ var pluginName='XhrQueue';var XhrQueue=function XhrQueue(){return {name:pluginNa
|
|
3010
3022
|
* @param logger Logger instance
|
3011
3023
|
* @returns RetryQueue instance
|
3012
3024
|
*/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
|
3013
|
-
"".concat(QUEUE_NAME,"_").concat(writeKey),finalQOpts,function(
|
3014
|
-
var queueErrResp=isErrRetryable(details)?details:null;logErrorOnFailure(details,
|
3015
|
-
done(null);}},storeManager);return eventsQueue;},/**
|
3025
|
+
"".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
|
3026
|
+
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 events=itemData.map(function(queueItemData){return queueItemData.event;});return (_getBatchDeliveryPayl=getBatchDeliveryPayload(events,logger))===null||_getBatchDeliveryPayl===void 0?void 0:_getBatchDeliveryPayl.length;});return eventsQueue;},/**
|
3016
3027
|
* Add event to the queue for delivery
|
3017
3028
|
* @param state Application state
|
3018
3029
|
* @param eventsQueue RetryQueue instance
|
@@ -3056,7 +3067,7 @@ state.lifecycle.status.value=LifecycleStatus.PluginsReady;});}});}/**
|
|
3056
3067
|
},{key:"getPluginsToLoadBasedOnConfig",value:function getPluginsToLoadBasedOnConfig(){var _state$nativeDestinat;// This contains the default plugins if load option has been omitted by user
|
3057
3068
|
var pluginsToLoadFromConfig=state.plugins.pluginsToLoadFromConfig.value;if(!pluginsToLoadFromConfig){return [];}// Error reporting related plugins
|
3058
3069
|
var supportedErrReportingProviderPluginNames=Object.values(ErrorReportingProvidersToPluginNameMap);if(state.reporting.errorReportingProviderPluginName.value){pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return !(pluginName!==state.reporting.errorReportingProviderPluginName.value&&supportedErrReportingProviderPluginNames.includes(pluginName));});}else {pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return !(pluginName===PluginName.ErrorReporting||supportedErrReportingProviderPluginNames.includes(pluginName));});}// dataplane events delivery plugins
|
3059
|
-
if(state.loadOptions.value.useBeacon===true&&state.capabilities.isBeaconAvailable.value){pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return pluginName!==PluginName.XhrQueue;});}else {if(state.loadOptions.value.useBeacon===true){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0
|
3070
|
+
if(state.loadOptions.value.useBeacon===true&&state.capabilities.isBeaconAvailable.value){pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return pluginName!==PluginName.XhrQueue;});}else {if(state.loadOptions.value.useBeacon===true){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0||_this$logger.warn(UNSUPPORTED_BEACON_API_WARNING(PLUGINS_MANAGER));}pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return pluginName!==PluginName.BeaconQueue;});}// Device mode destinations related plugins
|
3060
3071
|
if(getNonCloudDestinations((_state$nativeDestinat=state.nativeDestinations.configuredDestinations.value)!==null&&_state$nativeDestinat!==void 0?_state$nativeDestinat:[]).length===0){pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return ![PluginName.DeviceModeDestinations,PluginName.DeviceModeTransformation,PluginName.NativeDestinationQueue].includes(pluginName);});}// Consent Management related plugins
|
3061
3072
|
var supportedConsentManagerPlugins=Object.values(ConsentManagersToPluginNameMap);pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return !(pluginName!==state.consents.activeConsentManagerPluginName.value&&supportedConsentManagerPlugins.includes(pluginName));});// Storage encryption related plugins
|
3062
3073
|
var supportedStorageEncryptionPlugins=Object.values(StorageEncryptionVersionsToPluginNameMap);pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return !(pluginName!==state.storage.encryptionPluginName.value&&supportedStorageEncryptionPlugins.includes(pluginName));});// Storage migrator related plugins
|
@@ -3103,7 +3114,7 @@ xhr.timeout=timeout;Object.keys(options.headers).forEach(function(headerName){if
|
|
3103
3114
|
* Implement requests in a non-blocking way
|
3104
3115
|
*/},{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=!(callback&&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);}});}/**
|
3105
3116
|
* Handle errors
|
3106
|
-
*/},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0
|
3117
|
+
*/},{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;}}/**
|
3107
3118
|
* Set basic authentication header (eg writekey)
|
3108
3119
|
*/},{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);}/**
|
3109
3120
|
* Clear basic authentication header
|
@@ -3123,7 +3134,7 @@ state.capabilities.isAdBlocked.value=(details===null||details===void 0?void 0:de
|
|
3123
3134
|
|
3124
3135
|
var hasCrypto=function hasCrypto(){return !isNullOrUndefined(globalThis.crypto)&&isFunction(globalThis.crypto.getRandomValues);};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\./));};
|
3125
3136
|
|
3126
|
-
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
|
3137
|
+
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();});}};
|
3127
3138
|
|
3128
3139
|
var isDatasetAvailable=function isDatasetAvailable(){var testElement=document.createElement('div');testElement.setAttribute('data-a-b','c');return testElement.dataset?testElement.dataset.aB==='c':false;};var legacyJSEngineRequiredPolyfills={URLSearchParams:function URLSearchParams(){return !globalThis.URLSearchParams;},URL:function URL(){return !isFunction(globalThis.URL);},MutationObserver:function(_MutationObserver){function MutationObserver(){return _MutationObserver.apply(this,arguments);}MutationObserver.toString=function(){return _MutationObserver.toString();};return MutationObserver;}(function(){return isUndefined(MutationObserver);}),Promise:function(_Promise){function Promise(){return _Promise.apply(this,arguments);}Promise.toString=function(){return _Promise.toString();};return Promise;}(function(){return isUndefined(Promise);}),'Number.isNaN':function NumberIsNaN(){return !Number.isNaN;},'Number.isInteger':function NumberIsInteger(){return !Number.isInteger;},'Array.from':function ArrayFrom(){return !Array.from;},'Array.prototype.find':function ArrayPrototypeFind(){return !Array.prototype.find;},'Array.prototype.includes':function ArrayPrototypeIncludes(){return !Array.prototype.includes;},'String.prototype.endsWith':function StringPrototypeEndsWith(){return !String.prototype.endsWith;},'String.prototype.startsWith':function StringPrototypeStartsWith(){return !String.prototype.startsWith;},'String.prototype.includes':function StringPrototypeIncludes(){return !String.prototype.includes;},'Object.entries':function ObjectEntries(){return !Object.entries;},'Object.values':function ObjectValues(){return !Object.values;},'Element.prototype.dataset':function ElementPrototypeDataset(){return !isDatasetAvailable();},'String.prototype.replaceAll':function StringPrototypeReplaceAll(){return !String.prototype.replaceAll;},TextEncoder:function(_TextEncoder){function TextEncoder(){return _TextEncoder.apply(this,arguments);}TextEncoder.toString=function(){return _TextEncoder.toString();};return TextEncoder;}(function(){return isUndefined(TextEncoder);}),TextDecoder:function(_TextDecoder){function TextDecoder(){return _TextDecoder.apply(this,arguments);}TextDecoder.toString=function(){return _TextDecoder.toString();};return TextDecoder;}(function(){return isUndefined(TextDecoder);}),'String.fromCodePoint':function StringFromCodePoint(){return !String.fromCodePoint;},requestAnimationFrame:function requestAnimationFrame(){return !isFunction(globalThis.requestAnimationFrame);},cancelAnimationFrame:function cancelAnimationFrame(){return !isFunction(globalThis.cancelAnimationFrame);},CustomEvent:function CustomEvent(){return !isFunction(globalThis.CustomEvent);}};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(isCapabilityMissing()){needsPolyfill=true;break;}}return needsPolyfill;};
|
3129
3140
|
|
@@ -3134,24 +3145,26 @@ var matchingCodes=[22,1014];// [everything except Firefox, Firefox]
|
|
3134
3145
|
var isQuotaExceededError=matchingNames.includes(e.name)||matchingCodes.includes(e.code);return e instanceof DOMException&&isQuotaExceededError;};// TODO: also check for SecurityErrors
|
3135
3146
|
// https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage#exceptions
|
3136
3147
|
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
|
3137
|
-
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
|
3148
|
+
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.error("".concat(msgPrefix).concat(reason,"."),err);return false;}};
|
3138
3149
|
|
3139
3150
|
/**
|
3140
3151
|
* Encode.
|
3141
|
-
*/var encode=function encode(value){return encodeURIComponent(value);};/**
|
3152
|
+
*/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;}};/**
|
3142
3153
|
* Decode
|
3143
|
-
*/var decode=function decode(value){return decodeURIComponent(value);}
|
3154
|
+
*/var decode=function decode(value){try{return decodeURIComponent(value);}catch(err){// Do nothing as non-RS SDK cookies may not be URI encoded
|
3155
|
+
return undefined;}};/**
|
3144
3156
|
* Parse cookie `str`
|
3145
|
-
*/var parse=function parse(str){var obj={};var pairs=str.split(/\s*;\s*/);var pair;if(!pairs[0]){return obj;}
|
3157
|
+
*/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
|
3158
|
+
pairs.forEach(function(pairItem){pair=pairItem.split('=');var keyName=decode(pair[0]);if(keyName){obj[keyName]=decode(pair[1]);}});return obj;};/**
|
3146
3159
|
* Set cookie `name` to `value`
|
3147
|
-
*/var set=function set(name,value,optionsConfig){var options=_objectSpread2({},optionsConfig)||{};var cookieString="".concat(encode(name),"=").concat(encode(value));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;};/**
|
3160
|
+
*/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;};/**
|
3148
3161
|
* Return all cookies
|
3149
3162
|
*/var all=function all(){var cookieStringValue=globalThis.document.cookie;return parse(cookieStringValue);};/**
|
3150
3163
|
* Get cookie `name`
|
3151
3164
|
*/var get=function get(name){return all()[name];};/**
|
3152
3165
|
* Set or get cookie `name` with `value` and `options` object
|
3153
3166
|
*/ // eslint-disable-next-line func-names
|
3154
|
-
var cookie=function cookie(name,value,options){switch(arguments.length){case 3:case 2:return set(name,value,options);case 1:if(name){return get(name);}return all();default:return all();}};
|
3167
|
+
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();}};
|
3155
3168
|
|
3156
3169
|
var legacyGetHostname=function legacyGetHostname(href){var l=document.createElement('a');l.href=href;return l.hostname;};/**
|
3157
3170
|
* Levels returns all levels of the given url
|
@@ -3181,7 +3194,7 @@ var getDefaultCookieOptions=function getDefaultCookieOptions(){var topDomain=dom
|
|
3181
3194
|
/**
|
3182
3195
|
* A storage utility to persist values in cookies via Storage interface
|
3183
3196
|
*/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
|
3184
|
-
return CookieStorage.globalSingleton;}this.options=getDefaultCookieOptions();this.logger=logger;this.configure(options);CookieStorage.globalSingleton=this;}_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);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.length=Object.keys(cookie()).length;return true;}// eslint-disable-next-line class-methods-use-this
|
3197
|
+
return CookieStorage.globalSingleton;}this.options=getDefaultCookieOptions();this.logger=logger;this.configure(options);CookieStorage.globalSingleton=this;}_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);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
|
3185
3198
|
},{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
|
3186
3199
|
},{key:"clear",value:function clear(){// Not implemented
|
3187
3200
|
// getting a list of all cookie storage keys and remove all values
|
@@ -3239,7 +3252,7 @@ Object.keys(validKeys).forEach(function(key){var value=_this.get(validKeys[key])
|
|
3239
3252
|
_this.remove(key);});this.engine=inMemoryStorage;}/**
|
3240
3253
|
* Set value by key.
|
3241
3254
|
*/},{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
|
3242
|
-
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
|
3255
|
+
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
|
3243
3256
|
this.swapQueueStoreToInMemoryEngine();// and save it there
|
3244
3257
|
this.set(key,value);}else {this.onError(getMutatedError(err,STORE_DATA_SAVE_ERROR(key)));}}}/**
|
3245
3258
|
* Get by Key.
|
@@ -3256,7 +3269,7 @@ return JSON.parse(str);}catch(err){this.onError(new Error("".concat(STORE_DATA_F
|
|
3256
3269
|
* Extension point to use with encryption plugins
|
3257
3270
|
*/},{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:'';}/**
|
3258
3271
|
* Handle errors
|
3259
|
-
*/},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0
|
3272
|
+
*/},{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;}}}]);return Store;}();
|
3260
3273
|
|
3261
3274
|
/**
|
3262
3275
|
* A service to manage stores & available storage client configurations
|
@@ -3265,7 +3278,7 @@ return JSON.parse(str);}catch(err){this.onError(new Error("".concat(STORE_DATA_F
|
|
3265
3278
|
*/_createClass(StoreManager,[{key:"init",value:function init(){if(this.isInitialized){return;}var config={cookieOptions:{samesite:state.loadOptions.value.sameSiteCookie,secure:state.loadOptions.value.secureCookie,domain:state.loadOptions.value.setCookieDomain,enabled:true},localStorageOptions:{enabled:true},inMemoryStorageOptions:{enabled:true}};configureStorageEngines(removeUndefinedValues(config.cookieOptions),removeUndefinedValues(config.localStorageOptions),removeUndefinedValues(config.inMemoryStorageOptions));this.initClientDataStore();this.isInitialized=true;}/**
|
3266
3279
|
* Create store to persist data used by the SDK like session, used details etc
|
3267
3280
|
*/},{key:"initClientDataStore",value:function initClientDataStore(){var _getStorageEngine,_getStorageEngine2,_getStorageEngine3;var storageType=state.storage.type.value||COOKIE_STORAGE;var finalStorageType=storageType;switch(storageType){case LOCAL_STORAGE:if(!((_getStorageEngine=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine!==void 0&&_getStorageEngine.isEnabled)){finalStorageType=MEMORY_STORAGE;}break;case MEMORY_STORAGE:finalStorageType=MEMORY_STORAGE;break;case NO_STORAGE:finalStorageType=NO_STORAGE;break;case COOKIE_STORAGE:default:// First try setting the storage to cookie else to local storage
|
3268
|
-
if((_getStorageEngine2=getStorageEngine(COOKIE_STORAGE))!==null&&_getStorageEngine2!==void 0&&_getStorageEngine2.isEnabled){finalStorageType=COOKIE_STORAGE;}else if((_getStorageEngine3=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine3!==void 0&&_getStorageEngine3.isEnabled){finalStorageType=LOCAL_STORAGE;}else {finalStorageType=MEMORY_STORAGE;}break;}if(finalStorageType!==storageType){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0
|
3281
|
+
if((_getStorageEngine2=getStorageEngine(COOKIE_STORAGE))!==null&&_getStorageEngine2!==void 0&&_getStorageEngine2.isEnabled){finalStorageType=COOKIE_STORAGE;}else if((_getStorageEngine3=getStorageEngine(LOCAL_STORAGE))!==null&&_getStorageEngine3!==void 0&&_getStorageEngine3.isEnabled){finalStorageType=LOCAL_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,storageType,finalStorageType));}// TODO: fill in extra config values and bring them in from StoreManagerOptions if needed
|
3269
3282
|
// TODO: should we pass the keys for all in order to validate or leave free as v1.1?
|
3270
3283
|
if(finalStorageType!==NO_STORAGE){this.setStore({id:CLIENT_DATA_STORE_NAME,name:CLIENT_DATA_STORE_NAME,isEncrypted:true,noCompoundKey:true,type:finalStorageType});}}/**
|
3271
3284
|
* Create a new store
|
@@ -3273,7 +3286,7 @@ if(finalStorageType!==NO_STORAGE){this.setStore({id:CLIENT_DATA_STORE_NAME,name:
|
|
3273
3286
|
* Retrieve a store
|
3274
3287
|
*/},{key:"getStore",value:function getStore(id){return this.stores[id];}/**
|
3275
3288
|
* Handle errors
|
3276
|
-
*/},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0
|
3289
|
+
*/},{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;}}}]);return StoreManager;}();
|
3277
3290
|
|
3278
3291
|
/**
|
3279
3292
|
* Removes trailing slash from url
|
@@ -3321,7 +3334,10 @@ var defaultOptionalPluginsList=[PluginName.Bugsnag,PluginName.DeviceModeDestinat
|
|
3321
3334
|
*/var isPositiveInteger=function isPositiveInteger(num){return isNumber(num)&&num>=0&&Number.isInteger(num);};
|
3322
3335
|
|
3323
3336
|
var normalizeLoadOptions=function normalizeLoadOptions(loadOptionsFromState,loadOptions){var _normalizedLoadOpts$p;// TODO: Maybe add warnings for invalid values
|
3324
|
-
var normalizedLoadOpts=clone$1(loadOptions);if(!isString(normalizedLoadOpts.setCookieDomain)){delete normalizedLoadOpts.setCookieDomain;}if(!getObjectValues(CookieSameSite).includes(normalizedLoadOpts.sameSiteCookie)){delete normalizedLoadOpts.sameSiteCookie;}normalizedLoadOpts.secureCookie=normalizedLoadOpts.secureCookie===true;if(!getObjectValues(UaChTrackLevel).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;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;if(!isNumber(normalizedLoadOpts.dataPlaneEventsBufferTimeout)){delete normalizedLoadOpts.dataPlaneEventsBufferTimeout;}var mergedLoadOptions=mergeDeepRight(loadOptionsFromState,normalizedLoadOpts);return mergedLoadOptions;};var getSourceConfigURL=function getSourceConfigURL(configUrl,writeKey,lockIntegrationsVersion,logger){var defSearchParams=new URLSearchParams({p:MODULE_TYPE,v:APP_VERSION,build:BUILD_TYPE,writeKey:writeKey,lockIntegrationsVersion:lockIntegrationsVersion.toString()});var origin=DEFAULT_CONFIG_BE_URL;var searchParams=defSearchParams;var pathname='/sourceConfig/';var hash=''
|
3337
|
+
var normalizedLoadOpts=clone$1(loadOptions);if(!isString(normalizedLoadOpts.setCookieDomain)){delete normalizedLoadOpts.setCookieDomain;}if(!getObjectValues(CookieSameSite).includes(normalizedLoadOpts.sameSiteCookie)){delete normalizedLoadOpts.sameSiteCookie;}normalizedLoadOpts.secureCookie=normalizedLoadOpts.secureCookie===true;if(!getObjectValues(UaChTrackLevel).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;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;if(!isNumber(normalizedLoadOpts.dataPlaneEventsBufferTimeout)){delete normalizedLoadOpts.dataPlaneEventsBufferTimeout;}var mergedLoadOptions=mergeDeepRight(loadOptionsFromState,normalizedLoadOpts);return mergedLoadOptions;};var getSourceConfigURL=function getSourceConfigURL(configUrl,writeKey,lockIntegrationsVersion,logger){var defSearchParams=new URLSearchParams({p:MODULE_TYPE,v:APP_VERSION,build:BUILD_TYPE,writeKey:writeKey,lockIntegrationsVersion:lockIntegrationsVersion.toString()});var origin=DEFAULT_CONFIG_BE_URL;var searchParams=defSearchParams;var pathname='/sourceConfig/';var hash='';// Ideally, this check is not required but URL polyfill
|
3338
|
+
// doesn't seem to throw errors for empty URLs
|
3339
|
+
// TODO: Need to improve this check to find out if the URL is valid or not
|
3340
|
+
if(configUrl){try{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;}catch(err){logger===null||logger===void 0||logger.warn(INVALID_CONFIG_URL_WARNING(CONFIG_MANAGER,configUrl));}}return "".concat(origin).concat(pathname,"?").concat(searchParams).concat(hash);};
|
3325
3341
|
|
3326
3342
|
/**
|
3327
3343
|
* A function to filter enabled destinations and map to required properties only
|
@@ -3334,7 +3350,7 @@ var DEFAULT_REGION='US';/**
|
|
3334
3350
|
* A function to get url from source config response
|
3335
3351
|
* @param {array} urls An array of objects containing urls
|
3336
3352
|
* @returns
|
3337
|
-
*/var getDefaultUrlOfRegion=function getDefaultUrlOfRegion(urls){var url;if(Array.isArray(urls)&&urls.length>0){var obj=urls.find(function(elem){return elem.default===true;});if(obj&&isValidUrl(obj.url)){return obj.url;}}return url;};var validateResidencyServerRegion=function validateResidencyServerRegion(residencyServerRegion,logger){if(residencyServerRegion&&!Object.values(ResidencyServerRegion).includes(residencyServerRegion)){logger===null||logger===void 0
|
3353
|
+
*/var getDefaultUrlOfRegion=function getDefaultUrlOfRegion(urls){var url;if(Array.isArray(urls)&&urls.length>0){var obj=urls.find(function(elem){return elem.default===true;});if(obj&&isValidUrl(obj.url)){return obj.url;}}return url;};var validateResidencyServerRegion=function validateResidencyServerRegion(residencyServerRegion,logger){if(residencyServerRegion&&!Object.values(ResidencyServerRegion).includes(residencyServerRegion)){logger===null||logger===void 0||logger.warn(UNSUPPORTED_RESIDENCY_SERVER_REGION_WARNING(CONFIG_MANAGER,residencyServerRegion,DEFAULT_REGION));return undefined;}return residencyServerRegion;};/**
|
3338
3354
|
* A function to determine the dataPlaneUrl
|
3339
3355
|
* @param {Object} dataplanes An object containing dataPlaneUrl for different region
|
3340
3356
|
* @param {String} serverUrl dataPlaneUrl provided in the load call
|
@@ -3358,9 +3374,9 @@ return sdkURL;};/**
|
|
3358
3374
|
* @param logger Logger instance
|
3359
3375
|
*/var updateReportingState=function updateReportingState(res,logger){state.reporting.isErrorReportingEnabled.value=isErrorReportingEnabled(res.source.config);state.reporting.isMetricsReportingEnabled.value=isMetricsReportingEnabled(res.source.config);if(state.reporting.isErrorReportingEnabled.value){var errReportingProvider=getErrorReportingProviderNameFromConfig(res.source.config);// Get the corresponding plugin name of the selected error reporting provider from the supported error reporting providers
|
3360
3376
|
var errReportingProviderPlugin=errReportingProvider?ErrorReportingProvidersToPluginNameMap[errReportingProvider]:undefined;if(!isUndefined(errReportingProvider)&&!errReportingProviderPlugin){// set the default error reporting provider
|
3361
|
-
logger===null||logger===void 0
|
3362
|
-
logger===null||logger===void 0
|
3363
|
-
var configuredMigrationValue=(_state$loadOptions$va2=state.loadOptions.value.storage)===null||_state$loadOptions$va2===void 0?void 0:_state$loadOptions$va2.migrate;state.storage.migrate.value=configuredMigrationValue&&storageEncryptionVersion===DEFAULT_STORAGE_ENCRYPTION_VERSION;if(configuredMigrationValue===true&&state.storage.migrate.value!==configuredMigrationValue){logger===null||logger===void 0
|
3377
|
+
logger===null||logger===void 0||logger.warn(UNSUPPORTED_ERROR_REPORTING_PROVIDER_WARNING(CONFIG_MANAGER,errReportingProvider,ErrorReportingProvidersToPluginNameMap,DEFAULT_ERROR_REPORTING_PROVIDER));}state.reporting.errorReportingProviderPluginName.value=errReportingProviderPlugin!==null&&errReportingProviderPlugin!==void 0?errReportingProviderPlugin:ErrorReportingProvidersToPluginNameMap[DEFAULT_ERROR_REPORTING_PROVIDER];}};var updateStorageState=function updateStorageState(logger){var _state$loadOptions$va;var storageEncryptionVersion=(_state$loadOptions$va=state.loadOptions.value.storage)===null||_state$loadOptions$va===void 0||(_state$loadOptions$va=_state$loadOptions$va.encryption)===null||_state$loadOptions$va===void 0?void 0:_state$loadOptions$va.version;var encryptionPluginName=storageEncryptionVersion&&StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];if(!isUndefined(storageEncryptionVersion)&&isUndefined(encryptionPluginName)){// set the default encryption plugin
|
3378
|
+
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;}o(function(){var _state$loadOptions$va2;state.storage.encryptionPluginName.value=StorageEncryptionVersionsToPluginNameMap[storageEncryptionVersion];// Allow migration only if the configured encryption version is the default encryption version
|
3379
|
+
var configuredMigrationValue=(_state$loadOptions$va2=state.loadOptions.value.storage)===null||_state$loadOptions$va2===void 0?void 0:_state$loadOptions$va2.migrate;state.storage.migrate.value=configuredMigrationValue&&storageEncryptionVersion===DEFAULT_STORAGE_ENCRYPTION_VERSION;if(configuredMigrationValue===true&&state.storage.migrate.value!==configuredMigrationValue){logger===null||logger===void 0||logger.warn(STORAGE_DATA_MIGRATION_OVERRIDE_WARNING(CONFIG_MANAGER,storageEncryptionVersion,DEFAULT_STORAGE_ENCRYPTION_VERSION));}});};
|
3364
3380
|
|
3365
3381
|
/**
|
3366
3382
|
* A function that determines integration SDK loading path
|
@@ -3393,19 +3409,19 @@ var sdkURL=getSDKUrl();pluginsCDNPath=sdkURL&&isString(sdkURL)?sdkURL.split('/')
|
|
3393
3409
|
* Output: 'oneTrust'
|
3394
3410
|
*/var getUserSelectedConsentManager=function getUserSelectedConsentManager(cookieConsentOptions){if(!isNonEmptyObject(cookieConsentOptions)){return undefined;}var validCookieConsentOptions=cookieConsentOptions;return Object.keys(validCookieConsentOptions).find(function(e){return e&&validCookieConsentOptions[e].enabled===true;});};
|
3395
3411
|
|
3396
|
-
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);}_createClass(ConfigManager,[{key:"attachEffects",value:function attachEffects(){var _this=this;b(function(){var _this$logger;(_this$logger=_this.logger)===null||_this$logger===void 0
|
3412
|
+
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);}_createClass(ConfigManager,[{key:"attachEffects",value:function attachEffects(){var _this=this;b(function(){var _this$logger;(_this$logger=_this.logger)===null||_this$logger===void 0||_this$logger.setMinLogLevel(state.lifecycle.logLevel.value);});}/**
|
3397
3413
|
* A function to validate, construct and store loadOption, lifecycle, source and destination
|
3398
3414
|
* config related information in global state
|
3399
3415
|
*/},{key:"init",value:function init(){var _this2=this;var consentManagerPluginName;this.attachEffects();var lockIntegrationsVersion=state.loadOptions.value.lockIntegrationsVersion;validateLoadArgs(state.lifecycle.writeKey.value,state.lifecycle.dataPlaneUrl.value);// determine the path to fetch integration SDK from
|
3400
3416
|
var intgCdnUrl=getIntegrationsCDNPath(APP_VERSION,lockIntegrationsVersion,state.loadOptions.value.destSDKBaseURL);// determine the path to fetch remote plugins from
|
3401
3417
|
var pluginsCDNPath=getPluginsCDNPath(state.loadOptions.value.pluginsSDKBaseURL);// Get the consent manager if provided as load option
|
3402
3418
|
var selectedConsentManager=getUserSelectedConsentManager(state.loadOptions.value.cookieConsentManager);if(selectedConsentManager){// Get the corresponding plugin name of the selected consent manager from the supported consent managers
|
3403
|
-
consentManagerPluginName=ConsentManagersToPluginNameMap[selectedConsentManager];if(!consentManagerPluginName){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0
|
3404
|
-
o(function(){var _state$loadOptions$va;state.lifecycle.integrationsCDNPath.value=intgCdnUrl;state.lifecycle.pluginsCDNPath.value=pluginsCDNPath;if(state.loadOptions.value.logLevel){state.lifecycle.logLevel.value=state.loadOptions.value.logLevel;}
|
3419
|
+
consentManagerPluginName=ConsentManagersToPluginNameMap[selectedConsentManager];if(!consentManagerPluginName){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.error(UNSUPPORTED_CONSENT_MANAGER_ERROR(CONFIG_MANAGER,selectedConsentManager,ConsentManagersToPluginNameMap));}}updateStorageState(this.logger);// set application lifecycle state in global state
|
3420
|
+
o(function(){var _state$loadOptions$va;state.lifecycle.integrationsCDNPath.value=intgCdnUrl;state.lifecycle.pluginsCDNPath.value=pluginsCDNPath;if(state.loadOptions.value.logLevel){state.lifecycle.logLevel.value=state.loadOptions.value.logLevel;}state.lifecycle.sourceConfigUrl.value=getSourceConfigURL(state.loadOptions.value.configUrl,state.lifecycle.writeKey.value,lockIntegrationsVersion,_this2.logger);// Set consent manager plugin name in state
|
3405
3421
|
state.consents.activeConsentManagerPluginName.value=consentManagerPluginName;// set storage type in state
|
3406
|
-
var storageType=(_state$loadOptions$va=state.loadOptions.value.storage)===null||_state$loadOptions$va===void 0?void 0:_state$loadOptions$va.type;if(!isValidStorageType(storageType)){var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===void 0
|
3422
|
+
var storageType=(_state$loadOptions$va=state.loadOptions.value.storage)===null||_state$loadOptions$va===void 0?void 0:_state$loadOptions$va.type;if(!isValidStorageType(storageType)){var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===void 0||_this2$logger.warn(STORAGE_TYPE_VALIDATION_WARNING(CONFIG_MANAGER,storageType,DEFAULT_STORAGE_TYPE));state.storage.type.value=DEFAULT_STORAGE_TYPE;}else {state.storage.type.value=storageType;}});this.getConfig();}/**
|
3407
3423
|
* Handle errors
|
3408
|
-
*/},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0
|
3424
|
+
*/},{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;}}/**
|
3409
3425
|
* A callback function that is executed once we fetch the source config response.
|
3410
3426
|
* Use to construct and store information that are dependent on the sourceConfig.
|
3411
3427
|
*/},{key:"processConfig",value:function processConfig(response,details){var _this3=this;// TODO: add retry logic with backoff based on rejectionDetails.xhr.status
|
@@ -3453,20 +3469,15 @@ var CapabilitiesManager=/*#__PURE__*/function(){function CapabilitiesManager(err
|
|
3453
3469
|
},{key:"detectBrowserCapabilities",value:function detectBrowserCapabilities(){var _this=this;o(function(){// Storage related details
|
3454
3470
|
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
|
3455
3471
|
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
|
3456
|
-
state.context.userAgent.value=getUserAgent();state.context.locale.value=getLanguage();state.context.screen.value=getScreenDetails();
|
3457
|
-
_this.getPageProperties();});// Ad blocker detection
|
3472
|
+
state.context.userAgent.value=getUserAgent();state.context.locale.value=getLanguage();state.context.screen.value=getScreenDetails();if(hasUAClientHints()){getUserAgentClientHint(function(uach){state.context['ua-ch'].value=uach;},state.loadOptions.value.uaChTrackLevel);}});// Ad blocker detection
|
3458
3473
|
b(function(){if(state.loadOptions.value.sendAdblockPage===true&&state.lifecycle.sourceConfigUrl.value!==undefined){detectAdBlockers(_this.errorHandler,_this.logger);}});}/**
|
3459
|
-
* Get page properties details to use in event context
|
3460
|
-
*/ // eslint-disable-next-line class-methods-use-this
|
3461
|
-
},{key:"getPageProperties",value:function getPageProperties(){var pageProperties=getDefaultPageProperties();o(function(){state.page.path.value=pageProperties.path;state.page.referrer.value=pageProperties.referrer;state.page.referring_domain.value=pageProperties.referring_domain;state.page.search.value=pageProperties.search;state.page.title.value=pageProperties.title;state.page.url.value=pageProperties.url;state.page.tab_url.value=pageProperties.tab_url;});}/**
|
3462
3474
|
* Detect if polyfills are required and then load script from polyfill URL
|
3463
|
-
*/},{key:"prepareBrowserCapabilities",value:function prepareBrowserCapabilities(){var _state$loadOptions$va,_this2=this;state.capabilities.isLegacyDOM.value=isLegacyJSEngine();var polyfillUrl=(_state$loadOptions$va=state.loadOptions.value.polyfillURL)!==null&&_state$loadOptions$va!==void 0?_state$loadOptions$va:POLYFILL_URL;var shouldLoadPolyfill=state.loadOptions.value.polyfillIfRequired&&state.capabilities.isLegacyDOM.value&&Boolean(polyfillUrl);if(shouldLoadPolyfill){var _this$externalSrcLoad
|
3464
|
-
//
|
3465
|
-
var
|
3475
|
+
*/},{key:"prepareBrowserCapabilities",value:function prepareBrowserCapabilities(){var _state$loadOptions$va,_this2=this;state.capabilities.isLegacyDOM.value=isLegacyJSEngine();var polyfillUrl=(_state$loadOptions$va=state.loadOptions.value.polyfillURL)!==null&&_state$loadOptions$va!==void 0?_state$loadOptions$va:POLYFILL_URL;var shouldLoadPolyfill=state.loadOptions.value.polyfillIfRequired&&state.capabilities.isLegacyDOM.value&&Boolean(polyfillUrl);if(shouldLoadPolyfill){var _this$externalSrcLoad;var isDefaultPolyfillService=polyfillUrl!==state.loadOptions.value.polyfillURL;if(isDefaultPolyfillService){var polyfillCallback=function polyfillCallback(){return _this2.onReady();};// write key specific callback
|
3476
|
+
// NOTE: we're not putting this into RudderStackGlobals as providing the property path to the callback function in the polyfill URL is not possible
|
3477
|
+
var polyfillCallbackName="RS_polyfillCallback_".concat(state.lifecycle.writeKey.value);globalThis[polyfillCallbackName]=polyfillCallback;polyfillUrl="".concat(polyfillUrl,"&callback=").concat(polyfillCallbackName);}(_this$externalSrcLoad=this.externalSrcLoader)===null||_this$externalSrcLoad===void 0||_this$externalSrcLoad.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();}}/**
|
3466
3478
|
* Attach listeners to window to observe event that update capabilities state values
|
3467
3479
|
*/ // eslint-disable-next-line class-methods-use-this
|
3468
|
-
},{key:"attachWindowListeners",value:function attachWindowListeners(){
|
3469
|
-
}/**
|
3480
|
+
},{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));}/**
|
3470
3481
|
* Set the lifecycle status to next phase
|
3471
3482
|
*/ // eslint-disable-next-line class-methods-use-this
|
3472
3483
|
},{key:"onReady",value:function onReady(){this.detectBrowserCapabilities();state.lifecycle.status.value=LifecycleStatus.BrowserCapabilitiesReady;}/**
|
@@ -3484,17 +3495,19 @@ var RESERVED_ELEMENTS=['anonymousId','sentAt','receivedAt','timestamp','original
|
|
3484
3495
|
* To get the page properties for context object
|
3485
3496
|
* @param pageProps Page properties
|
3486
3497
|
* @returns page properties object for context
|
3487
|
-
*/var getContextPageProperties=function getContextPageProperties(pageProps){
|
3498
|
+
*/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
|
3499
|
+
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;};/**
|
3488
3500
|
* Add any missing default page properties using values from options and defaults
|
3489
3501
|
* @param properties Input page properties
|
3490
3502
|
* @param options API options
|
3491
|
-
*/var getUpdatedPageProperties=function getUpdatedPageProperties(properties,options){var optionsPageProps=(options===null||options===void 0?void 0:options.page)||{};var pageProps=properties
|
3503
|
+
*/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
|
3504
|
+
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;};/**
|
3492
3505
|
* Utility to check for reserved keys in the input object
|
3493
3506
|
* @param obj Generic object
|
3494
3507
|
* @param eventType Rudder event type
|
3495
3508
|
* @param parentKeyPath Object's parent key path
|
3496
3509
|
* @param logger Logger instance
|
3497
|
-
*/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
|
3510
|
+
*/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));}});}};/**
|
3498
3511
|
* Checks for reserved keys in traits, properties, and contextual traits
|
3499
3512
|
* @param rudderEvent Generated rudder event
|
3500
3513
|
* @param logger Logger instance
|
@@ -3511,7 +3524,7 @@ rudderEvent.originalTimestamp=options.originalTimestamp;}};/**
|
|
3511
3524
|
* @param rudderContext Generated rudder event
|
3512
3525
|
* @param options API options
|
3513
3526
|
* @param logger Logger instance
|
3514
|
-
*/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 {logger===null||logger===void 0
|
3527
|
+
*/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 {logger===null||logger===void 0||logger.warn(INVALID_CONTEXT_OBJECT_WARNING(EVENT_MANAGER));}}});return context;};/**
|
3515
3528
|
* A function to determine whether SDK should use the integration option provided in load call
|
3516
3529
|
* @returns boolean
|
3517
3530
|
*/var shouldUseGlobalIntegrationsConfigInEvents=function shouldUseGlobalIntegrationsConfigInEvents(){return state.loadOptions.value.useGlobalIntegrationsConfigInEvents&&isObjectLiteralAndNotNull(state.nativeDestinations.loadOnlyIntegrations.value);};/**
|
@@ -3531,7 +3544,7 @@ rudderEvent.context=getMergedContext(rudderEvent.context,options);}};/**
|
|
3531
3544
|
* @param pageProps Page properties
|
3532
3545
|
* @param logger logger
|
3533
3546
|
* @returns Enriched RudderEvent object
|
3534
|
-
*/var getEnrichedEvent=function getEnrichedEvent(rudderEvent,options,pageProps,logger){var commonEventData={channel:CHANNEL,context:{traits:clone$1(state.session.userTraits.value),sessionId:state.session.sessionInfo.value.id||undefined,sessionStart:state.session.sessionInfo.value.sessionStart||undefined,consentManagement:{deniedConsentIds:clone$1(state.consents.data.value.deniedConsentIds)},'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:
|
3547
|
+
*/var getEnrichedEvent=function getEnrichedEvent(rudderEvent,options,pageProps,logger){var commonEventData={channel:CHANNEL,context:{traits:clone$1(state.session.userTraits.value),sessionId:state.session.sessionInfo.value.id||undefined,sessionStart:state.session.sessionInfo.value.sessionStart||undefined,consentManagement:{deniedConsentIds:clone$1(state.consents.data.value.deniedConsentIds)},'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)},originalTimestamp:getCurrentTimeFormatted(),integrations:DEFAULT_INTEGRATIONS_CONFIG,messageId:generateUUID(),userId:rudderEvent.userId||state.session.userId.value};if(state.storage.type.value===NO_STORAGE){// Generate new anonymous id for each request
|
3535
3548
|
commonEventData.anonymousId=generateUUID();commonEventData.context.anonymousTracking=true;}else {// Type casting to string as the user session manager will take care of initializing the value
|
3536
3549
|
commonEventData.anonymousId=state.session.anonymousUserId.value;}if(rudderEvent.type===RudderEventType.Identify){commonEventData.context.traits=state.storage.type.value!==NO_STORAGE?clone$1(state.session.userTraits.value):rudderEvent.context.traits;}if(rudderEvent.type===RudderEventType.Group){if(rudderEvent.groupId||state.session.groupId.value){commonEventData.groupId=rudderEvent.groupId||state.session.groupId.value;}if(rudderEvent.traits||state.session.groupTraits.value){commonEventData.traits=state.storage.type.value!==NO_STORAGE?clone$1(state.session.groupTraits.value):rudderEvent.traits;}}var processedEvent=mergeDeepRight(rudderEvent,commonEventData);// Set the default values for the event properties
|
3537
3550
|
// matching with v1.1 payload
|
@@ -3596,7 +3609,7 @@ var MIN_SESSION_ID_LENGTH=10;/**
|
|
3596
3609
|
* Function to validate user provided sessionId
|
3597
3610
|
* @param {number} sessionId
|
3598
3611
|
* @returns
|
3599
|
-
*/var isManualSessionIdValid=function isManualSessionIdValid(sessionId,logger){if(!sessionId||!isPositiveInteger(sessionId)||!hasMinLength(MIN_SESSION_ID_LENGTH,sessionId)){logger===null||logger===void 0
|
3612
|
+
*/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;};/**
|
3600
3613
|
* A function to generate new auto tracking session
|
3601
3614
|
* @param sessionTimeout current timestamp
|
3602
3615
|
* @returns SessionInfo
|
@@ -3619,9 +3632,9 @@ this.setUserId((_this$getUserId=this.getUserId())!==null&&_this$getUserId!==void
|
|
3619
3632
|
this.initializeSessionTracking();// Register the effect to sync with storage
|
3620
3633
|
this.registerEffects();}}},{key:"setDefaultValues",value:function setDefaultValues(){o(function(){state.session.userId.value=defaultUserSessionValues.userId;state.session.userTraits.value=defaultUserSessionValues.userTraits;state.session.groupId.value=defaultUserSessionValues.groupId;state.session.groupTraits.value=defaultUserSessionValues.groupTraits;state.session.anonymousUserId.value=defaultUserSessionValues.anonymousUserId;state.session.initialReferrer.value=defaultUserSessionValues.initialReferrer;state.session.initialReferringDomain.value=defaultUserSessionValues.initialReferringDomain;state.session.sessionInfo.value=defaultUserSessionValues.sessionInfo;});}},{key:"migrateStorageIfNeeded",value:function migrateStorageIfNeeded(){var _this=this;if(!state.storage.migrate.value){return;}Object.values(userSessionStorageKeys).forEach(function(storageEntry){var _this$pluginsManager,_this$store;var migratedVal=(_this$pluginsManager=_this.pluginsManager)===null||_this$pluginsManager===void 0?void 0:_this$pluginsManager.invokeSingle('storage.migrate',storageEntry,(_this$store=_this.store)===null||_this$store===void 0?void 0:_this$store.engine,_this.errorHandler,_this.logger);_this.syncValueToStorage(storageEntry,migratedVal);});}/**
|
3621
3634
|
* A function to initialize sessionTracking
|
3622
|
-
*/},{key:"initializeSessionTracking",value:function initializeSessionTracking(){var _this$getSessionFromS;var sessionInfo=(_this$getSessionFromS=this.getSessionFromStorage())!==null&&_this$getSessionFromS!==void 0?_this$getSessionFromS:defaultSessionInfo;var finalAutoTrackingStatus=!(state.loadOptions.value.sessions.autoTrack===false||sessionInfo.manualTrack===true);var sessionTimeout;var configuredSessionTimeout=state.loadOptions.value.sessions.timeout;if(!isPositiveInteger(configuredSessionTimeout)){var _this$logger;(_this$logger=this.logger)===null||_this$logger===void 0
|
3635
|
+
*/},{key:"initializeSessionTracking",value:function initializeSessionTracking(){var _this$getSessionFromS;var sessionInfo=(_this$getSessionFromS=this.getSessionFromStorage())!==null&&_this$getSessionFromS!==void 0?_this$getSessionFromS:defaultSessionInfo;var finalAutoTrackingStatus=!(state.loadOptions.value.sessions.autoTrack===false||sessionInfo.manualTrack===true);var sessionTimeout;var configuredSessionTimeout=state.loadOptions.value.sessions.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));sessionTimeout=DEFAULT_SESSION_TIMEOUT_MS;}else {sessionTimeout=configuredSessionTimeout;}if(sessionTimeout===0){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0||_this$logger2.warn(TIMEOUT_ZERO_WARNING(USER_SESSION_MANAGER));finalAutoTrackingStatus=false;}// In case user provides a timeout value greater than 0 but less than 10 seconds SDK will show a warning
|
3623
3636
|
// and will proceed with it
|
3624
|
-
if(sessionTimeout>0&&sessionTimeout<MIN_SESSION_TIMEOUT_MS){var _this$logger3;(_this$logger3=this.logger)===null||_this$logger3===void 0
|
3637
|
+
if(sessionTimeout>0&&sessionTimeout<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,sessionTimeout,MIN_SESSION_TIMEOUT_MS));}state.session.sessionInfo.value=_objectSpread2(_objectSpread2({},sessionInfo),{},{timeout:sessionTimeout,autoTrack:finalAutoTrackingStatus});// If auto session tracking is enabled start the session tracking
|
3625
3638
|
if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking();}}/**
|
3626
3639
|
* Handles error
|
3627
3640
|
* @param error The error object
|
@@ -3629,7 +3642,7 @@ if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking();}}
|
|
3629
3642
|
* A function to sync values in storage
|
3630
3643
|
* @param key
|
3631
3644
|
* @param value
|
3632
|
-
*/},{key:"syncValueToStorage",value:function syncValueToStorage(key,value){if(value&&isString(value)||isNonEmptyObject(value)){var _this$store2;(_this$store2=this.store)===null||_this$store2===void 0
|
3645
|
+
*/},{key:"syncValueToStorage",value:function syncValueToStorage(key,value){if(value&&isString(value)||isNonEmptyObject(value)){var _this$store2;(_this$store2=this.store)===null||_this$store2===void 0||_this$store2.set(key,value);}else {var _this$store3;(_this$store3=this.store)===null||_this$store3===void 0||_this$store3.remove(key);}}/**
|
3633
3646
|
* Function to update storage whenever state value changes
|
3634
3647
|
*/},{key:"registerEffects",value:function registerEffects(){var _this2=this;/**
|
3635
3648
|
* Update userId in storage automatically when userId is updated in state
|
@@ -3723,7 +3736,7 @@ var autoCapturedAnonymousId=(_this$pluginsManager3=this.pluginsManager)===null||
|
|
3723
3736
|
*/},{key:"end",value:function end(){state.session.sessionInfo.value={};}/**
|
3724
3737
|
* Clear storage
|
3725
3738
|
* @param resetAnonymousId
|
3726
|
-
*/},{key:"clearUserSessionStorage",value:function clearUserSessionStorage(resetAnonymousId){var _this$store12,_this$store13,_this$store14,_this$store15;(_this$store12=this.store)===null||_this$store12===void 0
|
3739
|
+
*/},{key:"clearUserSessionStorage",value:function clearUserSessionStorage(resetAnonymousId){var _this$store12,_this$store13,_this$store14,_this$store15;(_this$store12=this.store)===null||_this$store12===void 0||_this$store12.remove(userSessionStorageKeys.userId);(_this$store13=this.store)===null||_this$store13===void 0||_this$store13.remove(userSessionStorageKeys.userTraits);(_this$store14=this.store)===null||_this$store14===void 0||_this$store14.remove(userSessionStorageKeys.groupId);(_this$store15=this.store)===null||_this$store15===void 0||_this$store15.remove(userSessionStorageKeys.groupTraits);if(resetAnonymousId){var _this$store16;(_this$store16=this.store)===null||_this$store16===void 0||_this$store16.remove(userSessionStorageKeys.anonymousUserId);}}}]);return UserSessionManager;}();
|
3727
3740
|
|
3728
3741
|
/**
|
3729
3742
|
* A buffer queue to serve as a store for any type of data
|
@@ -3742,19 +3755,19 @@ var DATA_PLANE_QUEUE_EXT_POINT_PREFIX='dataplaneEventsQueue';var DESTINATIONS_QU
|
|
3742
3755
|
*/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);}/**
|
3743
3756
|
* Initializes the event repository
|
3744
3757
|
*/_createClass(EventRepository,[{key:"init",value:function init(){var _this=this;this.dataplaneEventsQueue=this.pluginsManager.invokeSingle("".concat(DATA_PLANE_QUEUE_EXT_POINT_PREFIX,".init"),state,this.httpClient,this.storeManager,this.errorHandler,this.logger);this.destinationsEventsQueue=this.pluginsManager.invokeSingle("".concat(DESTINATIONS_QUEUE_EXT_POINT_PREFIX,".init"),state,this.pluginsManager,this.storeManager,this.errorHandler,this.logger);// Start the queue once the client destinations are ready
|
3745
|
-
b(function(){if(state.nativeDestinations.clientDestinationsReady.value===true){_this.destinationsEventsQueue.start();}})
|
3746
|
-
* Enqueues the event for processing
|
3747
|
-
* @param event RudderEvent object
|
3748
|
-
* @param callback API callback function
|
3749
|
-
*/},{key:"enqueue",value:function enqueue(event,callback){var _this2=this;// Start the queue processing only when the destinations are ready or hybrid mode destinations exist
|
3758
|
+
b(function(){if(state.nativeDestinations.clientDestinationsReady.value===true){var _this$destinationsEve;(_this$destinationsEve=_this.destinationsEventsQueue)===null||_this$destinationsEve===void 0||_this$destinationsEve.start();}});// Start the queue processing only when the destinations are ready or hybrid mode destinations exist
|
3750
3759
|
// However, events will be enqueued for now.
|
3751
3760
|
// At the time of processing the events, the integrations config data from destinations
|
3752
3761
|
// is merged into the event object
|
3753
|
-
b(function(){var
|
3754
|
-
if(state.loadOptions.value.bufferDataPlaneEventsUntilReady===true){globalThis.setTimeout(function(){var
|
3762
|
+
var timeoutId;b(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)&&((_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
|
3763
|
+
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);}}/**
|
3764
|
+
* Enqueues the event for processing
|
3765
|
+
* @param event RudderEvent object
|
3766
|
+
* @param callback API callback function
|
3767
|
+
*/},{key:"enqueue",value:function enqueue(event,callback){var dpQEvent=clone$1(event);this.pluginsManager.invokeSingle("".concat(DATA_PLANE_QUEUE_EXT_POINT_PREFIX,".enqueue"),state,this.dataplaneEventsQueue,dpQEvent,this.errorHandler,this.logger);var dQEvent=clone$1(event);this.pluginsManager.invokeSingle("".concat(DESTINATIONS_QUEUE_EXT_POINT_PREFIX,".enqueue"),state,this.destinationsEventsQueue,dQEvent,this.errorHandler,this.logger);// Invoke the callback if it exists
|
3755
3768
|
try{// Using the event sent to the data plane queue here
|
3756
3769
|
// to ensure the mutated (if any) event is sent to the callback
|
3757
|
-
callback===null||callback===void 0
|
3770
|
+
callback===null||callback===void 0||callback(dpQEvent);}catch(error){this.onError(error,API_CALLBACK_INVOKE_ERROR);}}/**
|
3758
3771
|
* Handles error
|
3759
3772
|
* @param error The error object
|
3760
3773
|
* @param customMessage a message
|
@@ -3784,15 +3797,15 @@ retrievePreloadBufferEvents(_this);_this.prepareInternalServices();_this.loadCon
|
|
3784
3797
|
* Process the buffer preloaded events by passing their arguments to the respective facade methods
|
3785
3798
|
*/},{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.eventRepository=new EventRepository(this.pluginsManager,this.storeManager,this.errorHandler,this.logger);this.eventManager=new EventManager(this.eventRepository,this.userSessionManager,this.errorHandler,this.logger);}/**
|
3786
3799
|
* Load configuration
|
3787
|
-
*/},{key:"loadConfig",value:function loadConfig(){var _this$configManager;if(!state.lifecycle.writeKey.value){this.errorHandler.onError(new Error('A write key is required to load the SDK. Please provide a valid write key.'),LOAD_CONFIGURATION);return;}this.httpClient.setAuthHeader(state.lifecycle.writeKey.value);(_this$configManager=this.configManager)===null||_this$configManager===void 0
|
3800
|
+
*/},{key:"loadConfig",value:function loadConfig(){var _this$configManager;if(!state.lifecycle.writeKey.value){this.errorHandler.onError(new Error('A write key is required to load the SDK. Please provide a valid write key.'),LOAD_CONFIGURATION);return;}this.httpClient.setAuthHeader(state.lifecycle.writeKey.value);(_this$configManager=this.configManager)===null||_this$configManager===void 0||_this$configManager.init();}/**
|
3788
3801
|
* Initialize the storage and event queue
|
3789
3802
|
*/},{key:"init",value:function init(){var _this$storeManager,_this$storeManager2,_this$userSessionMana,_this$eventManager;this.errorHandler.init(this.externalSrcLoader);// Initialize storage
|
3790
|
-
(_this$storeManager=this.storeManager)===null||_this$storeManager===void 0
|
3791
|
-
if(state.consents.activeConsentManagerPluginName.value){var _this$pluginsManager;(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===void 0
|
3792
|
-
(_this$eventManager=this.eventManager)===null||_this$eventManager===void 0
|
3803
|
+
(_this$storeManager=this.storeManager)===null||_this$storeManager===void 0||_this$storeManager.init();this.clientDataStore=(_this$storeManager2=this.storeManager)===null||_this$storeManager2===void 0?void 0:_this$storeManager2.getStore(CLIENT_DATA_STORE_NAME);(_this$userSessionMana=this.userSessionManager)===null||_this$userSessionMana===void 0||_this$userSessionMana.init(this.clientDataStore);// Initialize consent manager
|
3804
|
+
if(state.consents.activeConsentManagerPluginName.value){var _this$pluginsManager;(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===void 0||_this$pluginsManager.invokeSingle("consentManager.init",state,this.storeManager,this.logger);}// Initialize event manager
|
3805
|
+
(_this$eventManager=this.eventManager)===null||_this$eventManager===void 0||_this$eventManager.init();// Mark the SDK as initialized
|
3793
3806
|
state.lifecycle.status.value=LifecycleStatus.Initialized;}/**
|
3794
3807
|
* Load plugins
|
3795
|
-
*/},{key:"loadPlugins",value:function loadPlugins(){var _this$pluginsManager2;(_this$pluginsManager2=this.pluginsManager)===null||_this$pluginsManager2===void 0
|
3808
|
+
*/},{key:"loadPlugins",value:function loadPlugins(){var _this$pluginsManager2;(_this$pluginsManager2=this.pluginsManager)===null||_this$pluginsManager2===void 0||_this$pluginsManager2.init();// TODO: are we going to enable custom plugins to be passed as load options?
|
3796
3809
|
// registerCustomPlugins(state.loadOptions.value.customPlugins);
|
3797
3810
|
}/**
|
3798
3811
|
* Trigger onLoaded callback if any is provided in config & emit initialised event
|
@@ -3812,8 +3825,8 @@ var readyEvent=new CustomEvent('RSA_Ready',{detail:{analyticsInstance:globalThis
|
|
3812
3825
|
state.eventBuffer.toBeProcessedArray.value.forEach(function(bufferedItem){var methodName=bufferedItem[0];if(isFunction(_this3[methodName])){var _ref;(_ref=_this3)[methodName].apply(_ref,_toConsumableArray(bufferedItem.slice(1)));}});state.eventBuffer.toBeProcessedArray.value=[];}/**
|
3813
3826
|
* Load device mode destinations
|
3814
3827
|
*/},{key:"loadDestinations",value:function loadDestinations(){var _this$pluginsManager3,_this$pluginsManager4;// Set in state the desired activeDestinations to inject in DOM
|
3815
|
-
(_this$pluginsManager3=this.pluginsManager)===null||_this$pluginsManager3===void 0
|
3816
|
-
state.lifecycle.status.value=LifecycleStatus.DestinationsLoading;(_this$pluginsManager4=this.pluginsManager)===null||_this$pluginsManager4===void 0
|
3828
|
+
(_this$pluginsManager3=this.pluginsManager)===null||_this$pluginsManager3===void 0||_this$pluginsManager3.invokeSingle('nativeDestinations.setActiveDestinations',state,this.pluginsManager,this.errorHandler,this.logger);var totalDestinationsToLoad=state.nativeDestinations.activeDestinations.value.length;if(totalDestinationsToLoad===0){state.lifecycle.status.value=LifecycleStatus.DestinationsReady;return;}// Start loading native integration scripts and create instances
|
3829
|
+
state.lifecycle.status.value=LifecycleStatus.DestinationsLoading;(_this$pluginsManager4=this.pluginsManager)===null||_this$pluginsManager4===void 0||_this$pluginsManager4.invokeSingle('nativeDestinations.load',state,this.externalSrcLoader,this.errorHandler,this.logger);// Progress to next lifecycle phase if all native destinations are initialized or failed
|
3817
3830
|
b(function(){var areAllDestinationsReady=totalDestinationsToLoad===0||state.nativeDestinations.initializedDestinations.value.length+state.nativeDestinations.failedDestinations.value.length===totalDestinationsToLoad;if(areAllDestinationsReady){o(function(){state.lifecycle.status.value=LifecycleStatus.DestinationsReady;state.nativeDestinations.clientDestinationsReady.value=true;});}});}/**
|
3818
3831
|
* Invoke the ready callbacks if any exist
|
3819
3832
|
*/ // eslint-disable-next-line class-methods-use-this
|
@@ -3823,20 +3836,20 @@ b(function(){var areAllDestinationsReady=totalDestinationsToLoad===0||state.nati
|
|
3823
3836
|
* If destinations are loaded or no integration is available for loading
|
3824
3837
|
* execute the callback immediately else push the callbacks to a queue that
|
3825
3838
|
* will be executed after loading completes
|
3826
|
-
*/if(state.lifecycle.status.value===LifecycleStatus.Ready){try{callback();}catch(err){this.errorHandler.onError(err,ANALYTICS_CORE,READY_CALLBACK_INVOKE_ERROR);}}else {state.eventBuffer.readyCallbacksArray.value.push(callback);}}},{key:"page",value:function page(payload){var _this$eventManager2;var type='page';this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,payload]);return;}(_this$eventManager2=this.eventManager)===null||_this$eventManager2===void 0
|
3839
|
+
*/if(state.lifecycle.status.value===LifecycleStatus.Ready){try{callback();}catch(err){this.errorHandler.onError(err,ANALYTICS_CORE,READY_CALLBACK_INVOKE_ERROR);}}else {state.eventBuffer.readyCallbacksArray.value.push(callback);}}},{key:"page",value:function page(payload){var _this$eventManager2;var type='page';this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,payload]);return;}(_this$eventManager2=this.eventManager)===null||_this$eventManager2===void 0||_this$eventManager2.addEvent({type:RudderEventType.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.
|
3827
3840
|
// Send automatic ad blocked page event if adblockers are detected on the page
|
3828
3841
|
// Check page category to avoid infinite loop
|
3829
3842
|
if(state.capabilities.isAdBlocked.value===true&&payload.category!==ADBLOCK_PAGE_CATEGORY){var pageCallArgs={category:ADBLOCK_PAGE_CATEGORY,name:ADBLOCK_PAGE_NAME,properties:{// 'title' is intentionally omitted as it does not make sense
|
3830
3843
|
// in v3 implementation
|
3831
|
-
path:ADBLOCK_PAGE_PATH},options:state.loadOptions.value.sendAdblockPageOptions};this.page(pageCallArgs);}}},{key:"track",value:function track(payload){var _this$eventManager3;var type='track';this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,payload]);return;}(_this$eventManager3=this.eventManager)===null||_this$eventManager3===void 0
|
3832
|
-
if(!isNull(payload.userId)){var _this$userSessionMana2;(_this$userSessionMana2=this.userSessionManager)===null||_this$userSessionMana2===void 0
|
3833
|
-
if(!isNull(payload.groupId)){var _this$userSessionMana6;(_this$userSessionMana6=this.userSessionManager)===null||_this$userSessionMana6===void 0
|
3834
|
-
if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,anonymousId,rudderAmpLinkerParam]);return;}(_this$userSessionMana10=this.userSessionManager)===null||_this$userSessionMana10===void 0
|
3844
|
+
path:ADBLOCK_PAGE_PATH},options:state.loadOptions.value.sendAdblockPageOptions};this.page(pageCallArgs);}}},{key:"track",value:function track(payload){var _this$eventManager3;var type='track';this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,payload]);return;}(_this$eventManager3=this.eventManager)===null||_this$eventManager3===void 0||_this$eventManager3.addEvent({type:RudderEventType.Track,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';this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,payload]);return;}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
|
3845
|
+
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:RudderEventType.Identify,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';this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,payload]);return;}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:RudderEventType.Alias,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';this.errorHandler.leaveBreadcrumb("New ".concat(type," event"));state.metrics.triggered.value+=1;if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,payload]);return;}// `null` value indicates that previous group ID needs to be retained
|
3846
|
+
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:RudderEventType.Group,groupId:payload.groupId,traits:payload.traits,options:payload.options,callback:payload.callback});}},{key:"reset",value:function reset(resetAnonymousId){var _this$userSessionMana8;var type='reset';this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation, resetAnonymousId: ").concat(resetAnonymousId));if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,resetAnonymousId]);return;}(_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
|
3847
|
+
if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,anonymousId,rudderAmpLinkerParam]);return;}(_this$userSessionMana10=this.userSessionManager)===null||_this$userSessionMana10===void 0||_this$userSessionMana10.setAnonymousId(anonymousId,rudderAmpLinkerParam);}// eslint-disable-next-line class-methods-use-this
|
3835
3848
|
},{key:"getUserId",value:function getUserId(){return state.session.userId.value;}// eslint-disable-next-line class-methods-use-this
|
3836
3849
|
},{key:"getUserTraits",value:function getUserTraits(){return state.session.userTraits.value;}// eslint-disable-next-line class-methods-use-this
|
3837
3850
|
},{key:"getGroupId",value:function getGroupId(){return state.session.groupId.value;}// eslint-disable-next-line class-methods-use-this
|
3838
|
-
},{key:"getGroupTraits",value:function getGroupTraits(){return state.session.groupTraits.value;}},{key:"startSession",value:function startSession(sessionId){var _this$userSessionMana11;var type='startSession';this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,sessionId]);return;}(_this$userSessionMana11=this.userSessionManager)===null||_this$userSessionMana11===void 0
|
3839
|
-
},{key:"getSessionId",value:function getSessionId(){var _this$userSessionMana13,_state$session$sessio,_state$session$sessio2;(_this$userSessionMana13=this.userSessionManager)===null||_this$userSessionMana13===void 0
|
3851
|
+
},{key:"getGroupTraits",value:function getGroupTraits(){return state.session.groupTraits.value;}},{key:"startSession",value:function startSession(sessionId){var _this$userSessionMana11;var type='startSession';this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,sessionId]);return;}(_this$userSessionMana11=this.userSessionManager)===null||_this$userSessionMana11===void 0||_this$userSessionMana11.start(sessionId);}},{key:"endSession",value:function endSession(){var _this$userSessionMana12;var type='endSession';this.errorHandler.leaveBreadcrumb("New ".concat(type," invocation"));if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type]);return;}(_this$userSessionMana12=this.userSessionManager)===null||_this$userSessionMana12===void 0||_this$userSessionMana12.end();}// eslint-disable-next-line class-methods-use-this
|
3852
|
+
},{key:"getSessionId",value:function getSessionId(){var _this$userSessionMana13,_state$session$sessio,_state$session$sessio2;(_this$userSessionMana13=this.userSessionManager)===null||_this$userSessionMana13===void 0||_this$userSessionMana13.refreshSession();return (_state$session$sessio=(_state$session$sessio2=state.session.sessionInfo.value)===null||_state$session$sessio2===void 0?void 0:_state$session$sessio2.id)!==null&&_state$session$sessio!==void 0?_state$session$sessio:null;}// End consumer exposed methods
|
3840
3853
|
}]);return Analytics;}();
|
3841
3854
|
|
3842
3855
|
/*
|