@snowplow/react-native-tracker 4.0.2-dev.0 → 4.0.2-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/dist/commonjs/event_store.js +150 -0
  2. package/dist/commonjs/event_store.js.map +1 -0
  3. package/dist/commonjs/events.js +42 -0
  4. package/dist/commonjs/events.js.map +1 -0
  5. package/dist/commonjs/index.js +29 -0
  6. package/dist/commonjs/index.js.map +1 -0
  7. package/dist/commonjs/subject.js +82 -0
  8. package/dist/commonjs/subject.js.map +1 -0
  9. package/dist/commonjs/tracker.js +77 -0
  10. package/dist/commonjs/tracker.js.map +1 -0
  11. package/dist/commonjs/types.js +223 -0
  12. package/dist/commonjs/types.js.map +1 -0
  13. package/dist/module/event_store.js +145 -0
  14. package/dist/module/event_store.js.map +1 -0
  15. package/dist/module/events.js +38 -0
  16. package/dist/module/events.js.map +1 -0
  17. package/dist/module/index.js +7 -0
  18. package/dist/module/index.js.map +1 -0
  19. package/dist/module/subject.js +78 -0
  20. package/dist/module/subject.js.map +1 -0
  21. package/dist/module/tracker.js +74 -0
  22. package/dist/module/tracker.js.map +1 -0
  23. package/dist/module/types.js +73 -0
  24. package/dist/module/types.js.map +1 -0
  25. package/dist/typescript/commonjs/package.json +1 -0
  26. package/dist/typescript/commonjs/src/event_store.d.ts +4 -0
  27. package/dist/typescript/commonjs/src/event_store.d.ts.map +1 -0
  28. package/dist/typescript/commonjs/src/events.d.ts +10 -0
  29. package/dist/typescript/commonjs/src/events.d.ts.map +1 -0
  30. package/dist/typescript/commonjs/src/index.d.ts +4 -0
  31. package/dist/typescript/commonjs/src/index.d.ts.map +1 -0
  32. package/dist/typescript/commonjs/src/subject.d.ts +19 -0
  33. package/dist/typescript/commonjs/src/subject.d.ts.map +1 -0
  34. package/dist/typescript/commonjs/src/tracker.d.ts +9 -0
  35. package/dist/typescript/commonjs/src/tracker.d.ts.map +1 -0
  36. package/dist/{index.cjs.d.ts → typescript/commonjs/src/types.d.ts} +18 -65
  37. package/dist/typescript/commonjs/src/types.d.ts.map +1 -0
  38. package/dist/typescript/module/package.json +1 -0
  39. package/dist/typescript/module/src/event_store.d.ts +4 -0
  40. package/dist/typescript/module/src/event_store.d.ts.map +1 -0
  41. package/dist/typescript/module/src/events.d.ts +10 -0
  42. package/dist/typescript/module/src/events.d.ts.map +1 -0
  43. package/dist/typescript/module/src/index.d.ts +4 -0
  44. package/dist/typescript/module/src/index.d.ts.map +1 -0
  45. package/dist/typescript/module/src/subject.d.ts +19 -0
  46. package/dist/typescript/module/src/subject.d.ts.map +1 -0
  47. package/dist/typescript/module/src/tracker.d.ts +9 -0
  48. package/dist/typescript/module/src/tracker.d.ts.map +1 -0
  49. package/dist/{index.module.d.ts → typescript/module/src/types.d.ts} +18 -65
  50. package/dist/typescript/module/src/types.d.ts.map +1 -0
  51. package/package.json +52 -14
  52. package/dist/index.cjs.js +0 -2656
  53. package/dist/index.cjs.js.map +0 -1
  54. package/dist/index.cjs.min.d.ts +0 -499
  55. package/dist/index.cjs.min.js +0 -63
  56. package/dist/index.cjs.min.js.map +0 -1
  57. package/dist/index.module.js +0 -250
  58. package/dist/index.module.js.map +0 -1
package/dist/index.cjs.js DELETED
@@ -1,2656 +0,0 @@
1
- /*!
2
- * React Native tracker for Snowplow v4.0.2-dev.0 (https://docs.snowplow.io/docs/collecting-data/collecting-from-own-applications/javascript-trackers/)
3
- * Copyright 2022 Snowplow Analytics Ltd, 2010 Anthon Pang
4
- * Licensed under BSD-3-Clause
5
- */
6
-
7
- (function (global, factory) {
8
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
9
- typeof define === 'function' && define.amd ? define(['exports'], factory) :
10
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.snowplowBrowserTracking = {}));
11
- })(this, (function (exports) { 'use strict';
12
-
13
- /******************************************************************************
14
- Copyright (c) Microsoft Corporation.
15
-
16
- Permission to use, copy, modify, and/or distribute this software for any
17
- purpose with or without fee is hereby granted.
18
-
19
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
20
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
21
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
22
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
23
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
24
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
25
- PERFORMANCE OF THIS SOFTWARE.
26
- ***************************************************************************** */
27
-
28
- var __assign = function() {
29
- __assign = Object.assign || function __assign(t) {
30
- for (var s, i = 1, n = arguments.length; i < n; i++) {
31
- s = arguments[i];
32
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
33
- }
34
- return t;
35
- };
36
- return __assign.apply(this, arguments);
37
- };
38
-
39
- function __awaiter(thisArg, _arguments, P, generator) {
40
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
41
- return new (P || (P = Promise))(function (resolve, reject) {
42
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
43
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
44
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
45
- step((generator = generator.apply(thisArg, _arguments || [])).next());
46
- });
47
- }
48
-
49
- function __generator(thisArg, body) {
50
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
51
- return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
52
- function verb(n) { return function (v) { return step([n, v]); }; }
53
- function step(op) {
54
- if (f) throw new TypeError("Generator is already executing.");
55
- while (g && (g = 0, op[0] && (_ = 0)), _) try {
56
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
57
- if (y = 0, t) op = [op[0] & 2, t.value];
58
- switch (op[0]) {
59
- case 0: case 1: t = op; break;
60
- case 4: _.label++; return { value: op[1], done: false };
61
- case 5: _.label++; y = op[1]; op = [0]; continue;
62
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
63
- default:
64
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
65
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
66
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
67
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
68
- if (t[2]) _.ops.pop();
69
- _.trys.pop(); continue;
70
- }
71
- op = body.call(thisArg, _);
72
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
73
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
74
- }
75
- }
76
-
77
- function __spreadArray(to, from, pack) {
78
- if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
79
- if (ar || !(i in from)) {
80
- if (!ar) ar = Array.prototype.slice.call(from, 0, i);
81
- ar[i] = from[i];
82
- }
83
- }
84
- return to.concat(ar || Array.prototype.slice.call(from));
85
- }
86
-
87
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
88
- var e = new Error(message);
89
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
90
- };
91
-
92
- /**
93
- * Convert array of 16 byte values to UUID string format of the form:
94
- * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
95
- */
96
- var byteToHex = [];
97
- for (var i = 0; i < 256; ++i) {
98
- byteToHex.push((i + 0x100).toString(16).slice(1));
99
- }
100
- function unsafeStringify(arr, offset = 0) {
101
- // Note: Be careful editing this code! It's been tuned for performance
102
- // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
103
- //
104
- // Note to future-self: No, you can't remove the `toLowerCase()` call.
105
- // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351
106
- return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
107
- }
108
-
109
- // Unique ID creation requires a high quality random # generator. In the browser we therefore
110
- // require the crypto API and do not support built-in fallback to lower quality random number
111
- // generators (like Math.random()).
112
-
113
- var getRandomValues;
114
- var rnds8 = new Uint8Array(16);
115
- function rng() {
116
- // lazy load so that environments that need to polyfill have a chance to do so
117
- if (!getRandomValues) {
118
- // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
119
- getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
120
- if (!getRandomValues) {
121
- throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
122
- }
123
- }
124
- return getRandomValues(rnds8);
125
- }
126
-
127
- var randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
128
- var native = {
129
- randomUUID
130
- };
131
-
132
- function v4(options, buf, offset) {
133
- if (native.randomUUID && !buf && !options) {
134
- return native.randomUUID();
135
- }
136
- options = options || {};
137
- var rnds = options.random || (options.rng || rng)();
138
-
139
- // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
140
- rnds[6] = rnds[6] & 0x0f | 0x40;
141
- rnds[8] = rnds[8] & 0x3f | 0x80;
142
-
143
- // Copy bytes to buffer, if provided
144
- if (buf) {
145
- offset = offset || 0;
146
- for (var i = 0; i < 16; ++i) {
147
- buf[offset + i] = rnds[i];
148
- }
149
- return buf;
150
- }
151
- return unsafeStringify(rnds);
152
- }
153
-
154
- /*!
155
- * Core functionality for Snowplow JavaScript trackers v4.0.2-dev.0 (http://bit.ly/sp-js)
156
- * Copyright 2022 Snowplow Analytics Ltd, 2010 Anthon Pang
157
- * Licensed under BSD-3-Clause
158
- */
159
-
160
- var version$1 = "4.0.2-dev.0";
161
-
162
- /*
163
- * Copyright (c) 2013 Kevin van Zonneveld (http://kvz.io)
164
- * and Contributors (http://phpjs.org/authors)
165
- *
166
- * Permission is hereby granted, free of charge, to any person obtaining a copy of
167
- * this software and associated documentation files (the "Software"), to deal in
168
- * the Software without restriction, including without limitation the rights to
169
- * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
170
- * of the Software, and to permit persons to whom the Software is furnished to do
171
- * so, subject to the following conditions:
172
- *
173
- * The above copyright notice and this permission notice shall be included in all
174
- * copies or substantial portions of the Software.
175
- *
176
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
177
- * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
178
- * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
179
- * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
180
- * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
181
- * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
182
- * SOFTWARE.
183
- */
184
- /**
185
- * Decodes a url safe Base 64 encoded string
186
- * @remarks See: {@link http://tools.ietf.org/html/rfc4648#page-7}
187
- * @param data - String to decode
188
- * @returns The decoded string
189
- */
190
- function base64urldecode(data) {
191
- if (!data) {
192
- return data;
193
- }
194
- var padding = 4 - (data.length % 4);
195
- switch (padding) {
196
- case 2:
197
- data += '==';
198
- break;
199
- case 3:
200
- data += '=';
201
- break;
202
- }
203
- var b64Data = data.replace(/-/g, '+').replace(/_/g, '/');
204
- return base64decode(b64Data);
205
- }
206
- /**
207
- * Encodes a string into a url safe Base 64 encoded string
208
- * @remarks See: {@link http://tools.ietf.org/html/rfc4648#page-7}
209
- * @param data - String to encode
210
- * @returns The url safe Base 64 string
211
- */
212
- function base64urlencode(data) {
213
- if (!data) {
214
- return data;
215
- }
216
- var enc = base64encode(data);
217
- return enc.replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
218
- }
219
- var b64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
220
- /**
221
- * Encode string as base64.
222
- * Any type can be passed, but will be stringified
223
- *
224
- * @param data - string to encode
225
- * @returns base64-encoded string
226
- */
227
- function base64encode(data) {
228
- // discuss at: http://phpjs.org/functions/base64_encode/
229
- // original by: Tyler Akins (http://rumkin.com)
230
- // improved by: Bayron Guevara
231
- // improved by: Thunder.m
232
- // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
233
- // improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
234
- // improved by: Rafał Kukawski (http://kukawski.pl)
235
- // bugfixed by: Pellentesque Malesuada
236
- // example 1: base64_encode('Kevin van Zonneveld');
237
- // returns 1: 'S2V2aW4gdmFuIFpvbm5ldmVsZA=='
238
- // example 2: base64_encode('a');
239
- // returns 2: 'YQ=='
240
- // example 3: base64_encode('✓ à la mode');
241
- // returns 3: '4pyTIMOgIGxhIG1vZGU='
242
- var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0;
243
- var tmp_arr = [];
244
- if (!data) {
245
- return data;
246
- }
247
- data = unescape(encodeURIComponent(data));
248
- do {
249
- // pack three octets into four hexets
250
- o1 = data.charCodeAt(i++);
251
- o2 = data.charCodeAt(i++);
252
- o3 = data.charCodeAt(i++);
253
- bits = (o1 << 16) | (o2 << 8) | o3;
254
- h1 = (bits >> 18) & 0x3f;
255
- h2 = (bits >> 12) & 0x3f;
256
- h3 = (bits >> 6) & 0x3f;
257
- h4 = bits & 0x3f;
258
- // use hexets to index into b64, and append result to encoded string
259
- tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
260
- } while (i < data.length);
261
- var enc = tmp_arr.join('');
262
- var r = data.length % 3;
263
- return (r ? enc.slice(0, r - 3) : enc) + '==='.slice(r || 3);
264
- }
265
- /**
266
- * Decode base64 to string
267
- *
268
- * @param data - base64 to string
269
- * @returns decoded string
270
- */
271
- function base64decode(encodedData) {
272
- // discuss at: http://locutus.io/php/base64_decode/
273
- // original by: Tyler Akins (http://rumkin.com)
274
- // improved by: Thunder.m
275
- // improved by: Kevin van Zonneveld (http://kvz.io)
276
- // improved by: Kevin van Zonneveld (http://kvz.io)
277
- // input by: Aman Gupta
278
- // input by: Brett Zamir (http://brett-zamir.me)
279
- // bugfixed by: Onno Marsman (https://twitter.com/onnomarsman)
280
- // bugfixed by: Pellentesque Malesuada
281
- // bugfixed by: Kevin van Zonneveld (http://kvz.io)
282
- // improved by: Indigo744
283
- // example 1: base64_decode('S2V2aW4gdmFuIFpvbm5ldmVsZA==')
284
- // returns 1: 'Kevin van Zonneveld'
285
- // example 2: base64_decode('YQ==')
286
- // returns 2: 'a'
287
- // example 3: base64_decode('4pyTIMOgIGxhIG1vZGU=')
288
- // returns 3: '✓ à la mode'
289
- // decodeUTF8string()
290
- // Internal function to decode properly UTF8 string
291
- // Adapted from Solution #1 at https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding
292
- var decodeUTF8string = function (str) {
293
- // Going backwards: from bytestream, to percent-encoding, to original string.
294
- return decodeURIComponent(str
295
- .split('')
296
- .map(function (c) {
297
- return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
298
- })
299
- .join(''));
300
- };
301
- var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = '';
302
- var tmpArr = [];
303
- if (!encodedData) {
304
- return encodedData;
305
- }
306
- encodedData += '';
307
- do {
308
- // unpack four hexets into three octets using index points in b64
309
- h1 = b64.indexOf(encodedData.charAt(i++));
310
- h2 = b64.indexOf(encodedData.charAt(i++));
311
- h3 = b64.indexOf(encodedData.charAt(i++));
312
- h4 = b64.indexOf(encodedData.charAt(i++));
313
- bits = (h1 << 18) | (h2 << 12) | (h3 << 6) | h4;
314
- o1 = (bits >> 16) & 0xff;
315
- o2 = (bits >> 8) & 0xff;
316
- o3 = bits & 0xff;
317
- if (h3 === 64) {
318
- tmpArr[ac++] = String.fromCharCode(o1);
319
- }
320
- else if (h4 === 64) {
321
- tmpArr[ac++] = String.fromCharCode(o1, o2);
322
- }
323
- else {
324
- tmpArr[ac++] = String.fromCharCode(o1, o2, o3);
325
- }
326
- } while (i < encodedData.length);
327
- dec = tmpArr.join('');
328
- return decodeUTF8string(dec.replace(/\0+$/, ''));
329
- }
330
-
331
- /*
332
- * Copyright (c) 2022 Snowplow Analytics Ltd, 2010 Anthon Pang
333
- * All rights reserved.
334
- *
335
- * Redistribution and use in source and binary forms, with or without
336
- * modification, are permitted provided that the following conditions are met:
337
- *
338
- * 1. Redistributions of source code must retain the above copyright notice, this
339
- * list of conditions and the following disclaimer.
340
- *
341
- * 2. Redistributions in binary form must reproduce the above copyright notice,
342
- * this list of conditions and the following disclaimer in the documentation
343
- * and/or other materials provided with the distribution.
344
- *
345
- * 3. Neither the name of the copyright holder nor the names of its
346
- * contributors may be used to endorse or promote products derived from
347
- * this software without specific prior written permission.
348
- *
349
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
350
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
351
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
352
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
353
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
354
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
355
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
356
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
357
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
358
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
359
- */
360
- function payloadBuilder() {
361
- var dict = {}, allJson = [], jsonForProcessing = [], contextEntitiesForProcessing = [];
362
- var processor;
363
- var add = function (key, value) {
364
- if (value != null && value !== '') {
365
- // null also checks undefined
366
- dict[key] = value;
367
- }
368
- };
369
- var addDict = function (dict) {
370
- for (var key in dict) {
371
- if (Object.prototype.hasOwnProperty.call(dict, key)) {
372
- add(key, dict[key]);
373
- }
374
- }
375
- };
376
- var addJson = function (keyIfEncoded, keyIfNotEncoded, json) {
377
- if (json && isNonEmptyJson(json)) {
378
- var jsonWithKeys = { keyIfEncoded: keyIfEncoded, keyIfNotEncoded: keyIfNotEncoded, json: json };
379
- jsonForProcessing.push(jsonWithKeys);
380
- allJson.push(jsonWithKeys);
381
- }
382
- };
383
- var addContextEntity = function (entity) {
384
- contextEntitiesForProcessing.push(entity);
385
- };
386
- return {
387
- add: add,
388
- addDict: addDict,
389
- addJson: addJson,
390
- addContextEntity: addContextEntity,
391
- getPayload: function () { return dict; },
392
- getJson: function () { return allJson; },
393
- withJsonProcessor: function (jsonProcessor) {
394
- processor = jsonProcessor;
395
- },
396
- build: function () {
397
- processor === null || processor === void 0 ? void 0 : processor(this, jsonForProcessing, contextEntitiesForProcessing);
398
- return dict;
399
- },
400
- };
401
- }
402
- /**
403
- * A helper to build a Snowplow request from a set of name-value pairs, provided using the add methods.
404
- * Will base64 encode JSON, if desired, on build
405
- *
406
- * @returns The request builder, with add and build methods
407
- */
408
- function payloadJsonProcessor(encodeBase64) {
409
- return function (payloadBuilder, jsonForProcessing, contextEntitiesForProcessing) {
410
- var add = function (json, keyIfEncoded, keyIfNotEncoded) {
411
- var str = JSON.stringify(json);
412
- if (encodeBase64) {
413
- payloadBuilder.add(keyIfEncoded, base64urlencode(str));
414
- }
415
- else {
416
- payloadBuilder.add(keyIfNotEncoded, str);
417
- }
418
- };
419
- var getContextFromPayload = function () {
420
- var payload = payloadBuilder.getPayload();
421
- if (encodeBase64 ? payload.cx : payload.co) {
422
- return JSON.parse(encodeBase64 ? base64urldecode(payload.cx) : payload.co);
423
- }
424
- return undefined;
425
- };
426
- var combineContexts = function (originalContext, newContext) {
427
- var context = originalContext || getContextFromPayload();
428
- if (context) {
429
- context.data = context.data.concat(newContext.data);
430
- }
431
- else {
432
- context = newContext;
433
- }
434
- return context;
435
- };
436
- var context = undefined;
437
- for (var _i = 0, jsonForProcessing_1 = jsonForProcessing; _i < jsonForProcessing_1.length; _i++) {
438
- var json = jsonForProcessing_1[_i];
439
- if (json.keyIfEncoded === 'cx') {
440
- context = combineContexts(context, json.json);
441
- }
442
- else {
443
- add(json.json, json.keyIfEncoded, json.keyIfNotEncoded);
444
- }
445
- }
446
- jsonForProcessing.length = 0;
447
- if (contextEntitiesForProcessing.length) {
448
- var newContext = {
449
- schema: 'iglu:com.snowplowanalytics.snowplow/contexts/jsonschema/1-0-0',
450
- data: __spreadArray([], contextEntitiesForProcessing, true),
451
- };
452
- context = combineContexts(context, newContext);
453
- contextEntitiesForProcessing.length = 0;
454
- }
455
- if (context) {
456
- add(context, 'cx', 'co');
457
- }
458
- };
459
- }
460
- /**
461
- * Is property a non-empty JSON?
462
- * @param property - Checks if object is non-empty json
463
- */
464
- function isNonEmptyJson(property) {
465
- if (!isJson(property)) {
466
- return false;
467
- }
468
- for (var key in property) {
469
- if (Object.prototype.hasOwnProperty.call(property, key)) {
470
- return true;
471
- }
472
- }
473
- return false;
474
- }
475
- /**
476
- * Is property a JSON?
477
- * @param property - Checks if object is json
478
- */
479
- function isJson(property) {
480
- return (typeof property !== 'undefined' &&
481
- property !== null &&
482
- (property.constructor === {}.constructor || property.constructor === [].constructor));
483
- }
484
-
485
- /*
486
- * Copyright (c) 2022 Snowplow Analytics Ltd, 2010 Anthon Pang
487
- * All rights reserved.
488
- *
489
- * Redistribution and use in source and binary forms, with or without
490
- * modification, are permitted provided that the following conditions are met:
491
- *
492
- * 1. Redistributions of source code must retain the above copyright notice, this
493
- * list of conditions and the following disclaimer.
494
- *
495
- * 2. Redistributions in binary form must reproduce the above copyright notice,
496
- * this list of conditions and the following disclaimer in the documentation
497
- * and/or other materials provided with the distribution.
498
- *
499
- * 3. Neither the name of the copyright holder nor the names of its
500
- * contributors may be used to endorse or promote products derived from
501
- * this software without specific prior written permission.
502
- *
503
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
504
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
505
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
506
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
507
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
508
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
509
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
510
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
511
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
512
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
513
- */
514
- var label = 'Snowplow: ';
515
- exports.LOG_LEVEL = void 0;
516
- (function (LOG_LEVEL) {
517
- LOG_LEVEL[LOG_LEVEL["none"] = 0] = "none";
518
- LOG_LEVEL[LOG_LEVEL["error"] = 1] = "error";
519
- LOG_LEVEL[LOG_LEVEL["warn"] = 2] = "warn";
520
- LOG_LEVEL[LOG_LEVEL["debug"] = 3] = "debug";
521
- LOG_LEVEL[LOG_LEVEL["info"] = 4] = "info";
522
- })(exports.LOG_LEVEL || (exports.LOG_LEVEL = {}));
523
- var LOG = logger();
524
- function logger(logLevel) {
525
- if (logLevel === void 0) { logLevel = exports.LOG_LEVEL.warn; }
526
- function setLogLevel(level) {
527
- if (exports.LOG_LEVEL[level]) {
528
- logLevel = level;
529
- }
530
- else {
531
- logLevel = exports.LOG_LEVEL.warn;
532
- }
533
- }
534
- /**
535
- * Log errors, with or without error object
536
- */
537
- function error(message, error) {
538
- var extraParams = [];
539
- for (var _i = 2; _i < arguments.length; _i++) {
540
- extraParams[_i - 2] = arguments[_i];
541
- }
542
- if (logLevel >= exports.LOG_LEVEL.error && typeof console !== 'undefined') {
543
- var logMsg = label + message + '\n';
544
- if (error) {
545
- console.error.apply(console, __spreadArray([logMsg + '\n', error], extraParams, false));
546
- }
547
- else {
548
- console.error.apply(console, __spreadArray([logMsg], extraParams, false));
549
- }
550
- }
551
- }
552
- /**
553
- * Log warnings, with or without error object
554
- */
555
- function warn(message, error) {
556
- var extraParams = [];
557
- for (var _i = 2; _i < arguments.length; _i++) {
558
- extraParams[_i - 2] = arguments[_i];
559
- }
560
- if (logLevel >= exports.LOG_LEVEL.warn && typeof console !== 'undefined') {
561
- var logMsg = label + message;
562
- if (error) {
563
- console.warn.apply(console, __spreadArray([logMsg + '\n', error], extraParams, false));
564
- }
565
- else {
566
- console.warn.apply(console, __spreadArray([logMsg], extraParams, false));
567
- }
568
- }
569
- }
570
- /**
571
- * Log debug messages
572
- */
573
- function debug(message) {
574
- var extraParams = [];
575
- for (var _i = 1; _i < arguments.length; _i++) {
576
- extraParams[_i - 1] = arguments[_i];
577
- }
578
- if (logLevel >= exports.LOG_LEVEL.debug && typeof console !== 'undefined') {
579
- console.debug.apply(console, __spreadArray([label + message], extraParams, false));
580
- }
581
- }
582
- /**
583
- * Log info messages
584
- */
585
- function info(message) {
586
- var extraParams = [];
587
- for (var _i = 1; _i < arguments.length; _i++) {
588
- extraParams[_i - 1] = arguments[_i];
589
- }
590
- if (logLevel >= exports.LOG_LEVEL.info && typeof console !== 'undefined') {
591
- console.info.apply(console, __spreadArray([label + message], extraParams, false));
592
- }
593
- }
594
- return { setLogLevel: setLogLevel, warn: warn, error: error, debug: debug, info: info };
595
- }
596
-
597
- /*
598
- * Copyright (c) 2022 Snowplow Analytics Ltd, 2010 Anthon Pang
599
- * All rights reserved.
600
- *
601
- * Redistribution and use in source and binary forms, with or without
602
- * modification, are permitted provided that the following conditions are met:
603
- *
604
- * 1. Redistributions of source code must retain the above copyright notice, this
605
- * list of conditions and the following disclaimer.
606
- *
607
- * 2. Redistributions in binary form must reproduce the above copyright notice,
608
- * this list of conditions and the following disclaimer in the documentation
609
- * and/or other materials provided with the distribution.
610
- *
611
- * 3. Neither the name of the copyright holder nor the names of its
612
- * contributors may be used to endorse or promote products derived from
613
- * this software without specific prior written permission.
614
- *
615
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
616
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
617
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
618
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
619
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
620
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
621
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
622
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
623
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
624
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
625
- */
626
- /**
627
- * Contains helper functions to aid in the addition and removal of Global Contexts
628
- */
629
- function globalContexts() {
630
- var globalPrimitives = [];
631
- var conditionalProviders = [];
632
- var namedPrimitives = {};
633
- var namedConditionalProviders = {};
634
- /**
635
- * Returns all applicable global contexts for a specified event
636
- * @param event - The event to check for applicable global contexts for
637
- * @returns An array of contexts
638
- */
639
- var assembleAllContexts = function (event) {
640
- var eventSchema = getUsefulSchema(event);
641
- var eventType = getEventType(event);
642
- var contexts = [];
643
- var generatedPrimitives = generatePrimitives(globalPrimitives.concat(Object.values(namedPrimitives)), event, eventType, eventSchema);
644
- contexts.push.apply(contexts, generatedPrimitives);
645
- var generatedConditionals = generateConditionals(conditionalProviders.concat(Object.values(namedConditionalProviders)), event, eventType, eventSchema);
646
- contexts.push.apply(contexts, generatedConditionals);
647
- return contexts;
648
- };
649
- return {
650
- getGlobalPrimitives: function () {
651
- return globalPrimitives.concat(Object.values(namedPrimitives));
652
- },
653
- getConditionalProviders: function () {
654
- return conditionalProviders.concat(Object.values(namedConditionalProviders));
655
- },
656
- addGlobalContexts: function (contexts) {
657
- if (Array.isArray(contexts)) {
658
- var acceptedConditionalContexts = [];
659
- var acceptedContextPrimitives = [];
660
- for (var _i = 0, contexts_1 = contexts; _i < contexts_1.length; _i++) {
661
- var context = contexts_1[_i];
662
- if (isConditionalContextProvider(context)) {
663
- acceptedConditionalContexts.push(context);
664
- }
665
- else if (isContextPrimitive(context)) {
666
- acceptedContextPrimitives.push(context);
667
- }
668
- }
669
- globalPrimitives = globalPrimitives.concat(acceptedContextPrimitives);
670
- conditionalProviders = conditionalProviders.concat(acceptedConditionalContexts);
671
- }
672
- else {
673
- for (var _a = 0, _b = Object.entries(contexts); _a < _b.length; _a++) {
674
- var _c = _b[_a], name_1 = _c[0], context = _c[1];
675
- if (isConditionalContextProvider(context)) {
676
- namedConditionalProviders[name_1] = context;
677
- }
678
- else if (isContextPrimitive(context)) {
679
- namedPrimitives[name_1] = context;
680
- }
681
- }
682
- }
683
- },
684
- clearGlobalContexts: function () {
685
- conditionalProviders = [];
686
- globalPrimitives = [];
687
- namedConditionalProviders = {};
688
- namedPrimitives = {};
689
- },
690
- removeGlobalContexts: function (contexts) {
691
- var _loop_1 = function (context) {
692
- if (typeof context === 'string') {
693
- delete namedConditionalProviders[context];
694
- delete namedPrimitives[context];
695
- }
696
- else if (isConditionalContextProvider(context)) {
697
- conditionalProviders = conditionalProviders.filter(function (item) { return !compareProvider(context, item); });
698
- }
699
- else if (isContextPrimitive(context)) {
700
- globalPrimitives = globalPrimitives.filter(function (item) { return !compareProvider(context, item); });
701
- }
702
- };
703
- for (var _i = 0, contexts_2 = contexts; _i < contexts_2.length; _i++) {
704
- var context = contexts_2[_i];
705
- _loop_1(context);
706
- }
707
- },
708
- getApplicableContexts: function (event) {
709
- return assembleAllContexts(event);
710
- },
711
- };
712
- }
713
- function pluginContexts(plugins) {
714
- /**
715
- * Add common contexts to every event
716
- *
717
- * @param array - additionalContexts List of user-defined contexts
718
- * @returns userContexts combined with commonContexts
719
- */
720
- return {
721
- addPluginContexts: function (additionalContexts) {
722
- var combinedContexts = additionalContexts
723
- ? __spreadArray([], additionalContexts, true) : [];
724
- plugins.forEach(function (plugin) {
725
- try {
726
- if (plugin.contexts) {
727
- combinedContexts.push.apply(combinedContexts, plugin.contexts());
728
- }
729
- }
730
- catch (ex) {
731
- LOG.error('Error adding plugin contexts', ex);
732
- }
733
- });
734
- return combinedContexts;
735
- },
736
- };
737
- }
738
- /**
739
- * Slices a schema into its composite parts. Useful for ruleset filtering.
740
- * @param input - A schema string
741
- * @returns The vendor, schema name, major, minor and patch information of a schema string
742
- */
743
- function getSchemaParts(input) {
744
- var re = new RegExp('^iglu:([a-zA-Z0-9-_.]+)/([a-zA-Z0-9-_]+)/jsonschema/([1-9][0-9]*)-(0|[1-9][0-9]*)-(0|[1-9][0-9]*)$');
745
- var matches = re.exec(input);
746
- if (matches !== null)
747
- return matches.slice(1, 6);
748
- return undefined;
749
- }
750
- /**
751
- * Validates the vendor section of a schema string contains allowed wildcard values
752
- * @param parts - Array of parts from a schema string
753
- * @returns Whether the vendor validation parts are a valid combination
754
- */
755
- function validateVendorParts(parts) {
756
- if (parts[0] === '*' || parts[1] === '*') {
757
- return false; // no wildcard in first or second part
758
- }
759
- if (parts.slice(2).length > 0) {
760
- var asterisk = false;
761
- for (var _i = 0, _a = parts.slice(2); _i < _a.length; _i++) {
762
- var part = _a[_i];
763
- if (part === '*')
764
- // mark when we've found a wildcard
765
- asterisk = true;
766
- else if (asterisk)
767
- // invalid if alpha parts come after wildcard
768
- return false;
769
- }
770
- return true;
771
- }
772
- else if (parts.length == 2)
773
- return true;
774
- return false;
775
- }
776
- /**
777
- * Validates the vendor part of a schema string is valid for a rule set
778
- * @param input - Vendor part of a schema string
779
- * @returns Whether the vendor validation string is valid
780
- */
781
- function validateVendor(input) {
782
- var parts = input.split('.');
783
- if (parts && parts.length > 1)
784
- return validateVendorParts(parts);
785
- return false;
786
- }
787
- /**
788
- * Checks for validity of input and returns all the sections of a schema string that are used to match rules in a ruleset
789
- * @param input - A Schema string
790
- * @returns The sections of a schema string that are used to match rules in a ruleset
791
- */
792
- function getRuleParts(input) {
793
- var re = new RegExp('^iglu:((?:(?:[a-zA-Z0-9-_]+|\\*).)+(?:[a-zA-Z0-9-_]+|\\*))/([a-zA-Z0-9-_.]+|\\*)/jsonschema/([1-9][0-9]*|\\*)-(0|[1-9][0-9]*|\\*)-(0|[1-9][0-9]*|\\*)$');
794
- var matches = re.exec(input);
795
- if (matches !== null && validateVendor(matches[1]))
796
- return matches.slice(1, 6);
797
- return undefined;
798
- }
799
- /**
800
- * Ensures the rules specified in a schema string of a ruleset are valid
801
- * @param input - A Schema string
802
- * @returns if there rule is valid
803
- */
804
- function isValidRule(input) {
805
- var ruleParts = getRuleParts(input);
806
- if (ruleParts) {
807
- var vendor = ruleParts[0];
808
- return ruleParts.length === 5 && validateVendor(vendor);
809
- }
810
- return false;
811
- }
812
- /**
813
- * Check if a variable is an Array containing only strings
814
- * @param input - The variable to validate
815
- * @returns True if the input is an array containing only strings
816
- */
817
- function isStringArray(input) {
818
- return (Array.isArray(input) &&
819
- input.every(function (x) {
820
- return typeof x === 'string';
821
- }));
822
- }
823
- /**
824
- * Validates whether a rule set is an array of valid ruleset strings
825
- * @param input - The Array of rule set arguments
826
- * @returns True is the input is an array of valid rules
827
- */
828
- function isValidRuleSetArg(input) {
829
- if (isStringArray(input))
830
- return input.every(function (x) {
831
- return isValidRule(x);
832
- });
833
- else if (typeof input === 'string')
834
- return isValidRule(input);
835
- return false;
836
- }
837
- /**
838
- * Check if a variable is a valid, non-empty Self Describing JSON
839
- * @param input - The variable to validate
840
- * @returns True if a valid Self Describing JSON
841
- */
842
- function isSelfDescribingJson(input) {
843
- var sdj = input;
844
- if (isNonEmptyJson(sdj))
845
- if ('schema' in sdj && 'data' in sdj)
846
- return typeof sdj.schema === 'string' && typeof sdj.data === 'object';
847
- return false;
848
- }
849
- /**
850
- * Validates if the input object contains the expected properties of a ruleset
851
- * @param input - The object containing a rule set
852
- * @returns True if a valid rule set
853
- */
854
- function isRuleSet(input) {
855
- var ruleSet = input;
856
- var ruleCount = 0;
857
- if (input != null && typeof input === 'object' && !Array.isArray(input)) {
858
- if (Object.prototype.hasOwnProperty.call(ruleSet, 'accept')) {
859
- if (isValidRuleSetArg(ruleSet['accept'])) {
860
- ruleCount += 1;
861
- }
862
- else {
863
- return false;
864
- }
865
- }
866
- if (Object.prototype.hasOwnProperty.call(ruleSet, 'reject')) {
867
- if (isValidRuleSetArg(ruleSet['reject'])) {
868
- ruleCount += 1;
869
- }
870
- else {
871
- return false;
872
- }
873
- }
874
- // if either 'reject' or 'accept' or both exists,
875
- // we have a valid ruleset
876
- return ruleCount > 0 && ruleCount <= 2;
877
- }
878
- return false;
879
- }
880
- /**
881
- * Validates if the function can be a valid context generator function
882
- * @param input - The function to be validated
883
- */
884
- function isContextCallbackFunction(input) {
885
- return typeof input === 'function' && input.length <= 1;
886
- }
887
- /**
888
- * Validates if the function can be a valid context primitive function or self describing json
889
- * @param input - The function or orbject to be validated
890
- * @returns True if either a Context Generator or Self Describing JSON
891
- */
892
- function isContextPrimitive(input) {
893
- return isContextCallbackFunction(input) || isSelfDescribingJson(input);
894
- }
895
- /**
896
- * Validates if an array is a valid shape to be a Filter Provider
897
- * @param input - The Array of Context filter callbacks
898
- */
899
- function isFilterProvider(input) {
900
- if (Array.isArray(input)) {
901
- if (input.length === 2) {
902
- if (Array.isArray(input[1])) {
903
- return isContextCallbackFunction(input[0]) && input[1].every(isContextPrimitive);
904
- }
905
- return isContextCallbackFunction(input[0]) && isContextPrimitive(input[1]);
906
- }
907
- }
908
- return false;
909
- }
910
- /**
911
- * Validates if an array is a valid shape to be an array of rule sets
912
- * @param input - The Array of Rule Sets
913
- */
914
- function isRuleSetProvider(input) {
915
- if (Array.isArray(input) && input.length === 2) {
916
- if (!isRuleSet(input[0]))
917
- return false;
918
- if (Array.isArray(input[1]))
919
- return input[1].every(isContextPrimitive);
920
- return isContextPrimitive(input[1]);
921
- }
922
- return false;
923
- }
924
- /**
925
- * Checks if an input array is either a filter provider or a rule set provider
926
- * @param input - An array of filter providers or rule set providers
927
- * @returns Whether the array is a valid {@link ConditionalContextProvider}
928
- */
929
- function isConditionalContextProvider(input) {
930
- return isFilterProvider(input) || isRuleSetProvider(input);
931
- }
932
- /**
933
- * Checks if a given schema matches any rules within the provided rule set
934
- * @param ruleSet - The rule set containing rules to match schema against
935
- * @param schema - The schema to be matched against the rule set
936
- */
937
- function matchSchemaAgainstRuleSet(ruleSet, schema) {
938
- var rejectCount = 0;
939
- var acceptCount = 0;
940
- var acceptRules = ruleSet['accept'];
941
- if (Array.isArray(acceptRules)) {
942
- if (ruleSet.accept.some(function (rule) { return matchSchemaAgainstRule(rule, schema); })) {
943
- acceptCount++;
944
- }
945
- }
946
- else if (typeof acceptRules === 'string') {
947
- if (matchSchemaAgainstRule(acceptRules, schema)) {
948
- acceptCount++;
949
- }
950
- }
951
- var rejectRules = ruleSet['reject'];
952
- if (Array.isArray(rejectRules)) {
953
- if (ruleSet.reject.some(function (rule) { return matchSchemaAgainstRule(rule, schema); })) {
954
- rejectCount++;
955
- }
956
- }
957
- else if (typeof rejectRules === 'string') {
958
- if (matchSchemaAgainstRule(rejectRules, schema)) {
959
- rejectCount++;
960
- }
961
- }
962
- if (acceptCount > 0 && rejectCount === 0) {
963
- return true;
964
- }
965
- else if (acceptCount === 0 && rejectCount > 0) {
966
- return false;
967
- }
968
- return false;
969
- }
970
- /**
971
- * Checks if a given schema matches a specific rule from a rule set
972
- * @param rule - The rule to match schema against
973
- * @param schema - The schema to be matched against the rule
974
- */
975
- function matchSchemaAgainstRule(rule, schema) {
976
- if (!isValidRule(rule))
977
- return false;
978
- var ruleParts = getRuleParts(rule);
979
- var schemaParts = getSchemaParts(schema);
980
- if (ruleParts && schemaParts) {
981
- if (!matchVendor(ruleParts[0], schemaParts[0]))
982
- return false;
983
- for (var i = 1; i < 5; i++) {
984
- if (!matchPart(ruleParts[i], schemaParts[i]))
985
- return false;
986
- }
987
- return true; // if it hasn't failed, it passes
988
- }
989
- return false;
990
- }
991
- function matchVendor(rule, vendor) {
992
- // rule and vendor must have same number of elements
993
- var vendorParts = vendor.split('.');
994
- var ruleParts = rule.split('.');
995
- if (vendorParts && ruleParts) {
996
- if (vendorParts.length !== ruleParts.length)
997
- return false;
998
- for (var i = 0; i < ruleParts.length; i++) {
999
- if (!matchPart(vendorParts[i], ruleParts[i]))
1000
- return false;
1001
- }
1002
- return true;
1003
- }
1004
- return false;
1005
- }
1006
- function matchPart(rule, schema) {
1007
- // parts should be the string nested between slashes in the URI: /example/
1008
- return (rule && schema && rule === '*') || rule === schema;
1009
- }
1010
- // Returns the "useful" schema, i.e. what would someone want to use to identify events.
1011
- // For some events this is the 'e' property but for unstructured events, this is the
1012
- // 'schema' from the 'ue_px' field.
1013
- function getUsefulSchema(sb) {
1014
- var eventJson = sb.getJson();
1015
- for (var _i = 0, eventJson_1 = eventJson; _i < eventJson_1.length; _i++) {
1016
- var json = eventJson_1[_i];
1017
- if (json.keyIfEncoded === 'ue_px' && typeof json.json['data'] === 'object') {
1018
- var schema = json.json['data']['schema'];
1019
- if (typeof schema == 'string') {
1020
- return schema;
1021
- }
1022
- }
1023
- }
1024
- return '';
1025
- }
1026
- function getEventType(payloadBuilder) {
1027
- var eventType = payloadBuilder.getPayload()['e'];
1028
- return typeof eventType === 'string' ? eventType : '';
1029
- }
1030
- function buildGenerator(generator, event, eventType, eventSchema) {
1031
- var contextGeneratorResult = undefined;
1032
- try {
1033
- // try to evaluate context generator
1034
- var args = {
1035
- event: event.getPayload(),
1036
- eventType: eventType,
1037
- eventSchema: eventSchema,
1038
- };
1039
- contextGeneratorResult = generator(args);
1040
- // determine if the produced result is a valid SDJ
1041
- if (Array.isArray(contextGeneratorResult) && contextGeneratorResult.every(isSelfDescribingJson)) {
1042
- return contextGeneratorResult;
1043
- }
1044
- else if (isSelfDescribingJson(contextGeneratorResult)) {
1045
- return contextGeneratorResult;
1046
- }
1047
- else {
1048
- return undefined;
1049
- }
1050
- }
1051
- catch (error) {
1052
- contextGeneratorResult = undefined;
1053
- }
1054
- return contextGeneratorResult;
1055
- }
1056
- function normalizeToArray(input) {
1057
- if (Array.isArray(input)) {
1058
- return input;
1059
- }
1060
- return Array.of(input);
1061
- }
1062
- function generatePrimitives(contextPrimitives, event, eventType, eventSchema) {
1063
- var _a;
1064
- var normalizedInputs = normalizeToArray(contextPrimitives);
1065
- var partialEvaluate = function (primitive) {
1066
- var result = evaluatePrimitive(primitive, event, eventType, eventSchema);
1067
- if (result && result.length !== 0) {
1068
- return result;
1069
- }
1070
- return undefined;
1071
- };
1072
- var generatedContexts = normalizedInputs.map(partialEvaluate);
1073
- return (_a = []).concat.apply(_a, generatedContexts.filter(function (c) { return c != null && c.filter(Boolean); }));
1074
- }
1075
- function evaluatePrimitive(contextPrimitive, event, eventType, eventSchema) {
1076
- if (isSelfDescribingJson(contextPrimitive)) {
1077
- return [contextPrimitive];
1078
- }
1079
- else if (isContextCallbackFunction(contextPrimitive)) {
1080
- var generatorOutput = buildGenerator(contextPrimitive, event, eventType, eventSchema);
1081
- if (isSelfDescribingJson(generatorOutput)) {
1082
- return [generatorOutput];
1083
- }
1084
- else if (Array.isArray(generatorOutput)) {
1085
- return generatorOutput;
1086
- }
1087
- }
1088
- return undefined;
1089
- }
1090
- function evaluateProvider(provider, event, eventType, eventSchema) {
1091
- if (isFilterProvider(provider)) {
1092
- var filter = provider[0];
1093
- var filterResult = false;
1094
- try {
1095
- var args = {
1096
- event: event.getPayload(),
1097
- eventType: eventType,
1098
- eventSchema: eventSchema,
1099
- };
1100
- filterResult = filter(args);
1101
- }
1102
- catch (error) {
1103
- filterResult = false;
1104
- }
1105
- if (filterResult === true) {
1106
- return generatePrimitives(provider[1], event, eventType, eventSchema);
1107
- }
1108
- }
1109
- else if (isRuleSetProvider(provider)) {
1110
- if (matchSchemaAgainstRuleSet(provider[0], eventSchema)) {
1111
- return generatePrimitives(provider[1], event, eventType, eventSchema);
1112
- }
1113
- }
1114
- return [];
1115
- }
1116
- function compareProviderPart(a, b) {
1117
- if (typeof a === 'function')
1118
- return a === b;
1119
- return JSON.stringify(a) === JSON.stringify(b);
1120
- }
1121
- function compareProvider(a, b) {
1122
- if (isConditionalContextProvider(a)) {
1123
- if (!isConditionalContextProvider(b))
1124
- return false;
1125
- var ruleA = a[0], primitivesA = a[1];
1126
- var ruleB = b[0], primitivesB_1 = b[1];
1127
- if (!compareProviderPart(ruleA, ruleB))
1128
- return false;
1129
- if (Array.isArray(primitivesA)) {
1130
- if (!Array.isArray(primitivesB_1))
1131
- return false;
1132
- if (primitivesA.length !== primitivesB_1.length)
1133
- return false;
1134
- return primitivesA.reduce(function (matches, a, i) { return matches && compareProviderPart(a, primitivesB_1[i]); }, true);
1135
- }
1136
- else {
1137
- if (Array.isArray(primitivesB_1))
1138
- return false;
1139
- return compareProviderPart(primitivesA, primitivesB_1);
1140
- }
1141
- }
1142
- else if (isContextPrimitive(a)) {
1143
- if (!isContextPrimitive(b))
1144
- return false;
1145
- return compareProviderPart(a, b);
1146
- }
1147
- return false;
1148
- }
1149
- function generateConditionals(providers, event, eventType, eventSchema) {
1150
- var _a;
1151
- var normalizedInput = normalizeToArray(providers);
1152
- var partialEvaluate = function (provider) {
1153
- var result = evaluateProvider(provider, event, eventType, eventSchema);
1154
- if (result && result.length !== 0) {
1155
- return result;
1156
- }
1157
- return undefined;
1158
- };
1159
- var generatedContexts = normalizedInput.map(partialEvaluate);
1160
- return (_a = []).concat.apply(_a, generatedContexts.filter(function (c) { return c != null && c.filter(Boolean); }));
1161
- }
1162
-
1163
- /**
1164
- * Create a new EventStorePayload
1165
- */
1166
- function newEventStorePayload(_a) {
1167
- var payload = _a.payload, _b = _a.svrAnon, svrAnon = _b === void 0 ? false : _b;
1168
- return {
1169
- payload: payload,
1170
- svrAnon: svrAnon,
1171
- };
1172
- }
1173
-
1174
- /*
1175
- * Copyright (c) 2022 Snowplow Analytics Ltd, 2010 Anthon Pang
1176
- * All rights reserved.
1177
- *
1178
- * Redistribution and use in source and binary forms, with or without
1179
- * modification, are permitted provided that the following conditions are met:
1180
- *
1181
- * 1. Redistributions of source code must retain the above copyright notice, this
1182
- * list of conditions and the following disclaimer.
1183
- *
1184
- * 2. Redistributions in binary form must reproduce the above copyright notice,
1185
- * this list of conditions and the following disclaimer in the documentation
1186
- * and/or other materials provided with the distribution.
1187
- *
1188
- * 3. Neither the name of the copyright holder nor the names of its
1189
- * contributors may be used to endorse or promote products derived from
1190
- * this software without specific prior written permission.
1191
- *
1192
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
1193
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
1194
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
1195
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
1196
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
1197
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
1198
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
1199
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
1200
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
1201
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
1202
- */
1203
- /**
1204
- * Transform optional/old-behavior number timestamp into`Timestamp` ADT
1205
- *
1206
- * @param timestamp - optional number or timestamp object
1207
- * @returns correct timestamp object
1208
- */
1209
- function getTimestamp(timestamp) {
1210
- if (timestamp == null) {
1211
- return { type: 'dtm', value: new Date().getTime() };
1212
- }
1213
- else if (typeof timestamp === 'number') {
1214
- return { type: 'dtm', value: timestamp };
1215
- }
1216
- else if (timestamp.type === 'ttm') {
1217
- // We can return timestamp here, but this is safer fallback
1218
- return { type: 'ttm', value: timestamp.value };
1219
- }
1220
- else {
1221
- return { type: 'dtm', value: timestamp.value || new Date().getTime() };
1222
- }
1223
- }
1224
- /**
1225
- * Create a tracker core object
1226
- *
1227
- * @param base64 - Whether to base 64 encode contexts and self describing event JSONs
1228
- * @param corePlugins - The core plugins to be processed with each event
1229
- * @param callback - Function applied to every payload dictionary object
1230
- * @returns Tracker core
1231
- */
1232
- function trackerCore(configuration) {
1233
- if (configuration === void 0) { configuration = {}; }
1234
- function newCore(base64, corePlugins, callback) {
1235
- var pluginContextsHelper = pluginContexts(corePlugins), globalContextsHelper = globalContexts();
1236
- var encodeBase64 = base64, payloadPairs = {}; // Dictionary of key-value pairs which get added to every payload, e.g. tracker version
1237
- /**
1238
- * Wraps an array of custom contexts in a self-describing JSON
1239
- *
1240
- * @param contexts - Array of custom context self-describing JSONs
1241
- * @returns Outer JSON
1242
- */
1243
- function completeContexts(contexts) {
1244
- if (contexts && contexts.length) {
1245
- return {
1246
- schema: 'iglu:com.snowplowanalytics.snowplow/contexts/jsonschema/1-0-0',
1247
- data: contexts,
1248
- };
1249
- }
1250
- return undefined;
1251
- }
1252
- /**
1253
- * Adds all global contexts to a contexts array
1254
- *
1255
- * @param pb - PayloadData
1256
- * @param contexts - Custom contexts relating to the event
1257
- */
1258
- function attachGlobalContexts(pb, contexts) {
1259
- var applicableContexts = globalContextsHelper.getApplicableContexts(pb);
1260
- var returnedContexts = [];
1261
- if (contexts && contexts.length) {
1262
- returnedContexts.push.apply(returnedContexts, contexts);
1263
- }
1264
- if (applicableContexts && applicableContexts.length) {
1265
- returnedContexts.push.apply(returnedContexts, applicableContexts);
1266
- }
1267
- return returnedContexts;
1268
- }
1269
- /**
1270
- * Gets called by every trackXXX method
1271
- * Adds context and payloadPairs name-value pairs to the payload
1272
- * Applies the callback to the built payload
1273
- *
1274
- * @param pb - Payload
1275
- * @param context - Custom contexts relating to the event
1276
- * @param timestamp - Timestamp of the event
1277
- * @returns Payload after the callback is applied or undefined if the event is skipped
1278
- */
1279
- function track(pb, context, timestamp) {
1280
- pb.withJsonProcessor(payloadJsonProcessor(encodeBase64));
1281
- pb.add('eid', v4());
1282
- pb.addDict(payloadPairs);
1283
- var tstamp = getTimestamp(timestamp);
1284
- pb.add(tstamp.type, tstamp.value.toString());
1285
- var allContexts = attachGlobalContexts(pb, pluginContextsHelper.addPluginContexts(context));
1286
- var wrappedContexts = completeContexts(allContexts);
1287
- if (wrappedContexts !== undefined) {
1288
- pb.addJson('cx', 'co', wrappedContexts);
1289
- }
1290
- corePlugins.forEach(function (plugin) {
1291
- try {
1292
- if (plugin.beforeTrack) {
1293
- plugin.beforeTrack(pb);
1294
- }
1295
- }
1296
- catch (ex) {
1297
- LOG.error('Plugin beforeTrack', ex);
1298
- }
1299
- });
1300
- // Call the filter on plugins to determine if the event should be tracked
1301
- var skip = corePlugins.find(function (plugin) {
1302
- try {
1303
- return plugin.filter && plugin.filter(pb.build()) === false;
1304
- }
1305
- catch (ex) {
1306
- LOG.error('Plugin filter', ex);
1307
- return false;
1308
- }
1309
- });
1310
- if (skip) {
1311
- return undefined;
1312
- }
1313
- if (typeof callback === 'function') {
1314
- callback(pb);
1315
- }
1316
- var finalPayload = pb.build();
1317
- corePlugins.forEach(function (plugin) {
1318
- try {
1319
- if (plugin.afterTrack) {
1320
- plugin.afterTrack(finalPayload);
1321
- }
1322
- }
1323
- catch (ex) {
1324
- LOG.error('Plugin afterTrack', ex);
1325
- }
1326
- });
1327
- return finalPayload;
1328
- }
1329
- /**
1330
- * Set a persistent key-value pair to be added to every payload
1331
- *
1332
- * @param key - Field name
1333
- * @param value - Field value
1334
- */
1335
- function addPayloadPair(key, value) {
1336
- payloadPairs[key] = value;
1337
- }
1338
- var core = {
1339
- track: track,
1340
- addPayloadPair: addPayloadPair,
1341
- getBase64Encoding: function () {
1342
- return encodeBase64;
1343
- },
1344
- setBase64Encoding: function (encode) {
1345
- encodeBase64 = encode;
1346
- },
1347
- addPayloadDict: function (dict) {
1348
- for (var key in dict) {
1349
- if (Object.prototype.hasOwnProperty.call(dict, key)) {
1350
- payloadPairs[key] = dict[key];
1351
- }
1352
- }
1353
- },
1354
- resetPayloadPairs: function (dict) {
1355
- payloadPairs = isJson(dict) ? dict : {};
1356
- },
1357
- setTrackerVersion: function (version) {
1358
- addPayloadPair('tv', version);
1359
- },
1360
- setTrackerNamespace: function (name) {
1361
- addPayloadPair('tna', name);
1362
- },
1363
- setAppId: function (appId) {
1364
- addPayloadPair('aid', appId);
1365
- },
1366
- setPlatform: function (value) {
1367
- addPayloadPair('p', value);
1368
- },
1369
- setUserId: function (userId) {
1370
- addPayloadPair('uid', userId);
1371
- },
1372
- setScreenResolution: function (width, height) {
1373
- addPayloadPair('res', width + 'x' + height);
1374
- },
1375
- setViewport: function (width, height) {
1376
- addPayloadPair('vp', width + 'x' + height);
1377
- },
1378
- setColorDepth: function (depth) {
1379
- addPayloadPair('cd', depth);
1380
- },
1381
- setTimezone: function (timezone) {
1382
- addPayloadPair('tz', timezone);
1383
- },
1384
- setLang: function (lang) {
1385
- addPayloadPair('lang', lang);
1386
- },
1387
- setIpAddress: function (ip) {
1388
- addPayloadPair('ip', ip);
1389
- },
1390
- setUseragent: function (useragent) {
1391
- addPayloadPair('ua', useragent);
1392
- },
1393
- addGlobalContexts: function (contexts) {
1394
- globalContextsHelper.addGlobalContexts(contexts);
1395
- },
1396
- clearGlobalContexts: function () {
1397
- globalContextsHelper.clearGlobalContexts();
1398
- },
1399
- removeGlobalContexts: function (contexts) {
1400
- globalContextsHelper.removeGlobalContexts(contexts);
1401
- },
1402
- };
1403
- return core;
1404
- }
1405
- var base64 = configuration.base64, corePlugins = configuration.corePlugins, callback = configuration.callback, plugins = corePlugins !== null && corePlugins !== void 0 ? corePlugins : [], partialCore = newCore(base64 !== null && base64 !== void 0 ? base64 : true, plugins, callback), core = __assign(__assign({}, partialCore), { addPlugin: function (configuration) {
1406
- var _a, _b;
1407
- var plugin = configuration.plugin;
1408
- plugins.push(plugin);
1409
- (_a = plugin.logger) === null || _a === void 0 ? void 0 : _a.call(plugin, LOG);
1410
- (_b = plugin.activateCorePlugin) === null || _b === void 0 ? void 0 : _b.call(plugin, core);
1411
- } });
1412
- plugins === null || plugins === void 0 ? void 0 : plugins.forEach(function (plugin) {
1413
- var _a, _b;
1414
- (_a = plugin.logger) === null || _a === void 0 ? void 0 : _a.call(plugin, LOG);
1415
- (_b = plugin.activateCorePlugin) === null || _b === void 0 ? void 0 : _b.call(plugin, core);
1416
- });
1417
- return core;
1418
- }
1419
- /**
1420
- * Build a self-describing event
1421
- * A custom event type, allowing for an event to be tracked using your own custom schema
1422
- * and a data object which conforms to the supplied schema
1423
- *
1424
- * @param event - Contains the properties and schema location for the event
1425
- * @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track}
1426
- */
1427
- function buildSelfDescribingEvent(event) {
1428
- var _a = event.event, schema = _a.schema, data = _a.data, pb = payloadBuilder();
1429
- var ueJson = {
1430
- schema: 'iglu:com.snowplowanalytics.snowplow/unstruct_event/jsonschema/1-0-0',
1431
- data: { schema: schema, data: data },
1432
- };
1433
- pb.add('e', 'ue');
1434
- pb.addJson('ue_px', 'ue_pr', ueJson);
1435
- return pb;
1436
- }
1437
- /**
1438
- * Build a Page View Event
1439
- * Represents a Page View, which is typically fired as soon as possible when a web page
1440
- * is loaded within the users browser. Often also fired on "virtual page views" within
1441
- * Single Page Applications (SPA).
1442
- *
1443
- * @param event - Contains the properties for the Page View event
1444
- * @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track}
1445
- */
1446
- function buildPageView(event) {
1447
- var pageUrl = event.pageUrl, pageTitle = event.pageTitle, referrer = event.referrer, pb = payloadBuilder();
1448
- pb.add('e', 'pv'); // 'pv' for Page View
1449
- pb.add('url', pageUrl);
1450
- pb.add('page', pageTitle);
1451
- pb.add('refr', referrer);
1452
- return pb;
1453
- }
1454
- /**
1455
- * Build a Structured Event
1456
- * A classic style of event tracking, allows for easier movement between analytics
1457
- * systems. A loosely typed event, creating a Self Describing event is preferred, but
1458
- * useful for interoperability.
1459
- *
1460
- * @param event - Contains the properties for the Structured event
1461
- * @returns PayloadBuilder to be sent to {@link @snowplow/tracker-core#TrackerCore.track}
1462
- */
1463
- function buildStructEvent(event) {
1464
- var category = event.category, action = event.action, label = event.label, property = event.property, value = event.value, pb = payloadBuilder();
1465
- pb.add('e', 'se'); // 'se' for Structured Event
1466
- pb.add('se_ca', category);
1467
- pb.add('se_ac', action);
1468
- pb.add('se_la', label);
1469
- pb.add('se_pr', property);
1470
- pb.add('se_va', value == null ? undefined : value.toString());
1471
- return pb;
1472
- }
1473
-
1474
- function newInMemoryEventStore(_a) {
1475
- var _b = _a.maxSize, maxSize = _b === void 0 ? 1000 : _b, _c = _a.events, events = _c === void 0 ? [] : _c;
1476
- var store = __spreadArray([], events, true);
1477
- var count = function () { return Promise.resolve(store.length); };
1478
- return {
1479
- count: count,
1480
- add: function (payload) {
1481
- store.push(payload);
1482
- while (store.length > maxSize) {
1483
- store.shift();
1484
- }
1485
- return count();
1486
- },
1487
- removeHead: function (count) {
1488
- for (var i = 0; i < count; i++) {
1489
- store.shift();
1490
- }
1491
- return Promise.resolve();
1492
- },
1493
- iterator: function () {
1494
- var index = 0;
1495
- // copy the store to prevent mutation
1496
- var events = __spreadArray([], store, true);
1497
- return {
1498
- next: function () {
1499
- if (index < events.length) {
1500
- return Promise.resolve({ value: events[index++], done: false });
1501
- }
1502
- return Promise.resolve({ value: undefined, done: true });
1503
- },
1504
- };
1505
- },
1506
- getAll: function () { return Promise.resolve(__spreadArray([], store, true)); },
1507
- getAllPayloads: function () { return Promise.resolve(store.map(function (e) { return e.payload; })); },
1508
- };
1509
- }
1510
-
1511
- var PAYLOAD_DATA_SCHEMA = 'iglu:com.snowplowanalytics.snowplow/payload_data/jsonschema/1-0-4';
1512
-
1513
- /**
1514
- * Enclose an array of events in a self-describing payload_data JSON string
1515
- *
1516
- * @param array - events Batch of events
1517
- * @returns string payload_data self-describing JSON
1518
- */
1519
- function encloseInPayloadDataEnvelope(events) {
1520
- return JSON.stringify({
1521
- schema: PAYLOAD_DATA_SCHEMA,
1522
- data: events,
1523
- });
1524
- }
1525
- /**
1526
- * Attaches the STM field to outbound POST events.
1527
- *
1528
- * @param events - the events to attach the STM to
1529
- */
1530
- function attachStmToEvent(events) {
1531
- var stm = new Date().getTime().toString();
1532
- for (var i = 0; i < events.length; i++) {
1533
- events[i]['stm'] = stm;
1534
- }
1535
- return events;
1536
- }
1537
- function newEmitterRequest(_a) {
1538
- var endpoint = _a.endpoint, _b = _a.protocol, protocol = _b === void 0 ? 'https' : _b, port = _a.port, _c = _a.eventMethod, eventMethod = _c === void 0 ? 'post' : _c, customHeaders = _a.customHeaders, connectionTimeout = _a.connectionTimeout, _d = _a.keepalive, keepalive = _d === void 0 ? false : _d, _e = _a.postPath, postPath = _e === void 0 ? '/com.snowplowanalytics.snowplow/tp2' : _e, _f = _a.useStm, useStm = _f === void 0 ? true : _f, _g = _a.maxPostBytes, maxPostBytes = _g === void 0 ? 40000 : _g, _h = _a.credentials, credentials = _h === void 0 ? 'include' : _h;
1539
- var events = [];
1540
- var usePost = eventMethod.toLowerCase() === 'post';
1541
- var timer;
1542
- var abortController;
1543
- function countBytes() {
1544
- var count = events.reduce(function (acc, event) { return acc + (usePost ? event.getPOSTRequestBytesCount() : event.getGETRequestBytesCount()); }, 0);
1545
- if (usePost) {
1546
- count += 88; // 88 bytes for the payload_data envelope
1547
- }
1548
- return count;
1549
- }
1550
- function countEvents() {
1551
- return events.length;
1552
- }
1553
- function getServerAnonymizationOfExistingEvents() {
1554
- return events.length > 0 ? events[0].getServerAnonymization() : undefined;
1555
- }
1556
- function addEvent(event) {
1557
- if (events.length > 0 && getServerAnonymizationOfExistingEvents() !== event.getServerAnonymization()) {
1558
- return false;
1559
- }
1560
- else {
1561
- events.push(event);
1562
- return true;
1563
- }
1564
- }
1565
- function getEvents() {
1566
- return events;
1567
- }
1568
- function isFull() {
1569
- if (usePost) {
1570
- return countBytes() >= maxPostBytes;
1571
- }
1572
- else {
1573
- return events.length >= 1;
1574
- }
1575
- }
1576
- function createHeaders() {
1577
- var headers = new Headers();
1578
- if (usePost) {
1579
- headers.append('Content-Type', 'application/json; charset=UTF-8');
1580
- }
1581
- if (customHeaders) {
1582
- Object.keys(customHeaders).forEach(function (key) {
1583
- headers.append(key, customHeaders[key]);
1584
- });
1585
- }
1586
- if (getServerAnonymizationOfExistingEvents()) {
1587
- headers.append('SP-Anonymous', '*');
1588
- }
1589
- return headers;
1590
- }
1591
- function getFullCollectorUrl() {
1592
- var collectorUrl = endpoint;
1593
- if (!endpoint.includes('://')) {
1594
- collectorUrl = "".concat(protocol, "://").concat(endpoint);
1595
- }
1596
- if (port) {
1597
- collectorUrl = "".concat(collectorUrl, ":").concat(port);
1598
- }
1599
- var path = usePost ? postPath : '/i';
1600
- return collectorUrl + path;
1601
- }
1602
- function makeRequest(url, options) {
1603
- closeRequest(false);
1604
- abortController = new AbortController();
1605
- timer = setTimeout(function () {
1606
- var reason = 'Request timed out';
1607
- console.error(reason);
1608
- timer = undefined;
1609
- closeRequest(false, reason);
1610
- }, connectionTimeout !== null && connectionTimeout !== void 0 ? connectionTimeout : 5000);
1611
- var requestOptions = __assign({ headers: createHeaders(), signal: abortController.signal, keepalive: keepalive, credentials: credentials }, options);
1612
- var request = new Request(url, requestOptions);
1613
- return request;
1614
- }
1615
- function makePostRequest() {
1616
- var batch = attachStmToEvent(events.map(function (event) { return event.getPOSTRequestBody(); }));
1617
- return makeRequest(getFullCollectorUrl(), {
1618
- method: 'POST',
1619
- body: encloseInPayloadDataEnvelope(batch),
1620
- });
1621
- }
1622
- function makeGetRequest() {
1623
- if (events.length !== 1) {
1624
- throw new Error('Only one event can be sent in a GET request');
1625
- }
1626
- var event = events[0];
1627
- var url = event.getGETRequestURL(getFullCollectorUrl(), useStm);
1628
- return makeRequest(url, {
1629
- method: 'GET',
1630
- });
1631
- }
1632
- function toRequest() {
1633
- if (events.length === 0) {
1634
- return undefined;
1635
- }
1636
- if (usePost) {
1637
- return makePostRequest();
1638
- }
1639
- else {
1640
- return makeGetRequest();
1641
- }
1642
- }
1643
- function closeRequest(successful, reason) {
1644
- if (timer !== undefined) {
1645
- clearTimeout(timer);
1646
- timer = undefined;
1647
- }
1648
- if (abortController !== undefined) {
1649
- var controller = abortController;
1650
- abortController = undefined;
1651
- if (!successful) {
1652
- controller.abort(reason);
1653
- }
1654
- }
1655
- }
1656
- return {
1657
- addEvent: addEvent,
1658
- getEvents: getEvents,
1659
- toRequest: toRequest,
1660
- countBytes: countBytes,
1661
- countEvents: countEvents,
1662
- isFull: isFull,
1663
- closeRequest: closeRequest,
1664
- };
1665
- }
1666
-
1667
- /**
1668
- * Count the number of bytes a string will occupy when UTF-8 encoded
1669
- * Taken from http://stackoverflow.com/questions/2848462/count-bytes-in-textarea-using-javascript/
1670
- *
1671
- * @param s - The string
1672
- * @returns number Length of s in bytes when UTF-8 encoded
1673
- */
1674
- function getUTF8Length(s) {
1675
- var len = 0;
1676
- for (var i = 0; i < s.length; i++) {
1677
- var code = s.charCodeAt(i);
1678
- if (code <= 0x7f) {
1679
- len += 1;
1680
- }
1681
- else if (code <= 0x7ff) {
1682
- len += 2;
1683
- }
1684
- else if (code >= 0xd800 && code <= 0xdfff) {
1685
- // Surrogate pair: These take 4 bytes in UTF-8 and 2 chars in UCS-2
1686
- // (Assume next char is the other [valid] half and just skip it)
1687
- len += 4;
1688
- i++;
1689
- }
1690
- else if (code < 0xffff) {
1691
- len += 3;
1692
- }
1693
- else {
1694
- len += 4;
1695
- }
1696
- }
1697
- return len;
1698
- }
1699
- /*
1700
- * Convert a dictionary to a querystring
1701
- * The context field is the last in the querystring
1702
- */
1703
- function getQuerystring(request) {
1704
- var lowPriorityKeys = { co: true, cx: true };
1705
- var args = [];
1706
- for (var key in request) {
1707
- if (request.hasOwnProperty(key) && !lowPriorityKeys[key]) {
1708
- args.push(key + '=' + encodeURIComponent(request[key]));
1709
- }
1710
- }
1711
- for (var contextKey in lowPriorityKeys) {
1712
- if (request.hasOwnProperty(contextKey) && lowPriorityKeys[contextKey]) {
1713
- args.push(contextKey + '=' + encodeURIComponent(request[contextKey]));
1714
- }
1715
- }
1716
- return '?' + args.join('&');
1717
- }
1718
- /*
1719
- * Convert numeric fields to strings to match payload_data schema
1720
- */
1721
- function preparePostBody(request) {
1722
- var cleanedRequest = Object.keys(request)
1723
- .map(function (k) { return [k, request[k]]; })
1724
- .reduce(function (acc, _a) {
1725
- var key = _a[0], value = _a[1];
1726
- acc[key] = value.toString();
1727
- return acc;
1728
- }, {});
1729
- return cleanedRequest;
1730
- }
1731
- function newEmitterEvent(eventStorePayload) {
1732
- var querystring = null;
1733
- var postBody = null;
1734
- var byteCountGET = null;
1735
- var byteCountPOST = null;
1736
- function getPayload() {
1737
- return eventStorePayload.payload;
1738
- }
1739
- function getServerAnonymization() {
1740
- var _a;
1741
- return (_a = eventStorePayload.svrAnon) !== null && _a !== void 0 ? _a : false;
1742
- }
1743
- function getCachedQuerystring(payload) {
1744
- if (querystring === null) {
1745
- querystring = getQuerystring(payload);
1746
- }
1747
- return querystring;
1748
- }
1749
- function getGETRequestURL(collectorUrl, useStm) {
1750
- var querystring = getCachedQuerystring(getPayload());
1751
- if (useStm) {
1752
- return collectorUrl + querystring.replace('?', '?stm=' + new Date().getTime() + '&');
1753
- }
1754
- return collectorUrl + querystring;
1755
- }
1756
- function getGETRequestBytesCount() {
1757
- if (byteCountGET === null) {
1758
- var querystring_1 = getCachedQuerystring(getPayload());
1759
- byteCountGET = getUTF8Length(querystring_1);
1760
- }
1761
- return byteCountGET;
1762
- }
1763
- function getPOSTRequestBody() {
1764
- if (postBody === null) {
1765
- postBody = preparePostBody(getPayload());
1766
- }
1767
- return postBody;
1768
- }
1769
- function getPOSTRequestBytesCount() {
1770
- if (byteCountPOST === null) {
1771
- byteCountPOST = getUTF8Length(JSON.stringify(getPOSTRequestBody()));
1772
- }
1773
- return byteCountPOST;
1774
- }
1775
- return {
1776
- getPayload: getPayload,
1777
- getServerAnonymization: getServerAnonymization,
1778
- getGETRequestURL: getGETRequestURL,
1779
- getGETRequestBytesCount: getGETRequestBytesCount,
1780
- getPOSTRequestBody: getPOSTRequestBody,
1781
- getPOSTRequestBytesCount: getPOSTRequestBytesCount,
1782
- };
1783
- }
1784
-
1785
- function newEmitter(_a) {
1786
- var endpoint = _a.endpoint, _b = _a.eventMethod, eventMethod = _b === void 0 ? 'post' : _b, protocol = _a.protocol, port = _a.port, _c = _a.maxPostBytes, maxPostBytes = _c === void 0 ? 40000 : _c, maxGetBytes = _a.maxGetBytes, _d = _a.bufferSize, bufferSize = _d === void 0 ? 1 : _d, customHeaders = _a.customHeaders, serverAnonymization = _a.serverAnonymization, connectionTimeout = _a.connectionTimeout, keepalive = _a.keepalive, idService = _a.idService, _e = _a.dontRetryStatusCodes, dontRetryStatusCodes = _e === void 0 ? [] : _e, _f = _a.retryStatusCodes, retryStatusCodes = _f === void 0 ? [] : _f, _g = _a.retryFailedRequests, retryFailedRequests = _g === void 0 ? true : _g, onRequestFailure = _a.onRequestFailure, onRequestSuccess = _a.onRequestSuccess, _h = _a.customFetch, customFetch = _h === void 0 ? fetch : _h, useStm = _a.useStm, _j = _a.eventStore, eventStore = _j === void 0 ? newInMemoryEventStore({}) : _j, credentials = _a.credentials;
1787
- var idServiceCalled = false;
1788
- var flushInProgress = false;
1789
- var usePost = eventMethod.toLowerCase() === 'post';
1790
- dontRetryStatusCodes = dontRetryStatusCodes.concat([400, 401, 403, 410, 422]);
1791
- function shouldRetryForStatusCode(statusCode) {
1792
- // success, don't retry
1793
- if (statusCode >= 200 && statusCode < 300) {
1794
- return false;
1795
- }
1796
- if (!retryFailedRequests) {
1797
- return false;
1798
- }
1799
- // retry if status code among custom user-supplied retry codes
1800
- if (retryStatusCodes.includes(statusCode)) {
1801
- return true;
1802
- }
1803
- // retry if status code *not* among the don't retry codes
1804
- return !dontRetryStatusCodes.includes(statusCode);
1805
- }
1806
- function callOnRequestSuccess(payloads, response) {
1807
- if (onRequestSuccess !== undefined) {
1808
- setTimeout(function () {
1809
- try {
1810
- onRequestSuccess === null || onRequestSuccess === void 0 ? void 0 : onRequestSuccess(payloads, response);
1811
- }
1812
- catch (e) {
1813
- LOG.error('Error in onRequestSuccess', e);
1814
- }
1815
- }, 0);
1816
- }
1817
- }
1818
- function callOnRequestFailure(failure, response) {
1819
- if (onRequestFailure !== undefined) {
1820
- setTimeout(function () {
1821
- try {
1822
- onRequestFailure === null || onRequestFailure === void 0 ? void 0 : onRequestFailure(failure, response);
1823
- }
1824
- catch (e) {
1825
- LOG.error('Error in onRequestFailure', e);
1826
- }
1827
- }, 0);
1828
- }
1829
- }
1830
- function executeRequest(request) {
1831
- return __awaiter(this, void 0, void 0, function () {
1832
- var fetchRequest, payloads, response, willRetry, e_1, message;
1833
- return __generator(this, function (_a) {
1834
- switch (_a.label) {
1835
- case 0:
1836
- fetchRequest = request.toRequest();
1837
- if (fetchRequest === undefined) {
1838
- throw new Error('Empty batch');
1839
- }
1840
- payloads = request.getEvents().map(function (event) { return event.getPayload(); });
1841
- _a.label = 1;
1842
- case 1:
1843
- _a.trys.push([1, 4, , 5]);
1844
- return [4 /*yield*/, customFetch(fetchRequest)];
1845
- case 2:
1846
- response = _a.sent();
1847
- return [4 /*yield*/, response.text()];
1848
- case 3:
1849
- _a.sent(); // wait for the response to be fully read
1850
- request.closeRequest(true);
1851
- if (response.ok) {
1852
- callOnRequestSuccess(payloads, response);
1853
- return [2 /*return*/, { success: true, retry: false, status: response.status }];
1854
- }
1855
- else {
1856
- willRetry = shouldRetryForStatusCode(response.status);
1857
- callOnRequestFailure({
1858
- events: payloads,
1859
- status: response.status,
1860
- message: response.statusText,
1861
- willRetry: willRetry,
1862
- }, response);
1863
- return [2 /*return*/, { success: false, retry: willRetry, status: response.status }];
1864
- }
1865
- case 4:
1866
- e_1 = _a.sent();
1867
- request.closeRequest(false);
1868
- message = typeof e_1 === 'string' ? e_1 : e_1 ? e_1.message : 'Unknown error';
1869
- callOnRequestFailure({
1870
- events: payloads,
1871
- message: message,
1872
- willRetry: true,
1873
- });
1874
- return [2 /*return*/, { success: false, retry: true }];
1875
- case 5: return [2 /*return*/];
1876
- }
1877
- });
1878
- });
1879
- }
1880
- function newEmitterRequestWithConfig() {
1881
- return newEmitterRequest({
1882
- endpoint: endpoint,
1883
- protocol: protocol,
1884
- port: port,
1885
- eventMethod: eventMethod,
1886
- customHeaders: customHeaders,
1887
- connectionTimeout: connectionTimeout,
1888
- keepalive: keepalive,
1889
- maxPostBytes: maxPostBytes,
1890
- useStm: useStm,
1891
- credentials: credentials,
1892
- });
1893
- }
1894
- function shouldSkipEventStore(emitterEvent) {
1895
- var eventTooBigWarning = function (bytes, maxBytes) {
1896
- return LOG.warn('Event (' + bytes + 'B) too big, max is ' + maxBytes);
1897
- };
1898
- if (usePost) {
1899
- var bytes = emitterEvent.getPOSTRequestBytesCount() + 88; // 88 bytes for the payload_data envelope
1900
- var tooBig = bytes > maxPostBytes;
1901
- if (tooBig) {
1902
- eventTooBigWarning(bytes, maxPostBytes);
1903
- }
1904
- return tooBig;
1905
- }
1906
- else {
1907
- if (maxGetBytes === undefined) {
1908
- return false;
1909
- }
1910
- var bytes = emitterEvent.getGETRequestBytesCount();
1911
- var tooBig = bytes > maxGetBytes;
1912
- if (tooBig) {
1913
- eventTooBigWarning(bytes, maxGetBytes);
1914
- }
1915
- return tooBig;
1916
- }
1917
- }
1918
- function callIdService() {
1919
- return __awaiter(this, void 0, void 0, function () {
1920
- var request;
1921
- return __generator(this, function (_a) {
1922
- switch (_a.label) {
1923
- case 0:
1924
- if (!(idService && !idServiceCalled)) return [3 /*break*/, 2];
1925
- idServiceCalled = true;
1926
- request = new Request(idService, { method: 'GET' });
1927
- return [4 /*yield*/, customFetch(request)];
1928
- case 1:
1929
- _a.sent();
1930
- _a.label = 2;
1931
- case 2: return [2 /*return*/];
1932
- }
1933
- });
1934
- });
1935
- }
1936
- function flush() {
1937
- return __awaiter(this, void 0, void 0, function () {
1938
- var e_2;
1939
- return __generator(this, function (_a) {
1940
- switch (_a.label) {
1941
- case 0:
1942
- if (!!flushInProgress) return [3 /*break*/, 5];
1943
- flushInProgress = true;
1944
- _a.label = 1;
1945
- case 1:
1946
- _a.trys.push([1, 3, 4, 5]);
1947
- return [4 /*yield*/, continueFlush()];
1948
- case 2:
1949
- _a.sent();
1950
- return [3 /*break*/, 5];
1951
- case 3:
1952
- e_2 = _a.sent();
1953
- LOG.error('Error sending events', e_2);
1954
- return [3 /*break*/, 5];
1955
- case 4:
1956
- flushInProgress = false;
1957
- return [7 /*endfinally*/];
1958
- case 5: return [2 /*return*/];
1959
- }
1960
- });
1961
- });
1962
- }
1963
- function continueFlush() {
1964
- return __awaiter(this, void 0, void 0, function () {
1965
- var request, eventStoreIterator, _a, value, done, event_1, _b, success, retry, status;
1966
- return __generator(this, function (_c) {
1967
- switch (_c.label) {
1968
- case 0: return [4 /*yield*/, callIdService()];
1969
- case 1:
1970
- _c.sent();
1971
- request = newEmitterRequestWithConfig();
1972
- eventStoreIterator = eventStore.iterator();
1973
- _c.label = 2;
1974
- case 2:
1975
- if (request.isFull()) {
1976
- return [3 /*break*/, 4];
1977
- }
1978
- return [4 /*yield*/, eventStoreIterator.next()];
1979
- case 3:
1980
- _a = _c.sent(), value = _a.value, done = _a.done;
1981
- if (done || value === undefined) {
1982
- return [3 /*break*/, 4];
1983
- }
1984
- event_1 = newEmitterEvent(value);
1985
- if (!request.addEvent(event_1)) {
1986
- return [3 /*break*/, 4];
1987
- }
1988
- return [3 /*break*/, 2];
1989
- case 4:
1990
- if (request.countEvents() === 0) {
1991
- return [2 /*return*/];
1992
- }
1993
- return [4 /*yield*/, executeRequest(request)];
1994
- case 5:
1995
- _b = _c.sent(), success = _b.success, retry = _b.retry, status = _b.status;
1996
- if (!(success || !retry)) return [3 /*break*/, 7];
1997
- if (!success) {
1998
- LOG.error("Status ".concat(status, ", will not retry."));
1999
- }
2000
- return [4 /*yield*/, eventStore.removeHead(request.countEvents())];
2001
- case 6:
2002
- _c.sent();
2003
- _c.label = 7;
2004
- case 7:
2005
- if (!success) return [3 /*break*/, 9];
2006
- return [4 /*yield*/, continueFlush()];
2007
- case 8:
2008
- _c.sent();
2009
- _c.label = 9;
2010
- case 9: return [2 /*return*/];
2011
- }
2012
- });
2013
- });
2014
- }
2015
- function input(payload) {
2016
- return __awaiter(this, void 0, void 0, function () {
2017
- var eventStorePayload, event, request, count;
2018
- return __generator(this, function (_a) {
2019
- switch (_a.label) {
2020
- case 0:
2021
- eventStorePayload = newEventStorePayload({ payload: payload, svrAnon: serverAnonymization });
2022
- event = newEmitterEvent(eventStorePayload);
2023
- if (!shouldSkipEventStore(event)) return [3 /*break*/, 2];
2024
- request = newEmitterRequestWithConfig();
2025
- request.addEvent(event);
2026
- return [4 /*yield*/, executeRequest(request)];
2027
- case 1:
2028
- _a.sent();
2029
- return [3 /*break*/, 5];
2030
- case 2: return [4 /*yield*/, eventStore.add(eventStorePayload)];
2031
- case 3:
2032
- count = _a.sent();
2033
- if (!(count >= bufferSize)) return [3 /*break*/, 5];
2034
- return [4 /*yield*/, flush()];
2035
- case 4:
2036
- _a.sent();
2037
- _a.label = 5;
2038
- case 5: return [2 /*return*/];
2039
- }
2040
- });
2041
- });
2042
- }
2043
- function setCollectorUrl(url) {
2044
- endpoint = url;
2045
- }
2046
- function setAnonymousTracking(at) {
2047
- serverAnonymization = at;
2048
- }
2049
- function setBufferSize(bs) {
2050
- bufferSize = bs;
2051
- }
2052
- return {
2053
- flush: flush,
2054
- input: input,
2055
- setCollectorUrl: setCollectorUrl,
2056
- setAnonymousTracking: setAnonymousTracking,
2057
- setBufferSize: setBufferSize,
2058
- };
2059
- }
2060
-
2061
- /*
2062
- * Copyright (c) 2022 Snowplow Analytics Ltd, 2010 Anthon Pang
2063
- * All rights reserved.
2064
- *
2065
- * Redistribution and use in source and binary forms, with or without
2066
- * modification, are permitted provided that the following conditions are met:
2067
- *
2068
- * 1. Redistributions of source code must retain the above copyright notice, this
2069
- * list of conditions and the following disclaimer.
2070
- *
2071
- * 2. Redistributions in binary form must reproduce the above copyright notice,
2072
- * this list of conditions and the following disclaimer in the documentation
2073
- * and/or other materials provided with the distribution.
2074
- *
2075
- * 3. Neither the name of the copyright holder nor the names of its
2076
- * contributors may be used to endorse or promote products derived from
2077
- * this software without specific prior written permission.
2078
- *
2079
- * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
2080
- * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2081
- * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
2082
- * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
2083
- * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2084
- * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
2085
- * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
2086
- * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
2087
- * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
2088
- * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2089
- */
2090
- var version = version$1;
2091
-
2092
- var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
2093
-
2094
- var isPlainObj = value => {
2095
- if (Object.prototype.toString.call(value) !== '[object Object]') {
2096
- return false;
2097
- }
2098
-
2099
- const prototype = Object.getPrototypeOf(value);
2100
- return prototype === null || prototype === Object.prototype;
2101
- };
2102
-
2103
- const isOptionObject = isPlainObj;
2104
-
2105
- const {hasOwnProperty} = Object.prototype;
2106
- const {propertyIsEnumerable} = Object;
2107
- const defineProperty = (object, name, value) => Object.defineProperty(object, name, {
2108
- value,
2109
- writable: true,
2110
- enumerable: true,
2111
- configurable: true
2112
- });
2113
-
2114
- const globalThis$1 = commonjsGlobal;
2115
- const defaultMergeOptions = {
2116
- concatArrays: false,
2117
- ignoreUndefined: false
2118
- };
2119
-
2120
- const getEnumerableOwnPropertyKeys = value => {
2121
- const keys = [];
2122
-
2123
- for (const key in value) {
2124
- if (hasOwnProperty.call(value, key)) {
2125
- keys.push(key);
2126
- }
2127
- }
2128
-
2129
- /* istanbul ignore else */
2130
- if (Object.getOwnPropertySymbols) {
2131
- const symbols = Object.getOwnPropertySymbols(value);
2132
-
2133
- for (const symbol of symbols) {
2134
- if (propertyIsEnumerable.call(value, symbol)) {
2135
- keys.push(symbol);
2136
- }
2137
- }
2138
- }
2139
-
2140
- return keys;
2141
- };
2142
-
2143
- function clone(value) {
2144
- if (Array.isArray(value)) {
2145
- return cloneArray(value);
2146
- }
2147
-
2148
- if (isOptionObject(value)) {
2149
- return cloneOptionObject(value);
2150
- }
2151
-
2152
- return value;
2153
- }
2154
-
2155
- function cloneArray(array) {
2156
- const result = array.slice(0, 0);
2157
-
2158
- getEnumerableOwnPropertyKeys(array).forEach(key => {
2159
- defineProperty(result, key, clone(array[key]));
2160
- });
2161
-
2162
- return result;
2163
- }
2164
-
2165
- function cloneOptionObject(object) {
2166
- const result = Object.getPrototypeOf(object) === null ? Object.create(null) : {};
2167
-
2168
- getEnumerableOwnPropertyKeys(object).forEach(key => {
2169
- defineProperty(result, key, clone(object[key]));
2170
- });
2171
-
2172
- return result;
2173
- }
2174
-
2175
- /**
2176
- * @param {*} merged already cloned
2177
- * @param {*} source something to merge
2178
- * @param {string[]} keys keys to merge
2179
- * @param {Object} config Config Object
2180
- * @returns {*} cloned Object
2181
- */
2182
- const mergeKeys = (merged, source, keys, config) => {
2183
- keys.forEach(key => {
2184
- if (typeof source[key] === 'undefined' && config.ignoreUndefined) {
2185
- return;
2186
- }
2187
-
2188
- // Do not recurse into prototype chain of merged
2189
- if (key in merged && merged[key] !== Object.getPrototypeOf(merged)) {
2190
- defineProperty(merged, key, merge$1(merged[key], source[key], config));
2191
- } else {
2192
- defineProperty(merged, key, clone(source[key]));
2193
- }
2194
- });
2195
-
2196
- return merged;
2197
- };
2198
-
2199
- /**
2200
- * @param {*} merged already cloned
2201
- * @param {*} source something to merge
2202
- * @param {Object} config Config Object
2203
- * @returns {*} cloned Object
2204
- *
2205
- * see [Array.prototype.concat ( ...arguments )](http://www.ecma-international.org/ecma-262/6.0/#sec-array.prototype.concat)
2206
- */
2207
- const concatArrays = (merged, source, config) => {
2208
- let result = merged.slice(0, 0);
2209
- let resultIndex = 0;
2210
-
2211
- [merged, source].forEach(array => {
2212
- const indices = [];
2213
-
2214
- // `result.concat(array)` with cloning
2215
- for (let k = 0; k < array.length; k++) {
2216
- if (!hasOwnProperty.call(array, k)) {
2217
- continue;
2218
- }
2219
-
2220
- indices.push(String(k));
2221
-
2222
- if (array === merged) {
2223
- // Already cloned
2224
- defineProperty(result, resultIndex++, array[k]);
2225
- } else {
2226
- defineProperty(result, resultIndex++, clone(array[k]));
2227
- }
2228
- }
2229
-
2230
- // Merge non-index keys
2231
- result = mergeKeys(result, array, getEnumerableOwnPropertyKeys(array).filter(key => !indices.includes(key)), config);
2232
- });
2233
-
2234
- return result;
2235
- };
2236
-
2237
- /**
2238
- * @param {*} merged already cloned
2239
- * @param {*} source something to merge
2240
- * @param {Object} config Config Object
2241
- * @returns {*} cloned Object
2242
- */
2243
- function merge$1(merged, source, config) {
2244
- if (config.concatArrays && Array.isArray(merged) && Array.isArray(source)) {
2245
- return concatArrays(merged, source, config);
2246
- }
2247
-
2248
- if (!isOptionObject(source) || !isOptionObject(merged)) {
2249
- return clone(source);
2250
- }
2251
-
2252
- return mergeKeys(merged, source, getEnumerableOwnPropertyKeys(source), config);
2253
- }
2254
-
2255
- var mergeOptions = function (...options) {
2256
- const config = merge$1(clone(defaultMergeOptions), (this !== globalThis$1 && this) || {}, defaultMergeOptions);
2257
- let merged = {_: {}};
2258
-
2259
- for (const option of options) {
2260
- if (option === undefined) {
2261
- continue;
2262
- }
2263
-
2264
- if (!isOptionObject(option)) {
2265
- throw new TypeError('`' + option + '` is not an Option Object');
2266
- }
2267
-
2268
- merged = merge$1(merged, {_: option}, config);
2269
- }
2270
-
2271
- return merged._;
2272
- };
2273
-
2274
- var mergeOptions$1 = mergeOptions;
2275
-
2276
- /**
2277
- * Copyright (c) Nicolas Gallagher.
2278
- * Copyright (c) Facebook, Inc. and its affiliates.
2279
- *
2280
- * This source code is licensed under the MIT license found in the
2281
- * LICENSE file in the root directory of this source tree.
2282
- */
2283
-
2284
- // eslint-disable-next-line @typescript-eslint/ban-types
2285
-
2286
- // eslint-disable-next-line @typescript-eslint/ban-types
2287
-
2288
- const merge = mergeOptions$1.bind({
2289
- concatArrays: true,
2290
- ignoreUndefined: true
2291
- });
2292
- function mergeLocalStorageItem(key, value) {
2293
- const oldValue = window.localStorage.getItem(key);
2294
- if (oldValue) {
2295
- const oldObject = JSON.parse(oldValue);
2296
- const newObject = JSON.parse(value);
2297
- const nextValue = JSON.stringify(merge(oldObject, newObject));
2298
- window.localStorage.setItem(key, nextValue);
2299
- } else {
2300
- window.localStorage.setItem(key, value);
2301
- }
2302
- }
2303
- function createPromise(getValue, callback) {
2304
- return new Promise((resolve, reject) => {
2305
- try {
2306
- const value = getValue();
2307
- callback === null || callback === void 0 ? void 0 : callback(null, value);
2308
- resolve(value);
2309
- } catch (err) {
2310
- callback === null || callback === void 0 ? void 0 : callback(err);
2311
- reject(err);
2312
- }
2313
- });
2314
- }
2315
- function createPromiseAll(promises, callback, processResult) {
2316
- return Promise.all(promises).then(result => {
2317
- const value = (processResult === null || processResult === void 0 ? void 0 : processResult(result)) ?? null;
2318
- callback === null || callback === void 0 ? void 0 : callback(null, value);
2319
- return Promise.resolve(value);
2320
- }, errors => {
2321
- callback === null || callback === void 0 ? void 0 : callback(errors);
2322
- return Promise.reject(errors);
2323
- });
2324
- }
2325
- const AsyncStorage = {
2326
- /**
2327
- * Fetches `key` value.
2328
- */
2329
- getItem: (key, callback) => {
2330
- return createPromise(() => window.localStorage.getItem(key), callback);
2331
- },
2332
- /**
2333
- * Sets `value` for `key`.
2334
- */
2335
- setItem: (key, value, callback) => {
2336
- return createPromise(() => window.localStorage.setItem(key, value), callback);
2337
- },
2338
- /**
2339
- * Removes a `key`
2340
- */
2341
- removeItem: (key, callback) => {
2342
- return createPromise(() => window.localStorage.removeItem(key), callback);
2343
- },
2344
- /**
2345
- * Merges existing value with input value, assuming they are stringified JSON.
2346
- */
2347
- mergeItem: (key, value, callback) => {
2348
- return createPromise(() => mergeLocalStorageItem(key, value), callback);
2349
- },
2350
- /**
2351
- * Erases *all* AsyncStorage for the domain.
2352
- */
2353
- clear: callback => {
2354
- return createPromise(() => window.localStorage.clear(), callback);
2355
- },
2356
- /**
2357
- * Gets *all* keys known to the app, for all callers, libraries, etc.
2358
- */
2359
- getAllKeys: callback => {
2360
- return createPromise(() => {
2361
- const numberOfKeys = window.localStorage.length;
2362
- const keys = [];
2363
- for (let i = 0; i < numberOfKeys; i += 1) {
2364
- const key = window.localStorage.key(i) || "";
2365
- keys.push(key);
2366
- }
2367
- return keys;
2368
- }, callback);
2369
- },
2370
- /**
2371
- * (stub) Flushes any pending requests using a single batch call to get the data.
2372
- */
2373
- flushGetRequests: () => undefined,
2374
- /**
2375
- * multiGet resolves to an array of key-value pair arrays that matches the
2376
- * input format of multiSet.
2377
- *
2378
- * multiGet(['k1', 'k2']) -> [['k1', 'val1'], ['k2', 'val2']]
2379
- */
2380
- multiGet: (keys, callback) => {
2381
- const promises = keys.map(key => AsyncStorage.getItem(key));
2382
- const processResult = result => result.map((value, i) => [keys[i], value]);
2383
- return createPromiseAll(promises, callback, processResult);
2384
- },
2385
- /**
2386
- * Takes an array of key-value array pairs.
2387
- * multiSet([['k1', 'val1'], ['k2', 'val2']])
2388
- */
2389
- multiSet: (keyValuePairs, callback) => {
2390
- const promises = keyValuePairs.map(item => AsyncStorage.setItem(item[0], item[1]));
2391
- return createPromiseAll(promises, callback);
2392
- },
2393
- /**
2394
- * Delete all the keys in the `keys` array.
2395
- */
2396
- multiRemove: (keys, callback) => {
2397
- const promises = keys.map(key => AsyncStorage.removeItem(key));
2398
- return createPromiseAll(promises, callback);
2399
- },
2400
- /**
2401
- * Takes an array of key-value array pairs and merges them with existing
2402
- * values, assuming they are stringified JSON.
2403
- *
2404
- * multiMerge([['k1', 'val1'], ['k2', 'val2']])
2405
- */
2406
- multiMerge: (keyValuePairs, callback) => {
2407
- const promises = keyValuePairs.map(item => AsyncStorage.mergeItem(item[0], item[1]));
2408
- return createPromiseAll(promises, callback);
2409
- }
2410
- };
2411
- var AsyncStorage$1 = AsyncStorage;
2412
-
2413
- function newReactNativeEventStore(_a) {
2414
- var namespace = _a.namespace, _b = _a.maxEventStoreSize, maxEventStoreSize = _b === void 0 ? 1000 : _b, _c = _a.useAsyncStorageForEventStore, useAsyncStorage = _c === void 0 ? true : _c;
2415
- return __awaiter(this, void 0, void 0, function () {
2416
- function newInMemoryEventStoreForReactNative() {
2417
- return __awaiter(this, void 0, void 0, function () {
2418
- var data, events;
2419
- return __generator(this, function (_a) {
2420
- switch (_a.label) {
2421
- case 0:
2422
- if (!useAsyncStorage) return [3 /*break*/, 2];
2423
- return [4 /*yield*/, AsyncStorage$1.getItem(queueName)];
2424
- case 1:
2425
- data = _a.sent();
2426
- events = data ? JSON.parse(data) : [];
2427
- return [2 /*return*/, newInMemoryEventStore({ maxSize: maxEventStoreSize, events: events })];
2428
- case 2: return [2 /*return*/, newInMemoryEventStore({ maxSize: maxEventStoreSize })];
2429
- }
2430
- });
2431
- });
2432
- }
2433
- function sync() {
2434
- return __awaiter(this, void 0, void 0, function () {
2435
- var events;
2436
- return __generator(this, function (_a) {
2437
- switch (_a.label) {
2438
- case 0:
2439
- if (!useAsyncStorage) return [3 /*break*/, 3];
2440
- return [4 /*yield*/, getAll()];
2441
- case 1:
2442
- events = _a.sent();
2443
- return [4 /*yield*/, AsyncStorage$1.setItem(queueName, JSON.stringify(events))];
2444
- case 2:
2445
- _a.sent();
2446
- _a.label = 3;
2447
- case 3: return [2 /*return*/];
2448
- }
2449
- });
2450
- });
2451
- }
2452
- var queueName, eventStore, getAll, getAllPayloads, add, count, iterator, removeHead;
2453
- var _this = this;
2454
- return __generator(this, function (_d) {
2455
- switch (_d.label) {
2456
- case 0:
2457
- queueName = "snowplow_".concat(namespace);
2458
- return [4 /*yield*/, newInMemoryEventStoreForReactNative()];
2459
- case 1:
2460
- eventStore = _d.sent();
2461
- getAll = eventStore.getAll, getAllPayloads = eventStore.getAllPayloads, add = eventStore.add, count = eventStore.count, iterator = eventStore.iterator, removeHead = eventStore.removeHead;
2462
- return [2 /*return*/, {
2463
- count: count,
2464
- add: function (payload) { return __awaiter(_this, void 0, void 0, function () {
2465
- return __generator(this, function (_a) {
2466
- switch (_a.label) {
2467
- case 0: return [4 /*yield*/, add(payload)];
2468
- case 1:
2469
- _a.sent();
2470
- return [4 /*yield*/, sync()];
2471
- case 2:
2472
- _a.sent();
2473
- return [4 /*yield*/, count()];
2474
- case 3: return [2 /*return*/, _a.sent()];
2475
- }
2476
- });
2477
- }); },
2478
- removeHead: function (n) { return __awaiter(_this, void 0, void 0, function () {
2479
- return __generator(this, function (_a) {
2480
- switch (_a.label) {
2481
- case 0:
2482
- removeHead(n);
2483
- return [4 /*yield*/, sync()];
2484
- case 1:
2485
- _a.sent();
2486
- return [2 /*return*/];
2487
- }
2488
- });
2489
- }); },
2490
- iterator: iterator,
2491
- getAll: getAll,
2492
- getAllPayloads: getAllPayloads,
2493
- }];
2494
- }
2495
- });
2496
- });
2497
- }
2498
-
2499
- function newTrackEventFunctions(core) {
2500
- var trackSelfDescribingEvent = function (argmap, contexts) {
2501
- core.track(buildSelfDescribingEvent({ event: argmap }), contexts);
2502
- };
2503
- var trackStructuredEvent = function (argmap, contexts) {
2504
- var _a;
2505
- return (_a = core.track(buildStructEvent(argmap), contexts)) === null || _a === void 0 ? void 0 : _a.eid;
2506
- };
2507
- var trackPageViewEvent = function (argmap, contexts) {
2508
- var _a;
2509
- return (_a = core.track(buildPageView(argmap), contexts)) === null || _a === void 0 ? void 0 : _a.eid;
2510
- };
2511
- var trackTimingEvent = function (argmap, contexts) {
2512
- trackSelfDescribingEvent({
2513
- schema: 'iglu:com.snowplowanalytics.snowplow/timing/jsonschema/1-0-0',
2514
- data: argmap,
2515
- }, contexts);
2516
- };
2517
- var trackMessageNotificationEvent = function (argmap, contexts) {
2518
- trackSelfDescribingEvent({
2519
- schema: 'iglu:com.snowplowanalytics.mobile/message_notification/jsonschema/1-0-0',
2520
- data: argmap,
2521
- }, contexts);
2522
- };
2523
- return {
2524
- trackSelfDescribingEvent: trackSelfDescribingEvent,
2525
- trackStructuredEvent: trackStructuredEvent,
2526
- trackPageViewEvent: trackPageViewEvent,
2527
- trackTimingEvent: trackTimingEvent,
2528
- trackMessageNotificationEvent: trackMessageNotificationEvent,
2529
- };
2530
- }
2531
-
2532
- function newSubject(core, configuration) {
2533
- var domainUserId;
2534
- var networkUserId;
2535
- var addSubjectToPayload = function (payload) {
2536
- payload.add('duid', domainUserId);
2537
- payload.add('nuid', networkUserId);
2538
- };
2539
- var setScreenResolution = function (screenSize) {
2540
- return core.setScreenResolution(String(screenSize[0]), String(screenSize[1]));
2541
- };
2542
- var setNetworkUserId = function (userId) {
2543
- networkUserId = userId;
2544
- };
2545
- var setDomainUserId = function (userId) {
2546
- domainUserId = userId;
2547
- };
2548
- var setColorDepth = function (colorDepth) {
2549
- core.setColorDepth(String(colorDepth));
2550
- };
2551
- var setScreenViewport = function (screenSize) {
2552
- core.setViewport(String(screenSize[0]), String(screenSize[1]));
2553
- };
2554
- var setSubjectData = function (data) {
2555
- setNetworkUserId(data.networkUserId);
2556
- setDomainUserId(data.domainUserId);
2557
- if (data.userId) {
2558
- core.setUserId(data.userId);
2559
- }
2560
- if (data.useragent) {
2561
- core.setUseragent(data.useragent);
2562
- }
2563
- if (data.ipAddress) {
2564
- core.setIpAddress(data.ipAddress);
2565
- }
2566
- if (data.timezone) {
2567
- core.setTimezone(data.timezone);
2568
- }
2569
- if (data.language) {
2570
- core.setLang(data.language);
2571
- }
2572
- if (data.screenResolution) {
2573
- setScreenResolution(data.screenResolution);
2574
- }
2575
- if (data.colorDepth) {
2576
- setColorDepth(data.colorDepth);
2577
- }
2578
- if (data.screenViewport) {
2579
- setScreenViewport(data.screenViewport);
2580
- }
2581
- };
2582
- if (configuration) {
2583
- setSubjectData(configuration);
2584
- }
2585
- var subjectPlugin = {
2586
- plugin: {
2587
- beforeTrack: addSubjectToPayload,
2588
- },
2589
- };
2590
- return {
2591
- subjectPlugin: subjectPlugin,
2592
- properties: {
2593
- setUserId: core.setUserId,
2594
- setIpAddress: core.setIpAddress,
2595
- setUseragent: core.setUseragent,
2596
- setTimezone: core.setTimezone,
2597
- setLanguage: core.setLang,
2598
- setScreenResolution: setScreenResolution,
2599
- setNetworkUserId: setNetworkUserId,
2600
- setDomainUserId: setDomainUserId,
2601
- setSubjectData: setSubjectData,
2602
- setColorDepth: setColorDepth,
2603
- setScreenViewport: setScreenViewport,
2604
- },
2605
- };
2606
- }
2607
-
2608
- /**
2609
- * Creates a new tracker instance with the given configuration
2610
- * @param configuration - Configuration for the tracker
2611
- * @returns Tracker instance
2612
- */
2613
- function newTracker(configuration) {
2614
- return __awaiter(this, void 0, void 0, function () {
2615
- var namespace, appId, _a, encodeBase64, _b, emitter, callback, core, subject;
2616
- return __generator(this, function (_c) {
2617
- switch (_c.label) {
2618
- case 0:
2619
- namespace = configuration.namespace, appId = configuration.appId, _a = configuration.encodeBase64, encodeBase64 = _a === void 0 ? false : _a;
2620
- if (!(configuration.eventStore === undefined)) return [3 /*break*/, 2];
2621
- _b = configuration;
2622
- return [4 /*yield*/, newReactNativeEventStore(configuration)];
2623
- case 1:
2624
- _b.eventStore = _c.sent();
2625
- _c.label = 2;
2626
- case 2:
2627
- emitter = newEmitter(configuration);
2628
- callback = function (payload) {
2629
- emitter.input(payload.build());
2630
- };
2631
- core = trackerCore({ base64: encodeBase64, callback: callback });
2632
- subject = newSubject(core, configuration);
2633
- core.addPlugin(subject.subjectPlugin);
2634
- core.setPlatform('mob'); // default platform
2635
- core.setTrackerVersion('rn-' + version);
2636
- core.setTrackerNamespace(namespace);
2637
- if (appId) {
2638
- core.setAppId(appId);
2639
- }
2640
- return [2 /*return*/, __assign(__assign(__assign({}, newTrackEventFunctions(core)), subject.properties), { setAppId: core.setAppId, setPlatform: core.setPlatform, flush: emitter.flush, addGlobalContexts: core.addGlobalContexts, removeGlobalContexts: core.removeGlobalContexts, clearGlobalContexts: core.clearGlobalContexts, addPlugin: core.addPlugin })];
2641
- }
2642
- });
2643
- });
2644
- }
2645
-
2646
- if (typeof crypto === 'undefined') {
2647
- throw new Error('Web Crypto is not available. Please use a polyfill like react-native-get-random-values');
2648
- }
2649
-
2650
- exports.newTracker = newTracker;
2651
- exports.version = version;
2652
-
2653
- Object.defineProperty(exports, '__esModule', { value: true });
2654
-
2655
- }));
2656
- //# sourceMappingURL=index.cjs.js.map