posthog-js-lite 0.0.5 → 2.0.0-alpha1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +2 -24
  2. package/index.ts +5 -0
  3. package/lib/index.cjs.js +1473 -0
  4. package/lib/index.cjs.js.map +1 -0
  5. package/lib/index.d.ts +177 -0
  6. package/lib/index.esm.js +1468 -0
  7. package/lib/index.esm.js.map +1 -0
  8. package/lib/node_modules/tslib/tslib.es6.d.ts +35 -0
  9. package/lib/posthog-core/src/eventemitter.d.ts +8 -0
  10. package/lib/posthog-core/src/index.d.ts +84 -0
  11. package/lib/posthog-core/src/lz-string.d.ts +8 -0
  12. package/lib/posthog-core/src/types.d.ts +68 -0
  13. package/lib/posthog-core/src/utils.d.ts +13 -0
  14. package/lib/posthog-web/index.d.ts +3 -0
  15. package/lib/posthog-web/src/context.d.ts +1 -0
  16. package/lib/posthog-web/src/posthog-web.d.ts +18 -0
  17. package/lib/posthog-web/src/storage.d.ts +12 -0
  18. package/package.json +5 -42
  19. package/src/context.ts +168 -0
  20. package/src/posthog-web.ts +70 -0
  21. package/src/storage.ts +115 -0
  22. package/test/posthog-web.spec.ts +32 -0
  23. package/tsconfig.json +4 -17
  24. package/.prettierrc +0 -7
  25. package/babel.config.js +0 -4
  26. package/dist/babel.config.d.ts +0 -5
  27. package/dist/babel.config.js +0 -5
  28. package/dist/babel.config.js.map +0 -1
  29. package/dist/package.json +0 -44
  30. package/dist/src/__tests__/index.d.ts +0 -1
  31. package/dist/src/__tests__/index.js +0 -48
  32. package/dist/src/__tests__/index.js.map +0 -1
  33. package/dist/src/index.d.ts +0 -19
  34. package/dist/src/index.js +0 -109
  35. package/dist/src/index.js.map +0 -1
  36. package/dist/src/targets/browser.d.ts +0 -19
  37. package/dist/src/targets/browser.js +0 -10
  38. package/dist/src/targets/browser.js.map +0 -1
  39. package/dist/src/targets/node.d.ts +0 -19
  40. package/dist/src/targets/node.js +0 -9
  41. package/dist/src/targets/node.js.map +0 -1
  42. package/dist/src/types.d.ts +0 -20
  43. package/dist/src/types.js +0 -3
  44. package/dist/src/types.js.map +0 -1
  45. package/dist/src/utils/context.d.ts +0 -1
  46. package/dist/src/utils/context.js +0 -187
  47. package/dist/src/utils/context.js.map +0 -1
  48. package/dist/src/utils/lz-string.d.ts +0 -14
  49. package/dist/src/utils/lz-string.js +0 -467
  50. package/dist/src/utils/lz-string.js.map +0 -1
  51. package/dist/src/utils/utils.d.ts +0 -3
  52. package/dist/src/utils/utils.js +0 -29
  53. package/dist/src/utils/utils.js.map +0 -1
  54. package/dist/tsconfig.tsbuildinfo +0 -2454
  55. package/src/__tests__/index.js +0 -47
  56. package/src/index.ts +0 -127
  57. package/src/targets/browser.ts +0 -17
  58. package/src/targets/node.ts +0 -6
  59. package/src/types.ts +0 -22
  60. package/src/utils/context.ts +0 -163
  61. package/src/utils/lz-string.js +0 -511
  62. package/src/utils/utils.ts +0 -28
@@ -0,0 +1,1468 @@
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
+ /* global Reflect, Promise */
16
+ var extendStatics = function (d, b) {
17
+ extendStatics = Object.setPrototypeOf ||
18
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
19
+ function (d, b) { for (var p in b)
20
+ if (Object.prototype.hasOwnProperty.call(b, p))
21
+ d[p] = b[p]; };
22
+ return extendStatics(d, b);
23
+ };
24
+ function __extends(d, b) {
25
+ if (typeof b !== "function" && b !== null)
26
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
27
+ extendStatics(d, b);
28
+ function __() { this.constructor = d; }
29
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
30
+ }
31
+ var __assign = function () {
32
+ __assign = Object.assign || function __assign(t) {
33
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
34
+ s = arguments[i];
35
+ for (var p in s)
36
+ if (Object.prototype.hasOwnProperty.call(s, p))
37
+ t[p] = s[p];
38
+ }
39
+ return t;
40
+ };
41
+ return __assign.apply(this, arguments);
42
+ };
43
+ function __awaiter(thisArg, _arguments, P, generator) {
44
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
45
+ return new (P || (P = Promise))(function (resolve, reject) {
46
+ function fulfilled(value) { try {
47
+ step(generator.next(value));
48
+ }
49
+ catch (e) {
50
+ reject(e);
51
+ } }
52
+ function rejected(value) { try {
53
+ step(generator["throw"](value));
54
+ }
55
+ catch (e) {
56
+ reject(e);
57
+ } }
58
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
59
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
60
+ });
61
+ }
62
+ function __generator(thisArg, body) {
63
+ var _ = { label: 0, sent: function () { if (t[0] & 1)
64
+ throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
65
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { return this; }), g;
66
+ function verb(n) { return function (v) { return step([n, v]); }; }
67
+ function step(op) {
68
+ if (f)
69
+ throw new TypeError("Generator is already executing.");
70
+ while (_)
71
+ try {
72
+ 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)
73
+ return t;
74
+ if (y = 0, t)
75
+ op = [op[0] & 2, t.value];
76
+ switch (op[0]) {
77
+ case 0:
78
+ case 1:
79
+ t = op;
80
+ break;
81
+ case 4:
82
+ _.label++;
83
+ return { value: op[1], done: false };
84
+ case 5:
85
+ _.label++;
86
+ y = op[1];
87
+ op = [0];
88
+ continue;
89
+ case 7:
90
+ op = _.ops.pop();
91
+ _.trys.pop();
92
+ continue;
93
+ default:
94
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {
95
+ _ = 0;
96
+ continue;
97
+ }
98
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) {
99
+ _.label = op[1];
100
+ break;
101
+ }
102
+ if (op[0] === 6 && _.label < t[1]) {
103
+ _.label = t[1];
104
+ t = op;
105
+ break;
106
+ }
107
+ if (t && _.label < t[2]) {
108
+ _.label = t[2];
109
+ _.ops.push(op);
110
+ break;
111
+ }
112
+ if (t[2])
113
+ _.ops.pop();
114
+ _.trys.pop();
115
+ continue;
116
+ }
117
+ op = body.call(thisArg, _);
118
+ }
119
+ catch (e) {
120
+ op = [6, e];
121
+ y = 0;
122
+ }
123
+ finally {
124
+ f = t = 0;
125
+ }
126
+ if (op[0] & 5)
127
+ throw op[1];
128
+ return { value: op[0] ? op[1] : void 0, done: true };
129
+ }
130
+ }
131
+
132
+ var PostHogPersistedProperty;
133
+ (function (PostHogPersistedProperty) {
134
+ PostHogPersistedProperty["DistinctId"] = "distinct_id";
135
+ PostHogPersistedProperty["Props"] = "props";
136
+ PostHogPersistedProperty["FeatureFlags"] = "feature_flags";
137
+ PostHogPersistedProperty["OverrideFeatureFlags"] = "override_feature_flags";
138
+ PostHogPersistedProperty["Queue"] = "queue";
139
+ PostHogPersistedProperty["OptedOut"] = "opted_out";
140
+ PostHogPersistedProperty["SessionId"] = "session_id";
141
+ PostHogPersistedProperty["SessionLastTimestamp"] = "session_timestamp";
142
+ })(PostHogPersistedProperty || (PostHogPersistedProperty = {}));
143
+
144
+ function assert(truthyValue, message) {
145
+ if (!truthyValue) {
146
+ throw new Error(message);
147
+ }
148
+ }
149
+ function removeTrailingSlash(url) {
150
+ return url === null || url === void 0 ? void 0 : url.replace(/\/+$/, '');
151
+ }
152
+ function retriable(fn, props) {
153
+ if (props === void 0) { props = {}; }
154
+ return __awaiter(this, void 0, void 0, function () {
155
+ var _a, retryCount, _b, retryDelay, _c, retryCheck, lastError, i, res, e_1;
156
+ return __generator(this, function (_d) {
157
+ switch (_d.label) {
158
+ case 0:
159
+ _a = props.retryCount, retryCount = _a === void 0 ? 3 : _a, _b = props.retryDelay, retryDelay = _b === void 0 ? 1000 : _b, _c = props.retryCheck, retryCheck = _c === void 0 ? function () { return true; } : _c;
160
+ lastError = null;
161
+ i = 0;
162
+ _d.label = 1;
163
+ case 1:
164
+ if (!(i < retryCount + 1)) return [3 /*break*/, 8];
165
+ _d.label = 2;
166
+ case 2:
167
+ _d.trys.push([2, 4, , 5]);
168
+ return [4 /*yield*/, fn()];
169
+ case 3:
170
+ res = _d.sent();
171
+ return [2 /*return*/, res];
172
+ case 4:
173
+ e_1 = _d.sent();
174
+ lastError = e_1;
175
+ if (!retryCheck(e_1)) {
176
+ throw e_1;
177
+ }
178
+ return [3 /*break*/, 5];
179
+ case 5: return [4 /*yield*/, new Promise(function (r) { return setTimeout(r, retryDelay); })];
180
+ case 6:
181
+ _d.sent();
182
+ _d.label = 7;
183
+ case 7:
184
+ i++;
185
+ return [3 /*break*/, 1];
186
+ case 8: throw lastError;
187
+ }
188
+ });
189
+ });
190
+ }
191
+ // https://stackoverflow.com/a/8809472
192
+ function generateUUID(globalThis) {
193
+ // Public Domain/MIT
194
+ var d = new Date().getTime(); //Timestamp
195
+ var d2 = (globalThis && globalThis.performance && globalThis.performance.now && globalThis.performance.now() * 1000) || 0; //Time in microseconds since page-load or 0 if unsupported
196
+ return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
197
+ var r = Math.random() * 16; //random number between 0 and 16
198
+ if (d > 0) {
199
+ //Use timestamp until depleted
200
+ r = (d + r) % 16 | 0;
201
+ d = Math.floor(d / 16);
202
+ }
203
+ else {
204
+ //Use microseconds since page-load if supported
205
+ r = (d2 + r) % 16 | 0;
206
+ d2 = Math.floor(d2 / 16);
207
+ }
208
+ return (c === 'x' ? r : (r & 0x3) | 0x8).toString(16);
209
+ });
210
+ }
211
+ function currentTimestamp() {
212
+ return new Date().getTime();
213
+ }
214
+ function currentISOTime() {
215
+ return new Date().toISOString();
216
+ }
217
+ function safeSetTimeout(fn, timeout) {
218
+ // NOTE: we use this so rarely that it is totally fine to do `safeSetTimeout(fn, 0)``
219
+ // rather than setImmediate.
220
+ var t = setTimeout(fn, timeout);
221
+ // We unref if available to prevent Node.js hanging on exit
222
+ (t === null || t === void 0 ? void 0 : t.unref) && (t === null || t === void 0 ? void 0 : t.unref());
223
+ return t;
224
+ }
225
+
226
+ // Copyright (c) 2013 Pieroxy <pieroxy@pieroxy.net>
227
+ // This work is free. You can redistribute it and/or modify it
228
+ // under the terms of the WTFPL, Version 2
229
+ // For more information see LICENSE.txt or http://www.wtfpl.net/
230
+ //
231
+ // For more information, the home page:
232
+ // http://pieroxy.net/blog/pages/lz-string/testing.html
233
+ //
234
+ // LZ-based compression algorithm, version 1.4.4
235
+ // private property
236
+ var f = String.fromCharCode;
237
+ var keyStrBase64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
238
+ var baseReverseDic = {};
239
+ function getBaseValue(alphabet, character) {
240
+ if (!baseReverseDic[alphabet]) {
241
+ baseReverseDic[alphabet] = {};
242
+ for (var i = 0; i < alphabet.length; i++) {
243
+ baseReverseDic[alphabet][alphabet.charAt(i)] = i;
244
+ }
245
+ }
246
+ return baseReverseDic[alphabet][character];
247
+ }
248
+ var LZString = {
249
+ compressToBase64: function (input) {
250
+ if (input == null) {
251
+ return '';
252
+ }
253
+ var res = LZString._compress(input, 6, function (a) {
254
+ return keyStrBase64.charAt(a);
255
+ });
256
+ switch (res.length % 4 // To produce valid Base64
257
+ ) {
258
+ default: // When could this happen ?
259
+ case 0:
260
+ return res;
261
+ case 1:
262
+ return res + '===';
263
+ case 2:
264
+ return res + '==';
265
+ case 3:
266
+ return res + '=';
267
+ }
268
+ },
269
+ decompressFromBase64: function (input) {
270
+ if (input == null) {
271
+ return '';
272
+ }
273
+ if (input == '') {
274
+ return null;
275
+ }
276
+ return LZString._decompress(input.length, 32, function (index) {
277
+ return getBaseValue(keyStrBase64, input.charAt(index));
278
+ });
279
+ },
280
+ compress: function (uncompressed) {
281
+ return LZString._compress(uncompressed, 16, function (a) {
282
+ return f(a);
283
+ });
284
+ },
285
+ _compress: function (uncompressed, bitsPerChar, getCharFromInt) {
286
+ if (uncompressed == null) {
287
+ return '';
288
+ }
289
+ var context_dictionary = {}, context_dictionaryToCreate = {}, context_data = [];
290
+ var i, value, context_c = '', context_wc = '', context_w = '', context_enlargeIn = 2, // Compensate for the first entry which should not count
291
+ context_dictSize = 3, context_numBits = 2, context_data_val = 0, context_data_position = 0, ii;
292
+ for (ii = 0; ii < uncompressed.length; ii += 1) {
293
+ context_c = uncompressed.charAt(ii);
294
+ if (!Object.prototype.hasOwnProperty.call(context_dictionary, context_c)) {
295
+ context_dictionary[context_c] = context_dictSize++;
296
+ context_dictionaryToCreate[context_c] = true;
297
+ }
298
+ context_wc = context_w + context_c;
299
+ if (Object.prototype.hasOwnProperty.call(context_dictionary, context_wc)) {
300
+ context_w = context_wc;
301
+ }
302
+ else {
303
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
304
+ if (context_w.charCodeAt(0) < 256) {
305
+ for (i = 0; i < context_numBits; i++) {
306
+ context_data_val = context_data_val << 1;
307
+ if (context_data_position == bitsPerChar - 1) {
308
+ context_data_position = 0;
309
+ context_data.push(getCharFromInt(context_data_val));
310
+ context_data_val = 0;
311
+ }
312
+ else {
313
+ context_data_position++;
314
+ }
315
+ }
316
+ value = context_w.charCodeAt(0);
317
+ for (i = 0; i < 8; i++) {
318
+ context_data_val = (context_data_val << 1) | (value & 1);
319
+ if (context_data_position == bitsPerChar - 1) {
320
+ context_data_position = 0;
321
+ context_data.push(getCharFromInt(context_data_val));
322
+ context_data_val = 0;
323
+ }
324
+ else {
325
+ context_data_position++;
326
+ }
327
+ value = value >> 1;
328
+ }
329
+ }
330
+ else {
331
+ value = 1;
332
+ for (i = 0; i < context_numBits; i++) {
333
+ context_data_val = (context_data_val << 1) | value;
334
+ if (context_data_position == bitsPerChar - 1) {
335
+ context_data_position = 0;
336
+ context_data.push(getCharFromInt(context_data_val));
337
+ context_data_val = 0;
338
+ }
339
+ else {
340
+ context_data_position++;
341
+ }
342
+ value = 0;
343
+ }
344
+ value = context_w.charCodeAt(0);
345
+ for (i = 0; i < 16; i++) {
346
+ context_data_val = (context_data_val << 1) | (value & 1);
347
+ if (context_data_position == bitsPerChar - 1) {
348
+ context_data_position = 0;
349
+ context_data.push(getCharFromInt(context_data_val));
350
+ context_data_val = 0;
351
+ }
352
+ else {
353
+ context_data_position++;
354
+ }
355
+ value = value >> 1;
356
+ }
357
+ }
358
+ context_enlargeIn--;
359
+ if (context_enlargeIn == 0) {
360
+ context_enlargeIn = Math.pow(2, context_numBits);
361
+ context_numBits++;
362
+ }
363
+ delete context_dictionaryToCreate[context_w];
364
+ }
365
+ else {
366
+ value = context_dictionary[context_w];
367
+ for (i = 0; i < context_numBits; i++) {
368
+ context_data_val = (context_data_val << 1) | (value & 1);
369
+ if (context_data_position == bitsPerChar - 1) {
370
+ context_data_position = 0;
371
+ context_data.push(getCharFromInt(context_data_val));
372
+ context_data_val = 0;
373
+ }
374
+ else {
375
+ context_data_position++;
376
+ }
377
+ value = value >> 1;
378
+ }
379
+ }
380
+ context_enlargeIn--;
381
+ if (context_enlargeIn == 0) {
382
+ context_enlargeIn = Math.pow(2, context_numBits);
383
+ context_numBits++;
384
+ }
385
+ // Add wc to the dictionary.
386
+ context_dictionary[context_wc] = context_dictSize++;
387
+ context_w = String(context_c);
388
+ }
389
+ }
390
+ // Output the code for w.
391
+ if (context_w !== '') {
392
+ if (Object.prototype.hasOwnProperty.call(context_dictionaryToCreate, context_w)) {
393
+ if (context_w.charCodeAt(0) < 256) {
394
+ for (i = 0; i < context_numBits; i++) {
395
+ context_data_val = context_data_val << 1;
396
+ if (context_data_position == bitsPerChar - 1) {
397
+ context_data_position = 0;
398
+ context_data.push(getCharFromInt(context_data_val));
399
+ context_data_val = 0;
400
+ }
401
+ else {
402
+ context_data_position++;
403
+ }
404
+ }
405
+ value = context_w.charCodeAt(0);
406
+ for (i = 0; i < 8; i++) {
407
+ context_data_val = (context_data_val << 1) | (value & 1);
408
+ if (context_data_position == bitsPerChar - 1) {
409
+ context_data_position = 0;
410
+ context_data.push(getCharFromInt(context_data_val));
411
+ context_data_val = 0;
412
+ }
413
+ else {
414
+ context_data_position++;
415
+ }
416
+ value = value >> 1;
417
+ }
418
+ }
419
+ else {
420
+ value = 1;
421
+ for (i = 0; i < context_numBits; i++) {
422
+ context_data_val = (context_data_val << 1) | value;
423
+ if (context_data_position == bitsPerChar - 1) {
424
+ context_data_position = 0;
425
+ context_data.push(getCharFromInt(context_data_val));
426
+ context_data_val = 0;
427
+ }
428
+ else {
429
+ context_data_position++;
430
+ }
431
+ value = 0;
432
+ }
433
+ value = context_w.charCodeAt(0);
434
+ for (i = 0; i < 16; i++) {
435
+ context_data_val = (context_data_val << 1) | (value & 1);
436
+ if (context_data_position == bitsPerChar - 1) {
437
+ context_data_position = 0;
438
+ context_data.push(getCharFromInt(context_data_val));
439
+ context_data_val = 0;
440
+ }
441
+ else {
442
+ context_data_position++;
443
+ }
444
+ value = value >> 1;
445
+ }
446
+ }
447
+ context_enlargeIn--;
448
+ if (context_enlargeIn == 0) {
449
+ context_enlargeIn = Math.pow(2, context_numBits);
450
+ context_numBits++;
451
+ }
452
+ delete context_dictionaryToCreate[context_w];
453
+ }
454
+ else {
455
+ value = context_dictionary[context_w];
456
+ for (i = 0; i < context_numBits; i++) {
457
+ context_data_val = (context_data_val << 1) | (value & 1);
458
+ if (context_data_position == bitsPerChar - 1) {
459
+ context_data_position = 0;
460
+ context_data.push(getCharFromInt(context_data_val));
461
+ context_data_val = 0;
462
+ }
463
+ else {
464
+ context_data_position++;
465
+ }
466
+ value = value >> 1;
467
+ }
468
+ }
469
+ context_enlargeIn--;
470
+ if (context_enlargeIn == 0) {
471
+ context_enlargeIn = Math.pow(2, context_numBits);
472
+ context_numBits++;
473
+ }
474
+ }
475
+ // Mark the end of the stream
476
+ value = 2;
477
+ for (i = 0; i < context_numBits; i++) {
478
+ context_data_val = (context_data_val << 1) | (value & 1);
479
+ if (context_data_position == bitsPerChar - 1) {
480
+ context_data_position = 0;
481
+ context_data.push(getCharFromInt(context_data_val));
482
+ context_data_val = 0;
483
+ }
484
+ else {
485
+ context_data_position++;
486
+ }
487
+ value = value >> 1;
488
+ }
489
+ // Flush the last char
490
+ while (true) {
491
+ context_data_val = context_data_val << 1;
492
+ if (context_data_position == bitsPerChar - 1) {
493
+ context_data.push(getCharFromInt(context_data_val));
494
+ break;
495
+ }
496
+ else {
497
+ context_data_position++;
498
+ }
499
+ }
500
+ return context_data.join('');
501
+ },
502
+ decompress: function (compressed) {
503
+ if (compressed == null) {
504
+ return '';
505
+ }
506
+ if (compressed == '') {
507
+ return null;
508
+ }
509
+ return LZString._decompress(compressed.length, 32768, function (index) {
510
+ return compressed.charCodeAt(index);
511
+ });
512
+ },
513
+ _decompress: function (length, resetValue, getNextValue) {
514
+ var dictionary = [], result = [], data = { val: getNextValue(0), position: resetValue, index: 1 };
515
+ var enlargeIn = 4, dictSize = 4, numBits = 3, entry = '', i, w, bits, resb, maxpower, power, c;
516
+ for (i = 0; i < 3; i += 1) {
517
+ dictionary[i] = i;
518
+ }
519
+ bits = 0;
520
+ maxpower = Math.pow(2, 2);
521
+ power = 1;
522
+ while (power != maxpower) {
523
+ resb = data.val & data.position;
524
+ data.position >>= 1;
525
+ if (data.position == 0) {
526
+ data.position = resetValue;
527
+ data.val = getNextValue(data.index++);
528
+ }
529
+ bits |= (resb > 0 ? 1 : 0) * power;
530
+ power <<= 1;
531
+ }
532
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
533
+ switch ((bits)) {
534
+ case 0:
535
+ bits = 0;
536
+ maxpower = Math.pow(2, 8);
537
+ power = 1;
538
+ while (power != maxpower) {
539
+ resb = data.val & data.position;
540
+ data.position >>= 1;
541
+ if (data.position == 0) {
542
+ data.position = resetValue;
543
+ data.val = getNextValue(data.index++);
544
+ }
545
+ bits |= (resb > 0 ? 1 : 0) * power;
546
+ power <<= 1;
547
+ }
548
+ c = f(bits);
549
+ break;
550
+ case 1:
551
+ bits = 0;
552
+ maxpower = Math.pow(2, 16);
553
+ power = 1;
554
+ while (power != maxpower) {
555
+ resb = data.val & data.position;
556
+ data.position >>= 1;
557
+ if (data.position == 0) {
558
+ data.position = resetValue;
559
+ data.val = getNextValue(data.index++);
560
+ }
561
+ bits |= (resb > 0 ? 1 : 0) * power;
562
+ power <<= 1;
563
+ }
564
+ c = f(bits);
565
+ break;
566
+ case 2:
567
+ return '';
568
+ }
569
+ dictionary[3] = c;
570
+ w = c;
571
+ result.push(c);
572
+ while (true) {
573
+ if (data.index > length) {
574
+ return '';
575
+ }
576
+ bits = 0;
577
+ maxpower = Math.pow(2, numBits);
578
+ power = 1;
579
+ while (power != maxpower) {
580
+ resb = data.val & data.position;
581
+ data.position >>= 1;
582
+ if (data.position == 0) {
583
+ data.position = resetValue;
584
+ data.val = getNextValue(data.index++);
585
+ }
586
+ bits |= (resb > 0 ? 1 : 0) * power;
587
+ power <<= 1;
588
+ }
589
+ switch ((c = bits)) {
590
+ case 0:
591
+ bits = 0;
592
+ maxpower = Math.pow(2, 8);
593
+ power = 1;
594
+ while (power != maxpower) {
595
+ resb = data.val & data.position;
596
+ data.position >>= 1;
597
+ if (data.position == 0) {
598
+ data.position = resetValue;
599
+ data.val = getNextValue(data.index++);
600
+ }
601
+ bits |= (resb > 0 ? 1 : 0) * power;
602
+ power <<= 1;
603
+ }
604
+ dictionary[dictSize++] = f(bits);
605
+ c = dictSize - 1;
606
+ enlargeIn--;
607
+ break;
608
+ case 1:
609
+ bits = 0;
610
+ maxpower = Math.pow(2, 16);
611
+ power = 1;
612
+ while (power != maxpower) {
613
+ resb = data.val & data.position;
614
+ data.position >>= 1;
615
+ if (data.position == 0) {
616
+ data.position = resetValue;
617
+ data.val = getNextValue(data.index++);
618
+ }
619
+ bits |= (resb > 0 ? 1 : 0) * power;
620
+ power <<= 1;
621
+ }
622
+ dictionary[dictSize++] = f(bits);
623
+ c = dictSize - 1;
624
+ enlargeIn--;
625
+ break;
626
+ case 2:
627
+ return result.join('');
628
+ }
629
+ if (enlargeIn == 0) {
630
+ enlargeIn = Math.pow(2, numBits);
631
+ numBits++;
632
+ }
633
+ if (dictionary[c]) {
634
+ entry = dictionary[c];
635
+ }
636
+ else {
637
+ if (c === dictSize) {
638
+ entry = w + w.charAt(0);
639
+ }
640
+ else {
641
+ return null;
642
+ }
643
+ }
644
+ result.push(entry);
645
+ // Add w+entry[0] to the dictionary.
646
+ dictionary[dictSize++] = w + entry.charAt(0);
647
+ enlargeIn--;
648
+ w = entry;
649
+ if (enlargeIn == 0) {
650
+ enlargeIn = Math.pow(2, numBits);
651
+ numBits++;
652
+ }
653
+ }
654
+ },
655
+ };
656
+
657
+ var SimpleEventEmitter = /** @class */ (function () {
658
+ function SimpleEventEmitter() {
659
+ this.events = {};
660
+ this.events = {};
661
+ }
662
+ SimpleEventEmitter.prototype.on = function (event, listener) {
663
+ var _this = this;
664
+ if (!this.events[event]) {
665
+ this.events[event] = [];
666
+ }
667
+ this.events[event].push(listener);
668
+ return function () {
669
+ _this.events[event] = _this.events[event].filter(function (x) { return x !== listener; });
670
+ };
671
+ };
672
+ SimpleEventEmitter.prototype.emit = function (event, payload) {
673
+ if (!this.events[event]) {
674
+ return;
675
+ }
676
+ for (var _i = 0, _a = this.events[event]; _i < _a.length; _i++) {
677
+ var listener = _a[_i];
678
+ listener(payload);
679
+ }
680
+ };
681
+ return SimpleEventEmitter;
682
+ }());
683
+
684
+ var PostHogCore = /** @class */ (function () {
685
+ function PostHogCore(apiKey, options) {
686
+ var _this = this;
687
+ var _a, _b, _c, _d, _e, _f;
688
+ this.flagCallReported = {};
689
+ // internal
690
+ this._events = new SimpleEventEmitter();
691
+ assert(apiKey, "You must pass your PostHog project's api key.");
692
+ this.apiKey = apiKey;
693
+ this.host = removeTrailingSlash((options === null || options === void 0 ? void 0 : options.host) || 'https://app.posthog.com');
694
+ this.flushAt = (options === null || options === void 0 ? void 0 : options.flushAt) ? Math.max(options === null || options === void 0 ? void 0 : options.flushAt, 1) : 20;
695
+ this.flushInterval = (_a = options === null || options === void 0 ? void 0 : options.flushInterval) !== null && _a !== void 0 ? _a : 10000;
696
+ this.captureMode = (options === null || options === void 0 ? void 0 : options.captureMode) || 'form';
697
+ this.sendFeatureFlagEvent = (_b = options === null || options === void 0 ? void 0 : options.sendFeatureFlagEvent) !== null && _b !== void 0 ? _b : true;
698
+ this._decidePollInterval = Math.max(0, (_c = options === null || options === void 0 ? void 0 : options.decidePollInterval) !== null && _c !== void 0 ? _c : 30000);
699
+ // If enable is explicitly set to false we override the optout
700
+ this._optoutOverride = (options === null || options === void 0 ? void 0 : options.enable) === false;
701
+ this._retryOptions = {
702
+ retryCount: (_d = options === null || options === void 0 ? void 0 : options.fetchRetryCount) !== null && _d !== void 0 ? _d : 3,
703
+ retryDelay: (_e = options === null || options === void 0 ? void 0 : options.fetchRetryDelay) !== null && _e !== void 0 ? _e : 3000,
704
+ };
705
+ this._sessionExpirationTimeSeconds = (_f = options === null || options === void 0 ? void 0 : options.sessionExpirationTimeSeconds) !== null && _f !== void 0 ? _f : 1800; // 30 minutes
706
+ // NOTE: It is important we don't initiate anything in the constructor as some async IO may still be underway on the parent
707
+ if ((options === null || options === void 0 ? void 0 : options.preloadFeatureFlags) !== false) {
708
+ safeSetTimeout(function () {
709
+ void _this.reloadFeatureFlagsAsync();
710
+ }, 1);
711
+ }
712
+ }
713
+ PostHogCore.prototype.getCommonEventProperties = function () {
714
+ var featureFlags = this.getFeatureFlags();
715
+ return {
716
+ $lib: this.getLibraryId(),
717
+ $lib_version: this.getLibraryVersion(),
718
+ $active_feature_flags: featureFlags ? Object.keys(featureFlags) : undefined,
719
+ $enabled_feature_flags: featureFlags,
720
+ };
721
+ };
722
+ Object.defineProperty(PostHogCore.prototype, "props", {
723
+ // NOTE: Props are lazy loaded from localstorage hence the complex getter setter logic
724
+ get: function () {
725
+ if (!this._props) {
726
+ this._props = this.getPersistedProperty(PostHogPersistedProperty.Props);
727
+ }
728
+ return this._props || {};
729
+ },
730
+ set: function (val) {
731
+ this._props = val;
732
+ },
733
+ enumerable: false,
734
+ configurable: true
735
+ });
736
+ Object.defineProperty(PostHogCore.prototype, "optedOut", {
737
+ get: function () {
738
+ var _a, _b;
739
+ return (_b = (_a = this.getPersistedProperty(PostHogPersistedProperty.OptedOut)) !== null && _a !== void 0 ? _a : this._optoutOverride) !== null && _b !== void 0 ? _b : false;
740
+ },
741
+ enumerable: false,
742
+ configurable: true
743
+ });
744
+ PostHogCore.prototype.optIn = function () {
745
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, false);
746
+ };
747
+ PostHogCore.prototype.optOut = function () {
748
+ this.setPersistedProperty(PostHogPersistedProperty.OptedOut, true);
749
+ };
750
+ PostHogCore.prototype.on = function (event, cb) {
751
+ return this._events.on(event, cb);
752
+ };
753
+ PostHogCore.prototype.reset = function () {
754
+ for (var key in PostHogPersistedProperty) {
755
+ this.setPersistedProperty(PostHogPersistedProperty[key], null);
756
+ }
757
+ this.setPersistedProperty(PostHogPersistedProperty.DistinctId, generateUUID(globalThis));
758
+ };
759
+ PostHogCore.prototype.buildPayload = function (payload) {
760
+ return {
761
+ distinct_id: payload.distinct_id || this.getDistinctId(),
762
+ event: payload.event,
763
+ properties: __assign(__assign(__assign(__assign({}, this.props), (payload.properties || {})), this.getCommonEventProperties()), { $session_id: this.getSessionId() }),
764
+ };
765
+ };
766
+ PostHogCore.prototype.getSessionId = function () {
767
+ var sessionId = this.getPersistedProperty(PostHogPersistedProperty.SessionId);
768
+ var sessionTimestamp = this.getPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp) || 0;
769
+ if (!sessionId || Date.now() - sessionTimestamp > this._sessionExpirationTimeSeconds * 1000) {
770
+ sessionId = generateUUID(globalThis);
771
+ this.setPersistedProperty(PostHogPersistedProperty.SessionId, sessionId);
772
+ }
773
+ this.setPersistedProperty(PostHogPersistedProperty.SessionLastTimestamp, Date.now());
774
+ return sessionId;
775
+ };
776
+ PostHogCore.prototype.getDistinctId = function () {
777
+ var distinctId = this.getPersistedProperty(PostHogPersistedProperty.DistinctId);
778
+ if (!distinctId) {
779
+ distinctId = generateUUID(globalThis);
780
+ this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);
781
+ }
782
+ return distinctId;
783
+ };
784
+ PostHogCore.prototype.register = function (properties) {
785
+ this.props = __assign(__assign({}, this.props), properties);
786
+ this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
787
+ };
788
+ PostHogCore.prototype.unregister = function (property) {
789
+ delete this.props[property];
790
+ this.setPersistedProperty(PostHogPersistedProperty.Props, this.props);
791
+ };
792
+ /***
793
+ *** TRACKING
794
+ ***/
795
+ PostHogCore.prototype.identify = function (distinctId, properties) {
796
+ distinctId = distinctId || this.getDistinctId();
797
+ if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
798
+ this.groups(properties.$groups);
799
+ }
800
+ var payload = __assign(__assign({}, this.buildPayload({
801
+ distinct_id: distinctId,
802
+ event: '$identify',
803
+ properties: __assign(__assign({}, (properties || {})), { $anon_distinct_id: this.getDistinctId() }),
804
+ })), { $set: properties });
805
+ if (distinctId !== this.getDistinctId()) {
806
+ this.setPersistedProperty(PostHogPersistedProperty.DistinctId, distinctId);
807
+ }
808
+ this.enqueue('identify', payload);
809
+ return this;
810
+ };
811
+ PostHogCore.prototype.capture = function (event, properties) {
812
+ // NOTE: Legacy nodejs implementation uses groups
813
+ if (properties && properties['groups']) {
814
+ properties.$groups = properties.groups;
815
+ delete properties.groups;
816
+ }
817
+ if (properties === null || properties === void 0 ? void 0 : properties.$groups) {
818
+ this.groups(properties.$groups);
819
+ }
820
+ var payload = this.buildPayload({ event: event, properties: properties });
821
+ this.enqueue('capture', payload);
822
+ return this;
823
+ };
824
+ PostHogCore.prototype.alias = function (alias) {
825
+ var distinctId = this.getDistinctId();
826
+ var payload = this.buildPayload({
827
+ event: '$create_alias',
828
+ properties: {
829
+ distinct_id: distinctId,
830
+ alias: alias,
831
+ },
832
+ });
833
+ this.enqueue('alias', payload);
834
+ return this;
835
+ };
836
+ PostHogCore.prototype.autocapture = function (eventType, elements, properties) {
837
+ if (properties === void 0) { properties = {}; }
838
+ var payload = this.buildPayload({
839
+ event: '$autocapture',
840
+ properties: __assign(__assign({}, properties), { $event_type: eventType, $elements: elements }),
841
+ });
842
+ this.enqueue('autocapture', payload);
843
+ return this;
844
+ };
845
+ /***
846
+ *** GROUPS
847
+ ***/
848
+ PostHogCore.prototype.groups = function (groups) {
849
+ // Get persisted groups
850
+ var existingGroups = this.props.$groups || {};
851
+ // NOTE: Should we do the same for groups listed in identify / capture?
852
+ this.register({
853
+ $groups: __assign(__assign({}, existingGroups), groups),
854
+ });
855
+ if (Object.keys(groups).find(function (type) { return existingGroups[type] !== groups[type]; }) && this._decideResponsePromise) {
856
+ void this.reloadFeatureFlagsAsync();
857
+ }
858
+ return this;
859
+ };
860
+ PostHogCore.prototype.group = function (groupType, groupKey, groupProperties) {
861
+ var _a;
862
+ this.groups((_a = {},
863
+ _a[groupType] = groupKey,
864
+ _a));
865
+ if (groupProperties) {
866
+ this.groupIdentify(groupType, groupKey, groupProperties);
867
+ }
868
+ return this;
869
+ };
870
+ PostHogCore.prototype.groupIdentify = function (groupType, groupKey, groupProperties) {
871
+ var payload = {
872
+ event: '$groupidentify',
873
+ distinctId: "$".concat(groupType, "_").concat(groupKey),
874
+ properties: __assign({ $group_type: groupType, $group_key: groupKey, $group_set: groupProperties || {} }, this.getCommonEventProperties()),
875
+ };
876
+ this.enqueue('capture', payload);
877
+ return this;
878
+ };
879
+ /***
880
+ *** FEATURE FLAGS
881
+ ***/
882
+ PostHogCore.prototype.decideAsync = function () {
883
+ if (this._decideResponsePromise) {
884
+ return this._decideResponsePromise;
885
+ }
886
+ return this._decideAsync();
887
+ };
888
+ PostHogCore.prototype._decideAsync = function () {
889
+ return __awaiter(this, void 0, void 0, function () {
890
+ var url, distinctId, groups, fetchOptions;
891
+ var _this = this;
892
+ return __generator(this, function (_a) {
893
+ url = "".concat(this.host, "/decide/?v=2");
894
+ distinctId = this.getDistinctId();
895
+ groups = this.props.$groups || {};
896
+ fetchOptions = {
897
+ method: 'POST',
898
+ headers: { 'Content-Type': 'application/json' },
899
+ body: JSON.stringify({ groups: groups, distinct_id: distinctId, token: this.apiKey }),
900
+ };
901
+ this._decideResponsePromise = this.fetchWithRetry(url, fetchOptions)
902
+ .then(function (r) { return r.json(); })
903
+ .then(function (res) {
904
+ if (res.featureFlags) {
905
+ _this.setPersistedProperty(PostHogPersistedProperty.FeatureFlags, res.featureFlags);
906
+ }
907
+ _this._events.emit('featureflags', res.featureFlags);
908
+ return res;
909
+ });
910
+ return [2 /*return*/, this._decideResponsePromise];
911
+ });
912
+ });
913
+ };
914
+ PostHogCore.prototype.getFeatureFlag = function (key, defaultResult) {
915
+ var _a;
916
+ if (defaultResult === void 0) { defaultResult = false; }
917
+ var featureFlags = this.getFeatureFlags();
918
+ if (!featureFlags) {
919
+ // If we haven't loaded flags yet we respond undefined to indicate this
920
+ return undefined;
921
+ }
922
+ if (this.sendFeatureFlagEvent && !this.flagCallReported[key]) {
923
+ this.flagCallReported[key] = true;
924
+ this.capture('$feature_flag_called', {
925
+ $feature_flag: key,
926
+ $feature_flag_response: featureFlags[key],
927
+ });
928
+ }
929
+ // If we have flags we either return the value (true or string) or the defaultResult
930
+ return (_a = featureFlags[key]) !== null && _a !== void 0 ? _a : defaultResult;
931
+ };
932
+ PostHogCore.prototype.getFeatureFlags = function () {
933
+ var flags = this.getPersistedProperty(PostHogPersistedProperty.FeatureFlags);
934
+ var overriddenFlags = this.getPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags);
935
+ if (!overriddenFlags) {
936
+ return flags;
937
+ }
938
+ flags = flags || {};
939
+ for (var key in overriddenFlags) {
940
+ if (!overriddenFlags[key]) {
941
+ delete flags[key];
942
+ }
943
+ else {
944
+ flags[key] = overriddenFlags[key];
945
+ }
946
+ }
947
+ return flags;
948
+ };
949
+ PostHogCore.prototype.isFeatureEnabled = function (key, defaultResult) {
950
+ var _a;
951
+ if (defaultResult === void 0) { defaultResult = false; }
952
+ var flag = (_a = this.getFeatureFlag(key, defaultResult)) !== null && _a !== void 0 ? _a : defaultResult;
953
+ return !!flag;
954
+ };
955
+ PostHogCore.prototype.reloadFeatureFlagsAsync = function () {
956
+ return __awaiter(this, void 0, void 0, function () {
957
+ var _this = this;
958
+ return __generator(this, function (_a) {
959
+ switch (_a.label) {
960
+ case 0:
961
+ clearTimeout(this._decideTimer);
962
+ if (this._decidePollInterval) {
963
+ this._decideTimer = safeSetTimeout(function () { return _this.reloadFeatureFlagsAsync(); }, this._decidePollInterval);
964
+ }
965
+ this._decideResponsePromise = undefined;
966
+ return [4 /*yield*/, this.decideAsync()];
967
+ case 1: return [2 /*return*/, (_a.sent()).featureFlags];
968
+ }
969
+ });
970
+ });
971
+ };
972
+ // When listening to feature flags polling is active
973
+ PostHogCore.prototype.onFeatureFlags = function (cb) {
974
+ var _this = this;
975
+ if (!this._decideTimer) {
976
+ void this.reloadFeatureFlagsAsync();
977
+ }
978
+ return this.on('featureflags', function () { return __awaiter(_this, void 0, void 0, function () {
979
+ var flags;
980
+ return __generator(this, function (_a) {
981
+ flags = this.getFeatureFlags();
982
+ if (flags) {
983
+ cb(flags);
984
+ }
985
+ return [2 /*return*/];
986
+ });
987
+ }); });
988
+ };
989
+ PostHogCore.prototype.overrideFeatureFlag = function (flags) {
990
+ if (flags === null) {
991
+ return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, null);
992
+ }
993
+ return this.setPersistedProperty(PostHogPersistedProperty.OverrideFeatureFlags, flags);
994
+ };
995
+ /***
996
+ *** QUEUEING AND FLUSHING
997
+ ***/
998
+ PostHogCore.prototype.enqueue = function (type, _message) {
999
+ var _this = this;
1000
+ if (this.optedOut) {
1001
+ return;
1002
+ }
1003
+ var message = __assign(__assign({}, _message), { type: type, library: this.getLibraryId(), library_version: this.getLibraryVersion(), timestamp: _message.timestamp ? _message.timestamp : currentISOTime() });
1004
+ if (message.distinctId) {
1005
+ message.distinct_id = message.distinctId;
1006
+ delete message.distinctId;
1007
+ }
1008
+ var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1009
+ queue.push({ message: message });
1010
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1011
+ this._events.emit(type, message);
1012
+ // Flush queued events if we meet the flushAt length
1013
+ if (queue.length >= this.flushAt) {
1014
+ this.flush();
1015
+ }
1016
+ if (this.flushInterval && !this._flushTimer) {
1017
+ this._flushTimer = safeSetTimeout(function () { return _this.flush(); }, this.flushInterval);
1018
+ }
1019
+ };
1020
+ PostHogCore.prototype.flushAsync = function () {
1021
+ var _this = this;
1022
+ return new Promise(function (resolve, reject) {
1023
+ _this.flush(function (err, data) { return (err ? reject(err) : resolve(data)); });
1024
+ });
1025
+ };
1026
+ PostHogCore.prototype.flush = function (callback) {
1027
+ var _this = this;
1028
+ if (this.optedOut) {
1029
+ return callback && safeSetTimeout(callback, 0);
1030
+ }
1031
+ if (this._flushTimer) {
1032
+ clearTimeout(this._flushTimer);
1033
+ this._flushTimer = null;
1034
+ }
1035
+ var queue = this.getPersistedProperty(PostHogPersistedProperty.Queue) || [];
1036
+ if (!queue.length) {
1037
+ return callback && safeSetTimeout(callback, 0);
1038
+ }
1039
+ var items = queue.splice(0, this.flushAt);
1040
+ this.setPersistedProperty(PostHogPersistedProperty.Queue, queue);
1041
+ var messages = items.map(function (item) { return item.message; });
1042
+ var data = {
1043
+ api_key: this.apiKey,
1044
+ batch: messages,
1045
+ sent_at: currentISOTime(),
1046
+ };
1047
+ var done = function (err) {
1048
+ callback === null || callback === void 0 ? void 0 : callback(err, messages);
1049
+ _this._events.emit('flush', messages);
1050
+ };
1051
+ // Don't set the user agent if we're not on a browser. The latest spec allows
1052
+ // the User-Agent header (see https://fetch.spec.whatwg.org/#terminology-headers
1053
+ // and https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader),
1054
+ // but browsers such as Chrome and Safari have not caught up.
1055
+ this.getCustomUserAgent();
1056
+ var payload = JSON.stringify(data);
1057
+ var url = this.captureMode === 'form'
1058
+ ? "".concat(this.host, "/e/?ip=1&_=").concat(currentTimestamp(), "&v=").concat(this.getLibraryVersion())
1059
+ : "".concat(this.host, "/batch/");
1060
+ var fetchOptions = this.captureMode === 'form'
1061
+ ? {
1062
+ method: 'POST',
1063
+ mode: 'no-cors',
1064
+ credentials: 'omit',
1065
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
1066
+ body: "data=".concat(encodeURIComponent(LZString.compressToBase64(payload)), "&compression=lz64"),
1067
+ }
1068
+ : {
1069
+ method: 'POST',
1070
+ headers: { 'Content-Type': 'application/json' },
1071
+ body: payload,
1072
+ };
1073
+ this.fetchWithRetry(url, fetchOptions)
1074
+ .then(function () { return done(); })
1075
+ .catch(function (err) {
1076
+ if (err.response) {
1077
+ var error = new Error(err.response.statusText);
1078
+ return done(error);
1079
+ }
1080
+ done(err);
1081
+ });
1082
+ };
1083
+ PostHogCore.prototype.fetchWithRetry = function (url, options, retryOptions) {
1084
+ return __awaiter(this, void 0, void 0, function () {
1085
+ var _this = this;
1086
+ return __generator(this, function (_a) {
1087
+ return [2 /*return*/, retriable(function () { return _this.fetch(url, options); }, retryOptions || this._retryOptions)];
1088
+ });
1089
+ });
1090
+ };
1091
+ PostHogCore.prototype.shutdownAsync = function () {
1092
+ return __awaiter(this, void 0, void 0, function () {
1093
+ return __generator(this, function (_a) {
1094
+ switch (_a.label) {
1095
+ case 0:
1096
+ clearTimeout(this._decideTimer);
1097
+ clearTimeout(this._flushTimer);
1098
+ return [4 /*yield*/, this.flushAsync()];
1099
+ case 1:
1100
+ _a.sent();
1101
+ return [2 /*return*/];
1102
+ }
1103
+ });
1104
+ });
1105
+ };
1106
+ PostHogCore.prototype.shutdown = function () {
1107
+ void this.shutdownAsync();
1108
+ };
1109
+ return PostHogCore;
1110
+ }());
1111
+
1112
+ // TODO: Get this from package.json
1113
+
1114
+ var version$1 = '2.0.0-alpha';
1115
+ function getContext(window) {
1116
+ var context = {};
1117
+
1118
+ if (window.navigator) {
1119
+ var userAgent = window.navigator.userAgent;
1120
+ context = __assign(__assign({}, context), {
1121
+ $os: os(window),
1122
+ $browser: browser(userAgent, window.navigator.vendor, !!window.opera),
1123
+ $referrer: window.document.referrer,
1124
+ $referring_domain: referringDomain(window.document.referrer),
1125
+ $device: device(userAgent),
1126
+ $current_url: window.location.href,
1127
+ $host: window.location.host,
1128
+ $pathname: window.location.pathname,
1129
+ $browser_version: browserVersion(userAgent, window.navigator.vendor, !!window.opera),
1130
+ $screen_height: window.screen.height,
1131
+ $screen_width: window.screen.width,
1132
+ $screen_dpr: window.devicePixelRatio
1133
+ });
1134
+ }
1135
+
1136
+ context = __assign(__assign({}, context), {
1137
+ $lib: 'js',
1138
+ $lib_version: version$1,
1139
+ $insert_id: Math.random().toString(36).substring(2, 10) + Math.random().toString(36).substring(2, 10),
1140
+ $time: currentTimestamp() / 1000
1141
+ });
1142
+ return context; // TODO: strip empty props?
1143
+ }
1144
+
1145
+ function includes(haystack, needle) {
1146
+ return haystack.indexOf(needle) >= 0;
1147
+ }
1148
+
1149
+ function browser(userAgent, vendor, opera) {
1150
+ vendor = vendor || ''; // vendor is undefined for at least IE9
1151
+
1152
+ if (opera || includes(userAgent, ' OPR/')) {
1153
+ if (includes(userAgent, 'Mini')) {
1154
+ return 'Opera Mini';
1155
+ }
1156
+
1157
+ return 'Opera';
1158
+ } else if (/(BlackBerry|PlayBook|BB10)/i.test(userAgent)) {
1159
+ return 'BlackBerry';
1160
+ } else if (includes(userAgent, 'IEMobile') || includes(userAgent, 'WPDesktop')) {
1161
+ return 'Internet Explorer Mobile';
1162
+ } else if (includes(userAgent, 'SamsungBrowser/')) {
1163
+ // https://developer.samsung.com/internet/user-agent-string-format
1164
+ return 'Samsung Internet';
1165
+ } else if (includes(userAgent, 'Edge') || includes(userAgent, 'Edg/')) {
1166
+ return 'Microsoft Edge';
1167
+ } else if (includes(userAgent, 'FBIOS')) {
1168
+ return 'Facebook Mobile';
1169
+ } else if (includes(userAgent, 'Chrome')) {
1170
+ return 'Chrome';
1171
+ } else if (includes(userAgent, 'CriOS')) {
1172
+ return 'Chrome iOS';
1173
+ } else if (includes(userAgent, 'UCWEB') || includes(userAgent, 'UCBrowser')) {
1174
+ return 'UC Browser';
1175
+ } else if (includes(userAgent, 'FxiOS')) {
1176
+ return 'Firefox iOS';
1177
+ } else if (includes(vendor, 'Apple')) {
1178
+ if (includes(userAgent, 'Mobile')) {
1179
+ return 'Mobile Safari';
1180
+ }
1181
+
1182
+ return 'Safari';
1183
+ } else if (includes(userAgent, 'Android')) {
1184
+ return 'Android Mobile';
1185
+ } else if (includes(userAgent, 'Konqueror')) {
1186
+ return 'Konqueror';
1187
+ } else if (includes(userAgent, 'Firefox')) {
1188
+ return 'Firefox';
1189
+ } else if (includes(userAgent, 'MSIE') || includes(userAgent, 'Trident/')) {
1190
+ return 'Internet Explorer';
1191
+ } else if (includes(userAgent, 'Gecko')) {
1192
+ return 'Mozilla';
1193
+ } else {
1194
+ return '';
1195
+ }
1196
+ }
1197
+
1198
+ function browserVersion(userAgent, vendor, opera) {
1199
+ var regexList = {
1200
+ 'Internet Explorer Mobile': /rv:(\d+(\.\d+)?)/,
1201
+ 'Microsoft Edge': /Edge?\/(\d+(\.\d+)?)/,
1202
+ Chrome: /Chrome\/(\d+(\.\d+)?)/,
1203
+ 'Chrome iOS': /CriOS\/(\d+(\.\d+)?)/,
1204
+ 'UC Browser': /(UCBrowser|UCWEB)\/(\d+(\.\d+)?)/,
1205
+ Safari: /Version\/(\d+(\.\d+)?)/,
1206
+ 'Mobile Safari': /Version\/(\d+(\.\d+)?)/,
1207
+ Opera: /(Opera|OPR)\/(\d+(\.\d+)?)/,
1208
+ Firefox: /Firefox\/(\d+(\.\d+)?)/,
1209
+ 'Firefox iOS': /FxiOS\/(\d+(\.\d+)?)/,
1210
+ Konqueror: /Konqueror:(\d+(\.\d+)?)/,
1211
+ BlackBerry: /BlackBerry (\d+(\.\d+)?)/,
1212
+ 'Android Mobile': /android\s(\d+(\.\d+)?)/,
1213
+ 'Samsung Internet': /SamsungBrowser\/(\d+(\.\d+)?)/,
1214
+ 'Internet Explorer': /(rv:|MSIE )(\d+(\.\d+)?)/,
1215
+ Mozilla: /rv:(\d+(\.\d+)?)/
1216
+ };
1217
+ var browserString = browser(userAgent, vendor, opera);
1218
+ var regex = regexList[browserString] || undefined;
1219
+
1220
+ if (regex === undefined) {
1221
+ return null;
1222
+ }
1223
+
1224
+ var matches = userAgent.match(regex);
1225
+
1226
+ if (!matches) {
1227
+ return null;
1228
+ }
1229
+
1230
+ return parseFloat(matches[matches.length - 2]);
1231
+ }
1232
+
1233
+ function os(window) {
1234
+ var a = window.navigator.userAgent;
1235
+
1236
+ if (/Windows/i.test(a)) {
1237
+ if (/Phone/.test(a) || /WPDesktop/.test(a)) {
1238
+ return 'Windows Phone';
1239
+ }
1240
+
1241
+ return 'Windows';
1242
+ } else if (/(iPhone|iPad|iPod)/.test(a)) {
1243
+ return 'iOS';
1244
+ } else if (/Android/.test(a)) {
1245
+ return 'Android';
1246
+ } else if (/(BlackBerry|PlayBook|BB10)/i.test(a)) {
1247
+ return 'BlackBerry';
1248
+ } else if (/Mac/i.test(a)) {
1249
+ return 'Mac OS X';
1250
+ } else if (/Linux/.test(a)) {
1251
+ return 'Linux';
1252
+ } else if (/CrOS/.test(a)) {
1253
+ return 'Chrome OS';
1254
+ } else {
1255
+ return '';
1256
+ }
1257
+ }
1258
+
1259
+ function device(userAgent) {
1260
+ if (/Windows Phone/i.test(userAgent) || /WPDesktop/.test(userAgent)) {
1261
+ return 'Windows Phone';
1262
+ } else if (/iPad/.test(userAgent)) {
1263
+ return 'iPad';
1264
+ } else if (/iPod/.test(userAgent)) {
1265
+ return 'iPod Touch';
1266
+ } else if (/iPhone/.test(userAgent)) {
1267
+ return 'iPhone';
1268
+ } else if (/(BlackBerry|PlayBook|BB10)/i.test(userAgent)) {
1269
+ return 'BlackBerry';
1270
+ } else if (/Android/.test(userAgent)) {
1271
+ return 'Android';
1272
+ } else {
1273
+ return '';
1274
+ }
1275
+ }
1276
+
1277
+ function referringDomain(referrer) {
1278
+ var split = referrer.split('/');
1279
+
1280
+ if (split.length >= 3) {
1281
+ return split[2];
1282
+ }
1283
+
1284
+ return '';
1285
+ }
1286
+
1287
+ // Methods partially borrowed from quirksmode.org/js/cookies.html
1288
+ var cookieStore = {
1289
+ getItem: function (key) {
1290
+ try {
1291
+ var nameEQ = key + '=';
1292
+ var ca = document.cookie.split(';');
1293
+
1294
+ for (var i = 0; i < ca.length; i++) {
1295
+ var c = ca[i];
1296
+
1297
+ while (c.charAt(0) == ' ') {
1298
+ c = c.substring(1, c.length);
1299
+ }
1300
+
1301
+ if (c.indexOf(nameEQ) === 0) {
1302
+ return decodeURIComponent(c.substring(nameEQ.length, c.length));
1303
+ }
1304
+ }
1305
+ } catch (err) {}
1306
+
1307
+ return null;
1308
+ },
1309
+ setItem: function (key, value) {
1310
+ try {
1311
+ var cdomain = '',
1312
+ expires = '',
1313
+ secure = '';
1314
+ var new_cookie_val = key + '=' + encodeURIComponent(JSON.stringify(value)) + expires + '; path=/' + cdomain + secure;
1315
+ document.cookie = new_cookie_val;
1316
+ } catch (err) {
1317
+ return;
1318
+ }
1319
+ },
1320
+ removeItem: function (name) {
1321
+ try {
1322
+ cookieStore.setItem(name, '');
1323
+ } catch (err) {
1324
+ return;
1325
+ }
1326
+ },
1327
+ clear: function () {
1328
+ document.cookie = '';
1329
+ },
1330
+ getAllKeys: function () {
1331
+ var ca = document.cookie.split(';');
1332
+ var keys = [];
1333
+
1334
+ for (var i = 0; i < ca.length; i++) {
1335
+ var c = ca[i];
1336
+
1337
+ while (c.charAt(0) == ' ') {
1338
+ c = c.substring(1, c.length);
1339
+ }
1340
+
1341
+ keys.push(c.split('=')[0]);
1342
+ }
1343
+
1344
+ return keys;
1345
+ }
1346
+ };
1347
+
1348
+ var createStorageLike = function (store) {
1349
+ return {
1350
+ getItem: function (key) {
1351
+ return store.getItem(key);
1352
+ },
1353
+ setItem: function (key, value) {
1354
+ store.setItem(key, JSON.stringify(value));
1355
+ },
1356
+ removeItem: function (key) {
1357
+ store.removeItem(key);
1358
+ },
1359
+ clear: function () {
1360
+ store.clear();
1361
+ },
1362
+ getAllKeys: function () {
1363
+ var keys = [];
1364
+
1365
+ for (var key in localStorage) {
1366
+ keys.push(key);
1367
+ }
1368
+
1369
+ return keys;
1370
+ }
1371
+ };
1372
+ };
1373
+
1374
+ var _localStore = createStorageLike(window.localStorage);
1375
+ var _sessionStore = createStorageLike(window.sessionStorage);
1376
+
1377
+ var checkStoreIsSupported = function (storage, key) {
1378
+ if (key === void 0) {
1379
+ key = '__mplssupport__';
1380
+ }
1381
+
1382
+ if (!window) {
1383
+ return false;
1384
+ }
1385
+
1386
+ try {
1387
+ var val = 'xyz';
1388
+ storage.setItem(key, val);
1389
+
1390
+ if (storage.getItem(key) !== val) {
1391
+ return false;
1392
+ }
1393
+
1394
+ storage.removeItem(key);
1395
+ return true;
1396
+ } catch (err) {
1397
+ return false;
1398
+ }
1399
+ };
1400
+
1401
+ var localStore = checkStoreIsSupported(_localStore) ? _localStore : undefined;
1402
+ var sessionStorage = checkStoreIsSupported(_sessionStore) ? _sessionStore : undefined;
1403
+
1404
+ var version = "2.0.0-alpha1";
1405
+
1406
+ var PostHog =
1407
+ /** @class */
1408
+ function (_super) {
1409
+ __extends(PostHog, _super);
1410
+
1411
+ function PostHog(apiKey, options) {
1412
+ var _this = _super.call(this, apiKey, options) || this;
1413
+
1414
+ _this._storage = localStore || sessionStorage || cookieStore; // posthog-js stores options in one object on
1415
+
1416
+ _this._storageKey = (options === null || options === void 0 ? void 0 : options.persistence_name) ? "ph_".concat(options.persistence_name) : "ph_".concat(apiKey, "_posthog");
1417
+ return _this;
1418
+ }
1419
+
1420
+ PostHog.prototype.getPersistedProperty = function (key) {
1421
+ if (!this._storageCache) {
1422
+ this._storageCache = JSON.parse(this._storage.getItem(this._storageKey) || '{}') || {};
1423
+ }
1424
+
1425
+ return this._storageCache[key];
1426
+ };
1427
+
1428
+ PostHog.prototype.setPersistedProperty = function (key, value) {
1429
+ if (!this._storageCache) {
1430
+ this._storageCache = JSON.parse(this._storage.getItem(this._storageKey) || '{}') || {};
1431
+ }
1432
+
1433
+ if (value === null) {
1434
+ delete this._storageCache[key];
1435
+
1436
+ this._storage.removeItem(this._storageKey);
1437
+ } else {
1438
+ this._storageCache[key] = value;
1439
+
1440
+ this._storage.setItem(this._storageKey, JSON.stringify(this._storageCache));
1441
+ }
1442
+ };
1443
+
1444
+ PostHog.prototype.fetch = function (url, options) {
1445
+ return window.fetch(url, options);
1446
+ };
1447
+
1448
+ PostHog.prototype.getLibraryId = function () {
1449
+ return 'posthog-web';
1450
+ };
1451
+
1452
+ PostHog.prototype.getLibraryVersion = function () {
1453
+ return version;
1454
+ };
1455
+
1456
+ PostHog.prototype.getCustomUserAgent = function () {
1457
+ return;
1458
+ };
1459
+
1460
+ PostHog.prototype.getCommonEventProperties = function () {
1461
+ return __assign(__assign({}, _super.prototype.getCommonEventProperties.call(this)), getContext(window));
1462
+ };
1463
+
1464
+ return PostHog;
1465
+ }(PostHogCore);
1466
+
1467
+ export { PostHog, PostHog as default };
1468
+ //# sourceMappingURL=index.esm.js.map