@authsignal/browser 0.0.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.
@@ -0,0 +1,3771 @@
1
+ /******************************************************************************
2
+ Copyright (c) Microsoft Corporation.
3
+
4
+ Permission to use, copy, modify, and/or distribute this software for any
5
+ purpose with or without fee is hereby granted.
6
+
7
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
8
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
9
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
10
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
11
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
12
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
13
+ PERFORMANCE OF THIS SOFTWARE.
14
+ ***************************************************************************** */
15
+
16
+ var __assign = function() {
17
+ __assign = Object.assign || function __assign(t) {
18
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
19
+ s = arguments[i];
20
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];
21
+ }
22
+ return t;
23
+ };
24
+ return __assign.apply(this, arguments);
25
+ };
26
+
27
+ function __awaiter(thisArg, _arguments, P, generator) {
28
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
29
+ return new (P || (P = Promise))(function (resolve, reject) {
30
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
31
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
32
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
33
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
34
+ });
35
+ }
36
+
37
+ function __generator(thisArg, body) {
38
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
39
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
40
+ function verb(n) { return function (v) { return step([n, v]); }; }
41
+ function step(op) {
42
+ if (f) throw new TypeError("Generator is already executing.");
43
+ while (_) try {
44
+ 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;
45
+ if (y = 0, t) op = [op[0] & 2, t.value];
46
+ switch (op[0]) {
47
+ case 0: case 1: t = op; break;
48
+ case 4: _.label++; return { value: op[1], done: false };
49
+ case 5: _.label++; y = op[1]; op = [0]; continue;
50
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
51
+ default:
52
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
53
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
54
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
55
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
56
+ if (t[2]) _.ops.pop();
57
+ _.trys.pop(); continue;
58
+ }
59
+ op = body.call(thisArg, _);
60
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
61
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
62
+ }
63
+ }
64
+
65
+ /** @deprecated */
66
+ function __spreadArrays() {
67
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
68
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
69
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
70
+ r[k] = a[j];
71
+ return r;
72
+ }
73
+
74
+ /**
75
+ * FingerprintJS v3.3.3 - Copyright (c) FingerprintJS, Inc, 2022 (https://fingerprintjs.com)
76
+ * Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) license.
77
+ *
78
+ * This software contains code from open-source projects:
79
+ * MurmurHash3 by Karan Lyons (https://github.com/karanlyons/murmurHash3.js)
80
+ */
81
+
82
+ var version = "3.3.3";
83
+
84
+ function wait(durationMs, resolveWith) {
85
+ return new Promise(function (resolve) { return setTimeout(resolve, durationMs, resolveWith); });
86
+ }
87
+ function requestIdleCallbackIfAvailable(fallbackTimeout, deadlineTimeout) {
88
+ if (deadlineTimeout === void 0) { deadlineTimeout = Infinity; }
89
+ var requestIdleCallback = window.requestIdleCallback;
90
+ if (requestIdleCallback) {
91
+ // The function `requestIdleCallback` loses the binding to `window` here.
92
+ // `globalThis` isn't always equal `window` (see https://github.com/fingerprintjs/fingerprintjs/issues/683).
93
+ // Therefore, an error can occur. `call(window,` prevents the error.
94
+ return new Promise(function (resolve) { return requestIdleCallback.call(window, function () { return resolve(); }, { timeout: deadlineTimeout }); });
95
+ }
96
+ else {
97
+ return wait(Math.min(fallbackTimeout, deadlineTimeout));
98
+ }
99
+ }
100
+ function isPromise(value) {
101
+ return value && typeof value.then === 'function';
102
+ }
103
+ /**
104
+ * Calls a maybe asynchronous function without creating microtasks when the function is synchronous.
105
+ * Catches errors in both cases.
106
+ *
107
+ * If just you run a code like this:
108
+ * ```
109
+ * console.time('Action duration')
110
+ * await action()
111
+ * console.timeEnd('Action duration')
112
+ * ```
113
+ * The synchronous function time can be measured incorrectly because another microtask may run before the `await`
114
+ * returns the control back to the code.
115
+ */
116
+ function awaitIfAsync(action, callback) {
117
+ try {
118
+ var returnedValue = action();
119
+ if (isPromise(returnedValue)) {
120
+ returnedValue.then(function (result) { return callback(true, result); }, function (error) { return callback(false, error); });
121
+ }
122
+ else {
123
+ callback(true, returnedValue);
124
+ }
125
+ }
126
+ catch (error) {
127
+ callback(false, error);
128
+ }
129
+ }
130
+ /**
131
+ * If you run many synchronous tasks without using this function, the JS main loop will be busy and asynchronous tasks
132
+ * (e.g. completing a network request, rendering the page) won't be able to happen.
133
+ * This function allows running many synchronous tasks such way that asynchronous tasks can run too in background.
134
+ */
135
+ function forEachWithBreaks(items, callback, loopReleaseInterval) {
136
+ if (loopReleaseInterval === void 0) { loopReleaseInterval = 16; }
137
+ return __awaiter(this, void 0, void 0, function () {
138
+ var lastLoopReleaseTime, i, now;
139
+ return __generator(this, function (_a) {
140
+ switch (_a.label) {
141
+ case 0:
142
+ lastLoopReleaseTime = Date.now();
143
+ i = 0;
144
+ _a.label = 1;
145
+ case 1:
146
+ if (!(i < items.length)) return [3 /*break*/, 4];
147
+ callback(items[i], i);
148
+ now = Date.now();
149
+ if (!(now >= lastLoopReleaseTime + loopReleaseInterval)) return [3 /*break*/, 3];
150
+ lastLoopReleaseTime = now;
151
+ // Allows asynchronous actions and microtasks to happen
152
+ return [4 /*yield*/, wait(0)];
153
+ case 2:
154
+ // Allows asynchronous actions and microtasks to happen
155
+ _a.sent();
156
+ _a.label = 3;
157
+ case 3:
158
+ ++i;
159
+ return [3 /*break*/, 1];
160
+ case 4: return [2 /*return*/];
161
+ }
162
+ });
163
+ });
164
+ }
165
+
166
+ /*
167
+ * Taken from https://github.com/karanlyons/murmurHash3.js/blob/a33d0723127e2e5415056c455f8aed2451ace208/murmurHash3.js
168
+ */
169
+ //
170
+ // Given two 64bit ints (as an array of two 32bit ints) returns the two
171
+ // added together as a 64bit int (as an array of two 32bit ints).
172
+ //
173
+ function x64Add(m, n) {
174
+ m = [m[0] >>> 16, m[0] & 0xffff, m[1] >>> 16, m[1] & 0xffff];
175
+ n = [n[0] >>> 16, n[0] & 0xffff, n[1] >>> 16, n[1] & 0xffff];
176
+ var o = [0, 0, 0, 0];
177
+ o[3] += m[3] + n[3];
178
+ o[2] += o[3] >>> 16;
179
+ o[3] &= 0xffff;
180
+ o[2] += m[2] + n[2];
181
+ o[1] += o[2] >>> 16;
182
+ o[2] &= 0xffff;
183
+ o[1] += m[1] + n[1];
184
+ o[0] += o[1] >>> 16;
185
+ o[1] &= 0xffff;
186
+ o[0] += m[0] + n[0];
187
+ o[0] &= 0xffff;
188
+ return [(o[0] << 16) | o[1], (o[2] << 16) | o[3]];
189
+ }
190
+ //
191
+ // Given two 64bit ints (as an array of two 32bit ints) returns the two
192
+ // multiplied together as a 64bit int (as an array of two 32bit ints).
193
+ //
194
+ function x64Multiply(m, n) {
195
+ m = [m[0] >>> 16, m[0] & 0xffff, m[1] >>> 16, m[1] & 0xffff];
196
+ n = [n[0] >>> 16, n[0] & 0xffff, n[1] >>> 16, n[1] & 0xffff];
197
+ var o = [0, 0, 0, 0];
198
+ o[3] += m[3] * n[3];
199
+ o[2] += o[3] >>> 16;
200
+ o[3] &= 0xffff;
201
+ o[2] += m[2] * n[3];
202
+ o[1] += o[2] >>> 16;
203
+ o[2] &= 0xffff;
204
+ o[2] += m[3] * n[2];
205
+ o[1] += o[2] >>> 16;
206
+ o[2] &= 0xffff;
207
+ o[1] += m[1] * n[3];
208
+ o[0] += o[1] >>> 16;
209
+ o[1] &= 0xffff;
210
+ o[1] += m[2] * n[2];
211
+ o[0] += o[1] >>> 16;
212
+ o[1] &= 0xffff;
213
+ o[1] += m[3] * n[1];
214
+ o[0] += o[1] >>> 16;
215
+ o[1] &= 0xffff;
216
+ o[0] += m[0] * n[3] + m[1] * n[2] + m[2] * n[1] + m[3] * n[0];
217
+ o[0] &= 0xffff;
218
+ return [(o[0] << 16) | o[1], (o[2] << 16) | o[3]];
219
+ }
220
+ //
221
+ // Given a 64bit int (as an array of two 32bit ints) and an int
222
+ // representing a number of bit positions, returns the 64bit int (as an
223
+ // array of two 32bit ints) rotated left by that number of positions.
224
+ //
225
+ function x64Rotl(m, n) {
226
+ n %= 64;
227
+ if (n === 32) {
228
+ return [m[1], m[0]];
229
+ }
230
+ else if (n < 32) {
231
+ return [(m[0] << n) | (m[1] >>> (32 - n)), (m[1] << n) | (m[0] >>> (32 - n))];
232
+ }
233
+ else {
234
+ n -= 32;
235
+ return [(m[1] << n) | (m[0] >>> (32 - n)), (m[0] << n) | (m[1] >>> (32 - n))];
236
+ }
237
+ }
238
+ //
239
+ // Given a 64bit int (as an array of two 32bit ints) and an int
240
+ // representing a number of bit positions, returns the 64bit int (as an
241
+ // array of two 32bit ints) shifted left by that number of positions.
242
+ //
243
+ function x64LeftShift(m, n) {
244
+ n %= 64;
245
+ if (n === 0) {
246
+ return m;
247
+ }
248
+ else if (n < 32) {
249
+ return [(m[0] << n) | (m[1] >>> (32 - n)), m[1] << n];
250
+ }
251
+ else {
252
+ return [m[1] << (n - 32), 0];
253
+ }
254
+ }
255
+ //
256
+ // Given two 64bit ints (as an array of two 32bit ints) returns the two
257
+ // xored together as a 64bit int (as an array of two 32bit ints).
258
+ //
259
+ function x64Xor(m, n) {
260
+ return [m[0] ^ n[0], m[1] ^ n[1]];
261
+ }
262
+ //
263
+ // Given a block, returns murmurHash3's final x64 mix of that block.
264
+ // (`[0, h[0] >>> 1]` is a 33 bit unsigned right shift. This is the
265
+ // only place where we need to right shift 64bit ints.)
266
+ //
267
+ function x64Fmix(h) {
268
+ h = x64Xor(h, [0, h[0] >>> 1]);
269
+ h = x64Multiply(h, [0xff51afd7, 0xed558ccd]);
270
+ h = x64Xor(h, [0, h[0] >>> 1]);
271
+ h = x64Multiply(h, [0xc4ceb9fe, 0x1a85ec53]);
272
+ h = x64Xor(h, [0, h[0] >>> 1]);
273
+ return h;
274
+ }
275
+ //
276
+ // Given a string and an optional seed as an int, returns a 128 bit
277
+ // hash using the x64 flavor of MurmurHash3, as an unsigned hex.
278
+ //
279
+ function x64hash128(key, seed) {
280
+ key = key || '';
281
+ seed = seed || 0;
282
+ var remainder = key.length % 16;
283
+ var bytes = key.length - remainder;
284
+ var h1 = [0, seed];
285
+ var h2 = [0, seed];
286
+ var k1 = [0, 0];
287
+ var k2 = [0, 0];
288
+ var c1 = [0x87c37b91, 0x114253d5];
289
+ var c2 = [0x4cf5ad43, 0x2745937f];
290
+ var i;
291
+ for (i = 0; i < bytes; i = i + 16) {
292
+ k1 = [
293
+ (key.charCodeAt(i + 4) & 0xff) |
294
+ ((key.charCodeAt(i + 5) & 0xff) << 8) |
295
+ ((key.charCodeAt(i + 6) & 0xff) << 16) |
296
+ ((key.charCodeAt(i + 7) & 0xff) << 24),
297
+ (key.charCodeAt(i) & 0xff) |
298
+ ((key.charCodeAt(i + 1) & 0xff) << 8) |
299
+ ((key.charCodeAt(i + 2) & 0xff) << 16) |
300
+ ((key.charCodeAt(i + 3) & 0xff) << 24),
301
+ ];
302
+ k2 = [
303
+ (key.charCodeAt(i + 12) & 0xff) |
304
+ ((key.charCodeAt(i + 13) & 0xff) << 8) |
305
+ ((key.charCodeAt(i + 14) & 0xff) << 16) |
306
+ ((key.charCodeAt(i + 15) & 0xff) << 24),
307
+ (key.charCodeAt(i + 8) & 0xff) |
308
+ ((key.charCodeAt(i + 9) & 0xff) << 8) |
309
+ ((key.charCodeAt(i + 10) & 0xff) << 16) |
310
+ ((key.charCodeAt(i + 11) & 0xff) << 24),
311
+ ];
312
+ k1 = x64Multiply(k1, c1);
313
+ k1 = x64Rotl(k1, 31);
314
+ k1 = x64Multiply(k1, c2);
315
+ h1 = x64Xor(h1, k1);
316
+ h1 = x64Rotl(h1, 27);
317
+ h1 = x64Add(h1, h2);
318
+ h1 = x64Add(x64Multiply(h1, [0, 5]), [0, 0x52dce729]);
319
+ k2 = x64Multiply(k2, c2);
320
+ k2 = x64Rotl(k2, 33);
321
+ k2 = x64Multiply(k2, c1);
322
+ h2 = x64Xor(h2, k2);
323
+ h2 = x64Rotl(h2, 31);
324
+ h2 = x64Add(h2, h1);
325
+ h2 = x64Add(x64Multiply(h2, [0, 5]), [0, 0x38495ab5]);
326
+ }
327
+ k1 = [0, 0];
328
+ k2 = [0, 0];
329
+ switch (remainder) {
330
+ case 15:
331
+ k2 = x64Xor(k2, x64LeftShift([0, key.charCodeAt(i + 14)], 48));
332
+ // fallthrough
333
+ case 14:
334
+ k2 = x64Xor(k2, x64LeftShift([0, key.charCodeAt(i + 13)], 40));
335
+ // fallthrough
336
+ case 13:
337
+ k2 = x64Xor(k2, x64LeftShift([0, key.charCodeAt(i + 12)], 32));
338
+ // fallthrough
339
+ case 12:
340
+ k2 = x64Xor(k2, x64LeftShift([0, key.charCodeAt(i + 11)], 24));
341
+ // fallthrough
342
+ case 11:
343
+ k2 = x64Xor(k2, x64LeftShift([0, key.charCodeAt(i + 10)], 16));
344
+ // fallthrough
345
+ case 10:
346
+ k2 = x64Xor(k2, x64LeftShift([0, key.charCodeAt(i + 9)], 8));
347
+ // fallthrough
348
+ case 9:
349
+ k2 = x64Xor(k2, [0, key.charCodeAt(i + 8)]);
350
+ k2 = x64Multiply(k2, c2);
351
+ k2 = x64Rotl(k2, 33);
352
+ k2 = x64Multiply(k2, c1);
353
+ h2 = x64Xor(h2, k2);
354
+ // fallthrough
355
+ case 8:
356
+ k1 = x64Xor(k1, x64LeftShift([0, key.charCodeAt(i + 7)], 56));
357
+ // fallthrough
358
+ case 7:
359
+ k1 = x64Xor(k1, x64LeftShift([0, key.charCodeAt(i + 6)], 48));
360
+ // fallthrough
361
+ case 6:
362
+ k1 = x64Xor(k1, x64LeftShift([0, key.charCodeAt(i + 5)], 40));
363
+ // fallthrough
364
+ case 5:
365
+ k1 = x64Xor(k1, x64LeftShift([0, key.charCodeAt(i + 4)], 32));
366
+ // fallthrough
367
+ case 4:
368
+ k1 = x64Xor(k1, x64LeftShift([0, key.charCodeAt(i + 3)], 24));
369
+ // fallthrough
370
+ case 3:
371
+ k1 = x64Xor(k1, x64LeftShift([0, key.charCodeAt(i + 2)], 16));
372
+ // fallthrough
373
+ case 2:
374
+ k1 = x64Xor(k1, x64LeftShift([0, key.charCodeAt(i + 1)], 8));
375
+ // fallthrough
376
+ case 1:
377
+ k1 = x64Xor(k1, [0, key.charCodeAt(i)]);
378
+ k1 = x64Multiply(k1, c1);
379
+ k1 = x64Rotl(k1, 31);
380
+ k1 = x64Multiply(k1, c2);
381
+ h1 = x64Xor(h1, k1);
382
+ // fallthrough
383
+ }
384
+ h1 = x64Xor(h1, [0, key.length]);
385
+ h2 = x64Xor(h2, [0, key.length]);
386
+ h1 = x64Add(h1, h2);
387
+ h2 = x64Add(h2, h1);
388
+ h1 = x64Fmix(h1);
389
+ h2 = x64Fmix(h2);
390
+ h1 = x64Add(h1, h2);
391
+ h2 = x64Add(h2, h1);
392
+ return (('00000000' + (h1[0] >>> 0).toString(16)).slice(-8) +
393
+ ('00000000' + (h1[1] >>> 0).toString(16)).slice(-8) +
394
+ ('00000000' + (h2[0] >>> 0).toString(16)).slice(-8) +
395
+ ('00000000' + (h2[1] >>> 0).toString(16)).slice(-8));
396
+ }
397
+
398
+ /**
399
+ * Converts an error object to a plain object that can be used with `JSON.stringify`.
400
+ * If you just run `JSON.stringify(error)`, you'll get `'{}'`.
401
+ */
402
+ function errorToObject(error) {
403
+ var _a;
404
+ return __assign({ name: error.name, message: error.message, stack: (_a = error.stack) === null || _a === void 0 ? void 0 : _a.split('\n') }, error);
405
+ }
406
+
407
+ /*
408
+ * This file contains functions to work with pure data only (no browser features, DOM, side effects, etc).
409
+ */
410
+ /**
411
+ * Does the same as Array.prototype.includes but has better typing
412
+ */
413
+ function includes(haystack, needle) {
414
+ for (var i = 0, l = haystack.length; i < l; ++i) {
415
+ if (haystack[i] === needle) {
416
+ return true;
417
+ }
418
+ }
419
+ return false;
420
+ }
421
+ /**
422
+ * Like `!includes()` but with proper typing
423
+ */
424
+ function excludes(haystack, needle) {
425
+ return !includes(haystack, needle);
426
+ }
427
+ /**
428
+ * Be careful, NaN can return
429
+ */
430
+ function toInt(value) {
431
+ return parseInt(value);
432
+ }
433
+ /**
434
+ * Be careful, NaN can return
435
+ */
436
+ function toFloat(value) {
437
+ return parseFloat(value);
438
+ }
439
+ function replaceNaN(value, replacement) {
440
+ return typeof value === 'number' && isNaN(value) ? replacement : value;
441
+ }
442
+ function countTruthy(values) {
443
+ return values.reduce(function (sum, value) { return sum + (value ? 1 : 0); }, 0);
444
+ }
445
+ function round(value, base) {
446
+ if (base === void 0) { base = 1; }
447
+ if (Math.abs(base) >= 1) {
448
+ return Math.round(value / base) * base;
449
+ }
450
+ else {
451
+ // Sometimes when a number is multiplied by a small number, precision is lost,
452
+ // for example 1234 * 0.0001 === 0.12340000000000001, and it's more precise divide: 1234 / (1 / 0.0001) === 0.1234.
453
+ var counterBase = 1 / base;
454
+ return Math.round(value * counterBase) / counterBase;
455
+ }
456
+ }
457
+ /**
458
+ * Parses a CSS selector into tag name with HTML attributes.
459
+ * Only single element selector are supported (without operators like space, +, >, etc).
460
+ *
461
+ * Multiple values can be returned for each attribute. You decide how to handle them.
462
+ */
463
+ function parseSimpleCssSelector(selector) {
464
+ var _a, _b;
465
+ var errorMessage = "Unexpected syntax '" + selector + "'";
466
+ var tagMatch = /^\s*([a-z-]*)(.*)$/i.exec(selector);
467
+ var tag = tagMatch[1] || undefined;
468
+ var attributes = {};
469
+ var partsRegex = /([.:#][\w-]+|\[.+?\])/gi;
470
+ var addAttribute = function (name, value) {
471
+ attributes[name] = attributes[name] || [];
472
+ attributes[name].push(value);
473
+ };
474
+ for (;;) {
475
+ var match = partsRegex.exec(tagMatch[2]);
476
+ if (!match) {
477
+ break;
478
+ }
479
+ var part = match[0];
480
+ switch (part[0]) {
481
+ case '.':
482
+ addAttribute('class', part.slice(1));
483
+ break;
484
+ case '#':
485
+ addAttribute('id', part.slice(1));
486
+ break;
487
+ case '[': {
488
+ var attributeMatch = /^\[([\w-]+)([~|^$*]?=("(.*?)"|([\w-]+)))?(\s+[is])?\]$/.exec(part);
489
+ if (attributeMatch) {
490
+ addAttribute(attributeMatch[1], (_b = (_a = attributeMatch[4]) !== null && _a !== void 0 ? _a : attributeMatch[5]) !== null && _b !== void 0 ? _b : '');
491
+ }
492
+ else {
493
+ throw new Error(errorMessage);
494
+ }
495
+ break;
496
+ }
497
+ default:
498
+ throw new Error(errorMessage);
499
+ }
500
+ }
501
+ return [tag, attributes];
502
+ }
503
+
504
+ function ensureErrorWithMessage(error) {
505
+ return error && typeof error === 'object' && 'message' in error ? error : { message: error };
506
+ }
507
+ /**
508
+ * Loads the given entropy source. Returns a function that gets an entropy component from the source.
509
+ *
510
+ * The result is returned synchronously to prevent `loadSources` from
511
+ * waiting for one source to load before getting the components from the other sources.
512
+ */
513
+ function loadSource(source, sourceOptions) {
514
+ var isFinalResultLoaded = function (loadResult) {
515
+ return typeof loadResult !== 'function';
516
+ };
517
+ var sourceLoadPromise = new Promise(function (resolveLoad) {
518
+ var loadStartTime = Date.now();
519
+ // `awaitIfAsync` is used instead of just `await` in order to measure the duration of synchronous sources
520
+ // correctly (other microtasks won't affect the duration).
521
+ awaitIfAsync(source.bind(null, sourceOptions), function () {
522
+ var loadArgs = [];
523
+ for (var _i = 0; _i < arguments.length; _i++) {
524
+ loadArgs[_i] = arguments[_i];
525
+ }
526
+ var loadDuration = Date.now() - loadStartTime;
527
+ // Source loading failed
528
+ if (!loadArgs[0]) {
529
+ return resolveLoad(function () { return ({ error: ensureErrorWithMessage(loadArgs[1]), duration: loadDuration }); });
530
+ }
531
+ var loadResult = loadArgs[1];
532
+ // Source loaded with the final result
533
+ if (isFinalResultLoaded(loadResult)) {
534
+ return resolveLoad(function () { return ({ value: loadResult, duration: loadDuration }); });
535
+ }
536
+ // Source loaded with "get" stage
537
+ resolveLoad(function () {
538
+ return new Promise(function (resolveGet) {
539
+ var getStartTime = Date.now();
540
+ awaitIfAsync(loadResult, function () {
541
+ var getArgs = [];
542
+ for (var _i = 0; _i < arguments.length; _i++) {
543
+ getArgs[_i] = arguments[_i];
544
+ }
545
+ var duration = loadDuration + Date.now() - getStartTime;
546
+ // Source getting failed
547
+ if (!getArgs[0]) {
548
+ return resolveGet({ error: ensureErrorWithMessage(getArgs[1]), duration: duration });
549
+ }
550
+ // Source getting succeeded
551
+ resolveGet({ value: getArgs[1], duration: duration });
552
+ });
553
+ });
554
+ });
555
+ });
556
+ });
557
+ return function getComponent() {
558
+ return sourceLoadPromise.then(function (finalizeSource) { return finalizeSource(); });
559
+ };
560
+ }
561
+ /**
562
+ * Loads the given entropy sources. Returns a function that collects the entropy components.
563
+ *
564
+ * The result is returned synchronously in order to allow start getting the components
565
+ * before the sources are loaded completely.
566
+ *
567
+ * Warning for package users:
568
+ * This function is out of Semantic Versioning, i.e. can change unexpectedly. Usage is at your own risk.
569
+ */
570
+ function loadSources(sources, sourceOptions, excludeSources) {
571
+ var includedSources = Object.keys(sources).filter(function (sourceKey) { return excludes(excludeSources, sourceKey); });
572
+ var sourceGetters = Array(includedSources.length);
573
+ // Using `forEachWithBreaks` allows asynchronous sources to complete between synchronous sources
574
+ // and measure the duration correctly
575
+ forEachWithBreaks(includedSources, function (sourceKey, index) {
576
+ sourceGetters[index] = loadSource(sources[sourceKey], sourceOptions);
577
+ });
578
+ return function getComponents() {
579
+ return __awaiter(this, void 0, void 0, function () {
580
+ var components, _i, includedSources_1, sourceKey, componentPromises, _loop_1, state_1;
581
+ return __generator(this, function (_a) {
582
+ switch (_a.label) {
583
+ case 0:
584
+ components = {};
585
+ for (_i = 0, includedSources_1 = includedSources; _i < includedSources_1.length; _i++) {
586
+ sourceKey = includedSources_1[_i];
587
+ components[sourceKey] = undefined;
588
+ }
589
+ componentPromises = Array(includedSources.length);
590
+ _loop_1 = function () {
591
+ var hasAllComponentPromises;
592
+ return __generator(this, function (_a) {
593
+ switch (_a.label) {
594
+ case 0:
595
+ hasAllComponentPromises = true;
596
+ return [4 /*yield*/, forEachWithBreaks(includedSources, function (sourceKey, index) {
597
+ if (!componentPromises[index]) {
598
+ // `sourceGetters` may be incomplete at this point of execution because `forEachWithBreaks` is asynchronous
599
+ if (sourceGetters[index]) {
600
+ componentPromises[index] = sourceGetters[index]().then(function (component) { return (components[sourceKey] = component); });
601
+ }
602
+ else {
603
+ hasAllComponentPromises = false;
604
+ }
605
+ }
606
+ })];
607
+ case 1:
608
+ _a.sent();
609
+ if (hasAllComponentPromises) {
610
+ return [2 /*return*/, "break"];
611
+ }
612
+ return [4 /*yield*/, wait(1)]; // Lets the source load loop continue
613
+ case 2:
614
+ _a.sent(); // Lets the source load loop continue
615
+ return [2 /*return*/];
616
+ }
617
+ });
618
+ };
619
+ _a.label = 1;
620
+ case 1: return [5 /*yield**/, _loop_1()];
621
+ case 2:
622
+ state_1 = _a.sent();
623
+ if (state_1 === "break")
624
+ return [3 /*break*/, 4];
625
+ _a.label = 3;
626
+ case 3: return [3 /*break*/, 1];
627
+ case 4: return [4 /*yield*/, Promise.all(componentPromises)];
628
+ case 5:
629
+ _a.sent();
630
+ return [2 /*return*/, components];
631
+ }
632
+ });
633
+ });
634
+ };
635
+ }
636
+
637
+ /*
638
+ * Functions to help with features that vary through browsers
639
+ */
640
+ /**
641
+ * Checks whether the browser is based on Trident (the Internet Explorer engine) without using user-agent.
642
+ *
643
+ * Warning for package users:
644
+ * This function is out of Semantic Versioning, i.e. can change unexpectedly. Usage is at your own risk.
645
+ */
646
+ function isTrident() {
647
+ var w = window;
648
+ var n = navigator;
649
+ // The properties are checked to be in IE 10, IE 11 and not to be in other browsers in October 2020
650
+ return (countTruthy([
651
+ 'MSCSSMatrix' in w,
652
+ 'msSetImmediate' in w,
653
+ 'msIndexedDB' in w,
654
+ 'msMaxTouchPoints' in n,
655
+ 'msPointerEnabled' in n,
656
+ ]) >= 4);
657
+ }
658
+ /**
659
+ * Checks whether the browser is based on EdgeHTML (the pre-Chromium Edge engine) without using user-agent.
660
+ *
661
+ * Warning for package users:
662
+ * This function is out of Semantic Versioning, i.e. can change unexpectedly. Usage is at your own risk.
663
+ */
664
+ function isEdgeHTML() {
665
+ // Based on research in October 2020
666
+ var w = window;
667
+ var n = navigator;
668
+ return (countTruthy(['msWriteProfilerMark' in w, 'MSStream' in w, 'msLaunchUri' in n, 'msSaveBlob' in n]) >= 3 &&
669
+ !isTrident());
670
+ }
671
+ /**
672
+ * Checks whether the browser is based on Chromium without using user-agent.
673
+ *
674
+ * Warning for package users:
675
+ * This function is out of Semantic Versioning, i.e. can change unexpectedly. Usage is at your own risk.
676
+ */
677
+ function isChromium() {
678
+ // Based on research in October 2020. Tested to detect Chromium 42-86.
679
+ var w = window;
680
+ var n = navigator;
681
+ return (countTruthy([
682
+ 'webkitPersistentStorage' in n,
683
+ 'webkitTemporaryStorage' in n,
684
+ n.vendor.indexOf('Google') === 0,
685
+ 'webkitResolveLocalFileSystemURL' in w,
686
+ 'BatteryManager' in w,
687
+ 'webkitMediaStream' in w,
688
+ 'webkitSpeechGrammar' in w,
689
+ ]) >= 5);
690
+ }
691
+ /**
692
+ * Checks whether the browser is based on mobile or desktop Safari without using user-agent.
693
+ * All iOS browsers use WebKit (the Safari engine).
694
+ *
695
+ * Warning for package users:
696
+ * This function is out of Semantic Versioning, i.e. can change unexpectedly. Usage is at your own risk.
697
+ */
698
+ function isWebKit() {
699
+ // Based on research in September 2020
700
+ var w = window;
701
+ var n = navigator;
702
+ return (countTruthy([
703
+ 'ApplePayError' in w,
704
+ 'CSSPrimitiveValue' in w,
705
+ 'Counter' in w,
706
+ n.vendor.indexOf('Apple') === 0,
707
+ 'getStorageUpdates' in n,
708
+ 'WebKitMediaKeys' in w,
709
+ ]) >= 4);
710
+ }
711
+ /**
712
+ * Checks whether the WebKit browser is a desktop Safari.
713
+ *
714
+ * Warning for package users:
715
+ * This function is out of Semantic Versioning, i.e. can change unexpectedly. Usage is at your own risk.
716
+ */
717
+ function isDesktopSafari() {
718
+ var w = window;
719
+ return (countTruthy([
720
+ 'safari' in w,
721
+ !('DeviceMotionEvent' in w),
722
+ !('ongestureend' in w),
723
+ !('standalone' in navigator),
724
+ ]) >= 3);
725
+ }
726
+ /**
727
+ * Checks whether the browser is based on Gecko (Firefox engine) without using user-agent.
728
+ *
729
+ * Warning for package users:
730
+ * This function is out of Semantic Versioning, i.e. can change unexpectedly. Usage is at your own risk.
731
+ */
732
+ function isGecko() {
733
+ var _a, _b;
734
+ var w = window;
735
+ // Based on research in September 2020
736
+ return (countTruthy([
737
+ 'buildID' in navigator,
738
+ 'MozAppearance' in ((_b = (_a = document.documentElement) === null || _a === void 0 ? void 0 : _a.style) !== null && _b !== void 0 ? _b : {}),
739
+ 'onmozfullscreenchange' in w,
740
+ 'mozInnerScreenX' in w,
741
+ 'CSSMozDocumentRule' in w,
742
+ 'CanvasCaptureMediaStream' in w,
743
+ ]) >= 4);
744
+ }
745
+ /**
746
+ * Checks whether the browser is based on Chromium version ≥86 without using user-agent.
747
+ * It doesn't check that the browser is based on Chromium, there is a separate function for this.
748
+ */
749
+ function isChromium86OrNewer() {
750
+ // Checked in Chrome 85 vs Chrome 86 both on desktop and Android
751
+ var w = window;
752
+ return (countTruthy([
753
+ !('MediaSettingsRange' in w),
754
+ 'RTCEncodedAudioFrame' in w,
755
+ '' + w.Intl === '[object Intl]',
756
+ '' + w.Reflect === '[object Reflect]',
757
+ ]) >= 3);
758
+ }
759
+ /**
760
+ * Checks whether the browser is based on WebKit version ≥606 (Safari ≥12) without using user-agent.
761
+ * It doesn't check that the browser is based on WebKit, there is a separate function for this.
762
+ *
763
+ * @link https://en.wikipedia.org/wiki/Safari_version_history#Release_history Safari-WebKit versions map
764
+ */
765
+ function isWebKit606OrNewer() {
766
+ // Checked in Safari 9–14
767
+ var w = window;
768
+ return (countTruthy([
769
+ 'DOMRectList' in w,
770
+ 'RTCPeerConnectionIceEvent' in w,
771
+ 'SVGGeometryElement' in w,
772
+ 'ontransitioncancel' in w,
773
+ ]) >= 3);
774
+ }
775
+ /**
776
+ * Checks whether the device is an iPad.
777
+ * It doesn't check that the engine is WebKit and that the WebKit isn't desktop.
778
+ */
779
+ function isIPad() {
780
+ // Checked on:
781
+ // Safari on iPadOS (both mobile and desktop modes): 8, 11, 12, 13, 14
782
+ // Chrome on iPadOS (both mobile and desktop modes): 11, 12, 13, 14
783
+ // Safari on iOS (both mobile and desktop modes): 9, 10, 11, 12, 13, 14
784
+ // Chrome on iOS (both mobile and desktop modes): 9, 10, 11, 12, 13, 14
785
+ // Before iOS 13. Safari tampers the value in "request desktop site" mode since iOS 13.
786
+ if (navigator.platform === 'iPad') {
787
+ return true;
788
+ }
789
+ var s = screen;
790
+ var screenRatio = s.width / s.height;
791
+ return (countTruthy([
792
+ 'MediaSource' in window,
793
+ !!Element.prototype.webkitRequestFullscreen,
794
+ // iPhone 4S that runs iOS 9 matches this. But it won't match the criteria above, so it won't be detected as iPad.
795
+ screenRatio > 0.65 && screenRatio < 1.53,
796
+ ]) >= 2);
797
+ }
798
+ /**
799
+ * Warning for package users:
800
+ * This function is out of Semantic Versioning, i.e. can change unexpectedly. Usage is at your own risk.
801
+ */
802
+ function getFullscreenElement() {
803
+ var d = document;
804
+ return d.fullscreenElement || d.msFullscreenElement || d.mozFullScreenElement || d.webkitFullscreenElement || null;
805
+ }
806
+ function exitFullscreen() {
807
+ var d = document;
808
+ // `call` is required because the function throws an error without a proper "this" context
809
+ return (d.exitFullscreen || d.msExitFullscreen || d.mozCancelFullScreen || d.webkitExitFullscreen).call(d);
810
+ }
811
+ /**
812
+ * Checks whether the device runs on Android without using user-agent.
813
+ *
814
+ * Warning for package users:
815
+ * This function is out of Semantic Versioning, i.e. can change unexpectedly. Usage is at your own risk.
816
+ */
817
+ function isAndroid() {
818
+ var isItChromium = isChromium();
819
+ var isItGecko = isGecko();
820
+ // Only 2 browser engines are presented on Android.
821
+ // Actually, there is also Android 4.1 browser, but it's not worth detecting it at the moment.
822
+ if (!isItChromium && !isItGecko) {
823
+ return false;
824
+ }
825
+ var w = window;
826
+ // Chrome removes all words "Android" from `navigator` when desktop version is requested
827
+ // Firefox keeps "Android" in `navigator.appVersion` when desktop version is requested
828
+ return (countTruthy([
829
+ 'onorientationchange' in w,
830
+ 'orientation' in w,
831
+ isItChromium && !('SharedWorker' in w),
832
+ isItGecko && /android/i.test(navigator.appVersion),
833
+ ]) >= 2);
834
+ }
835
+
836
+ /**
837
+ * A deep description: https://fingerprintjs.com/blog/audio-fingerprinting/
838
+ * Inspired by and based on https://github.com/cozylife/audio-fingerprint
839
+ */
840
+ function getAudioFingerprint() {
841
+ var w = window;
842
+ var AudioContext = w.OfflineAudioContext || w.webkitOfflineAudioContext;
843
+ if (!AudioContext) {
844
+ return -2 /* NotSupported */;
845
+ }
846
+ // In some browsers, audio context always stays suspended unless the context is started in response to a user action
847
+ // (e.g. a click or a tap). It prevents audio fingerprint from being taken at an arbitrary moment of time.
848
+ // Such browsers are old and unpopular, so the audio fingerprinting is just skipped in them.
849
+ // See a similar case explanation at https://stackoverflow.com/questions/46363048/onaudioprocess-not-called-on-ios11#46534088
850
+ if (doesCurrentBrowserSuspendAudioContext()) {
851
+ return -1 /* KnownToSuspend */;
852
+ }
853
+ var hashFromIndex = 4500;
854
+ var hashToIndex = 5000;
855
+ var context = new AudioContext(1, hashToIndex, 44100);
856
+ var oscillator = context.createOscillator();
857
+ oscillator.type = 'triangle';
858
+ oscillator.frequency.value = 10000;
859
+ var compressor = context.createDynamicsCompressor();
860
+ compressor.threshold.value = -50;
861
+ compressor.knee.value = 40;
862
+ compressor.ratio.value = 12;
863
+ compressor.attack.value = 0;
864
+ compressor.release.value = 0.25;
865
+ oscillator.connect(compressor);
866
+ compressor.connect(context.destination);
867
+ oscillator.start(0);
868
+ var _a = startRenderingAudio(context), renderPromise = _a[0], finishRendering = _a[1];
869
+ var fingerprintPromise = renderPromise.then(function (buffer) { return getHash(buffer.getChannelData(0).subarray(hashFromIndex)); }, function (error) {
870
+ if (error.name === "timeout" /* Timeout */ || error.name === "suspended" /* Suspended */) {
871
+ return -3 /* Timeout */;
872
+ }
873
+ throw error;
874
+ });
875
+ // Suppresses the console error message in case when the fingerprint fails before requested
876
+ fingerprintPromise.catch(function () { return undefined; });
877
+ return function () {
878
+ finishRendering();
879
+ return fingerprintPromise;
880
+ };
881
+ }
882
+ /**
883
+ * Checks if the current browser is known to always suspend audio context
884
+ */
885
+ function doesCurrentBrowserSuspendAudioContext() {
886
+ return isWebKit() && !isDesktopSafari() && !isWebKit606OrNewer();
887
+ }
888
+ /**
889
+ * Starts rendering the audio context.
890
+ * When the returned function is called, the render process starts finishing.
891
+ */
892
+ function startRenderingAudio(context) {
893
+ var renderTryMaxCount = 3;
894
+ var renderRetryDelay = 500;
895
+ var runningMaxAwaitTime = 500;
896
+ var runningSufficientTime = 5000;
897
+ var finalize = function () { return undefined; };
898
+ var resultPromise = new Promise(function (resolve, reject) {
899
+ var isFinalized = false;
900
+ var renderTryCount = 0;
901
+ var startedRunningAt = 0;
902
+ context.oncomplete = function (event) { return resolve(event.renderedBuffer); };
903
+ var startRunningTimeout = function () {
904
+ setTimeout(function () { return reject(makeInnerError("timeout" /* Timeout */)); }, Math.min(runningMaxAwaitTime, startedRunningAt + runningSufficientTime - Date.now()));
905
+ };
906
+ var tryRender = function () {
907
+ try {
908
+ context.startRendering();
909
+ switch (context.state) {
910
+ case 'running':
911
+ startedRunningAt = Date.now();
912
+ if (isFinalized) {
913
+ startRunningTimeout();
914
+ }
915
+ break;
916
+ // Sometimes the audio context doesn't start after calling `startRendering` (in addition to the cases where
917
+ // audio context doesn't start at all). A known case is starting an audio context when the browser tab is in
918
+ // background on iPhone. Retries usually help in this case.
919
+ case 'suspended':
920
+ // The audio context can reject starting until the tab is in foreground. Long fingerprint duration
921
+ // in background isn't a problem, therefore the retry attempts don't count in background. It can lead to
922
+ // a situation when a fingerprint takes very long time and finishes successfully. FYI, the audio context
923
+ // can be suspended when `document.hidden === false` and start running after a retry.
924
+ if (!document.hidden) {
925
+ renderTryCount++;
926
+ }
927
+ if (isFinalized && renderTryCount >= renderTryMaxCount) {
928
+ reject(makeInnerError("suspended" /* Suspended */));
929
+ }
930
+ else {
931
+ setTimeout(tryRender, renderRetryDelay);
932
+ }
933
+ break;
934
+ }
935
+ }
936
+ catch (error) {
937
+ reject(error);
938
+ }
939
+ };
940
+ tryRender();
941
+ finalize = function () {
942
+ if (!isFinalized) {
943
+ isFinalized = true;
944
+ if (startedRunningAt > 0) {
945
+ startRunningTimeout();
946
+ }
947
+ }
948
+ };
949
+ });
950
+ return [resultPromise, finalize];
951
+ }
952
+ function getHash(signal) {
953
+ var hash = 0;
954
+ for (var i = 0; i < signal.length; ++i) {
955
+ hash += Math.abs(signal[i]);
956
+ }
957
+ return hash;
958
+ }
959
+ function makeInnerError(name) {
960
+ var error = new Error(name);
961
+ error.name = name;
962
+ return error;
963
+ }
964
+
965
+ /**
966
+ * Creates and keeps an invisible iframe while the given function runs.
967
+ * The given function is called when the iframe is loaded and has a body.
968
+ * The iframe allows to measure DOM sizes inside itself.
969
+ *
970
+ * Notice: passing an initial HTML code doesn't work in IE.
971
+ *
972
+ * Warning for package users:
973
+ * This function is out of Semantic Versioning, i.e. can change unexpectedly. Usage is at your own risk.
974
+ */
975
+ function withIframe(action, initialHtml, domPollInterval) {
976
+ var _a, _b, _c;
977
+ if (domPollInterval === void 0) { domPollInterval = 50; }
978
+ return __awaiter(this, void 0, void 0, function () {
979
+ var d, iframe;
980
+ return __generator(this, function (_d) {
981
+ switch (_d.label) {
982
+ case 0:
983
+ d = document;
984
+ _d.label = 1;
985
+ case 1:
986
+ if (!!d.body) return [3 /*break*/, 3];
987
+ return [4 /*yield*/, wait(domPollInterval)];
988
+ case 2:
989
+ _d.sent();
990
+ return [3 /*break*/, 1];
991
+ case 3:
992
+ iframe = d.createElement('iframe');
993
+ _d.label = 4;
994
+ case 4:
995
+ _d.trys.push([4, , 10, 11]);
996
+ return [4 /*yield*/, new Promise(function (_resolve, _reject) {
997
+ var isComplete = false;
998
+ var resolve = function () {
999
+ isComplete = true;
1000
+ _resolve();
1001
+ };
1002
+ var reject = function (error) {
1003
+ isComplete = true;
1004
+ _reject(error);
1005
+ };
1006
+ iframe.onload = resolve;
1007
+ iframe.onerror = reject;
1008
+ var style = iframe.style;
1009
+ style.setProperty('display', 'block', 'important'); // Required for browsers to calculate the layout
1010
+ style.position = 'absolute';
1011
+ style.top = '0';
1012
+ style.left = '0';
1013
+ style.visibility = 'hidden';
1014
+ if (initialHtml && 'srcdoc' in iframe) {
1015
+ iframe.srcdoc = initialHtml;
1016
+ }
1017
+ else {
1018
+ iframe.src = 'about:blank';
1019
+ }
1020
+ d.body.appendChild(iframe);
1021
+ // WebKit in WeChat doesn't fire the iframe's `onload` for some reason.
1022
+ // This code checks for the loading state manually.
1023
+ // See https://github.com/fingerprintjs/fingerprintjs/issues/645
1024
+ var checkReadyState = function () {
1025
+ var _a, _b;
1026
+ // The ready state may never become 'complete' in Firefox despite the 'load' event being fired.
1027
+ // So an infinite setTimeout loop can happen without this check.
1028
+ // See https://github.com/fingerprintjs/fingerprintjs/pull/716#issuecomment-986898796
1029
+ if (isComplete) {
1030
+ return;
1031
+ }
1032
+ // Make sure iframe.contentWindow and iframe.contentWindow.document are both loaded
1033
+ // The contentWindow.document can miss in JSDOM (https://github.com/jsdom/jsdom).
1034
+ if (((_b = (_a = iframe.contentWindow) === null || _a === void 0 ? void 0 : _a.document) === null || _b === void 0 ? void 0 : _b.readyState) === 'complete') {
1035
+ resolve();
1036
+ }
1037
+ else {
1038
+ setTimeout(checkReadyState, 10);
1039
+ }
1040
+ };
1041
+ checkReadyState();
1042
+ })];
1043
+ case 5:
1044
+ _d.sent();
1045
+ _d.label = 6;
1046
+ case 6:
1047
+ if (!!((_b = (_a = iframe.contentWindow) === null || _a === void 0 ? void 0 : _a.document) === null || _b === void 0 ? void 0 : _b.body)) return [3 /*break*/, 8];
1048
+ return [4 /*yield*/, wait(domPollInterval)];
1049
+ case 7:
1050
+ _d.sent();
1051
+ return [3 /*break*/, 6];
1052
+ case 8: return [4 /*yield*/, action(iframe, iframe.contentWindow)];
1053
+ case 9: return [2 /*return*/, _d.sent()];
1054
+ case 10:
1055
+ (_c = iframe.parentNode) === null || _c === void 0 ? void 0 : _c.removeChild(iframe);
1056
+ return [7 /*endfinally*/];
1057
+ case 11: return [2 /*return*/];
1058
+ }
1059
+ });
1060
+ });
1061
+ }
1062
+ /**
1063
+ * Creates a DOM element that matches the given selector.
1064
+ * Only single element selector are supported (without operators like space, +, >, etc).
1065
+ */
1066
+ function selectorToElement(selector) {
1067
+ var _a = parseSimpleCssSelector(selector), tag = _a[0], attributes = _a[1];
1068
+ var element = document.createElement(tag !== null && tag !== void 0 ? tag : 'div');
1069
+ for (var _i = 0, _b = Object.keys(attributes); _i < _b.length; _i++) {
1070
+ var name_1 = _b[_i];
1071
+ var value = attributes[name_1].join(' ');
1072
+ // Changing the `style` attribute can cause a CSP error, therefore we change the `style.cssText` property.
1073
+ // https://github.com/fingerprintjs/fingerprintjs/issues/733
1074
+ if (name_1 === 'style') {
1075
+ addStyleString(element.style, value);
1076
+ }
1077
+ else {
1078
+ element.setAttribute(name_1, value);
1079
+ }
1080
+ }
1081
+ return element;
1082
+ }
1083
+ /**
1084
+ * Adds CSS styles from a string in such a way that doesn't trigger a CSP warning (unsafe-inline or unsafe-eval)
1085
+ */
1086
+ function addStyleString(style, source) {
1087
+ // We don't use `style.cssText` because browsers must block it when no `unsafe-eval` CSP is presented: https://csplite.com/csp145/#w3c_note
1088
+ // Even though the browsers ignore this standard, we don't use `cssText` just in case.
1089
+ for (var _i = 0, _a = source.split(';'); _i < _a.length; _i++) {
1090
+ var property = _a[_i];
1091
+ var match = /^\s*([\w-]+)\s*:\s*(.+?)(\s*!([\w-]+))?\s*$/.exec(property);
1092
+ if (match) {
1093
+ var name_2 = match[1], value = match[2], priority = match[4];
1094
+ style.setProperty(name_2, value, priority || ''); // The last argument can't be undefined in IE11
1095
+ }
1096
+ }
1097
+ }
1098
+
1099
+ // We use m or w because these two characters take up the maximum width.
1100
+ // And we use a LLi so that the same matching fonts can get separated.
1101
+ var testString = 'mmMwWLliI0O&1';
1102
+ // We test using 48px font size, we may use any size. I guess larger the better.
1103
+ var textSize = '48px';
1104
+ // A font will be compared against all the three default fonts.
1105
+ // And if for any default fonts it doesn't match, then that font is available.
1106
+ var baseFonts = ['monospace', 'sans-serif', 'serif'];
1107
+ var fontList = [
1108
+ // This is android-specific font from "Roboto" family
1109
+ 'sans-serif-thin',
1110
+ 'ARNO PRO',
1111
+ 'Agency FB',
1112
+ 'Arabic Typesetting',
1113
+ 'Arial Unicode MS',
1114
+ 'AvantGarde Bk BT',
1115
+ 'BankGothic Md BT',
1116
+ 'Batang',
1117
+ 'Bitstream Vera Sans Mono',
1118
+ 'Calibri',
1119
+ 'Century',
1120
+ 'Century Gothic',
1121
+ 'Clarendon',
1122
+ 'EUROSTILE',
1123
+ 'Franklin Gothic',
1124
+ 'Futura Bk BT',
1125
+ 'Futura Md BT',
1126
+ 'GOTHAM',
1127
+ 'Gill Sans',
1128
+ 'HELV',
1129
+ 'Haettenschweiler',
1130
+ 'Helvetica Neue',
1131
+ 'Humanst521 BT',
1132
+ 'Leelawadee',
1133
+ 'Letter Gothic',
1134
+ 'Levenim MT',
1135
+ 'Lucida Bright',
1136
+ 'Lucida Sans',
1137
+ 'Menlo',
1138
+ 'MS Mincho',
1139
+ 'MS Outlook',
1140
+ 'MS Reference Specialty',
1141
+ 'MS UI Gothic',
1142
+ 'MT Extra',
1143
+ 'MYRIAD PRO',
1144
+ 'Marlett',
1145
+ 'Meiryo UI',
1146
+ 'Microsoft Uighur',
1147
+ 'Minion Pro',
1148
+ 'Monotype Corsiva',
1149
+ 'PMingLiU',
1150
+ 'Pristina',
1151
+ 'SCRIPTINA',
1152
+ 'Segoe UI Light',
1153
+ 'Serifa',
1154
+ 'SimHei',
1155
+ 'Small Fonts',
1156
+ 'Staccato222 BT',
1157
+ 'TRAJAN PRO',
1158
+ 'Univers CE 55 Medium',
1159
+ 'Vrinda',
1160
+ 'ZWAdobeF',
1161
+ ];
1162
+ // kudos to http://www.lalit.org/lab/javascript-css-font-detect/
1163
+ function getFonts() {
1164
+ // Running the script in an iframe makes it not affect the page look and not be affected by the page CSS. See:
1165
+ // https://github.com/fingerprintjs/fingerprintjs/issues/592
1166
+ // https://github.com/fingerprintjs/fingerprintjs/issues/628
1167
+ return withIframe(function (_, _a) {
1168
+ var document = _a.document;
1169
+ var holder = document.body;
1170
+ holder.style.fontSize = textSize;
1171
+ // div to load spans for the default fonts and the fonts to detect
1172
+ var spansContainer = document.createElement('div');
1173
+ var defaultWidth = {};
1174
+ var defaultHeight = {};
1175
+ // creates a span where the fonts will be loaded
1176
+ var createSpan = function (fontFamily) {
1177
+ var span = document.createElement('span');
1178
+ var style = span.style;
1179
+ style.position = 'absolute';
1180
+ style.top = '0';
1181
+ style.left = '0';
1182
+ style.fontFamily = fontFamily;
1183
+ span.textContent = testString;
1184
+ spansContainer.appendChild(span);
1185
+ return span;
1186
+ };
1187
+ // creates a span and load the font to detect and a base font for fallback
1188
+ var createSpanWithFonts = function (fontToDetect, baseFont) {
1189
+ return createSpan("'" + fontToDetect + "'," + baseFont);
1190
+ };
1191
+ // creates spans for the base fonts and adds them to baseFontsDiv
1192
+ var initializeBaseFontsSpans = function () {
1193
+ return baseFonts.map(createSpan);
1194
+ };
1195
+ // creates spans for the fonts to detect and adds them to fontsDiv
1196
+ var initializeFontsSpans = function () {
1197
+ // Stores {fontName : [spans for that font]}
1198
+ var spans = {};
1199
+ var _loop_1 = function (font) {
1200
+ spans[font] = baseFonts.map(function (baseFont) { return createSpanWithFonts(font, baseFont); });
1201
+ };
1202
+ for (var _i = 0, fontList_1 = fontList; _i < fontList_1.length; _i++) {
1203
+ var font = fontList_1[_i];
1204
+ _loop_1(font);
1205
+ }
1206
+ return spans;
1207
+ };
1208
+ // checks if a font is available
1209
+ var isFontAvailable = function (fontSpans) {
1210
+ return baseFonts.some(function (baseFont, baseFontIndex) {
1211
+ return fontSpans[baseFontIndex].offsetWidth !== defaultWidth[baseFont] ||
1212
+ fontSpans[baseFontIndex].offsetHeight !== defaultHeight[baseFont];
1213
+ });
1214
+ };
1215
+ // create spans for base fonts
1216
+ var baseFontsSpans = initializeBaseFontsSpans();
1217
+ // create spans for fonts to detect
1218
+ var fontsSpans = initializeFontsSpans();
1219
+ // add all the spans to the DOM
1220
+ holder.appendChild(spansContainer);
1221
+ // get the default width for the three base fonts
1222
+ for (var index = 0; index < baseFonts.length; index++) {
1223
+ defaultWidth[baseFonts[index]] = baseFontsSpans[index].offsetWidth; // width for the default font
1224
+ defaultHeight[baseFonts[index]] = baseFontsSpans[index].offsetHeight; // height for the default font
1225
+ }
1226
+ // check available fonts
1227
+ return fontList.filter(function (font) { return isFontAvailable(fontsSpans[font]); });
1228
+ });
1229
+ }
1230
+
1231
+ function getPlugins() {
1232
+ var rawPlugins = navigator.plugins;
1233
+ if (!rawPlugins) {
1234
+ return undefined;
1235
+ }
1236
+ var plugins = [];
1237
+ // Safari 10 doesn't support iterating navigator.plugins with for...of
1238
+ for (var i = 0; i < rawPlugins.length; ++i) {
1239
+ var plugin = rawPlugins[i];
1240
+ if (!plugin) {
1241
+ continue;
1242
+ }
1243
+ var mimeTypes = [];
1244
+ for (var j = 0; j < plugin.length; ++j) {
1245
+ var mimeType = plugin[j];
1246
+ mimeTypes.push({
1247
+ type: mimeType.type,
1248
+ suffixes: mimeType.suffixes,
1249
+ });
1250
+ }
1251
+ plugins.push({
1252
+ name: plugin.name,
1253
+ description: plugin.description,
1254
+ mimeTypes: mimeTypes,
1255
+ });
1256
+ }
1257
+ return plugins;
1258
+ }
1259
+
1260
+ // https://www.browserleaks.com/canvas#how-does-it-work
1261
+ function getCanvasFingerprint() {
1262
+ var _a = makeCanvasContext(), canvas = _a[0], context = _a[1];
1263
+ if (!isSupported(canvas, context)) {
1264
+ return { winding: false, geometry: '', text: '' };
1265
+ }
1266
+ return {
1267
+ winding: doesSupportWinding(context),
1268
+ geometry: makeGeometryImage(canvas, context),
1269
+ // Text is unstable:
1270
+ // https://github.com/fingerprintjs/fingerprintjs/issues/583
1271
+ // https://github.com/fingerprintjs/fingerprintjs/issues/103
1272
+ // Therefore it's extracted into a separate image.
1273
+ text: makeTextImage(canvas, context),
1274
+ };
1275
+ }
1276
+ function makeCanvasContext() {
1277
+ var canvas = document.createElement('canvas');
1278
+ canvas.width = 1;
1279
+ canvas.height = 1;
1280
+ return [canvas, canvas.getContext('2d')];
1281
+ }
1282
+ function isSupported(canvas, context) {
1283
+ // TODO: look into: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob
1284
+ return !!(context && canvas.toDataURL);
1285
+ }
1286
+ function doesSupportWinding(context) {
1287
+ // https://web.archive.org/web/20170825024655/http://blogs.adobe.com/webplatform/2013/01/30/winding-rules-in-canvas/
1288
+ // https://github.com/Modernizr/Modernizr/blob/master/feature-detects/canvas/winding.js
1289
+ context.rect(0, 0, 10, 10);
1290
+ context.rect(2, 2, 6, 6);
1291
+ return !context.isPointInPath(5, 5, 'evenodd');
1292
+ }
1293
+ function makeTextImage(canvas, context) {
1294
+ // Resizing the canvas cleans it
1295
+ canvas.width = 240;
1296
+ canvas.height = 60;
1297
+ context.textBaseline = 'alphabetic';
1298
+ context.fillStyle = '#f60';
1299
+ context.fillRect(100, 1, 62, 20);
1300
+ context.fillStyle = '#069';
1301
+ // It's important to use explicit built-in fonts in order to exclude the affect of font preferences
1302
+ // (there is a separate entropy source for them).
1303
+ context.font = '11pt "Times New Roman"';
1304
+ // The choice of emojis has a gigantic impact on rendering performance (especially in FF).
1305
+ // Some newer emojis cause it to slow down 50-200 times.
1306
+ // There must be no text to the right of the emoji, see https://github.com/fingerprintjs/fingerprintjs/issues/574
1307
+ // A bare emoji shouldn't be used because the canvas will change depending on the script encoding:
1308
+ // https://github.com/fingerprintjs/fingerprintjs/issues/66
1309
+ // Escape sequence shouldn't be used too because Terser will turn it into a bare unicode.
1310
+ var printedText = "Cwm fjordbank gly " + String.fromCharCode(55357, 56835) /* 😃 */;
1311
+ context.fillText(printedText, 2, 15);
1312
+ context.fillStyle = 'rgba(102, 204, 0, 0.2)';
1313
+ context.font = '18pt Arial';
1314
+ context.fillText(printedText, 4, 45);
1315
+ return save(canvas);
1316
+ }
1317
+ function makeGeometryImage(canvas, context) {
1318
+ // Resizing the canvas cleans it
1319
+ canvas.width = 122;
1320
+ canvas.height = 110;
1321
+ // Canvas blending
1322
+ // https://web.archive.org/web/20170826194121/http://blogs.adobe.com/webplatform/2013/01/28/blending-features-in-canvas/
1323
+ // http://jsfiddle.net/NDYV8/16/
1324
+ context.globalCompositeOperation = 'multiply';
1325
+ for (var _i = 0, _a = [
1326
+ ['#f2f', 40, 40],
1327
+ ['#2ff', 80, 40],
1328
+ ['#ff2', 60, 80],
1329
+ ]; _i < _a.length; _i++) {
1330
+ var _b = _a[_i], color = _b[0], x = _b[1], y = _b[2];
1331
+ context.fillStyle = color;
1332
+ context.beginPath();
1333
+ context.arc(x, y, 40, 0, Math.PI * 2, true);
1334
+ context.closePath();
1335
+ context.fill();
1336
+ }
1337
+ // Canvas winding
1338
+ // https://web.archive.org/web/20130913061632/http://blogs.adobe.com/webplatform/2013/01/30/winding-rules-in-canvas/
1339
+ // http://jsfiddle.net/NDYV8/19/
1340
+ context.fillStyle = '#f9c';
1341
+ context.arc(60, 60, 60, 0, Math.PI * 2, true);
1342
+ context.arc(60, 60, 20, 0, Math.PI * 2, true);
1343
+ context.fill('evenodd');
1344
+ return save(canvas);
1345
+ }
1346
+ function save(canvas) {
1347
+ // TODO: look into: https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob
1348
+ return canvas.toDataURL();
1349
+ }
1350
+
1351
+ /**
1352
+ * This is a crude and primitive touch screen detection. It's not possible to currently reliably detect the availability
1353
+ * of a touch screen with a JS, without actually subscribing to a touch event.
1354
+ *
1355
+ * @see http://www.stucox.com/blog/you-cant-detect-a-touchscreen/
1356
+ * @see https://github.com/Modernizr/Modernizr/issues/548
1357
+ */
1358
+ function getTouchSupport() {
1359
+ var n = navigator;
1360
+ var maxTouchPoints = 0;
1361
+ var touchEvent;
1362
+ if (n.maxTouchPoints !== undefined) {
1363
+ maxTouchPoints = toInt(n.maxTouchPoints);
1364
+ }
1365
+ else if (n.msMaxTouchPoints !== undefined) {
1366
+ maxTouchPoints = n.msMaxTouchPoints;
1367
+ }
1368
+ try {
1369
+ document.createEvent('TouchEvent');
1370
+ touchEvent = true;
1371
+ }
1372
+ catch (_a) {
1373
+ touchEvent = false;
1374
+ }
1375
+ var touchStart = 'ontouchstart' in window;
1376
+ return {
1377
+ maxTouchPoints: maxTouchPoints,
1378
+ touchEvent: touchEvent,
1379
+ touchStart: touchStart,
1380
+ };
1381
+ }
1382
+
1383
+ function getOsCpu() {
1384
+ return navigator.oscpu;
1385
+ }
1386
+
1387
+ function getLanguages() {
1388
+ var n = navigator;
1389
+ var result = [];
1390
+ var language = n.language || n.userLanguage || n.browserLanguage || n.systemLanguage;
1391
+ if (language !== undefined) {
1392
+ result.push([language]);
1393
+ }
1394
+ if (Array.isArray(n.languages)) {
1395
+ // Starting from Chromium 86, there is only a single value in `navigator.language` in Incognito mode:
1396
+ // the value of `navigator.language`. Therefore the value is ignored in this browser.
1397
+ if (!(isChromium() && isChromium86OrNewer())) {
1398
+ result.push(n.languages);
1399
+ }
1400
+ }
1401
+ else if (typeof n.languages === 'string') {
1402
+ var languages = n.languages;
1403
+ if (languages) {
1404
+ result.push(languages.split(','));
1405
+ }
1406
+ }
1407
+ return result;
1408
+ }
1409
+
1410
+ function getColorDepth() {
1411
+ return window.screen.colorDepth;
1412
+ }
1413
+
1414
+ function getDeviceMemory() {
1415
+ // `navigator.deviceMemory` is a string containing a number in some unidentified cases
1416
+ return replaceNaN(toFloat(navigator.deviceMemory), undefined);
1417
+ }
1418
+
1419
+ function getScreenResolution() {
1420
+ var s = screen;
1421
+ // Some browsers return screen resolution as strings, e.g. "1200", instead of a number, e.g. 1200.
1422
+ // I suspect it's done by certain plugins that randomize browser properties to prevent fingerprinting.
1423
+ // Some browsers even return screen resolution as not numbers.
1424
+ var parseDimension = function (value) { return replaceNaN(toInt(value), null); };
1425
+ var dimensions = [parseDimension(s.width), parseDimension(s.height)];
1426
+ dimensions.sort().reverse();
1427
+ return dimensions;
1428
+ }
1429
+
1430
+ var screenFrameCheckInterval = 2500;
1431
+ var roundingPrecision = 10;
1432
+ // The type is readonly to protect from unwanted mutations
1433
+ var screenFrameBackup;
1434
+ var screenFrameSizeTimeoutId;
1435
+ /**
1436
+ * Starts watching the screen frame size. When a non-zero size appears, the size is saved and the watch is stopped.
1437
+ * Later, when `getScreenFrame` runs, it will return the saved non-zero size if the current size is null.
1438
+ *
1439
+ * This trick is required to mitigate the fact that the screen frame turns null in some cases.
1440
+ * See more on this at https://github.com/fingerprintjs/fingerprintjs/issues/568
1441
+ */
1442
+ function watchScreenFrame() {
1443
+ if (screenFrameSizeTimeoutId !== undefined) {
1444
+ return;
1445
+ }
1446
+ var checkScreenFrame = function () {
1447
+ var frameSize = getCurrentScreenFrame();
1448
+ if (isFrameSizeNull(frameSize)) {
1449
+ screenFrameSizeTimeoutId = setTimeout(checkScreenFrame, screenFrameCheckInterval);
1450
+ }
1451
+ else {
1452
+ screenFrameBackup = frameSize;
1453
+ screenFrameSizeTimeoutId = undefined;
1454
+ }
1455
+ };
1456
+ checkScreenFrame();
1457
+ }
1458
+ function getScreenFrame() {
1459
+ var _this = this;
1460
+ watchScreenFrame();
1461
+ return function () { return __awaiter(_this, void 0, void 0, function () {
1462
+ var frameSize;
1463
+ return __generator(this, function (_a) {
1464
+ switch (_a.label) {
1465
+ case 0:
1466
+ frameSize = getCurrentScreenFrame();
1467
+ if (!isFrameSizeNull(frameSize)) return [3 /*break*/, 2];
1468
+ if (screenFrameBackup) {
1469
+ return [2 /*return*/, __spreadArrays(screenFrameBackup)];
1470
+ }
1471
+ if (!getFullscreenElement()) return [3 /*break*/, 2];
1472
+ // Some browsers set the screen frame to zero when programmatic fullscreen is on.
1473
+ // There is a chance of getting a non-zero frame after exiting the fullscreen.
1474
+ // See more on this at https://github.com/fingerprintjs/fingerprintjs/issues/568
1475
+ return [4 /*yield*/, exitFullscreen()];
1476
+ case 1:
1477
+ // Some browsers set the screen frame to zero when programmatic fullscreen is on.
1478
+ // There is a chance of getting a non-zero frame after exiting the fullscreen.
1479
+ // See more on this at https://github.com/fingerprintjs/fingerprintjs/issues/568
1480
+ _a.sent();
1481
+ frameSize = getCurrentScreenFrame();
1482
+ _a.label = 2;
1483
+ case 2:
1484
+ if (!isFrameSizeNull(frameSize)) {
1485
+ screenFrameBackup = frameSize;
1486
+ }
1487
+ return [2 /*return*/, frameSize];
1488
+ }
1489
+ });
1490
+ }); };
1491
+ }
1492
+ /**
1493
+ * Sometimes the available screen resolution changes a bit, e.g. 1900x1440 → 1900x1439. A possible reason: macOS Dock
1494
+ * shrinks to fit more icons when there is too little space. The rounding is used to mitigate the difference.
1495
+ */
1496
+ function getRoundedScreenFrame() {
1497
+ var _this = this;
1498
+ var screenFrameGetter = getScreenFrame();
1499
+ return function () { return __awaiter(_this, void 0, void 0, function () {
1500
+ var frameSize, processSize;
1501
+ return __generator(this, function (_a) {
1502
+ switch (_a.label) {
1503
+ case 0: return [4 /*yield*/, screenFrameGetter()];
1504
+ case 1:
1505
+ frameSize = _a.sent();
1506
+ processSize = function (sideSize) { return (sideSize === null ? null : round(sideSize, roundingPrecision)); };
1507
+ // It might look like I don't know about `for` and `map`.
1508
+ // In fact, such code is used to avoid TypeScript issues without using `as`.
1509
+ return [2 /*return*/, [processSize(frameSize[0]), processSize(frameSize[1]), processSize(frameSize[2]), processSize(frameSize[3])]];
1510
+ }
1511
+ });
1512
+ }); };
1513
+ }
1514
+ function getCurrentScreenFrame() {
1515
+ var s = screen;
1516
+ // Some browsers return screen resolution as strings, e.g. "1200", instead of a number, e.g. 1200.
1517
+ // I suspect it's done by certain plugins that randomize browser properties to prevent fingerprinting.
1518
+ //
1519
+ // Some browsers (IE, Edge ≤18) don't provide `screen.availLeft` and `screen.availTop`. The property values are
1520
+ // replaced with 0 in such cases to not lose the entropy from `screen.availWidth` and `screen.availHeight`.
1521
+ return [
1522
+ replaceNaN(toFloat(s.availTop), null),
1523
+ replaceNaN(toFloat(s.width) - toFloat(s.availWidth) - replaceNaN(toFloat(s.availLeft), 0), null),
1524
+ replaceNaN(toFloat(s.height) - toFloat(s.availHeight) - replaceNaN(toFloat(s.availTop), 0), null),
1525
+ replaceNaN(toFloat(s.availLeft), null),
1526
+ ];
1527
+ }
1528
+ function isFrameSizeNull(frameSize) {
1529
+ for (var i = 0; i < 4; ++i) {
1530
+ if (frameSize[i]) {
1531
+ return false;
1532
+ }
1533
+ }
1534
+ return true;
1535
+ }
1536
+
1537
+ function getHardwareConcurrency() {
1538
+ // sometimes hardware concurrency is a string
1539
+ return replaceNaN(toInt(navigator.hardwareConcurrency), undefined);
1540
+ }
1541
+
1542
+ function getTimezone() {
1543
+ var _a;
1544
+ var DateTimeFormat = (_a = window.Intl) === null || _a === void 0 ? void 0 : _a.DateTimeFormat;
1545
+ if (DateTimeFormat) {
1546
+ var timezone = new DateTimeFormat().resolvedOptions().timeZone;
1547
+ if (timezone) {
1548
+ return timezone;
1549
+ }
1550
+ }
1551
+ // For browsers that don't support timezone names
1552
+ // The minus is intentional because the JS offset is opposite to the real offset
1553
+ var offset = -getTimezoneOffset();
1554
+ return "UTC" + (offset >= 0 ? '+' : '') + Math.abs(offset);
1555
+ }
1556
+ function getTimezoneOffset() {
1557
+ var currentYear = new Date().getFullYear();
1558
+ // The timezone offset may change over time due to daylight saving time (DST) shifts.
1559
+ // The non-DST timezone offset is used as the result timezone offset.
1560
+ // Since the DST season differs in the northern and the southern hemispheres,
1561
+ // both January and July timezones offsets are considered.
1562
+ return Math.max(
1563
+ // `getTimezoneOffset` returns a number as a string in some unidentified cases
1564
+ toFloat(new Date(currentYear, 0, 1).getTimezoneOffset()), toFloat(new Date(currentYear, 6, 1).getTimezoneOffset()));
1565
+ }
1566
+
1567
+ function getSessionStorage() {
1568
+ try {
1569
+ return !!window.sessionStorage;
1570
+ }
1571
+ catch (error) {
1572
+ /* SecurityError when referencing it means it exists */
1573
+ return true;
1574
+ }
1575
+ }
1576
+
1577
+ // https://bugzilla.mozilla.org/show_bug.cgi?id=781447
1578
+ function getLocalStorage() {
1579
+ try {
1580
+ return !!window.localStorage;
1581
+ }
1582
+ catch (e) {
1583
+ /* SecurityError when referencing it means it exists */
1584
+ return true;
1585
+ }
1586
+ }
1587
+
1588
+ function getIndexedDB() {
1589
+ // IE and Edge don't allow accessing indexedDB in private mode, therefore IE and Edge will have different
1590
+ // visitor identifier in normal and private modes.
1591
+ if (isTrident() || isEdgeHTML()) {
1592
+ return undefined;
1593
+ }
1594
+ try {
1595
+ return !!window.indexedDB;
1596
+ }
1597
+ catch (e) {
1598
+ /* SecurityError when referencing it means it exists */
1599
+ return true;
1600
+ }
1601
+ }
1602
+
1603
+ function getOpenDatabase() {
1604
+ return !!window.openDatabase;
1605
+ }
1606
+
1607
+ function getCpuClass() {
1608
+ return navigator.cpuClass;
1609
+ }
1610
+
1611
+ function getPlatform() {
1612
+ // Android Chrome 86 and 87 and Android Firefox 80 and 84 don't mock the platform value when desktop mode is requested
1613
+ var platform = navigator.platform;
1614
+ // iOS mocks the platform value when desktop version is requested: https://github.com/fingerprintjs/fingerprintjs/issues/514
1615
+ // iPad uses desktop mode by default since iOS 13
1616
+ // The value is 'MacIntel' on M1 Macs
1617
+ // The value is 'iPhone' on iPod Touch
1618
+ if (platform === 'MacIntel') {
1619
+ if (isWebKit() && !isDesktopSafari()) {
1620
+ return isIPad() ? 'iPad' : 'iPhone';
1621
+ }
1622
+ }
1623
+ return platform;
1624
+ }
1625
+
1626
+ function getVendor() {
1627
+ return navigator.vendor || '';
1628
+ }
1629
+
1630
+ /**
1631
+ * Checks for browser-specific (not engine specific) global variables to tell browsers with the same engine apart.
1632
+ * Only somewhat popular browsers are considered.
1633
+ */
1634
+ function getVendorFlavors() {
1635
+ var flavors = [];
1636
+ for (var _i = 0, _a = [
1637
+ // Blink and some browsers on iOS
1638
+ 'chrome',
1639
+ // Safari on macOS
1640
+ 'safari',
1641
+ // Chrome on iOS (checked in 85 on 13 and 87 on 14)
1642
+ '__crWeb',
1643
+ '__gCrWeb',
1644
+ // Yandex Browser on iOS, macOS and Android (checked in 21.2 on iOS 14, macOS and Android)
1645
+ 'yandex',
1646
+ // Yandex Browser on iOS (checked in 21.2 on 14)
1647
+ '__yb',
1648
+ '__ybro',
1649
+ // Firefox on iOS (checked in 32 on 14)
1650
+ '__firefox__',
1651
+ // Edge on iOS (checked in 46 on 14)
1652
+ '__edgeTrackingPreventionStatistics',
1653
+ 'webkit',
1654
+ // Opera Touch on iOS (checked in 2.6 on 14)
1655
+ 'oprt',
1656
+ // Samsung Internet on Android (checked in 11.1)
1657
+ 'samsungAr',
1658
+ // UC Browser on Android (checked in 12.10 and 13.0)
1659
+ 'ucweb',
1660
+ 'UCShellJava',
1661
+ // Puffin on Android (checked in 9.0)
1662
+ 'puffinDevice',
1663
+ ]; _i < _a.length; _i++) {
1664
+ var key = _a[_i];
1665
+ var value = window[key];
1666
+ if (value && typeof value === 'object') {
1667
+ flavors.push(key);
1668
+ }
1669
+ }
1670
+ return flavors.sort();
1671
+ }
1672
+
1673
+ /**
1674
+ * navigator.cookieEnabled cannot detect custom or nuanced cookie blocking configurations. For example, when blocking
1675
+ * cookies via the Advanced Privacy Settings in IE9, it always returns true. And there have been issues in the past with
1676
+ * site-specific exceptions. Don't rely on it.
1677
+ *
1678
+ * @see https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cookies.js Taken from here
1679
+ */
1680
+ function areCookiesEnabled() {
1681
+ var d = document;
1682
+ // Taken from here: https://github.com/Modernizr/Modernizr/blob/master/feature-detects/cookies.js
1683
+ // navigator.cookieEnabled cannot detect custom or nuanced cookie blocking configurations. For example, when blocking
1684
+ // cookies via the Advanced Privacy Settings in IE9, it always returns true. And there have been issues in the past
1685
+ // with site-specific exceptions. Don't rely on it.
1686
+ // try..catch because some in situations `document.cookie` is exposed but throws a
1687
+ // SecurityError if you try to access it; e.g. documents created from data URIs
1688
+ // or in sandboxed iframes (depending on flags/context)
1689
+ try {
1690
+ // Create cookie
1691
+ d.cookie = 'cookietest=1; SameSite=Strict;';
1692
+ var result = d.cookie.indexOf('cookietest=') !== -1;
1693
+ // Delete cookie
1694
+ d.cookie = 'cookietest=1; SameSite=Strict; expires=Thu, 01-Jan-1970 00:00:01 GMT';
1695
+ return result;
1696
+ }
1697
+ catch (e) {
1698
+ return false;
1699
+ }
1700
+ }
1701
+
1702
+ /**
1703
+ * Only single element selector are supported (no operators like space, +, >, etc).
1704
+ * `embed` and `position: fixed;` will be considered as blocked anyway because it always has no offsetParent.
1705
+ * Avoid `iframe` and anything with `[src=]` because they produce excess HTTP requests.
1706
+ *
1707
+ * See docs/content_blockers.md to learn how to make the list
1708
+ */
1709
+ var filters = {
1710
+ abpIndo: [
1711
+ '#Iklan-Melayang',
1712
+ '#Kolom-Iklan-728',
1713
+ '#SidebarIklan-wrapper',
1714
+ 'a[title="7naga poker" i]',
1715
+ '[title="ALIENBOLA" i]',
1716
+ ],
1717
+ abpvn: [
1718
+ '#quangcaomb',
1719
+ '.iosAdsiosAds-layout',
1720
+ '.quangcao',
1721
+ '[href^="https://r88.vn/"]',
1722
+ '[href^="https://zbet.vn/"]',
1723
+ ],
1724
+ adBlockFinland: [
1725
+ '.mainostila',
1726
+ '.sponsorit',
1727
+ '.ylamainos',
1728
+ 'a[href*="/clickthrgh.asp?"]',
1729
+ 'a[href^="https://app.readpeak.com/ads"]',
1730
+ ],
1731
+ adBlockPersian: [
1732
+ '#navbar_notice_50',
1733
+ 'a[href^="http://g1.v.fwmrm.net/ad/"]',
1734
+ '.kadr',
1735
+ 'TABLE[width="140px"]',
1736
+ '#divAgahi',
1737
+ ],
1738
+ adBlockWarningRemoval: ['#adblock-honeypot', '.adblocker-root', '.wp_adblock_detect'],
1739
+ adGuardAnnoyances: ['amp-embed[type="zen"]', '.hs-sosyal', '#cookieconsentdiv', 'div[class^="app_gdpr"]', '.as-oil'],
1740
+ adGuardBase: ['#ad-after', '#ad-p3', '.BetterJsPopOverlay', '#ad_300X250', '#bannerfloat22'],
1741
+ adGuardChinese: [
1742
+ // Disabled because not reproducible. Will be replaced during the next filter update.
1743
+ // '#piao_div_0[style*="width:140px;"]',
1744
+ 'a[href*=".ttz5.cn"]',
1745
+ 'a[href*=".yabovip2027.com/"]',
1746
+ '.tm3all2h4b',
1747
+ '.cc5278_banner_ad',
1748
+ ],
1749
+ adGuardFrench: [
1750
+ '.zonepub',
1751
+ '[class*="_adLeaderboard"]',
1752
+ '[id^="block-xiti_oas-"]',
1753
+ 'a[href^="http://ptapjmp.com/"]',
1754
+ 'a[href^="https://go.alvexo.com/"]',
1755
+ ],
1756
+ adGuardGerman: [
1757
+ '.banneritemwerbung_head_1',
1758
+ '.boxstartwerbung',
1759
+ '.werbung3',
1760
+ 'a[href^="http://www.eis.de/index.phtml?refid="]',
1761
+ 'a[href^="https://www.tipico.com/?affiliateId="]',
1762
+ ],
1763
+ adGuardJapanese: [
1764
+ '#kauli_yad_1',
1765
+ '#ad-giftext',
1766
+ '#adsSPRBlock',
1767
+ 'a[href^="http://ad2.trafficgate.net/"]',
1768
+ 'a[href^="http://www.rssad.jp/"]',
1769
+ ],
1770
+ adGuardMobile: ['amp-auto-ads', '#mgid_iframe', '.amp_ad', 'amp-embed[type="24smi"]', '#mgid_iframe1'],
1771
+ adGuardRussian: [
1772
+ 'a[href^="https://ya-distrib.ru/r/"]',
1773
+ 'a[href^="https://ad.letmeads.com/"]',
1774
+ '.reclama',
1775
+ 'div[id^="smi2adblock"]',
1776
+ 'div[id^="AdFox_banner_"]',
1777
+ ],
1778
+ adGuardSocial: [
1779
+ 'a[href^="//www.stumbleupon.com/submit?url="]',
1780
+ 'a[href^="//telegram.me/share/url?"]',
1781
+ '.etsy-tweet',
1782
+ '#inlineShare',
1783
+ '.popup-social',
1784
+ ],
1785
+ adGuardSpanishPortuguese: [
1786
+ '#barraPublicidade',
1787
+ '#Publicidade',
1788
+ '#publiEspecial',
1789
+ '#queTooltip',
1790
+ '[href^="http://ads.glispa.com/"]',
1791
+ ],
1792
+ adGuardTrackingProtection: [
1793
+ 'amp-embed[type="taboola"]',
1794
+ '#qoo-counter',
1795
+ 'a[href^="http://click.hotlog.ru/"]',
1796
+ 'a[href^="http://hitcounter.ru/top/stat.php"]',
1797
+ 'a[href^="http://top.mail.ru/jump"]',
1798
+ ],
1799
+ adGuardTurkish: [
1800
+ '#backkapat',
1801
+ '#reklami',
1802
+ 'a[href^="http://adserv.ontek.com.tr/"]',
1803
+ 'a[href^="http://izlenzi.com/campaign/"]',
1804
+ 'a[href^="http://www.installads.net/"]',
1805
+ ],
1806
+ bulgarian: ['td#freenet_table_ads', '#adbody', '#ea_intext_div', '.lapni-pop-over', '#xenium_hot_offers'],
1807
+ easyList: ['#AD_banner_bottom', '#Ads_google_02', '#N-ad-article-rightRail-1', '#ad-fullbanner2', '#ad-zone-2'],
1808
+ easyListChina: [
1809
+ 'a[href*=".wensixuetang.com/"]',
1810
+ 'A[href*="/hth107.com/"]',
1811
+ '.appguide-wrap[onclick*="bcebos.com"]',
1812
+ '.frontpageAdvM',
1813
+ '#taotaole',
1814
+ ],
1815
+ easyListCookie: ['#adtoniq-msg-bar', '#CoockiesPage', '#CookieModal_cookiemodal', '#DO_CC_PANEL', '#ShowCookie'],
1816
+ easyListCzechSlovak: ['#onlajny-stickers', '#reklamni-box', '.reklama-megaboard', '.sklik', '[id^="sklikReklama"]'],
1817
+ easyListDutch: [
1818
+ '#advertentie',
1819
+ '#vipAdmarktBannerBlock',
1820
+ '.adstekst',
1821
+ 'a[href^="https://xltube.nl/click/"]',
1822
+ '#semilo-lrectangle',
1823
+ ],
1824
+ easyListGermany: [
1825
+ 'a[href^="http://www.hw-area.com/?dp="]',
1826
+ 'a[href^="https://ads.sunmaker.com/tracking.php?"]',
1827
+ '.werbung-skyscraper2',
1828
+ '.bannergroup_werbung',
1829
+ '.ads_rechts',
1830
+ ],
1831
+ easyListItaly: [
1832
+ '.box_adv_annunci',
1833
+ '.sb-box-pubbliredazionale',
1834
+ 'a[href^="http://affiliazioniads.snai.it/"]',
1835
+ 'a[href^="https://adserver.html.it/"]',
1836
+ 'a[href^="https://affiliazioniads.snai.it/"]',
1837
+ ],
1838
+ easyListLithuania: [
1839
+ '.reklamos_tarpas',
1840
+ '.reklamos_nuorodos',
1841
+ 'img[alt="Reklaminis skydelis"]',
1842
+ 'img[alt="Dedikuoti.lt serveriai"]',
1843
+ 'img[alt="Hostingas Serveriai.lt"]',
1844
+ ],
1845
+ estonian: ['A[href*="http://pay4results24.eu"]'],
1846
+ fanboyAnnoyances: [
1847
+ '#feedback-tab',
1848
+ '#taboola-below-article',
1849
+ '.feedburnerFeedBlock',
1850
+ '.widget-feedburner-counter',
1851
+ '[title="Subscribe to our blog"]',
1852
+ ],
1853
+ fanboyAntiFacebook: ['.util-bar-module-firefly-visible'],
1854
+ fanboyEnhancedTrackers: [
1855
+ '.open.pushModal',
1856
+ '#issuem-leaky-paywall-articles-zero-remaining-nag',
1857
+ '#sovrn_container',
1858
+ 'div[class$="-hide"][zoompage-fontsize][style="display: block;"]',
1859
+ '.BlockNag__Card',
1860
+ ],
1861
+ fanboySocial: [
1862
+ '.td-tags-and-social-wrapper-box',
1863
+ '.twitterContainer',
1864
+ '.youtube-social',
1865
+ 'a[title^="Like us on Facebook"]',
1866
+ 'img[alt^="Share on Digg"]',
1867
+ ],
1868
+ frellwitSwedish: [
1869
+ 'a[href*="casinopro.se"][target="_blank"]',
1870
+ 'a[href*="doktor-se.onelink.me"]',
1871
+ 'article.category-samarbete',
1872
+ 'div.holidAds',
1873
+ 'ul.adsmodern',
1874
+ ],
1875
+ greekAdBlock: [
1876
+ 'A[href*="adman.otenet.gr/click?"]',
1877
+ 'A[href*="http://axiabanners.exodus.gr/"]',
1878
+ 'A[href*="http://interactive.forthnet.gr/click?"]',
1879
+ 'DIV.agores300',
1880
+ 'TABLE.advright',
1881
+ ],
1882
+ hungarian: [
1883
+ 'A[href*="ad.eval.hu"]',
1884
+ 'A[href*="ad.netmedia.hu"]',
1885
+ 'A[href*="daserver.ultraweb.hu"]',
1886
+ '#cemp_doboz',
1887
+ '.optimonk-iframe-container',
1888
+ ],
1889
+ iDontCareAboutCookies: [
1890
+ '.alert-info[data-block-track*="CookieNotice"]',
1891
+ '.ModuleTemplateCookieIndicator',
1892
+ '.o--cookies--container',
1893
+ '.cookie-msg-info-container',
1894
+ '#cookies-policy-sticky',
1895
+ ],
1896
+ icelandicAbp: ['A[href^="/framework/resources/forms/ads.aspx"]'],
1897
+ latvian: [
1898
+ 'a[href="http://www.salidzini.lv/"][style="display: block; width: 120px; height: 40px; overflow: hidden; position: relative;"]',
1899
+ 'a[href="http://www.salidzini.lv/"][style="display: block; width: 88px; height: 31px; overflow: hidden; position: relative;"]',
1900
+ ],
1901
+ listKr: [
1902
+ 'a[href*="//kingtoon.slnk.kr"]',
1903
+ 'a[href*="//playdsb.com/kr"]',
1904
+ 'div.logly-lift-adz',
1905
+ 'div[data-widget_id="ml6EJ074"]',
1906
+ 'ins.daum_ddn_area',
1907
+ ],
1908
+ listeAr: [
1909
+ '.geminiLB1Ad',
1910
+ '.right-and-left-sponsers',
1911
+ 'a[href*=".aflam.info"]',
1912
+ 'a[href*="booraq.org"]',
1913
+ 'a[href*="dubizzle.com/ar/?utm_source="]',
1914
+ ],
1915
+ listeFr: [
1916
+ 'a[href^="http://promo.vador.com/"]',
1917
+ '#adcontainer_recherche',
1918
+ 'a[href*="weborama.fr/fcgi-bin/"]',
1919
+ '.site-pub-interstitiel',
1920
+ 'div[id^="crt-"][data-criteo-id]',
1921
+ ],
1922
+ officialPolish: [
1923
+ '#ceneo-placeholder-ceneo-12',
1924
+ '[href^="https://aff.sendhub.pl/"]',
1925
+ 'a[href^="http://advmanager.techfun.pl/redirect/"]',
1926
+ 'a[href^="http://www.trizer.pl/?utm_source"]',
1927
+ 'div#skapiec_ad',
1928
+ ],
1929
+ ro: [
1930
+ 'a[href^="//afftrk.altex.ro/Counter/Click"]',
1931
+ 'a[href^="/magazin/"]',
1932
+ 'a[href^="https://blackfridaysales.ro/trk/shop/"]',
1933
+ 'a[href^="https://event.2performant.com/events/click"]',
1934
+ 'a[href^="https://l.profitshare.ro/"]',
1935
+ ],
1936
+ ruAd: [
1937
+ 'a[href*="//febrare.ru/"]',
1938
+ 'a[href*="//utimg.ru/"]',
1939
+ 'a[href*="://chikidiki.ru"]',
1940
+ '#pgeldiz',
1941
+ '.yandex-rtb-block',
1942
+ ],
1943
+ thaiAds: ['a[href*=macau-uta-popup]', '#ads-google-middle_rectangle-group', '.ads300s', '.bumq', '.img-kosana'],
1944
+ webAnnoyancesUltralist: [
1945
+ '#mod-social-share-2',
1946
+ '#social-tools',
1947
+ '.ctpl-fullbanner',
1948
+ '.zergnet-recommend',
1949
+ '.yt.btn-link.btn-md.btn',
1950
+ ],
1951
+ };
1952
+ /**
1953
+ * The order of the returned array means nothing (it's always sorted alphabetically).
1954
+ *
1955
+ * Notice that the source is slightly unstable.
1956
+ * Safari provides a 2-taps way to disable all content blockers on a page temporarily.
1957
+ * Also content blockers can be disabled permanently for a domain, but it requires 4 taps.
1958
+ * So empty array shouldn't be treated as "no blockers", it should be treated as "no signal".
1959
+ * If you are a website owner, don't make your visitors want to disable content blockers.
1960
+ */
1961
+ function getDomBlockers(_a) {
1962
+ var debug = (_a === void 0 ? {} : _a).debug;
1963
+ return __awaiter(this, void 0, void 0, function () {
1964
+ var filterNames, allSelectors, blockedSelectors, activeBlockers;
1965
+ var _b;
1966
+ return __generator(this, function (_c) {
1967
+ switch (_c.label) {
1968
+ case 0:
1969
+ if (!isApplicable()) {
1970
+ return [2 /*return*/, undefined];
1971
+ }
1972
+ filterNames = Object.keys(filters);
1973
+ allSelectors = (_b = []).concat.apply(_b, filterNames.map(function (filterName) { return filters[filterName]; }));
1974
+ return [4 /*yield*/, getBlockedSelectors(allSelectors)];
1975
+ case 1:
1976
+ blockedSelectors = _c.sent();
1977
+ if (debug) {
1978
+ printDebug(blockedSelectors);
1979
+ }
1980
+ activeBlockers = filterNames.filter(function (filterName) {
1981
+ var selectors = filters[filterName];
1982
+ var blockedCount = countTruthy(selectors.map(function (selector) { return blockedSelectors[selector]; }));
1983
+ return blockedCount > selectors.length * 0.6;
1984
+ });
1985
+ activeBlockers.sort();
1986
+ return [2 /*return*/, activeBlockers];
1987
+ }
1988
+ });
1989
+ });
1990
+ }
1991
+ function isApplicable() {
1992
+ // Safari (desktop and mobile) and all Android browsers keep content blockers in both regular and private mode
1993
+ return isWebKit() || isAndroid();
1994
+ }
1995
+ function getBlockedSelectors(selectors) {
1996
+ var _a;
1997
+ return __awaiter(this, void 0, void 0, function () {
1998
+ var d, root, elements, blockedSelectors, i, element, holder, i;
1999
+ return __generator(this, function (_b) {
2000
+ switch (_b.label) {
2001
+ case 0:
2002
+ d = document;
2003
+ root = d.createElement('div');
2004
+ elements = new Array(selectors.length);
2005
+ blockedSelectors = {} // Set() isn't used just in case somebody need older browser support
2006
+ ;
2007
+ forceShow(root);
2008
+ // First create all elements that can be blocked. If the DOM steps below are done in a single cycle,
2009
+ // browser will alternate tree modification and layout reading, that is very slow.
2010
+ for (i = 0; i < selectors.length; ++i) {
2011
+ element = selectorToElement(selectors[i]);
2012
+ holder = d.createElement('div') // Protects from unwanted effects of `+` and `~` selectors of filters
2013
+ ;
2014
+ forceShow(holder);
2015
+ holder.appendChild(element);
2016
+ root.appendChild(holder);
2017
+ elements[i] = element;
2018
+ }
2019
+ _b.label = 1;
2020
+ case 1:
2021
+ if (!!d.body) return [3 /*break*/, 3];
2022
+ return [4 /*yield*/, wait(50)];
2023
+ case 2:
2024
+ _b.sent();
2025
+ return [3 /*break*/, 1];
2026
+ case 3:
2027
+ d.body.appendChild(root);
2028
+ try {
2029
+ // Then check which of the elements are blocked
2030
+ for (i = 0; i < selectors.length; ++i) {
2031
+ if (!elements[i].offsetParent) {
2032
+ blockedSelectors[selectors[i]] = true;
2033
+ }
2034
+ }
2035
+ }
2036
+ finally {
2037
+ // Then remove the elements
2038
+ (_a = root.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(root);
2039
+ }
2040
+ return [2 /*return*/, blockedSelectors];
2041
+ }
2042
+ });
2043
+ });
2044
+ }
2045
+ function forceShow(element) {
2046
+ element.style.setProperty('display', 'block', 'important');
2047
+ }
2048
+ function printDebug(blockedSelectors) {
2049
+ var message = 'DOM blockers debug:\n```';
2050
+ for (var _i = 0, _a = Object.keys(filters); _i < _a.length; _i++) {
2051
+ var filterName = _a[_i];
2052
+ message += "\n" + filterName + ":";
2053
+ for (var _b = 0, _c = filters[filterName]; _b < _c.length; _b++) {
2054
+ var selector = _c[_b];
2055
+ message += "\n " + selector + " " + (blockedSelectors[selector] ? '🚫' : '➡️');
2056
+ }
2057
+ }
2058
+ // console.log is ok here because it's under a debug clause
2059
+ // eslint-disable-next-line no-console
2060
+ console.log(message + "\n```");
2061
+ }
2062
+
2063
+ /**
2064
+ * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@media/color-gamut
2065
+ */
2066
+ function getColorGamut() {
2067
+ // rec2020 includes p3 and p3 includes srgb
2068
+ for (var _i = 0, _a = ['rec2020', 'p3', 'srgb']; _i < _a.length; _i++) {
2069
+ var gamut = _a[_i];
2070
+ if (matchMedia("(color-gamut: " + gamut + ")").matches) {
2071
+ return gamut;
2072
+ }
2073
+ }
2074
+ return undefined;
2075
+ }
2076
+
2077
+ /**
2078
+ * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@media/inverted-colors
2079
+ */
2080
+ function areColorsInverted() {
2081
+ if (doesMatch('inverted')) {
2082
+ return true;
2083
+ }
2084
+ if (doesMatch('none')) {
2085
+ return false;
2086
+ }
2087
+ return undefined;
2088
+ }
2089
+ function doesMatch(value) {
2090
+ return matchMedia("(inverted-colors: " + value + ")").matches;
2091
+ }
2092
+
2093
+ /**
2094
+ * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@media/forced-colors
2095
+ */
2096
+ function areColorsForced() {
2097
+ if (doesMatch$1('active')) {
2098
+ return true;
2099
+ }
2100
+ if (doesMatch$1('none')) {
2101
+ return false;
2102
+ }
2103
+ return undefined;
2104
+ }
2105
+ function doesMatch$1(value) {
2106
+ return matchMedia("(forced-colors: " + value + ")").matches;
2107
+ }
2108
+
2109
+ var maxValueToCheck = 100;
2110
+ /**
2111
+ * If the display is monochrome (e.g. black&white), the value will be ≥0 and will mean the number of bits per pixel.
2112
+ * If the display is not monochrome, the returned value will be 0.
2113
+ * If the browser doesn't support this feature, the returned value will be undefined.
2114
+ *
2115
+ * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@media/monochrome
2116
+ */
2117
+ function getMonochromeDepth() {
2118
+ if (!matchMedia('(min-monochrome: 0)').matches) {
2119
+ // The media feature isn't supported by the browser
2120
+ return undefined;
2121
+ }
2122
+ // A variation of binary search algorithm can be used here.
2123
+ // But since expected values are very small (≤10), there is no sense in adding the complexity.
2124
+ for (var i = 0; i <= maxValueToCheck; ++i) {
2125
+ if (matchMedia("(max-monochrome: " + i + ")").matches) {
2126
+ return i;
2127
+ }
2128
+ }
2129
+ throw new Error('Too high value');
2130
+ }
2131
+
2132
+ /**
2133
+ * @see https://www.w3.org/TR/mediaqueries-5/#prefers-contrast
2134
+ * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-contrast
2135
+ */
2136
+ function getContrastPreference() {
2137
+ if (doesMatch$2('no-preference')) {
2138
+ return 0 /* None */;
2139
+ }
2140
+ // The sources contradict on the keywords. Probably 'high' and 'low' will never be implemented.
2141
+ // Need to check it when all browsers implement the feature.
2142
+ if (doesMatch$2('high') || doesMatch$2('more')) {
2143
+ return 1 /* More */;
2144
+ }
2145
+ if (doesMatch$2('low') || doesMatch$2('less')) {
2146
+ return -1 /* Less */;
2147
+ }
2148
+ if (doesMatch$2('forced')) {
2149
+ return 10 /* ForcedColors */;
2150
+ }
2151
+ return undefined;
2152
+ }
2153
+ function doesMatch$2(value) {
2154
+ return matchMedia("(prefers-contrast: " + value + ")").matches;
2155
+ }
2156
+
2157
+ /**
2158
+ * @see https://developer.mozilla.org/en-US/docs/Web/CSS/@media/prefers-reduced-motion
2159
+ */
2160
+ function isMotionReduced() {
2161
+ if (doesMatch$3('reduce')) {
2162
+ return true;
2163
+ }
2164
+ if (doesMatch$3('no-preference')) {
2165
+ return false;
2166
+ }
2167
+ return undefined;
2168
+ }
2169
+ function doesMatch$3(value) {
2170
+ return matchMedia("(prefers-reduced-motion: " + value + ")").matches;
2171
+ }
2172
+
2173
+ /**
2174
+ * @see https://www.w3.org/TR/mediaqueries-5/#dynamic-range
2175
+ */
2176
+ function isHDR() {
2177
+ if (doesMatch$4('high')) {
2178
+ return true;
2179
+ }
2180
+ if (doesMatch$4('standard')) {
2181
+ return false;
2182
+ }
2183
+ return undefined;
2184
+ }
2185
+ function doesMatch$4(value) {
2186
+ return matchMedia("(dynamic-range: " + value + ")").matches;
2187
+ }
2188
+
2189
+ var M = Math; // To reduce the minified code size
2190
+ var fallbackFn = function () { return 0; };
2191
+ /**
2192
+ * @see https://gitlab.torproject.org/legacy/trac/-/issues/13018
2193
+ * @see https://bugzilla.mozilla.org/show_bug.cgi?id=531915
2194
+ */
2195
+ function getMathFingerprint() {
2196
+ // Native operations
2197
+ var acos = M.acos || fallbackFn;
2198
+ var acosh = M.acosh || fallbackFn;
2199
+ var asin = M.asin || fallbackFn;
2200
+ var asinh = M.asinh || fallbackFn;
2201
+ var atanh = M.atanh || fallbackFn;
2202
+ var atan = M.atan || fallbackFn;
2203
+ var sin = M.sin || fallbackFn;
2204
+ var sinh = M.sinh || fallbackFn;
2205
+ var cos = M.cos || fallbackFn;
2206
+ var cosh = M.cosh || fallbackFn;
2207
+ var tan = M.tan || fallbackFn;
2208
+ var tanh = M.tanh || fallbackFn;
2209
+ var exp = M.exp || fallbackFn;
2210
+ var expm1 = M.expm1 || fallbackFn;
2211
+ var log1p = M.log1p || fallbackFn;
2212
+ // Operation polyfills
2213
+ var powPI = function (value) { return M.pow(M.PI, value); };
2214
+ var acoshPf = function (value) { return M.log(value + M.sqrt(value * value - 1)); };
2215
+ var asinhPf = function (value) { return M.log(value + M.sqrt(value * value + 1)); };
2216
+ var atanhPf = function (value) { return M.log((1 + value) / (1 - value)) / 2; };
2217
+ var sinhPf = function (value) { return M.exp(value) - 1 / M.exp(value) / 2; };
2218
+ var coshPf = function (value) { return (M.exp(value) + 1 / M.exp(value)) / 2; };
2219
+ var expm1Pf = function (value) { return M.exp(value) - 1; };
2220
+ var tanhPf = function (value) { return (M.exp(2 * value) - 1) / (M.exp(2 * value) + 1); };
2221
+ var log1pPf = function (value) { return M.log(1 + value); };
2222
+ // Note: constant values are empirical
2223
+ return {
2224
+ acos: acos(0.123124234234234242),
2225
+ acosh: acosh(1e308),
2226
+ acoshPf: acoshPf(1e154),
2227
+ asin: asin(0.123124234234234242),
2228
+ asinh: asinh(1),
2229
+ asinhPf: asinhPf(1),
2230
+ atanh: atanh(0.5),
2231
+ atanhPf: atanhPf(0.5),
2232
+ atan: atan(0.5),
2233
+ sin: sin(-1e300),
2234
+ sinh: sinh(1),
2235
+ sinhPf: sinhPf(1),
2236
+ cos: cos(10.000000000123),
2237
+ cosh: cosh(1),
2238
+ coshPf: coshPf(1),
2239
+ tan: tan(-1e300),
2240
+ tanh: tanh(1),
2241
+ tanhPf: tanhPf(1),
2242
+ exp: exp(1),
2243
+ expm1: expm1(1),
2244
+ expm1Pf: expm1Pf(1),
2245
+ log1p: log1p(10),
2246
+ log1pPf: log1pPf(10),
2247
+ powPI: powPI(-100),
2248
+ };
2249
+ }
2250
+
2251
+ /**
2252
+ * We use m or w because these two characters take up the maximum width.
2253
+ * Also there are a couple of ligatures.
2254
+ */
2255
+ var defaultText = 'mmMwWLliI0fiflO&1';
2256
+ /**
2257
+ * Settings of text blocks to measure. The keys are random but persistent words.
2258
+ */
2259
+ var presets = {
2260
+ /**
2261
+ * The default font. User can change it in desktop Chrome, desktop Firefox, IE 11,
2262
+ * Android Chrome (but only when the size is ≥ than the default) and Android Firefox.
2263
+ */
2264
+ default: [],
2265
+ /** OS font on macOS. User can change its size and weight. Applies after Safari restart. */
2266
+ apple: [{ font: '-apple-system-body' }],
2267
+ /** User can change it in desktop Chrome and desktop Firefox. */
2268
+ serif: [{ fontFamily: 'serif' }],
2269
+ /** User can change it in desktop Chrome and desktop Firefox. */
2270
+ sans: [{ fontFamily: 'sans-serif' }],
2271
+ /** User can change it in desktop Chrome and desktop Firefox. */
2272
+ mono: [{ fontFamily: 'monospace' }],
2273
+ /**
2274
+ * Check the smallest allowed font size. User can change it in desktop Chrome, desktop Firefox and desktop Safari.
2275
+ * The height can be 0 in Chrome on a retina display.
2276
+ */
2277
+ min: [{ fontSize: '1px' }],
2278
+ /** Tells one OS from another in desktop Chrome. */
2279
+ system: [{ fontFamily: 'system-ui' }],
2280
+ };
2281
+ /**
2282
+ * The result is a dictionary of the width of the text samples.
2283
+ * Heights aren't included because they give no extra entropy and are unstable.
2284
+ *
2285
+ * The result is very stable in IE 11, Edge 18 and Safari 14.
2286
+ * The result changes when the OS pixel density changes in Chromium 87. The real pixel density is required to solve,
2287
+ * but seems like it's impossible: https://stackoverflow.com/q/1713771/1118709.
2288
+ * The "min" and the "mono" (only on Windows) value may change when the page is zoomed in Firefox 87.
2289
+ */
2290
+ function getFontPreferences() {
2291
+ return withNaturalFonts(function (document, container) {
2292
+ var elements = {};
2293
+ var sizes = {};
2294
+ // First create all elements to measure. If the DOM steps below are done in a single cycle,
2295
+ // browser will alternate tree modification and layout reading, that is very slow.
2296
+ for (var _i = 0, _a = Object.keys(presets); _i < _a.length; _i++) {
2297
+ var key = _a[_i];
2298
+ var _b = presets[key], _c = _b[0], style = _c === void 0 ? {} : _c, _d = _b[1], text = _d === void 0 ? defaultText : _d;
2299
+ var element = document.createElement('span');
2300
+ element.textContent = text;
2301
+ element.style.whiteSpace = 'nowrap';
2302
+ for (var _e = 0, _f = Object.keys(style); _e < _f.length; _e++) {
2303
+ var name_1 = _f[_e];
2304
+ var value = style[name_1];
2305
+ if (value !== undefined) {
2306
+ element.style[name_1] = value;
2307
+ }
2308
+ }
2309
+ elements[key] = element;
2310
+ container.appendChild(document.createElement('br'));
2311
+ container.appendChild(element);
2312
+ }
2313
+ // Then measure the created elements
2314
+ for (var _g = 0, _h = Object.keys(presets); _g < _h.length; _g++) {
2315
+ var key = _h[_g];
2316
+ sizes[key] = elements[key].getBoundingClientRect().width;
2317
+ }
2318
+ return sizes;
2319
+ });
2320
+ }
2321
+ /**
2322
+ * Creates a DOM environment that provides the most natural font available, including Android OS font.
2323
+ * Measurements of the elements are zoom-independent.
2324
+ * Don't put a content to measure inside an absolutely positioned element.
2325
+ */
2326
+ function withNaturalFonts(action, containerWidthPx) {
2327
+ if (containerWidthPx === void 0) { containerWidthPx = 4000; }
2328
+ /*
2329
+ * Requirements for Android Chrome to apply the system font size to a text inside an iframe:
2330
+ * - The iframe mustn't have a `display: none;` style;
2331
+ * - The text mustn't be positioned absolutely;
2332
+ * - The text block must be wide enough.
2333
+ * 2560px on some devices in portrait orientation for the biggest font size option (32px);
2334
+ * - There must be much enough text to form a few lines (I don't know the exact numbers);
2335
+ * - The text must have the `text-size-adjust: none` style. Otherwise the text will scale in "Desktop site" mode;
2336
+ *
2337
+ * Requirements for Android Firefox to apply the system font size to a text inside an iframe:
2338
+ * - The iframe document must have a header: `<meta name="viewport" content="width=device-width, initial-scale=1" />`.
2339
+ * The only way to set it is to use the `srcdoc` attribute of the iframe;
2340
+ * - The iframe content must get loaded before adding extra content with JavaScript;
2341
+ *
2342
+ * https://example.com as the iframe target always inherits Android font settings so it can be used as a reference.
2343
+ *
2344
+ * Observations on how page zoom affects the measurements:
2345
+ * - macOS Safari 11.1, 12.1, 13.1, 14.0: zoom reset + offsetWidth = 100% reliable;
2346
+ * - macOS Safari 11.1, 12.1, 13.1, 14.0: zoom reset + getBoundingClientRect = 100% reliable;
2347
+ * - macOS Safari 14.0: offsetWidth = 5% fluctuation;
2348
+ * - macOS Safari 14.0: getBoundingClientRect = 5% fluctuation;
2349
+ * - iOS Safari 9, 10, 11.0, 12.0: haven't found a way to zoom a page (pinch doesn't change layout);
2350
+ * - iOS Safari 13.1, 14.0: zoom reset + offsetWidth = 100% reliable;
2351
+ * - iOS Safari 13.1, 14.0: zoom reset + getBoundingClientRect = 100% reliable;
2352
+ * - iOS Safari 14.0: offsetWidth = 100% reliable;
2353
+ * - iOS Safari 14.0: getBoundingClientRect = 100% reliable;
2354
+ * - Chrome 42, 65, 80, 87: zoom 1/devicePixelRatio + offsetWidth = 1px fluctuation;
2355
+ * - Chrome 42, 65, 80, 87: zoom 1/devicePixelRatio + getBoundingClientRect = 100% reliable;
2356
+ * - Chrome 87: offsetWidth = 1px fluctuation;
2357
+ * - Chrome 87: getBoundingClientRect = 0.7px fluctuation;
2358
+ * - Firefox 48, 51: offsetWidth = 10% fluctuation;
2359
+ * - Firefox 48, 51: getBoundingClientRect = 10% fluctuation;
2360
+ * - Firefox 52, 53, 57, 62, 66, 67, 68, 71, 75, 80, 84: offsetWidth = width 100% reliable, height 10% fluctuation;
2361
+ * - Firefox 52, 53, 57, 62, 66, 67, 68, 71, 75, 80, 84: getBoundingClientRect = width 100% reliable, height 10%
2362
+ * fluctuation;
2363
+ * - Android Chrome 86: haven't found a way to zoom a page (pinch doesn't change layout);
2364
+ * - Android Firefox 84: font size in accessibility settings changes all the CSS sizes, but offsetWidth and
2365
+ * getBoundingClientRect keep measuring with regular units, so the size reflects the font size setting and doesn't
2366
+ * fluctuate;
2367
+ * - IE 11, Edge 18: zoom 1/devicePixelRatio + offsetWidth = 100% reliable;
2368
+ * - IE 11, Edge 18: zoom 1/devicePixelRatio + getBoundingClientRect = reflects the zoom level;
2369
+ * - IE 11, Edge 18: offsetWidth = 100% reliable;
2370
+ * - IE 11, Edge 18: getBoundingClientRect = 100% reliable;
2371
+ */
2372
+ return withIframe(function (_, iframeWindow) {
2373
+ var iframeDocument = iframeWindow.document;
2374
+ var iframeBody = iframeDocument.body;
2375
+ var bodyStyle = iframeBody.style;
2376
+ bodyStyle.width = containerWidthPx + "px";
2377
+ bodyStyle.webkitTextSizeAdjust = bodyStyle.textSizeAdjust = 'none';
2378
+ // See the big comment above
2379
+ if (isChromium()) {
2380
+ iframeBody.style.zoom = "" + 1 / iframeWindow.devicePixelRatio;
2381
+ }
2382
+ else if (isWebKit()) {
2383
+ iframeBody.style.zoom = 'reset';
2384
+ }
2385
+ // See the big comment above
2386
+ var linesOfText = iframeDocument.createElement('div');
2387
+ linesOfText.textContent = __spreadArrays(Array((containerWidthPx / 20) << 0)).map(function () { return 'word'; }).join(' ');
2388
+ iframeBody.appendChild(linesOfText);
2389
+ return action(iframeDocument, iframeBody);
2390
+ }, '<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1">');
2391
+ }
2392
+
2393
+ /**
2394
+ * The list of entropy sources used to make visitor identifiers.
2395
+ *
2396
+ * This value isn't restricted by Semantic Versioning, i.e. it may be changed without bumping minor or major version of
2397
+ * this package.
2398
+ */
2399
+ var sources = {
2400
+ // READ FIRST:
2401
+ // See https://github.com/fingerprintjs/fingerprintjs/blob/master/contributing.md#how-to-make-an-entropy-source
2402
+ // to learn how entropy source works and how to make your own.
2403
+ // The sources run in this exact order.
2404
+ // The asynchronous sources are at the start to run in parallel with other sources.
2405
+ fonts: getFonts,
2406
+ domBlockers: getDomBlockers,
2407
+ fontPreferences: getFontPreferences,
2408
+ audio: getAudioFingerprint,
2409
+ screenFrame: getRoundedScreenFrame,
2410
+ osCpu: getOsCpu,
2411
+ languages: getLanguages,
2412
+ colorDepth: getColorDepth,
2413
+ deviceMemory: getDeviceMemory,
2414
+ screenResolution: getScreenResolution,
2415
+ hardwareConcurrency: getHardwareConcurrency,
2416
+ timezone: getTimezone,
2417
+ sessionStorage: getSessionStorage,
2418
+ localStorage: getLocalStorage,
2419
+ indexedDB: getIndexedDB,
2420
+ openDatabase: getOpenDatabase,
2421
+ cpuClass: getCpuClass,
2422
+ platform: getPlatform,
2423
+ plugins: getPlugins,
2424
+ canvas: getCanvasFingerprint,
2425
+ touchSupport: getTouchSupport,
2426
+ vendor: getVendor,
2427
+ vendorFlavors: getVendorFlavors,
2428
+ cookiesEnabled: areCookiesEnabled,
2429
+ colorGamut: getColorGamut,
2430
+ invertedColors: areColorsInverted,
2431
+ forcedColors: areColorsForced,
2432
+ monochrome: getMonochromeDepth,
2433
+ contrast: getContrastPreference,
2434
+ reducedMotion: isMotionReduced,
2435
+ hdr: isHDR,
2436
+ math: getMathFingerprint,
2437
+ };
2438
+ /**
2439
+ * Loads the built-in entropy sources.
2440
+ * Returns a function that collects the entropy components to make the visitor identifier.
2441
+ */
2442
+ function loadBuiltinSources(options) {
2443
+ return loadSources(sources, options, []);
2444
+ }
2445
+
2446
+ var commentTemplate = '$ if upgrade to Pro: https://fpjs.dev/pro';
2447
+ function getConfidence(components) {
2448
+ var openConfidenceScore = getOpenConfidenceScore(components);
2449
+ var proConfidenceScore = deriveProConfidenceScore(openConfidenceScore);
2450
+ return { score: openConfidenceScore, comment: commentTemplate.replace(/\$/g, "" + proConfidenceScore) };
2451
+ }
2452
+ function getOpenConfidenceScore(components) {
2453
+ // In order to calculate the true probability of the visitor identifier being correct, we need to know the number of
2454
+ // website visitors (the higher the number, the less the probability because the fingerprint entropy is limited).
2455
+ // JS agent doesn't know the number of visitors, so we can only do an approximate assessment.
2456
+ if (isAndroid()) {
2457
+ return 0.4;
2458
+ }
2459
+ // Safari (mobile and desktop)
2460
+ if (isWebKit()) {
2461
+ return isDesktopSafari() ? 0.5 : 0.3;
2462
+ }
2463
+ var platform = components.platform.value || '';
2464
+ // Windows
2465
+ if (/^Win/.test(platform)) {
2466
+ // The score is greater than on macOS because of the higher variety of devices running Windows.
2467
+ // Chrome provides more entropy than Firefox according too
2468
+ // https://netmarketshare.com/browser-market-share.aspx?options=%7B%22filter%22%3A%7B%22%24and%22%3A%5B%7B%22platform%22%3A%7B%22%24in%22%3A%5B%22Windows%22%5D%7D%7D%5D%7D%2C%22dateLabel%22%3A%22Trend%22%2C%22attributes%22%3A%22share%22%2C%22group%22%3A%22browser%22%2C%22sort%22%3A%7B%22share%22%3A-1%7D%2C%22id%22%3A%22browsersDesktop%22%2C%22dateInterval%22%3A%22Monthly%22%2C%22dateStart%22%3A%222019-11%22%2C%22dateEnd%22%3A%222020-10%22%2C%22segments%22%3A%22-1000%22%7D
2469
+ // So we assign the same score to them.
2470
+ return 0.6;
2471
+ }
2472
+ // macOS
2473
+ if (/^Mac/.test(platform)) {
2474
+ // Chrome provides more entropy than Safari and Safari provides more entropy than Firefox.
2475
+ // Chrome is more popular than Safari and Safari is more popular than Firefox according to
2476
+ // https://netmarketshare.com/browser-market-share.aspx?options=%7B%22filter%22%3A%7B%22%24and%22%3A%5B%7B%22platform%22%3A%7B%22%24in%22%3A%5B%22Mac%20OS%22%5D%7D%7D%5D%7D%2C%22dateLabel%22%3A%22Trend%22%2C%22attributes%22%3A%22share%22%2C%22group%22%3A%22browser%22%2C%22sort%22%3A%7B%22share%22%3A-1%7D%2C%22id%22%3A%22browsersDesktop%22%2C%22dateInterval%22%3A%22Monthly%22%2C%22dateStart%22%3A%222019-11%22%2C%22dateEnd%22%3A%222020-10%22%2C%22segments%22%3A%22-1000%22%7D
2477
+ // So we assign the same score to them.
2478
+ return 0.5;
2479
+ }
2480
+ // Another platform, e.g. a desktop Linux. It's rare, so it should be pretty unique.
2481
+ return 0.7;
2482
+ }
2483
+ function deriveProConfidenceScore(openConfidenceScore) {
2484
+ return round(0.99 + 0.01 * openConfidenceScore, 0.0001);
2485
+ }
2486
+
2487
+ function componentsToCanonicalString(components) {
2488
+ var result = '';
2489
+ for (var _i = 0, _a = Object.keys(components).sort(); _i < _a.length; _i++) {
2490
+ var componentKey = _a[_i];
2491
+ var component = components[componentKey];
2492
+ var value = component.error ? 'error' : JSON.stringify(component.value);
2493
+ result += "" + (result ? '|' : '') + componentKey.replace(/([:|\\])/g, '\\$1') + ":" + value;
2494
+ }
2495
+ return result;
2496
+ }
2497
+ function componentsToDebugString(components) {
2498
+ return JSON.stringify(components, function (_key, value) {
2499
+ if (value instanceof Error) {
2500
+ return errorToObject(value);
2501
+ }
2502
+ return value;
2503
+ }, 2);
2504
+ }
2505
+ function hashComponents(components) {
2506
+ return x64hash128(componentsToCanonicalString(components));
2507
+ }
2508
+ /**
2509
+ * Makes a GetResult implementation that calculates the visitor id hash on demand.
2510
+ * Designed for optimisation.
2511
+ */
2512
+ function makeLazyGetResult(components) {
2513
+ var visitorIdCache;
2514
+ // This function runs very fast, so there is no need to make it lazy
2515
+ var confidence = getConfidence(components);
2516
+ // A plain class isn't used because its getters and setters aren't enumerable.
2517
+ return {
2518
+ get visitorId() {
2519
+ if (visitorIdCache === undefined) {
2520
+ visitorIdCache = hashComponents(this.components);
2521
+ }
2522
+ return visitorIdCache;
2523
+ },
2524
+ set visitorId(visitorId) {
2525
+ visitorIdCache = visitorId;
2526
+ },
2527
+ confidence: confidence,
2528
+ components: components,
2529
+ version: version,
2530
+ };
2531
+ }
2532
+ /**
2533
+ * A delay is required to ensure consistent entropy components.
2534
+ * See https://github.com/fingerprintjs/fingerprintjs/issues/254
2535
+ * and https://github.com/fingerprintjs/fingerprintjs/issues/307
2536
+ * and https://github.com/fingerprintjs/fingerprintjs/commit/945633e7c5f67ae38eb0fea37349712f0e669b18
2537
+ */
2538
+ function prepareForSources(delayFallback) {
2539
+ if (delayFallback === void 0) { delayFallback = 50; }
2540
+ // A proper deadline is unknown. Let it be twice the fallback timeout so that both cases have the same average time.
2541
+ return requestIdleCallbackIfAvailable(delayFallback, delayFallback * 2);
2542
+ }
2543
+ /**
2544
+ * The function isn't exported from the index file to not allow to call it without `load()`.
2545
+ * The hiding gives more freedom for future non-breaking updates.
2546
+ *
2547
+ * A factory function is used instead of a class to shorten the attribute names in the minified code.
2548
+ * Native private class fields could've been used, but TypeScript doesn't allow them with `"target": "es5"`.
2549
+ */
2550
+ function makeAgent(getComponents, debug) {
2551
+ var creationTime = Date.now();
2552
+ return {
2553
+ get: function (options) {
2554
+ return __awaiter(this, void 0, void 0, function () {
2555
+ var startTime, components, result;
2556
+ return __generator(this, function (_a) {
2557
+ switch (_a.label) {
2558
+ case 0:
2559
+ startTime = Date.now();
2560
+ return [4 /*yield*/, getComponents()];
2561
+ case 1:
2562
+ components = _a.sent();
2563
+ result = makeLazyGetResult(components);
2564
+ if (debug || (options === null || options === void 0 ? void 0 : options.debug)) {
2565
+ // console.log is ok here because it's under a debug clause
2566
+ // eslint-disable-next-line no-console
2567
+ console.log("Copy the text below to get the debug data:\n\n```\nversion: " + result.version + "\nuserAgent: " + navigator.userAgent + "\ntimeBetweenLoadAndGet: " + (startTime - creationTime) + "\nvisitorId: " + result.visitorId + "\ncomponents: " + componentsToDebugString(components) + "\n```");
2568
+ }
2569
+ return [2 /*return*/, result];
2570
+ }
2571
+ });
2572
+ });
2573
+ },
2574
+ };
2575
+ }
2576
+ /**
2577
+ * Sends an unpersonalized AJAX request to collect installation statistics
2578
+ */
2579
+ function monitor() {
2580
+ // The FingerprintJS CDN (https://github.com/fingerprintjs/cdn) replaces `window.__fpjs_d_m` with `true`
2581
+ if (window.__fpjs_d_m || Math.random() >= 0.001) {
2582
+ return;
2583
+ }
2584
+ try {
2585
+ var request = new XMLHttpRequest();
2586
+ request.open('get', "https://m1.openfpcdn.io/fingerprintjs/v" + version + "/npm-monitoring", true);
2587
+ request.send();
2588
+ }
2589
+ catch (error) {
2590
+ // console.error is ok here because it's an unexpected error handler
2591
+ // eslint-disable-next-line no-console
2592
+ console.error(error);
2593
+ }
2594
+ }
2595
+ /**
2596
+ * Builds an instance of Agent and waits a delay required for a proper operation.
2597
+ */
2598
+ function load(_a) {
2599
+ var _b = _a === void 0 ? {} : _a, delayFallback = _b.delayFallback, debug = _b.debug, _c = _b.monitoring, monitoring = _c === void 0 ? true : _c;
2600
+ return __awaiter(this, void 0, void 0, function () {
2601
+ var getComponents;
2602
+ return __generator(this, function (_d) {
2603
+ switch (_d.label) {
2604
+ case 0:
2605
+ if (monitoring) {
2606
+ monitor();
2607
+ }
2608
+ return [4 /*yield*/, prepareForSources(delayFallback)];
2609
+ case 1:
2610
+ _d.sent();
2611
+ getComponents = loadBuiltinSources({ debug: debug });
2612
+ return [2 /*return*/, makeAgent(getComponents, debug)];
2613
+ }
2614
+ });
2615
+ });
2616
+ }
2617
+
2618
+ // Unique ID creation requires a high quality random # generator. In the browser we therefore
2619
+ // require the crypto API and do not support built-in fallback to lower quality random number
2620
+ // generators (like Math.random()).
2621
+ var getRandomValues;
2622
+ var rnds8 = new Uint8Array(16);
2623
+ function rng() {
2624
+ // lazy load so that environments that need to polyfill have a chance to do so
2625
+ if (!getRandomValues) {
2626
+ // getRandomValues needs to be invoked in a context where "this" is a Crypto implementation. Also,
2627
+ // find the complete implementation of crypto (msCrypto) on IE11.
2628
+ getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto) || typeof msCrypto !== 'undefined' && typeof msCrypto.getRandomValues === 'function' && msCrypto.getRandomValues.bind(msCrypto);
2629
+
2630
+ if (!getRandomValues) {
2631
+ throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
2632
+ }
2633
+ }
2634
+
2635
+ return getRandomValues(rnds8);
2636
+ }
2637
+
2638
+ var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
2639
+
2640
+ function validate(uuid) {
2641
+ return typeof uuid === 'string' && REGEX.test(uuid);
2642
+ }
2643
+
2644
+ /**
2645
+ * Convert array of 16 byte values to UUID string format of the form:
2646
+ * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
2647
+ */
2648
+
2649
+ var byteToHex = [];
2650
+
2651
+ for (var i = 0; i < 256; ++i) {
2652
+ byteToHex.push((i + 0x100).toString(16).substr(1));
2653
+ }
2654
+
2655
+ function stringify(arr) {
2656
+ var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
2657
+ // Note: Be careful editing this code! It's been tuned for performance
2658
+ // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
2659
+ var uuid = (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(); // Consistency check for valid UUID. If this throws, it's likely due to one
2660
+ // of the following:
2661
+ // - One or more input array values don't map to a hex octet (leading to
2662
+ // "undefined" in the uuid)
2663
+ // - Invalid input values for the RFC `version` or `variant` fields
2664
+
2665
+ if (!validate(uuid)) {
2666
+ throw TypeError('Stringified UUID is invalid');
2667
+ }
2668
+
2669
+ return uuid;
2670
+ }
2671
+
2672
+ function parse(uuid) {
2673
+ if (!validate(uuid)) {
2674
+ throw TypeError('Invalid UUID');
2675
+ }
2676
+
2677
+ var v;
2678
+ var arr = new Uint8Array(16); // Parse ########-....-....-....-............
2679
+
2680
+ arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
2681
+ arr[1] = v >>> 16 & 0xff;
2682
+ arr[2] = v >>> 8 & 0xff;
2683
+ arr[3] = v & 0xff; // Parse ........-####-....-....-............
2684
+
2685
+ arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
2686
+ arr[5] = v & 0xff; // Parse ........-....-####-....-............
2687
+
2688
+ arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
2689
+ arr[7] = v & 0xff; // Parse ........-....-....-####-............
2690
+
2691
+ arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
2692
+ arr[9] = v & 0xff; // Parse ........-....-....-....-############
2693
+ // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
2694
+
2695
+ arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
2696
+ arr[11] = v / 0x100000000 & 0xff;
2697
+ arr[12] = v >>> 24 & 0xff;
2698
+ arr[13] = v >>> 16 & 0xff;
2699
+ arr[14] = v >>> 8 & 0xff;
2700
+ arr[15] = v & 0xff;
2701
+ return arr;
2702
+ }
2703
+
2704
+ function stringToBytes(str) {
2705
+ str = unescape(encodeURIComponent(str)); // UTF8 escape
2706
+
2707
+ var bytes = [];
2708
+
2709
+ for (var i = 0; i < str.length; ++i) {
2710
+ bytes.push(str.charCodeAt(i));
2711
+ }
2712
+
2713
+ return bytes;
2714
+ }
2715
+
2716
+ var DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
2717
+ var URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
2718
+ function v35 (name, version, hashfunc) {
2719
+ function generateUUID(value, namespace, buf, offset) {
2720
+ if (typeof value === 'string') {
2721
+ value = stringToBytes(value);
2722
+ }
2723
+
2724
+ if (typeof namespace === 'string') {
2725
+ namespace = parse(namespace);
2726
+ }
2727
+
2728
+ if (namespace.length !== 16) {
2729
+ throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
2730
+ } // Compute hash of namespace and value, Per 4.3
2731
+ // Future: Use spread syntax when supported on all platforms, e.g. `bytes =
2732
+ // hashfunc([...namespace, ... value])`
2733
+
2734
+
2735
+ var bytes = new Uint8Array(16 + value.length);
2736
+ bytes.set(namespace);
2737
+ bytes.set(value, namespace.length);
2738
+ bytes = hashfunc(bytes);
2739
+ bytes[6] = bytes[6] & 0x0f | version;
2740
+ bytes[8] = bytes[8] & 0x3f | 0x80;
2741
+
2742
+ if (buf) {
2743
+ offset = offset || 0;
2744
+
2745
+ for (var i = 0; i < 16; ++i) {
2746
+ buf[offset + i] = bytes[i];
2747
+ }
2748
+
2749
+ return buf;
2750
+ }
2751
+
2752
+ return stringify(bytes);
2753
+ } // Function#name is not settable on some platforms (#270)
2754
+
2755
+
2756
+ try {
2757
+ generateUUID.name = name; // eslint-disable-next-line no-empty
2758
+ } catch (err) {} // For CommonJS default export support
2759
+
2760
+
2761
+ generateUUID.DNS = DNS;
2762
+ generateUUID.URL = URL;
2763
+ return generateUUID;
2764
+ }
2765
+
2766
+ /*
2767
+ * Browser-compatible JavaScript MD5
2768
+ *
2769
+ * Modification of JavaScript MD5
2770
+ * https://github.com/blueimp/JavaScript-MD5
2771
+ *
2772
+ * Copyright 2011, Sebastian Tschan
2773
+ * https://blueimp.net
2774
+ *
2775
+ * Licensed under the MIT license:
2776
+ * https://opensource.org/licenses/MIT
2777
+ *
2778
+ * Based on
2779
+ * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
2780
+ * Digest Algorithm, as defined in RFC 1321.
2781
+ * Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
2782
+ * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
2783
+ * Distributed under the BSD License
2784
+ * See http://pajhome.org.uk/crypt/md5 for more info.
2785
+ */
2786
+ function md5(bytes) {
2787
+ if (typeof bytes === 'string') {
2788
+ var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
2789
+
2790
+ bytes = new Uint8Array(msg.length);
2791
+
2792
+ for (var i = 0; i < msg.length; ++i) {
2793
+ bytes[i] = msg.charCodeAt(i);
2794
+ }
2795
+ }
2796
+
2797
+ return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
2798
+ }
2799
+ /*
2800
+ * Convert an array of little-endian words to an array of bytes
2801
+ */
2802
+
2803
+
2804
+ function md5ToHexEncodedArray(input) {
2805
+ var output = [];
2806
+ var length32 = input.length * 32;
2807
+ var hexTab = '0123456789abcdef';
2808
+
2809
+ for (var i = 0; i < length32; i += 8) {
2810
+ var x = input[i >> 5] >>> i % 32 & 0xff;
2811
+ var hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
2812
+ output.push(hex);
2813
+ }
2814
+
2815
+ return output;
2816
+ }
2817
+ /**
2818
+ * Calculate output length with padding and bit length
2819
+ */
2820
+
2821
+
2822
+ function getOutputLength(inputLength8) {
2823
+ return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
2824
+ }
2825
+ /*
2826
+ * Calculate the MD5 of an array of little-endian words, and a bit length.
2827
+ */
2828
+
2829
+
2830
+ function wordsToMd5(x, len) {
2831
+ /* append padding */
2832
+ x[len >> 5] |= 0x80 << len % 32;
2833
+ x[getOutputLength(len) - 1] = len;
2834
+ var a = 1732584193;
2835
+ var b = -271733879;
2836
+ var c = -1732584194;
2837
+ var d = 271733878;
2838
+
2839
+ for (var i = 0; i < x.length; i += 16) {
2840
+ var olda = a;
2841
+ var oldb = b;
2842
+ var oldc = c;
2843
+ var oldd = d;
2844
+ a = md5ff(a, b, c, d, x[i], 7, -680876936);
2845
+ d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
2846
+ c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
2847
+ b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
2848
+ a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
2849
+ d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
2850
+ c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
2851
+ b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
2852
+ a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
2853
+ d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
2854
+ c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
2855
+ b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
2856
+ a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
2857
+ d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
2858
+ c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
2859
+ b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
2860
+ a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
2861
+ d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
2862
+ c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
2863
+ b = md5gg(b, c, d, a, x[i], 20, -373897302);
2864
+ a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
2865
+ d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
2866
+ c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
2867
+ b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
2868
+ a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
2869
+ d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
2870
+ c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
2871
+ b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
2872
+ a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
2873
+ d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
2874
+ c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
2875
+ b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
2876
+ a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
2877
+ d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
2878
+ c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
2879
+ b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
2880
+ a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
2881
+ d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
2882
+ c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
2883
+ b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
2884
+ a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
2885
+ d = md5hh(d, a, b, c, x[i], 11, -358537222);
2886
+ c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
2887
+ b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
2888
+ a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
2889
+ d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
2890
+ c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
2891
+ b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
2892
+ a = md5ii(a, b, c, d, x[i], 6, -198630844);
2893
+ d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
2894
+ c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
2895
+ b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
2896
+ a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
2897
+ d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
2898
+ c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
2899
+ b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
2900
+ a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
2901
+ d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
2902
+ c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
2903
+ b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
2904
+ a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
2905
+ d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
2906
+ c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
2907
+ b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
2908
+ a = safeAdd(a, olda);
2909
+ b = safeAdd(b, oldb);
2910
+ c = safeAdd(c, oldc);
2911
+ d = safeAdd(d, oldd);
2912
+ }
2913
+
2914
+ return [a, b, c, d];
2915
+ }
2916
+ /*
2917
+ * Convert an array bytes to an array of little-endian words
2918
+ * Characters >255 have their high-byte silently ignored.
2919
+ */
2920
+
2921
+
2922
+ function bytesToWords(input) {
2923
+ if (input.length === 0) {
2924
+ return [];
2925
+ }
2926
+
2927
+ var length8 = input.length * 8;
2928
+ var output = new Uint32Array(getOutputLength(length8));
2929
+
2930
+ for (var i = 0; i < length8; i += 8) {
2931
+ output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
2932
+ }
2933
+
2934
+ return output;
2935
+ }
2936
+ /*
2937
+ * Add integers, wrapping at 2^32. This uses 16-bit operations internally
2938
+ * to work around bugs in some JS interpreters.
2939
+ */
2940
+
2941
+
2942
+ function safeAdd(x, y) {
2943
+ var lsw = (x & 0xffff) + (y & 0xffff);
2944
+ var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
2945
+ return msw << 16 | lsw & 0xffff;
2946
+ }
2947
+ /*
2948
+ * Bitwise rotate a 32-bit number to the left.
2949
+ */
2950
+
2951
+
2952
+ function bitRotateLeft(num, cnt) {
2953
+ return num << cnt | num >>> 32 - cnt;
2954
+ }
2955
+ /*
2956
+ * These functions implement the four basic operations the algorithm uses.
2957
+ */
2958
+
2959
+
2960
+ function md5cmn(q, a, b, x, s, t) {
2961
+ return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
2962
+ }
2963
+
2964
+ function md5ff(a, b, c, d, x, s, t) {
2965
+ return md5cmn(b & c | ~b & d, a, b, x, s, t);
2966
+ }
2967
+
2968
+ function md5gg(a, b, c, d, x, s, t) {
2969
+ return md5cmn(b & d | c & ~d, a, b, x, s, t);
2970
+ }
2971
+
2972
+ function md5hh(a, b, c, d, x, s, t) {
2973
+ return md5cmn(b ^ c ^ d, a, b, x, s, t);
2974
+ }
2975
+
2976
+ function md5ii(a, b, c, d, x, s, t) {
2977
+ return md5cmn(c ^ (b | ~d), a, b, x, s, t);
2978
+ }
2979
+
2980
+ v35('v3', 0x30, md5);
2981
+
2982
+ function v4(options, buf, offset) {
2983
+ options = options || {};
2984
+ var rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
2985
+
2986
+ rnds[6] = rnds[6] & 0x0f | 0x40;
2987
+ rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
2988
+
2989
+ if (buf) {
2990
+ offset = offset || 0;
2991
+
2992
+ for (var i = 0; i < 16; ++i) {
2993
+ buf[offset + i] = rnds[i];
2994
+ }
2995
+
2996
+ return buf;
2997
+ }
2998
+
2999
+ return stringify(rnds);
3000
+ }
3001
+
3002
+ // Adapted from Chris Veness' SHA1 code at
3003
+ // http://www.movable-type.co.uk/scripts/sha1.html
3004
+ function f(s, x, y, z) {
3005
+ switch (s) {
3006
+ case 0:
3007
+ return x & y ^ ~x & z;
3008
+
3009
+ case 1:
3010
+ return x ^ y ^ z;
3011
+
3012
+ case 2:
3013
+ return x & y ^ x & z ^ y & z;
3014
+
3015
+ case 3:
3016
+ return x ^ y ^ z;
3017
+ }
3018
+ }
3019
+
3020
+ function ROTL(x, n) {
3021
+ return x << n | x >>> 32 - n;
3022
+ }
3023
+
3024
+ function sha1(bytes) {
3025
+ var K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
3026
+ var H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
3027
+
3028
+ if (typeof bytes === 'string') {
3029
+ var msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
3030
+
3031
+ bytes = [];
3032
+
3033
+ for (var i = 0; i < msg.length; ++i) {
3034
+ bytes.push(msg.charCodeAt(i));
3035
+ }
3036
+ } else if (!Array.isArray(bytes)) {
3037
+ // Convert Array-like to Array
3038
+ bytes = Array.prototype.slice.call(bytes);
3039
+ }
3040
+
3041
+ bytes.push(0x80);
3042
+ var l = bytes.length / 4 + 2;
3043
+ var N = Math.ceil(l / 16);
3044
+ var M = new Array(N);
3045
+
3046
+ for (var _i = 0; _i < N; ++_i) {
3047
+ var arr = new Uint32Array(16);
3048
+
3049
+ for (var j = 0; j < 16; ++j) {
3050
+ arr[j] = bytes[_i * 64 + j * 4] << 24 | bytes[_i * 64 + j * 4 + 1] << 16 | bytes[_i * 64 + j * 4 + 2] << 8 | bytes[_i * 64 + j * 4 + 3];
3051
+ }
3052
+
3053
+ M[_i] = arr;
3054
+ }
3055
+
3056
+ M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
3057
+ M[N - 1][14] = Math.floor(M[N - 1][14]);
3058
+ M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
3059
+
3060
+ for (var _i2 = 0; _i2 < N; ++_i2) {
3061
+ var W = new Uint32Array(80);
3062
+
3063
+ for (var t = 0; t < 16; ++t) {
3064
+ W[t] = M[_i2][t];
3065
+ }
3066
+
3067
+ for (var _t = 16; _t < 80; ++_t) {
3068
+ W[_t] = ROTL(W[_t - 3] ^ W[_t - 8] ^ W[_t - 14] ^ W[_t - 16], 1);
3069
+ }
3070
+
3071
+ var a = H[0];
3072
+ var b = H[1];
3073
+ var c = H[2];
3074
+ var d = H[3];
3075
+ var e = H[4];
3076
+
3077
+ for (var _t2 = 0; _t2 < 80; ++_t2) {
3078
+ var s = Math.floor(_t2 / 20);
3079
+ var T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[_t2] >>> 0;
3080
+ e = d;
3081
+ d = c;
3082
+ c = ROTL(b, 30) >>> 0;
3083
+ b = a;
3084
+ a = T;
3085
+ }
3086
+
3087
+ H[0] = H[0] + a >>> 0;
3088
+ H[1] = H[1] + b >>> 0;
3089
+ H[2] = H[2] + c >>> 0;
3090
+ H[3] = H[3] + d >>> 0;
3091
+ H[4] = H[4] + e >>> 0;
3092
+ }
3093
+
3094
+ return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];
3095
+ }
3096
+
3097
+ v35('v5', 0x50, sha1);
3098
+
3099
+ var setCookie = function (name, value, expire, domain, secure) {
3100
+ var expireString = expire === Infinity ? " expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + expire;
3101
+ document.cookie =
3102
+ encodeURIComponent(name) +
3103
+ "=" +
3104
+ value +
3105
+ "; path=/;" +
3106
+ expireString +
3107
+ (domain ? "; domain=" + domain : "") +
3108
+ (secure ? "; secure" : "");
3109
+ };
3110
+ var getCookieDomain = function () {
3111
+ return location.hostname.replace("www.", "");
3112
+ };
3113
+ var generateId = function () {
3114
+ return v4();
3115
+ };
3116
+ var getCookie = function (name) {
3117
+ if (!name) {
3118
+ return null;
3119
+ }
3120
+ return (decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(name).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null);
3121
+ };
3122
+ var getHostWithProtocol = function (host) {
3123
+ while (endsWith(host, "/")) {
3124
+ host = host.substr(0, host.length - 1);
3125
+ }
3126
+ if (host.indexOf("https://") === 0 || host.indexOf("http://") === 0) {
3127
+ return host;
3128
+ }
3129
+ else {
3130
+ return "//" + host;
3131
+ }
3132
+ };
3133
+ function endsWith(str, suffix) {
3134
+ return str.indexOf(suffix, str.length - suffix.length) !== -1;
3135
+ }
3136
+ var reformatDate = function (strDate) {
3137
+ var end = strDate.split(".")[1];
3138
+ if (!end) {
3139
+ return strDate;
3140
+ }
3141
+ if (end.length >= 7) {
3142
+ return strDate;
3143
+ }
3144
+ return strDate.slice(0, -1) + "0".repeat(7 - end.length) + "Z";
3145
+ };
3146
+
3147
+ var focusableSelectors = [
3148
+ 'a[href]:not([tabindex^="-"])',
3149
+ 'area[href]:not([tabindex^="-"])',
3150
+ 'input:not([type="hidden"]):not([type="radio"]):not([disabled]):not([tabindex^="-"])',
3151
+ 'input[type="radio"]:not([disabled]):not([tabindex^="-"])',
3152
+ 'select:not([disabled]):not([tabindex^="-"])',
3153
+ 'textarea:not([disabled]):not([tabindex^="-"])',
3154
+ 'button:not([disabled]):not([tabindex^="-"])',
3155
+ 'iframe:not([tabindex^="-"])',
3156
+ 'audio[controls]:not([tabindex^="-"])',
3157
+ 'video[controls]:not([tabindex^="-"])',
3158
+ '[contenteditable]:not([tabindex^="-"])',
3159
+ '[tabindex]:not([tabindex^="-"])',
3160
+ ];
3161
+
3162
+ var TAB_KEY = 9;
3163
+ var ESCAPE_KEY = 27;
3164
+
3165
+ /**
3166
+ * Define the constructor to instantiate a dialog
3167
+ *
3168
+ * @constructor
3169
+ * @param {Element} element
3170
+ */
3171
+ function A11yDialog(element) {
3172
+ // Prebind the functions that will be bound in addEventListener and
3173
+ // removeEventListener to avoid losing references
3174
+ this._show = this.show.bind(this);
3175
+ this._hide = this.hide.bind(this);
3176
+ this._maintainFocus = this._maintainFocus.bind(this);
3177
+ this._bindKeypress = this._bindKeypress.bind(this);
3178
+
3179
+ this.$el = element;
3180
+ this.shown = false;
3181
+ this._id = this.$el.getAttribute('data-a11y-dialog') || this.$el.id;
3182
+ this._previouslyFocused = null;
3183
+ this._listeners = {};
3184
+
3185
+ // Initialise everything needed for the dialog to work properly
3186
+ this.create();
3187
+ }
3188
+
3189
+ /**
3190
+ * Set up everything necessary for the dialog to be functioning
3191
+ *
3192
+ * @param {(NodeList | Element | string)} targets
3193
+ * @return {this}
3194
+ */
3195
+ A11yDialog.prototype.create = function () {
3196
+ this.$el.setAttribute('aria-hidden', true);
3197
+ this.$el.setAttribute('aria-modal', true);
3198
+ this.$el.setAttribute('tabindex', -1);
3199
+
3200
+ if (!this.$el.hasAttribute('role')) {
3201
+ this.$el.setAttribute('role', 'dialog');
3202
+ }
3203
+
3204
+ // Keep a collection of dialog openers, each of which will be bound a click
3205
+ // event listener to open the dialog
3206
+ this._openers = $$('[data-a11y-dialog-show="' + this._id + '"]');
3207
+ this._openers.forEach(
3208
+ function (opener) {
3209
+ opener.addEventListener('click', this._show);
3210
+ }.bind(this)
3211
+ );
3212
+
3213
+ // Keep a collection of dialog closers, each of which will be bound a click
3214
+ // event listener to close the dialog
3215
+ this._closers = $$('[data-a11y-dialog-hide]', this.$el).concat(
3216
+ $$('[data-a11y-dialog-hide="' + this._id + '"]')
3217
+ );
3218
+ this._closers.forEach(
3219
+ function (closer) {
3220
+ closer.addEventListener('click', this._hide);
3221
+ }.bind(this)
3222
+ );
3223
+
3224
+ // Execute all callbacks registered for the `create` event
3225
+ this._fire('create');
3226
+
3227
+ return this
3228
+ };
3229
+
3230
+ /**
3231
+ * Show the dialog element, disable all the targets (siblings), trap the
3232
+ * current focus within it, listen for some specific key presses and fire all
3233
+ * registered callbacks for `show` event
3234
+ *
3235
+ * @param {CustomEvent} event
3236
+ * @return {this}
3237
+ */
3238
+ A11yDialog.prototype.show = function (event) {
3239
+ // If the dialog is already open, abort
3240
+ if (this.shown) {
3241
+ return this
3242
+ }
3243
+
3244
+ // Keep a reference to the currently focused element to be able to restore
3245
+ // it later
3246
+ this._previouslyFocused = document.activeElement;
3247
+ this.$el.removeAttribute('aria-hidden');
3248
+ this.shown = true;
3249
+
3250
+ // Set the focus to the dialog element
3251
+ moveFocusToDialog(this.$el);
3252
+
3253
+ // Bind a focus event listener to the body element to make sure the focus
3254
+ // stays trapped inside the dialog while open, and start listening for some
3255
+ // specific key presses (TAB and ESC)
3256
+ document.body.addEventListener('focus', this._maintainFocus, true);
3257
+ document.addEventListener('keydown', this._bindKeypress);
3258
+
3259
+ // Execute all callbacks registered for the `show` event
3260
+ this._fire('show', event);
3261
+
3262
+ return this
3263
+ };
3264
+
3265
+ /**
3266
+ * Hide the dialog element, enable all the targets (siblings), restore the
3267
+ * focus to the previously active element, stop listening for some specific
3268
+ * key presses and fire all registered callbacks for `hide` event
3269
+ *
3270
+ * @param {CustomEvent} event
3271
+ * @return {this}
3272
+ */
3273
+ A11yDialog.prototype.hide = function (event) {
3274
+ // If the dialog is already closed, abort
3275
+ if (!this.shown) {
3276
+ return this
3277
+ }
3278
+
3279
+ this.shown = false;
3280
+ this.$el.setAttribute('aria-hidden', 'true');
3281
+
3282
+ // If there was a focused element before the dialog was opened (and it has a
3283
+ // `focus` method), restore the focus back to it
3284
+ // See: https://github.com/KittyGiraudel/a11y-dialog/issues/108
3285
+ if (this._previouslyFocused && this._previouslyFocused.focus) {
3286
+ this._previouslyFocused.focus();
3287
+ }
3288
+
3289
+ // Remove the focus event listener to the body element and stop listening
3290
+ // for specific key presses
3291
+ document.body.removeEventListener('focus', this._maintainFocus, true);
3292
+ document.removeEventListener('keydown', this._bindKeypress);
3293
+
3294
+ // Execute all callbacks registered for the `hide` event
3295
+ this._fire('hide', event);
3296
+
3297
+ return this
3298
+ };
3299
+
3300
+ /**
3301
+ * Destroy the current instance (after making sure the dialog has been hidden)
3302
+ * and remove all associated listeners from dialog openers and closers
3303
+ *
3304
+ * @return {this}
3305
+ */
3306
+ A11yDialog.prototype.destroy = function () {
3307
+ // Hide the dialog to avoid destroying an open instance
3308
+ this.hide();
3309
+
3310
+ // Remove the click event listener from all dialog openers
3311
+ this._openers.forEach(
3312
+ function (opener) {
3313
+ opener.removeEventListener('click', this._show);
3314
+ }.bind(this)
3315
+ );
3316
+
3317
+ // Remove the click event listener from all dialog closers
3318
+ this._closers.forEach(
3319
+ function (closer) {
3320
+ closer.removeEventListener('click', this._hide);
3321
+ }.bind(this)
3322
+ );
3323
+
3324
+ // Execute all callbacks registered for the `destroy` event
3325
+ this._fire('destroy');
3326
+
3327
+ // Keep an object of listener types mapped to callback functions
3328
+ this._listeners = {};
3329
+
3330
+ return this
3331
+ };
3332
+
3333
+ /**
3334
+ * Register a new callback for the given event type
3335
+ *
3336
+ * @param {string} type
3337
+ * @param {Function} handler
3338
+ */
3339
+ A11yDialog.prototype.on = function (type, handler) {
3340
+ if (typeof this._listeners[type] === 'undefined') {
3341
+ this._listeners[type] = [];
3342
+ }
3343
+
3344
+ this._listeners[type].push(handler);
3345
+
3346
+ return this
3347
+ };
3348
+
3349
+ /**
3350
+ * Unregister an existing callback for the given event type
3351
+ *
3352
+ * @param {string} type
3353
+ * @param {Function} handler
3354
+ */
3355
+ A11yDialog.prototype.off = function (type, handler) {
3356
+ var index = (this._listeners[type] || []).indexOf(handler);
3357
+
3358
+ if (index > -1) {
3359
+ this._listeners[type].splice(index, 1);
3360
+ }
3361
+
3362
+ return this
3363
+ };
3364
+
3365
+ /**
3366
+ * Iterate over all registered handlers for given type and call them all with
3367
+ * the dialog element as first argument, event as second argument (if any). Also
3368
+ * dispatch a custom event on the DOM element itself to make it possible to
3369
+ * react to the lifecycle of auto-instantiated dialogs.
3370
+ *
3371
+ * @access private
3372
+ * @param {string} type
3373
+ * @param {CustomEvent} event
3374
+ */
3375
+ A11yDialog.prototype._fire = function (type, event) {
3376
+ var listeners = this._listeners[type] || [];
3377
+ var domEvent = new CustomEvent(type, { detail: event });
3378
+
3379
+ this.$el.dispatchEvent(domEvent);
3380
+
3381
+ listeners.forEach(
3382
+ function (listener) {
3383
+ listener(this.$el, event);
3384
+ }.bind(this)
3385
+ );
3386
+ };
3387
+
3388
+ /**
3389
+ * Private event handler used when listening to some specific key presses
3390
+ * (namely ESCAPE and TAB)
3391
+ *
3392
+ * @access private
3393
+ * @param {Event} event
3394
+ */
3395
+ A11yDialog.prototype._bindKeypress = function (event) {
3396
+ // This is an escape hatch in case there are nested dialogs, so the keypresses
3397
+ // are only reacted to for the most recent one
3398
+ if (!this.$el.contains(document.activeElement)) return
3399
+
3400
+ // If the dialog is shown and the ESCAPE key is being pressed, prevent any
3401
+ // further effects from the ESCAPE key and hide the dialog, unless its role
3402
+ // is 'alertdialog', which should be modal
3403
+ if (
3404
+ this.shown &&
3405
+ event.which === ESCAPE_KEY &&
3406
+ this.$el.getAttribute('role') !== 'alertdialog'
3407
+ ) {
3408
+ event.preventDefault();
3409
+ this.hide(event);
3410
+ }
3411
+
3412
+ // If the dialog is shown and the TAB key is being pressed, make sure the
3413
+ // focus stays trapped within the dialog element
3414
+ if (this.shown && event.which === TAB_KEY) {
3415
+ trapTabKey(this.$el, event);
3416
+ }
3417
+ };
3418
+
3419
+ /**
3420
+ * Private event handler used when making sure the focus stays within the
3421
+ * currently open dialog
3422
+ *
3423
+ * @access private
3424
+ * @param {Event} event
3425
+ */
3426
+ A11yDialog.prototype._maintainFocus = function (event) {
3427
+ // If the dialog is shown and the focus is not within a dialog element (either
3428
+ // this one or another one in case of nested dialogs) or within an element
3429
+ // with the `data-a11y-dialog-focus-trap-ignore` attribute, move it back to
3430
+ // its first focusable child.
3431
+ // See: https://github.com/KittyGiraudel/a11y-dialog/issues/177
3432
+ if (
3433
+ this.shown &&
3434
+ !event.target.closest('[aria-modal="true"]') &&
3435
+ !event.target.closest('[data-a11y-dialog-ignore-focus-trap]')
3436
+ ) {
3437
+ moveFocusToDialog(this.$el);
3438
+ }
3439
+ };
3440
+
3441
+ /**
3442
+ * Convert a NodeList into an array
3443
+ *
3444
+ * @param {NodeList} collection
3445
+ * @return {Array<Element>}
3446
+ */
3447
+ function toArray(collection) {
3448
+ return Array.prototype.slice.call(collection)
3449
+ }
3450
+
3451
+ /**
3452
+ * Query the DOM for nodes matching the given selector, scoped to context (or
3453
+ * the whole document)
3454
+ *
3455
+ * @param {String} selector
3456
+ * @param {Element} [context = document]
3457
+ * @return {Array<Element>}
3458
+ */
3459
+ function $$(selector, context) {
3460
+ return toArray((context || document).querySelectorAll(selector))
3461
+ }
3462
+
3463
+ /**
3464
+ * Set the focus to the first element with `autofocus` with the element or the
3465
+ * element itself
3466
+ *
3467
+ * @param {Element} node
3468
+ */
3469
+ function moveFocusToDialog(node) {
3470
+ var focused = node.querySelector('[autofocus]') || node;
3471
+
3472
+ focused.focus();
3473
+ }
3474
+
3475
+ /**
3476
+ * Get the focusable children of the given element
3477
+ *
3478
+ * @param {Element} node
3479
+ * @return {Array<Element>}
3480
+ */
3481
+ function getFocusableChildren(node) {
3482
+ return $$(focusableSelectors.join(','), node).filter(function (child) {
3483
+ return !!(
3484
+ child.offsetWidth ||
3485
+ child.offsetHeight ||
3486
+ child.getClientRects().length
3487
+ )
3488
+ })
3489
+ }
3490
+
3491
+ /**
3492
+ * Trap the focus inside the given element
3493
+ *
3494
+ * @param {Element} node
3495
+ * @param {Event} event
3496
+ */
3497
+ function trapTabKey(node, event) {
3498
+ var focusableChildren = getFocusableChildren(node);
3499
+ var focusedItemIndex = focusableChildren.indexOf(document.activeElement);
3500
+
3501
+ // If the SHIFT key is being pressed while tabbing (moving backwards) and
3502
+ // the currently focused item is the first one, move the focus to the last
3503
+ // focusable item from the dialog element
3504
+ if (event.shiftKey && focusedItemIndex === 0) {
3505
+ focusableChildren[focusableChildren.length - 1].focus();
3506
+ event.preventDefault();
3507
+ // If the SHIFT key is not being pressed (moving forwards) and the currently
3508
+ // focused item is the last one, move the focus to the first focusable item
3509
+ // from the dialog element
3510
+ } else if (
3511
+ !event.shiftKey &&
3512
+ focusedItemIndex === focusableChildren.length - 1
3513
+ ) {
3514
+ focusableChildren[0].focus();
3515
+ event.preventDefault();
3516
+ }
3517
+ }
3518
+
3519
+ function instantiateDialogs() {
3520
+ $$('[data-a11y-dialog]').forEach(function (node) {
3521
+ new A11yDialog(node);
3522
+ });
3523
+ }
3524
+
3525
+ if (typeof document !== 'undefined') {
3526
+ if (document.readyState === 'loading') {
3527
+ document.addEventListener('DOMContentLoaded', instantiateDialogs);
3528
+ } else {
3529
+ if (window.requestAnimationFrame) {
3530
+ window.requestAnimationFrame(instantiateDialogs);
3531
+ } else {
3532
+ window.setTimeout(instantiateDialogs, 16);
3533
+ }
3534
+ }
3535
+ }
3536
+
3537
+ var DIALOG_CONTAINER_ID = "authsignal-popup";
3538
+ var DIALOG_CONTENT_ID = "authsignal-popup-content";
3539
+ var PopupHandler = /** @class */ (function () {
3540
+ function PopupHandler() {
3541
+ this.popup = null;
3542
+ if (document.querySelector("#".concat(DIALOG_CONTAINER_ID))) {
3543
+ throw new Error("Multiple instances of Authsignal popup is not supported.");
3544
+ }
3545
+ this.create();
3546
+ }
3547
+ PopupHandler.prototype.create = function () {
3548
+ // Dialog container
3549
+ var container = document.createElement("div");
3550
+ container.setAttribute("id", DIALOG_CONTAINER_ID);
3551
+ container.setAttribute("aria-hidden", "true");
3552
+ container.setAttribute("class", "dialog-container");
3553
+ // Dialog overlay
3554
+ var overlay = document.createElement("div");
3555
+ overlay.setAttribute("class", "dialog-overlay");
3556
+ overlay.setAttribute("data-a11y-dialog-hide", "true");
3557
+ container.appendChild(overlay);
3558
+ // Dialog content
3559
+ var content = document.createElement("div");
3560
+ content.setAttribute("class", "dialog-content");
3561
+ content.setAttribute("id", DIALOG_CONTENT_ID);
3562
+ container.appendChild(content);
3563
+ document.body.appendChild(container);
3564
+ this.popup = new A11yDialog(container);
3565
+ this.popup.on("hide", this.destroy);
3566
+ };
3567
+ PopupHandler.prototype.destroy = function () {
3568
+ var dialogEl = document.querySelector("#".concat(DIALOG_CONTAINER_ID));
3569
+ if (dialogEl) {
3570
+ document.body.removeChild(dialogEl);
3571
+ }
3572
+ };
3573
+ PopupHandler.prototype.show = function (_a) {
3574
+ var challengeUrl = _a.challengeUrl;
3575
+ if (!this.popup) {
3576
+ throw new Error("Popup is not initialized");
3577
+ }
3578
+ var iframe = document.createElement("iframe");
3579
+ iframe.setAttribute("name", "authsignal");
3580
+ iframe.setAttribute("title", "Authsignal multi-factor authentication challenge");
3581
+ iframe.setAttribute("src", challengeUrl);
3582
+ iframe.setAttribute("width", "600");
3583
+ iframe.setAttribute("height", "600");
3584
+ iframe.setAttribute("frameborder", "0");
3585
+ var dialogContent = document.querySelector("#".concat(DIALOG_CONTENT_ID));
3586
+ if (dialogContent) {
3587
+ dialogContent.appendChild(iframe);
3588
+ }
3589
+ this.popup.show();
3590
+ };
3591
+ PopupHandler.prototype.close = function () {
3592
+ if (!this.popup) {
3593
+ throw new Error("Popup is not initialized");
3594
+ }
3595
+ this.popup.hide();
3596
+ };
3597
+ return PopupHandler;
3598
+ }());
3599
+
3600
+ function authsignalClient(publishableKey, options) {
3601
+ var client = new AuthsignalClient();
3602
+ client.init(publishableKey, options);
3603
+ return client;
3604
+ }
3605
+ var AuthsignalClient = /** @class */ (function () {
3606
+ function AuthsignalClient() {
3607
+ this.anonymousId = "";
3608
+ this.initialized = false;
3609
+ this.publishableKey = "";
3610
+ this.cookieDomain = "";
3611
+ this.idCookieName = "";
3612
+ this.trackingHost = "";
3613
+ }
3614
+ AuthsignalClient.prototype.init = function (publishableKey, options) {
3615
+ return __awaiter(this, void 0, void 0, function () {
3616
+ var _a, anonymousId, isGeneratedAnonymousId, agent, registerAnonymousIdRequest;
3617
+ return __generator(this, function (_b) {
3618
+ switch (_b.label) {
3619
+ case 0:
3620
+ this.cookieDomain = (options === null || options === void 0 ? void 0 : options.cookie_domain) || getCookieDomain();
3621
+ this.idCookieName = (options === null || options === void 0 ? void 0 : options.cookie_name) || "__as_aid";
3622
+ this.trackingHost = getHostWithProtocol((options === null || options === void 0 ? void 0 : options.tracking_host) || "t.authsignal.com");
3623
+ _a = this;
3624
+ return [4 /*yield*/, load({
3625
+ monitoring: false
3626
+ })];
3627
+ case 1:
3628
+ _a.fingerprintClient = _b.sent();
3629
+ anonymousId = this.getAnonymousId();
3630
+ this.anonymousId = anonymousId.idCookie;
3631
+ isGeneratedAnonymousId = anonymousId.generated;
3632
+ return [4 /*yield*/, this.fingerprintClient.get()];
3633
+ case 2:
3634
+ agent = _b.sent();
3635
+ this.deviceFingerprint = agent.visitorId;
3636
+ if (!publishableKey) {
3637
+ throw Error("IntegrationError");
3638
+ }
3639
+ this.publishableKey = publishableKey;
3640
+ if (!isGeneratedAnonymousId) return [3 /*break*/, 4];
3641
+ registerAnonymousIdRequest = this.buildRegisterAnonymousIdRequest();
3642
+ return [4 /*yield*/, this.registerAnonymousId(registerAnonymousIdRequest)];
3643
+ case 3:
3644
+ _b.sent();
3645
+ _b.label = 4;
3646
+ case 4:
3647
+ this.initialized = true;
3648
+ return [2 /*return*/];
3649
+ }
3650
+ });
3651
+ });
3652
+ };
3653
+ AuthsignalClient.prototype.identify = function (props) {
3654
+ return __awaiter(this, void 0, void 0, function () {
3655
+ var request;
3656
+ return __generator(this, function (_a) {
3657
+ switch (_a.label) {
3658
+ case 0:
3659
+ console.log("AS user identified", props);
3660
+ request = __assign(__assign({}, props), { anonymousId: this.anonymousId });
3661
+ return [4 /*yield*/, this.registerIdentity(request)];
3662
+ case 1: return [2 /*return*/, _a.sent()];
3663
+ }
3664
+ });
3665
+ });
3666
+ };
3667
+ AuthsignalClient.prototype.getAnonymousId = function () {
3668
+ var idCookie = getCookie(this.idCookieName);
3669
+ if (idCookie) {
3670
+ return { idCookie: idCookie, generated: false };
3671
+ }
3672
+ var newId = generateId();
3673
+ setCookie("__as_aid", newId, Infinity, this.cookieDomain, document.location.protocol !== "http:");
3674
+ return { idCookie: newId, generated: true };
3675
+ };
3676
+ AuthsignalClient.prototype.challengeWithPopup = function (_a) {
3677
+ var challengeUrl = _a.challengeUrl;
3678
+ var Popup = new PopupHandler();
3679
+ Popup.show({ challengeUrl: challengeUrl });
3680
+ return new Promise(function (resolve, reject) {
3681
+ var handleChallenge = function (event) {
3682
+ if (event.data === "authsignal-challenge-success") {
3683
+ Popup.close();
3684
+ resolve(true);
3685
+ }
3686
+ else if (event.data === "authsignal-challenge-failure") {
3687
+ Popup.close();
3688
+ reject(false);
3689
+ }
3690
+ };
3691
+ window.addEventListener("message", handleChallenge, false);
3692
+ });
3693
+ };
3694
+ AuthsignalClient.prototype.registerIdentity = function (request) {
3695
+ return __awaiter(this, void 0, void 0, function () {
3696
+ var result;
3697
+ return __generator(this, function (_a) {
3698
+ switch (_a.label) {
3699
+ case 0:
3700
+ console.log(request);
3701
+ return [4 /*yield*/, this.sendJson("/identity", request)];
3702
+ case 1:
3703
+ result = _a.sent();
3704
+ return [2 /*return*/, result];
3705
+ }
3706
+ });
3707
+ });
3708
+ };
3709
+ AuthsignalClient.prototype.registerAnonymousId = function (request) {
3710
+ return __awaiter(this, void 0, void 0, function () {
3711
+ var result;
3712
+ return __generator(this, function (_a) {
3713
+ switch (_a.label) {
3714
+ case 0:
3715
+ console.log(request);
3716
+ return [4 /*yield*/, this.sendJson("/register", request)];
3717
+ case 1:
3718
+ result = _a.sent();
3719
+ return [2 /*return*/, result];
3720
+ }
3721
+ });
3722
+ });
3723
+ };
3724
+ AuthsignalClient.prototype.buildRegisterAnonymousIdRequest = function () {
3725
+ var now = new Date();
3726
+ return {
3727
+ deviceFingerprint: this.deviceFingerprint || "",
3728
+ anonymousId: this.anonymousId,
3729
+ sourceHost: this.cookieDomain,
3730
+ utcTime: reformatDate(now.toISOString()),
3731
+ clientData: {
3732
+ userAgent: navigator.userAgent || "",
3733
+ fonts: screen.width + "x" + screen.height,
3734
+ language: navigator.language,
3735
+ tzOffset: now.getTimezoneOffset(),
3736
+ screenResolution: screen.width + "x" + screen.height,
3737
+ viewPort: Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0) +
3738
+ "x" +
3739
+ Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0)
3740
+ }
3741
+ };
3742
+ };
3743
+ AuthsignalClient.prototype.sendJson = function (path, payload) {
3744
+ var jsonString = JSON.stringify(payload);
3745
+ var url = "".concat(this.trackingHost, "/api/v1/client/").concat(path, "?publishableKey=").concat(this.publishableKey);
3746
+ // Think about encapsulating the payloads around a message contract
3747
+ // SDK client versions, additional meta data
3748
+ return this.xmlHttpReqTransport(url, jsonString);
3749
+ };
3750
+ AuthsignalClient.prototype.xmlHttpReqTransport = function (url, json) {
3751
+ var req = new XMLHttpRequest();
3752
+ return new Promise(function (resolve, reject) {
3753
+ req.onerror = function () {
3754
+ reject(new Error("Failed to send JSON. See console logs"));
3755
+ };
3756
+ req.onload = function () {
3757
+ if (req.status !== 200) {
3758
+ reject(new Error("Failed to send JSON. Error code: ".concat(req.status, ". See logs for details")));
3759
+ }
3760
+ resolve();
3761
+ };
3762
+ req.open("POST", url);
3763
+ req.setRequestHeader("Content-Type", "application/json");
3764
+ req.send(json);
3765
+ });
3766
+ };
3767
+ return AuthsignalClient;
3768
+ }());
3769
+
3770
+ export { AuthsignalClient, authsignalClient };
3771
+ //# sourceMappingURL=index.js.map