@rudderstack/analytics-js 3.0.0-beta.5 → 3.0.0-beta.6
Sign up to get free protection for your applications and to get access to all the features.
- package/CHANGELOG.md +19 -0
- package/legacy/cjs/index.js +354 -338
- package/legacy/esm/index.js +354 -338
- package/legacy/umd/index.js +354 -338
- package/modern/cjs/index.js +37 -33
- package/modern/esm/index.js +37 -33
- package/modern/umd/index.js +37 -33
- package/package.json +5 -11
package/legacy/umd/index.js
CHANGED
@@ -24,331 +24,336 @@
|
|
24
24
|
|
25
25
|
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;}({});
|
26
26
|
|
27
|
-
function ownKeys(
|
28
|
-
var
|
27
|
+
function ownKeys(e, r) {
|
28
|
+
var t = Object.keys(e);
|
29
29
|
if (Object.getOwnPropertySymbols) {
|
30
|
-
var
|
31
|
-
|
32
|
-
return Object.getOwnPropertyDescriptor(
|
33
|
-
})),
|
30
|
+
var o = Object.getOwnPropertySymbols(e);
|
31
|
+
r && (o = o.filter(function (r) {
|
32
|
+
return Object.getOwnPropertyDescriptor(e, r).enumerable;
|
33
|
+
})), t.push.apply(t, o);
|
34
34
|
}
|
35
|
-
return
|
35
|
+
return t;
|
36
36
|
}
|
37
|
-
function _objectSpread2(
|
38
|
-
for (var
|
39
|
-
var
|
40
|
-
|
41
|
-
_defineProperty(
|
42
|
-
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(
|
43
|
-
Object.defineProperty(
|
37
|
+
function _objectSpread2(e) {
|
38
|
+
for (var r = 1; r < arguments.length; r++) {
|
39
|
+
var t = null != arguments[r] ? arguments[r] : {};
|
40
|
+
r % 2 ? ownKeys(Object(t), !0).forEach(function (r) {
|
41
|
+
_defineProperty(e, r, t[r]);
|
42
|
+
}) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) {
|
43
|
+
Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r));
|
44
44
|
});
|
45
45
|
}
|
46
|
-
return
|
46
|
+
return e;
|
47
47
|
}
|
48
48
|
function _regeneratorRuntime() {
|
49
49
|
_regeneratorRuntime = function () {
|
50
|
-
return
|
50
|
+
return e;
|
51
51
|
};
|
52
|
-
var
|
53
|
-
|
54
|
-
|
55
|
-
|
56
|
-
|
52
|
+
var t,
|
53
|
+
e = {},
|
54
|
+
r = Object.prototype,
|
55
|
+
n = r.hasOwnProperty,
|
56
|
+
o = Object.defineProperty || function (t, e, r) {
|
57
|
+
t[e] = r.value;
|
57
58
|
},
|
58
|
-
|
59
|
-
|
60
|
-
|
61
|
-
|
62
|
-
function define(
|
63
|
-
return Object.defineProperty(
|
64
|
-
value:
|
59
|
+
i = "function" == typeof Symbol ? Symbol : {},
|
60
|
+
a = i.iterator || "@@iterator",
|
61
|
+
c = i.asyncIterator || "@@asyncIterator",
|
62
|
+
u = i.toStringTag || "@@toStringTag";
|
63
|
+
function define(t, e, r) {
|
64
|
+
return Object.defineProperty(t, e, {
|
65
|
+
value: r,
|
65
66
|
enumerable: !0,
|
66
67
|
configurable: !0,
|
67
68
|
writable: !0
|
68
|
-
}),
|
69
|
+
}), t[e];
|
69
70
|
}
|
70
71
|
try {
|
71
72
|
define({}, "");
|
72
|
-
} catch (
|
73
|
-
define = function (
|
74
|
-
return
|
73
|
+
} catch (t) {
|
74
|
+
define = function (t, e, r) {
|
75
|
+
return t[e] = r;
|
75
76
|
};
|
76
77
|
}
|
77
|
-
function wrap(
|
78
|
-
var
|
79
|
-
|
80
|
-
|
81
|
-
return
|
82
|
-
value: makeInvokeMethod(
|
83
|
-
}),
|
78
|
+
function wrap(t, e, r, n) {
|
79
|
+
var i = e && e.prototype instanceof Generator ? e : Generator,
|
80
|
+
a = Object.create(i.prototype),
|
81
|
+
c = new Context(n || []);
|
82
|
+
return o(a, "_invoke", {
|
83
|
+
value: makeInvokeMethod(t, r, c)
|
84
|
+
}), a;
|
84
85
|
}
|
85
|
-
function tryCatch(
|
86
|
+
function tryCatch(t, e, r) {
|
86
87
|
try {
|
87
88
|
return {
|
88
89
|
type: "normal",
|
89
|
-
arg:
|
90
|
+
arg: t.call(e, r)
|
90
91
|
};
|
91
|
-
} catch (
|
92
|
+
} catch (t) {
|
92
93
|
return {
|
93
94
|
type: "throw",
|
94
|
-
arg:
|
95
|
+
arg: t
|
95
96
|
};
|
96
97
|
}
|
97
98
|
}
|
98
|
-
|
99
|
-
var
|
99
|
+
e.wrap = wrap;
|
100
|
+
var h = "suspendedStart",
|
101
|
+
l = "suspendedYield",
|
102
|
+
f = "executing",
|
103
|
+
s = "completed",
|
104
|
+
y = {};
|
100
105
|
function Generator() {}
|
101
106
|
function GeneratorFunction() {}
|
102
107
|
function GeneratorFunctionPrototype() {}
|
103
|
-
var
|
104
|
-
define(
|
108
|
+
var p = {};
|
109
|
+
define(p, a, function () {
|
105
110
|
return this;
|
106
111
|
});
|
107
|
-
var
|
108
|
-
|
109
|
-
|
110
|
-
var
|
111
|
-
function defineIteratorMethods(
|
112
|
-
["next", "throw", "return"].forEach(function (
|
113
|
-
define(
|
114
|
-
return this._invoke(
|
112
|
+
var d = Object.getPrototypeOf,
|
113
|
+
v = d && d(d(values([])));
|
114
|
+
v && v !== r && n.call(v, a) && (p = v);
|
115
|
+
var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p);
|
116
|
+
function defineIteratorMethods(t) {
|
117
|
+
["next", "throw", "return"].forEach(function (e) {
|
118
|
+
define(t, e, function (t) {
|
119
|
+
return this._invoke(e, t);
|
115
120
|
});
|
116
121
|
});
|
117
122
|
}
|
118
|
-
function AsyncIterator(
|
119
|
-
function invoke(
|
120
|
-
var
|
121
|
-
if ("throw" !==
|
122
|
-
var
|
123
|
-
|
124
|
-
return
|
125
|
-
invoke("next",
|
126
|
-
}, function (
|
127
|
-
invoke("throw",
|
128
|
-
}) :
|
129
|
-
|
130
|
-
}, function (
|
131
|
-
return invoke("throw",
|
123
|
+
function AsyncIterator(t, e) {
|
124
|
+
function invoke(r, o, i, a) {
|
125
|
+
var c = tryCatch(t[r], t, o);
|
126
|
+
if ("throw" !== c.type) {
|
127
|
+
var u = c.arg,
|
128
|
+
h = u.value;
|
129
|
+
return h && "object" == typeof h && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) {
|
130
|
+
invoke("next", t, i, a);
|
131
|
+
}, function (t) {
|
132
|
+
invoke("throw", t, i, a);
|
133
|
+
}) : e.resolve(h).then(function (t) {
|
134
|
+
u.value = t, i(u);
|
135
|
+
}, function (t) {
|
136
|
+
return invoke("throw", t, i, a);
|
132
137
|
});
|
133
138
|
}
|
134
|
-
|
139
|
+
a(c.arg);
|
135
140
|
}
|
136
|
-
var
|
137
|
-
|
138
|
-
value: function (
|
141
|
+
var r;
|
142
|
+
o(this, "_invoke", {
|
143
|
+
value: function (t, n) {
|
139
144
|
function callInvokeWithMethodAndArg() {
|
140
|
-
return new
|
141
|
-
invoke(
|
145
|
+
return new e(function (e, r) {
|
146
|
+
invoke(t, n, e, r);
|
142
147
|
});
|
143
148
|
}
|
144
|
-
return
|
149
|
+
return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg();
|
145
150
|
}
|
146
151
|
});
|
147
152
|
}
|
148
|
-
function makeInvokeMethod(
|
149
|
-
var
|
150
|
-
return function (
|
151
|
-
if (
|
152
|
-
if (
|
153
|
-
if ("throw" ===
|
153
|
+
function makeInvokeMethod(e, r, n) {
|
154
|
+
var o = h;
|
155
|
+
return function (i, a) {
|
156
|
+
if (o === f) throw new Error("Generator is already running");
|
157
|
+
if (o === s) {
|
158
|
+
if ("throw" === i) throw a;
|
154
159
|
return {
|
155
|
-
value:
|
160
|
+
value: t,
|
156
161
|
done: !0
|
157
162
|
};
|
158
163
|
}
|
159
|
-
for (
|
160
|
-
var
|
161
|
-
if (
|
162
|
-
var
|
163
|
-
if (
|
164
|
-
if (
|
165
|
-
return
|
164
|
+
for (n.method = i, n.arg = a;;) {
|
165
|
+
var c = n.delegate;
|
166
|
+
if (c) {
|
167
|
+
var u = maybeInvokeDelegate(c, n);
|
168
|
+
if (u) {
|
169
|
+
if (u === y) continue;
|
170
|
+
return u;
|
166
171
|
}
|
167
172
|
}
|
168
|
-
if ("next" ===
|
169
|
-
if (
|
170
|
-
|
171
|
-
} else "return" ===
|
172
|
-
|
173
|
-
var
|
174
|
-
if ("normal" ===
|
175
|
-
if (
|
173
|
+
if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) {
|
174
|
+
if (o === h) throw o = s, n.arg;
|
175
|
+
n.dispatchException(n.arg);
|
176
|
+
} else "return" === n.method && n.abrupt("return", n.arg);
|
177
|
+
o = f;
|
178
|
+
var p = tryCatch(e, r, n);
|
179
|
+
if ("normal" === p.type) {
|
180
|
+
if (o = n.done ? s : l, p.arg === y) continue;
|
176
181
|
return {
|
177
|
-
value:
|
178
|
-
done:
|
182
|
+
value: p.arg,
|
183
|
+
done: n.done
|
179
184
|
};
|
180
185
|
}
|
181
|
-
"throw" ===
|
186
|
+
"throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg);
|
182
187
|
}
|
183
188
|
};
|
184
189
|
}
|
185
|
-
function maybeInvokeDelegate(
|
186
|
-
var
|
187
|
-
|
188
|
-
if (
|
189
|
-
var
|
190
|
-
if ("throw" ===
|
191
|
-
var
|
192
|
-
return
|
190
|
+
function maybeInvokeDelegate(e, r) {
|
191
|
+
var n = r.method,
|
192
|
+
o = e.iterator[n];
|
193
|
+
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;
|
194
|
+
var i = tryCatch(o, e.iterator, r.arg);
|
195
|
+
if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y;
|
196
|
+
var a = i.arg;
|
197
|
+
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);
|
193
198
|
}
|
194
|
-
function pushTryEntry(
|
195
|
-
var
|
196
|
-
tryLoc:
|
199
|
+
function pushTryEntry(t) {
|
200
|
+
var e = {
|
201
|
+
tryLoc: t[0]
|
197
202
|
};
|
198
|
-
1 in
|
203
|
+
1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e);
|
199
204
|
}
|
200
|
-
function resetTryEntry(
|
201
|
-
var
|
202
|
-
|
205
|
+
function resetTryEntry(t) {
|
206
|
+
var e = t.completion || {};
|
207
|
+
e.type = "normal", delete e.arg, t.completion = e;
|
203
208
|
}
|
204
|
-
function Context(
|
209
|
+
function Context(t) {
|
205
210
|
this.tryEntries = [{
|
206
211
|
tryLoc: "root"
|
207
|
-
}],
|
212
|
+
}], t.forEach(pushTryEntry, this), this.reset(!0);
|
208
213
|
}
|
209
|
-
function values(
|
210
|
-
if (
|
211
|
-
var
|
212
|
-
if (
|
213
|
-
if ("function" == typeof
|
214
|
-
if (!isNaN(
|
215
|
-
var
|
216
|
-
|
217
|
-
for (; ++
|
218
|
-
return next.value =
|
214
|
+
function values(e) {
|
215
|
+
if (e || "" === e) {
|
216
|
+
var r = e[a];
|
217
|
+
if (r) return r.call(e);
|
218
|
+
if ("function" == typeof e.next) return e;
|
219
|
+
if (!isNaN(e.length)) {
|
220
|
+
var o = -1,
|
221
|
+
i = function next() {
|
222
|
+
for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next;
|
223
|
+
return next.value = t, next.done = !0, next;
|
219
224
|
};
|
220
|
-
return
|
225
|
+
return i.next = i;
|
221
226
|
}
|
222
227
|
}
|
223
|
-
throw new TypeError(typeof
|
228
|
+
throw new TypeError(typeof e + " is not iterable");
|
224
229
|
}
|
225
|
-
return GeneratorFunction.prototype = GeneratorFunctionPrototype,
|
230
|
+
return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", {
|
226
231
|
value: GeneratorFunctionPrototype,
|
227
232
|
configurable: !0
|
228
|
-
}),
|
233
|
+
}), o(GeneratorFunctionPrototype, "constructor", {
|
229
234
|
value: GeneratorFunction,
|
230
235
|
configurable: !0
|
231
|
-
}), GeneratorFunction.displayName = define(GeneratorFunctionPrototype,
|
232
|
-
var
|
233
|
-
return !!
|
234
|
-
},
|
235
|
-
return Object.setPrototypeOf ? Object.setPrototypeOf(
|
236
|
-
},
|
236
|
+
}), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) {
|
237
|
+
var e = "function" == typeof t && t.constructor;
|
238
|
+
return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name));
|
239
|
+
}, e.mark = function (t) {
|
240
|
+
return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t;
|
241
|
+
}, e.awrap = function (t) {
|
237
242
|
return {
|
238
|
-
__await:
|
243
|
+
__await: t
|
239
244
|
};
|
240
|
-
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype,
|
245
|
+
}, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () {
|
241
246
|
return this;
|
242
|
-
}),
|
243
|
-
void 0 ===
|
244
|
-
var
|
245
|
-
return
|
246
|
-
return
|
247
|
+
}), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) {
|
248
|
+
void 0 === i && (i = Promise);
|
249
|
+
var a = new AsyncIterator(wrap(t, r, n, o), i);
|
250
|
+
return e.isGeneratorFunction(r) ? a : a.next().then(function (t) {
|
251
|
+
return t.done ? t.value : a.next();
|
247
252
|
});
|
248
|
-
}, defineIteratorMethods(
|
253
|
+
}, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () {
|
249
254
|
return this;
|
250
|
-
}), define(
|
255
|
+
}), define(g, "toString", function () {
|
251
256
|
return "[object Generator]";
|
252
|
-
}),
|
253
|
-
var
|
254
|
-
|
255
|
-
for (var
|
256
|
-
return
|
257
|
-
for (;
|
258
|
-
var
|
259
|
-
if (
|
257
|
+
}), e.keys = function (t) {
|
258
|
+
var e = Object(t),
|
259
|
+
r = [];
|
260
|
+
for (var n in e) r.push(n);
|
261
|
+
return r.reverse(), function next() {
|
262
|
+
for (; r.length;) {
|
263
|
+
var t = r.pop();
|
264
|
+
if (t in e) return next.value = t, next.done = !1, next;
|
260
265
|
}
|
261
266
|
return next.done = !0, next;
|
262
267
|
};
|
263
|
-
},
|
268
|
+
}, e.values = values, Context.prototype = {
|
264
269
|
constructor: Context,
|
265
|
-
reset: function (
|
266
|
-
if (this.prev = 0, this.next = 0, this.sent = this._sent =
|
270
|
+
reset: function (e) {
|
271
|
+
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);
|
267
272
|
},
|
268
273
|
stop: function () {
|
269
274
|
this.done = !0;
|
270
|
-
var
|
271
|
-
if ("throw" ===
|
275
|
+
var t = this.tryEntries[0].completion;
|
276
|
+
if ("throw" === t.type) throw t.arg;
|
272
277
|
return this.rval;
|
273
278
|
},
|
274
|
-
dispatchException: function (
|
275
|
-
if (this.done) throw
|
276
|
-
var
|
277
|
-
function handle(
|
278
|
-
return
|
279
|
+
dispatchException: function (e) {
|
280
|
+
if (this.done) throw e;
|
281
|
+
var r = this;
|
282
|
+
function handle(n, o) {
|
283
|
+
return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o;
|
279
284
|
}
|
280
|
-
for (var
|
281
|
-
var
|
282
|
-
|
283
|
-
if ("root" ===
|
284
|
-
if (
|
285
|
-
var
|
286
|
-
|
287
|
-
if (
|
288
|
-
if (this.prev <
|
289
|
-
if (this.prev <
|
290
|
-
} else if (
|
291
|
-
if (this.prev <
|
285
|
+
for (var o = this.tryEntries.length - 1; o >= 0; --o) {
|
286
|
+
var i = this.tryEntries[o],
|
287
|
+
a = i.completion;
|
288
|
+
if ("root" === i.tryLoc) return handle("end");
|
289
|
+
if (i.tryLoc <= this.prev) {
|
290
|
+
var c = n.call(i, "catchLoc"),
|
291
|
+
u = n.call(i, "finallyLoc");
|
292
|
+
if (c && u) {
|
293
|
+
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
|
294
|
+
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
|
295
|
+
} else if (c) {
|
296
|
+
if (this.prev < i.catchLoc) return handle(i.catchLoc, !0);
|
292
297
|
} else {
|
293
|
-
if (!
|
294
|
-
if (this.prev <
|
298
|
+
if (!u) throw new Error("try statement without catch or finally");
|
299
|
+
if (this.prev < i.finallyLoc) return handle(i.finallyLoc);
|
295
300
|
}
|
296
301
|
}
|
297
302
|
}
|
298
303
|
},
|
299
|
-
abrupt: function (
|
300
|
-
for (var
|
301
|
-
var
|
302
|
-
if (
|
303
|
-
var
|
304
|
+
abrupt: function (t, e) {
|
305
|
+
for (var r = this.tryEntries.length - 1; r >= 0; --r) {
|
306
|
+
var o = this.tryEntries[r];
|
307
|
+
if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) {
|
308
|
+
var i = o;
|
304
309
|
break;
|
305
310
|
}
|
306
311
|
}
|
307
|
-
|
308
|
-
var
|
309
|
-
return
|
312
|
+
i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null);
|
313
|
+
var a = i ? i.completion : {};
|
314
|
+
return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a);
|
310
315
|
},
|
311
|
-
complete: function (
|
312
|
-
if ("throw" ===
|
313
|
-
return "break" ===
|
316
|
+
complete: function (t, e) {
|
317
|
+
if ("throw" === t.type) throw t.arg;
|
318
|
+
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;
|
314
319
|
},
|
315
|
-
finish: function (
|
316
|
-
for (var
|
317
|
-
var
|
318
|
-
if (
|
320
|
+
finish: function (t) {
|
321
|
+
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
|
322
|
+
var r = this.tryEntries[e];
|
323
|
+
if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y;
|
319
324
|
}
|
320
325
|
},
|
321
|
-
catch: function (
|
322
|
-
for (var
|
323
|
-
var
|
324
|
-
if (
|
325
|
-
var
|
326
|
-
if ("throw" ===
|
327
|
-
var
|
328
|
-
resetTryEntry(
|
326
|
+
catch: function (t) {
|
327
|
+
for (var e = this.tryEntries.length - 1; e >= 0; --e) {
|
328
|
+
var r = this.tryEntries[e];
|
329
|
+
if (r.tryLoc === t) {
|
330
|
+
var n = r.completion;
|
331
|
+
if ("throw" === n.type) {
|
332
|
+
var o = n.arg;
|
333
|
+
resetTryEntry(r);
|
329
334
|
}
|
330
|
-
return
|
335
|
+
return o;
|
331
336
|
}
|
332
337
|
}
|
333
338
|
throw new Error("illegal catch attempt");
|
334
339
|
},
|
335
|
-
delegateYield: function (
|
340
|
+
delegateYield: function (e, r, n) {
|
336
341
|
return this.delegate = {
|
337
|
-
iterator: values(
|
338
|
-
resultName:
|
339
|
-
nextLoc:
|
340
|
-
}, "next" === this.method && (this.arg =
|
342
|
+
iterator: values(e),
|
343
|
+
resultName: r,
|
344
|
+
nextLoc: n
|
345
|
+
}, "next" === this.method && (this.arg = t), y;
|
341
346
|
}
|
342
|
-
},
|
347
|
+
}, e;
|
343
348
|
}
|
344
|
-
function _typeof(
|
349
|
+
function _typeof(o) {
|
345
350
|
"@babel/helpers - typeof";
|
346
351
|
|
347
|
-
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (
|
348
|
-
return typeof
|
349
|
-
} : function (
|
350
|
-
return
|
351
|
-
}, _typeof(
|
352
|
+
return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) {
|
353
|
+
return typeof o;
|
354
|
+
} : function (o) {
|
355
|
+
return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o;
|
356
|
+
}, _typeof(o);
|
352
357
|
}
|
353
358
|
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
|
354
359
|
try {
|
@@ -1022,17 +1027,24 @@
|
|
1022
1027
|
|
1023
1028
|
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';
|
1024
1029
|
|
1025
|
-
var APP_NAME='RudderLabs JavaScript SDK';var APP_VERSION='3.0.0-beta.
|
1030
|
+
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';
|
1026
1031
|
|
1027
1032
|
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';
|
1028
1033
|
|
1034
|
+
var DEFAULT_XHR_TIMEOUT_MS=10*1000;// 10 seconds
|
1035
|
+
var DEFAULT_COOKIE_MAX_AGE_MS=31536000*1000;// 1 year
|
1036
|
+
var DEFAULT_SESSION_TIMEOUT_MS=30*60*1000;// 30 minutes
|
1037
|
+
var MIN_SESSION_TIMEOUT_MS=10*1000;// 10 seconds
|
1038
|
+
var DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS=10*1000;// 10 seconds
|
1039
|
+
var DEBOUNCED_TIMEOUT_MS=250;// 250 milliseconds
|
1040
|
+
|
1029
1041
|
/**
|
1030
1042
|
* Create globally accessible RudderStackGlobals object
|
1031
1043
|
*/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]={};}};/**
|
1032
1044
|
* Add move values to globally accessible RudderStackGlobals object per analytics instance
|
1033
1045
|
*/var setExposedGlobal=function setExposedGlobal(keyName,value){var analyticsInstanceId=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'app';createExposedGlobals(analyticsInstanceId);globalThis.RudderStackGlobals[analyticsInstanceId][keyName]=value;};/**
|
1034
1046
|
* Get values from globally accessible RudderStackGlobals object by analytics instance
|
1035
|
-
*/var getExposedGlobal=function getExposedGlobal(keyName){var analyticsInstanceId=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'app';createExposedGlobals(analyticsInstanceId);return globalThis.RudderStackGlobals[analyticsInstanceId][keyName];};
|
1047
|
+
*/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);};}
|
1036
1048
|
|
1037
1049
|
/**
|
1038
1050
|
* Parse query string params into object values for keys that start with a defined prefix
|
@@ -1063,14 +1075,14 @@
|
|
1063
1075
|
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.
|
1064
1076
|
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
1065
1077
|
// @ts-ignore-next-line
|
1066
|
-
while(ancestors.length>0&&ancestors[ancestors.length-1]!==this){ancestors.pop();}if(ancestors.includes(value)){logger===null||logger===void 0
|
1078
|
+
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;};};/**
|
1067
1079
|
* Utility method for JSON stringify object excluding null values & circular references
|
1068
1080
|
*
|
1069
1081
|
* @param {*} value input
|
1070
1082
|
* @param {boolean} excludeNull if it should exclude nul or not
|
1071
1083
|
* @param {function} logger optional logger methods for warning
|
1072
1084
|
* @returns string
|
1073
|
-
*/var stringifyWithoutCircular=function stringifyWithoutCircular(value,excludeNull,excludeKeys,logger){try{return JSON.stringify(value,getCircularReplacer(excludeNull,excludeKeys,logger));}catch(err){logger===null||logger===void 0
|
1085
|
+
*/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;}};
|
1074
1086
|
|
1075
1087
|
/**
|
1076
1088
|
* Get mutated error with issue prepended to error message
|
@@ -1121,7 +1133,7 @@
|
|
1121
1133
|
* Load external resource of type javascript
|
1122
1134
|
*/_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();}});}/**
|
1123
1135
|
* Handle errors
|
1124
|
-
*/},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0
|
1136
|
+
*/},{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;}();
|
1125
1137
|
|
1126
1138
|
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);}
|
1127
1139
|
|
@@ -1135,7 +1147,7 @@
|
|
1135
1147
|
|
1136
1148
|
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;';/**
|
1137
1149
|
* Service to log messages/data to output provider, default is console
|
1138
|
-
*/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
|
1150
|
+
*/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
|
1139
1151
|
// to assist on the fly debugging?
|
1140
1152
|
},{key:"setMinLogLevel",value:function setMinLogLevel(logLevel){this.minLogLevel=LOG_LEVEL_MAP[logLevel];if(isUndefined(this.minLogLevel)){this.minLogLevel=LOG_LEVEL_MAP[DEFAULT_LOG_LEVEL];}}/**
|
1141
1153
|
* Formats the console message using `scope` and styles
|
@@ -1154,13 +1166,7 @@
|
|
1154
1166
|
|
1155
1167
|
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
|
1156
1168
|
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
|
1157
|
-
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
|
1158
|
-
|
1159
|
-
var DEFAULT_XHR_TIMEOUT_MS=10*1000;// 10 seconds
|
1160
|
-
var DEFAULT_COOKIE_MAX_AGE_MS=31536000*1000;// 1 year
|
1161
|
-
var DEFAULT_SESSION_TIMEOUT_MS=30*60*1000;// 30 minutes
|
1162
|
-
var MIN_SESSION_TIMEOUT_MS=10*1000;// 10 seconds
|
1163
|
-
var DEFAULT_DATA_PLANE_EVENTS_BUFFER_TIMEOUT_MS=10*1000;// 10 seconds
|
1169
|
+
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
|
1164
1170
|
|
1165
1171
|
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
|
1166
1172
|
// const DEST_SDK_BASE_URL = `${SDK_CDN_BASE_URL}/latest/${CDN_ARCH_VERSION_DIR}/${BUILD_TYPE}/${CDN_INT_DIR}`;
|
@@ -1200,12 +1206,12 @@
|
|
1200
1206
|
// to next or return the value if it is the last one instead of an array per
|
1201
1207
|
// plugin that is the normal invoke
|
1202
1208
|
// TODO: add invoke method for extension point that we know only one plugin can be used. add invokeMultiple and invokeSingle methods
|
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
|
1204
|
-
var notExistDeps=plugin.deps.filter(function(dependency){return !_this.byName[dependency];});(_this$logger5=_this.logger)===null||_this$logger5===void 0
|
1209
|
+
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.
|
1210
|
+
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
|
1205
1211
|
// do some unified pre-process before application starts.
|
1206
1212
|
},{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
|
1207
1213
|
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
|
1208
|
-
if(throws){throw err;}else {var _this2$logger;(_this2$logger=_this2.logger)===null||_this2$logger===void 0
|
1214
|
+
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);
|
1209
1215
|
|
1210
1216
|
var FAILED_REQUEST_ERR_MSG_PREFIX='The request failed';var ERROR_MESSAGES_TO_BE_FILTERED=[FAILED_REQUEST_ERR_MSG_PREFIX];
|
1211
1217
|
|
@@ -1220,7 +1226,7 @@
|
|
1220
1226
|
/**
|
1221
1227
|
* A service to handle errors
|
1222
1228
|
*/var ErrorHandler=/*#__PURE__*/function(){// If no logger is passed errors will be thrown as unhandled error
|
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
|
1229
|
+
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
|
1224
1230
|
var errorMessage=processError(error);// If no error message after we normalize, then we swallow/ignore the errors
|
1225
1231
|
if(!errorMessage){return;}errorMessage=removeDoubleSpaces("".concat(context).concat(LOG_CONTEXT_SEPARATOR).concat(customMessage," ").concat(errorMessage));var normalizedError=error;// Enhance error message
|
1226
1232
|
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;}}/**
|
@@ -1233,7 +1239,7 @@
|
|
1233
1239
|
*
|
1234
1240
|
* @param {Error} error Error instance from handled error
|
1235
1241
|
*/},{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
|
1236
|
-
(_this$logger2=this.logger)===null||_this$logger2===void 0
|
1242
|
+
(_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);
|
1237
1243
|
|
1238
1244
|
var DestinationConnectionMode=/*#__PURE__*/function(DestinationConnectionMode){DestinationConnectionMode["Hybrid"]="hybrid";DestinationConnectionMode["Cloud"]="cloud";DestinationConnectionMode["Device"]="device";return DestinationConnectionMode;}({});
|
1239
1245
|
|
@@ -1269,7 +1275,7 @@
|
|
1269
1275
|
|
1270
1276
|
var generateUUID=function generateUUID(){if(hasCrypto$1()){return v4$1();}return v4();};
|
1271
1277
|
|
1272
|
-
var QueueStatuses={IN_PROGRESS:'inProgress',QUEUE:'queue',RECLAIM_START:'reclaimStart',RECLAIM_END:'reclaimEnd',ACK:'ack'};
|
1278
|
+
var QueueStatuses={IN_PROGRESS:'inProgress',QUEUE:'queue',RECLAIM_START:'reclaimStart',RECLAIM_END:'reclaimEnd',ACK:'ack',BATCH_QUEUE:'batchQueue'};
|
1273
1279
|
|
1274
1280
|
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);
|
1275
1281
|
|
@@ -1429,7 +1435,7 @@
|
|
1429
1435
|
var EVENT_PAYLOAD_SIZE_BYTES_LIMIT=32*1024;// 32 KB
|
1430
1436
|
|
1431
1437
|
var INVALID_SOURCE_CONFIG_ERROR="Invalid source configuration or source id.";// ERROR
|
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
|
1438
|
+
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
|
1433
1439
|
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
|
1434
1440
|
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.");};
|
1435
1441
|
|
@@ -1438,11 +1444,11 @@
|
|
1438
1444
|
* @param event RudderEvent object
|
1439
1445
|
* @param logger Logger instance
|
1440
1446
|
* @returns stringified event payload. Empty string if error occurs.
|
1441
|
-
*/var getDeliveryPayload$1=function getDeliveryPayload(event,logger){
|
1447
|
+
*/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);};/**
|
1442
1448
|
* Utility to validate final payload size before sending to server
|
1443
1449
|
* @param event RudderEvent object
|
1444
1450
|
* @param logger Logger instance
|
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
|
1451
|
+
*/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));}};/**
|
1446
1452
|
* Filters and returns the user supplied integrations config that should take preference over the destination specific integrations config
|
1447
1453
|
* @param eventIntgConfig User supplied integrations config at event level
|
1448
1454
|
* @param destinationsIntgConfig Cumulative integrations config from all destinations
|
@@ -1470,7 +1476,7 @@
|
|
1470
1476
|
* @param events RudderEvent object array
|
1471
1477
|
* @param logger Logger instance
|
1472
1478
|
* @returns stringified events payload as Blob, undefined if error occurs.
|
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
|
1479
|
+
*/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;};
|
1474
1480
|
|
1475
1481
|
var COOKIE_STORAGE='cookieStorage';var LOCAL_STORAGE='localStorage';var SESSION_STORAGE='sessionStorage';var MEMORY_STORAGE='memoryStorage';var NO_STORAGE='none';
|
1476
1482
|
|
@@ -1481,7 +1487,7 @@
|
|
1481
1487
|
var isExceededMaxPayloadSize=Boolean(batchData&&batchData.length>MAX_BATCH_PAYLOAD_SIZE_BYTES);if(isExceededMaxPayloadSize){// Flush all previous items
|
1482
1488
|
eventsToSend=queue.slice(0,queue.length-1);this.flushQueue(eventsToSend);// Add only latest item in the remaining queue that is cleared appropriately in flushQueue
|
1483
1489
|
queue=this.getQueue();queue.push(entry);}this.setQueue(this.name,queue);// If queue has total of max items then flush
|
1484
|
-
if(queue.length===this.maxItems){this.flushQueue();}this.start();}},{key:"addItem",value:function addItem(
|
1490
|
+
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
|
1485
1491
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
1486
1492
|
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
|
1487
1493
|
beaconSendCallback(null);}else {this.nextFlushPending=true;}}}]);return BeaconItemsQueue;}();
|
@@ -1494,7 +1500,7 @@
|
|
1494
1500
|
* @param errorHandler Error handler instance
|
1495
1501
|
* @param logger Logger instance
|
1496
1502
|
* @returns BeaconItemsQueue instance
|
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
|
1503
|
+
*/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
|
1498
1504
|
done(null);}};var eventsQueue=new BeaconItemsQueue("".concat(QUEUE_NAME$2,"_").concat(writeKey,"}"),finalQOpts,queueProcessCallback,storeManager);return eventsQueue;},/**
|
1499
1505
|
* Add event to the queue for delivery
|
1500
1506
|
* @param state Application state
|
@@ -1532,15 +1538,15 @@
|
|
1532
1538
|
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
|
1533
1539
|
if(!isRudderSDKError(event)){return false;}enhanceErrorEventMutator(event,metadataSource);return true;}catch(_unused){// Drop the error event if it couldn't be filtered as
|
1534
1540
|
// it is most likely a non-SDK error
|
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.
|
1541
|
+
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
|
1536
1542
|
metaData:{SDK:{name:'JS',installType:'npm'}},beforeSend:onError(state),autoCaptureSessions:false,// auto capture sessions is disabled
|
1537
1543
|
collectUserIp:false,// collecting user's IP is disabled
|
1538
1544
|
// enabledBreadcrumbTypes: ['error', 'log', 'user'], // for v7 and above
|
1539
|
-
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
|
1545
|
+
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
|
1540
1546
|
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;};
|
1541
1547
|
|
1542
1548
|
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
|
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
|
1549
|
+
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);}}};};
|
1544
1550
|
|
1545
1551
|
var READY_CHECK_TIMEOUT_MS=11*1000;// 11 seconds
|
1546
1552
|
var SCRIPT_LOAD_TIMEOUT_MS=10*1000;// 10 seconds
|
@@ -1566,16 +1572,16 @@
|
|
1566
1572
|
* @param curDestIntgConfig Current destinations integration config
|
1567
1573
|
* @param logger Logger object
|
1568
1574
|
* @returns Combined destinations integrations config
|
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
|
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){
|
1571
|
-
logger===null||logger===void 0
|
1575
|
+
*/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
|
1576
|
+
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
|
1577
|
+
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));}};
|
1572
1578
|
|
1573
1579
|
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
|
1574
1580
|
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
|
1575
|
-
var configSupportedDestinations=state.nativeDestinations.configuredDestinations.value.filter(function(configDest){if(destDisplayNamesToFileNamesMap[configDest.displayName]){return true;}errorHandler===null||errorHandler===void 0
|
1581
|
+
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
|
1576
1582
|
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
|
1577
1583
|
(_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
|
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
|
1584
|
+
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);}});}}};};
|
1579
1585
|
|
1580
1586
|
/* 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
|
1581
1587
|
// TODO: for now this is a pass through
|
@@ -1685,6 +1691,9 @@
|
|
1685
1691
|
|
1686
1692
|
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;}();
|
1687
1693
|
|
1694
|
+
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
|
1695
|
+
var DEFAULT_MAX_BATCH_ITEMS=100;
|
1696
|
+
|
1688
1697
|
var sortByTime=function sortByTime(a,b){return a.time-b.time;};var RETRY_QUEUE='RetryQueue';/**
|
1689
1698
|
* Constructs a RetryQueue backed by localStorage
|
1690
1699
|
*
|
@@ -1692,10 +1701,11 @@
|
|
1692
1701
|
* @param {String} name The name of the queue. Will be used to find abandoned queues and retry their items
|
1693
1702
|
* @param {Object} [opts] Optional argument to override `maxItems`, `maxAttempts`, `minRetryDelay, `maxRetryDelay`, `backoffFactor` and `backoffJitter`.
|
1694
1703
|
* @param {QueueProcessCallback} fn The function to call in order to process an item added to the queue
|
1695
|
-
*/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||
|
1696
|
-
this.timeouts={
|
1697
|
-
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
|
1698
|
-
this.ack=this.ack.bind(this);this.checkReclaim=this.checkReclaim.bind(this);this.processHead=this.processHead.bind(this);this.scheduleTimeoutActive=false;}_createClass(RetryQueue,[{key:"
|
1704
|
+
*/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
|
1705
|
+
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
|
1706
|
+
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
|
1707
|
+
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
|
1708
|
+
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
|
1699
1709
|
},{key:"setQueue",value:function setQueue(name,value){this.store.set(name!==null&&name!==void 0?name:this.name,value!==null&&value!==void 0?value:[]);}/**
|
1700
1710
|
* Stops processing the queue
|
1701
1711
|
*/},{key:"stop",value:function stop(){this.schedule.cancelAll();this.scheduleTimeoutActive=false;}/**
|
@@ -1711,34 +1721,38 @@
|
|
1711
1721
|
*
|
1712
1722
|
* @param {Number} attemptNumber The attemptNumber (1 for first retry)
|
1713
1723
|
* @return {Number} The delay in milliseconds to wait before attempting a retry
|
1714
|
-
*/},{key:"getDelay",value:function getDelay(attemptNumber){var ms=this.backoff.
|
1724
|
+
*/},{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
|
1725
|
+
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
|
1726
|
+
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();}}}/**
|
1715
1727
|
* Adds an item to the queue
|
1716
1728
|
*
|
1717
|
-
* @param {Object}
|
1718
|
-
*/},{key:"addItem",value:function addItem(
|
1729
|
+
* @param {Object} itemData The item to process
|
1730
|
+
*/},{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()};}/**
|
1719
1731
|
* Adds an item to the retry queue
|
1720
1732
|
*
|
1721
|
-
* @param {Object}
|
1733
|
+
* @param {Object} itemData The item to retry
|
1722
1734
|
* @param {Number} attemptNumber The attempt number (1 for first retry)
|
1723
1735
|
* @param {Error} [error] The error from previous attempt, if there was one
|
1724
1736
|
* @param {String} [id] The id of the queued message used for tracking duplicate entries
|
1725
|
-
*/},{key:"requeue",value:function requeue(
|
1737
|
+
*/},{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
|
1726
1738
|
this.schedule.cancel(this.processId);// Pop the head off the queue
|
1727
|
-
var queue=(
|
1728
|
-
var processItemCallback=function processItemCallback(el,id){return function(err,res){var
|
1739
|
+
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
|
1740
|
+
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
|
1729
1741
|
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
|
1730
1742
|
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
|
1731
|
-
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
|
1732
|
-
queue=(
|
1733
|
-
},{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.
|
1734
|
-
addConcatQueue(their.queue,0);//
|
1743
|
+
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
|
1744
|
+
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
|
1745
|
+
},{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#
|
1746
|
+
addConcatQueue(their.queue,0);// Process batch queue items
|
1747
|
+
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
|
1748
|
+
addConcatQueue(their.batchQueue,0);}// if the queue is abandoned, all the in-progress are failed. retry them immediately and increment the attempt#
|
1735
1749
|
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
|
1736
|
-
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){
|
1750
|
+
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
|
1737
1751
|
this.processHead();}// eslint-disable-next-line class-methods-use-this
|
1738
|
-
},{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.
|
1752
|
+
},{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
|
1739
1753
|
continue;}if(parts[0]!==name){// eslint-disable-next-line no-continue
|
1740
1754
|
continue;}if(parts[2]!==QueueStatuses.ACK){// eslint-disable-next-line no-continue
|
1741
|
-
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.
|
1755
|
+
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;}();
|
1742
1756
|
|
1743
1757
|
var DEFAULT_QUEUE_OPTIONS={maxItems:100};var QUEUE_NAME$1='rudder_destinations_events';var NATIVE_DESTINATION_QUEUE_PLUGIN='NativeDestinationQueuePlugin';
|
1744
1758
|
|
@@ -1746,7 +1760,7 @@
|
|
1746
1760
|
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
|
1747
1761
|
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
|
1748
1762
|
// This will remain until we update the destinations to accept the event directly
|
1749
|
-
(_dest$instance=dest.instance)===null||_dest$instance===void 0||(_dest$instance$method=_dest$instance[methodName])===null||_dest$instance$method===void 0
|
1763
|
+
(_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));}};
|
1750
1764
|
|
1751
1765
|
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:{/**
|
1752
1766
|
* Initialize the queue for delivery to destinations
|
@@ -1757,7 +1771,7 @@
|
|
1757
1771
|
* @param logger Logger instance
|
1758
1772
|
* @returns IQueue instance
|
1759
1773
|
*/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
|
1760
|
-
"".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
|
1774
|
+
"".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
|
1761
1775
|
done(null);},storeManager,MEMORY_STORAGE);// TODO: This seems to not work as expected. Need to investigate
|
1762
1776
|
// effect(() => {
|
1763
1777
|
// if (state.nativeDestinations.clientDestinationsReady.value === true) {
|
@@ -1783,7 +1797,7 @@
|
|
1783
1797
|
|
1784
1798
|
var ONETRUST_CONSENT_MANAGER_PLUGIN='OneTrustConsentManagerPlugin';
|
1785
1799
|
|
1786
|
-
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
|
1800
|
+
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
|
1787
1801
|
// the cookie categories Ids that the user has consented to.
|
1788
1802
|
// Eg: ',C0001,C0003,'
|
1789
1803
|
// We split it and save it as an array.
|
@@ -1794,7 +1808,7 @@
|
|
1794
1808
|
// Eg:
|
1795
1809
|
// ["Performance Cookies", "Functional Cookies"]
|
1796
1810
|
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.
|
1797
|
-
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
|
1811
|
+
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;}}}};};
|
1798
1812
|
|
1799
1813
|
var KETCH_CONSENT_MANAGER_PLUGIN='KetchConsentManagerPlugin';var KETCH_CONSENT_COOKIE_NAME_V1='_ketch_consent_v1_';
|
1800
1814
|
|
@@ -1804,8 +1818,8 @@
|
|
1804
1818
|
* @param logger Logger instance
|
1805
1819
|
* @returns Consent data from the consent cookie
|
1806
1820
|
*/var getKetchConsentData=function getKetchConsentData(storeManager,logger){var rawConsentCookieData=null;try{// Create a data store instance to read the consent cookie
|
1807
|
-
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
|
1808
|
-
var consentCookieData;try{consentCookieData=JSON.parse(fromBase64(rawConsentCookieData));}catch(err){logger===null||logger===void 0
|
1821
|
+
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
|
1822
|
+
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
|
1809
1823
|
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;};/**
|
1810
1824
|
* Gets the consent data in the format expected by the application state
|
1811
1825
|
* @param ketchConsentData Consent data derived from the consent cookie
|
@@ -1821,7 +1835,7 @@
|
|
1821
1835
|
globalThis.updateKetchConsent=function(ketchConsentData){updateConsentStateFromData(state,ketchConsentData);};// retrieve consent data and update the state
|
1822
1836
|
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.
|
1823
1837
|
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.
|
1824
|
-
var containsAnyOfConsent=purposes.some(function(element){return allowedConsents.includes(element.trim());});return containsAnyOfConsent;}catch(err){errorHandler===null||errorHandler===void 0
|
1838
|
+
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;}}}};};
|
1825
1839
|
|
1826
1840
|
var ENCRYPTION_PREFIX_V3='RS_ENC_v3_';
|
1827
1841
|
|
@@ -2995,7 +3009,7 @@
|
|
2995
3009
|
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
|
2996
3010
|
// Try latest
|
2997
3011
|
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
|
2998
|
-
return JSON.parse(decryptedVal);}catch(err){errorHandler===null||errorHandler===void 0
|
3012
|
+
return JSON.parse(decryptedVal);}catch(err){errorHandler===null||errorHandler===void 0||errorHandler.onError(err,STORAGE_MIGRATOR_PLUGIN,STORAGE_MIGRATION_ERROR(key));return null;}}}};};
|
2999
3013
|
|
3000
3014
|
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
|
3001
3015
|
isRetryableNWFailure=xhrStatus===429||xhrStatus>=500&&xhrStatus<600;}return isRetryableNWFailure;};
|
@@ -3003,7 +3017,7 @@
|
|
3003
3017
|
var DEFAULT_RETRY_QUEUE_OPTIONS={maxRetryDelay:360000,minRetryDelay:1000,backoffFactor:2,maxAttempts:10,maxItems:100};var REQUEST_TIMEOUT_MS=10*1000;// 10 seconds
|
3004
3018
|
var DATA_PLANE_API_VERSION='v1';var QUEUE_NAME='rudder';var XHR_QUEUE_PLUGIN='XhrQueuePlugin';
|
3005
3019
|
|
3006
|
-
var getNormalizedQueueOptions=function getNormalizedQueueOptions(queueOpts){return mergeDeepRight(DEFAULT_RETRY_QUEUE_OPTIONS,queueOpts);};var getDeliveryUrl=function getDeliveryUrl(dataplaneUrl,
|
3020
|
+
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};};
|
3007
3021
|
|
3008
3022
|
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:{/**
|
3009
3023
|
* Initialize the queue for delivery
|
@@ -3014,9 +3028,8 @@
|
|
3014
3028
|
* @param logger Logger instance
|
3015
3029
|
* @returns RetryQueue instance
|
3016
3030
|
*/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
|
3017
|
-
"".concat(QUEUE_NAME,"_").concat(writeKey),finalQOpts,function(
|
3018
|
-
var queueErrResp=isErrRetryable(details)?details:null;logErrorOnFailure(details,
|
3019
|
-
done(null);}},storeManager);return eventsQueue;},/**
|
3031
|
+
"".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
|
3032
|
+
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;},/**
|
3020
3033
|
* Add event to the queue for delivery
|
3021
3034
|
* @param state Application state
|
3022
3035
|
* @param eventsQueue RetryQueue instance
|
@@ -3060,7 +3073,7 @@
|
|
3060
3073
|
},{key:"getPluginsToLoadBasedOnConfig",value:function getPluginsToLoadBasedOnConfig(){var _state$nativeDestinat;// This contains the default plugins if load option has been omitted by user
|
3061
3074
|
var pluginsToLoadFromConfig=state.plugins.pluginsToLoadFromConfig.value;if(!pluginsToLoadFromConfig){return [];}// Error reporting related plugins
|
3062
3075
|
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
|
3063
|
-
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
|
3076
|
+
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
|
3064
3077
|
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
|
3065
3078
|
var supportedConsentManagerPlugins=Object.values(ConsentManagersToPluginNameMap);pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return !(pluginName!==state.consents.activeConsentManagerPluginName.value&&supportedConsentManagerPlugins.includes(pluginName));});// Storage encryption related plugins
|
3066
3079
|
var supportedStorageEncryptionPlugins=Object.values(StorageEncryptionVersionsToPluginNameMap);pluginsToLoadFromConfig=pluginsToLoadFromConfig.filter(function(pluginName){return !(pluginName!==state.storage.encryptionPluginName.value&&supportedStorageEncryptionPlugins.includes(pluginName));});// Storage migrator related plugins
|
@@ -3107,7 +3120,7 @@
|
|
3107
3120
|
* Implement requests in a non-blocking way
|
3108
3121
|
*/},{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);}});}/**
|
3109
3122
|
* Handle errors
|
3110
|
-
*/},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0
|
3123
|
+
*/},{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;}}/**
|
3111
3124
|
* Set basic authentication header (eg writekey)
|
3112
3125
|
*/},{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);}/**
|
3113
3126
|
* Clear basic authentication header
|
@@ -3127,7 +3140,7 @@
|
|
3127
3140
|
|
3128
3141
|
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\./));};
|
3129
3142
|
|
3130
|
-
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
|
3143
|
+
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();});}};
|
3131
3144
|
|
3132
3145
|
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;};
|
3133
3146
|
|
@@ -3138,24 +3151,26 @@
|
|
3138
3151
|
var isQuotaExceededError=matchingNames.includes(e.name)||matchingCodes.includes(e.code);return e instanceof DOMException&&isQuotaExceededError;};// TODO: also check for SecurityErrors
|
3139
3152
|
// https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage#exceptions
|
3140
3153
|
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
|
3141
|
-
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
|
3154
|
+
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;}};
|
3142
3155
|
|
3143
3156
|
/**
|
3144
3157
|
* Encode.
|
3145
|
-
*/var encode=function encode(value){return encodeURIComponent(value);};/**
|
3158
|
+
*/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;}};/**
|
3146
3159
|
* Decode
|
3147
|
-
*/var decode=function decode(value){return decodeURIComponent(value);}
|
3160
|
+
*/var decode=function decode(value){try{return decodeURIComponent(value);}catch(err){// Do nothing as non-RS SDK cookies may not be URI encoded
|
3161
|
+
return undefined;}};/**
|
3148
3162
|
* Parse cookie `str`
|
3149
|
-
*/var parse=function parse(str){var obj={};var pairs=str.split(/\s*;\s*/);var pair;if(!pairs[0]){return obj;}
|
3163
|
+
*/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
|
3164
|
+
pairs.forEach(function(pairItem){pair=pairItem.split('=');var keyName=decode(pair[0]);if(keyName){obj[keyName]=decode(pair[1]);}});return obj;};/**
|
3150
3165
|
* Set cookie `name` to `value`
|
3151
|
-
*/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;};/**
|
3166
|
+
*/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;};/**
|
3152
3167
|
* Return all cookies
|
3153
3168
|
*/var all=function all(){var cookieStringValue=globalThis.document.cookie;return parse(cookieStringValue);};/**
|
3154
3169
|
* Get cookie `name`
|
3155
3170
|
*/var get=function get(name){return all()[name];};/**
|
3156
3171
|
* Set or get cookie `name` with `value` and `options` object
|
3157
3172
|
*/ // eslint-disable-next-line func-names
|
3158
|
-
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();}};
|
3173
|
+
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();}};
|
3159
3174
|
|
3160
3175
|
var legacyGetHostname=function legacyGetHostname(href){var l=document.createElement('a');l.href=href;return l.hostname;};/**
|
3161
3176
|
* Levels returns all levels of the given url
|
@@ -3185,7 +3200,7 @@
|
|
3185
3200
|
/**
|
3186
3201
|
* A storage utility to persist values in cookies via Storage interface
|
3187
3202
|
*/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
|
3188
|
-
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
|
3203
|
+
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
|
3189
3204
|
},{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
|
3190
3205
|
},{key:"clear",value:function clear(){// Not implemented
|
3191
3206
|
// getting a list of all cookie storage keys and remove all values
|
@@ -3243,7 +3258,7 @@
|
|
3243
3258
|
_this.remove(key);});this.engine=inMemoryStorage;}/**
|
3244
3259
|
* Set value by key.
|
3245
3260
|
*/},{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
|
3246
|
-
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
|
3261
|
+
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
|
3247
3262
|
this.swapQueueStoreToInMemoryEngine();// and save it there
|
3248
3263
|
this.set(key,value);}else {this.onError(getMutatedError(err,STORE_DATA_SAVE_ERROR(key)));}}}/**
|
3249
3264
|
* Get by Key.
|
@@ -3260,7 +3275,7 @@
|
|
3260
3275
|
* Extension point to use with encryption plugins
|
3261
3276
|
*/},{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:'';}/**
|
3262
3277
|
* Handle errors
|
3263
|
-
*/},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0
|
3278
|
+
*/},{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;}();
|
3264
3279
|
|
3265
3280
|
/**
|
3266
3281
|
* A service to manage stores & available storage client configurations
|
@@ -3269,7 +3284,7 @@
|
|
3269
3284
|
*/_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;}/**
|
3270
3285
|
* Create store to persist data used by the SDK like session, used details etc
|
3271
3286
|
*/},{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
|
3272
|
-
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
|
3287
|
+
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
|
3273
3288
|
// TODO: should we pass the keys for all in order to validate or leave free as v1.1?
|
3274
3289
|
if(finalStorageType!==NO_STORAGE){this.setStore({id:CLIENT_DATA_STORE_NAME,name:CLIENT_DATA_STORE_NAME,isEncrypted:true,noCompoundKey:true,type:finalStorageType});}}/**
|
3275
3290
|
* Create a new store
|
@@ -3277,7 +3292,7 @@
|
|
3277
3292
|
* Retrieve a store
|
3278
3293
|
*/},{key:"getStore",value:function getStore(id){return this.stores[id];}/**
|
3279
3294
|
* Handle errors
|
3280
|
-
*/},{key:"onError",value:function onError(error){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0
|
3295
|
+
*/},{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;}();
|
3281
3296
|
|
3282
3297
|
/**
|
3283
3298
|
* Removes trailing slash from url
|
@@ -3325,7 +3340,10 @@
|
|
3325
3340
|
*/var isPositiveInteger=function isPositiveInteger(num){return isNumber(num)&&num>=0&&Number.isInteger(num);};
|
3326
3341
|
|
3327
3342
|
var normalizeLoadOptions=function normalizeLoadOptions(loadOptionsFromState,loadOptions){var _normalizedLoadOpts$p;// TODO: Maybe add warnings for invalid values
|
3328
|
-
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=''
|
3343
|
+
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
|
3344
|
+
// doesn't seem to throw errors for empty URLs
|
3345
|
+
// TODO: Need to improve this check to find out if the URL is valid or not
|
3346
|
+
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);};
|
3329
3347
|
|
3330
3348
|
/**
|
3331
3349
|
* A function to filter enabled destinations and map to required properties only
|
@@ -3338,7 +3356,7 @@
|
|
3338
3356
|
* A function to get url from source config response
|
3339
3357
|
* @param {array} urls An array of objects containing urls
|
3340
3358
|
* @returns
|
3341
|
-
*/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
|
3359
|
+
*/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;};/**
|
3342
3360
|
* A function to determine the dataPlaneUrl
|
3343
3361
|
* @param {Object} dataplanes An object containing dataPlaneUrl for different region
|
3344
3362
|
* @param {String} serverUrl dataPlaneUrl provided in the load call
|
@@ -3362,9 +3380,9 @@
|
|
3362
3380
|
* @param logger Logger instance
|
3363
3381
|
*/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
|
3364
3382
|
var errReportingProviderPlugin=errReportingProvider?ErrorReportingProvidersToPluginNameMap[errReportingProvider]:undefined;if(!isUndefined(errReportingProvider)&&!errReportingProviderPlugin){// set the default error reporting provider
|
3365
|
-
logger===null||logger===void 0
|
3366
|
-
logger===null||logger===void 0
|
3367
|
-
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
|
3383
|
+
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
|
3384
|
+
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
|
3385
|
+
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));}});};
|
3368
3386
|
|
3369
3387
|
/**
|
3370
3388
|
* A function that determines integration SDK loading path
|
@@ -3397,19 +3415,19 @@
|
|
3397
3415
|
* Output: 'oneTrust'
|
3398
3416
|
*/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;});};
|
3399
3417
|
|
3400
|
-
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
|
3418
|
+
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);});}/**
|
3401
3419
|
* A function to validate, construct and store loadOption, lifecycle, source and destination
|
3402
3420
|
* config related information in global state
|
3403
3421
|
*/},{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
|
3404
3422
|
var intgCdnUrl=getIntegrationsCDNPath(APP_VERSION,lockIntegrationsVersion,state.loadOptions.value.destSDKBaseURL);// determine the path to fetch remote plugins from
|
3405
3423
|
var pluginsCDNPath=getPluginsCDNPath(state.loadOptions.value.pluginsSDKBaseURL);// Get the consent manager if provided as load option
|
3406
3424
|
var selectedConsentManager=getUserSelectedConsentManager(state.loadOptions.value.cookieConsentManager);if(selectedConsentManager){// Get the corresponding plugin name of the selected consent manager from the supported consent managers
|
3407
|
-
consentManagerPluginName=ConsentManagersToPluginNameMap[selectedConsentManager];if(!consentManagerPluginName){var _this$logger2;(_this$logger2=this.logger)===null||_this$logger2===void 0
|
3408
|
-
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;}
|
3425
|
+
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
|
3426
|
+
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
|
3409
3427
|
state.consents.activeConsentManagerPluginName.value=consentManagerPluginName;// set storage type in state
|
3410
|
-
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
|
3428
|
+
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();}/**
|
3411
3429
|
* Handle errors
|
3412
|
-
*/},{key:"onError",value:function onError(error,customMessage,shouldAlwaysThrow){if(this.hasErrorHandler){var _this$errorHandler;(_this$errorHandler=this.errorHandler)===null||_this$errorHandler===void 0
|
3430
|
+
*/},{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;}}/**
|
3413
3431
|
* A callback function that is executed once we fetch the source config response.
|
3414
3432
|
* Use to construct and store information that are dependent on the sourceConfig.
|
3415
3433
|
*/},{key:"processConfig",value:function processConfig(response,details){var _this3=this;// TODO: add retry logic with backoff based on rejectionDetails.xhr.status
|
@@ -3460,13 +3478,12 @@
|
|
3460
3478
|
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
|
3461
3479
|
b(function(){if(state.loadOptions.value.sendAdblockPage===true&&state.lifecycle.sourceConfigUrl.value!==undefined){detectAdBlockers(_this.errorHandler,_this.logger);}});}/**
|
3462
3480
|
* 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
|
3481
|
+
*/},{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
|
3482
|
+
// NOTE: we're not putting this into RudderStackGlobals as providing the property path to the callback function in the polyfill URL is not possible
|
3483
|
+
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
3484
|
* Attach listeners to window to observe event that update capabilities state values
|
3467
3485
|
*/ // eslint-disable-next-line class-methods-use-this
|
3468
|
-
},{key:"attachWindowListeners",value:function attachWindowListeners(){globalThis.addEventListener('offline',function(){state.capabilities.isOnline.value=false;});globalThis.addEventListener('online',function(){state.capabilities.isOnline.value=true;})
|
3469
|
-
}/**
|
3486
|
+
},{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
3487
|
* Set the lifecycle status to next phase
|
3471
3488
|
*/ // eslint-disable-next-line class-methods-use-this
|
3472
3489
|
},{key:"onReady",value:function onReady(){this.detectBrowserCapabilities();state.lifecycle.status.value=LifecycleStatus.BrowserCapabilitiesReady;}/**
|
@@ -3496,7 +3513,7 @@
|
|
3496
3513
|
* @param eventType Rudder event type
|
3497
3514
|
* @param parentKeyPath Object's parent key path
|
3498
3515
|
* @param logger Logger instance
|
3499
|
-
*/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
|
3516
|
+
*/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));}});}};/**
|
3500
3517
|
* Checks for reserved keys in traits, properties, and contextual traits
|
3501
3518
|
* @param rudderEvent Generated rudder event
|
3502
3519
|
* @param logger Logger instance
|
@@ -3513,7 +3530,7 @@
|
|
3513
3530
|
* @param rudderContext Generated rudder event
|
3514
3531
|
* @param options API options
|
3515
3532
|
* @param logger Logger instance
|
3516
|
-
*/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
|
3533
|
+
*/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;};/**
|
3517
3534
|
* A function to determine whether SDK should use the integration option provided in load call
|
3518
3535
|
* @returns boolean
|
3519
3536
|
*/var shouldUseGlobalIntegrationsConfigInEvents=function shouldUseGlobalIntegrationsConfigInEvents(){return state.loadOptions.value.useGlobalIntegrationsConfigInEvents&&isObjectLiteralAndNotNull(state.nativeDestinations.loadOnlyIntegrations.value);};/**
|
@@ -3533,8 +3550,7 @@
|
|
3533
3550
|
* @param pageProps Page properties
|
3534
3551
|
* @param logger logger
|
3535
3552
|
* @returns Enriched RudderEvent object
|
3536
|
-
*/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
|
3537
|
-
screen:getScreenDetails(),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
|
3553
|
+
*/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
|
3538
3554
|
commonEventData.anonymousId=generateUUID();commonEventData.context.anonymousTracking=true;}else {// Type casting to string as the user session manager will take care of initializing the value
|
3539
3555
|
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
|
3540
3556
|
// matching with v1.1 payload
|
@@ -3599,7 +3615,7 @@
|
|
3599
3615
|
* Function to validate user provided sessionId
|
3600
3616
|
* @param {number} sessionId
|
3601
3617
|
* @returns
|
3602
|
-
*/var isManualSessionIdValid=function isManualSessionIdValid(sessionId,logger){if(!sessionId||!isPositiveInteger(sessionId)||!hasMinLength(MIN_SESSION_ID_LENGTH,sessionId)){logger===null||logger===void 0
|
3618
|
+
*/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;};/**
|
3603
3619
|
* A function to generate new auto tracking session
|
3604
3620
|
* @param sessionTimeout current timestamp
|
3605
3621
|
* @returns SessionInfo
|
@@ -3622,9 +3638,9 @@
|
|
3622
3638
|
this.initializeSessionTracking();// Register the effect to sync with storage
|
3623
3639
|
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);});}/**
|
3624
3640
|
* A function to initialize sessionTracking
|
3625
|
-
*/},{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
|
3641
|
+
*/},{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
|
3626
3642
|
// and will proceed with it
|
3627
|
-
if(sessionTimeout>0&&sessionTimeout<MIN_SESSION_TIMEOUT_MS){var _this$logger3;(_this$logger3=this.logger)===null||_this$logger3===void 0
|
3643
|
+
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
|
3628
3644
|
if(state.session.sessionInfo.value.autoTrack){this.startOrRenewAutoTracking();}}/**
|
3629
3645
|
* Handles error
|
3630
3646
|
* @param error The error object
|
@@ -3632,7 +3648,7 @@
|
|
3632
3648
|
* A function to sync values in storage
|
3633
3649
|
* @param key
|
3634
3650
|
* @param value
|
3635
|
-
*/},{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
|
3651
|
+
*/},{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);}}/**
|
3636
3652
|
* Function to update storage whenever state value changes
|
3637
3653
|
*/},{key:"registerEffects",value:function registerEffects(){var _this2=this;/**
|
3638
3654
|
* Update userId in storage automatically when userId is updated in state
|
@@ -3726,7 +3742,7 @@
|
|
3726
3742
|
*/},{key:"end",value:function end(){state.session.sessionInfo.value={};}/**
|
3727
3743
|
* Clear storage
|
3728
3744
|
* @param resetAnonymousId
|
3729
|
-
*/},{key:"clearUserSessionStorage",value:function clearUserSessionStorage(resetAnonymousId){var _this$store12,_this$store13,_this$store14,_this$store15;(_this$store12=this.store)===null||_this$store12===void 0
|
3745
|
+
*/},{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;}();
|
3730
3746
|
|
3731
3747
|
/**
|
3732
3748
|
* A buffer queue to serve as a store for any type of data
|
@@ -3745,19 +3761,19 @@
|
|
3745
3761
|
*/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);}/**
|
3746
3762
|
* Initializes the event repository
|
3747
3763
|
*/_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
|
3748
|
-
b(function(){if(state.nativeDestinations.clientDestinationsReady.value===true){_this.destinationsEventsQueue.start();}})
|
3749
|
-
* Enqueues the event for processing
|
3750
|
-
* @param event RudderEvent object
|
3751
|
-
* @param callback API callback function
|
3752
|
-
*/},{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
|
3764
|
+
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
|
3753
3765
|
// However, events will be enqueued for now.
|
3754
3766
|
// At the time of processing the events, the integrations config data from destinations
|
3755
3767
|
// is merged into the event object
|
3756
|
-
b(function(){var
|
3757
|
-
if(state.loadOptions.value.bufferDataPlaneEventsUntilReady===true){globalThis.setTimeout(function(){var
|
3768
|
+
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
|
3769
|
+
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);}}/**
|
3770
|
+
* Enqueues the event for processing
|
3771
|
+
* @param event RudderEvent object
|
3772
|
+
* @param callback API callback function
|
3773
|
+
*/},{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
|
3758
3774
|
try{// Using the event sent to the data plane queue here
|
3759
3775
|
// to ensure the mutated (if any) event is sent to the callback
|
3760
|
-
callback===null||callback===void 0
|
3776
|
+
callback===null||callback===void 0||callback(dpQEvent);}catch(error){this.onError(error,API_CALLBACK_INVOKE_ERROR);}}/**
|
3761
3777
|
* Handles error
|
3762
3778
|
* @param error The error object
|
3763
3779
|
* @param customMessage a message
|
@@ -3787,15 +3803,15 @@
|
|
3787
3803
|
* Process the buffer preloaded events by passing their arguments to the respective facade methods
|
3788
3804
|
*/},{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);}/**
|
3789
3805
|
* Load configuration
|
3790
|
-
*/},{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
|
3806
|
+
*/},{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();}/**
|
3791
3807
|
* Initialize the storage and event queue
|
3792
3808
|
*/},{key:"init",value:function init(){var _this$storeManager,_this$storeManager2,_this$userSessionMana,_this$eventManager;this.errorHandler.init(this.externalSrcLoader);// Initialize storage
|
3793
|
-
(_this$storeManager=this.storeManager)===null||_this$storeManager===void 0
|
3794
|
-
if(state.consents.activeConsentManagerPluginName.value){var _this$pluginsManager;(_this$pluginsManager=this.pluginsManager)===null||_this$pluginsManager===void 0
|
3795
|
-
(_this$eventManager=this.eventManager)===null||_this$eventManager===void 0
|
3809
|
+
(_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
|
3810
|
+
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
|
3811
|
+
(_this$eventManager=this.eventManager)===null||_this$eventManager===void 0||_this$eventManager.init();// Mark the SDK as initialized
|
3796
3812
|
state.lifecycle.status.value=LifecycleStatus.Initialized;}/**
|
3797
3813
|
* Load plugins
|
3798
|
-
*/},{key:"loadPlugins",value:function loadPlugins(){var _this$pluginsManager2;(_this$pluginsManager2=this.pluginsManager)===null||_this$pluginsManager2===void 0
|
3814
|
+
*/},{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?
|
3799
3815
|
// registerCustomPlugins(state.loadOptions.value.customPlugins);
|
3800
3816
|
}/**
|
3801
3817
|
* Trigger onLoaded callback if any is provided in config & emit initialised event
|
@@ -3815,8 +3831,8 @@
|
|
3815
3831
|
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=[];}/**
|
3816
3832
|
* Load device mode destinations
|
3817
3833
|
*/},{key:"loadDestinations",value:function loadDestinations(){var _this$pluginsManager3,_this$pluginsManager4;// Set in state the desired activeDestinations to inject in DOM
|
3818
|
-
(_this$pluginsManager3=this.pluginsManager)===null||_this$pluginsManager3===void 0
|
3819
|
-
state.lifecycle.status.value=LifecycleStatus.DestinationsLoading;(_this$pluginsManager4=this.pluginsManager)===null||_this$pluginsManager4===void 0
|
3834
|
+
(_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
|
3835
|
+
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
|
3820
3836
|
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;});}});}/**
|
3821
3837
|
* Invoke the ready callbacks if any exist
|
3822
3838
|
*/ // eslint-disable-next-line class-methods-use-this
|
@@ -3826,20 +3842,20 @@
|
|
3826
3842
|
* If destinations are loaded or no integration is available for loading
|
3827
3843
|
* execute the callback immediately else push the callbacks to a queue that
|
3828
3844
|
* will be executed after loading completes
|
3829
|
-
*/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
|
3845
|
+
*/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.
|
3830
3846
|
// Send automatic ad blocked page event if adblockers are detected on the page
|
3831
3847
|
// Check page category to avoid infinite loop
|
3832
3848
|
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
|
3833
3849
|
// in v3 implementation
|
3834
|
-
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
|
3835
|
-
if(!isNull(payload.userId)){var _this$userSessionMana2;(_this$userSessionMana2=this.userSessionManager)===null||_this$userSessionMana2===void 0
|
3836
|
-
if(!isNull(payload.groupId)){var _this$userSessionMana6;(_this$userSessionMana6=this.userSessionManager)===null||_this$userSessionMana6===void 0
|
3837
|
-
if(!state.lifecycle.loaded.value){state.eventBuffer.toBeProcessedArray.value.push([type,anonymousId,rudderAmpLinkerParam]);return;}(_this$userSessionMana10=this.userSessionManager)===null||_this$userSessionMana10===void 0
|
3850
|
+
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
|
3851
|
+
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
|
3852
|
+
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
|
3853
|
+
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
|
3838
3854
|
},{key:"getUserId",value:function getUserId(){return state.session.userId.value;}// eslint-disable-next-line class-methods-use-this
|
3839
3855
|
},{key:"getUserTraits",value:function getUserTraits(){return state.session.userTraits.value;}// eslint-disable-next-line class-methods-use-this
|
3840
3856
|
},{key:"getGroupId",value:function getGroupId(){return state.session.groupId.value;}// eslint-disable-next-line class-methods-use-this
|
3841
|
-
},{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
|
3842
|
-
},{key:"getSessionId",value:function getSessionId(){var _this$userSessionMana13,_state$session$sessio,_state$session$sessio2;(_this$userSessionMana13=this.userSessionManager)===null||_this$userSessionMana13===void 0
|
3857
|
+
},{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
|
3858
|
+
},{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
|
3843
3859
|
}]);return Analytics;}();
|
3844
3860
|
|
3845
3861
|
/*
|